chenzhaoyang
2025-12-17 063da0bf961e1d35e25dc107f883f7492f4c5a7c
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
import type React from "react";
import { useState, useRef, useEffect } from "react";
import LinkTo from "@storybook/addon-links/react";
 
import type { Meta } from "@storybook/react";
import { useAtom, useAtomValue, useSetAtom } from "jotai";
import { atomWithStorage } from "jotai/utils";
import { evaluatedThemeAtom } from "../../../storybook/addons/theme-toggle/atoms";
// @ts-ignore: JS module without types
import designTokens from "./tokens";
 
// Define types for design tokens
type DesignTokenValue = string | Record<string, any>;
type FlattenedTokens = Record<string, string>;
 
const pxToRem = (px: number) => `${px / 16}rem`;
 
// Token categories and their descriptions
const categoryDescriptions: Record<string, string> = {
  colors: "Color tokens for UI elements including semantic, and scale colors",
  spacing: "Spacing values for layout, padding, margins, and positioning",
  typography: "Typography tokens for font families, font sizes, font weights, line heights, and letter spacing",
  cornerRadius: "Corner radius values for UI components with rounded edges",
};
 
// Color subcategories and their descriptions
const colorSubcategoryDescriptions: Record<string, string> = {
  primitives: "Base color scales for the design system",
  neutral: "Neutral colors for backgrounds, text, borders, and other UI elements",
  accent: "Accent colors for highlighting and distinguishing UI elements",
  primary: "Primary brand colors for key UI elements and interactions",
  negative: "Negative/danger colors for error states and destructive actions",
  positive: "Positive/success colors for confirmations and success states",
  warning: "Warning colors for cautionary messages and states",
};
 
