Back

Animated Label Creator (Notion-Style)

Notion-inspired animated label/tag creation with smooth transitions and color picker.

Category
Micro InteractionReact
CSS
shadcn

Manual

Create a file and paste the following code into it.

src/components/ui/label-input-selector.tsx
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
"use client";

import { useEffect, useCallback, useRef, useState, KeyboardEvent } from "react";
import { AnimatePresence, motion } from "motion/react";
import { TextMorph } from "torph/react";
import { cn } from "@/lib/cn";
import { Input } from "@/components/ui/input";
import { PixelLoader } from "@/components/ui/pixel-loader";
import { LabelIcon } from "@/components/ui/icons/label";
import { PlusIcon } from "@/components/ui/icons/plus";

const COLORS = [
  { name: "Red", value: "#ef4444" },
  { name: "Orange", value: "#f97316" },
  { name: "Green", value: "#22c55e" },
  { name: "Blue", value: "#3b82f6" },
  { name: "Violet", value: "#8b5cf6" },
  { name: "Pink", value: "#ec4899" },
] as const;

export interface Label {
  text: string;
  color: string;
}

export interface LabelColorOption {
  name: string;
  value: string;
}

type Mode = "typing" | "color-picking" | "creating";

interface LabelInputSelectorProps {
  labels?: Label[];
  onLabelsChange?: (labels: Label[]) => void;
  placeholder?: string;
  className?: string;
  colors?: LabelColorOption[];
  createDelayMs?: number;
  defaultOpen?: boolean;
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
  buttonAriaLabel?: string;
}

