add shared topic color utility

This commit is contained in:
2026-06-21 22:15:50 +02:00
parent 424918404f
commit 7a7e04d2f0
+108
View File
@@ -0,0 +1,108 @@
export interface TopicHierarchyColorInput {
id?: string | null;
name?: string | null;
subfield_id?: string | null;
subfield_name?: string | null;
field_id?: string | null;
field_name?: string | null;
domain_id?: string | null;
domain_name?: string | null;
}
const FIELD_HUES: Record<string, number> = {
'agricultural and biological sciences': 127,
'arts and humanities': 28,
'biochemistry, genetics and molecular biology': 154,
'business, management and accounting': 44,
'chemical engineering': 188,
chemistry: 174,
'computer science': 214,
'decision sciences': 202,
dentistry: 348,
'earth and planetary sciences': 112,
'economics, econometrics and finance': 52,
energy: 88,
engineering: 199,
'environmental science': 142,
'health professions': 334,
'immunology and microbiology': 163,
'materials science': 258,
mathematics: 233,
medicine: 348,
neuroscience: 282,
nursing: 326,
'pharmacology, toxicology and pharmaceutics': 5,
'physics and astronomy': 246,
psychology: 302,
'social sciences': 20,
veterinary: 135,
};
const DOMAIN_FALLBACK_HUES: Record<string, number> = {
'health sciences': 348,
'life sciences': 145,
'physical sciences': 214,
'social sciences': 24,
};
const SUBFIELD_HUE_OFFSETS = [-18, -12, -7, -3, 3, 7, 12, 18];
export function topicHierarchyColor(
topic: TopicHierarchyColorInput | undefined | null,
): string {
if (!topic) {
return 'hsl(214 58% 38%)';
}
const fieldKey = normalizeColorKey(topic.field_name);
const domainKey = normalizeColorKey(topic.domain_name);
const fieldIdentity =
topic.field_id ?? fieldKey ?? topic.domain_id ?? domainKey;
const subfieldIdentity =
topic.subfield_id ??
normalizeColorKey(topic.subfield_name) ??
topic.id ??
normalizeColorKey(topic.name) ??
fieldIdentity ??
'topic';
const baseHue =
(fieldKey ? FIELD_HUES[fieldKey] : undefined) ??
(domainKey ? DOMAIN_FALLBACK_HUES[domainKey] : undefined) ??
stableHue(fieldIdentity ?? subfieldIdentity);
const variantHash = stableHash(subfieldIdentity);
const offset =
SUBFIELD_HUE_OFFSETS[variantHash % SUBFIELD_HUE_OFFSETS.length];
const hue = normalizeHue(baseHue + offset);
const saturation = 55 + ((variantHash >> 3) % 14);
const lightness = 32 + ((variantHash >> 7) % 10);
return `hsl(${hue} ${saturation}% ${lightness}%)`;
}
function normalizeColorKey(
value: string | null | undefined,
): string | undefined {
const normalized = value?.trim().toLowerCase();
return normalized || undefined;
}
function stableHue(value: string): number {
return stableHash(value) % 360;
}
function stableHash(value: string): number {
let hash = 0;
for (let index = 0; index < value.length; index += 1) {
hash = Math.imul(hash ^ value.charCodeAt(index), 16777619);
}
return hash >>> 0;
}
function normalizeHue(value: number): number {
return ((value % 360) + 360) % 360;
}