tooltip.tsx 2.2 KB

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