focus.mjs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { addDomEvent } from '../events/add-dom-event.mjs';
  2. import { Feature } from '../motion/features/Feature.mjs';
  3. import { pipe } from '../utils/pipe.mjs';
  4. class FocusGesture extends Feature {
  5. constructor() {
  6. super(...arguments);
  7. this.isActive = false;
  8. }
  9. onFocus() {
  10. let isFocusVisible = false;
  11. /**
  12. * If this element doesn't match focus-visible then don't
  13. * apply whileHover. But, if matches throws that focus-visible
  14. * is not a valid selector then in that browser outline styles will be applied
  15. * to the element by default and we want to match that behaviour with whileFocus.
  16. */
  17. try {
  18. isFocusVisible = this.node.current.matches(":focus-visible");
  19. }
  20. catch (e) {
  21. isFocusVisible = true;
  22. }
  23. if (!isFocusVisible || !this.node.animationState)
  24. return;
  25. this.node.animationState.setActive("whileFocus", true);
  26. this.isActive = true;
  27. }
  28. onBlur() {
  29. if (!this.isActive || !this.node.animationState)
  30. return;
  31. this.node.animationState.setActive("whileFocus", false);
  32. this.isActive = false;
  33. }
  34. mount() {
  35. this.unmount = pipe(addDomEvent(this.node.current, "focus", () => this.onFocus()), addDomEvent(this.node.current, "blur", () => this.onBlur()));
  36. }
  37. unmount() { }
  38. }
  39. export { FocusGesture };