All files / apps / web/src / helpers tone.ts

100% Statements 8/8
100% Branches 0/0
100% Functions 2/2
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  20x                 20x       159x   1422x   159x           151x    
// Full class names so Tailwind sees them; the six pairs are the prototype's avatar colours.
const TONE_CLASSES = [
  'bg-avatar-0 text-avatar-0-ink',
  'bg-avatar-1 text-avatar-1-ink',
  'bg-avatar-2 text-avatar-2-ink',
  'bg-avatar-3 text-avatar-3-ink',
  'bg-avatar-4 text-avatar-4-ink',
  'bg-avatar-5 text-avatar-5-ink',
] as const
 
export const TONE_COUNT = TONE_CLASSES.length
 
// The same seed (a person's or a conversation's name) always lands on the same tone, on every screen.
export function toneIndex(seed: string): number {
  let hash = 0
 
  for (let i = 0; i < seed.length; i += 1) hash = (hash * 31 + seed.charCodeAt(i)) % 9973
 
  return hash % TONE_COUNT
}
 
// Background and ink classes of the seed's tone, for an avatar or any badge that stands for someone.
export function toneClass(seed: string): string {
  // toneIndex stays inside the six; String() only drops the `| undefined` of the indexed type.
  return String(TONE_CLASSES[toneIndex(seed)])
}