Skip to content

Commit

Permalink
Replace repetitive blurhash code with component
Browse files Browse the repository at this point in the history
  • Loading branch information
alexgleason committed Jul 2, 2021
1 parent 5d27cbe commit 5c630ad
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 89 deletions.
65 changes: 65 additions & 0 deletions app/soapbox/components/blurhash.js
Original file line number Diff line number Diff line change
@@ -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);
39 changes: 8 additions & 31 deletions app/soapbox/components/media_gallery.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { isIOS } from '../is_mobile';
import { truncateFilename } from 'soapbox/utils/media';
import classNames from 'classnames';
import { decode } from 'blurhash';
import { isPanoramic, isPortrait, isNonConformingRatio, minimumAspectRatio, maximumAspectRatio } from '../utils/media_aspect_ratio';
import { Map as ImmutableMap } from 'immutable';
import { getSettings } from 'soapbox/actions/settings';
import Icon from 'soapbox/components/icon';
import StillImage from 'soapbox/components/still_image';
import Blurhash from 'soapbox/components/blurhash';

const ATTACHMENT_LIMIT = 4;
const MAX_FILENAME_LENGTH = 45;
Expand Down Expand Up @@ -102,34 +102,6 @@ class Item extends React.PureComponent {
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() {
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 = () => {
this.setState({ loaded: true });
}
Expand Down Expand Up @@ -174,7 +146,7 @@ class Item extends React.PureComponent {
return (
<div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ position, float, left, top, right, bottom, height, width: `${width}%` }}>
<a className='media-gallery__item-thumbnail' href={attachment.get('remote_url')} target='_blank' style={{ cursor: 'pointer' }}>
<canvas width={32} height={32} ref={this.setCanvasRef} className='media-gallery__preview' />
<Blurhash hash={attachment.get('blurhash')} className='media-gallery__preview' />
<span className='media-gallery__item__icons'><Icon id='file' /></span>
<span className='media-gallery__filename__label'>{filename}</span>
</a>
Expand Down Expand Up @@ -273,7 +245,12 @@ class Item extends React.PureComponent {
+{total - ATTACHMENT_LIMIT + 1}
</div>
)}
<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')}
className={classNames('media-gallery__preview', {
'media-gallery__preview--hidden': visible && this.state.loaded,
})}
/>
{visible && thumbnail}
</div>
);
Expand Down
37 changes: 7 additions & 30 deletions app/soapbox/features/account_gallery/components/media_item.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Icon from 'soapbox/components/icon';
import classNames from 'classnames';
import { decode } from 'blurhash';
import Blurhash from 'soapbox/components/blurhash';
import { isIOS } from 'soapbox/is_mobile';
import { getSettings } from 'soapbox/actions/settings';
import StillImage from 'soapbox/components/still_image';
Expand All @@ -31,34 +31,6 @@ class MediaItem extends ImmutablePureComponent {
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 = () => {
this.setState({ loaded: true });
}
Expand Down Expand Up @@ -169,7 +141,12 @@ class MediaItem extends ImmutablePureComponent {
return (
<div className='account-gallery__item' style={{ width, height }}>
<a className='media-gallery__item-thumbnail' href={status.get('url')} target='_blank' onClick={this.handleClick} title={title}>
<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,
})}
/>
{visible && thumbnail}
{!visible && icon}
</a>
Expand Down
37 changes: 9 additions & 28 deletions app/soapbox/features/video/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { throttle } from 'lodash';
import classNames from 'classnames';
import { isFullscreen, requestFullscreen, exitFullscreen } from '../ui/util/fullscreen';
import Icon from 'soapbox/components/icon';
import { decode } from 'blurhash';
import Blurhash from 'soapbox/components/blurhash';
import { isPanoramic, isPortrait, minimumAspectRatio, maximumAspectRatio } from '../../utils/media_aspect_ratio';
import { getSettings } from 'soapbox/actions/settings';

Expand Down Expand Up @@ -167,10 +167,6 @@ class Video extends React.PureComponent {
this.volume = c;
}

setCanvasRef = c => {
this.canvas = c;
}

handleClickRoot = e => e.stopPropagation();

handlePlay = () => {
Expand Down Expand Up @@ -278,10 +274,6 @@ class Video extends React.PureComponent {
document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange, true);
document.addEventListener('mozfullscreenchange', this.handleFullscreenChange, true);
document.addEventListener('MSFullscreenChange', this.handleFullscreenChange, true);

if (this.props.blurhash) {
this._decode();
}
}

componentWillUnmount() {
Expand All @@ -292,7 +284,7 @@ class Video extends React.PureComponent {
}

componentDidUpdate(prevProps, prevState) {
const { visible, blurhash } = this.props;
const { visible } = this.props;

if (!is(visible, prevProps.visible) && visible !== undefined) {
this.setState({ revealed: visible });
Expand All @@ -301,22 +293,6 @@ class Video extends React.PureComponent {
if (prevState.revealed && !this.state.revealed && this.video) {
this.video.pause();
}

if (prevProps.blurhash !== blurhash && blurhash) {
this._decode();
}
}

_decode() {
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);
}
}

handleFullscreenChange = () => {
Expand Down Expand Up @@ -396,7 +372,7 @@ class Video extends React.PureComponent {
}

render() {
const { src, inline, onOpenVideo, onCloseVideo, intl, alt, detailed, sensitive, link, aspectRatio } = this.props;
const { src, inline, onOpenVideo, onCloseVideo, intl, alt, detailed, sensitive, link, aspectRatio, blurhash } = this.props;
const { containerWidth, currentTime, duration, volume, buffer, dragging, paused, fullscreen, hovered, muted, revealed } = this.state;
const progress = (currentTime / duration) * 100;
const playerStyle = {};
Expand Down Expand Up @@ -437,7 +413,12 @@ class Video extends React.PureComponent {
onClick={this.handleClickRoot}
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,
})}
/>

{revealed && <video
ref={this.setVideoRef}
Expand Down

0 comments on commit 5c630ad

Please sign in to comment.