Fix misaligned tooltip positions in modal dialogs

This commit fixes a bug that causes tooltips to be slightly misaligned.

Tooltip positioning was incorrect during modal transitions due to their
initial movement, causing tooltips to align incorrectly at the start of
the animation rather than the end.

One way to solve this would be using `autoUpdate` from `floating-ui`
with `animationFrame: true`. However, this recalculates positions tens
of times per second, impacting performance. This is a monkey solution.

This commit adopts a more efficient approach by updating tooltip
positions only at the end of the transitions, which reduces calculations
and conserves resources.

Key changes:

- Addd transition end event listener for updating tooltip positions.
- Use throttling to eliminate excessive position recalculations.

Other supporting changes:

- Improve throttle function to support efficient recalculations of
  positions:
  - Add ability to optionally exclude the first execution (leading
    call).
  - Refactor to simplify it make it easier to follow and read.
  - Fix a bug where initial calls were incorrectly throttled if
    `dateNow()` returned `0`.
- Introduce and use a global hook for efficient DOM event management.
  This greatily introduce safety, reuse and testability of event
  listening.
This commit is contained in:
undergroundwires
2024-05-08 15:24:12 +02:00
parent a3343205b1
commit dd71536316
26 changed files with 1165 additions and 335 deletions

View File

@@ -40,7 +40,7 @@
<script lang="ts">
import {
defineComponent, ref, onMounted, onUnmounted, computed,
defineComponent, ref, computed,
} from 'vue';
import { injectKey } from '@/presentation/injectionSymbols';
import SizeObserver from '@/presentation/components/Shared/SizeObserver.vue';
@@ -54,6 +54,7 @@ export default defineComponent({
},
setup() {
const { currentState, onStateChange } = injectKey((keys) => keys.useCollectionState);
const { startListening } = injectKey((keys) => keys.useAutoUnsubscribedEventListener);
const width = ref<number | undefined>();
@@ -70,7 +71,7 @@ export default defineComponent({
collapseAllCards();
}, { immediate: true });
const outsideClickListener = (event: PointerEvent): void => {
startListening(document, 'click', (event) => {
if (areAllCardsCollapsed()) {
return;
}
@@ -79,14 +80,6 @@ export default defineComponent({
if (element && !element.contains(target)) {
onOutsideOfActiveCardClicked(target);
}
};
onMounted(() => {
document.addEventListener('click', outsideClickListener);
});
onUnmounted(() => {
document.removeEventListener('click', outsideClickListener);
});
function onOutsideOfActiveCardClicked(clickedElement: Element): void {

View File

@@ -1,6 +1,11 @@
import { ref, onMounted, onUnmounted } from 'vue';
import { ref } from 'vue';
import { useAutoUnsubscribedEventListener, type UseEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
export function useKeyboardInteractionState(window: WindowWithEventListeners = globalThis.window) {
export function useKeyboardInteractionState(
eventTarget: EventTarget = DefaultEventSource,
useEventListener: UseEventListener = useAutoUnsubscribedEventListener,
) {
const { startListening } = useEventListener();
const isKeyboardBeingUsed = ref(false);
const enableKeyboardFocus = () => {
@@ -17,20 +22,10 @@ export function useKeyboardInteractionState(window: WindowWithEventListeners = g
isKeyboardBeingUsed.value = false;
};
onMounted(() => {
window.addEventListener('keydown', enableKeyboardFocus, true);
window.addEventListener('click', disableKeyboardFocus, true);
});
onUnmounted(() => {
window.removeEventListener('keydown', enableKeyboardFocus);
window.removeEventListener('click', disableKeyboardFocus);
});
startListening(eventTarget, 'keydown', enableKeyboardFocus);
startListening(eventTarget, 'click', disableKeyboardFocus);
return { isKeyboardBeingUsed };
}
export interface WindowWithEventListeners {
addEventListener: typeof global.window.addEventListener;
removeEventListener: typeof global.window.removeEventListener;
}
export const DefaultEventSource = document;

View File

@@ -1,4 +1,5 @@
import { onMounted, onUnmounted, type Ref } from 'vue';
import { type Ref } from 'vue';
import { useAutoUnsubscribedEventListener, type UseEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
import { TreeNodeCheckState } from './Node/State/CheckState';
import type { TreeNode } from './Node/TreeNode';
import type { TreeRoot } from './TreeRoot/TreeRoot';
@@ -10,8 +11,10 @@ type TreeNavigationKeyCodes = 'ArrowLeft' | 'ArrowUp' | 'ArrowRight' | 'ArrowDow
export function useTreeKeyboardNavigation(
treeRootRef: Readonly<Ref<TreeRoot>>,
treeElementRef: Readonly<Ref<HTMLElement | undefined>>,
useEventListener: UseEventListener = useAutoUnsubscribedEventListener,
) {
useKeyboardListener(treeElementRef, (event) => {
const { startListening } = useEventListener();
startListening(treeElementRef, 'keydown', (event) => {
if (!treeElementRef.value) {
return; // Not yet initialized?
}
@@ -40,19 +43,6 @@ export function useTreeKeyboardNavigation(
});
}
function useKeyboardListener(
elementRef: Readonly<Ref<HTMLElement | undefined>>,
handleKeyboardEvent: (event: KeyboardEvent) => void,
) {
onMounted(() => {
elementRef.value?.addEventListener('keydown', handleKeyboardEvent, true);
});
onUnmounted(() => {
elementRef.value?.removeEventListener('keydown', handleKeyboardEvent);
});
}
interface TreeNavigationContext {
readonly focus: SingleNodeFocusManager;
readonly nodes: QueryableNodes;

View File

@@ -0,0 +1,79 @@
import {
onBeforeUnmount,
shallowRef,
watch,
type Ref,
} from 'vue';
export interface UseEventListener {
(): TargetEventListener;
}
export const useAutoUnsubscribedEventListener: UseEventListener = () => ({
startListening: (eventTargetSource, eventType, eventHandler) => {
const eventTargetRef = isEventTarget(eventTargetSource)
? shallowRef(eventTargetSource)
: eventTargetSource;
return startListeningRef(
eventTargetRef,
eventType,
eventHandler,
);
},
});
type EventTargetRef = Readonly<Ref<EventTarget | undefined>>;
type EventTargetOrRef = EventTargetRef | EventTarget;
function isEventTarget(obj: EventTargetOrRef): obj is EventTarget {
return obj instanceof EventTarget;
}
export interface TargetEventListener {
startListening<TEvent extends keyof HTMLElementEventMap>(
eventTargetSource: EventTargetOrRef,
eventType: TEvent,
eventHandler: (event: HTMLElementEventMap[TEvent]) => void,
): void;
}
function startListeningRef<TEvent extends keyof HTMLElementEventMap>(
eventTargetRef: Readonly<Ref<EventTarget | undefined>>,
eventType: TEvent,
eventHandler: (event: HTMLElementEventMap[TEvent]) => void,
): void {
const eventListenerManager = new EventListenerManager();
watch(() => eventTargetRef.value, (element) => {
eventListenerManager.removeListenerIfExists();
if (!element) {
return;
}
eventListenerManager.addListener(element, eventType, eventHandler);
}, { immediate: true });
onBeforeUnmount(() => {
eventListenerManager.removeListenerIfExists();
});
}
class EventListenerManager {
private removeListener: (() => void) | null = null;
public removeListenerIfExists() {
if (this.removeListener === null) {
return;
}
this.removeListener();
this.removeListener = null;
}
public addListener<TEvent extends keyof HTMLElementEventMap>(
eventTarget: EventTarget,
eventType: TEvent,
eventHandler: (event: HTMLElementEventMap[TEvent]) => void,
) {
eventTarget.addEventListener(eventType, eventHandler);
this.removeListener = () => eventTarget.removeEventListener(eventType, eventHandler);
}
}

View File

@@ -1,17 +1,14 @@
import { onBeforeMount, onBeforeUnmount } from 'vue';
import { useAutoUnsubscribedEventListener, type UseEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
export function useEscapeKeyListener(callback: () => void) {
const onKeyUp = (event: KeyboardEvent) => {
export function useEscapeKeyListener(
callback: () => void,
eventTarget: EventTarget = document,
useEventListener: UseEventListener = useAutoUnsubscribedEventListener,
): void {
const { startListening } = useEventListener();
startListening(eventTarget, 'keyup', (event) => {
if (event.key === 'Escape') {
callback();
}
};
onBeforeMount(() => {
window.addEventListener('keyup', onKeyUp);
});
onBeforeUnmount(() => {
window.removeEventListener('keyup', onKeyUp);
});
}

View File

@@ -19,7 +19,8 @@
<script lang="ts">
import {
defineComponent, ref, watchEffect, nextTick,
defineComponent, ref, watchEffect,
nextTick, inject,
} from 'vue';
import ModalOverlay from './ModalOverlay.vue';
import ModalContent from './ModalContent.vue';
@@ -28,6 +29,8 @@ import { useCurrentFocusToggle } from './Hooks/UseCurrentFocusToggle';
import { useEscapeKeyListener } from './Hooks/UseEscapeKeyListener';
import { useAllTrueWatcher } from './Hooks/UseAllTrueWatcher';
export const INJECTION_KEY_ESCAPE_LISTENER = Symbol('useEscapeKeyListener');
export default defineComponent({
components: {
ModalOverlay,
@@ -49,6 +52,11 @@ export default defineComponent({
/* eslint-enable @typescript-eslint/no-unused-vars */
},
setup(props, { emit }) {
const listenEscapeKey: typeof useEscapeKeyListener = inject(
INJECTION_KEY_ESCAPE_LISTENER,
useEscapeKeyListener,
);
const isRendered = ref(false);
const isOpen = ref(false);
const overlayTransitionedOut = ref(false);
@@ -56,7 +64,7 @@ export default defineComponent({
useLockBodyBackgroundScroll(isOpen);
useCurrentFocusToggle(isOpen);
useEscapeKeyListener(() => handleEscapeKeyUp());
listenEscapeKey(() => handleEscapeKeyUp());
const {
onAllConditionsMet: onModalFullyTransitionedOut,

View File

@@ -35,6 +35,9 @@ import {
} from '@floating-ui/vue';
import { defineComponent, shallowRef, computed } from 'vue';
import { useResizeObserverPolyfill } from '@/presentation/components/Shared/Hooks/UseResizeObserverPolyfill';
import { throttle } from '@/application/Common/Timing/Throttle';
import { type TargetEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
import { injectKey } from '@/presentation/injectionSymbols';
import type { CSSProperties } from 'vue';
const GAP_BETWEEN_TOOLTIP_AND_TRIGGER_IN_PX = 2;
@@ -48,9 +51,12 @@ export default defineComponent({
const triggeringElement = shallowRef<HTMLElement | undefined>();
const arrowElement = shallowRef<HTMLElement | undefined>();
const eventListener = injectKey((keys) => keys.useAutoUnsubscribedEventListener);
useResizeObserverPolyfill();
const { floatingStyles, middlewareData, placement } = useFloating(
const {
floatingStyles, middlewareData, placement, update,
} = useFloating(
triggeringElement,
tooltipDisplayElement,
{
@@ -68,6 +74,17 @@ export default defineComponent({
},
);
/*
Not using `float-ui`'s `autoUpdate` with `animationFrame: true` because it updates tooltips on
every frame through `requestAnimationFrame`. This behavior is analogous to a continuous loop
(often 60 updates per second and more depending on the refresh rate), which can be excessively
performance-intensive. It's overkill for the application needs and a monkey solution due to
its brute-force nature.
*/
setupTransitionEndEvents(throttle(() => {
update();
}, 400, { excludeLeadingCall: true }), eventListener);
const arrowStyles = computed<CSSProperties>(() => {
if (!middlewareData.value.arrow) {
return {
@@ -126,6 +143,19 @@ function getCounterpartBoxOffsetProperty(placement: Placement): keyof CSSPropert
const currentSide = placement.split('-')[0] as Side;
return sideCounterparts[currentSide];
}
function setupTransitionEndEvents(
handler: () => void,
listener: TargetEventListener,
) {
const transitionEndEvents: readonly (keyof HTMLElementEventMap)[] = [
'transitionend',
'transitioncancel',
];
transitionEndEvents.forEach((eventName) => {
listener.startListening(document.body, eventName, handler);
});
}
</script>
<style scoped lang="scss">