diff --git a/Gemfile.lock b/Gemfile.lock index b47ab0091..c3269e108 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -93,7 +93,7 @@ GEM cocaine (~> 0.5.3) aws-eventstream (1.1.0) aws-partitions (1.329.0) - aws-sdk-core (3.99.2) + aws-sdk-core (3.100.0) aws-eventstream (~> 1, >= 1.0.2) aws-partitions (~> 1, >= 1.239.0) aws-sigv4 (~> 1.1) diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb index b8bca580f..5c8cdd174 100644 --- a/app/controllers/accounts_controller.rb +++ b/app/controllers/accounts_controller.rb @@ -11,7 +11,7 @@ class AccountsController < ApplicationController before_action :set_body_classes skip_around_action :set_locale, if: -> { [:json, :rss].include?(request.format&.to_sym) } - skip_before_action :require_functional! + skip_before_action :require_functional!, unless: :whitelist_mode? def show respond_to do |format| diff --git a/app/controllers/api/base_controller.rb b/app/controllers/api/base_controller.rb index 153ade253..045e7dd26 100644 --- a/app/controllers/api/base_controller.rb +++ b/app/controllers/api/base_controller.rb @@ -7,7 +7,7 @@ class Api::BaseController < ApplicationController include RateLimitHeaders skip_before_action :store_current_location - skip_before_action :require_functional! + skip_before_action :require_functional!, unless: :whitelist_mode? before_action :require_authenticated_user!, if: :disallow_unauthenticated_api_access? before_action :set_cache_headers diff --git a/app/controllers/concerns/localized.rb b/app/controllers/concerns/localized.rb index d1384ed56..fe1142f34 100644 --- a/app/controllers/concerns/localized.rb +++ b/app/controllers/concerns/localized.rb @@ -7,8 +7,6 @@ module Localized around_action :set_locale end - private - def set_locale locale = current_user.locale if respond_to?(:user_signed_in?) && user_signed_in? locale ||= session[:locale] ||= default_locale @@ -19,6 +17,8 @@ module Localized end end + private + def default_locale if ENV['DEFAULT_LOCALE'].present? I18n.default_locale diff --git a/app/controllers/concerns/sign_in_token_authentication_concern.rb b/app/controllers/concerns/sign_in_token_authentication_concern.rb index 88c009b19..f5178930b 100644 --- a/app/controllers/concerns/sign_in_token_authentication_concern.rb +++ b/app/controllers/concerns/sign_in_token_authentication_concern.rb @@ -42,9 +42,11 @@ module SignInTokenAuthenticationConcern UserMailer.sign_in_token(user, request.remote_ip, request.user_agent, Time.now.utc.to_s).deliver_later! end - session[:attempt_user_id] = user.id - use_pack 'auth' - @body_classes = 'lighter' - render :sign_in_token + set_locale do + session[:attempt_user_id] = user.id + use_pack 'auth' + @body_classes = 'lighter' + render :sign_in_token + end end end diff --git a/app/controllers/concerns/two_factor_authentication_concern.rb b/app/controllers/concerns/two_factor_authentication_concern.rb index 0d9f87455..35c0c27cf 100644 --- a/app/controllers/concerns/two_factor_authentication_concern.rb +++ b/app/controllers/concerns/two_factor_authentication_concern.rb @@ -40,9 +40,11 @@ module TwoFactorAuthenticationConcern end def prompt_for_two_factor(user) - session[:attempt_user_id] = user.id - use_pack 'auth' - @body_classes = 'lighter' - render :two_factor + set_locale do + session[:attempt_user_id] = user.id + use_pack 'auth' + @body_classes = 'lighter' + render :two_factor + end end end diff --git a/app/controllers/directories_controller.rb b/app/controllers/directories_controller.rb index adf2bd014..549c6a39e 100644 --- a/app/controllers/directories_controller.rb +++ b/app/controllers/directories_controller.rb @@ -10,7 +10,7 @@ class DirectoriesController < ApplicationController before_action :set_accounts before_action :set_pack - skip_before_action :require_functional! + skip_before_action :require_functional!, unless: :whitelist_mode? def index render :index diff --git a/app/controllers/follower_accounts_controller.rb b/app/controllers/follower_accounts_controller.rb index eb223c3f7..5ffbdae79 100644 --- a/app/controllers/follower_accounts_controller.rb +++ b/app/controllers/follower_accounts_controller.rb @@ -8,7 +8,7 @@ class FollowerAccountsController < ApplicationController before_action :set_cache_headers skip_around_action :set_locale, if: -> { request.format == :json } - skip_before_action :require_functional! + skip_before_action :require_functional!, unless: :whitelist_mode? def index respond_to do |format| diff --git a/app/controllers/following_accounts_controller.rb b/app/controllers/following_accounts_controller.rb index 4ddccf607..69820ebb7 100644 --- a/app/controllers/following_accounts_controller.rb +++ b/app/controllers/following_accounts_controller.rb @@ -8,7 +8,7 @@ class FollowingAccountsController < ApplicationController before_action :set_cache_headers skip_around_action :set_locale, if: -> { request.format == :json } - skip_before_action :require_functional! + skip_before_action :require_functional!, unless: :whitelist_mode? def index respond_to do |format| diff --git a/app/controllers/media_controller.rb b/app/controllers/media_controller.rb index 1d166d6e7..ce015dd1b 100644 --- a/app/controllers/media_controller.rb +++ b/app/controllers/media_controller.rb @@ -4,7 +4,7 @@ class MediaController < ApplicationController include Authorization skip_before_action :store_current_location - skip_before_action :require_functional! + skip_before_action :require_functional!, unless: :whitelist_mode? before_action :authenticate_user!, if: :whitelist_mode? before_action :set_media_attachment diff --git a/app/controllers/remote_interaction_controller.rb b/app/controllers/remote_interaction_controller.rb index 51bb9bdea..a277bfa10 100644 --- a/app/controllers/remote_interaction_controller.rb +++ b/app/controllers/remote_interaction_controller.rb @@ -11,7 +11,7 @@ class RemoteInteractionController < ApplicationController before_action :set_body_classes before_action :set_pack - skip_before_action :require_functional! + skip_before_action :require_functional!, unless: :whitelist_mode? def new @remote_follow = RemoteFollow.new(session_params) diff --git a/app/controllers/statuses_controller.rb b/app/controllers/statuses_controller.rb index b0abad984..a6ab8828f 100644 --- a/app/controllers/statuses_controller.rb +++ b/app/controllers/statuses_controller.rb @@ -19,7 +19,7 @@ class StatusesController < ApplicationController before_action :set_autoplay, only: :embed skip_around_action :set_locale, if: -> { request.format == :json } - skip_before_action :require_functional!, only: [:show, :embed] + skip_before_action :require_functional!, only: [:show, :embed], unless: :whitelist_mode? content_security_policy only: :embed do |p| p.frame_ancestors(false) diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb index 2363cb31b..e46c0532c 100644 --- a/app/controllers/tags_controller.rb +++ b/app/controllers/tags_controller.rb @@ -15,7 +15,7 @@ class TagsController < ApplicationController before_action :set_body_classes before_action :set_instance_presenter - skip_before_action :require_functional! + skip_before_action :require_functional!, unless: :whitelist_mode? def show respond_to do |format| diff --git a/app/javascript/flavours/glitch/features/emoji_picker/index.js b/app/javascript/flavours/glitch/features/emoji_picker/index.js index 14e5cb94a..d0d9714a8 100644 --- a/app/javascript/flavours/glitch/features/emoji_picker/index.js +++ b/app/javascript/flavours/glitch/features/emoji_picker/index.js @@ -283,7 +283,7 @@ class EmojiPickerMenu extends React.PureComponent { if (!emoji.native) { emoji.native = emoji.colons; } - if (!event.ctrlKey) { + if (!(event.ctrlKey || event.metaKey)) { this.props.onClose(); } this.props.onPick(emoji); diff --git a/app/javascript/flavours/glitch/styles/components/media.scss b/app/javascript/flavours/glitch/styles/components/media.scss index dbf0c908d..772b40dc4 100644 --- a/app/javascript/flavours/glitch/styles/components/media.scss +++ b/app/javascript/flavours/glitch/styles/components/media.scss @@ -76,7 +76,7 @@ border-radius: 4px; position: relative; width: 100%; - height: 110px; + min-height: 64px; @include fullwidth-gallery; } @@ -404,6 +404,7 @@ @include fullwidth-gallery; video { + display: block; max-width: 100vw; max-height: 80vh; z-index: 1; diff --git a/app/javascript/mastodon/components/media_gallery.js b/app/javascript/mastodon/components/media_gallery.js index a31de206b..0ec866138 100644 --- a/app/javascript/mastodon/components/media_gallery.js +++ b/app/javascript/mastodon/components/media_gallery.js @@ -8,10 +8,10 @@ import { isIOS } from '../is_mobile'; import classNames from 'classnames'; import { autoPlayGif, cropImages, displayMedia, useBlurhash } from '../initial_state'; import { decode } from 'blurhash'; +import { debounce } from 'lodash'; const messages = defineMessages({ - toggle_visible: { id: 'media_gallery.toggle_visible', - defaultMessage: 'Hide {number, plural, one {image} other {images}}' }, + toggle_visible: { id: 'media_gallery.toggle_visible', defaultMessage: 'Hide {number, plural, one {image} other {images}}' }, }); class Item extends React.PureComponent { @@ -267,6 +267,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' }); @@ -275,6 +283,14 @@ class MediaGallery extends React.PureComponent { } } + handleResize = debounce(() => { + if (this.node) { + this._setDimensions(); + } + }, 250, { + trailing: true, + }); + handleOpen = () => { if (this.props.onToggleVisibility) { this.props.onToggleVisibility(); @@ -287,15 +303,25 @@ class MediaGallery extends React.PureComponent { this.props.onOpenMedia(this.props.media, index); } - handleRef = (node) => { - if (node) { - // offsetWidth triggers a layout, so only calculate when we need to - if (this.props.cacheWidth) this.props.cacheWidth(node.offsetWidth); + handleRef = c => { + this.node = c; + + if (this.node) { + this._setDimensions(); + } + } + + _setDimensions () { + const width = this.node.offsetWidth; - this.setState({ - width: node.offsetWidth, - }); + // offsetWidth triggers a layout, so only calculate when we need to + if (this.props.cacheWidth) { + this.props.cacheWidth(width); } + + this.setState({ + width: width, + }); } isFullSizeEligible() { diff --git a/app/javascript/mastodon/components/status.js b/app/javascript/mastodon/components/status.js index f99ccd39a..5f42534ba 100644 --- a/app/javascript/mastodon/components/status.js +++ b/app/javascript/mastodon/components/status.js @@ -345,9 +345,11 @@ class Status extends ImmutablePureComponent { )} diff --git a/app/javascript/mastodon/features/audio/index.js b/app/javascript/mastodon/features/audio/index.js index baad1c0e5..9da143c96 100644 --- a/app/javascript/mastodon/features/audio/index.js +++ b/app/javascript/mastodon/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 'mastodon/features/video'; import Icon from 'mastodon/components/icon'; import classNames from 'classnames'; import { throttle } from 'lodash'; +import { encode, decode } from 'blurhash'; +import { getPointerPosition, fileNameFromURL } from 'mastodon/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,132 +140,168 @@ 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, intl: PropTypes.object.isRequired, + cacheWidth: PropTypes.func, }; 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? - volWidth = 50; - volOffset = 70; + setPlayerRef = c => { + this.player = c; - volHandleOffset = v => { - const offset = v * this.volWidth + this.volOffset; + if (this.player) { + this._setDimensions(); + } + } + + _setDimensions () { + const width = this.player.offsetWidth; + const height = width / (16/9); + + if (this.props.cacheWidth) { + this.props.cacheWidth(width); + } - return (offset > 110) ? 110 : offset; + this.setState({ width, height }); + } + + 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('scroll', this.handleScroll); + window.addEventListener('resize', this.handleResize, { passive: true }); + + const img = new Image(); + img.crossOrigin = 'anonymous'; + img.onload = () => this.handlePosterLoad(img); + img.src = this.props.poster; } - componentDidUpdate (prevProps) { - if (this.waveform && prevProps.src !== this.props.src) { - this._updateWaveform(); + componentDidUpdate (prevProps, prevState) { + if (prevProps.poster !== this.props.poster) { + const img = new Image(); + img.crossOrigin = 'anonymous'; + img.onload = () => this.handlePosterLoad(img); + img.src = this.props.poster; } + + if (prevState.blurhash !== this.state.blurhash) { + const context = this.blurhashCanvas.getContext('2d'); + const pixels = decode(this.state.blurhash, 32, 32); + const outputImageData = new ImageData(pixels, 32, 32); + + context.putImageData(outputImageData, 0, 0); + } + + this._clear(); + this._draw(); } componentWillUnmount () { window.removeEventListener('scroll', this.handleScroll); + window.removeEventListener('resize', this.handleResize); + } - if (this.wavesurfer) { - this.wavesurfer.destroy(); - this.wavesurfer = null; + togglePlay = () => { + if (this.state.paused) { + this.setState({ paused: false }, () => this.audio.play()); + } else { + this.setState({ paused: true }, () => this.audio.pause()); } } - _updateWaveform () { - const { src, height, duration, peaks, preload } = this.props; - - 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'); - - if (this.wavesurfer) { - this.wavesurfer.destroy(); - this.loaded = false; + handleResize = debounce(() => { + if (this.player) { + this._setDimensions(); } + }, 250, { + trailing: true, + }); - const wavesurfer = WaveSurfer.create({ - container: this.waveform, - height, - barWidth: 3, - cursorWidth: 0, - progressColor, - waveColor, - backend: 'MediaElement', - interact: preload, - }); - - 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.setState({ paused: false }, () => this.wavesurfer.play()); - } else { - this.setState({ paused: true }, () => this.wavesurfer.pause()); + if (this.audioContext) { + this.audioContext.suspend(); + } + } + + handleProgress = () => { + if (this.audio.buffered.length > 0) { + this.setState({ buffer: this.audio.buffered.end(0) / this.audio.duration * 100 }); } } toggleMute = () => { const muted = !this.state.muted; - this.setState({ muted }, () => this.wavesurfer.setMute(muted)); + + this.setState({ muted }, () => { + this.audio.muted = muted; + }); } handleVolumeMouseDown = e => { @@ -162,74 +323,374 @@ class Audio extends React.PureComponent { document.removeEventListener('touchend', this.handleVolumeMouseUp, true); } - handleMouseVolSlide = throttle(e => { - const rect = this.volume.getBoundingClientRect(); - const x = (e.clientX - rect.left) / this.volWidth; // x position within the element. + 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); - if(!isNaN(x)) { - let slideamt = x; + this.setState({ dragging: true }); + this.audio.pause(); + this.handleMouseMove(e); - if (x > 1) { - slideamt = 1; - } else if(x < 0) { - slideamt = 0; - } + 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.wavesurfer.setVolume(slideamt); + this.setState({ dragging: false }); + this.audio.play(); + } + + handleMouseMove = throttle(e => { + const { x } = getPointerPosition(this.seek, e); + const currentTime = Math.floor(this.audio.duration * x); + + if (!isNaN(currentTime)) { + this.setState({ currentTime }, () => { + this.audio.currentTime = currentTime; + }); + } + }, 60); + + handleTimeUpdate = () => { + this.setState({ + currentTime: Math.floor(this.audio.currentTime), + duration: Math.floor(this.audio.duration), + }); + } + + handleMouseVolSlide = throttle(e => { + const { x } = getPointerPosition(this.volume, e); + + if(!isNaN(x)) { + this.setState({ volume: x }, () => { + this.audio.volume = x; + }); } }, 60); handleScroll = throttle(() => { - if (!this.waveform || !this.wavesurfer) { + if (!this.canvas || !this.audio) { return; } - const { top, height } = this.waveform.getBoundingClientRect(); + const { top, height } = this.canvas.getBoundingClientRect(); const inView = (top <= (window.innerHeight || document.documentElement.clientHeight)) && (top + height >= 0); if (!this.state.paused && !inView) { - this.setState({ paused: true }, () => this.wavesurfer.pause()); + this.setState({ paused: true }, () => this.audio.pause()); } - }, 150, { trailing: true }) + }, 150, { trailing: true }); - render () { - const { height, intl, alt, editable } = this.props; - const { paused, muted, volume, currentTime } = this.state; + 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; - const volumeWidth = muted ? 0 : volume * this.volWidth; - const volumeHandleLoc = muted ? this.volHandleOffset(0) : this.volHandleOffset(volume); + 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); + const averageColor = decodeRGB(decode83(blurhash.slice(2, 6))); + + this.setState({ + blurhash, + 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._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); + } + + _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); + } + + 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; + + 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 ( -
-
-
+
+