refactor: share hex-id shortening in lib/format

This commit is contained in:
Avi 2026-08-25 10:12:49 -05:00
commit e6a1efc7f2
3 changed files with 49 additions and 6 deletions

View file

@ -0,0 +1,39 @@
import { shortHexId, shortenNpub } from './format';
describe('shortHexId', () => {
it('returns an empty string unchanged', () => {
expect(shortHexId('')).toBe('');
});
it('returns a string of exactly 16 characters unchanged', () => {
const value = 'a'.repeat(16);
expect(shortHexId(value)).toBe(value);
});
it('shortens a string of 17 characters to first8…last8', () => {
// 17 chars: 9 leading a's then 8 b's.
const value = 'aaaaaaaaabbbbbbbb';
expect(shortHexId(value)).toBe('aaaaaaaa…bbbbbbbb');
});
it('shortens a 64-character hexadecimal id to first8…last8', () => {
const hex = 'a47921f7247f6f70391d9563ce0f7bbd4d73922e13cbac6ca57f712e68cdc9f0';
expect(shortHexId(hex)).toBe('a47921f7…68cdc9f0');
});
});
describe('shortenNpub', () => {
it('returns the full value when shortening is disabled', () => {
const npub = 'npub153ujraey0ahhqwgaj43uurmmh4xh8y3wz096cm990acju6xde8cqynjxwv';
expect(shortenNpub(npub, false)).toBe(npub);
});
it('keeps short values even when shortening is enabled', () => {
expect(shortenNpub('npub1short', true)).toBe('npub1short');
});
it('shortens with a 10-character prefix and 8-character suffix when enabled', () => {
const npub = 'npub153ujraey0ahhqwgaj43uurmmh4xh8y3wz096cm990acju6xde8cqynjxwv';
expect(shortenNpub(npub, true)).toBe('npub153ujr...cqynjxwv');
});
});

View file

@ -63,3 +63,11 @@ export function initialsFor(label: string): string {
}
return trimmed.charAt(0).toUpperCase();
}
/**
* Shorten a long hexadecimal id for display: `a47921f7…68cdc9f0`.
* Keeps the full value when the string is short enough to read as-is.
*/
export function shortHexId(value: string): string {
return value.length > 16 ? `${value.slice(0, 8)}…${value.slice(-8)}` : value;
}

View file

@ -4,6 +4,7 @@ import { Badge } from '../components/Badge';
import { Button } from '../components/Button';
import { ErrorText } from '../components/ErrorText';
import { Icon } from '../components/Icon';
import { shortHexId } from '../lib/format';
import type { SignerStatus } from '../lib/types';
import { useApp } from '../state/AppProvider';
@ -15,11 +16,6 @@ const EMPTY_STATUS: SignerStatus = {
pending: [],
};
/** Shorten a 64-char hex key for display. */
function shortHex(value: string): string {
return value.length > 16 ? `${value.slice(0, 8)}…${value.slice(-8)}` : value;
}
export function SignerScreen() {
const { state, signerConnect, signerDisconnect, signerStatus, signerApprove } = useApp();
const [status, setStatus] = useState<SignerStatus>(EMPTY_STATUS);
@ -137,7 +133,7 @@ export function SignerScreen() {
<dd>
{status.peer ? (
<code className="mono" title={status.peer}>
{shortHex(status.peer)}
{shortHexId(status.peer)}
</code>
) : (
<span className="muted">None yet</span>