// Component to render a token value
const TokenValue = ({ token, tokenName }: { token: string; tokenName: string }) => {
  const theme = useAtomValue(evaluatedThemeAtom);
 
  // Determine token type
  const isColor = typeof token === "string" && token.includes("--color-");
  const isSpacing = typeof token === "string" && token.includes("--spacing-");
  const isTypography =
    typeof token === "string" &&
    (token.includes("--font-size-") ||
      token.includes("--line-height-") ||
      token.includes("--letter-spacing-") ||
      token.includes("--font-family-") ||
      token.includes("--font-weight-"));
  const isCornerRadius = typeof token === "string" && token.includes("--corner-radius-");
 
  // Create a ref to access computed values
  const [computedValue, setComputedValue] = useState<string>("");
  const elementRef = useRef<HTMLDivElement>(null);
  const computedValueRef = useRef<string>(computedValue);
  computedValueRef.current = computedValue;
 
  // Get the computed value when the component mounts
  useEffect(() => {
    const handleComputedValue = () => {
      if (elementRef.current && token.includes("var(")) {
        // Extract the CSS variable name from the token string
        const varName = token.match(/var\((.*?)\)/)?.[1] || "";
        if (varName) {
          // Get the computed style for the variable
          const computedStyle = getComputedStyle(document.body).getPropertyValue(varName).trim();
          if (computedStyle !== computedValueRef.current) {
            setComputedValue(computedStyle);
          }
        }
      }
    };
 
    handleComputedValue();
  }, [token, theme]);
 
  const handleCopy = (e: React.MouseEvent<HTMLDivElement>) => {
    // Copy token name to clipboard
    navigator.clipboard.writeText(token);
 
    // Find and show the copy indicator
    const parent = e.currentTarget;
    const copyIndicator = parent.querySelector(".copy-indicator") as HTMLElement;
 
    if (copyIndicator) {
      copyIndicator.style.bottom = "8px";
      copyIndicator.style.opacity = "1";
 
      // Hide after a delay
      setTimeout(() => {
        copyIndicator.style.bottom = "-30px";
        copyIndicator.style.opacity = "0";
      }, 1500);
    }
  };
 
  // Get the token value name and path
  const tokens = tokenName.split(".");
  let tokenValueName = tokens.pop() || tokenName;
  if (tokenValueName === "DEFAULT") {
    tokenValueName = tokens.pop() || tokenName;
  }
 
  return (
    <div
      ref={elementRef}
      className="flex flex-col p-4 border border-neutral-border rounded-lg mb-2 cursor-pointer relative overflow-hidden transition-all duration-200 hover:shadow-md"
      onClick={handleCopy}
      title={`Click to copy: ${tokenName}`}
    >
      {/* Visual preview for different token types */}
      {isColor && (
        <div className="flex flex-col gap-2 mb-3">
          <div
            className="w-full h-16 bg-neutral-surface rounded border border-neutral-border shadow-inner"
            style={{ backgroundColor: token }}
          />
        </div>
      )}
 
      {isSpacing && (
        <div className="mb-3 h-16 flex items-center justify-center px-4">
          <div
            className="h-2 rounded min-w-1 relative"
            style={{
              width: token,
              background: "linear-gradient(90deg, #6366F1 0%, #A855F7 100%)",
            }}
          />
        </div>
      )}
 
      {isTypography && (
        <div className="mb-3 h-16 flex items-center justify-center overflow-hidden">
          {token.includes("--font-size-") && (
            <div
              className="whitespace-nowrap leading-tight"
              style={{
                fontSize: token,
              }}
            >
              Aa
            </div>
          )}
 
          {token.includes("--line-height-") && (
            <div className="relative w-3/5 h-10">
              <div
                className="w-full flex items-center justify-center text-xs text-primary-content relative"
                style={{
                  height: token,
                  backgroundColor: "rgba(99, 102, 241, 0.2)",
                }}
              >
                Line Height
              </div>
            </div>
          )}
 
          {token.includes("--letter-spacing-") && (
            <div
              className="text-sm relative px-4"
              style={{
                letterSpacing: token,
              }}
            >
              LETTER SPACING
            </div>
          )}
 
          {token.includes("--font-family-") && (
            <div
              className="text-sm relative px-4"
              style={{
                fontFamily: token,
              }}
            >
              Font Family
            </div>
          )}
 
          {token.includes("--font-weight-") && (
            <div
              className="text-sm relative px-4"
              style={{
                fontWeight: token,
              }}
            >
              Font Weight
            </div>
          )}
        </div>
      )}
 
      {isCornerRadius && (
        <div className="mb-3 h-16 flex items-center justify-center relative">
          <div
            className="w-3/5 h-10 bg-primary-surface-content-subtle text-primary-surface-content-boldest border border-dashed border-primary-border"
            style={{
              borderRadius: token,
            }}
          />
        </div>
      )}
 
      {/* Token information */}
      <div className="flex justify-between">
        <div className="flex-1 flex flex-col gap-1">
          <div className="flex justify-between items-center">
            <div className="flex flex-col">
              <div className="text-neutral-content text-sm font-bold break-words">{tokenValueName}</div>
              <div className="text-[10px] text-neutral-content-subtlest -mt-1">{tokens.join(".")}</div>
            </div>
 
            <span className="text-xs text-neutral-content text-right">{computedValue || "..."}</span>
          </div>
 
          <div className="text-xs font-bold text-neutral-content-subtler text-center break-all flex-shrink-0 bg-neutral-surface p-0.5 rounded">
            {token.replace("var(", "").replace(")", "")}
          </div>
        </div>
      </div>
 
      {/* Copy indicator */}
      <div className="copy-indicator absolute -bottom-7 right-2 bg-neutral-inverted-surface text-neutral-inverted-content px-2 py-1 rounded text-xs opacity-0 transition-all duration-300 z-10">
        Copied!
      </div>
    </div>
  );
};
 
const searchAtom = atomWithStorage("tokensSearch", "");
const activeCategoryAtom = atomWithStorage("tokensActiveCategory", "all");
const activeColorSubcategoryAtom = atomWithStorage("tokensActiveColorSubcategory", "all");
 
