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

@@ -1,44 +1,156 @@
/* eslint-disable max-classes-per-file */
import { PlatformTimer } from './PlatformTimer';
import type { Timer, TimeoutType } from './Timer';
export type CallbackType = (..._: readonly unknown[]) => void;
export interface ThrottleOptions {
/** Skip the immediate execution of the callback on the first invoke */
readonly excludeLeadingCall: boolean;
readonly timer: Timer;
}
const DefaultOptions: ThrottleOptions = {
excludeLeadingCall: false,
timer: PlatformTimer,
};
export function throttle(
callback: CallbackType,
waitInMs: number,
timer: Timer = PlatformTimer,
options: Partial<ThrottleOptions> = DefaultOptions,
): CallbackType {
const throttler = new Throttler(timer, waitInMs, callback);
const defaultedOptions: ThrottleOptions = {
...DefaultOptions,
...options,
};
const throttler = new Throttler(waitInMs, callback, defaultedOptions);
return (...args: unknown[]) => throttler.invoke(...args);
}
class Throttler {
private queuedExecutionId: TimeoutType | undefined;
private lastExecutionTime: number | null = null;
private previouslyRun: number;
private executionScheduler: DelayedCallbackScheduler;
constructor(
private readonly timer: Timer,
private readonly waitInMs: number,
private readonly callback: CallbackType,
private readonly options: ThrottleOptions,
) {
if (!waitInMs) { throw new Error('missing delay'); }
if (waitInMs < 0) { throw new Error('negative delay'); }
this.executionScheduler = new DelayedCallbackScheduler(options.timer);
}
public invoke(...args: unknown[]): void {
const now = this.timer.dateNow();
if (this.queuedExecutionId !== undefined) {
this.timer.clearTimeout(this.queuedExecutionId);
this.queuedExecutionId = undefined;
}
if (!this.previouslyRun || (now - this.previouslyRun >= this.waitInMs)) {
this.callback(...args);
this.previouslyRun = now;
} else {
const nextCall = () => this.invoke(...args);
const nextCallDelayInMs = this.waitInMs - (now - this.previouslyRun);
this.queuedExecutionId = this.timer.setTimeout(nextCall, nextCallDelayInMs);
switch (true) {
case this.isLeadingCallWithinThrottlePeriod(): {
if (this.options.excludeLeadingCall) {
this.scheduleNext(args);
return;
}
this.executeNow(args);
return;
}
case this.isAlreadyScheduled(): {
this.updateNextScheduled(args);
return;
}
case !this.isThrottlePeriodPassed(): {
this.scheduleNext(args);
return;
}
default:
throw new Error('Throttle logical error: no conditions for execution or scheduling were met.');
}
}
private isLeadingCallWithinThrottlePeriod(): boolean {
return this.isThrottlePeriodPassed()
&& !this.isAlreadyScheduled();
}
private isThrottlePeriodPassed(): boolean {
if (this.lastExecutionTime === null) {
return true;
}
const timeSinceLastExecution = this.options.timer.dateNow() - this.lastExecutionTime;
const isThrottleTimePassed = timeSinceLastExecution >= this.waitInMs;
return isThrottleTimePassed;
}
private isAlreadyScheduled(): boolean {
return this.executionScheduler.getNext() !== null;
}
private scheduleNext(args: unknown[]): void {
if (this.executionScheduler.getNext()) {
throw new Error('An execution is already scheduled.');
}
this.executionScheduler.resetNext(
() => this.executeNow(args),
this.waitInMs,
);
}
private updateNextScheduled(args: unknown[]): void {
const nextScheduled = this.executionScheduler.getNext();
if (!nextScheduled) {
throw new Error('A non-existent scheduled execution cannot be updated.');
}
const nextDelay = nextScheduled.scheduledTime - this.dateNow();
this.executionScheduler.resetNext(
() => this.executeNow(args),
nextDelay,
);
}
private executeNow(args: unknown[]): void {
this.callback(...args);
this.lastExecutionTime = this.dateNow();
}
private dateNow(): number {
return this.options.timer.dateNow();
}
}
interface ScheduledCallback {
readonly scheduleTimeoutId: TimeoutType;
readonly scheduledTime: number;
}
class DelayedCallbackScheduler {
private scheduledCallback: ScheduledCallback | null = null;
constructor(
private readonly timer: Timer,
) { }
public getNext(): ScheduledCallback | null {
return this.scheduledCallback;
}
public resetNext(
callback: () => void,
delayInMs: number,
) {
this.clear();
this.scheduledCallback = {
scheduledTime: this.timer.dateNow() + delayInMs,
scheduleTimeoutId: this.timer.setTimeout(() => {
this.clear();
callback();
}, delayInMs),
};
}
private clear() {
if (this.scheduledCallback === null) {
return;
}
this.timer.clearTimeout(this.scheduledCallback.scheduleTimeoutId);
this.scheduledCallback = null;
}
}

View File

@@ -16,6 +16,7 @@ import { useCodeRunner } from '@/presentation/components/Shared/Hooks/UseCodeRun
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
import { useDialog } from '@/presentation/components/Shared/Hooks/Dialog/UseDialog';
import { useScriptDiagnosticsCollector } from '@/presentation/components/Shared/Hooks/UseScriptDiagnosticsCollector';
import { useAutoUnsubscribedEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
export function provideDependencies(
context: IApplicationContext,
@@ -77,6 +78,10 @@ export function provideDependencies(
InjectionKeys.useScriptDiagnosticsCollector,
useScriptDiagnosticsCollector,
),
useAutoUnsubscribedEventListener: (di) => di.provide(
InjectionKeys.useAutoUnsubscribedEventListener,
useAutoUnsubscribedEventListener,
),
};
registerAll(Object.values(resolvers), api);
}

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">

View File

@@ -7,9 +7,10 @@ import type { useCurrentCode } from '@/presentation/components/Shared/Hooks/UseC
import type { useAutoUnsubscribedEvents } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEvents';
import type { useUserSelectionState } from '@/presentation/components/Shared/Hooks/UseUserSelectionState';
import type { useLogger } from '@/presentation/components/Shared/Hooks/Log/UseLogger';
import type { useCodeRunner } from './components/Shared/Hooks/UseCodeRunner';
import type { useDialog } from './components/Shared/Hooks/Dialog/UseDialog';
import type { useScriptDiagnosticsCollector } from './components/Shared/Hooks/UseScriptDiagnosticsCollector';
import type { useCodeRunner } from '@/presentation/components/Shared/Hooks/UseCodeRunner';
import type { useDialog } from '@/presentation/components/Shared/Hooks/Dialog/UseDialog';
import type { useScriptDiagnosticsCollector } from '@/presentation/components/Shared/Hooks/UseScriptDiagnosticsCollector';
import type { useAutoUnsubscribedEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
export const InjectionKeys = {
useCollectionState: defineTransientKey<ReturnType<typeof useCollectionState>>('useCollectionState'),
@@ -23,6 +24,7 @@ export const InjectionKeys = {
useCodeRunner: defineTransientKey<ReturnType<typeof useCodeRunner>>('useCodeRunner'),
useDialog: defineTransientKey<ReturnType<typeof useDialog>>('useDialog'),
useScriptDiagnosticsCollector: defineTransientKey<ReturnType<typeof useScriptDiagnosticsCollector>>('useScriptDiagnostics'),
useAutoUnsubscribedEventListener: defineTransientKey<ReturnType<typeof useAutoUnsubscribedEventListener>>('useAutoUnsubscribedEventListener'),
};
export interface InjectionKeyWithLifetime<T> {

View File

@@ -1,7 +1,7 @@
import { describe, it, afterEach } from 'vitest';
import { OperatingSystem } from '@/domain/OperatingSystem';
import { MobileSafariActivePseudoClassEnabler } from '@/presentation/bootstrapping/Modules/MobileSafariActivePseudoClassEnabler';
import { type EventName, createWindowEventSpies } from '@tests/shared/Spies/WindowEventSpies';
import { createEventSpies } from '@tests/shared/Spies/EventTargetSpy';
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
import { isTouchEnabledDevice } from '@/infrastructure/RuntimeEnvironment/Browser/TouchSupportDetection';
import { BrowserRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserRuntimeEnvironment';
@@ -14,9 +14,9 @@ describe('MobileSafariActivePseudoClassEnabler', () => {
}) => {
it(description, () => {
// arrange
const expectedEvent: EventName = 'touchstart';
const expectedEvent: keyof WindowEventMap = 'touchstart';
patchUserAgent(userAgent, afterEach);
const { isAddEventCalled, currentListeners } = createWindowEventSpies(afterEach);
const { isAddEventCalled, formatListeners } = createEventSpies(window, afterEach);
const patchedEnvironment = new TouchSupportControlledBrowserEnvironment(supportsTouch);
const sut = new MobileSafariActivePseudoClassEnabler(patchedEnvironment);
// act
@@ -30,7 +30,7 @@ describe('MobileSafariActivePseudoClassEnabler', () => {
`Touch supported\t\t: ${supportsTouch}`,
`Current OS\t\t: ${patchedEnvironment.os === undefined ? 'unknown' : OperatingSystem[patchedEnvironment.os]}`,
`Is desktop?\t\t: ${patchedEnvironment.isRunningAsDesktopApplication ? 'Yes (Desktop app)' : 'No (Browser)'}`,
`Listeners (${currentListeners.length})\t\t: ${JSON.stringify(currentListeners)}`,
`Listeners\t\t: ${formatListeners()}`,
]));
});
});

View File

@@ -0,0 +1,74 @@
import {
describe, it, expect,
} from 'vitest';
import { defineComponent } from 'vue';
import { mount } from '@vue/test-utils';
import { createEventSpies } from '@tests/shared/Spies/EventTargetSpy';
import { useEscapeKeyListener } from '@/presentation/components/Shared/Modal/Hooks/UseEscapeKeyListener';
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
const EventSource: EventTarget = document;
type EventName = keyof DocumentEventMap;
describe('UseEscapeKeyListener', () => {
it('executes the callback when the Escape key is pressed', () => {
// arrange
const expectedCallbackCall = true;
let callbackCalled = false;
const callback = () => {
callbackCalled = true;
};
// act
mountWrapperComponent(callback);
const event = new KeyboardEvent('keyup', { key: 'Escape' });
EventSource.dispatchEvent(event);
// assert
expect(callbackCalled).to.equal(expectedCallbackCall);
});
it('adds the event listener on component mount', () => {
// arrange
const expectedEventType: EventName = 'keyup';
const { isAddEventCalled, formatListeners } = createEventSpies(EventSource, afterEach);
// act
mountWrapperComponent();
// assert
const isAdded = isAddEventCalled(expectedEventType);
expect(isAdded).to.equal(true, formatAssertionMessage([
`Expected event type to be added: "${expectedEventType}".`,
`Current listeners: ${formatListeners()}`,
]));
});
it('removes the event listener once unmounted', () => {
// arrange
const expectedEventType: EventName = 'keyup';
const { isRemoveEventCalled, formatListeners } = createEventSpies(EventSource, afterEach);
// act
const wrapper = mountWrapperComponent();
wrapper.unmount();
// assert
const isRemoved = isRemoveEventCalled(expectedEventType);
expect(isRemoved).to.equal(true, formatAssertionMessage([
`Expected event type to be removed: "${expectedEventType}".`,
`Remaining listeners: ${formatListeners()}`,
]));
});
});
function mountWrapperComponent(
callback = () => {},
) {
return mount(defineComponent({
setup() {
useEscapeKeyListener(callback);
},
template: '<div></div>',
}));
}

View File

@@ -0,0 +1,63 @@
import { describe, it, expect } from 'vitest';
import { shallowMount } from '@vue/test-utils';
import { defineComponent } from 'vue';
import { useKeyboardInteractionState } from '@/presentation/components/Scripts/View/Tree/TreeView/Node/UseKeyboardInteractionState';
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
describe('useKeyboardInteractionState', () => {
describe('isKeyboardBeingUsed', () => {
it('`false` initially', () => {
// arrange
const expectedValue = false;
// act
const { returnObject } = mountWrapperComponent();
// assert
const actualValue = returnObject.isKeyboardBeingUsed.value;
expect(actualValue).to.equal(expectedValue);
});
it('`true` after any key is pressed', () => {
// arrange
const expectedValue = true;
// act
const { returnObject } = mountWrapperComponent();
triggerKeyPress();
// assert
const actualValue = returnObject.isKeyboardBeingUsed.value;
expect(actualValue).to.equal(expectedValue);
});
it('`false` after any key is pressed once detached', () => {
// arrange
const expectedValue = false;
// act
const { wrapper, returnObject } = mountWrapperComponent();
wrapper.unmount();
triggerKeyPress(); // should not react to it
// assert
const actualValue = returnObject.isKeyboardBeingUsed.value;
expect(actualValue).to.equal(expectedValue);
});
});
});
function triggerKeyPress() {
const eventSource: EventTarget = document;
const keydownEvent = new KeyboardEvent('keydown', { key: 'a' });
eventSource.dispatchEvent(keydownEvent);
}
function mountWrapperComponent() {
let returnObject: ReturnType<typeof useKeyboardInteractionState> | undefined;
const wrapper = shallowMount(defineComponent({
setup() {
returnObject = useKeyboardInteractionState();
},
template: '<div></div>',
}));
expectExists(returnObject);
return {
returnObject,
wrapper,
};
}

View File

@@ -0,0 +1,67 @@
import {
describe, it, expect,
} from 'vitest';
import { mount } from '@vue/test-utils';
import { defineComponent } from 'vue';
import { useAutoUnsubscribedEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
describe('UseAutoUnsubscribedEventListener', () => {
describe('event listening on different targets', () => {
const testCases: readonly {
readonly description: string;
readonly eventTarget: EventTarget;
}[] = [
{
description: 'a div element',
eventTarget: document.createElement('div'),
},
{
description: 'the document',
eventTarget: document,
},
{
description: 'the HTML element',
eventTarget: document.documentElement,
},
{
description: 'the body element',
eventTarget: document.body,
},
// `window` target is not working in tests due to how `jsdom` handles it
];
testCases.forEach((
{ description, eventTarget },
) => {
it(description, () => {
// arrange
let actualEvent: KeyboardEvent | undefined;
const expectedEvent = new KeyboardEvent('keypress');
mountWrapperComponent(
({ startListening }) => {
startListening(eventTarget, 'keypress', (event) => {
actualEvent = event;
});
},
);
// act
eventTarget.dispatchEvent(expectedEvent);
// assert
expect(actualEvent).to.equal(expectedEvent);
});
});
});
});
function mountWrapperComponent(
callback: (returnObject: ReturnType<typeof useAutoUnsubscribedEventListener>) => void,
) {
return mount(defineComponent({
setup() {
const returnObject = useAutoUnsubscribedEventListener();
callback(returnObject);
},
template: '<div></div>',
}));
}

View File

@@ -0,0 +1,29 @@
import {
describe, it, expect,
} from 'vitest';
import { mount } from '@vue/test-utils';
import ModalContainer from '@/presentation/components/Shared/Modal/ModalContainer.vue';
describe('ModalContainer', () => {
it('closes on pressing ESC key', async () => {
// arrange
const wrapper = mountComponent({ modelValue: true });
// act
const escapeEvent = new KeyboardEvent('keyup', { key: 'Escape' });
document.dispatchEvent(escapeEvent);
// assert
expect(wrapper.emitted('update:modelValue')).to.deep.equal([[false]]);
});
});
function mountComponent(options: {
readonly modelValue: boolean,
}) {
return mount(ModalContainer, {
props: {
modelValue: options.modelValue,
},
});
}

View File

@@ -0,0 +1,70 @@
export function createEventSpies(
eventTarget: EventTarget,
restoreCallback: (restoreFunc: () => void) => void,
) {
const originalAddEventListener = eventTarget.addEventListener;
const originalRemoveEventListener = eventTarget.removeEventListener;
const currentListeners = new Array<Parameters<typeof eventTarget.addEventListener>>();
const addEventListenerCalls = new Array<Parameters<typeof eventTarget.addEventListener>>();
const removeEventListenerCalls = new Array<Parameters<typeof eventTarget.removeEventListener>>();
eventTarget.addEventListener = (
...args: Parameters<typeof eventTarget.addEventListener>
): ReturnType<typeof eventTarget.addEventListener> => {
addEventListenerCalls.push(args);
currentListeners.push(args);
return originalAddEventListener.call(eventTarget, ...args);
};
eventTarget.removeEventListener = (
...args: Parameters<typeof eventTarget.removeEventListener>
): ReturnType<typeof eventTarget.removeEventListener> => {
removeEventListenerCalls.push(args);
const [type, listener] = args;
const registeredListener = findCurrentListener(type, listener);
if (registeredListener) {
const index = currentListeners.indexOf(registeredListener);
if (index > -1) {
currentListeners.splice(index, 1);
}
}
return originalRemoveEventListener.call(eventTarget, ...args);
};
function findCurrentListener(
type: string,
listener: EventListenerOrEventListenerObject | null,
): Parameters<typeof eventTarget.addEventListener> | undefined {
return currentListeners.find((args) => {
const [eventType, eventListener] = args;
return eventType === type && listener === eventListener;
});
}
restoreCallback(() => {
eventTarget.addEventListener = originalAddEventListener;
eventTarget.removeEventListener = originalRemoveEventListener;
});
return {
isAddEventCalled(eventType: string): boolean {
const call = addEventListenerCalls.find((args) => {
const [type] = args;
return type === eventType;
});
return call !== undefined;
},
isRemoveEventCalled(eventType: string) {
const call = removeEventListenerCalls.find((args) => {
const [type] = args;
return type === eventType;
});
return call !== undefined;
},
formatListeners: () => {
return JSON.stringify(currentListeners);
},
};
}

View File

@@ -1,67 +0,0 @@
export type EventName = keyof WindowEventMap;
export function createWindowEventSpies(restoreCallback: (restoreFunc: () => void) => void) {
const originalAddEventListener = window.addEventListener;
const originalRemoveEventListener = window.removeEventListener;
const currentListeners = new Array<Parameters<typeof window.addEventListener>>();
const addEventListenerCalls = new Array<Parameters<typeof window.addEventListener>>();
const removeEventListenerCalls = new Array<Parameters<typeof window.removeEventListener>>();
window.addEventListener = (
...args: Parameters<typeof window.addEventListener>
): ReturnType<typeof window.addEventListener> => {
addEventListenerCalls.push(args);
currentListeners.push(args);
return originalAddEventListener.call(window, ...args);
};
window.removeEventListener = (
...args: Parameters<typeof window.removeEventListener>
): ReturnType<typeof window.removeEventListener> => {
removeEventListenerCalls.push(args);
const [type, listener] = args;
const registeredListener = findCurrentListener(type as EventName, listener);
if (registeredListener) {
const index = currentListeners.indexOf(registeredListener);
if (index > -1) {
currentListeners.splice(index, 1);
}
}
return originalRemoveEventListener.call(window, ...args);
};
function findCurrentListener(
type: EventName,
listener: EventListenerOrEventListenerObject,
): Parameters<typeof window.addEventListener> | undefined {
return currentListeners.find((args) => {
const [eventType, eventListener] = args;
return eventType === type && listener === eventListener;
});
}
restoreCallback(() => {
window.addEventListener = originalAddEventListener;
window.removeEventListener = originalRemoveEventListener;
});
return {
isAddEventCalled(eventType: EventName): boolean {
const call = addEventListenerCalls.find((args) => {
const [type] = args;
return type === eventType;
});
return call !== undefined;
},
isRemoveEventCalled(eventType: EventName) {
const call = removeEventListenerCalls.find((args) => {
const [type] = args;
return type === eventType;
});
return call !== undefined;
},
currentListeners,
};
}

View File

@@ -1,53 +1,116 @@
import { describe, it, expect } from 'vitest';
import { TimerStub } from '@tests/unit/shared/Stubs/TimerStub';
import { throttle } from '@/application/Common/Timing/Throttle';
import { throttle, type ThrottleOptions } from '@/application/Common/Timing/Throttle';
import type { Timer } from '@/application/Common/Timing/Timer';
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
describe('throttle', () => {
describe('validates parameters', () => {
describe('throws if waitInMs is invalid', () => {
// arrange
const testCases = [
describe('parameter validation', () => {
describe('throws for invalid waitInMs', () => {
const testCases: readonly {
readonly description: string;
readonly value: number;
readonly expectedError: string;
}[] = [
{
name: 'given zero',
description: 'given zero',
value: 0,
expectedError: 'missing delay',
},
{
name: 'given negative',
description: 'given negative',
value: -2,
expectedError: 'negative delay',
},
];
const noopCallback = () => { /* do nothing */ };
for (const testCase of testCases) {
it(`"${testCase.name}" throws "${testCase.expectedError}"`, () => {
testCases.forEach((
{ description, expectedError, value: waitInMs },
) => {
it(`"${description}" throws "${expectedError}"`, () => {
// arrange
const context = new TestContext()
.withWaitInMs(waitInMs);
// act
const waitInMs = testCase.value;
const act = () => throttle(noopCallback, waitInMs);
const act = () => context.throttle();
// assert
expect(act).to.throw(testCase.expectedError);
expect(act).to.throw(expectedError);
});
}
});
});
});
it('should call the callback immediately', () => {
it('executes the leading callback immediately', () => {
// arrange
const timer = new TimerStub();
let totalRuns = 0;
const callback = () => totalRuns++;
const throttleFunc = throttle(callback, 500, timer);
const throttleFunc = new TestContext()
.withTimer(timer)
.withCallback(callback)
.throttle();
// act
throttleFunc();
// assert
expect(totalRuns).to.equal(1);
});
it('should call the callback again after the timeout', () => {
it('executes the leading callback with initial arguments', () => {
// arrange
const expectedArguments = [1, 2, 3];
const timer = new TimerStub();
let lastArgs: readonly number[] | null = null;
const callback = (...args: readonly number[]) => { lastArgs = args; };
const waitInMs = 500;
const throttleFunc = new TestContext()
.withWaitInMs(waitInMs)
.withTimer(timer)
.withCallback(callback)
.throttle();
// act
throttleFunc(...expectedArguments);
timer.tickNext(waitInMs / 3);
throttleFunc(4, 5, 6);
timer.tickNext(waitInMs / 3);
throttleFunc(7, 8, 9);
// assert
expect(lastArgs).to.deep.equal(expectedArguments);
});
it('executes the trailing callback with final arguments', () => {
// arrange
const expectedArguments = [1, 2, 3];
const timer = new TimerStub();
let lastArgs: readonly number[] | null = null;
const callback = (...args: readonly number[]) => { lastArgs = args; };
const waitInMs = 500;
const throttleFunc = new TestContext()
.withWaitInMs(waitInMs)
.withTimer(timer)
.withCallback(callback)
.throttle();
// act
throttleFunc(1, 2, 3);
timer.tickNext(100);
throttleFunc(4, 5, 6);
timer.tickNext(100);
throttleFunc(lastArgs);
// assert
expect(lastArgs).to.deep.equal(expectedArguments);
});
it('executes the callback after the delay', () => {
// arrange
const timer = new TimerStub();
let totalRuns = 0;
const callback = () => totalRuns++;
const waitInMs = 500;
const throttleFunc = throttle(callback, waitInMs, timer);
const throttleFunc = new TestContext()
.withWaitInMs(waitInMs)
.withTimer(timer)
.withCallback(callback)
.throttle();
// act
throttleFunc();
totalRuns--; // So we don't count the initial run
@@ -56,53 +119,207 @@ describe('throttle', () => {
// assert
expect(totalRuns).to.equal(1);
});
it('should call the callback at most once at given time', () => {
it('limits calls to at most once per period', () => {
// arrange
const totalExpectedCalls = 2; // leading and trailing only
const timer = new TimerStub();
let totalRuns = 0;
const callback = () => totalRuns++;
const waitInMs = 500;
const waitInMs = 200;
const totalCalls = 10;
const throttleFunc = throttle(callback, waitInMs, timer);
const throttleFunc = new TestContext()
.withWaitInMs(waitInMs)
.withTimer(timer)
.withCallback(callback)
.throttle();
// act
for (let currentCall = 0; currentCall < totalCalls; currentCall++) {
const currentTime = (waitInMs / totalCalls) * currentCall;
timer.setCurrentTime(currentTime);
throttleFunc();
}
timer.tickNext(waitInMs);
// assert
expect(totalRuns).to.equal(2); // one initial and one at the end
expect(totalRuns).to.equal(totalExpectedCalls);
});
it('should call the callback as long as delay is waited', () => {
it('executes the callback after each complete delay period', () => {
// arrange
const timer = new TimerStub();
let totalRuns = 0;
const callback = () => totalRuns++;
const waitInMs = 500;
const expectedTotalRuns = 10;
const throttleFunc = throttle(callback, waitInMs, timer);
const throttleFunc = new TestContext()
.withWaitInMs(waitInMs)
.withTimer(timer)
.withCallback(callback)
.throttle();
// act
for (let i = 0; i < expectedTotalRuns; i++) {
Array.from({ length: expectedTotalRuns }).forEach(() => {
throttleFunc();
timer.tickNext(waitInMs);
}
});
// assert
expect(totalRuns).to.equal(expectedTotalRuns);
});
it('should call arguments as expected', () => {
// arrange
const timer = new TimerStub();
const expected = [1, 2, 3];
const actual = new Array<number>();
const callback = (arg: number) => { actual.push(arg); };
const waitInMs = 500;
const throttleFunc = throttle(callback, waitInMs, timer);
// act
for (const arg of expected) {
throttleFunc(arg);
describe('leading call exclusion', () => {
it('does not execute the callback immediately on the first call', () => {
// arrange
const timer = new TimerStub();
let totalRuns = 0;
const callback = () => totalRuns++;
const throttleFunc = new TestContext()
.withTimer(timer)
.withCallback(callback)
.withExcludeLeadingCall(true)
.throttle();
// act
throttleFunc();
// assert
expect(totalRuns).to.equal(0);
});
it('executes the initial call after the initial wait time', () => {
// arrange
const timer = new TimerStub();
let totalRuns = 0;
const waitInMs = 200;
const callback = () => totalRuns++;
const throttleFunc = new TestContext()
.withTimer(timer)
.withCallback(callback)
.withExcludeLeadingCall(true)
.withWaitInMs(waitInMs)
.throttle();
// act
throttleFunc();
timer.tickNext(waitInMs);
}
// assert
expect(expected).to.deep.equal(actual);
// assert
expect(totalRuns).to.equal(1);
});
it('executes two calls after two wait periods', () => {
// arrange
const expectedTotalRuns = 2;
const calledArgs = new Array<string>();
const timer = new TimerStub();
const waitInMs = 300;
let totalRuns = 0;
const callback = (message: string) => {
totalRuns++;
calledArgs.push(message);
};
const throttleFunc = new TestContext()
.withTimer(timer)
.withCallback(callback)
.withWaitInMs(waitInMs)
.withExcludeLeadingCall(true)
.throttle();
// act
Array.from({ length: expectedTotalRuns }).forEach((_, index) => {
throttleFunc(`Call ${index} (zero-based, where initial call is 0)`);
timer.tickNext(waitInMs);
});
// assert
expect(totalRuns).to.equal(expectedTotalRuns, formatAssertionMessage([
`Expected total runs to equal ${expectedTotalRuns}, but got ${totalRuns}.`,
'Detailed call information:',
...calledArgs.map((message, index) => `${index + 1}) ${message}`),
]));
});
it('only executes once when multiple calls are made during the initial wait period', () => {
// arrange
const timer = new TimerStub();
let totalRuns = 0;
const callback = () => { totalRuns++; };
const waitInMs = 300;
const throttleFunc = new TestContext()
.withTimer(timer)
.withWaitInMs(waitInMs)
.withCallback(callback)
.withExcludeLeadingCall(true)
.throttle();
// act
throttleFunc();
timer.tickNext(waitInMs / 3);
throttleFunc();
timer.tickNext(waitInMs / 3);
throttleFunc();
timer.tickNext(waitInMs / 3);
// assert
expect(totalRuns).to.equal(1);
});
it('executes the last provided arguments only after the wait period expires', () => {
// arrange
const expectedLastArg = 'trailing call';
const timer = new TimerStub();
let actualLastArg: string | null = null;
const callback = (arg: string) => {
actualLastArg = arg;
};
const waitInMs = 300;
const throttleFunc = new TestContext()
.withTimer(timer)
.withWaitInMs(waitInMs)
.withCallback(callback)
.withExcludeLeadingCall(true)
.throttle();
// act
throttleFunc('leading call');
timer.tickNext(waitInMs / 3);
throttleFunc('call in the middle');
timer.tickNext(waitInMs / 3);
throttleFunc(expectedLastArg);
timer.tickNext(waitInMs / 3);
// assert
expect(actualLastArg).to.equal(expectedLastArg);
});
});
});
type CallbackType = Parameters<typeof throttle>[0];
class TestContext {
private options: Partial<ThrottleOptions> | undefined = {
timer: new TimerStub(),
};
private waitInMs: number = 500;
private callback: CallbackType = () => { /* NO OP */ };
public withTimer(timer: Timer): this {
return this.withOptions({
...(this.options ?? {}),
timer,
});
}
public withWaitInMs(waitInMs: number): this {
this.waitInMs = waitInMs;
return this;
}
public withCallback(callback: CallbackType): this {
this.callback = callback;
return this;
}
public withExcludeLeadingCall(excludeLeadingCall: boolean): this {
return this.withOptions({
...(this.options ?? {}),
excludeLeadingCall,
});
}
public withOptions(options: Partial<ThrottleOptions> | undefined): this {
this.options = options;
return this;
}
public throttle(): ReturnType<typeof throttle> {
return throttle(
this.callback,
this.waitInMs,
this.options,
);
}
}

View File

@@ -22,6 +22,7 @@ describe('DependencyProvider', () => {
useCodeRunner: createTransientTests(),
useDialog: createTransientTests(),
useScriptDiagnosticsCollector: createTransientTests(),
useAutoUnsubscribedEventListener: createTransientTests(),
};
Object.entries(testCases).forEach(([key, runTests]) => {
const registeredKey = InjectionKeys[key].key;

View File

@@ -6,6 +6,7 @@ import { useCollectionState } from '@/presentation/components/Shared/Hooks/UseCo
import { UseCollectionStateStub } from '@tests/unit/shared/Stubs/UseCollectionStateStub';
import { InjectionKeys } from '@/presentation/injectionSymbols';
import { createSizeObserverStub } from '@tests/unit/shared/Stubs/SizeObserverStub';
import { UseEventListenerStub } from '@tests/unit/shared/Stubs/UseEventListenerStub';
const DOM_SELECTOR_CARDS = '.cards';
@@ -54,6 +55,7 @@ function mountComponent(options?: {
provide: {
[InjectionKeys.useCollectionState.key]:
() => options?.useCollectionState ?? new UseCollectionStateStub().get(),
[InjectionKeys.useAutoUnsubscribedEventListener.key]: new UseEventListenerStub().get(),
},
stubs: {
[sizeObserverName]: sizeObserverStub,

View File

@@ -1,120 +1,81 @@
import { describe, it, expect } from 'vitest';
import { shallowMount } from '@vue/test-utils';
import { defineComponent, nextTick } from 'vue';
import {
type WindowWithEventListeners, useKeyboardInteractionState,
} from '@/presentation/components/Scripts/View/Tree/TreeView/Node/UseKeyboardInteractionState';
import { useKeyboardInteractionState } from '@/presentation/components/Scripts/View/Tree/TreeView/Node/UseKeyboardInteractionState';
import type { UseEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
import { UseEventListenerStub } from '@tests/unit/shared/Stubs/UseEventListenerStub';
describe('useKeyboardInteractionState', () => {
describe('isKeyboardBeingUsed', () => {
it('should initialize as `false`', () => {
it('initializes as `false`', () => {
// arrange
const { windowStub } = createWindowStub();
const expectedValue = false;
const context = new TestContext();
// act
const { returnObject } = mountWrapperComponent(windowStub);
const { isKeyboardBeingUsed } = context.get();
// assert
expect(returnObject.isKeyboardBeingUsed.value).to.equal(false);
expect(isKeyboardBeingUsed.value).to.equal(expectedValue);
});
it('should set to `true` on keydown event', () => {
it('becomes `true` on `keydown` event', () => {
// arrange
const { triggerEvent, windowStub } = createWindowStub();
const expectedValue = true;
const eventTarget = new EventTarget();
const context = new TestContext()
.withEventTarget(eventTarget);
// act
const { returnObject } = mountWrapperComponent(windowStub);
triggerEvent('keydown');
const { isKeyboardBeingUsed } = context.get();
eventTarget.dispatchEvent(new Event('keydown'));
// assert
expect(returnObject.isKeyboardBeingUsed.value).to.equal(true);
expect(isKeyboardBeingUsed.value).to.equal(expectedValue);
});
it('should stay `false` on click event', () => {
it('remains `false` on `click` event', () => {
// arrange
const { triggerEvent, windowStub } = createWindowStub();
const expectedValue = false;
const eventTarget = new EventTarget();
const context = new TestContext()
.withEventTarget(eventTarget);
// act
const { returnObject } = mountWrapperComponent(windowStub);
triggerEvent('click');
const { isKeyboardBeingUsed } = context.get();
eventTarget.dispatchEvent(new Event('click'));
// assert
expect(returnObject.isKeyboardBeingUsed.value).to.equal(false);
expect(isKeyboardBeingUsed.value).to.equal(expectedValue);
});
it('should transition to `false` on click event after keydown event', () => {
it('transitions back to `false` on `click` event after `keydown` event', () => {
// arrange
const { triggerEvent, windowStub } = createWindowStub();
const expectedValue = false;
const eventTarget = new EventTarget();
const context = new TestContext()
.withEventTarget(eventTarget);
// act
const { returnObject } = mountWrapperComponent(windowStub);
triggerEvent('keydown');
triggerEvent('click');
const { isKeyboardBeingUsed } = context.get();
eventTarget.dispatchEvent(new Event('keydown'));
eventTarget.dispatchEvent(new Event('click'));
// assert
expect(returnObject.isKeyboardBeingUsed.value).to.equal(false);
});
});
describe('attach/detach', () => {
it('should attach keydown and click events on mounted', () => {
// arrange
const { listeners, windowStub } = createWindowStub();
// act
mountWrapperComponent(windowStub);
// assert
expect(listeners.keydown).to.have.lengthOf(1);
expect(listeners.click).to.have.lengthOf(1);
});
it('should detach keydown and click events on unmounted', async () => {
// arrange
const { listeners, windowStub } = createWindowStub();
// act
const { wrapper } = mountWrapperComponent(windowStub);
wrapper.unmount();
await nextTick();
// assert
expect(listeners.keydown).to.have.lengthOf(0);
expect(listeners.click).to.have.lengthOf(0);
expect(isKeyboardBeingUsed.value).to.equal(expectedValue);
});
});
});
function mountWrapperComponent(window: WindowWithEventListeners) {
let returnObject: ReturnType<typeof useKeyboardInteractionState> | undefined;
const wrapper = shallowMount(defineComponent({
setup() {
returnObject = useKeyboardInteractionState(window);
},
template: '<div></div>',
}));
if (!returnObject) {
throw new Error('missing hook result');
class TestContext {
private eventTarget: EventTarget = new EventTarget();
private useEventListener: UseEventListener = new UseEventListenerStub().get();
public withEventTarget(eventTarget: EventTarget): this {
this.eventTarget = eventTarget;
return this;
}
return {
returnObject,
wrapper,
};
}
type EventListenerWindowFunction = (ev: Event) => unknown;
type WindowEventKey = keyof WindowEventMap;
public withUseEventListener(useEventListener: UseEventListener): this {
this.useEventListener = useEventListener;
return this;
}
function createWindowStub() {
const listeners: Partial<Record<WindowEventKey, EventListenerWindowFunction[]>> = {};
const windowStub: WindowWithEventListeners = {
addEventListener: (eventName: string, fn: EventListenerWindowFunction) => {
if (!listeners[eventName]) {
listeners[eventName] = [];
}
listeners[eventName].push(fn);
},
removeEventListener: (eventName: string, fn: EventListenerWindowFunction) => {
if (!listeners[eventName]) return;
const index = listeners[eventName].indexOf(fn);
if (index > -1) {
listeners[eventName].splice(index, 1);
}
},
};
return {
windowStub,
triggerEvent: (eventName: WindowEventKey) => {
listeners[eventName]?.forEach((fn) => fn(new Event(eventName)));
},
listeners,
};
public get() {
return useKeyboardInteractionState(
this.eventTarget,
this.useEventListener,
);
}
}

View File

@@ -0,0 +1,172 @@
import { describe, it, expect } from 'vitest';
import { shallowMount } from '@vue/test-utils';
import { nextTick, shallowRef } from 'vue';
import { useAutoUnsubscribedEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
import { expectDoesNotThrowAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
describe('UseAutoUnsubscribedEventListener', () => {
describe('startListening', () => {
describe('direct value', () => {
it('immediately adds listener', () => {
// arrange
const eventTarget = new EventTarget();
const eventType: keyof HTMLElementEventMap = 'abort';
const expectedEvent = new CustomEvent(eventType);
let actualEvent: Event | null = null;
const callback = (event: Event) => {
actualEvent = event;
};
// act
const { returnObject } = mountWrapper();
returnObject.startListening(eventTarget, eventType, callback);
eventTarget.dispatchEvent(expectedEvent);
// assert
expect(actualEvent).to.equal(expectedEvent);
});
it('removes listener after component unmounts', () => {
// arrange
const expectedCallbackCall = false;
let isCallbackCalled = false;
const callback = () => {
isCallbackCalled = true;
};
const eventTarget = new EventTarget();
const eventType: keyof HTMLElementEventMap = 'abort';
// act
const { wrapper } = mountWrapper({
setup: (listener) => listener.startListening(eventTarget, eventType, callback),
});
wrapper.unmount();
eventTarget.dispatchEvent(new CustomEvent(eventType));
// assert
expect(isCallbackCalled).to.equal(expectedCallbackCall);
});
});
describe('reference', () => {
it('immediately adds listener', () => {
// arrange
const eventTarget = new EventTarget();
const eventTargetRef = shallowRef(eventTarget);
const eventType: keyof HTMLElementEventMap = 'abort';
const expectedEvent = new CustomEvent(eventType);
let actualEvent: Event | null = null;
const callback = (event: Event) => {
actualEvent = event;
};
// act
const { returnObject } = mountWrapper();
returnObject.startListening(eventTargetRef, eventType, callback);
eventTarget.dispatchEvent(expectedEvent);
// assert
expect(actualEvent).to.equal(expectedEvent);
});
it('adds listener upon reference update', async () => {
// arrange
const oldValue = new EventTarget();
const newValue = new EventTarget();
const targetRef = shallowRef(oldValue);
const eventType: keyof HTMLElementEventMap = 'abort';
const expectedEvent = new CustomEvent(eventType);
let actualEvent: Event | null = null;
const callback = (event: Event) => {
actualEvent = event;
};
// act
const { returnObject } = mountWrapper();
returnObject.startListening(targetRef, eventType, callback);
targetRef.value = newValue;
await nextTick();
newValue.dispatchEvent(expectedEvent);
// assert
expect(actualEvent).to.equal(expectedEvent);
});
it('does not throw if initial element is undefined', () => {
// arrange
const targetRef = shallowRef(undefined);
// act
const { returnObject } = mountWrapper();
const act = () => {
returnObject.startListening(targetRef, 'abort', () => { /* NO OP */ });
};
// assert
expect(act).to.not.throw();
});
it('does not throw when reference becomes undefined', async () => {
// arrange
const targetRef = shallowRef<EventTarget | undefined>(new EventTarget());
// act
const { returnObject } = mountWrapper();
returnObject.startListening(targetRef, 'abort', () => { /* NO OP */ });
const act = async () => {
targetRef.value = undefined;
await nextTick();
};
// assert
await expectDoesNotThrowAsync(act);
});
it('removes listener on reference change', async () => {
// arrange
const expectedCallbackCall = false;
let isCallbackCalled = false;
const callback = () => {
isCallbackCalled = true;
};
const oldValue = new EventTarget();
const newValue = new EventTarget();
const targetRef = shallowRef(oldValue);
const eventType: keyof HTMLElementEventMap = 'abort';
const expectedEvent = new CustomEvent(eventType);
// act
const { returnObject } = mountWrapper();
returnObject.startListening(targetRef, eventType, callback);
targetRef.value = newValue;
await nextTick();
oldValue.dispatchEvent(expectedEvent);
// assert
expect(isCallbackCalled).to.equal(expectedCallbackCall);
});
it('removes listener after component unmounts', () => {
// arrange
const expectedCallbackCall = false;
let isCallbackCalled = false;
const callback = () => {
isCallbackCalled = true;
};
const target = new EventTarget();
const targetRef = shallowRef(target);
const eventType: keyof HTMLElementEventMap = 'abort';
// act
const { wrapper } = mountWrapper({
setup: (listener) => listener.startListening(targetRef, eventType, callback),
});
wrapper.unmount();
target.dispatchEvent(new CustomEvent(eventType));
// assert
expect(isCallbackCalled).to.equal(expectedCallbackCall);
});
});
});
});
function mountWrapper(options?: {
readonly constructorArgs?: Parameters<typeof useAutoUnsubscribedEventListener>,
/** Running inside `setup` allows simulating lifecycle events like unmounting. */
readonly setup?: (returnObject: ReturnType<typeof useAutoUnsubscribedEventListener>) => void,
}) {
let returnObject: ReturnType<typeof useAutoUnsubscribedEventListener> | undefined;
const wrapper = shallowMount({
setup() {
returnObject = useAutoUnsubscribedEventListener(...(options?.constructorArgs ?? []));
if (options?.setup) {
options.setup(returnObject);
}
},
template: '<div></div>',
});
expectExists(returnObject);
return {
wrapper,
returnObject,
};
}

View File

@@ -1,78 +1,79 @@
import {
describe, it, expect, afterEach,
describe, it, expect,
} from 'vitest';
import { shallowMount } from '@vue/test-utils';
import { nextTick, defineComponent } from 'vue';
import { useEscapeKeyListener } from '@/presentation/components/Shared/Modal/Hooks/UseEscapeKeyListener';
import { type EventName, createWindowEventSpies } from '@tests/shared/Spies/WindowEventSpies';
import type { UseEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
import { UseEventListenerStub } from '@tests/unit/shared/Stubs/UseEventListenerStub';
describe('useEscapeKeyListener', () => {
it('executes the callback when the Escape key is pressed', async () => {
it('executes the callback when the Escape key is pressed', () => {
// arrange
let callbackCalled = false;
const callback = () => {
callbackCalled = true;
};
createComponent(callback);
const escapeEvent = new KeyboardEvent('keyup', { key: 'Escape' });
const eventTarget = new EventTarget();
const context = new TestContext()
.withEventTarget(eventTarget)
.withCallback(callback);
// act
const event = new KeyboardEvent('keyup', { key: 'Escape' });
window.dispatchEvent(event);
await nextTick();
context.get();
eventTarget.dispatchEvent(escapeEvent);
// assert
expect(callbackCalled).to.equal(true);
});
it('does not execute the callback for other key presses', async () => {
it('does not execute the callback for other key presses', () => {
// arrange
let callbackCalled = false;
const callback = () => {
callbackCalled = true;
};
createComponent(callback);
const enterKeyEvent = new KeyboardEvent('keyup', { key: 'Enter' });
const eventTarget = new EventTarget();
const context = new TestContext()
.withEventTarget(eventTarget)
.withCallback(callback);
// act
const event = new KeyboardEvent('keyup', { key: 'Enter' });
window.dispatchEvent(event);
await nextTick();
context.get();
eventTarget.dispatchEvent(enterKeyEvent);
// assert
expect(callbackCalled).to.equal(false);
});
it('adds an event listener on component mount', () => {
// arrange
const expectedEventType: EventName = 'keyup';
const { isAddEventCalled } = createWindowEventSpies(afterEach);
// act
createComponent();
// assert
expect(isAddEventCalled(expectedEventType)).to.equal(true);
});
it('removes the event listener on component unmount', async () => {
// arrange
const expectedEventType: EventName = 'keyup';
const { isRemoveEventCalled } = createWindowEventSpies(afterEach);
// act
const wrapper = createComponent();
wrapper.unmount();
await nextTick();
// assert
expect(isRemoveEventCalled(expectedEventType)).to.equal(true);
});
});
function createComponent(callback = () => {}) {
return shallowMount(defineComponent({
setup() {
useEscapeKeyListener(callback);
},
template: '<div></div>',
}));
class TestContext {
private callback: () => void = () => { /* NOOP */ };
private useEventListener: UseEventListener = new UseEventListenerStub().get();
private eventTarget: EventTarget = new EventTarget();
public withCallback(callback: () => void): this {
this.callback = callback;
return this;
}
public withUseEventListener(useEventListener: UseEventListener): this {
this.useEventListener = useEventListener;
return this;
}
public withEventTarget(eventTarget: EventTarget = new EventTarget()): this {
this.eventTarget = eventTarget;
return this;
}
public get(): ReturnType<typeof useEscapeKeyListener> {
return useEscapeKeyListener(
this.callback,
this.eventTarget,
this.useEventListener,
);
}
}

View File

@@ -1,10 +1,11 @@
import {
describe, it, expect, afterEach,
describe, it, expect,
} from 'vitest';
import { shallowMount } from '@vue/test-utils';
import { nextTick } from 'vue';
import ModalContainer from '@/presentation/components/Shared/Modal/ModalContainer.vue';
import { createWindowEventSpies } from '@tests/shared/Spies/WindowEventSpies';
import ModalContainer, { INJECTION_KEY_ESCAPE_LISTENER } from '@/presentation/components/Shared/Modal/ModalContainer.vue';
import type { useEscapeKeyListener } from '@/presentation/components/Shared/Modal/Hooks/UseEscapeKeyListener';
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
const DOM_MODAL_CONTAINER_SELECTOR = '.modal-container';
const COMPONENT_MODAL_OVERLAY_NAME = 'ModalOverlay';
@@ -73,15 +74,23 @@ describe('ModalContainer.vue', () => {
it('closes on pressing ESC key', async () => {
// arrange
createWindowEventSpies(afterEach);
const wrapper = mountComponent({ modelValue: true });
let escapeKeyCallback: (() => void) | undefined;
const escapeKeyListenerStub: typeof useEscapeKeyListener = (callback) => {
escapeKeyCallback = callback;
};
const wrapper = mountComponent({
modelValue: true,
escapeListener: escapeKeyListenerStub,
});
// act
const escapeEvent = new KeyboardEvent('keyup', { key: 'Escape' });
window.dispatchEvent(escapeEvent);
await wrapper.vm.$nextTick();
if (escapeKeyCallback) {
escapeKeyCallback();
}
await nextTick();
// assert
expectExists(escapeKeyCallback);
expect(wrapper.emitted('update:modelValue')).to.deep.equal([[false]]);
});
@@ -94,7 +103,7 @@ describe('ModalContainer.vue', () => {
// act
overlayMock.vm.$emit('transitionedOut');
contentMock.vm.$emit('transitionedOut');
await wrapper.vm.$nextTick();
await nextTick();
// assert
expect(wrapper.emitted('update:modelValue')).to.deep.equal([[false]]);
@@ -126,7 +135,7 @@ describe('ModalContainer.vue', () => {
// act
const overlayMock = wrapper.findComponent({ name: COMPONENT_MODAL_OVERLAY_NAME });
overlayMock.vm.$emit('click');
await wrapper.vm.$nextTick();
await nextTick();
// assert
expect(wrapper.emitted('update:modelValue')).to.equal(undefined);
@@ -139,7 +148,7 @@ describe('ModalContainer.vue', () => {
// act
const overlayMock = wrapper.findComponent({ name: COMPONENT_MODAL_OVERLAY_NAME });
overlayMock.vm.$emit('click');
await wrapper.vm.$nextTick();
await nextTick();
// assert
expect(wrapper.emitted('update:modelValue')).to.deep.equal([[false]]);
@@ -151,7 +160,7 @@ function mountComponent(options: {
readonly modelValue: boolean,
readonly closeOnOutsideClick?: boolean,
readonly slotHtml?: string,
readonly attachToDocument?: boolean,
readonly escapeListener?: typeof useEscapeKeyListener,
}) {
return shallowMount(ModalContainer, {
props: {
@@ -162,6 +171,10 @@ function mountComponent(options: {
},
slots: options.slotHtml !== undefined ? { default: options.slotHtml } : undefined,
global: {
provide: {
[INJECTION_KEY_ESCAPE_LISTENER]:
options?.escapeListener ?? (() => { /* NOP */ }),
},
stubs: {
[COMPONENT_MODAL_OVERLAY_NAME]: {
name: COMPONENT_MODAL_OVERLAY_NAME,

View File

@@ -24,7 +24,8 @@ export class TimerStub implements Timer {
}
public clearTimeout(timeoutId: TimeoutType): void {
this.subscriptions[+timeoutId].unsubscribe();
const subscriptionIndex = +timeoutId;
this.subscriptions[subscriptionIndex].unsubscribe();
}
public dateNow(): number {

View File

@@ -0,0 +1,15 @@
import type { UseEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
export class UseEventListenerStub {
public get(): UseEventListener {
return () => ({
startListening: (targetElementSource, eventType, eventResponseFunction) => {
if (targetElementSource instanceof EventTarget) {
targetElementSource.addEventListener(eventType, eventResponseFunction);
return;
}
targetElementSource.value?.addEventListener(eventType, eventResponseFunction);
},
});
}
}