Merge pull request #1380 from ThibG/glitch-soc/merge-upstream

Merge upstream changes
remotes/1727458204337373841/tmp_refs/heads/signup-info-prompt
ThibG 2020-07-10 17:29:43 +02:00 committed by GitHub
commit ddf7cc1ab5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
38 changed files with 651 additions and 597 deletions

View File

@ -1,8 +1,8 @@
export const DROPDOWN_MENU_OPEN = 'DROPDOWN_MENU_OPEN'; export const DROPDOWN_MENU_OPEN = 'DROPDOWN_MENU_OPEN';
export const DROPDOWN_MENU_CLOSE = 'DROPDOWN_MENU_CLOSE'; export const DROPDOWN_MENU_CLOSE = 'DROPDOWN_MENU_CLOSE';
export function openDropdownMenu(id, placement, keyboard) { export function openDropdownMenu(id, placement, keyboard, scroll_key) {
return { type: DROPDOWN_MENU_OPEN, id, placement, keyboard }; return { type: DROPDOWN_MENU_OPEN, id, placement, keyboard, scroll_key };
} }
export function closeDropdownMenu(id) { export function closeDropdownMenu(id) {

View File

@ -0,0 +1,65 @@
// @ts-check
import { decode } from 'blurhash';
import React, { useRef, useEffect } from 'react';
import PropTypes from 'prop-types';
/**
* @typedef BlurhashPropsBase
* @property {string?} hash Hash to render
* @property {number} width
* Width of the blurred region in pixels. Defaults to 32
* @property {number} [height]
* Height of the blurred region in pixels. Defaults to width
* @property {boolean} [dummy]
* Whether dummy mode is enabled. If enabled, nothing is rendered
* and canvas left untouched
*/
/** @typedef {JSX.IntrinsicElements['canvas'] & BlurhashPropsBase} BlurhashProps */
/**
* Component that is used to render blurred of blurhash string
*
* @param {BlurhashProps} param1 Props of the component
* @returns Canvas which will render blurred region element to embed
*/
function Blurhash({
hash,
width = 32,
height = width,
dummy = false,
...canvasProps
}) {
const canvasRef = /** @type {import('react').MutableRefObject<HTMLCanvasElement>} */ (useRef());
useEffect(() => {
const { current: canvas } = canvasRef;
canvas.width = canvas.width; // resets canvas
if (dummy || !hash) return;
try {
const pixels = decode(hash, width, height);
const ctx = canvas.getContext('2d');
const imageData = new ImageData(pixels, width, height);
ctx.putImageData(imageData, 0, 0);
} catch (err) {
console.error('Blurhash decoding failure', { err, hash });
}
}, [dummy, hash, width, height]);
return (
<canvas {...canvasProps} ref={canvasRef} width={width} height={height} />
);
}
Blurhash.propTypes = {
hash: PropTypes.string.isRequired,
width: PropTypes.number,
height: PropTypes.number,
dummy: PropTypes.bool,
};
export default React.memo(Blurhash);

View File

@ -7,8 +7,8 @@ import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { isIOS } from 'flavours/glitch/util/is_mobile'; import { isIOS } from 'flavours/glitch/util/is_mobile';
import classNames from 'classnames'; import classNames from 'classnames';
import { autoPlayGif, displayMedia, useBlurhash } from 'flavours/glitch/util/initial_state'; import { autoPlayGif, displayMedia, useBlurhash } from 'flavours/glitch/util/initial_state';
import { decode } from 'blurhash';
import { debounce } from 'lodash'; import { debounce } from 'lodash';
import Blurhash from 'flavours/glitch/components/blurhash';
const messages = defineMessages({ const messages = defineMessages({
hidden: { hidden: {
@ -94,36 +94,6 @@ class Item extends React.PureComponent {
e.stopPropagation(); e.stopPropagation();
} }
componentDidMount () {
if (this.props.attachment.get('blurhash')) {
this._decode();
}
}
componentDidUpdate (prevProps) {
if (prevProps.attachment.get('blurhash') !== this.props.attachment.get('blurhash') && this.props.attachment.get('blurhash')) {
this._decode();
}
}
_decode () {
if (!useBlurhash) return;
const hash = this.props.attachment.get('blurhash');
const pixels = decode(hash, 32, 32);
if (pixels) {
const ctx = this.canvas.getContext('2d');
const imageData = new ImageData(pixels, 32, 32);
ctx.putImageData(imageData, 0, 0);
}
}
setCanvasRef = c => {
this.canvas = c;
}
handleImageLoad = () => { handleImageLoad = () => {
this.setState({ loaded: true }); this.setState({ loaded: true });
} }
@ -186,7 +156,11 @@ class Item extends React.PureComponent {
return ( return (
<div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}> <div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}>
<a className='media-gallery__item-thumbnail' href={attachment.get('remote_url') || attachment.get('url')} style={{ cursor: 'pointer' }} title={attachment.get('description')} target='_blank' rel='noopener noreferrer'> <a className='media-gallery__item-thumbnail' href={attachment.get('remote_url') || attachment.get('url')} style={{ cursor: 'pointer' }} title={attachment.get('description')} target='_blank' rel='noopener noreferrer'>
<canvas width={32} height={32} ref={this.setCanvasRef} className='media-gallery__preview' /> <Blurhash
hash={attachment.get('blurhash')}
className='media-gallery__preview'
dummy={!useBlurhash}
/>
</a> </a>
</div> </div>
); );
@ -253,7 +227,13 @@ class Item extends React.PureComponent {
return ( return (
<div className={classNames('media-gallery__item', { standalone, letterbox })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}> <div className={classNames('media-gallery__item', { standalone, letterbox })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}>
<canvas width={32} height={32} ref={this.setCanvasRef} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': visible && this.state.loaded })} /> <Blurhash
hash={attachment.get('blurhash')}
dummy={!useBlurhash}
className={classNames('media-gallery__preview', {
'media-gallery__preview--hidden': visible && this.state.loaded,
})}
/>
{visible && thumbnail} {visible && thumbnail}
</div> </div>
); );

View File

@ -10,10 +10,18 @@ import { List as ImmutableList } from 'immutable';
import classNames from 'classnames'; import classNames from 'classnames';
import { attachFullscreenListener, detachFullscreenListener, isFullscreen } from 'flavours/glitch/util/fullscreen'; import { attachFullscreenListener, detachFullscreenListener, isFullscreen } from 'flavours/glitch/util/fullscreen';
import LoadingIndicator from './loading_indicator'; import LoadingIndicator from './loading_indicator';
import { connect } from 'react-redux';
const MOUSE_IDLE_DELAY = 300; const MOUSE_IDLE_DELAY = 300;
export default class ScrollableList extends PureComponent { const mapStateToProps = (state, { scrollKey }) => {
return {
preventScroll: scrollKey === state.getIn(['dropdown_menu', 'scroll_key']),
};
};
export default @connect(mapStateToProps)
class ScrollableList extends PureComponent {
static contextTypes = { static contextTypes = {
router: PropTypes.object, router: PropTypes.object,
@ -37,6 +45,7 @@ export default class ScrollableList extends PureComponent {
emptyMessage: PropTypes.node, emptyMessage: PropTypes.node,
children: PropTypes.node, children: PropTypes.node,
bindToDocument: PropTypes.bool, bindToDocument: PropTypes.bool,
preventScroll: PropTypes.bool,
}; };
static defaultProps = { static defaultProps = {
@ -124,7 +133,7 @@ export default class ScrollableList extends PureComponent {
}); });
handleMouseIdle = () => { handleMouseIdle = () => {
if (this.scrollToTopOnMouseIdle) { if (this.scrollToTopOnMouseIdle && !this.props.preventScroll) {
this.setScrollTop(0); this.setScrollTop(0);
} }
this.mouseMovedRecently = false; this.mouseMovedRecently = false;
@ -176,7 +185,7 @@ export default class ScrollableList extends PureComponent {
this.getFirstChildKey(prevProps) !== this.getFirstChildKey(this.props); this.getFirstChildKey(prevProps) !== this.getFirstChildKey(this.props);
const pendingChanged = (prevProps.numPending > 0) !== (this.props.numPending > 0); const pendingChanged = (prevProps.numPending > 0) !== (this.props.numPending > 0);
if (pendingChanged || someItemInserted && (this.getScrollTop() > 0 || this.mouseMovedRecently)) { if (pendingChanged || someItemInserted && (this.getScrollTop() > 0 || this.mouseMovedRecently || this.props.preventScroll)) {
return this.getScrollHeight() - this.getScrollTop(); return this.getScrollHeight() - this.getScrollTop();
} else { } else {
return null; return null;

View File

@ -96,6 +96,7 @@ class Status extends ImmutablePureComponent {
cacheMediaWidth: PropTypes.func, cacheMediaWidth: PropTypes.func,
cachedMediaWidth: PropTypes.number, cachedMediaWidth: PropTypes.number,
onClick: PropTypes.func, onClick: PropTypes.func,
scrollKey: PropTypes.string,
}; };
state = { state = {

View File

@ -74,6 +74,7 @@ class StatusActionBar extends ImmutablePureComponent {
withDismiss: PropTypes.bool, withDismiss: PropTypes.bool,
showReplyCount: PropTypes.bool, showReplyCount: PropTypes.bool,
directMessage: PropTypes.bool, directMessage: PropTypes.bool,
scrollKey: PropTypes.string,
intl: PropTypes.object.isRequired, intl: PropTypes.object.isRequired,
}; };
@ -198,7 +199,7 @@ class StatusActionBar extends ImmutablePureComponent {
} }
render () { render () {
const { status, intl, withDismiss, showReplyCount, directMessage } = this.props; const { status, intl, withDismiss, showReplyCount, directMessage, scrollKey } = this.props;
const mutingConversation = status.get('muted'); const mutingConversation = status.get('muted');
const anonymousAccess = !me; const anonymousAccess = !me;
@ -300,7 +301,16 @@ class StatusActionBar extends ImmutablePureComponent {
<IconButton key='bookmark-button' className='status__action-bar-button bookmark-icon' disabled={anonymousAccess} active={status.get('bookmarked')} pressed={status.get('bookmarked')} title={intl.formatMessage(messages.bookmark)} icon='bookmark' onClick={this.handleBookmarkClick} />, <IconButton key='bookmark-button' className='status__action-bar-button bookmark-icon' disabled={anonymousAccess} active={status.get('bookmarked')} pressed={status.get('bookmarked')} title={intl.formatMessage(messages.bookmark)} icon='bookmark' onClick={this.handleBookmarkClick} />,
filterButton, filterButton,
<div key='dropdown-button' className='status__action-bar-dropdown'> <div key='dropdown-button' className='status__action-bar-dropdown'>
<DropdownMenuContainer disabled={anonymousAccess} status={status} items={menu} icon='ellipsis-h' size={18} direction='right' ariaLabel={intl.formatMessage(messages.more)} /> <DropdownMenuContainer
scrollKey={scrollKey}
disabled={anonymousAccess}
status={status}
items={menu}
icon='ellipsis-h'
size={18}
direction='right'
ariaLabel={intl.formatMessage(messages.more)}
/>
</div>, </div>,
]} ]}

View File

@ -99,6 +99,7 @@ export default class StatusList extends ImmutablePureComponent {
onMoveUp={this.handleMoveUp} onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown} onMoveDown={this.handleMoveDown}
contextType={timelineId} contextType={timelineId}
scrollKey={this.props.scrollKey}
/> />
)) ))
) : null; ) : null;
@ -112,6 +113,7 @@ export default class StatusList extends ImmutablePureComponent {
onMoveUp={this.handleMoveUp} onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown} onMoveDown={this.handleMoveDown}
contextType={timelineId} contextType={timelineId}
scrollKey={this.props.scrollKey}
/> />
)).concat(scrollableContent); )).concat(scrollableContent);
} }

