Files
pezkuwi-ui/packages/reactnative-identicon/src/Identicon.tsx
T
Satoshi Qazi Muhammed 6cf7cc635a Update copyright headers to 2026
The header rule in @pezkuwi/dev requires the current year. Year range only; the third-party beachball LICENSE is left as it is.
2026-10-08 11:10:19 +04:00

82 lines
1.9 KiB
TypeScript

// Copyright 2017-2026 @pezkuwi/reactnative-identicon authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Prefix } from '@pezkuwi/util-crypto/address/types';
import type { Props as ComponentProps } from './types.js';
import React from 'react';
import { isHex, isU8a, u8aToHex } from '@pezkuwi/util';
import { decodeAddress, encodeAddress } from '@pezkuwi/util-crypto';
import { Empty, Pezkuwi } from './icons/index.js';
const Fallback = Pezkuwi;
interface Props {
prefix?: Prefix;
size?: number;
theme?: 'pezkuwi';
value?: string | Uint8Array | null;
}
interface State {
address: string;
publicKey: string;
}
const DEFAULT_SIZE = 64;
const DEFAULT_THEME = 'pezkuwi';
const Components: Record<string, React.ComponentType<ComponentProps>> = {
pezkuwi: Pezkuwi
};
export default class IdentityIcon extends React.PureComponent<Props, State> {
public override state: State = {
address: '',
publicKey: '0x'
};
private static prefix?: Prefix = undefined;
public static setDefaultPrefix (prefix: Prefix): void {
IdentityIcon.prefix = prefix;
}
public static getDerivedStateFromProps ({ prefix = IdentityIcon.prefix, value }: Props, prevState: State): State | null {
try {
const address = isU8a(value) || isHex(value)
? encodeAddress(value, prefix)
: (value || '');
const publicKey = u8aToHex(decodeAddress(address, true, prefix));
return address === prevState.address
? null
: { address, publicKey };
} catch {
return {
address: '',
publicKey: '0x'
};
}
}
public override render (): React.ReactNode {
const { size = DEFAULT_SIZE, theme = DEFAULT_THEME } = this.props;
const { address, publicKey } = this.state;
const Component = !address
? Empty
: Components[theme] || Fallback;
return (
<Component
address={address}
publicKey={publicKey}
size={size}
/>
);
}
}