tooltip.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { Tooltip as KobalteTooltip } from "@kobalte/core/tooltip"
  2. import { children, createSignal, Match, onMount, splitProps, Switch, type JSX } from "solid-js"
  3. import type { ComponentProps } from "solid-js"
  4. export interface TooltipProps extends ComponentProps<typeof KobalteTooltip> {
  5. value: JSX.Element
  6. class?: string
  7. contentClass?: string
  8. contentStyle?: JSX.CSSProperties
  9. inactive?: boolean
  10. }
  11. export interface TooltipKeybindProps extends Omit<TooltipProps, "value"> {
  12. title: string
  13. keybind: string
  14. }
  15. export function TooltipKeybind(props: TooltipKeybindProps) {
  16. const [local, others] = splitProps(props, ["title", "keybind"])
  17. return (
  18. <Tooltip
  19. {...others}
  20. value={
  21. <div data-slot="tooltip-keybind">
  22. <span>{local.title}</span>
  23. <span data-slot="tooltip-keybind-key">{local.keybind}</span>
  24. </div>
  25. }
  26. />
  27. )
  28. }
  29. export function Tooltip(props: TooltipProps) {
  30. const [open, setOpen] = createSignal(false)
  31. const [local, others] = splitProps(props, ["children", "class", "contentClass", "contentStyle", "inactive"])
  32. const c = children(() => local.children)
  33. onMount(() => {
  34. const childElements = c()
  35. if (childElements instanceof HTMLElement) {
  36. childElements.addEventListener("focus", () => setOpen(true))
  37. childElements.addEventListener("blur", () => setOpen(false))
  38. } else if (Array.isArray(childElements)) {
  39. for (const child of childElements) {
  40. if (child instanceof HTMLElement) {
  41. child.addEventListener("focus", () => setOpen(true))
  42. child.addEventListener("blur", () => setOpen(false))
  43. }
  44. }
  45. }
  46. })
  47. return (
  48. <Switch>
  49. <Match when={local.inactive}>{local.children}</Match>
  50. <Match when={true}>
  51. <KobalteTooltip forceMount gutter={4} {...others} open={open()} onOpenChange={setOpen}>
  52. <KobalteTooltip.Trigger as={"div"} data-component="tooltip-trigger" class={local.class}>
  53. {c()}
  54. </KobalteTooltip.Trigger>
  55. <KobalteTooltip.Portal>
  56. <KobalteTooltip.Content
  57. data-component="tooltip"
  58. data-placement={props.placement}
  59. class={local.contentClass}
  60. style={local.contentStyle}
  61. >
  62. {others.value}
  63. {/* <KobalteTooltip.Arrow data-slot="tooltip-arrow" /> */}
  64. </KobalteTooltip.Content>
  65. </KobalteTooltip.Portal>
  66. </KobalteTooltip>
  67. </Match>
  68. </Switch>
  69. )
  70. }