diff options
Diffstat (limited to 'app/javascript/flavours/glitch')
10 files changed, 782 insertions, 179 deletions
diff --git a/app/javascript/flavours/glitch/components/media_gallery.js b/app/javascript/flavours/glitch/components/media_gallery.js index 973406ad2..71240530c 100644 --- a/app/javascript/flavours/glitch/components/media_gallery.js +++ b/app/javascript/flavours/glitch/components/media_gallery.js @@ -8,6 +8,7 @@ import { isIOS } from 'flavours/glitch/util/is_mobile'; import classNames from 'classnames'; import { autoPlayGif, displayMedia, useBlurhash } from 'flavours/glitch/util/initial_state'; import { decode } from 'blurhash'; +import { debounce } from 'lodash'; const messages = defineMessages({ hidden: { @@ -289,6 +290,14 @@ class MediaGallery extends React.PureComponent { width: this.props.defaultWidth, }; + componentDidMount () { + window.addEventListener('resize', this.handleResize, { passive: true }); + } + + componentWillUnmount () { + window.removeEventListener('resize', this.handleResize); + } + componentWillReceiveProps (nextProps) { if (!is(nextProps.media, this.props.media) && nextProps.visible === undefined) { this.setState({ visible: displayMedia !== 'hide_all' && !nextProps.sensitive || displayMedia === 'show_all' }); @@ -305,6 +314,14 @@ class MediaGallery extends React.PureComponent { } } + handleResize = debounce(() => { + if (this.node) { + this._setDimensions(); + } + }, 250, { + trailing: true, + }); + handleOpen = () => { if (this.props.onToggleVisibility) { this.props.onToggleVisibility(); @@ -319,11 +336,23 @@ class MediaGallery extends React.PureComponent { handleRef = (node) => { this.node = node; - if (node && node.offsetWidth && node.offsetWidth != this.state.width) { - if (this.props.cacheWidth) this.props.cacheWidth(node.offsetWidth); + + if (this.node) { + this._setDimensions(); + } + } + + _setDimensions () { + const width = this.node.offsetWidth; + + if (width && width != this.state.width) { + // offsetWidth triggers a layout, so only calculate when we need to + if (this.props.cacheWidth) { + this.props.cacheWidth(width); + } this.setState({ - width: node.offsetWidth, + width: width, }); } } diff --git a/app/javascript/flavours/glitch/components/status.js b/app/javascript/flavours/glitch/components/status.js index e036c0da7..37acc7511 100644 --- a/app/javascript/flavours/glitch/components/status.js +++ b/app/javascript/flavours/glitch/components/status.js @@ -591,9 +591,12 @@ class Status extends ImmutablePureComponent { <Component src={attachment.get('url')} alt={attachment.get('description')} + poster={attachment.get('preview_url') || status.getIn(['account', 'avatar_static'])} + blurhash={attachment.get('blurhash')} duration={attachment.getIn(['meta', 'original', 'duration'], 0)} - peaks={[0]} - height={70} + width={this.props.cachedMediaWidth} + height={110} + cacheWidth={this.props.cacheMediaWidth} /> )} </Bundle> diff --git a/app/javascript/flavours/glitch/features/account_timeline/index.js b/app/javascript/flavours/glitch/features/account_timeline/index.js index a8e8aa7a8..5558ba2a3 100644 --- a/app/javascript/flavours/glitch/features/account_timeline/index.js +++ b/app/javascript/flavours/glitch/features/account_timeline/index.js @@ -21,7 +21,7 @@ const mapStateToProps = (state, { params: { accountId }, withReplies = false }) const path = withReplies ? `${accountId}:with_replies` : accountId; return { - remote: !!state.getIn(['accounts', accountId, 'acct']) !== state.getIn(['accounts', accountId, 'username']), + remote: !!(state.getIn(['accounts', accountId, 'acct']) !== state.getIn(['accounts', accountId, 'username'])), remoteUrl: state.getIn(['accounts', accountId, 'url']), isAccount: !!state.getIn(['accounts', accountId]), statusIds: state.getIn(['timelines', `account:${path}`, 'items'], ImmutableList()), diff --git a/app/javascript/flavours/glitch/features/audio/index.js b/app/javascript/flavours/glitch/features/audio/index.js index ba3534492..53b13ec13 100644 --- a/app/javascript/flavours/glitch/features/audio/index.js +++ b/app/javascript/flavours/glitch/features/audio/index.js @@ -1,11 +1,136 @@ import React from 'react'; import PropTypes from 'prop-types'; -import WaveSurfer from 'wavesurfer.js'; import { defineMessages, injectIntl } from 'react-intl'; import { formatTime } from 'flavours/glitch/features/video'; import Icon from 'flavours/glitch/components/icon'; import classNames from 'classnames'; import { throttle } from 'lodash'; +import { encode, decode } from 'blurhash'; +import { getPointerPosition, fileNameFromURL } from 'flavours/glitch/features/video'; +import { debounce } from 'lodash'; + +const digitCharacters = [ + '0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + 'A', + 'B', + 'C', + 'D', + 'E', + 'F', + 'G', + 'H', + 'I', + 'J', + 'K', + 'L', + 'M', + 'N', + 'O', + 'P', + 'Q', + 'R', + 'S', + 'T', + 'U', + 'V', + 'W', + 'X', + 'Y', + 'Z', + 'a', + 'b', + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i', + 'j', + 'k', + 'l', + 'm', + 'n', + 'o', + 'p', + 'q', + 'r', + 's', + 't', + 'u', + 'v', + 'w', + 'x', + 'y', + 'z', + '#', + '$', + '%', + '*', + '+', + ',', + '-', + '.', + ':', + ';', + '=', + '?', + '@', + '[', + ']', + '^', + '_', + '{', + '|', + '}', + '~', +]; + +const decode83 = (str) => { + let value = 0; + let c, digit; + + for (let i = 0; i < str.length; i++) { + c = str[i]; + digit = digitCharacters.indexOf(c); + value = value * 83 + digit; + } + + return value; +}; + +const decodeRGB = int => ({ + r: Math.max(0, (int >> 16)), + g: Math.max(0, (int >> 8) & 255), + b: Math.max(0, (int & 255)), +}); + +const luma = ({ r, g, b }) => 0.2126 * r + 0.7152 * g + 0.0722 * b; + +const adjustColor = ({ r, g, b }, lumaThreshold = 100) => { + let delta; + + if (luma({ r, g, b }) >= lumaThreshold) { + delta = -80; + } else { + delta = 80; + } + + return { + r: r + delta, + g: g + delta, + b: b + delta, + }; +}; const messages = defineMessages({ play: { id: 'video.play', defaultMessage: 'Play' }, @@ -15,130 +140,180 @@ const messages = defineMessages({ download: { id: 'video.download', defaultMessage: 'Download file' }, }); +const TICK_SIZE = 10; +const PADDING = 180; + export default @injectIntl class Audio extends React.PureComponent { static propTypes = { src: PropTypes.string.isRequired, alt: PropTypes.string, + poster: PropTypes.string, duration: PropTypes.number, - peaks: PropTypes.arrayOf(PropTypes.number), + width: PropTypes.number, height: PropTypes.number, - preload: PropTypes.bool, editable: PropTypes.bool, + fullscreen: PropTypes.bool, intl: PropTypes.object.isRequired, + cacheWidth: PropTypes.func, + blurhash: PropTypes.string, }; state = { + width: this.props.width, currentTime: 0, + buffer: 0, duration: null, paused: true, muted: false, volume: 0.5, + dragging: false, + color: { r: 255, g: 255, b: 255 }, }; - // hard coded in components.scss - // any way to get ::before values programatically? + setPlayerRef = c => { + this.player = c; + + if (this.player) { + this._setDimensions(); + } + } + + _setDimensions () { + const width = this.player.offsetWidth; + const height = this.props.fullscreen ? this.player.offsetHeight : (width / (16/9)); - volWidth = 50; + if (this.props.cacheWidth) { + this.props.cacheWidth(width); + } - volOffset = 70; + this.setState({ width, height }); + } - volHandleOffset = v => { - const offset = v * this.volWidth + this.volOffset; - return (offset > 110) ? 110 : offset; + setSeekRef = c => { + this.seek = c; } setVolumeRef = c => { this.volume = c; } - setWaveformRef = c => { - this.waveform = c; + setAudioRef = c => { + this.audio = c; + + if (this.audio) { + this.setState({ volume: this.audio.volume, muted: this.audio.muted }); + } } - componentDidMount () { - if (this.waveform) { - this._updateWaveform(); + setBlurhashCanvasRef = c => { + this.blurhashCanvas = c; + } + + setCanvasRef = c => { + this.canvas = c; + + if (c) { + this.canvasContext = c.getContext('2d'); } } + + componentDidMount () { + window.addEventListener('resize', this.handleResize, { passive: true }); - componentDidUpdate (prevProps) { - if (this.waveform && prevProps.src !== this.props.src) { - this._updateWaveform(); + if (!this.props.blurhash) { + const img = new Image(); + img.crossOrigin = 'anonymous'; + img.onload = () => this.handlePosterLoad(img); + img.src = this.props.poster; + } else { + this._setColorScheme(); + this._decodeBlurhash(); } } - componentWillUnmount () { - if (this.wavesurfer) { - this.wavesurfer.destroy(); - this.wavesurfer = null; + componentDidUpdate (prevProps, prevState) { + if (prevProps.poster !== this.props.poster && !this.props.blurhash) { + const img = new Image(); + img.crossOrigin = 'anonymous'; + img.onload = () => this.handlePosterLoad(img); + img.src = this.props.poster; + } + + if (prevState.blurhash !== this.state.blurhash || prevProps.blurhash !== this.props.blurhash) { + this._setColorScheme(); + this._decodeBlurhash(); } + + this._clear(); + this._draw(); } - _updateWaveform () { - const { src, height, duration, peaks, preload } = this.props; + _decodeBlurhash () { + const context = this.blurhashCanvas.getContext('2d'); + const pixels = decode(this.props.blurhash || this.state.blurhash, 32, 32); + const outputImageData = new ImageData(pixels, 32, 32); + + context.putImageData(outputImageData, 0, 0); + } - const progressColor = window.getComputedStyle(document.querySelector('.audio-player__progress-placeholder')).getPropertyValue('background-color'); - const waveColor = window.getComputedStyle(document.querySelector('.audio-player__wave-placeholder')).getPropertyValue('background-color'); + componentWillUnmount () { + window.removeEventListener('resize', this.handleResize); + } - if (this.wavesurfer) { - this.wavesurfer.destroy(); - this.loaded = false; + togglePlay = () => { + if (this.state.paused) { + this.setState({ paused: false }, () => this.audio.play()); + } else { + this.setState({ paused: true }, () => this.audio.pause()); } + } - const wavesurfer = WaveSurfer.create({ - container: this.waveform, - height, - barWidth: 3, - cursorWidth: 0, - progressColor, - waveColor, - backend: 'MediaElement', - interact: preload, - }); + handleResize = debounce(() => { + if (this.player) { + this._setDimensions(); + } + }, 250, { + trailing: true, + }); - wavesurfer.setVolume(this.state.volume); + handlePlay = () => { + this.setState({ paused: false }); - if (preload) { - wavesurfer.load(src); - this.loaded = true; - } else { - wavesurfer.load(src, peaks, 'none', duration); - this.loaded = false; + if (this.canvas && !this.audioContext) { + this._initAudioContext(); } - wavesurfer.on('ready', () => this.setState({ duration: Math.floor(wavesurfer.getDuration()) })); - wavesurfer.on('audioprocess', () => this.setState({ currentTime: Math.floor(wavesurfer.getCurrentTime()) })); - wavesurfer.on('pause', () => this.setState({ paused: true })); - wavesurfer.on('play', () => this.setState({ paused: false })); - wavesurfer.on('volume', volume => this.setState({ volume })); - wavesurfer.on('mute', muted => this.setState({ muted })); + if (this.audioContext && this.audioContext.state === 'suspended') { + this.audioContext.resume(); + } - this.wavesurfer = wavesurfer; + this._renderCanvas(); } - togglePlay = () => { - if (this.state.paused) { - if (!this.props.preload && !this.loaded) { - this.wavesurfer.createBackend(); - this.wavesurfer.createPeakCache(); - this.wavesurfer.load(this.props.src); - this.wavesurfer.toggleInteraction(); - this.wavesurfer.setVolume(this.state.volume); - this.loaded = true; - } + handlePause = () => { + this.setState({ paused: true }); - this.wavesurfer.play(); - this.setState({ paused: false }); - } else { - this.wavesurfer.pause(); - this.setState({ paused: true }); + if (this.audioContext) { + this.audioContext.suspend(); + } + } + + handleProgress = () => { + const lastTimeRange = this.audio.buffered.length - 1; + + if (lastTimeRange > -1) { + this.setState({ buffer: Math.ceil(this.audio.buffered.end(lastTimeRange) / this.audio.duration * 100) }); } } toggleMute = () => { - this.wavesurfer.setMute(!this.state.muted); + const muted = !this.state.muted; + + this.setState({ muted }, () => { + this.audio.muted = muted; + }); } handleVolumeMouseDown = e => { @@ -160,73 +335,374 @@ class Audio extends React.PureComponent { document.removeEventListener('touchend', this.handleVolumeMouseUp, true); } + handleMouseDown = e => { + document.addEventListener('mousemove', this.handleMouseMove, true); + document.addEventListener('mouseup', this.handleMouseUp, true); + document.addEventListener('touchmove', this.handleMouseMove, true); + document.addEventListener('touchend', this.handleMouseUp, true); + + this.setState({ dragging: true }); + this.audio.pause(); + this.handleMouseMove(e); + + e.preventDefault(); + e.stopPropagation(); + } + + handleMouseUp = () => { + document.removeEventListener('mousemove', this.handleMouseMove, true); + document.removeEventListener('mouseup', this.handleMouseUp, true); + document.removeEventListener('touchmove', this.handleMouseMove, true); + document.removeEventListener('touchend', this.handleMouseUp, true); + + this.setState({ dragging: false }); + this.audio.play(); + } + + handleMouseMove = throttle(e => { + const { x } = getPointerPosition(this.seek, e); + const currentTime = this.audio.duration * x; + + if (!isNaN(currentTime)) { + this.setState({ currentTime }, () => { + this.audio.currentTime = currentTime; + }); + } + }, 15); + + handleTimeUpdate = () => { + this.setState({ + currentTime: this.audio.currentTime, + duration: Math.floor(this.audio.duration), + }); + } + handleMouseVolSlide = throttle(e => { - const rect = this.volume.getBoundingClientRect(); - const x = (e.clientX - rect.left) / this.volWidth; // x position within the element. + const { x } = getPointerPosition(this.volume, e); if(!isNaN(x)) { - let slideamt = x; + this.setState({ volume: x }, () => { + this.audio.volume = x; + }); + } + }, 15); + + handleMouseEnter = () => { + this.setState({ hovered: true }); + } + + handleMouseLeave = () => { + this.setState({ hovered: false }); + } + + _initAudioContext () { + const context = new AudioContext(); + const analyser = context.createAnalyser(); + const source = context.createMediaElementSource(this.audio); + + analyser.smoothingTimeConstant = 0.6; + analyser.fftSize = 2048; + + source.connect(analyser); + source.connect(context.destination); + + this.audioContext = context; + this.analyser = analyser; + } + + handlePosterLoad = image => { + const canvas = document.createElement('canvas'); + const context = canvas.getContext('2d'); + + canvas.width = image.width; + canvas.height = image.height; + + context.drawImage(image, 0, 0); + + const inputImageData = context.getImageData(0, 0, image.width, image.height); + const blurhash = encode(inputImageData.data, image.width, image.height, 4, 4); - if (x > 1) { - slideamt = 1; - } else if(x < 0) { - slideamt = 0; + this.setState({ blurhash }); + } + + _setColorScheme () { + const blurhash = this.props.blurhash || this.state.blurhash; + const averageColor = decodeRGB(decode83(blurhash.slice(2, 6))); + + this.setState({ + color: adjustColor(averageColor), + darkText: luma(averageColor) >= 165, + }); + } + + handleDownload = () => { + fetch(this.props.src).then(res => res.blob()).then(blob => { + const element = document.createElement('a'); + const objectURL = URL.createObjectURL(blob); + + element.setAttribute('href', objectURL); + element.setAttribute('download', fileNameFromURL(this.props.src)); + + document.body.appendChild(element); + element.click(); + document.body.removeChild(element); + + URL.revokeObjectURL(objectURL); + }).catch(err => { + console.error(err); + }); + } + + _renderCanvas () { + requestAnimationFrame(() => { + this.handleTimeUpdate(); + this._clear(); + this._draw(); + + if (!this.state.paused) { + this._renderCanvas(); } + }); + } + + _clear () { + this.canvasContext.clearRect(0, 0, this.state.width, this.state.height); + } + + _draw () { + this.canvasContext.save(); + + const ticks = this._getTicks(360 * this._getScaleCoefficient(), TICK_SIZE); + + ticks.forEach(tick => { + this._drawTick(tick.x1, tick.y1, tick.x2, tick.y2); + }); + + this.canvasContext.restore(); + } + + _getRadius () { + return parseInt(((this.state.height || this.props.height) - (PADDING * this._getScaleCoefficient()) * 2) / 2); + } - this.wavesurfer.setVolume(slideamt); + _getScaleCoefficient () { + return (this.state.height || this.props.height) / 982; + } + + _getTicks (count, size, animationParams = [0, 90]) { + const radius = this._getRadius(); + const ticks = this._getTickPoints(count); + const lesser = 200; + const m = []; + const bufferLength = this.analyser ? this.analyser.frequencyBinCount : 0; + const frequencyData = new Uint8Array(bufferLength); + const allScales = []; + const scaleCoefficient = this._getScaleCoefficient(); + + if (this.analyser) { + this.analyser.getByteFrequencyData(frequencyData); } - }, 60); - render () { - const { height, intl, alt, editable } = this.props; - const { paused, muted, volume, currentTime } = this.state; + ticks.forEach((tick, i) => { + const coef = 1 - i / (ticks.length * 2.5); + + let delta = ((frequencyData[i] || 0) - lesser * coef) * scaleCoefficient; + + if (delta < 0) { + delta = 0; + } + + let k; + + if (animationParams[0] <= tick.angle && tick.angle <= animationParams[1]) { + k = radius / (radius - this._getSize(tick.angle, animationParams[0], animationParams[1]) - delta); + } else { + k = radius / (radius - (size + delta)); + } + + const x1 = tick.x * (radius - size); + const y1 = tick.y * (radius - size); + const x2 = x1 * k; + const y2 = y1 * k; + + m.push({ x1, y1, x2, y2 }); + + if (i < 20) { + let scale = delta / (200 * scaleCoefficient); + scale = scale < 1 ? 1 : scale; + allScales.push(scale); + } + }); + + const scale = allScales.reduce((pv, cv) => pv + cv, 0) / allScales.length; - const volumeWidth = muted ? 0 : volume * this.volWidth; - const volumeHandleLoc = muted ? this.volHandleOffset(0) : this.volHandleOffset(volume); + return m.map(({ x1, y1, x2, y2 }) => ({ + x1: x1, + y1: y1, + x2: x2 * scale, + y2: y2 * scale, + })); + } + + _getSize (angle, l, r) { + const scaleCoefficient = this._getScaleCoefficient(); + const maxTickSize = TICK_SIZE * 9 * scaleCoefficient; + const m = (r - l) / 2; + const x = (angle - l); + + let h; + + if (x === m) { + return maxTickSize; + } + + const d = Math.abs(m - x); + const v = 40 * Math.sqrt(1 / d); + + if (v > maxTickSize) { + h = maxTickSize; + } else { + h = Math.max(TICK_SIZE, v); + } + + return h; + } + + _getTickPoints (count) { + const PI = 360; + const coords = []; + const step = PI / count; + + let rad; + + for(let deg = 0; deg < PI; deg += step) { + rad = deg * Math.PI / (PI / 2); + coords.push({ x: Math.cos(rad), y: -Math.sin(rad), angle: deg }); + } + + return coords; + } + + _drawTick (x1, y1, x2, y2) { + const cx = this._getCX(); + const cy = this._getCY(); + + const dx1 = Math.ceil(cx + x1); + const dy1 = Math.ceil(cy + y1); + const dx2 = Math.ceil(cx + x2); + const dy2 = Math.ceil(cy + y2); + + const gradient = this.canvasContext.createLinearGradient(dx1, dy1, dx2, dy2); + + const mainColor = `rgb(${this.state.color.r}, ${this.state.color.g}, ${this.state.color.b})`; + const lastColor = `rgba(${this.state.color.r}, ${this.state.color.g}, ${this.state.color.b}, 0)`; + + gradient.addColorStop(0, mainColor); + gradient.addColorStop(0.6, mainColor); + gradient.addColorStop(1, lastColor); + + this.canvasContext.beginPath(); + this.canvasContext.strokeStyle = gradient; + this.canvasContext.lineWidth = 2; + this.canvasContext.moveTo(dx1, dy1); + this.canvasContext.lineTo(dx2, dy2); + this.canvasContext.stroke(); + } + + _getCX() { + return Math.floor(this.state.width / 2); + } + + _getCY() { + return Math.floor(this._getRadius() + (PADDING * this._getScaleCoefficient())); + } + + _getColor () { + return `rgb(${this.state.color.r}, ${this.state.color.g}, ${this.state.color.b})`; + } + + render () { + const { src, intl, alt, editable } = this.props; + const { paused, muted, volume, currentTime, duration, buffer, darkText, dragging } = this.state; + const progress = (currentTime / duration) * 100; return ( - <div className={classNames('audio-player', { editable })}> - <div className='audio-player__progress-placeholder' style={{ display: 'none' }} /> - <div className='audio-player__wave-placeholder' style={{ display: 'none' }} /> + <div className={classNames('audio-player', { editable, 'with-light-background': darkText })} ref={this.setPlayerRef} style={{ width: '100%', height: this.props.fullscreen ? '100%' : (this.state.height || this.props.height) }} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> + <audio + src={src} + ref={this.setAudioRef} + preload='none' + onPlay={this.handlePlay} + onPause={this.handlePause} + onProgress={this.handleProgress} + crossOrigin='anonymous' + /> - <div - className='audio-player__waveform' + <canvas + className='audio-player__background' + onClick={this.togglePlay} + width='32' + height='32' + style={{ width: this.state.width, height: this.state.height, position: 'absolute', top: 0, left: 0 }} + ref={this.setBlurhashCanvasRef} aria-label={alt} title={alt} - style={{ height }} - ref={this.setWaveformRef} + role='button' + tabIndex='0' + /> + + <canvas + className='audio-player__canvas' + width={this.state.width} + height={this.state.height} + style={{ width: '100%', position: 'absolute', top: 0, left: 0, pointerEvents: 'none' }} + ref={this.setCanvasRef} /> + <img + src={this.props.poster} + alt='' + width={(this._getRadius() - TICK_SIZE) * 2} + height={(this._getRadius() - TICK_SIZE) * 2} + style={{ position: 'absolute', left: this._getCX(), top: this._getCY(), transform: 'translate(-50%, -50%)', borderRadius: '50%', pointerEvents: 'none' }} + /> + + <div className='video-player__seek' onMouseDown={this.handleMouseDown} ref={this.setSeekRef}> + <div className='video-player__seek__buffer' style={{ width: `${buffer}%` }} /> + <div className='video-player__seek__progress' style={{ width: `${progress}%`, backgroundColor: this._getColor() }} /> + + <span + className={classNames('video-player__seek__handle', { active: dragging })} + tabIndex='0' + style={{ left: `${progress}%`, backgroundColor: this._getColor() }} + /> + </div> + <div className='video-player__controls active'> <div className='video-player__buttons-bar'> <div className='video-player__buttons left'> <button type='button' title={intl.formatMessage(paused ? messages.play : messages.pause)} aria-label={intl.formatMessage(paused ? messages.play : messages.pause)} onClick={this.togglePlay}><Icon id={paused ? 'play' : 'pause'} fixedWidth /></button> <button type='button' title={intl.formatMessage(muted ? messages.unmute : messages.mute)} aria-label={intl.formatMessage(muted ? messages.unmute : messages.mute)} onClick={this.toggleMute}><Icon id={muted ? 'volume-off' : 'volume-up'} fixedWidth /></button> - <div className='video-player__volume' onMouseDown={this.handleVolumeMouseDown} ref={this.setVolumeRef}> - - <div className='video-player__volume__current' style={{ width: `${volumeWidth}px` }} /> + <div className={classNames('video-player__volume', { active: this.state.hovered })} ref={this.setVolumeRef} onMouseDown={this.handleVolumeMouseDown}> + <div className='video-player__volume__current' style={{ width: `${volume * 100}%`, backgroundColor: this._getColor() }} /> <span className={classNames('video-player__volume__handle')} tabIndex='0' - style={{ left: `${volumeHandleLoc}px` }} + style={{ left: `${volume * 100}%`, backgroundColor: this._getColor() }} /> </div> - <span> - <span className='video-player__time-current'>{formatTime(currentTime)}</span> + <span className='video-player__time'> + <span className='video-player__time-current'>{formatTime(Math.floor(currentTime))}</span> <span className='video-player__time-sep'>/</span> <span className='video-player__time-total'>{formatTime(this.state.duration || Math.floor(this.props.duration))}</span> </span> </div> <div className='video-player__buttons right'> - <button type='button' title={intl.formatMessage(messages.download)} aria-label={intl.formatMessage(messages.download)}> - <a className='video-player__download__icon' href={this.props.src} download> - <Icon id={'download'} fixedWidth /> - </a> - </button> + <button type='button' title={intl.formatMessage(messages.download)} aria-label={intl.formatMessage(messages.download)} onClick={this.handleDownload}><Icon id='download' fixedWidth /></button> </div> </div> </div> diff --git a/app/javascript/flavours/glitch/features/followers/index.js b/app/javascript/flavours/glitch/features/followers/index.js index 8ae46be94..25f7f05b4 100644 --- a/app/javascript/flavours/glitch/features/followers/index.js +++ b/app/javascript/flavours/glitch/features/followers/index.js @@ -20,7 +20,7 @@ import ScrollableList from 'flavours/glitch/components/scrollable_list'; import TimelineHint from 'flavours/glitch/components/timeline_hint'; const mapStateToProps = (state, props) => ({ - remote: !!state.getIn(['accounts', props.params.accountId, 'acct']) !== state.getIn(['accounts', props.params.accountId, 'username']), + remote: !!(state.getIn(['accounts', props.params.accountId, 'acct']) !== state.getIn(['accounts', props.params.accountId, 'username'])), remoteUrl: state.getIn(['accounts', props.params.accountId, 'url']), isAccount: !!state.getIn(['accounts', props.params.accountId]), accountIds: state.getIn(['user_lists', 'followers', props.params.accountId, 'items']), diff --git a/app/javascript/flavours/glitch/features/following/index.js b/app/javascript/flavours/glitch/features/following/index.js index e06eaa8a6..968829fd5 100644 --- a/app/javascript/flavours/glitch/features/following/index.js +++ b/app/javascript/flavours/glitch/features/following/index.js @@ -20,7 +20,7 @@ import ScrollableList from 'flavours/glitch/components/scrollable_list'; import TimelineHint from 'flavours/glitch/components/timeline_hint'; const mapStateToProps = (state, props) => ({ - remote: !!state.getIn(['accounts', props.params.accountId, 'acct']) !== state.getIn(['accounts', props.params.accountId, 'username']), + remote: !!(state.getIn(['accounts', props.params.accountId, 'acct']) !== state.getIn(['accounts', props.params.accountId, 'username'])), remoteUrl: state.getIn(['accounts', props.params.accountId, 'url']), isAccount: !!state.getIn(['accounts', props.params.accountId]), accountIds: state.getIn(['user_lists', 'following', props.params.accountId, 'items']), diff --git a/app/javascript/flavours/glitch/features/status/components/card.js b/app/javascript/flavours/glitch/features/status/components/card.js index d2de225c0..4b6676062 100644 --- a/app/javascript/flavours/glitch/features/status/components/card.js +++ b/app/javascript/flavours/glitch/features/status/components/card.js @@ -9,6 +9,7 @@ import { decode as decodeIDNA } from 'flavours/glitch/util/idna'; import Icon from 'flavours/glitch/components/icon'; import { useBlurhash } from 'flavours/glitch/util/initial_state'; import { decode } from 'blurhash'; +import { debounce } from 'lodash'; const getHostname = url => { const parser = document.createElement('a'); @@ -83,13 +84,20 @@ export default class Card extends React.PureComponent { } componentDidMount () { + window.addEventListener('resize', this.handleResize, { passive: true }); + if (this.props.card && this.props.card.get('blurhash')) { this._decode(); } } + componentWillUnmount () { + window.removeEventListener('resize', this.handleResize); + } + componentDidUpdate (prevProps) { const { card } = this.props; + if (card.get('blurhash') && (!prevProps.card || prevProps.card.get('blurhash') !== card.get('blurhash'))) { this._decode(); } @@ -109,6 +117,24 @@ export default class Card extends React.PureComponent { } } + _setDimensions () { + const width = this.node.offsetWidth; + + if (this.props.cacheWidth) { + this.props.cacheWidth(width); + } + + this.setState({ width }); + } + + handleResize = debounce(() => { + if (this.node) { + this._setDimensions(); + } + }, 250, { + trailing: true, + }); + handlePhotoClick = () => { const { card, onOpenMedia } = this.props; @@ -141,9 +167,10 @@ export default class Card extends React.PureComponent { } setRef = c => { - if (c) { - if (this.props.cacheWidth) this.props.cacheWidth(c.offsetWidth); - this.setState({ width: c.offsetWidth }); + this.node = c; + + if (this.node) { + this._setDimensions(); } } diff --git a/app/javascript/flavours/glitch/features/status/components/detailed_status.js b/app/javascript/flavours/glitch/features/status/components/detailed_status.js index 4fbd65517..d57335612 100644 --- a/app/javascript/flavours/glitch/features/status/components/detailed_status.js +++ b/app/javascript/flavours/glitch/features/status/components/detailed_status.js @@ -142,8 +142,9 @@ export default class DetailedStatus extends ImmutablePureComponent { src={attachment.get('url')} alt={attachment.get('description')} duration={attachment.getIn(['meta', 'original', 'duration'], 0)} - height={110} - preload + poster={attachment.get('preview_url') || status.getIn(['account', 'avatar_static'])} + blurhash={attachment.get('blurhash')} + height={150} /> ); mediaIcon = 'music'; diff --git a/app/javascript/flavours/glitch/features/video/index.js b/app/javascript/flavours/glitch/features/video/index.js index e5b681064..c7cb5bc43 100644 --- a/app/javascript/flavours/glitch/features/video/index.js +++ b/app/javascript/flavours/glitch/features/video/index.js @@ -2,7 +2,7 @@ import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { fromJS, is } from 'immutable'; -import { throttle } from 'lodash'; +import { throttle, debounce } from 'lodash'; import classNames from 'classnames'; import { isFullscreen, requestFullscreen, exitFullscreen } from 'flavours/glitch/util/fullscreen'; import { displayMedia, useBlurhash } from 'flavours/glitch/util/initial_state'; @@ -19,7 +19,6 @@ const messages = defineMessages({ close: { id: 'video.close', defaultMessage: 'Close video' }, fullscreen: { id: 'video.fullscreen', defaultMessage: 'Full screen' }, exit_fullscreen: { id: 'video.exit_fullscreen', defaultMessage: 'Exit full screen' }, - download: { id: 'video.download', defaultMessage: 'Download file' }, }); export const formatTime = secondsNum => { @@ -86,6 +85,14 @@ export const getPointerPosition = (el, event) => { return position; }; +export const fileNameFromURL = str => { + const url = new URL(str); + const pathname = url.pathname; + const index = pathname.lastIndexOf('/'); + + return pathname.substring(index + 1); +}; + export default @injectIntl class Video extends React.PureComponent { @@ -134,22 +141,24 @@ class Video extends React.PureComponent { } } - // hard coded in components.scss - // any way to get ::before values programatically? - volWidth = 50; - volOffset = 70; - volHandleOffset = v => { - const offset = v * this.volWidth + this.volOffset; - return (offset > 110) ? 110 : offset; - } - setPlayerRef = c => { this.player = c; - if (c && c.offsetWidth && c.offsetWidth != this.state.containerWidth) { - if (this.props.cacheWidth) this.props.cacheWidth(this.player.offsetWidth); + if (this.player) { + this._setDimensions(); + } + } + + _setDimensions () { + const width = this.player.offsetWidth; + + if (width && width != this.state.containerWidth) { + if (this.props.cacheWidth) { + this.props.cacheWidth(width); + } + this.setState({ - containerWidth: c.offsetWidth, + containerWidth: width, }); } } @@ -229,18 +238,12 @@ class Video extends React.PureComponent { } handleMouseVolSlide = throttle(e => { - const rect = this.volume.getBoundingClientRect(); - const x = (e.clientX - rect.left) / this.volWidth; //x position within the element. + const { x } = getPointerPosition(this.volume, e); if(!isNaN(x)) { - var slideamt = x; - if(x > 1) { - slideamt = 1; - } else if(x < 0) { - slideamt = 0; - } - this.video.volume = slideamt; - this.setState({ volume: slideamt }); + this.setState({ volume: x }, () => { + this.video.volume = x; + }); } }, 15); @@ -301,12 +304,16 @@ class Video extends React.PureComponent { document.addEventListener('mozfullscreenchange', this.handleFullscreenChange, true); document.addEventListener('MSFullscreenChange', this.handleFullscreenChange, true); + window.addEventListener('resize', this.handleResize, { passive: true }); + if (this.props.blurhash) { this._decode(); } } componentWillUnmount () { + window.removeEventListener('resize', this.handleResize); + document.removeEventListener('fullscreenchange', this.handleFullscreenChange, true); document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange, true); document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange, true); @@ -342,6 +349,14 @@ class Video extends React.PureComponent { } } + handleResize = debounce(() => { + if (this.player) { + this._setDimensions(); + } + }, 250, { + trailing: true, + }); + handleFullscreenChange = () => { this.setState({ fullscreen: isFullscreen() }); } @@ -430,9 +445,6 @@ class Video extends React.PureComponent { const progress = (currentTime / duration) * 100; const playerStyle = {}; - const volumeWidth = (muted) ? 0 : volume * this.volWidth; - const volumeHandleLoc = (muted) ? this.volHandleOffset(0) : this.volHandleOffset(volume); - const computedClass = classNames('video-player', { inactive: !revealed, detailed, inline: inline && !fullscreen, fullscreen, editable, letterbox, 'full-width': fullwidth }); let { width, height } = this.props; @@ -519,18 +531,18 @@ class Video extends React.PureComponent { <button type='button' title={intl.formatMessage(paused ? messages.play : messages.pause)} aria-label={intl.formatMessage(paused ? messages.play : messages.pause)} onClick={this.togglePlay} autoFocus={detailed}><Icon id={paused ? 'play' : 'pause'} fixedWidth /></button> <button type='button' title={intl.formatMessage(muted ? messages.unmute : messages.mute)} aria-label={intl.formatMessage(muted ? messages.unmute : messages.mute)} onClick={this.toggleMute}><Icon id={muted ? 'volume-off' : 'volume-up'} fixedWidth /></button> - <div className='video-player__volume' onMouseDown={this.handleVolumeMouseDown} ref={this.setVolumeRef}> - - <div className='video-player__volume__current' style={{ width: `${volumeWidth}px` }} /> + <div className={classNames('video-player__volume', { active: this.state.hovered })} onMouseDown={this.handleVolumeMouseDown} ref={this.setVolumeRef}> + <div className='video-player__volume__current' style={{ width: `${volume * 100}%` }} /> + <span className={classNames('video-player__volume__handle')} tabIndex='0' - style={{ left: `${volumeHandleLoc}px` }} + style={{ left: `${volume * 100}%` }} /> </div> {(detailed || fullscreen) && ( - <span> + <span className='video-player__time'> <span className='video-player__time-current'>{formatTime(Math.floor(currentTime))}</span> <span className='video-player__time-sep'>/</span> <span className='video-player__time-total'>{formatTime(duration)}</span> @@ -544,7 +556,6 @@ class Video extends React.PureComponent { {(!onCloseVideo && !editable && !fullscreen) && <button type='button' title={intl.formatMessage(messages.hide)} aria-label={intl.formatMessage(messages.hide)} onClick={this.toggleReveal}><Icon id='eye-slash' fixedWidth /></button>} {(!fullscreen && onOpenVideo) && <button type='button' title={intl.formatMessage(messages.expand)} aria-label={intl.formatMessage(messages.expand)} onClick={this.handleOpenVideo}><Icon id='expand' fixedWidth /></button>} {onCloseVideo && <button type='button' title={intl.formatMessage(messages.close)} aria-label={intl.formatMessage(messages.close)} onClick={this.handleCloseVideo}><Icon id='compress' fixedWidth /></button>} - <button type='button' title={intl.formatMessage(messages.download)} aria-label={intl.formatMessage(messages.download)}><a className='video-player__download__icon' href={this.props.src} download><Icon id={'download'} fixedWidth /></a></button> <button type='button' title={intl.formatMessage(fullscreen ? messages.exit_fullscreen : messages.fullscreen)} aria-label={intl.formatMessage(fullscreen ? messages.exit_fullscreen : messages.fullscreen)} onClick={this.toggleFullscreen}><Icon id={fullscreen ? 'compress' : 'arrows-alt'} fixedWidth /></button> </div> </div> diff --git a/app/javascript/flavours/glitch/styles/components/media.scss b/app/javascript/flavours/glitch/styles/components/media.scss index 772b40dc4..5f6eff808 100644 --- a/app/javascript/flavours/glitch/styles/components/media.scss +++ b/app/javascript/flavours/glitch/styles/components/media.scss @@ -332,6 +332,7 @@ } .audio-player { + overflow: hidden; box-sizing: border-box; position: relative; background: darken($ui-base-color, 8%); @@ -344,37 +345,54 @@ height: 100%; } - &__waveform { - padding: 15px 0; - position: relative; - overflow: hidden; + .video-player__volume::before, + .video-player__seek::before { + background: rgba($white, 0.15); + } - &::before { - content: ""; - display: block; - position: absolute; - border-top: 1px solid lighten($ui-base-color, 4%); - width: 100%; - height: 0; - left: 0; - top: calc(50% + 1px); + &.with-light-background { + color: $black; + + .video-player__volume::before, + .video-player__seek::before { + background: rgba($black, 0.15); + } + + .video-player__seek__buffer { + background: rgba($black, 0.2); + } + + .video-player__buttons button { + color: rgba($black, 0.75); + + &:active, + &:hover, + &:focus { + color: $black; + } + } + + .video-player__time-sep, + .video-player__time-total, + .video-player__time-current { + color: $black; } } - &__progress-placeholder { - background-color: rgba(lighten($ui-highlight-color, 8%), 0.5); + .video-player__seek::before, + .video-player__seek__buffer, + .video-player__seek__progress { + top: 0; } - &__wave-placeholder { - background-color: lighten($ui-base-color, 16%); + .video-player__seek__handle { + top: -4px; } .video-player__controls { padding: 0 15px; padding-top: 10px; - background: darken($ui-base-color, 8%); - border-top: 1px solid lighten($ui-base-color, 4%); - border-radius: 0 0 4px 4px; + background: transparent; } } @@ -386,6 +404,7 @@ border-radius: 4px; box-sizing: border-box; direction: ltr; + color: $white; &.editable { border-radius: 0; @@ -513,6 +532,10 @@ } &__buttons { + display: flex; + flex: 0 1 auto; + min-width: 30px; + align-items: center; font-size: 16px; white-space: nowrap; overflow: hidden; @@ -531,6 +554,7 @@ } button { + flex: 0 0 auto; background: transparent; padding: 2px 10px; font-size: 16px; @@ -545,6 +569,13 @@ } } + &__time { + display: inline; + flex: 0 1 auto; + overflow: hidden; + text-overflow: ellipsis; + } + &__time-sep, &__time-total, &__time-current { @@ -554,7 +585,6 @@ &__time-current { color: $white; - margin-left: 60px; } &__time-sep { @@ -568,9 +598,22 @@ } &__volume { + flex: 0 0 auto; + display: inline-flex; cursor: pointer; height: 24px; - display: inline; + position: relative; + overflow: hidden; + + .no-reduce-motion & { + transition: all 100ms linear; + } + + &.active { + overflow: visible; + width: 50px; + margin-right: 16px; + } &::before { content: ""; @@ -580,8 +623,9 @@ display: block; position: absolute; height: 4px; - left: 70px; - bottom: 20px; + left: 0; + top: 50%; + transform: translate(0, -50%); } &__current { @@ -589,8 +633,9 @@ position: absolute; height: 4px; border-radius: 4px; - left: 70px; - bottom: 20px; + left: 0; + top: 50%; + transform: translate(0, -50%); background: lighten($ui-highlight-color, 8%); } @@ -600,12 +645,21 @@ border-radius: 50%; width: 12px; height: 12px; - bottom: 16px; - left: 70px; - transition: opacity .1s ease; + top: 50%; + left: 0; + margin-left: -6px; + transform: translate(0, -50%); background: lighten($ui-highlight-color, 8%); box-shadow: 1px 2px 6px rgba($base-shadow-color, 0.2); - pointer-events: none; + opacity: 0; + + .no-reduce-motion & { + transition: opacity 100ms linear; + } + } + + &.active &__handle { + opacity: 1; } } @@ -665,10 +719,12 @@ height: 12px; top: 6px; margin-left: -6px; - transition: opacity .1s ease; background: lighten($ui-highlight-color, 8%); box-shadow: 1px 2px 6px rgba($base-shadow-color, 0.2); - pointer-events: none; + + .no-reduce-motion & { + transition: opacity .1s ease; + } &.active { opacity: 1; |