Open History to see the last commit
1import { useState } from "react";
2import { flushSync } from "react-dom";
3
4import { cn } from "../../lib/utils";
5import { SharedTooltipTrigger } from "../ui/shared-tooltip";
6
7const REDACTED_TEXT_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";
8
9export function redactedPlaceholder(value: string): string {
10 let state = 0x811c9dc5;
11 for (let index = 0; index < value.length; index += 1) {
12 state ^= value.charCodeAt(index);
13 state = Math.imul(state, 0x01000193);
14 }
15
16 const nextChar = () => {
17 state = Math.imul(state ^ (state >>> 13), 0x85ebca6b);
18 state = Math.imul(state ^ (state >>> 16), 0xc2b2ae35);
19 return REDACTED_TEXT_ALPHABET[Math.abs(state) % REDACTED_TEXT_ALPHABET.length] ?? "x";
20 };
21
22 return Array.from(value, (char) => {
23 if (char === "@" || char === "." || char === "-" || char === "_") return char;
24 return nextChar();
25 }).join("");
26}
27
28export function RedactedSensitiveText(props: {
29 readonly value: string | null | undefined;
30 readonly ariaLabel: string;
31 readonly revealTooltip: string;
32 readonly hideTooltip: string;
33 readonly className?: string;
34}) {
35 const [visibility, setVisibility] = useState<"hidden" | "hiding" | "revealed">("hidden");
36 const revealed = visibility === "revealed";
37 const value = props.value?.trim();
38 const redacted = value ? redactedPlaceholder(value) : "";
39
40 if (!value) return null;
41
42 return (
43 <SharedTooltipTrigger
44 render={
45 <button
46 type="button"
47 className={cn(
48 "min-w-0 cursor-pointer rounded-sm font-mono text-2xs leading-normal transition hover:text-foreground",
49 revealed ? "text-muted-foreground" : "select-none text-muted-foreground blur-xs",
50 props.className,
51 )}
52 onClick={(event) => {
53 if (!revealed) return setVisibility("revealed");
54 const button = event.currentTarget;
55 flushSync(() => setVisibility("hiding"));
56 const finishHiding = () =>
57 setVisibility((current) => (current === "hiding" ? "hidden" : current));
58 const blur = button
59 .getAnimations()
60 .find(
61 (animation) =>
62 animation instanceof CSSTransition && animation.transitionProperty === "filter",
63 );
64 // Theme changes suppress the transition; a reversed one settles once revealed.
65 if (blur) void blur.finished.then(finishHiding, finishHiding);
66 else finishHiding();
67 }}
68 aria-label={props.ariaLabel}
69 >
70 {visibility === "hidden" ? redacted : value}
71 </button>
72 }
73 label={revealed ? props.hideTooltip : props.revealTooltip}
74 />
75 );
76}