Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat( default behaviour ): pause notification kill-duration on mouseover then resume on mouseleave #109

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions cypress/integration/notyf_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,32 @@ context('Notyf', () => {
expect(pos.top).to.be.greaterThan(VIEWPORT_HEIGHT / 2);
});
});

it('should pause on mouseover', () => {

setConfiguration({ message: 'Notyf 1' })
cy.get('#success-btn').click()

setConfiguration({ message: 'Notyf 2' })
cy.get('#success-btn').click()

setConfiguration({ message: 'Notyf 3' })
cy.get('#success-btn').click()

cy.get('.notyf__toast:nth-child(2)').trigger('mouseover')

cy.wait(2000)

cy.get('.notyf').children().should('have.length', 1)

cy.get('.notyf__toast').trigger('mouseleave')

cy.wait(2000)

cy.get('.notyf__toast').should('not.be.exist')

})

});

describe('Global custom configuration', () => {
Expand Down
17 changes: 3 additions & 14 deletions src/notyf.models.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { INotyfNotificationOptions, DeepPartial, NotyfEvent } from './notyf.options';
import EventEmitter from './utils/classes/eventEmitter';

export interface INotyfEventPayload {
target: NotyfNotification;
Expand All @@ -7,20 +8,8 @@ export interface INotyfEventPayload {

export type NotyfEventCallback = (payload: INotyfEventPayload) => void;

export class NotyfNotification {
private listeners: Partial<Record<NotyfEvent, NotyfEventCallback[]>> = {};

constructor(public options: DeepPartial<INotyfNotificationOptions>) {}

public on(eventType: NotyfEvent, cb: NotyfEventCallback) {
const callbacks = this.listeners[eventType] || [];
this.listeners[eventType] = callbacks.concat([cb]);
}

private triggerEvent(eventType: NotyfEvent, event?: Event) {
const callbacks = this.listeners[eventType] || [];
callbacks.forEach((cb) => cb({ target: this, event }));
}
export class NotyfNotification extends EventEmitter<{ [ K in NotyfEvent ]: INotyfEventPayload }> {
constructor(public options: DeepPartial<INotyfNotificationOptions>) { super() }
}

export interface IRenderedNotification {
Expand Down
2 changes: 2 additions & 0 deletions src/notyf.options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export interface INotyfPosition {
export enum NotyfEvent {
Dismiss = 'dismiss',
Click = 'click',
MouseOver = 'mouseover',
MouseLeave = 'mouseleave'
}

export interface INotyfIcon {
Expand Down
25 changes: 17 additions & 8 deletions src/notyf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
NotyfEvent,
} from './notyf.options';
import { NotyfView } from './notyf.view';
import Timer from './utils/classes/timer';

/**
* Main controller class. Defines the main Notyf API.
Expand All @@ -29,12 +30,10 @@ export default class Notyf {

this.view.on(NotyfEvent.Dismiss, ({ target, event }) => {
this._removeNotification(target);
// tslint:disable-next-line: no-string-literal
target['triggerEvent'](NotyfEvent.Dismiss, event);
target.triggerEvent(NotyfEvent.Dismiss, { target, event });
});

// tslint:disable-next-line: no-string-literal
this.view.on(NotyfEvent.Click, ({ target, event }) => target['triggerEvent'](NotyfEvent.Click, event));
this.view.on(NotyfEvent.Click, ({ target, event }) => target.triggerEvent(NotyfEvent.Click, { target, event }));
}

public error(payload: string | Partial<INotyfNotificationOptions>) {
Expand Down Expand Up @@ -82,12 +81,22 @@ export default class Notyf {
}

private _pushNotification(notification: NotyfNotification) {
this.notifications.push(notification);

this.notifications.push( notification );

const duration =
notification.options.duration !== undefined ? notification.options.duration : this.options.duration;
if (duration) {
setTimeout(() => this._removeNotification(notification), duration);
}

if ( !duration ) return

const timer = new Timer( duration );

notification.on(NotyfEvent.MouseOver, () => timer.pause());

notification.on(NotyfEvent.MouseLeave, () => timer.resume());

timer.on('finished', () => this._removeNotification(notification) )

}

private _removeNotification(notification: NotyfNotification) {
Expand Down
8 changes: 8 additions & 0 deletions src/notyf.view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,14 @@ export class NotyfView {
this.events[NotyfEvent.Click]?.({ target: notification, event }),
);

notificationElem.addEventListener('mouseover', event =>
notification.triggerEvent(NotyfEvent.MouseOver, { target: notification, event })
)

notificationElem.addEventListener('mouseleave', event =>
notification.triggerEvent(NotyfEvent.MouseLeave, { target: notification, event })
)

// Adjust margins depending on whether its an upper or lower notification
const className = this.getYPosition(options) === 'top' ? 'upper' : 'lower';
notificationElem.classList.add(`notyf__toast--${className}`);
Expand Down
23 changes: 23 additions & 0 deletions src/utils/classes/eventEmitter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
type EventCallback<E> = (event: E) => void;

export default class EventEmitter< EventMap extends any > {

protected listeners: {

[K in keyof EventMap]?: EventCallback< EventMap[K] >[]

} = {}

constructor() {}

on<Event extends keyof EventMap>(eventType: Event, cb: EventCallback< EventMap[Event] >) {
const callbacks: EventCallback< EventMap[Event] >[] = this.listeners[eventType] ?? [];
this.listeners[eventType] = callbacks.concat([cb]);
}

triggerEvent<Event extends keyof EventMap>(eventType: Event, event: EventMap[ Event ]) {
const callbacks: EventCallback< EventMap[Event] >[] = this.listeners[eventType] ?? [];
callbacks.forEach((callback: EventCallback< EventMap[Event] >) => callback(event));
}

}
58 changes: 58 additions & 0 deletions src/utils/classes/timer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import EventEmitter from './eventEmitter';

type TimerEvents = "finished" | "pause" | "resume"
type TimerEventMap = Record<TimerEvents, undefined>

export default class Timer extends EventEmitter< TimerEventMap > {

private startTime: number = Date.now();

private timer: ReturnType<typeof setTimeout>;

private lastTime: number = Date.now();

get leftTime() {
return this.duration - (this.lastTime - this.startTime);
}

constructor( public duration: number ) {

super();

this.timer = setTimeout(() => {

this.triggerEvent('finished', undefined);

this.lastTime = Date.now();

}, duration);

}

pause() {

clearTimeout(this.timer);

this.lastTime = Date.now();

this.triggerEvent('pause', undefined);

}

resume() {

clearTimeout(this.timer);

this.timer = setTimeout(() => {

this.triggerEvent('finished', undefined);

this.lastTime = Date.now();

}, this.leftTime);

this.triggerEvent('resume', undefined);

}

}