// Component for the token catalog
const TokenCatalog = () => {
  const [searchTerm, setSearchTerm] = useAtom(searchAtom);
  const [activeCategory, setActiveCategory] = useAtom(activeCategoryAtom);
  const [activeColorSubcategory, setActiveColorSubcategory] = useAtom(activeColorSubcategoryAtom);
 
  // Function to flatten nested token objects into a searchable format
  const flattenTokens = (obj: Record<string, DesignTokenValue>, prefix = ""): FlattenedTokens => {
    const result: FlattenedTokens = {};
 
    for (const key in obj) {
      const newPrefix = prefix ? `${prefix}.${key}` : key;
 
      if (typeof obj[key] === "object" && obj[key] !== null) {
        Object.assign(result, flattenTokens(obj[key] as Record<string, DesignTokenValue>, newPrefix));
      } else {
        result[newPrefix] = obj[key] as string;
      }
    }
 
    return result;
  };
 
  // Get all tokens in a flat structure
  const allTokens = flattenTokens(designTokens);
 
  // Filter tokens based on search and category filters
  const filteredTokens = Object.entries(allTokens).filter(([name, value]) => {
    // Filter by search term
    const matchesSearch =
      searchTerm === "" ||
      name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      String(value).toLowerCase().includes(searchTerm.toLowerCase());
 
    // Filter by category
    const matchesCategory = activeCategory === "all" || name.startsWith(activeCategory);
 
    // Filter by color subcategory if in colors category
    const matchesColorSubcategory =
      !name.startsWith("colors") ||
      activeColorSubcategory === "all" ||
      (activeColorSubcategory === "primitives"
        ? !name.startsWith("colors.neutral") &&
          !name.startsWith("colors.primary") &&
          !name.startsWith("colors.negative") &&
          !name.startsWith("colors.positive") &&
          !name.startsWith("colors.warning") &&
          !name.startsWith("colors.accent") &&
          name.startsWith("colors.")
        : name.startsWith(`colors.${activeColorSubcategory}`));
 
    return matchesSearch && matchesCategory && matchesColorSubcategory;
  });
 
  // Group filtered tokens by their top-level category
  const groupedTokens: Record<string, Array<[string, string]>> = filteredTokens.reduce(
    (acc, [name, value]) => {
      const topCategory = name.split(".")[0];
 
      if (!acc[topCategory]) {
        acc[topCategory] = [];
      }
 
      acc[topCategory].push([name, value]);
      return acc;
    },
    {} as Record<string, Array<[string, string]>>,
  );
 
  return (
    <div className="token-catalog p-8">
      <div className="mb-6">
        <input
          type="text"
          placeholder="Search tokens by name or value..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="p-2 rounded border border-neutral-border bg-neutral-background text-neutral-content focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-focus-outline w-full text-sm mb-4"
        />
 
        <div className="flex gap-2 mb-4 flex-wrap">
          <button
            type="button"
            onClick={() => {
              setActiveCategory("all");
              setActiveColorSubcategory("all");
            }}
            className={`py-1.5 px-3 rounded border text-sm cursor-pointer ${
              activeCategory === "all"
                ? "bg-primary-surface border-primary-border text-primary-surface-content"
                : "bg-neutral-surface border-neutral-border"
            }`}
          >
            All Categories
          </button>
          {Object.keys(categoryDescriptions).map((category) => (
            <button
              type="button"
              key={category}
              onClick={() => {
                setActiveCategory(category);
                if (category !== "colors") {
                  setActiveColorSubcategory("all");
                }
              }}
              className={`py-1.5 px-3 rounded border text-sm cursor-pointer ${
                activeCategory === category
                  ? "bg-primary-surface border-primary-border text-primary-surface-content"
                  : "bg-neutral-surface border-neutral-border"
              }`}
            >
              {category}
            </button>
          ))}
        </div>
 
        {activeCategory === "colors" && (
          <div className="flex gap-2 mb-4 flex-wrap">
            <button
              type="button"
              onClick={() => setActiveColorSubcategory("all")}
              className={`py-1.5 px-3 rounded border text-sm cursor-pointer ${
                activeColorSubcategory === "all"
                  ? "bg-primary-surface border-primary-border text-primary-surface-content"
                  : "bg-neutral-surface border-neutral-border"
              }`}
            >
              All Colors
            </button>
            {Object.keys(colorSubcategoryDescriptions).map((subcategory) => (
              <button
                type="button"
                key={subcategory}
                onClick={() => {
                  setActiveColorSubcategory(subcategory);
                }}
                className={`py-1.5 px-3 rounded border text-sm cursor-pointer ${
                  activeColorSubcategory === subcategory
                    ? "bg-primary-surface border-primary-border text-primary-surface-content"
                    : "bg-neutral-surface border-neutral-border"
                }`}
              >
                {subcategory}
              </button>
            ))}
          </div>
        )}
      </div>
 
      {/* Display the tokens */}
      {Object.keys(groupedTokens).length === 0 ? (
        <div className="text-center my-10 text-neutral-content-subtler">No tokens found matching "{searchTerm}"</div>
      ) : (
        Object.entries(groupedTokens).map(([category, tokens]) => (
          <div key={category} className="category-section mb-10">
            <h2 className="text-lg m-0 mb-2 pb-2 border-b border-neutral-border">
              {category} ({tokens.length})
            </h2>
            <p className="text-sm m-0 mb-4 text-neutral-content-subtler">
              {categoryDescriptions[category] || "Design tokens in this category"}
            </p>
 
            <div className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))" }}>
              {tokens.map(([name, value]) => (
                <TokenValue key={name} token={value} tokenName={name} />
              ))}
            </div>
          </div>
        ))
      )}
    </div>
  );
};
 
