diff --git a/projects/coreui-angular/src/lib/popover/popover.directive.ts b/projects/coreui-angular/src/lib/popover/popover.directive.ts index 70fb335f..cadb9420 100644 --- a/projects/coreui-angular/src/lib/popover/popover.directive.ts +++ b/projects/coreui-angular/src/lib/popover/popover.directive.ts @@ -1,10 +1,10 @@ -import { Directive, inject, input, model, TemplateRef } from '@angular/core'; +import { booleanAttribute, Directive, inject, input, model, TemplateRef } from '@angular/core'; import { Options } from '@popperjs/core'; import { Triggers } from '../coreui.types'; import { ListenersService, UIDService } from '../services'; import { ElementRefDirective } from '../shared'; -import { TooltipDirectiveBase } from '../tooltip/tooltip-directive-base'; +import { delayAttribute, TooltipDelay, TooltipDirectiveBase } from '../tooltip/tooltip-directive-base'; import { PopoverComponent } from './popover/popover.component'; @Directive({ @@ -17,12 +17,31 @@ export class PopoverDirective extends TooltipDirectiveBase { protected readonly offset = 9; protected readonly tooltipId = inject(UIDService).getUID('popover'); + /** + * Fades the popover in and out. + * @returns boolean + * @default true + * @since 5.7.45 + */ + readonly animation = input(true, { alias: 'cPopoverAnimation', transform: booleanAttribute }); + /** * Content of popover * @returns string | TemplateRef | undefined */ readonly content = input | undefined>(undefined, { alias: 'cPopover' }); + /** + * Delay in ms: `show` before the popover appears, `hide` after its trigger ends. A number sets both. + * @returns number | { show?: number; hide?: number } + * @default { show: 150, hide: 0 } + * @since 5.7.45 + */ + readonly delay = input( + {}, + { alias: 'cPopoverDelay', transform: delayAttribute } + ); + /** * Describes the placement of your component after Popper.js has applied all the modifiers that may have flipped or altered the originally provided placement property. * @returns 'top' | 'bottom' | 'left' | 'right' diff --git a/projects/coreui-angular/src/lib/popover/popover/popover.component.spec.ts b/projects/coreui-angular/src/lib/popover/popover/popover.component.spec.ts index cb1f562a..55acdc2f 100644 --- a/projects/coreui-angular/src/lib/popover/popover/popover.component.spec.ts +++ b/projects/coreui-angular/src/lib/popover/popover/popover.component.spec.ts @@ -1,26 +1,35 @@ -import { Component } from '@angular/core'; -import { TestBed } from '@angular/core/testing'; +import { Component, signal } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { PopoverComponent } from './popover.component'; @Component({ - template: '', + template: ` + + + `, imports: [PopoverComponent] }) -class TestComponent {} +class TestComponent { + readonly animation = signal(true); + readonly visible = signal(false); +} describe('PopoverComponent', () => { let component: PopoverComponent; let element: HTMLElement; + let boundElement: HTMLElement; + let fixture: ComponentFixture; beforeEach(async () => { - const fixture = TestBed.createComponent(TestComponent); + fixture = TestBed.createComponent(TestComponent); await fixture.whenStable(); - const debugElement = fixture.debugElement.query(By.directive(PopoverComponent)); + const [debugElement, boundDebugElement] = fixture.debugElement.queryAll(By.directive(PopoverComponent)); component = debugElement.componentInstance; element = debugElement.nativeElement; + boundElement = boundDebugElement.nativeElement; }); it('should create', () => { @@ -33,6 +42,23 @@ describe('PopoverComponent', () => { expect(element.classList.contains('bs-popover-auto')).toBe(true); }); + it('should not fade without animation', async () => { + fixture.componentInstance.animation.set(false); + await fixture.whenStable(); + expect(boundElement.classList.contains('popover')).toBe(true); + expect(boundElement.classList.contains('fade')).toBe(false); + }); + + it('should be hidden without animation while not visible', async () => { + expect(boundElement.classList.contains('invisible')).toBe(false); + fixture.componentInstance.animation.set(false); + await fixture.whenStable(); + expect(boundElement.classList.contains('invisible')).toBe(true); + fixture.componentInstance.visible.set(true); + await fixture.whenStable(); + expect(boundElement.classList.contains('invisible')).toBe(false); + }); + it('should not have the tooltip css classes', () => { expect(element.classList.contains('tooltip')).toBe(false); expect(element.classList.contains('bs-tooltip-auto')).toBe(false); diff --git a/projects/coreui-angular/src/lib/popover/popover/popover.component.ts b/projects/coreui-angular/src/lib/popover/popover/popover.component.ts index 3fb83bc2..66fdc442 100644 --- a/projects/coreui-angular/src/lib/popover/popover/popover.component.ts +++ b/projects/coreui-angular/src/lib/popover/popover/popover.component.ts @@ -15,6 +15,14 @@ import { TooltipComponentBase } from '../../tooltip/tooltip/tooltip-component-ba export class PopoverComponent extends TooltipComponentBase { protected readonly prefix = 'popover'; + /** + * Fades the popover in and out. + * @returns boolean + * @default true + * @since 5.7.45 + */ + readonly animation = input(true, { transform: booleanAttribute }); + /** * Content of popover * @returns string | TemplateRef diff --git a/projects/coreui-angular/src/lib/tooltip/tooltip-directive-base.spec.ts b/projects/coreui-angular/src/lib/tooltip/tooltip-directive-base.spec.ts new file mode 100644 index 00000000..71bd9250 --- /dev/null +++ b/projects/coreui-angular/src/lib/tooltip/tooltip-directive-base.spec.ts @@ -0,0 +1,623 @@ +import { Binding, effect, inputBinding, outputBinding, signal, WritableSignal } from '@angular/core'; +import { DirectiveFixture, TestBed } from '@angular/core/testing'; +import { expect, vi } from 'vitest'; +import { PopoverDirective } from '../popover/popover.directive'; +import { TooltipDirective } from './tooltip.directive'; + +describe.each([ + { type: TooltipDirective, prefix: 'cTooltip', selector: '.tooltip' }, + { type: PopoverDirective, prefix: 'cPopover', selector: '.popover' } +])('$prefix delay and animation', ({ type, prefix, selector }) => { + let content: WritableSignal; + let visible: WritableSignal; + let changes: boolean[]; + let fixture: DirectiveFixture; + let intersect: IntersectionObserverCallback; + + beforeEach(() => { + (globalThis as any).IntersectionObserver = class { + constructor(callback: IntersectionObserverCallback) { + intersect = callback; + } + observe = vi.fn(); + unobserve = vi.fn(); + disconnect = vi.fn(); + }; + vi.useFakeTimers(); + content = signal('content'); + visible = signal(false); + changes = []; + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.useRealTimers(); + }); + + const create = (...bindings: Binding[]) => { + fixture = TestBed.createDirective(type, { + tagName: 'button', + bindings: [ + inputBinding(prefix, content), + inputBinding(`${prefix}Visible`, visible), + outputBinding(`${prefix}VisibleChange`, (value) => { + visible.set(value); + changes.push(value); + }), + ...bindings + ] + }); + fixture.autoDetectChanges(); + }; + + const createOneWay = (change: (value: boolean) => unknown = vi.fn(), ...bindings: Binding[]) => { + fixture = TestBed.createDirective(type, { + tagName: 'button', + bindings: [ + inputBinding(prefix, content), + inputBinding(`${prefix}Delay`, () => ({ hide: 400 })), + inputBinding(`${prefix}Visible`, visible), + outputBinding(`${prefix}VisibleChange`, (value) => { + changes.push(value); + change(value); + }), + ...bindings + ] + }); + fixture.autoDetectChanges(); + }; + + const fire = (name: string) => { + fixture.nativeElement.dispatchEvent(new Event(name)); + fixture.detectChanges(); + }; + + const wait = async (time: number) => { + await vi.advanceTimersByTimeAsync(time); + fixture.detectChanges(); + }; + + const show = async (time = 1000) => { + fire('mouseenter'); + await wait(time); + changes.length = 0; + }; + + const bubble = () => document.querySelector(selector) as HTMLElement | null; + + const state = () => { + const classes = bubble()?.classList; + if (!classes) { + return 'absent'; + } + return classes.contains('d-none') ? 'waiting' : classes.contains('show') ? 'shown' : 'hiding'; + }; + + it('should show 150 ms after its trigger and hide at once by default', async () => { + create(); + fire('mouseenter'); + expect(changes).toEqual([true]); + await wait(149); + expect(state()).toBe('waiting'); + await wait(1); + expect(state()).toBe('shown'); + fire('mouseleave'); + expect(changes).toEqual([true, false]); + expect(state()).toBe('hiding'); + await wait(299); + expect(state()).toBe('hiding'); + await wait(1); + expect(state()).toBe('absent'); + }); + + it.each([ + ['a number', 400, 400, 400], + ['a numeric string', '400', 400, 400], + ['an object', { show: 400, hide: 200 }, 400, 200], + ['an object without hide', { show: 400 }, 400, 0], + ['an object without show', { hide: 400 }, 150, 400], + ['zero', 0, 0, 0], + ['null', null, 150, 0], + ['undefined', undefined, 150, 0], + ['not a number', 'soon', 150, 0] + ])('should delay showing and hiding by %s', async (_, delay, showDelay, hideDelay) => { + create(inputBinding(`${prefix}Delay`, () => delay)); + fire('mouseenter'); + expect(changes).toEqual([true]); + if (showDelay) { + await wait(showDelay - 1); + expect(state()).toBe('waiting'); + } + await wait(1); + expect(state()).toBe('shown'); + fire('mouseleave'); + if (hideDelay) { + await wait(hideDelay - 1); + expect(state()).toBe('shown'); + expect(changes).toEqual([true]); + expect(fixture.nativeElement.hasAttribute('aria-describedby')).toBe(true); + await wait(1); + } + expect(changes).toEqual([true, false]); + expect(state()).toBe('hiding'); + expect(fixture.nativeElement.hasAttribute('aria-describedby')).toBe(false); + }); + + it('should drop the show at once when its trigger ends before the show delay', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ show: 400, hide: 1000 }))); + fire('mouseenter'); + await wait(399); + fire('mouseleave'); + expect(changes).toEqual([true, false]); + await wait(299); + expect(state()).toBe('waiting'); + await wait(1); + expect(state()).toBe('absent'); + await wait(1000); + expect(state()).toBe('absent'); + }); + + it('should drop the show at once when its trigger ends before change detection', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ show: 0, hide: 1000 }))); + fixture.nativeElement.dispatchEvent(new Event('mouseenter')); + fixture.nativeElement.dispatchEvent(new Event('mouseleave')); + expect(changes).toEqual([true, false]); + fixture.detectChanges(); + await wait(1); + expect(state()).toBe('absent'); + }); + + it('should show again after its trigger starts and ends before change detection', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ hide: 400 }))); + await show(); + fire('mouseleave'); + await wait(1000); + expect(state()).toBe('absent'); + fixture.nativeElement.dispatchEvent(new Event('mouseenter')); + fixture.nativeElement.dispatchEvent(new Event('mouseleave')); + await wait(100); + fire('mouseenter'); + await wait(1000); + expect(state()).toBe('shown'); + }); + + it('should stay when its trigger starts again before the hide delay', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ hide: 400 }))); + await show(); + fire('mouseleave'); + await wait(399); + expect(state()).toBe('shown'); + fire('mouseenter'); + await wait(1000); + expect(state()).toBe('shown'); + expect(changes).toEqual([]); + }); + + it('should count the hide delay from the last end of a trigger', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ hide: 400 }))); + await show(); + fire('mouseleave'); + await wait(300); + fire('mouseenter'); + fire('mouseleave'); + await wait(399); + expect(state()).toBe('shown'); + await wait(1); + expect(state()).toBe('hiding'); + expect(changes).toEqual([false]); + }); + + it('should delay both clicks of a click trigger', async () => { + create( + inputBinding(`${prefix}Trigger`, () => 'click'), + inputBinding(`${prefix}Delay`, () => ({ show: 400, hide: 200 })) + ); + fire('click'); + await wait(399); + expect(state()).toBe('waiting'); + await wait(1); + expect(state()).toBe('shown'); + fire('click'); + await wait(199); + expect(state()).toBe('shown'); + await wait(1); + expect(state()).toBe('hiding'); + }); + + it.each([ + ['clicked', ['click', 'click', 'click']], + ['clicked after blur', ['click', 'blur', 'click']] + ])('should start the hide delay again when it is %s again inside it', async (_, events) => { + create( + inputBinding(`${prefix}Trigger`, () => 'click'), + inputBinding(`${prefix}Delay`, () => ({ hide: 400 })) + ); + fire(events[0]); + await wait(1000); + fire(events[1]); + await wait(300); + fire(events[2]); + await wait(399); + expect(state()).toBe('shown'); + expect(changes).toEqual([true]); + await wait(1); + expect(state()).toBe('hiding'); + expect(changes).toEqual([true, false]); + }); + + it('should hide when its trigger starts and ends again before change detection', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ hide: 400 }))); + await show(); + const host = fixture.nativeElement; + host.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); + host.dispatchEvent(new Event('mouseenter')); + host.dispatchEvent(new Event('mouseleave')); + await wait(399); + expect(state()).toBe('shown'); + await wait(1); + expect(state()).toBe('hiding'); + }); + + it('should keep the hide delay when another input changes', async () => { + const delay = signal({ hide: 400 }); + create(inputBinding(`${prefix}Delay`, delay)); + await show(); + fire('mouseleave'); + await wait(100); + delay.set({ hide: 1000 }); + content.set('other'); + fixture.detectChanges(); + await wait(299); + expect(state()).toBe('shown'); + await wait(1); + expect(state()).toBe('hiding'); + }); + + it('should not stay after its trigger ends while the content is empty', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ hide: 400 }))); + await show(); + content.set(''); + fixture.detectChanges(); + fire('mouseleave'); + content.set('content'); + fixture.detectChanges(); + expect(state()).toBe('hiding'); + }); + + it('should hide at once when the content empties inside the hide delay and for good when the delay ends', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ hide: 400 }))); + await show(); + fire('mouseleave'); + await wait(100); + content.set(''); + fixture.detectChanges(); + expect(state()).toBe('hiding'); + content.set('content'); + fixture.detectChanges(); + expect(state()).toBe('shown'); + await wait(300); + expect(state()).toBe('hiding'); + expect(changes).toEqual([false]); + await wait(300); + expect(state()).toBe('absent'); + expect(fixture.nativeElement.hasAttribute('aria-describedby')).toBe(false); + }); + + it('should hide at once on Escape inside the hide delay', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ hide: 400 }))); + await show(); + fire('mouseleave'); + await wait(100); + const escape = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }); + fixture.nativeElement.dispatchEvent(escape); + fixture.detectChanges(); + expect(escape.defaultPrevented).toBe(true); + expect(state()).toBe('hiding'); + await wait(1000); + expect(changes).toEqual([false]); + }); + + it('should let Escape through and drop the show inside the show delay', async () => { + create(inputBinding(`${prefix}Delay`, () => 400)); + fire('mouseenter'); + await wait(399); + const reached = vi.fn(); + document.addEventListener('keydown', reached); + const escape = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }); + fixture.nativeElement.dispatchEvent(escape); + document.removeEventListener('keydown', reached); + fixture.detectChanges(); + expect(escape.defaultPrevented).toBe(false); + expect(reached).toHaveBeenCalled(); + expect(changes).toEqual([true, false]); + await wait(1000); + expect(state()).toBe('absent'); + }); + + it('should let a second Escape through before change detection', async () => { + create(); + await show(); + const press = () => { + const escape = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }); + fixture.nativeElement.dispatchEvent(escape); + return escape.defaultPrevented; + }; + expect([press(), press()]).toEqual([true, false]); + }); + + it('should hide at once when the page hides it', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ hide: 400 }))); + await show(); + visible.set(false); + fixture.detectChanges(); + expect(state()).toBe('hiding'); + }); + + it('should hide at once when the page hides it inside the hide delay', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ hide: 400 }))); + await show(); + fire('mouseleave'); + await wait(100); + visible.set(false); + fixture.detectChanges(); + expect(state()).toBe('hiding'); + await wait(1000); + expect(state()).toBe('absent'); + expect(changes).toEqual([]); + }); + + it('should hide at once when the page shows and hides it inside the hide delay', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ hide: 400 }))); + await show(); + fire('mouseleave'); + await wait(100); + visible.set(true); + fixture.detectChanges(); + expect(state()).toBe('shown'); + visible.set(false); + fixture.detectChanges(); + expect(state()).toBe('hiding'); + }); + + it('should hide after the hide delay when the page shows it inside the delay', async () => { + createOneWay(); + await show(); + fire('mouseleave'); + await wait(100); + visible.set(true); + fixture.detectChanges(); + await wait(299); + expect(state()).toBe('shown'); + await wait(1); + expect(state()).toBe('hiding'); + }); + + it('should stay when the page shows it again in the turn of Escape inside the hide delay', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ hide: 400 }))); + await show(); + fire('mouseleave'); + await wait(100); + fixture.nativeElement.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); + fixture.directiveInstance.visible.set(true); + await wait(1000); + expect(state()).toBe('shown'); + }); + + it('should stay when the page shows it again through its input on Escape inside the hide delay', async () => { + createOneWay((value) => !value && visible.set(true)); + await show(); + fire('mouseleave'); + await wait(100); + fixture.nativeElement.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); + fixture.detectChanges(); + await wait(1000); + expect(state()).toBe('shown'); + }); + + it('should stay when the page hides and shows it in one turn inside the hide delay', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ hide: 400 }))); + await show(); + fire('mouseleave'); + await wait(100); + fixture.directiveInstance.visible.set(false); + fixture.directiveInstance.visible.set(true); + await wait(1000); + expect(state()).toBe('shown'); + }); + + it('should hide when the page accepts the changes late', async () => { + createOneWay((value) => setTimeout(() => visible.set(value), 250)); + fire('mouseenter'); + await wait(200); + fire('mouseleave'); + await wait(2000); + expect(visible()).toBe(false); + expect(state()).toBe('absent'); + }); + + it('should hide on the next click after the page keeps it open past the hide delay', async () => { + let busy = true; + create( + inputBinding(`${prefix}Trigger`, () => 'click'), + inputBinding(`${prefix}Delay`, () => ({ hide: 400 })), + outputBinding(`${prefix}VisibleChange`, (value) => { + if (!value && busy) { + fixture.directiveInstance.visible.set(true); + } + }) + ); + fire('click'); + await wait(1000); + fire('click'); + await wait(1000); + expect(state()).toBe('shown'); + busy = false; + fire('click'); + await wait(400); + expect(state()).toBe('hiding'); + }); + + it('should hide on the next click after the page keeps it open through its input past the hide delay', async () => { + let busy = true; + createOneWay( + (value) => !value && busy && visible.set(true), + inputBinding(`${prefix}Trigger`, () => 'click') + ); + fire('click'); + await wait(1000); + fire('click'); + await wait(1000); + expect(state()).toBe('shown'); + busy = false; + fire('click'); + await wait(399); + expect(state()).toBe('shown'); + await wait(1); + expect(state()).toBe('hiding'); + }); + + it.each([ + ['hide', false], + ['show', true] + ])('should hide when its trigger ends in the %s listener of the page that shows it again', async (_, ending) => { + let again = true; + create( + inputBinding(`${prefix}Trigger`, () => 'focus'), + inputBinding(`${prefix}Delay`, () => ({ hide: 400 })), + outputBinding(`${prefix}VisibleChange`, (value) => { + if (!value && again) { + again = false; + fixture.directiveInstance.visible.set(true); + } + if (value === ending && !again) { + fixture.nativeElement.dispatchEvent(new Event('blur')); + } + }) + ); + fire('focus'); + await wait(1000); + fixture.nativeElement.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); + await wait(399); + expect(state()).toBe('shown'); + await wait(1); + expect(state()).toBe('hiding'); + }); + + it('should hide 100 ms after its reference leaves the viewport inside the hide delay', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ hide: 1000 }))); + await show(); + fire('mouseleave'); + intersect( + [{ target: fixture.nativeElement, isIntersecting: false } as unknown as IntersectionObserverEntry], + {} as IntersectionObserver + ); + await wait(100); + expect(state()).toBe('hiding'); + await wait(2000); + expect(changes).toEqual([false]); + }); + + it('should leave no timer and report nothing when it is destroyed inside the hide delay', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ hide: 400 }))); + await show(); + fire('mouseleave'); + fixture.destroy(); + expect(state()).toBe('absent'); + await vi.advanceTimersByTimeAsync(100); + expect(vi.getTimerCount()).toBe(0); + expect(changes).toEqual([]); + }); + + it.each([ + ['starts', 'focus'], + ['ends', 'blur'], + ['toggles', 'click'] + ])('should not make an effect that %s its trigger depend on it', async (_, name) => { + const delay = signal({ hide: 400 }); + create( + inputBinding(`${prefix}Trigger`, () => ['focus', 'click']), + inputBinding(`${prefix}Delay`, delay) + ); + if (name !== 'focus') { + fire('focus'); + await wait(1000); + } + const run = vi.fn(() => fixture.nativeElement.dispatchEvent(new Event(name))); + TestBed.runInInjectionContext(() => effect(run)); + TestBed.tick(); + expect(run).toHaveBeenCalledTimes(1); + delay.set({ hide: 500 }); + await wait(1000); + expect(state()).toBe(name === 'focus' ? 'shown' : 'absent'); + expect(run).toHaveBeenCalledTimes(1); + }); + + it('should restart the show delay when it shows again inside the show delay', async () => { + create(inputBinding(`${prefix}Delay`, () => ({ show: 400 }))); + fire('mouseenter'); + await wait(300); + fire('mouseleave'); + await wait(100); + fire('mouseenter'); + await wait(399); + expect(state()).toBe('waiting'); + await wait(1); + expect(state()).toBe('shown'); + }); + + it('should leave Popper alone when the delay changes while shown', async () => { + const delay = signal({ show: 100 }); + create(inputBinding(`${prefix}Delay`, delay)); + await show(); + const measure = vi.spyOn(fixture.nativeElement, 'getBoundingClientRect'); + delay.set({ show: 200 }); + fixture.detectChanges(); + await wait(0); + expect(measure).not.toHaveBeenCalled(); + }); + + it('should fade by default', async () => { + create(); + await show(); + expect(bubble()?.classList.contains('fade')).toBe(true); + }); + + it('should neither fade nor wait for the fade without animation', async () => { + create(inputBinding(`${prefix}Animation`, () => false)); + await show(); + expect(bubble()?.classList.contains('fade')).toBe(false); + fire('mouseleave'); + await wait(0); + expect(state()).toBe('absent'); + }); + + it('should follow the animation while shown', async () => { + const animation = signal(true); + create(inputBinding(`${prefix}Animation`, animation)); + await show(); + animation.set(false); + fixture.detectChanges(); + expect(bubble()?.classList.contains('fade')).toBe(false); + expect(state()).toBe('shown'); + animation.set(true); + fixture.detectChanges(); + fire('mouseleave'); + await wait(299); + expect(state()).toBe('hiding'); + await wait(1); + expect(state()).toBe('absent'); + }); + + it('should show again after the animation changed while hidden', async () => { + const animation = signal(true); + create(inputBinding(`${prefix}Animation`, animation)); + await show(); + fire('mouseleave'); + await wait(1000); + animation.set(false); + fixture.detectChanges(); + fire('mouseenter'); + await wait(1000); + expect(state()).toBe('shown'); + }); +}); diff --git a/projects/coreui-angular/src/lib/tooltip/tooltip-directive-base.ts b/projects/coreui-angular/src/lib/tooltip/tooltip-directive-base.ts index e5310b3b..21479dbe 100644 --- a/projects/coreui-angular/src/lib/tooltip/tooltip-directive-base.ts +++ b/projects/coreui-angular/src/lib/tooltip/tooltip-directive-base.ts @@ -9,7 +9,10 @@ import { ElementRef, inject, InputSignal, + InputSignalWithTransform, + linkedSignal, ModelSignal, + numberAttribute, OnDestroy, OnInit, PLATFORM_ID, @@ -29,6 +32,11 @@ import { IListenersConfig, IntersectionService, ListenersService } from '../serv import { ElementRefDirective } from '../shared'; import { TooltipComponentBase } from './tooltip/tooltip-component-base'; +export type TooltipDelay = number | { show?: number; hide?: number }; + +export const delayAttribute = (value: TooltipDelay | string | null | undefined): TooltipDelay => + typeof value === 'object' ? (value ?? {}) : numberAttribute(value); + @Directive() export abstract class TooltipDirectiveBase implements OnDestroy, OnInit, AfterViewChecked { readonly #renderer = inject(Renderer2); @@ -40,12 +48,15 @@ export abstract class TooltipDirectiveBase implements OnDestroy, OnInit, AfterVi readonly #isServer = isPlatformServer(inject(PLATFORM_ID)); #timerId1: ReturnType | undefined; #timerId2: ReturnType | undefined; + #endingId: ReturnType | undefined; protected abstract readonly component: Type; protected abstract readonly offset: number; protected abstract readonly tooltipId: string; + abstract readonly animation: InputSignalWithTransform; abstract readonly content: InputSignal | undefined>; + abstract readonly delay: InputSignalWithTransform; abstract readonly placement: InputSignal<'top' | 'bottom' | 'left' | 'right'>; abstract readonly popperOptions: InputSignal>; abstract readonly reference: InputSignal; @@ -80,6 +91,14 @@ export abstract class TooltipDirectiveBase implements OnDestroy, OnInit, AfterVi onCleanup(() => subscription.unsubscribe()); }); + readonly #delay = computed(() => { + const delay = this.delay(); + const { show, hide } = typeof delay === 'number' ? { show: delay, hide: delay } : delay; + return { show: numberAttribute(show, 150), hide: numberAttribute(hide, 0) }; + }); + + readonly #ending = linkedSignal({ source: () => this.visible(), computation: () => false }); + readonly #shown = computed(() => !this.#isServer && this.visible() && !!this.content()); readonly #visibleEffect = afterRenderEffect({ @@ -94,7 +113,7 @@ export abstract class TooltipDirectiveBase implements OnDestroy, OnInit, AfterVi if (event.key !== 'Escape') { return; } - if (this.#shown()) { + if (this.#revealed()) { event.preventDefault(); event.stopPropagation(); } @@ -128,6 +147,7 @@ export abstract class TooltipDirectiveBase implements OnDestroy, OnInit, AfterVi ngOnDestroy(): void { this.clearListeners(); + clearTimeout(this.#endingId); this.destroyTooltipElement(); this.#syncAriaDescribedBy(false); } @@ -150,18 +170,42 @@ export abstract class TooltipDirectiveBase implements OnDestroy, OnInit, AfterVi hostElement: this.#hostElement, trigger: this.trigger(), callbackToggle: () => { - this.visible.update((value) => !value); + untracked(() => (this.visible() ? this.#end() : this.#start())); }, callbackOff: () => { - this.visible.set(false); + untracked(() => this.#end()); }, callbackOn: () => { - this.visible.set(true); + this.#start(); } }; this.#listenersService.setListeners(config); } + #start(): void { + this.#ending.set(false); + this.visible.set(true); + } + + #end(): void { + const { hide } = this.#delay(); + clearTimeout(this.#endingId); + if (hide > 0 && this.#revealed()) { + this.#ending.set(true); + this.#endingId = setTimeout(() => { + if (this.#ending()) { + this.visible.set(false); + } + }, hide); + return; + } + this.visible.set(false); + } + + #revealed(): boolean { + return this.visible() && !!this.tooltipRef?.instance.visible(); + } + private clearListeners(): void { this.#listenersService.clearListeners(); } @@ -187,6 +231,7 @@ export abstract class TooltipDirectiveBase implements OnDestroy, OnInit, AfterVi this.createTooltipElement(); } + this.tooltipRef?.setInput('animation', this.animation()); this.tooltipRef?.setInput('content', this.content() ?? ''); if (this.popperInstance) { @@ -200,7 +245,7 @@ export abstract class TooltipDirectiveBase implements OnDestroy, OnInit, AfterVi if (this.#timerId1 === undefined) { this.#reveal(); } else { - this.#timerId1 = setTimeout(() => this.#reveal(), 150); + this.#scheduleReveal(); } } this.popperInstance.update(); @@ -209,13 +254,12 @@ export abstract class TooltipDirectiveBase implements OnDestroy, OnInit, AfterVi this.tooltip = this.tooltipRef?.location.nativeElement; this.#renderer.addClass(this.tooltip, 'd-none'); - this.#renderer.addClass(this.tooltip, 'fade'); this.#viewContainerRef.insert(this.tooltipRef.hostView); this.#renderer.appendChild(this.#document.body, this.tooltip); this.#createPopper(); - this.#timerId1 = setTimeout(() => this.#reveal(), 150); + this.#scheduleReveal(); } #createPopper(): void { @@ -224,6 +268,10 @@ export abstract class TooltipDirectiveBase implements OnDestroy, OnInit, AfterVi }); } + #scheduleReveal(): void { + this.#timerId1 = setTimeout(() => this.#reveal(), untracked(this.#delay).show); + } + #reveal(): void { this.#renderer.removeClass(this.tooltip, 'd-none'); this.tooltipRef?.setInput('visible', this.visible()); @@ -237,6 +285,7 @@ export abstract class TooltipDirectiveBase implements OnDestroy, OnInit, AfterVi return; } + const fadeTime = untracked(this.animation) ? 300 : 0; clearTimeout(this.#timerId2); this.#timerId2 = setTimeout(() => { const index = this.#viewContainerRef.indexOf(this.tooltipRef.hostView); @@ -246,7 +295,7 @@ export abstract class TooltipDirectiveBase implements OnDestroy, OnInit, AfterVi this.popperInstance?.destroy(); this.popperInstance = undefined; this.#timerId2 = undefined; - }, 300); + }, fadeTime); this.tooltipRef.setInput('visible', false); } diff --git a/projects/coreui-angular/src/lib/tooltip/tooltip.directive.ts b/projects/coreui-angular/src/lib/tooltip/tooltip.directive.ts index f702caf1..4f962c17 100644 --- a/projects/coreui-angular/src/lib/tooltip/tooltip.directive.ts +++ b/projects/coreui-angular/src/lib/tooltip/tooltip.directive.ts @@ -1,11 +1,11 @@ -import { Directive, inject, input, model, TemplateRef } from '@angular/core'; +import { booleanAttribute, Directive, inject, input, model, TemplateRef } from '@angular/core'; import { Options } from '@popperjs/core'; import { Triggers } from '../coreui.types'; import { ListenersService, UIDService } from '../services'; import { ElementRefDirective } from '../shared'; import { TooltipComponent } from './tooltip/tooltip.component'; -import { TooltipDirectiveBase } from './tooltip-directive-base'; +import { delayAttribute, TooltipDelay, TooltipDirectiveBase } from './tooltip-directive-base'; @Directive({ selector: '[cTooltip]', @@ -17,12 +17,31 @@ export class TooltipDirective extends TooltipDirectiveBase { protected readonly offset = 5; protected readonly tooltipId = inject(UIDService).getUID('tooltip'); + /** + * Fades the tooltip in and out. + * @returns boolean + * @default true + * @since 5.7.45 + */ + readonly animation = input(true, { alias: 'cTooltipAnimation', transform: booleanAttribute }); + /** * Content of tooltip * @returns string | TemplateRef | undefined */ readonly content = input | undefined>(undefined, { alias: 'cTooltip' }); + /** + * Delay in ms: `show` before the tooltip appears, `hide` after its trigger ends. A number sets both. + * @returns number | { show?: number; hide?: number } + * @default { show: 150, hide: 0 } + * @since 5.7.45 + */ + readonly delay = input( + {}, + { alias: 'cTooltipDelay', transform: delayAttribute } + ); + /** * Describes the placement of your component after Popper.js has applied all the modifiers that may have flipped or altered the originally provided placement property. * @returns 'top' | 'bottom' | 'left' | 'right' diff --git a/projects/coreui-angular/src/lib/tooltip/tooltip/tooltip-component-base.ts b/projects/coreui-angular/src/lib/tooltip/tooltip/tooltip-component-base.ts index 4431c5eb..bad46739 100644 --- a/projects/coreui-angular/src/lib/tooltip/tooltip/tooltip-component-base.ts +++ b/projects/coreui-angular/src/lib/tooltip/tooltip/tooltip-component-base.ts @@ -18,6 +18,7 @@ export abstract class TooltipComponentBase implements OnDestroy { protected abstract readonly prefix: string; + abstract readonly animation: InputSignalWithTransform; abstract readonly content: InputSignal>; abstract readonly visible: InputSignalWithTransform; @@ -31,7 +32,8 @@ export abstract class TooltipComponentBase implements OnDestroy { readonly hostClasses = computed(() => { return { [this.prefix]: true, - fade: true, + fade: this.animation(), + invisible: !this.animation() && !this.visible(), show: this.visible(), [`bs-${this.prefix}-auto`]: true } as Record; diff --git a/projects/coreui-angular/src/lib/tooltip/tooltip/tooltip.component.spec.ts b/projects/coreui-angular/src/lib/tooltip/tooltip/tooltip.component.spec.ts index f105c789..4abce3c6 100644 --- a/projects/coreui-angular/src/lib/tooltip/tooltip/tooltip.component.spec.ts +++ b/projects/coreui-angular/src/lib/tooltip/tooltip/tooltip.component.spec.ts @@ -1,26 +1,35 @@ -import { Component } from '@angular/core'; -import { TestBed } from '@angular/core/testing'; +import { Component, signal } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { TooltipComponent } from './tooltip.component'; @Component({ - template: '', + template: ` + + + `, imports: [TooltipComponent] }) -class TestComponent {} +class TestComponent { + readonly animation = signal(true); + readonly visible = signal(false); +} describe('TooltipComponent', () => { let component: TooltipComponent; let element: HTMLElement; + let boundElement: HTMLElement; + let fixture: ComponentFixture; beforeEach(async () => { - const fixture = TestBed.createComponent(TestComponent); + fixture = TestBed.createComponent(TestComponent); await fixture.whenStable(); - const debugElement = fixture.debugElement.query(By.directive(TooltipComponent)); + const [debugElement, boundDebugElement] = fixture.debugElement.queryAll(By.directive(TooltipComponent)); component = debugElement.componentInstance; element = debugElement.nativeElement; + boundElement = boundDebugElement.nativeElement; }); it('should create', () => { @@ -32,6 +41,23 @@ describe('TooltipComponent', () => { expect(element.classList.contains('fade')).toBe(true); }); + it('should not fade without animation', async () => { + fixture.componentInstance.animation.set(false); + await fixture.whenStable(); + expect(boundElement.classList.contains('tooltip')).toBe(true); + expect(boundElement.classList.contains('fade')).toBe(false); + }); + + it('should be hidden without animation while not visible', async () => { + expect(boundElement.classList.contains('invisible')).toBe(false); + fixture.componentInstance.animation.set(false); + await fixture.whenStable(); + expect(boundElement.classList.contains('invisible')).toBe(true); + fixture.componentInstance.visible.set(true); + await fixture.whenStable(); + expect(boundElement.classList.contains('invisible')).toBe(false); + }); + it('should not have the popover css classes', () => { expect(element.classList.contains('popover')).toBe(false); expect(element.classList.contains('bs-popover-auto')).toBe(false); diff --git a/projects/coreui-angular/src/lib/tooltip/tooltip/tooltip.component.ts b/projects/coreui-angular/src/lib/tooltip/tooltip/tooltip.component.ts index dba5399e..7841f60d 100644 --- a/projects/coreui-angular/src/lib/tooltip/tooltip/tooltip.component.ts +++ b/projects/coreui-angular/src/lib/tooltip/tooltip/tooltip.component.ts @@ -15,6 +15,14 @@ import { TooltipComponentBase } from './tooltip-component-base'; export class TooltipComponent extends TooltipComponentBase { protected readonly prefix = 'tooltip'; + /** + * Fades the tooltip in and out. + * @returns boolean + * @default true + * @since 5.7.45 + */ + readonly animation = input(true, { transform: booleanAttribute }); + /** * Content of tooltip * @returns string | TemplateRef