summaryrefslogtreecommitdiffhomepage
path: root/packages/ui/src/components/morph-chevron.tsx
blob: 280aeb7e34ed6839e4bca514d97672bcea6e4f09 (plain)
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
import { createEffect, createUniqueId, on } from "solid-js"

export interface MorphChevronProps {
  expanded: boolean
  class?: string
}

const COLLAPSED = "M4 6L8 10L12 6"
const EXPANDED = "M4 10L8 6L12 10"

export function MorphChevron(props: MorphChevronProps) {
  const id = createUniqueId()
  let path: SVGPathElement | undefined
  let expandAnim: SVGAnimateElement | undefined
  let collapseAnim: SVGAnimateElement | undefined

  createEffect(
    on(
      () => props.expanded,
      (expanded, prev) => {
        if (prev === undefined) {
          // Set initial state without animation
          path?.setAttribute("d", expanded ? EXPANDED : COLLAPSED)
          return
        }
        if (expanded) {
          expandAnim?.beginElement()
        } else {
          collapseAnim?.beginElement()
        }
      },
    ),
  )

  return (
    <svg
      viewBox="0 0 16 16"
      data-slot="morph-chevron-svg"
      class={props.class}
      xmlns="http://www.w3.org/2000/svg"
      aria-hidden="true"
    >
      <path ref={path} d={COLLAPSED} id={`morph-chevron-path-${id}`}>
        <animate
          ref={(el) => {
            expandAnim = el
          }}
          id={`morph-expand-${id}`}
          attributeName="d"
          dur="200ms"
          fill="freeze"
          calcMode="spline"
          keySplines="0.25 0 0.5 1"
          values="M4 6L8 10L12 6;M4 10L8 6L12 10"
          begin="indefinite"
        />
        <animate
          ref={(el) => {
            collapseAnim = el
          }}
          id={`morph-collapse-${id}`}
          attributeName="d"
          dur="200ms"
          fill="freeze"
          calcMode="spline"
          keySplines="0.25 0 0.5 1"
          values="M4 10L8 6L12 10;M4 6L8 10L12 6"
          begin="indefinite"
        />
      </path>
    </svg>
  )
}