Cleanup Identicon icon append (#151)

* Cleanup Identicon icon append

* Add SO link

* Ooops, unused vars :(

* Magic number
This commit is contained in:
Jaco Greeff 2018-07-13 13:01:26 +02:00 committed by GitHub
parent a186eb2c3d
commit 753a89f38f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 20 additions and 58 deletions

View File

@ -1,33 +0,0 @@
// Copyright 2017-2018 @polkadot/ui-react authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
describe('autoFocus', () => {
let appendIcon;
let mockIdenticon;
let node;
beforeEach(() => {
node = {
appendChild: jest.fn()
};
mockIdenticon = jest.fn(() => 'genIdentitycon');
jest.mock('@polkadot/ui-identicon', () => mockIdenticon);
appendIcon = require('./appendIcon').default;
});
it('generates & appends icon to the node', () => {
appendIcon('testAddr', 'testSize')(node);
expect(node.appendChild).toHaveBeenCalledWith('genIdentitycon');
expect(mockIdenticon).toHaveBeenCalledWith('testAddr', 'testSize');
});
it('does not call identicon when no node', () => {
appendIcon('testAddr', 'testSize')();
expect(mockIdenticon).not.toHaveBeenCalled();
});
});

View File

@ -1,21 +0,0 @@
// Copyright 2017-2018 @polkadot/ui-react authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import identicon from '@polkadot/ui-identicon/index';
type NodeRefSet = (node: Element | null) => void;
export default function appendIcon (address: string | Uint8Array, size: number): NodeRefSet {
return (node: Element | null): void => {
if (node) {
while (node.firstChild) {
node.removeChild(node.firstChild);
}
node.appendChild(
identicon(address, size)
);
}
};
}

View File

@ -7,24 +7,40 @@ import { BaseProps } from '../types';
import './IdentityIcon.css';
import React from 'react';
import appendIcon from './appendIcon';
import identicon from '@polkadot/ui-identicon/index';
type Props = BaseProps & {
size?: number,
value: string | Uint8Array
};
const DEFAULT_SIZE = 64;
export default class IdentityIcon extends React.PureComponent<Props> {
render () {
const { className, size = 64, style, value } = this.props;
const { className, style } = this.props;
return (
<div
className={['ui--IdentityIcon', className].join(' ')}
ref={appendIcon(value, size)} // TODO: The append should probably be in this class and done in a more "React-y" way
ref={this.appendIcon}
style={style}
/>
);
}
appendIcon = (node: Element | null): void => {
const { size = DEFAULT_SIZE, value } = this.props;
// https://stackoverflow.com/a/22966637
if (node && node.parentNode) {
const cloned = node.cloneNode(false);
cloned.appendChild(
identicon(value, size)
);
node.parentNode.replaceChild(cloned, node);
}
}
}