View File

@ -11,7 +11,7 @@ const mapStateToProps = state => ({
openedViaKeyboard: state.getIn(['dropdown_menu', 'keyboard']), openedViaKeyboard: state.getIn(['dropdown_menu', 'keyboard']),
}); });
const mapDispatchToProps = (dispatch, { status, items }) => ({ const mapDispatchToProps = (dispatch, { status, items, scrollKey }) => ({
onOpen(id, onItemClick, dropdownPlacement, keyboard) { onOpen(id, onItemClick, dropdownPlacement, keyboard) {
dispatch(isUserTouching() ? openModal('ACTIONS', { dispatch(isUserTouching() ? openModal('ACTIONS', {
status, status,
@ -22,7 +22,7 @@ const mapDispatchToProps = (dispatch, { status, items }) => ({
onClick: item.action ? ((e) => { return onItemClick(i, e) }) : null, onClick: item.action ? ((e) => { return onItemClick(i, e) }) : null,
} : null } : null
), ),
}) : openDropdownMenu(id, dropdownPlacement, keyboard)); }) : openDropdownMenu(id, dropdownPlacement, keyboard, scrollKey));
}, },
onClose(id) { onClose(id) {
dispatch(closeModal('ACTIONS')); dispatch(closeModal('ACTIONS'));

View File

@ -1,7 +1,7 @@
import { decode } from 'blurhash'; import Blurhash from 'flavours/glitch/components/blurhash';
import classNames from 'classnames'; import classNames from 'classnames';
import Icon from 'flavours/glitch/components/icon'; import Icon from 'flavours/glitch/components/icon';
import { autoPlayGif, displayMedia } from 'flavours/glitch/util/initial_state'; import { autoPlayGif, displayMedia, useBlurhash } from 'flavours/glitch/util/initial_state';
import { isIOS } from 'flavours/glitch/util/is_mobile'; import { isIOS } from 'flavours/glitch/util/is_mobile';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import React from 'react'; import React from 'react';
@ -21,34 +21,6 @@ export default class MediaItem extends ImmutablePureComponent {
loaded: false, loaded: false,
}; };
componentDidMount () {
if (this.props.attachment.get('blurhash')) {
this._decode();
}
}
componentDidUpdate (prevProps) {
if (prevProps.attachment.get('blurhash') !== this.props.attachment.get('blurhash') && this.props.attachment.get('blurhash')) {
this._decode();
}
}
_decode () {
const hash = this.props.attachment.get('blurhash');
const pixels = decode(hash, 32, 32);
if (pixels) {
const ctx = this.canvas.getContext('2d');
const imageData = new ImageData(pixels, 32, 32);
ctx.putImageData(imageData, 0, 0);
}
}
setCanvasRef = c => {
this.canvas = c;
}
handleImageLoad = () => { handleImageLoad = () => {
this.setState({ loaded: true }); this.setState({ loaded: true });
} }
@ -149,7 +121,13 @@ export default class MediaItem extends ImmutablePureComponent {
return ( return (
<div className='account-gallery__item' style={{ width, height }}> <div className='account-gallery__item' style={{ width, height }}>
<a className='media-gallery__item-thumbnail' href={status.get('url')} onClick={this.handleClick} title={title} target='_blank' rel='noopener noreferrer'> <a className='media-gallery__item-thumbnail' href={status.get('url')} onClick={this.handleClick} title={title} target='_blank' rel='noopener noreferrer'>
<canvas width={32} height={32} ref={this.setCanvasRef} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': visible && loaded })} /> <Blurhash
hash={attachment.get('blurhash')}
className={classNames('media-gallery__preview', {
'media-gallery__preview--hidden': visible && loaded,
})}
dummy={!useBlurhash}
/>
{visible ? thumbnail : icon} {visible ? thumbnail : icon}
</a> </a>
</div> </div>

View File

@ -7,11 +7,7 @@ import classNames from 'classnames';
import { throttle } from 'lodash'; import { throttle } from 'lodash';
import { getPointerPosition, fileNameFromURL } from 'flavours/glitch/features/video'; import { getPointerPosition, fileNameFromURL } from 'flavours/glitch/features/video';
import { debounce } from 'lodash'; import { debounce } from 'lodash';
import Visualizer from './visualizer';
const hex2rgba = (hex, alpha = 1) => {
const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16));
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
};
const messages = defineMessages({ const messages = defineMessages({
play: { id: 'video.play', defaultMessage: 'Play' }, play: { id: 'video.play', defaultMessage: 'Play' },
@ -54,6 +50,11 @@ class Audio extends React.PureComponent {
dragging: false, dragging: false,
}; };
constructor (props) {
super(props);
this.visualizer = new Visualizer(TICK_SIZE);
}
setPlayerRef = c => { setPlayerRef = c => {
this.player = c; this.player = c;
@ -92,9 +93,7 @@ class Audio extends React.PureComponent {
setCanvasRef = c => { setCanvasRef = c => {
this.canvas = c; this.canvas = c;
if (c) { this.visualizer.setCanvas(c);
this.canvasContext = c.getContext('2d');
}
} }
componentDidMount () { componentDidMount () {
@ -247,17 +246,12 @@ class Audio extends React.PureComponent {
_initAudioContext () { _initAudioContext () {
const context = new AudioContext(); const context = new AudioContext();
const analyser = context.createAnalyser();
const source = context.createMediaElementSource(this.audio); const source = context.createMediaElementSource(this.audio);
analyser.smoothingTimeConstant = 0.6; this.visualizer.setAudioContext(context, source);
analyser.fftSize = 2048;
source.connect(analyser);
source.connect(context.destination); source.connect(context.destination);
this.audioContext = context; this.audioContext = context;
this.analyser = analyser;
} }
handleDownload = () => { handleDownload = () => {
@ -290,20 +284,12 @@ class Audio extends React.PureComponent {
}); });
} }
_clear () { _clear() {
this.canvasContext.clearRect(0, 0, this.state.width, this.state.height); this.visualizer.clear(this.state.width, this.state.height);
} }
_draw () { _draw() {
this.canvasContext.save(); this.visualizer.draw(this._getCX(), this._getCY(), this._getAccentColor(), this._getRadius(), this._getScaleCoefficient());
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 () { _getRadius () {
@ -314,126 +300,6 @@ class Audio extends React.PureComponent {
return (this.state.height || this.props.height) / 982; 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 = this._getAccentColor();
const lastColor = hex2rgba(mainColor, 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() { _getCX() {
return Math.floor(this.state.width / 2); return Math.floor(this.state.width / 2);
} }

View File

@ -0,0 +1,136 @@
/*
Copyright (c) 2020 by Alex Permyakov (https://codepen.io/alexdevp/pen/RNELPV)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const hex2rgba = (hex, alpha = 1) => {
const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16));
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
};
export default class Visualizer {
constructor (tickSize) {
this.tickSize = tickSize;
}
setCanvas(canvas) {
this.canvas = canvas;
if (canvas) {
this.context = canvas.getContext('2d');
}
}
setAudioContext(context, source) {
const analyser = context.createAnalyser();
analyser.smoothingTimeConstant = 0.6;
analyser.fftSize = 2048;
source.connect(analyser);
this.analyser = analyser;
}
getTickPoints (count) {
const coords = [];
for(let i = 0; i < count; i++) {
const rad = Math.PI * 2 * i / count;
coords.push({ x: Math.cos(rad), y: -Math.sin(rad) });
}
return coords;
}
drawTick (cx, cy, mainColor, x1, y1, x2, y2) {
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.context.createLinearGradient(dx1, dy1, dx2, dy2);
const lastColor = hex2rgba(mainColor, 0);
gradient.addColorStop(0, mainColor);
gradient.addColorStop(0.6, mainColor);
gradient.addColorStop(1, lastColor);
this.context.beginPath();
this.context.strokeStyle = gradient;
this.context.lineWidth = 2;
this.context.moveTo(dx1, dy1);
this.context.lineTo(dx2, dy2);
this.context.stroke();
}
getTicks (count, size, radius, scaleCoefficient) {
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 = [];
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;
}
const 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,
}));
}
clear (width, height) {
this.context.clearRect(0, 0, width, height);
}
draw (cx, cy, color, radius, coefficient) {
this.context.save();
const ticks = this.getTicks(parseInt(360 * coefficient), this.tickSize, radius, coefficient);
ticks.forEach(tick => {
this.drawTick(cx, cy, color, tick.x1, tick.y1, tick.x2, tick.y2);
});
this.context.restore();
}
}

View File

@ -36,6 +36,7 @@ class Conversation extends ImmutablePureComponent {
accounts: ImmutablePropTypes.list.isRequired, accounts: ImmutablePropTypes.list.isRequired,
lastStatus: ImmutablePropTypes.map, lastStatus: ImmutablePropTypes.map,
unread:PropTypes.bool.isRequired, unread:PropTypes.bool.isRequired,
scrollKey: PropTypes.string,
onMoveUp: PropTypes.func, onMoveUp: PropTypes.func,
onMoveDown: PropTypes.func, onMoveDown: PropTypes.func,
markRead: PropTypes.func.isRequired, markRead: PropTypes.func.isRequired,
@ -156,7 +157,7 @@ class Conversation extends ImmutablePureComponent {
} }
render () { render () {
const { accounts, lastStatus, unread, intl } = this.props; const { accounts, lastStatus, unread, scrollKey, intl } = this.props;
const { isExpanded } = this.state; const { isExpanded } = this.state;
if (lastStatus === null) { if (lastStatus === null) {
@ -223,7 +224,15 @@ class Conversation extends ImmutablePureComponent {
<IconButton className='status__action-bar-button' title={intl.formatMessage(messages.reply)} icon='reply' onClick={this.handleReply} /> <IconButton className='status__action-bar-button' title={intl.formatMessage(messages.reply)} icon='reply' onClick={this.handleReply} />
<div className='status__action-bar-dropdown'> <div className='status__action-bar-dropdown'>
<DropdownMenuContainer status={lastStatus} items={menu} icon='ellipsis-h' size={18} direction='right' title={intl.formatMessage(messages.more)} /> <DropdownMenuContainer
scrollKey={scrollKey}
status={lastStatus}
items={menu}
icon='ellipsis-h'
size={18}
direction='right'
title={intl.formatMessage(messages.more)}
/>
</div> </div>
</div> </div>
</div> </div>

View File

@ -10,6 +10,7 @@ export default class ConversationsList extends ImmutablePureComponent {
static propTypes = { static propTypes = {
conversations: ImmutablePropTypes.list.isRequired, conversations: ImmutablePropTypes.list.isRequired,
scrollKey: PropTypes.string.isRequired,
hasMore: PropTypes.bool, hasMore: PropTypes.bool,
isLoading: PropTypes.bool, isLoading: PropTypes.bool,
onLoadMore: PropTypes.func, onLoadMore: PropTypes.func,
@ -57,13 +58,14 @@ export default class ConversationsList extends ImmutablePureComponent {
const { conversations, onLoadMore, ...other } = this.props; const { conversations, onLoadMore, ...other } = this.props;
return ( return (
<ScrollableList {...other} onLoadMore={onLoadMore && this.handleLoadOlder} scrollKey='direct' ref={this.setRef}> <ScrollableList {...other} onLoadMore={onLoadMore && this.handleLoadOlder} ref={this.setRef}>
{conversations.map(item => ( {conversations.map(item => (
<ConversationContainer <ConversationContainer
key={item.get('id')} key={item.get('id')}
conversationId={item.get('id')} conversationId={item.get('id')}
onMoveUp={this.handleMoveUp} onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown} onMoveDown={this.handleMoveDown}
scrollKey={this.props.scrollKey}
/> />
))} ))}
</ScrollableList> </ScrollableList>

View File

@ -8,7 +8,7 @@ import classnames from 'classnames';
import { decode as decodeIDNA } from 'flavours/glitch/util/idna'; import { decode as decodeIDNA } from 'flavours/glitch/util/idna';
import Icon from 'flavours/glitch/components/icon'; import Icon from 'flavours/glitch/components/icon';
import { useBlurhash } from 'flavours/glitch/util/initial_state'; import { useBlurhash } from 'flavours/glitch/util/initial_state';
import { decode } from 'blurhash'; import Blurhash from 'flavours/glitch/components/blurhash';
import { debounce } from 'lodash'; import { debounce } from 'lodash';
const getHostname = url => { const getHostname = url => {
@ -85,38 +85,12 @@ export default class Card extends React.PureComponent {
componentDidMount () { componentDidMount () {
window.addEventListener('resize', this.handleResize, { passive: true }); window.addEventListener('resize', this.handleResize, { passive: true });
if (this.props.card && this.props.card.get('blurhash') && this.canvas) {
this._decode();
}
} }
componentWillUnmount () { componentWillUnmount () {
window.removeEventListener('resize', this.handleResize); 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.canvas) {
this._decode();
}
}
_decode () {
if (!useBlurhash) return;
const hash = this.props.card.get('blurhash');
const pixels = decode(hash, 32, 32);
if (pixels) {
const ctx = this.canvas.getContext('2d');
const imageData = new ImageData(pixels, 32, 32);
ctx.putImageData(imageData, 0, 0);
}
}
_setDimensions () { _setDimensions () {
const width = this.node.offsetWidth; const width = this.node.offsetWidth;
@ -174,10 +148,6 @@ export default class Card extends React.PureComponent {
} }
} }
setCanvasRef = c => {
this.canvas = c;
}
handleImageLoad = () => { handleImageLoad = () => {
this.setState({ previewLoaded: true }); this.setState({ previewLoaded: true });
} }
@ -230,7 +200,15 @@ export default class Card extends React.PureComponent {
); );
let embed = ''; let embed = '';
let canvas = <canvas width={32} height={32} ref={this.setCanvasRef} className={classnames('status-card__image-preview', { 'status-card__image-preview--hidden' : revealed && this.state.previewLoaded })} />; let canvas = (
<Blurhash
className={classnames('status-card__image-preview', {
'status-card__image-preview--hidden': revealed && this.state.previewLoaded,
})}
hash={card.get('blurhash')}
dummy={!useBlurhash}
/>
);
let thumbnail = <img src={card.get('image')} alt='' style={{ width: horizontal ? width : null, height: horizontal ? height : null, visibility: revealed ? null : 'hidden' }} onLoad={this.handleImageLoad} className='status-card__image-image' />; let thumbnail = <img src={card.get('image')} alt='' style={{ width: horizontal ? width : null, height: horizontal ? height : null, visibility: revealed ? null : 'hidden' }} onLoad={this.handleImageLoad} className='status-card__image-image' />;
let spoilerButton = ( let spoilerButton = (
<button type='button' onClick={this.handleReveal} className='spoiler-button__overlay'> <button type='button' onClick={this.handleReveal} className='spoiler-button__overlay'>

View File

@ -7,7 +7,7 @@ import classNames from 'classnames';
import { isFullscreen, requestFullscreen, exitFullscreen } from 'flavours/glitch/util/fullscreen'; import { isFullscreen, requestFullscreen, exitFullscreen } from 'flavours/glitch/util/fullscreen';
import { displayMedia, useBlurhash } from 'flavours/glitch/util/initial_state'; import { displayMedia, useBlurhash } from 'flavours/glitch/util/initial_state';
import Icon from 'flavours/glitch/components/icon'; import Icon from 'flavours/glitch/components/icon';
import { decode } from 'blurhash'; import Blurhash from 'flavours/glitch/components/blurhash';
const messages = defineMessages({ const messages = defineMessages({
play: { id: 'video.play', defaultMessage: 'Play' }, play: { id: 'video.play', defaultMessage: 'Play' },
@ -179,14 +179,6 @@ class Video extends React.PureComponent {
this.volume = c; this.volume = c;
} }
setCanvasRef = c => {
this.canvas = c;
if (c && this.props.blurhash) {
this._decode();
}
}
handleMouseDownRoot = e => { handleMouseDownRoot = e => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
@ -305,10 +297,6 @@ class Video extends React.PureComponent {
document.addEventListener('MSFullscreenChange', this.handleFullscreenChange, true); document.addEventListener('MSFullscreenChange', this.handleFullscreenChange, true);
window.addEventListener('resize', this.handleResize, { passive: true }); window.addEventListener('resize', this.handleResize, { passive: true });
if (this.props.blurhash) {
this._decode();
}
} }
componentWillUnmount () { componentWillUnmount () {
@ -330,23 +318,6 @@ class Video extends React.PureComponent {
if (this.video && this.state.revealed && this.props.preventPlayback && !prevProps.preventPlayback) { if (this.video && this.state.revealed && this.props.preventPlayback && !prevProps.preventPlayback) {
this.video.pause(); this.video.pause();
} }
if (prevProps.blurhash !== this.props.blurhash && this.props.blurhash) {
this._decode();
}
}
_decode () {
if (!this.canvas || !useBlurhash) return;
const hash = this.props.blurhash;
const pixels = decode(hash, 32, 32);
if (pixels) {
const ctx = this.canvas.getContext('2d');
const imageData = new ImageData(pixels, 32, 32);
ctx.putImageData(imageData, 0, 0);
}
} }
handleResize = debounce(() => { handleResize = debounce(() => {
@ -440,7 +411,7 @@ class Video extends React.PureComponent {
} }
render () { render () {
const { preview, src, inline, startTime, onOpenVideo, onCloseVideo, intl, alt, letterbox, fullwidth, detailed, sensitive, link, editable } = this.props; const { preview, src, inline, startTime, onOpenVideo, onCloseVideo, intl, alt, letterbox, fullwidth, detailed, sensitive, link, editable, blurhash } = this.props;
const { containerWidth, currentTime, duration, volume, buffer, dragging, paused, fullscreen, hovered, muted, revealed } = this.state; const { containerWidth, currentTime, duration, volume, buffer, dragging, paused, fullscreen, hovered, muted, revealed } = this.state;
const progress = (currentTime / duration) * 100; const progress = (currentTime / duration) * 100;
const playerStyle = {}; const playerStyle = {};
@ -485,7 +456,13 @@ class Video extends React.PureComponent {
onMouseDown={this.handleMouseDownRoot} onMouseDown={this.handleMouseDownRoot}
tabIndex={0} tabIndex={0}
> >
<canvas width={32} height={32} ref={this.setCanvasRef} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': revealed })} /> <Blurhash
hash={blurhash}
className={classNames('media-gallery__preview', {
'media-gallery__preview--hidden': revealed,
})}
dummy={!useBlurhash}
/>
{(revealed || editable) && <video {(revealed || editable) && <video
ref={this.setVideoRef} ref={this.setVideoRef}

View File

@ -4,14 +4,14 @@ import {
DROPDOWN_MENU_CLOSE, DROPDOWN_MENU_CLOSE,
} from '../actions/dropdown_menu'; } from '../actions/dropdown_menu';
const initialState = Immutable.Map({ openId: null, placement: null, keyboard: false }); const initialState = Immutable.Map({ openId: null, placement: null, keyboard: false, scroll_key: null });
export default function dropdownMenu(state = initialState, action) { export default function dropdownMenu(state = initialState, action) {
switch (action.type) { switch (action.type) {
case DROPDOWN_MENU_OPEN: case DROPDOWN_MENU_OPEN:
return state.merge({ openId: action.id, placement: action.placement, keyboard: action.keyboard }); return state.merge({ openId: action.id, placement: action.placement, keyboard: action.keyboard, scroll_key: action.scroll_key });
case DROPDOWN_MENU_CLOSE: case DROPDOWN_MENU_CLOSE:
return state.get('openId') === action.id ? state.set('openId', null) : state; return state.get('openId') === action.id ? state.set('openId', null).set('scroll_key', null) : state;
default: default:
return state; return state;
} }

View File

@ -1,8 +1,8 @@
export const DROPDOWN_MENU_OPEN = 'DROPDOWN_MENU_OPEN'; export const DROPDOWN_MENU_OPEN = 'DROPDOWN_MENU_OPEN';
export const DROPDOWN_MENU_CLOSE = 'DROPDOWN_MENU_CLOSE'; export const DROPDOWN_MENU_CLOSE = 'DROPDOWN_MENU_CLOSE';
export function openDropdownMenu(id, placement, keyboard) { export function openDropdownMenu(id, placement, keyboard, scroll_key) {
return { type: DROPDOWN_MENU_OPEN, id, placement, keyboard }; return { type: DROPDOWN_MENU_OPEN, id, placement, keyboard, scroll_key };
} }
export function closeDropdownMenu(id) { export function closeDropdownMenu(id) {

View File

@ -0,0 +1,65 @@
// @ts-check
import { decode } from 'blurhash';
import React, { useRef, useEffect } from 'react';
import PropTypes from 'prop-types';
/**
* @typedef BlurhashPropsBase
* @property {string?} hash Hash to render
* @property {number} width
* Width of the blurred region in pixels. Defaults to 32
* @property {number} [height]
* Height of the blurred region in pixels. Defaults to width
* @property {boolean} [dummy]
* Whether dummy mode is enabled. If enabled, nothing is rendered
* and canvas left untouched
*/
/** @typedef {JSX.IntrinsicElements['canvas'] & BlurhashPropsBase} BlurhashProps */
/**
* Component that is used to render blurred of blurhash string
*
* @param {BlurhashProps} param1 Props of the component
* @returns Canvas which will render blurred region element to embed
*/
function Blurhash({
hash,
width = 32,
height = width,
dummy = false,
...canvasProps
}) {
const canvasRef = /** @type {import('react').MutableRefObject<HTMLCanvasElement>} */ (useRef());
useEffect(() => {
const { current: canvas } = canvasRef;
canvas.width = canvas.width; // resets canvas
if (dummy || !hash) return;
try {
const pixels = decode(hash, width, height);
const ctx = canvas.getContext('2d');
const imageData = new ImageData(pixels, width, height);
ctx.putImageData(imageData, 0, 0);
} catch (err) {
console.error('Blurhash decoding failure', { err, hash });
}
}, [dummy, hash, width, height]);
return (
<canvas {...canvasProps} ref={canvasRef} width={width} height={height} />
);
}
Blurhash.propTypes = {
hash: PropTypes.string.isRequired,
width: PropTypes.number,
height: PropTypes.number,
dummy: PropTypes.bool,
};
export default React.memo(Blurhash);

View File

@ -7,8 +7,8 @@ import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { isIOS } from '../is_mobile'; import { isIOS } from '../is_mobile';
import classNames from 'classnames'; import classNames from 'classnames';
import { autoPlayGif, cropImages, displayMedia, useBlurhash } from '../initial_state'; import { autoPlayGif, cropImages, displayMedia, useBlurhash } from '../initial_state';
import { decode } from 'blurhash';
import { debounce } from 'lodash'; import { debounce } from 'lodash';
import Blurhash from 'mastodon/components/blurhash';
const messages = defineMessages({ 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}}' },
@ -74,36 +74,6 @@ class Item extends React.PureComponent {
e.stopPropagation(); e.stopPropagation();
} }
componentDidMount () {
if (this.props.attachment.get('blurhash')) {
this._decode();
}
}
componentDidUpdate (prevProps) {
if (prevProps.attachment.get('blurhash') !== this.props.attachment.get('blurhash') && this.props.attachment.get('blurhash')) {
this._decode();
}
}
_decode () {
if (!useBlurhash) return;
const hash = this.props.attachment.get('blurhash');
const pixels = decode(hash, 32, 32);
if (pixels) {
const ctx = this.canvas.getContext('2d');
const imageData = new ImageData(pixels, 32, 32);
ctx.putImageData(imageData, 0, 0);
}
}
setCanvasRef = c => {
this.canvas = c;
}
handleImageLoad = () => { handleImageLoad = () => {
this.setState({ loaded: true }); this.setState({ loaded: true });
} }
@ -166,7 +136,11 @@ class Item extends React.PureComponent {
return ( return (
<div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}> <div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}>
<a className='media-gallery__item-thumbnail' href={attachment.get('remote_url') || attachment.get('url')} style={{ cursor: 'pointer' }} title={attachment.get('description')} target='_blank' rel='noopener noreferrer'> <a className='media-gallery__item-thumbnail' href={attachment.get('remote_url') || attachment.get('url')} style={{ cursor: 'pointer' }} title={attachment.get('description')} target='_blank' rel='noopener noreferrer'>
<canvas width={32} height={32} ref={this.setCanvasRef} className='media-gallery__preview' /> <Blurhash
hash={attachment.get('blurhash')}
className='media-gallery__preview'
dummy={!useBlurhash}
/>
</a> </a>
</div> </div>
); );
@ -232,7 +206,13 @@ class Item extends React.PureComponent {
return ( return (
<div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}> <div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}>
<canvas width={32} height={32} ref={this.setCanvasRef} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': visible && this.state.loaded })} /> <Blurhash
hash={attachment.get('blurhash')}
dummy={!useBlurhash}
className={classNames('media-gallery__preview', {
'media-gallery__preview--hidden': visible && this.state.loaded,
})}
/>
{visible && thumbnail} {visible && thumbnail}
</div> </div>
); );

View File

@ -10,10 +10,18 @@ import { List as ImmutableList } from 'immutable';
import classNames from 'classnames'; import classNames from 'classnames';
import { attachFullscreenListener, detachFullscreenListener, isFullscreen } from '../features/ui/util/fullscreen'; import { attachFullscreenListener, detachFullscreenListener, isFullscreen } from '../features/ui/util/fullscreen';
import LoadingIndicator from './loading_indicator'; import LoadingIndicator from './loading_indicator';
import { connect } from 'react-redux';
const MOUSE_IDLE_DELAY = 300; const MOUSE_IDLE_DELAY = 300;
export default class ScrollableList extends PureComponent { const mapStateToProps = (state, { scrollKey }) => {
return {
preventScroll: scrollKey === state.getIn(['dropdown_menu', 'scroll_key']),
};
};
export default @connect(mapStateToProps)
class ScrollableList extends PureComponent {
static contextTypes = { static contextTypes = {
router: PropTypes.object, router: PropTypes.object,
@ -37,6 +45,7 @@ export default class ScrollableList extends PureComponent {
emptyMessage: PropTypes.node, emptyMessage: PropTypes.node,
children: PropTypes.node, children: PropTypes.node,
bindToDocument: PropTypes.bool, bindToDocument: PropTypes.bool,
preventScroll: PropTypes.bool,
}; };
static defaultProps = { static defaultProps = {
@ -129,7 +138,7 @@ export default class ScrollableList extends PureComponent {
}); });
handleMouseIdle = () => { handleMouseIdle = () => {
if (this.scrollToTopOnMouseIdle) { if (this.scrollToTopOnMouseIdle && !this.props.preventScroll) {
this.setScrollTop(0); this.setScrollTop(0);
} }
@ -179,7 +188,7 @@ export default class ScrollableList extends PureComponent {
this.getFirstChildKey(prevProps) !== this.getFirstChildKey(this.props); this.getFirstChildKey(prevProps) !== this.getFirstChildKey(this.props);
const pendingChanged = (prevProps.numPending > 0) !== (this.props.numPending > 0); const pendingChanged = (prevProps.numPending > 0) !== (this.props.numPending > 0);
if (pendingChanged || someItemInserted && (this.getScrollTop() > 0 || this.mouseMovedRecently)) { if (pendingChanged || someItemInserted && (this.getScrollTop() > 0 || this.mouseMovedRecently || this.props.preventScroll)) {
return this.getScrollHeight() - this.getScrollTop(); return this.getScrollHeight() - this.getScrollTop();
} else { } else {
return null; return null;

View File

@ -94,6 +94,7 @@ class Status extends ImmutablePureComponent {
updateScrollBottom: PropTypes.func, updateScrollBottom: PropTypes.func,
cacheMediaWidth: PropTypes.func, cacheMediaWidth: PropTypes.func,
cachedMediaWidth: PropTypes.number, cachedMediaWidth: PropTypes.number,
scrollKey: PropTypes.string,
}; };
// Avoid checking props that are functions (and whose equality will always // Avoid checking props that are functions (and whose equality will always
@ -264,7 +265,7 @@ class Status extends ImmutablePureComponent {
let media = null; let media = null;
let statusAvatar, prepend, rebloggedByText; let statusAvatar, prepend, rebloggedByText;
const { intl, hidden, featured, otherAccounts, unread, showThread } = this.props; const { intl, hidden, featured, otherAccounts, unread, showThread, scrollKey } = this.props;
let { status, account, ...other } = this.props; let { status, account, ...other } = this.props;
@ -459,7 +460,7 @@ class Status extends ImmutablePureComponent {
{media} {media}
<StatusActionBar status={status} account={account} {...other} /> <StatusActionBar scrollKey={scrollKey} status={status} account={account} {...other} />
</div> </div>
</div> </div>
</HotKeys> </HotKeys>

View File

@ -85,6 +85,7 @@ class StatusActionBar extends ImmutablePureComponent {
onPin: PropTypes.func, onPin: PropTypes.func,
onBookmark: PropTypes.func, onBookmark: PropTypes.func,
withDismiss: PropTypes.bool, withDismiss: PropTypes.bool,
scrollKey: PropTypes.string,
intl: PropTypes.object.isRequired, intl: PropTypes.object.isRequired,
}; };
@ -229,7 +230,7 @@ class StatusActionBar extends ImmutablePureComponent {
} }
render () { render () {
const { status, relationship, intl, withDismiss } = this.props; const { status, relationship, intl, withDismiss, scrollKey } = this.props;
const mutingConversation = status.get('muted'); const mutingConversation = status.get('muted');
const anonymousAccess = !me; const anonymousAccess = !me;
@ -333,7 +334,16 @@ class StatusActionBar extends ImmutablePureComponent {
{shareButton} {shareButton}
<div className='status__action-bar-dropdown'> <div className='status__action-bar-dropdown'>
<DropdownMenuContainer disabled={anonymousAccess} status={status} items={menu} icon='ellipsis-h' size={18} direction='right' title={intl.formatMessage(messages.more)} /> <DropdownMenuContainer
scrollKey={scrollKey}
disabled={anonymousAccess}
status={status}
items={menu}
icon='ellipsis-h'
size={18}
direction='right'
title={intl.formatMessage(messages.more)}
/>
</div> </div>
</div> </div>
); );

View File

@ -99,6 +99,7 @@ export default class StatusList extends ImmutablePureComponent {
onMoveUp={this.handleMoveUp} onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown} onMoveDown={this.handleMoveDown}
contextType={timelineId} contextType={timelineId}
scrollKey={this.props.scrollKey}
showThread showThread
/> />
)) ))

View File

@ -12,7 +12,7 @@ const mapStateToProps = state => ({
openedViaKeyboard: state.getIn(['dropdown_menu', 'keyboard']), openedViaKeyboard: state.getIn(['dropdown_menu', 'keyboard']),
}); });
const mapDispatchToProps = (dispatch, { status, items }) => ({ const mapDispatchToProps = (dispatch, { status, items, scrollKey }) => ({
onOpen(id, onItemClick, dropdownPlacement, keyboard) { onOpen(id, onItemClick, dropdownPlacement, keyboard) {
if (status) { if (status) {
dispatch(fetchRelationships([status.getIn(['account', 'id'])])); dispatch(fetchRelationships([status.getIn(['account', 'id'])]));
@ -22,7 +22,7 @@ const mapDispatchToProps = (dispatch, { status, items }) => ({
status, status,
actions: items, actions: items,
onClick: onItemClick, onClick: onItemClick,
}) : openDropdownMenu(id, dropdownPlacement, keyboard)); }) : openDropdownMenu(id, dropdownPlacement, keyboard, scrollKey));
}, },
onClose(id) { onClose(id) {

View File

@ -47,7 +47,6 @@ const messages = defineMessages({
unendorse: { id: 'account.unendorse', defaultMessage: 'Don\'t feature on profile' }, unendorse: { id: 'account.unendorse', defaultMessage: 'Don\'t feature on profile' },
add_or_remove_from_list: { id: 'account.add_or_remove_from_list', defaultMessage: 'Add or Remove from lists' }, add_or_remove_from_list: { id: 'account.add_or_remove_from_list', defaultMessage: 'Add or Remove from lists' },
admin_account: { id: 'status.admin_account', defaultMessage: 'Open moderation interface for @{name}' }, admin_account: { id: 'status.admin_account', defaultMessage: 'Open moderation interface for @{name}' },
add_account_note: { id: 'account.add_account_note', defaultMessage: 'Add note for @{name}' },
}); });
const dateFormatOptions = { const dateFormatOptions = {

View File

@ -1,7 +1,7 @@
import { decode } from 'blurhash'; import Blurhash from 'mastodon/components/blurhash';
import classNames from 'classnames'; import classNames from 'classnames';
import Icon from 'mastodon/components/icon'; import Icon from 'mastodon/components/icon';
import { autoPlayGif, displayMedia } from 'mastodon/initial_state'; import { autoPlayGif, displayMedia, useBlurhash } from 'mastodon/initial_state';
import { isIOS } from 'mastodon/is_mobile'; import { isIOS } from 'mastodon/is_mobile';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import React from 'react'; import React from 'react';
@ -21,34 +21,6 @@ export default class MediaItem extends ImmutablePureComponent {
loaded: false, loaded: false,
}; };
componentDidMount () {
if (this.props.attachment.get('blurhash')) {
this._decode();
}
}
componentDidUpdate (prevProps) {
if (prevProps.attachment.get('blurhash') !== this.props.attachment.get('blurhash') && this.props.attachment.get('blurhash')) {
this._decode();
}
}
_decode () {
const hash = this.props.attachment.get('blurhash');
const pixels = decode(hash, 32, 32);
if (pixels) {
const ctx = this.canvas.getContext('2d');
const imageData = new ImageData(pixels, 32, 32);
ctx.putImageData(imageData, 0, 0);
}
}
setCanvasRef = c => {
this.canvas = c;
}
handleImageLoad = () => { handleImageLoad = () => {
this.setState({ loaded: true }); this.setState({ loaded: true });
} }
@ -152,7 +124,13 @@ export default class MediaItem extends ImmutablePureComponent {
return ( return (
<div className='account-gallery__item' style={{ width, height }}> <div className='account-gallery__item' style={{ width, height }}>
<a className='media-gallery__item-thumbnail' href={status.get('url')} onClick={this.handleClick} title={title} target='_blank' rel='noopener noreferrer'> <a className='media-gallery__item-thumbnail' href={status.get('url')} onClick={this.handleClick} title={title} target='_blank' rel='noopener noreferrer'>
<canvas width={32} height={32} ref={this.setCanvasRef} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': visible && loaded })} /> <Blurhash
hash={attachment.get('blurhash')}
className={classNames('media-gallery__preview', {
'media-gallery__preview--hidden': visible && loaded,
})}
dummy={!useBlurhash}
/>
{visible && thumbnail} {visible && thumbnail}
{!visible && icon} {!visible && icon}
</a> </a>

View File

@ -7,11 +7,7 @@ import classNames from 'classnames';
import { throttle } from 'lodash'; import { throttle } from 'lodash';
import { getPointerPosition, fileNameFromURL } from 'mastodon/features/video'; import { getPointerPosition, fileNameFromURL } from 'mastodon/features/video';
import { debounce } from 'lodash'; import { debounce } from 'lodash';
import Visualizer from './visualizer';
const hex2rgba = (hex, alpha = 1) => {
const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16));
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
};
const messages = defineMessages({ const messages = defineMessages({
play: { id: 'video.play', defaultMessage: 'Play' }, play: { id: 'video.play', defaultMessage: 'Play' },
@ -54,6 +50,11 @@ class Audio extends React.PureComponent {
dragging: false, dragging: false,
}; };
constructor (props) {
super(props);
this.visualizer = new Visualizer(TICK_SIZE);
}
setPlayerRef = c => { setPlayerRef = c => {
this.player = c; this.player = c;
@ -92,9 +93,7 @@ class Audio extends React.PureComponent {
setCanvasRef = c => { setCanvasRef = c => {
this.canvas = c; this.canvas = c;
if (c) { this.visualizer.setCanvas(c);
this.canvasContext = c.getContext('2d');
}
} }
componentDidMount () { componentDidMount () {
@ -262,17 +261,12 @@ class Audio extends React.PureComponent {
_initAudioContext () { _initAudioContext () {
const context = new AudioContext(); const context = new AudioContext();
const analyser = context.createAnalyser();
const source = context.createMediaElementSource(this.audio); const source = context.createMediaElementSource(this.audio);
analyser.smoothingTimeConstant = 0.6; this.visualizer.setAudioContext(context, source);
analyser.fftSize = 2048;
source.connect(analyser);
source.connect(context.destination); source.connect(context.destination);
this.audioContext = context; this.audioContext = context;
this.analyser = analyser;
} }
handleDownload = () => { handleDownload = () => {
@ -305,20 +299,12 @@ class Audio extends React.PureComponent {
}); });
} }
_clear () { _clear() {
this.canvasContext.clearRect(0, 0, this.state.width, this.state.height); this.visualizer.clear(this.state.width, this.state.height);
} }
_draw () { _draw() {
this.canvasContext.save(); this.visualizer.draw(this._getCX(), this._getCY(), this._getAccentColor(), this._getRadius(), this._getScaleCoefficient());
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 () { _getRadius () {
@ -329,126 +315,6 @@ class Audio extends React.PureComponent {
return (this.state.height || this.props.height) / 982; 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 = this._getAccentColor();
const lastColor = hex2rgba(mainColor, 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() { _getCX() {
return Math.floor(this.state.width / 2); return Math.floor(this.state.width / 2);
} }

View File

@ -0,0 +1,136 @@
/*
Copyright (c) 2020 by Alex Permyakov (https://codepen.io/alexdevp/pen/RNELPV)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const hex2rgba = (hex, alpha = 1) => {
const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16));
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
};
export default class Visualizer {
constructor (tickSize) {
this.tickSize = tickSize;
}
setCanvas(canvas) {
this.canvas = canvas;
if (canvas) {
this.context = canvas.getContext('2d');
}
}
setAudioContext(context, source) {
const analyser = context.createAnalyser();
analyser.smoothingTimeConstant = 0.6;
analyser.fftSize = 2048;
source.connect(analyser);
this.analyser = analyser;
}
getTickPoints (count) {
const coords = [];
for(let i = 0; i < count; i++) {
const rad = Math.PI * 2 * i / count;
coords.push({ x: Math.cos(rad), y: -Math.sin(rad) });
}
return coords;
}
drawTick (cx, cy, mainColor, x1, y1, x2, y2) {
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.context.createLinearGradient(dx1, dy1, dx2, dy2);
const lastColor = hex2rgba(mainColor, 0);
gradient.addColorStop(0, mainColor);
gradient.addColorStop(0.6, mainColor);
gradient.addColorStop(1, lastColor);
this.context.beginPath();
this.context.strokeStyle = gradient;
this.context.lineWidth = 2;
this.context.moveTo(dx1, dy1);
this.context.lineTo(dx2, dy2);
this.context.stroke();
}
getTicks (count, size, radius, scaleCoefficient) {
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 = [];
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;
}
const 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,
}));
}
clear (width, height) {
this.context.clearRect(0, 0, width, height);
}
draw (cx, cy, color, radius, coefficient) {
this.context.save();
const ticks = this.getTicks(parseInt(360 * coefficient), this.tickSize, radius, coefficient);
ticks.forEach(tick => {
this.drawTick(cx, cy, color, tick.x1, tick.y1, tick.x2, tick.y2);
});
this.context.restore();
}
}

View File

@ -36,6 +36,7 @@ class Conversation extends ImmutablePureComponent {
accounts: ImmutablePropTypes.list.isRequired, accounts: ImmutablePropTypes.list.isRequired,
lastStatus: ImmutablePropTypes.map, lastStatus: ImmutablePropTypes.map,
unread:PropTypes.bool.isRequired, unread:PropTypes.bool.isRequired,
scrollKey: PropTypes.string,
onMoveUp: PropTypes.func, onMoveUp: PropTypes.func,
onMoveDown: PropTypes.func, onMoveDown: PropTypes.func,
markRead: PropTypes.func.isRequired, markRead: PropTypes.func.isRequired,
@ -127,7 +128,7 @@ class Conversation extends ImmutablePureComponent {
} }
render () { render () {
const { accounts, lastStatus, unread, intl } = this.props; const { accounts, lastStatus, unread, scrollKey, intl } = this.props;
if (lastStatus === null) { if (lastStatus === null) {
return null; return null;
@ -194,7 +195,15 @@ class Conversation extends ImmutablePureComponent {
<IconButton className='status__action-bar-button' title={intl.formatMessage(messages.reply)} icon='reply' onClick={this.handleReply} /> <IconButton className='status__action-bar-button' title={intl.formatMessage(messages.reply)} icon='reply' onClick={this.handleReply} />
<div className='status__action-bar-dropdown'> <div className='status__action-bar-dropdown'>
<DropdownMenuContainer status={lastStatus} items={menu} icon='ellipsis-h' size={18} direction='right' title={intl.formatMessage(messages.more)} /> <DropdownMenuContainer
scrollKey={scrollKey}
status={lastStatus}
items={menu}
icon='ellipsis-h'
size={18}
direction='right'
title={intl.formatMessage(messages.more)}
/>
</div> </div>
</div> </div>
</div> </div>

View File

@ -10,6 +10,7 @@ export default class ConversationsList extends ImmutablePureComponent {
static propTypes = { static propTypes = {
conversations: ImmutablePropTypes.list.isRequired, conversations: ImmutablePropTypes.list.isRequired,
scrollKey: PropTypes.string.isRequired,
hasMore: PropTypes.bool, hasMore: PropTypes.bool,
isLoading: PropTypes.bool, isLoading: PropTypes.bool,
onLoadMore: PropTypes.func, onLoadMore: PropTypes.func,
@ -58,13 +59,14 @@ export default class ConversationsList extends ImmutablePureComponent {
const { conversations, onLoadMore, ...other } = this.props; const { conversations, onLoadMore, ...other } = this.props;
return ( return (
<ScrollableList {...other} onLoadMore={onLoadMore && this.handleLoadOlder} scrollKey='direct' ref={this.setRef}> <ScrollableList {...other} onLoadMore={onLoadMore && this.handleLoadOlder} ref={this.setRef}>
{conversations.map(item => ( {conversations.map(item => (
<ConversationContainer <ConversationContainer
key={item.get('id')} key={item.get('id')}
conversationId={item.get('id')} conversationId={item.get('id')}
onMoveUp={this.handleMoveUp} onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown} onMoveDown={this.handleMoveDown}
scrollKey={this.props.scrollKey}
/> />
))} ))}
</ScrollableList> </ScrollableList>

View File

@ -7,7 +7,7 @@ import punycode from 'punycode';
import classnames from 'classnames'; import classnames from 'classnames';
import Icon from 'mastodon/components/icon'; import Icon from 'mastodon/components/icon';
import { useBlurhash } from 'mastodon/initial_state'; import { useBlurhash } from 'mastodon/initial_state';
import { decode } from 'blurhash'; import Blurhash from 'mastodon/components/blurhash';
import { debounce } from 'lodash'; import { debounce } from 'lodash';
const IDNA_PREFIX = 'xn--'; const IDNA_PREFIX = 'xn--';
@ -93,38 +93,12 @@ export default class Card extends React.PureComponent {
componentDidMount () { componentDidMount () {
window.addEventListener('resize', this.handleResize, { passive: true }); window.addEventListener('resize', this.handleResize, { passive: true });
if (this.props.card && this.props.card.get('blurhash') && this.canvas) {
this._decode();
}
} }
componentWillUnmount () { componentWillUnmount () {
window.removeEventListener('resize', this.handleResize); 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.canvas) {
this._decode();
}
}
_decode () {
if (!useBlurhash) return;
const hash = this.props.card.get('blurhash');
const pixels = decode(hash, 32, 32);
if (pixels) {
const ctx = this.canvas.getContext('2d');
const imageData = new ImageData(pixels, 32, 32);
ctx.putImageData(imageData, 0, 0);
}
}
_setDimensions () { _setDimensions () {
const width = this.node.offsetWidth; const width = this.node.offsetWidth;
@ -182,10 +156,6 @@ export default class Card extends React.PureComponent {
} }
} }
setCanvasRef = c => {
this.canvas = c;
}
handleImageLoad = () => { handleImageLoad = () => {
this.setState({ previewLoaded: true }); this.setState({ previewLoaded: true });
} }
@ -238,7 +208,15 @@ export default class Card extends React.PureComponent {
); );
let embed = ''; let embed = '';
let canvas = <canvas width={32} height={32} ref={this.setCanvasRef} className={classnames('status-card__image-preview', { 'status-card__image-preview--hidden' : revealed && this.state.previewLoaded })} />; let canvas = (
<Blurhash
className={classnames('status-card__image-preview', {
'status-card__image-preview--hidden': revealed && this.state.previewLoaded,
})}
hash={card.get('blurhash')}
dummy={!useBlurhash}
/>
);
let thumbnail = <img src={card.get('image')} alt='' style={{ width: horizontal ? width : null, height: horizontal ? height : null, visibility: revealed ? null : 'hidden' }} onLoad={this.handleImageLoad} className='status-card__image-image' />; let thumbnail = <img src={card.get('image')} alt='' style={{ width: horizontal ? width : null, height: horizontal ? height : null, visibility: revealed ? null : 'hidden' }} onLoad={this.handleImageLoad} className='status-card__image-image' />;
let spoilerButton = ( let spoilerButton = (
<button type='button' onClick={this.handleReveal} className='spoiler-button__overlay'> <button type='button' onClick={this.handleReveal} className='spoiler-button__overlay'>

View File

@ -7,7 +7,7 @@ import classNames from 'classnames';
import { isFullscreen, requestFullscreen, exitFullscreen } from '../ui/util/fullscreen'; import { isFullscreen, requestFullscreen, exitFullscreen } from '../ui/util/fullscreen';
import { displayMedia, useBlurhash } from '../../initial_state'; import { displayMedia, useBlurhash } from '../../initial_state';
import Icon from 'mastodon/components/icon'; import Icon from 'mastodon/components/icon';
import { decode } from 'blurhash'; import Blurhash from 'mastodon/components/blurhash';
const messages = defineMessages({ const messages = defineMessages({
play: { id: 'video.play', defaultMessage: 'Play' }, play: { id: 'video.play', defaultMessage: 'Play' },
@ -169,10 +169,6 @@ class Video extends React.PureComponent {
this.volume = c; this.volume = c;
} }
setCanvasRef = c => {
this.canvas = c;
}
handleClickRoot = e => e.stopPropagation(); handleClickRoot = e => e.stopPropagation();
handlePlay = () => { handlePlay = () => {
@ -289,10 +285,6 @@ class Video extends React.PureComponent {
window.addEventListener('scroll', this.handleScroll); window.addEventListener('scroll', this.handleScroll);
window.addEventListener('resize', this.handleResize, { passive: true }); window.addEventListener('resize', this.handleResize, { passive: true });
if (this.props.blurhash) {
this._decode();
}
} }
componentWillUnmount () { componentWillUnmount () {
@ -315,24 +307,6 @@ class Video extends React.PureComponent {
if (prevState.revealed && !this.state.revealed && this.video) { if (prevState.revealed && !this.state.revealed && this.video) {
this.video.pause(); this.video.pause();
} }
if (prevProps.blurhash !== this.props.blurhash && this.props.blurhash) {
this._decode();
}
}
_decode () {
if (!useBlurhash) return;
const hash = this.props.blurhash;
const pixels = decode(hash, 32, 32);
if (pixels) {
const ctx = this.canvas.getContext('2d');
const imageData = new ImageData(pixels, 32, 32);
ctx.putImageData(imageData, 0, 0);
}
} }
handleResize = debounce(() => { handleResize = debounce(() => {
@ -438,7 +412,7 @@ class Video extends React.PureComponent {
} }
render () { render () {
const { preview, src, inline, startTime, onOpenVideo, onCloseVideo, intl, alt, detailed, sensitive, link, editable } = this.props; const { preview, src, inline, startTime, onOpenVideo, onCloseVideo, intl, alt, detailed, sensitive, link, editable, blurhash } = this.props;
const { containerWidth, currentTime, duration, volume, buffer, dragging, paused, fullscreen, hovered, muted, revealed } = this.state; const { containerWidth, currentTime, duration, volume, buffer, dragging, paused, fullscreen, hovered, muted, revealed } = this.state;
const progress = (currentTime / duration) * 100; const progress = (currentTime / duration) * 100;
const playerStyle = {}; const playerStyle = {};
@ -481,7 +455,13 @@ class Video extends React.PureComponent {
onClick={this.handleClickRoot} onClick={this.handleClickRoot}
tabIndex={0} tabIndex={0}
> >
<canvas width={32} height={32} ref={this.setCanvasRef} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': revealed })} /> <Blurhash
hash={blurhash}
className={classNames('media-gallery__preview', {
'media-gallery__preview--hidden': revealed,
})}
dummy={!useBlurhash}
/>
{(revealed || editable) && <video {(revealed || editable) && <video
ref={this.setVideoRef} ref={this.setVideoRef}

View File

@ -139,6 +139,23 @@
], ],
"path": "app/javascript/mastodon/components/column_header.json" "path": "app/javascript/mastodon/components/column_header.json"
}, },
{
"descriptors": [
{
"defaultMessage": "{count, plural, one {{counter} Toot} other {{counter} Toots}}",
"id": "account.statuses_counter"
},
{
"defaultMessage": "{count, plural, other {{counter} Following}}",
"id": "account.following_counter"
},
{
"defaultMessage": "{count, plural, one {{counter} Follower} other {{counter} Followers}}",
"id": "account.followers_counter"
}
],
"path": "app/javascript/mastodon/components/common_counter.json"
},
{ {
"descriptors": [ "descriptors": [
{ {
@ -172,8 +189,8 @@
{ {
"descriptors": [ "descriptors": [
{ {
"defaultMessage": "{count} {rawCount, plural, one {person} other {people}} talking", "defaultMessage": "{count, plural, one {{counter} person} other {{counter} people}} talking",
"id": "trends.count_by_accounts" "id": "trends.counter_by_accounts"
} }
], ],
"path": "app/javascript/mastodon/components/hashtag.json" "path": "app/javascript/mastodon/components/hashtag.json"
@ -340,6 +357,23 @@
], ],
"path": "app/javascript/mastodon/components/relative_timestamp.json" "path": "app/javascript/mastodon/components/relative_timestamp.json"
}, },
{
"descriptors": [
{
"defaultMessage": "{count}K",
"id": "units.short.thousand"
},
{
"defaultMessage": "{count}M",
"id": "units.short.million"
},
{
"defaultMessage": "{count}B",
"id": "units.short.billion"
}
],
"path": "app/javascript/mastodon/components/short_number.json"
},
{ {
"descriptors": [ "descriptors": [
{ {
@ -833,18 +867,6 @@
{ {
"defaultMessage": "Group", "defaultMessage": "Group",
"id": "account.badges.group" "id": "account.badges.group"
},
{
"defaultMessage": "Toots",
"id": "account.posts"
},
{
"defaultMessage": "Follows",
"id": "account.follows"
},
{
"defaultMessage": "Followers",
"id": "account.followers"
} }
], ],
"path": "app/javascript/mastodon/features/account/components/header.json" "path": "app/javascript/mastodon/features/account/components/header.json"

View File

@ -15,7 +15,8 @@
"account.follow": "Follow", "account.follow": "Follow",
"account.followers": "Followers", "account.followers": "Followers",
"account.followers.empty": "No one follows this user yet.", "account.followers.empty": "No one follows this user yet.",
"account.follows": "Follows", "account.followers_counter": "{count, plural, one {{counter} Follower} other {{counter} Followers}}",
"account.following_counter": "{count, plural, other {{counter} Following}}",
"account.follows.empty": "This user doesn't follow anyone yet.", "account.follows.empty": "This user doesn't follow anyone yet.",
"account.follows_you": "Follows you", "account.follows_you": "Follows you",
"account.hide_reblogs": "Hide boosts from @{name}", "account.hide_reblogs": "Hide boosts from @{name}",
@ -35,6 +36,7 @@
"account.requested": "Awaiting approval. Click to cancel follow request", "account.requested": "Awaiting approval. Click to cancel follow request",
"account.share": "Share @{name}'s profile", "account.share": "Share @{name}'s profile",
"account.show_reblogs": "Show boosts from @{name}", "account.show_reblogs": "Show boosts from @{name}",
"account.statuses_counter": "{count, plural, one {{counter} Toot} other {{counter} Toots}}",
"account.unblock": "Unblock @{name}", "account.unblock": "Unblock @{name}",
"account.unblock_domain": "Unblock domain {domain}", "account.unblock_domain": "Unblock domain {domain}",
"account.unendorse": "Don't feature on profile", "account.unendorse": "Don't feature on profile",
@ -426,9 +428,12 @@
"timeline_hint.resources.followers": "Followers", "timeline_hint.resources.followers": "Followers",
"timeline_hint.resources.follows": "Follows", "timeline_hint.resources.follows": "Follows",
"timeline_hint.resources.statuses": "Older toots", "timeline_hint.resources.statuses": "Older toots",
"trends.count_by_accounts": "{count} {rawCount, plural, one {person} other {people}} talking", "trends.counter_by_accounts": "{count, plural, one {{counter} person} other {{counter} people}} talking",
"trends.trending_now": "Trending now", "trends.trending_now": "Trending now",
"ui.beforeunload": "Your draft will be lost if you leave Mastodon.", "ui.beforeunload": "Your draft will be lost if you leave Mastodon.",
"units.short.billion": "{count}B",
"units.short.million": "{count}M",
"units.short.thousand": "{count}K",
"upload_area.title": "Drag & drop to upload", "upload_area.title": "Drag & drop to upload",
"upload_button.label": "Add images, a video or an audio file", "upload_button.label": "Add images, a video or an audio file",
"upload_error.limit": "File upload limit exceeded.", "upload_error.limit": "File upload limit exceeded.",

View File

@ -4,14 +4,14 @@ import {
DROPDOWN_MENU_CLOSE, DROPDOWN_MENU_CLOSE,
} from '../actions/dropdown_menu'; } from '../actions/dropdown_menu';
const initialState = Immutable.Map({ openId: null, placement: null, keyboard: false }); const initialState = Immutable.Map({ openId: null, placement: null, keyboard: false, scroll_key: null });
export default function dropdownMenu(state = initialState, action) { export default function dropdownMenu(state = initialState, action) {
switch (action.type) { switch (action.type) {
case DROPDOWN_MENU_OPEN: case DROPDOWN_MENU_OPEN:
return state.merge({ openId: action.id, placement: action.placement, keyboard: action.keyboard }); return state.merge({ openId: action.id, placement: action.placement, keyboard: action.keyboard, scroll_key: action.scroll_key });
case DROPDOWN_MENU_CLOSE: case DROPDOWN_MENU_CLOSE:
return state.get('openId') === action.id ? state.set('openId', null) : state; return state.get('openId') === action.id ? state.set('openId', null).set('scroll_key', null) : state;
default: default:
return state; return state;
} }

View File

@ -3,7 +3,7 @@
= javascript_pack_tag 'public', integrity: true, crossorigin: 'anonymous' = javascript_pack_tag 'public', integrity: true, crossorigin: 'anonymous'
- if @media_attachment.video? - if @media_attachment.video?
= react_component :video, src: @media_attachment.file.url(:original), preview: @media_attachment.file.url(:small), blurhash: @media_attachment.blurhash, width: 670, height: 380, editable: true, detailed: true, inline: true, alt: @media_attachment.description do = react_component :video, src: @media_attachment.file.url(:original), preview: @media_attachment.thumbnail.present? ? @media_attachment.thumbnail.url : @media_attachment.file.url(:small), blurhash: @media_attachment.blurhash, width: 670, height: 380, editable: true, detailed: true, inline: true, alt: @media_attachment.description do
%video{ controls: 'controls' } %video{ controls: 'controls' }
%source{ src: @media_attachment.file.url(:original) } %source{ src: @media_attachment.file.url(:original) }
- elsif @media_attachment.gifv? - elsif @media_attachment.gifv?

View File

@ -29,7 +29,7 @@
- if !status.media_attachments.empty? - if !status.media_attachments.empty?
- if status.media_attachments.first.video? - if status.media_attachments.first.video?
- video = status.media_attachments.first - video = status.media_attachments.first
= react_component :video, src: video.file.url(:original), preview: video.file.url(:small), blurhash: video.blurhash, sensitive: status.sensitive?, width: 670, height: 380, detailed: true, inline: true, alt: video.description do = react_component :video, src: video.file.url(:original), preview: video.thumbnail.present? ? video.thumbnail.url : video.file.url(:small), blurhash: video.blurhash, sensitive: status.sensitive?, width: 670, height: 380, detailed: true, inline: true, alt: video.description do
= render partial: 'statuses/attachment_list', locals: { attachments: status.media_attachments } = render partial: 'statuses/attachment_list', locals: { attachments: status.media_attachments }
- elsif status.media_attachments.first.audio? - elsif status.media_attachments.first.audio?
- audio = status.media_attachments.first - audio = status.media_attachments.first

View File

@ -35,7 +35,7 @@
- if !status.media_attachments.empty? - if !status.media_attachments.empty?
- if status.media_attachments.first.video? - if status.media_attachments.first.video?
- video = status.media_attachments.first - video = status.media_attachments.first
= react_component :video, src: video.file.url(:original), preview: video.file.url(:small), blurhash: video.blurhash, sensitive: status.sensitive?, width: 610, height: 343, inline: true, alt: video.description do = react_component :video, src: video.file.url(:original), preview: video.thumbnail.present? ? video.thumbnail.url : video.file.url(:small), blurhash: video.blurhash, sensitive: status.sensitive?, width: 610, height: 343, inline: true, alt: video.description do
= render partial: 'statuses/attachment_list', locals: { attachments: status.media_attachments } = render partial: 'statuses/attachment_list', locals: { attachments: status.media_attachments }
- elsif status.media_attachments.first.audio? - elsif status.media_attachments.first.audio?
- audio = status.media_attachments.first - audio = status.media_attachments.first