export function LabelInputSelector({
  labels: initialLabels = [],
  onLabelsChange,
  placeholder = "Change labels...",
  className,
  colors = [...COLORS],
  createDelayMs = 5000,
  defaultOpen = false,
  open,
  onOpenChange,
  buttonAriaLabel = "Open label selector",
}: LabelInputSelectorProps) {
  const [labels, setLabels] = useState<Label[]>(initialLabels);
  const [mode, setMode] = useState<Mode>("typing");
  const [value, setValue] = useState("");
  const [currentLabel, setCurrentLabel] = useState("");
  const [selectedColorIndex, setSelectedColorIndex] = useState(0);
  const [creatingLabel, setCreatingLabel] = useState("");
  const [creatingColor, setCreatingColor] = useState("");
  const [internalOpen, setInternalOpen] = useState(defaultOpen);
  const inputRef = useRef<HTMLInputElement>(null);
  const rootRef = useRef<HTMLDivElement>(null);

  const isOpen = open ?? internalOpen;
  const setOpen = useCallback(
    (next: boolean) => {
      if (open === undefined) setInternalOpen(next);
      onOpenChange?.(next);
    },
    [onOpenChange, open]
  );

  const addLabel = useCallback(
    (text: string, color: string) => {
      setLabels((prev) => {
        const next = [{ text, color }, ...prev];
        onLabelsChange?.(next);
        return next;
      });
    },
    [onLabelsChange]
  );

  const startColorPicking = useCallback(
    (text: string) => {
      const trimmed = text.trim();
      if (!trimmed) return;
      setCurrentLabel(trimmed);
      setValue("");
      setSelectedColorIndex(0);
      setMode("color-picking");
      setOpen(true);
    },
    [setOpen]
  );

  const submitSelectedColor = useCallback(() => {
    const selected = colors[selectedColorIndex];
    setCreatingLabel(currentLabel);
    setCreatingColor(selected.value);
    setMode("creating");
  }, [colors, currentLabel, selectedColorIndex]);

  useEffect(() => {
    if (!isOpen) return;
    inputRef.current?.focus();
  }, [isOpen, mode]);

  useEffect(() => {
    if (!isOpen) return;
    const handlePointerDown = (event: PointerEvent) => {
      const target = event.target as Node | null;
      if (!target || !rootRef.current) return;
      if (rootRef.current.contains(target)) return;
      setOpen(false);
      setMode("typing");
      setCurrentLabel("");
      setValue("");
    };
    document.addEventListener("pointerdown", handlePointerDown);
    return () => document.removeEventListener("pointerdown", handlePointerDown);
  }, [isOpen, setOpen]);

  useEffect(() => {
    if (mode !== "creating") return;
    const timeout = setTimeout(() => {
      addLabel(creatingLabel, creatingColor);
      setCreatingLabel("");
      setCreatingColor("");
      setCurrentLabel("");
      setValue("");
      setMode("typing");
    }, createDelayMs);
    return () => clearTimeout(timeout);
  }, [addLabel, createDelayMs, creatingColor, creatingLabel, mode]);

  const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      e.preventDefault();
      if (mode === "typing") startColorPicking(value);
      else if (mode === "color-picking") submitSelectedColor();
      return;
    }
    if (e.key === "Escape" && mode !== "typing") {
      e.preventDefault();
      setMode("typing");
      setCurrentLabel("");
      setValue("");
      return;
    }
    if (mode === "color-picking" && (e.key === "ArrowDown" || e.key === "ArrowUp")) {
      e.preventDefault();
      setSelectedColorIndex((index) =>
        e.key === "ArrowDown"
          ? Math.min(index + 1, colors.length - 1)
          : Math.max(index - 1, 0)
      );
    }
  };

  const handleColorSelect = (index: number) => {
    setSelectedColorIndex(index);
    const selected = colors[index];
    setCreatingLabel(currentLabel);
    setCreatingColor(selected.value);
    setMode("creating");
  };

  const isMenuOpen = mode === "typing" ? value.trim().length > 0 : mode === "color-picking";
  const showCreateOption = mode === "typing" && value.trim().length > 0;
  const selectedColor = colors[selectedColorIndex];
  const hasContext = labels.length > 0 || mode === "color-picking" || mode === "creating";
  const inputPlaceholder =
    mode === "typing" ? placeholder : mode === "color-picking" ? "Pick color for label" : "Creating label...";

  return (
    <div ref={rootRef} className={cn("relative inline-flex flex-col items-center gap-3", className)}>
      <button
        type="button"
        aria-label={buttonAriaLabel}
        onClick={() => setOpen(!isOpen)}
        className="flex size-9 shrink-0 items-center justify-center rounded-full border border-border bg-background text-foreground/90 shadow-sm transition-colors hover:bg-muted"
      >
        <PlusIcon className="size-4" />
      </button>

      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0, y: -6, scale: 0.98 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: -6, scale: 0.98 }}
            transition={{ duration: 0.2, ease: "easeOut" }}
            className="absolute top-[calc(100%+0.5rem)] left-1/2 z-20 w-sm -translate-x-1/2 overflow-hidden rounded-lg border border-border/90 bg-neutral-100 shadow-[0_14px_28px_rgba(15,23,42,0.08)]"
          >
            <AnimatePresence initial={false}>
              {hasContext && (
                <motion.div
                  initial={{ height: 0, opacity: 0 }}
                  animate={{ height: "auto", opacity: 1 }}
                  exit={{ height: 0, opacity: 0 }}
                  className="overflow-hidden"
                >
                  <div className="px-3 py-1.5">
                    <div className="flex flex-wrap items-center gap-2">
                      <AnimatePresence mode="popLayout">
                        {mode === "color-picking" && (
                          <motion.div
                            key="create-header"
                            initial={{ opacity: 0, y: -6 }}
                            animate={{ opacity: 1, y: 0 }}
                            exit={{ opacity: 0, y: -6 }}
                            transition={{ duration: 0.18 }}
                            className="inline-flex w-full items-center gap-2 text-sm"
                          >
                            <LabelIcon />
                            <TextMorph as="span" duration={240} className="text-muted-foreground">
                              Create
                            </TextMorph>
                            <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: selectedColor.value }} />
                            <TextMorph as="span" duration={260} className="font-medium">
                              {currentLabel}
                            </TextMorph>
                          </motion.div>
                        )}

                        {mode === "creating" && (
                          <motion.div
                            key="creating-chip"
                            layout
                            initial={{ opacity: 0, scale: 0.96 }}
                            animate={{ opacity: 1, scale: 1 }}
                            exit={{ opacity: 0, scale: 0.96 }}
                            className="inline-flex items-center gap-2 text-sm"
                          >
                            <PixelLoader className="mt-[1px]" />
                            <TextMorph as="span" duration={220} className="text-muted-foreground">
                              Creating
                            </TextMorph>
                            <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: creatingColor }} />
                            <TextMorph as="span" duration={240} className="font-medium">
                              {creatingLabel}
                            </TextMorph>
                          </motion.div>
                        )}

                        {mode !== "color-picking" &&
                          labels.map((label, index) => (
                            <motion.span
                              key={`${label.text}-${index}`}
                              layout
                              initial={{ opacity: 0, scale: 0.92 }}
                              animate={{ opacity: 1, scale: 1 }}
                              exit={{ opacity: 0, scale: 0.92 }}
                              className="inline-flex items-center gap-1.5 text-sm"
                            >
                              <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: label.color }} />
                              {label.text}
                            </motion.span>
                          ))}
                      </AnimatePresence>
                    </div>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
            <div className="rounded-t-lg overflow-hidden bg-white outline outline-1 outline-border/80">
              <Input
                ref={inputRef}
                value={value}
                onChange={(e) => setValue(e.target.value)}
                onKeyDown={handleKeyDown}
                readOnly={mode !== "typing"}
                placeholder={inputPlaceholder}
                autoFocus
                className="border-none focus-visible:ring-0 shadow-none"
              />
              <AnimatePresence mode="wait">
                {isMenuOpen && (
                  <motion.div
                    key={mode}
                    initial={{ height: 0, opacity: 0 }}
                    animate={{ height: "auto", opacity: 1 }}
                    exit={{ height: 0, opacity: 0 }}
                    transition={{ duration: 0.2 }}
                    className="overflow-hidden p-1 border-t border-border/80"
                  >
                    {mode === "typing" && showCreateOption && (
                      <button
                        type="button"
                        onClick={() => startColorPicking(value)}
                        className="flex w-full min-w-0 items-center gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-accent"
                      >
                        <PlusIcon className="size-4 flex-shrink-0" />
                        <span className="text-foreground/90 whitespace-nowrap">Create new label:</span>
                        <span className="min-w-0 flex-1 truncate text-muted-foreground">
                          {`"${value.trim()}"`}
                        </span>
                      </button>
                    )}
                    {mode !== "typing" && (
                      <div className={cn("mt-2 space-y-1", mode === "creating" && "pointer-events-none opacity-55")}>
                        {colors.map((color, index) => (
                          <button
                            key={color.name}
                            type="button"
                            onClick={() => handleColorSelect(index)}
                            className={cn(
                              "flex w-full items-center gap-2 rounded-md px-3 py-2 text-left transition-colors",
                              selectedColorIndex === index ? "bg-accent" : "hover:bg-accent/60"
                            )}
                          >
                            <span className="size-3 shrink-0 rounded-full" style={{ backgroundColor: color.value }} />
                            <span className="text-sm">{color.name}</span>
                          </button>
                        ))}
                      </div>
                    )}
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

Update the import paths to match your project setup.

Similar screens