// Component to display design tokens organized by categories
const TokenCategorized = () => {
  const setSearchTerm = useSetAtom(searchAtom);
  const setActiveCategory = useSetAtom(activeCategoryAtom);
  const setActiveColorSubcategory = useSetAtom(activeColorSubcategoryAtom);
 
  // Helper function to generate a color palette for the colors category
  const generateColorPalette = () => {
    return (
      <div className="flex flex-col gap-4">
        <div className="flex gap-16">
          <div className="flex gap-3 items-center">
            {["primary", "positive", "warning", "negative", "neutral"].map((color) => (
              <div key={color} className="flex flex-col items-center w-13">
                <div
                  className="w-12 h-12 rounded border border-neutral-border"
                  style={{ backgroundColor: `var(--color-${color}-surface)` }}
                  title={`${color}`}
                />
                <div className="text-xs">{color}</div>
              </div>
            ))}
          </div>
          <div className="flex gap-3 items-center">
            {["grape", "blueberry", "kale", "kiwi", "mango", "persimmon"].map((color) => (
              <div key={color} className="flex flex-col items-center w-13">
                <div
                  className="w-12 h-12 rounded border border-neutral-border"
                  style={{ backgroundColor: `var(--color-${color}-500)` }}
                  title={`${color}`}
                />
                <div className="text-xs">{color}</div>
              </div>
            ))}
          </div>
        </div>
        <div className="flex flex-wrap gap-4">
          {Object.entries(colorSubcategoryDescriptions).map(([subCategory, subDescription]) => (
            <LinkTo
              key={subCategory}
              kind="design-tokens"
              story="tokens-catalog"
              className="flex-1 basis-[300px] border border-neutral-border rounded-lg p-4 cursor-pointer relative overflow-hidden hover:shadow-md transition-all duration-200"
              onClick={() => {
                setSearchTerm("");
                setActiveCategory("colors");
                setActiveColorSubcategory(subCategory);
              }}
            >
              {/* Color preview for each subcategory */}
              {!["primitives", "neutral", "accent"].includes(subCategory) && (
                <div
                  className="absolute top-0 right-0 w-15 h-15 opacity-30 rounded-bl-full border-l border-b border-neutral-border"
                  style={{ backgroundColor: `var(--color-${subCategory}-surface)` }}
                />
              )}
 
              {["primitives", "neutral", "accent"].includes(subCategory) && (
                <div className="absolute top-0 right-0 w-15 h-15 opacity-30 overflow-hidden border-l border-b border-neutral-border">
                  <div className="flex">
                    <div
                      className="w-5 h-5"
                      style={{
                        backgroundColor: `var(--color-${
                          subCategory === "primitives"
                            ? "grape-500"
                            : subCategory === "neutral"
                              ? "neutral-surface"
                              : "accent-grape-bold"
                        })`,
                      }}
                    />
                    <div
                      className="w-5 h-5"
                      style={{
                        backgroundColor: `var(--color-${
                          subCategory === "primitives"
                            ? "blueberry-500"
                            : subCategory === "neutral"
                              ? "neutral-surface-hover"
                              : "accent-blueberry-bold"
                        })`,
                      }}
                    />
                    <div
                      className="w-5 h-5"
                      style={{
                        backgroundColor: `var(--color-${
                          subCategory === "primitives"
                            ? "kale-500"
                            : subCategory === "neutral"
                              ? "neutral-surface-active"
                              : "accent-kale-bold"
                        })`,
                      }}
                    />
                  </div>
                  <div className="flex">
                    <div
                      className="w-5 h-5"
                      style={{
                        backgroundColor: `var(--color-${
                          subCategory === "primitives"
                            ? "kiwi-500"
                            : subCategory === "neutral"
                              ? "neutral-border"
                              : "accent-kiwi-bold"
                        })`,
                      }}
                    />
                    <div
                      className="w-5 h-5"
                      style={{
                        backgroundColor: `var(--color-${
                          subCategory === "primitives"
                            ? "mango-500"
                            : subCategory === "neutral"
                              ? "neutral-border-subtle"
                              : "accent-mango-bold"
                        })`,
                      }}
                    />
                    <div
                      className="w-5 h-5"
                      style={{
                        backgroundColor: `var(--color-${
                          subCategory === "primitives"
                            ? "persimmon-500"
                            : subCategory === "neutral"
                              ? "neutral-border-subtler"
                              : "accent-persimmon-bold"
                        })`,
                      }}
                    />
                  </div>
                  <div className="flex">
                    <div
                      className="w-5 h-5"
                      style={{
                        backgroundColor: `var(--color-${
                          subCategory === "primitives"
                            ? "plum-500"
                            : subCategory === "neutral"
                              ? "neutral-content"
                              : "accent-plum-bold"
                        })`,
                      }}
                    />
                    <div
                      className="w-5 h-5"
                      style={{
                        backgroundColor: `var(--color-${
                          subCategory === "primitives"
                            ? "fig-500"
                            : subCategory === "neutral"
                              ? "neutral-content-subtle"
                              : "accent-fig-bold"
                        })`,
                      }}
                    />
                    <div
                      className="w-5 h-5"
                      style={{
                        backgroundColor: `var(--color-${
                          subCategory === "primitives"
                            ? "sand-500"
                            : subCategory === "neutral"
                              ? "neutral-content-subtler"
                              : "accent-sand-bold"
                        })`,
                      }}
                    />
                  </div>
                </div>
              )}
 
              <h3 className="text-base mb-2">{subCategory}</h3>
              <p className="text-sm text-neutral-content-subtler relative z-10">{subDescription}</p>
            </LinkTo>
          ))}
        </div>
      </div>
    );
  };
 
  const RawColorsPalette = () => {
    return (
      <div className="flex flex-col gap-4">
        <div className="flex flex-col gap-1">
          <h3 className="text-base">Raw Color Values</h3>
          <p className="text-sm text-neutral-content-subtler">
            These color tokens have raw RGB values available for creating translucent colors with custom opacity. The
            same code will automatically adapt to dark mode.
          </p>
        </div>
        <div className="flex flex-col gap-6">
          {/* Primitive color demonstration */}
          <div className="mt-2">
            <h4 className="text-sm font-semibold mb-2">Primary Color with Different Opacities</h4>
            <div className="flex gap-4">
              {[10, 25, 50, 75, 100].map((opacity) => (
                <div key={opacity} className="flex flex-col items-center">
                  <div
                    className="w-12 h-12 rounded bg-neutral-surface border border-neutral-border mb-1"
                    style={{ backgroundColor: `rgb(var(--color-primary-surface-raw) / ${opacity}%)` }}
                  />
                  <span className="text-xs">{opacity}%</span>
                </div>
              ))}
            </div>
            <div className="mt-3 bg-neutral-surface p-2 rounded text-xs font-mono">
              background-color: rgb(var(--color-primary-surface-raw) / 50%);
            </div>
          </div>
 
          {/* Shadow/outline example */}
          <div>
            <h4 className="text-sm font-semibold mb-2">Shadow Example</h4>
            <div className="flex gap-4">
              <div className="flex flex-col items-center">
                <div
                  className="w-16 h-16 rounded bg-neutral-surface flex items-center justify-center"
                  style={{
                    boxShadow: "0 4px 8px rgb(var(--color-neutral-shadow-raw) / 15%)",
                  }}
                >
                  <span className="text-xs text-center">Neutral Shadow</span>
                </div>
              </div>
            </div>
            <div className="mt-3 bg-neutral-surface p-2 rounded text-xs font-mono">
              box-shadow: 0 4px 8px rgb(var(--color-neutral-shadow-raw) / 15%);
            </div>
          </div>
        </div>
      </div>
    );
  };
 
  // Helper function to generate a spacing visualization
  const generateSpacingPreview = () => {
    return (
      <div className="flex flex-col gap-2 mt-4 items-start">
        {["100", "200", "400", "800"].map((size) => (
          <div key={size} className="flex flex-col">
            <div
              className="h-5 bg-primary-surface text-primary-content rounded relative"
              style={{ width: `var(--spacing-${size})` }}
              title={`spacing-${size}`}
            />
            <div className="text-xs">{size}</div>
          </div>
        ))}
      </div>
    );
  };
 
  // Helper function to generate a typography preview
  const generateTypographyPreview = () => {
    return (
      <div className="flex flex-col gap-2 mt-4">
        <div style={{ fontSize: "var(--font-size-12)", lineHeight: "var(--line-height-16)" }}>
          Font Size 12: {pxToRem(12)}
        </div>
        <div style={{ fontSize: "var(--font-size-14)", lineHeight: "var(--line-height-20)" }}>
          Font Size 14: {pxToRem(14)}
        </div>
        <div style={{ fontSize: "var(--font-size-16)", lineHeight: "var(--line-height-24)" }}>
          Font Size 16: {pxToRem(16)}
        </div>
      </div>
    );
  };
 
  // Helper function to generate a corner radius preview
  const generateCornerRadiusPreview = () => {
    return (
      <div className="flex gap-4 mt-4">
        {["small", "medium", "large"].map((size) => (
          <div
            key={size}
            className="w-15 h-10 bg-primary-surface-content-subtle text-primary-surface-content-boldest border border-dashed border-primary-border flex items-center justify-center text-xs"
            style={{ borderRadius: `var(--corner-radius-${size})` }}
            title={`corner-radius-${size}`}
          >
            {size}
          </div>
        ))}
      </div>
    );
  };
 
  // Get the appropriate preview for each category
  const getCategoryPreview = (category: string) => {
    switch (category) {
      case "colors":
        return generateColorPalette();
      case "spacing":
        return generateSpacingPreview();
      case "typography":
        return generateTypographyPreview();
      case "cornerRadius":
        return generateCornerRadiusPreview();
      default:
        return null;
    }
  };
 
  return (
    <div className="p-8">
      <h1 className="text-2xl mb-6">Design Tokens</h1>
      <p className="mb-6">
        Browse through our design tokens organized by category. These tokens are the foundation of our design system.
      </p>
 
      <div className="flex flex-col gap-12">
        {Object.entries(categoryDescriptions).map(([category, description]) => (
          <div key={category} className="flex flex-col gap-4">
            <div className="flex flex-col gap-2">
              <h2 className="text-xl">{category.replace(/-/g, " ").replace(/\b\w/g, (char) => char.toUpperCase())}</h2>
              <p className="text-neutral-content-subtler">{description}</p>
            </div>
 
            {/* Preview for each category */}
            {getCategoryPreview(category)}
 
            {/* Add raw colors palette for the colors category */}
            {category === "colors" && (
              <div className="mt-4">
                <RawColorsPalette />
              </div>
            )}
 
            {category !== "colors" && (
              <LinkTo
                kind="design-tokens"
                story="tokens-catalog"
                className="block border border-neutral-border rounded-lg p-4 cursor-pointer mt-6 hover:shadow-md transition-all duration-200"
                onClick={() => {
                  setSearchTerm("");
                  setActiveCategory(category);
                }}
              >
                <p className="text-sm">View all {category} tokens &rarr;</p>
              </LinkTo>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};
 
const meta: Meta = {
  title: "Design/Tokens",
  tags: ["!autodocs"],
  parameters: {
    layout: "fullscreen",
    docs: {
      description: {
        component: "A catalog of all available design tokens in the system. Click on any token to copy its path.",
      },
    },
  },
};
 
export default meta;
 
export const TokensIndex = {
  render: () => <TokenCategorized />,
  name: "Index",
  parameters: {
    docs: {
      description: {
        story: "Design tokens organized by their categories for easier navigation.",
      },
    },
  },
};
 
export const TokensCatalog = {
  render: () => <TokenCatalog />,
  name: "Catalog",
  parameters: {
    docs: {
      description: {
        story: "All design tokens displayed in a searchable and filterable grid.",
      },
    },
  },
};