NotificationItem.js 2.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
import {Component} from 'san';
import Icon from 'san-mui/Icon';

const typeMap = {
    success: 'check_circle',
    info: 'info',
    warning: 'error',
    error: 'cancel'
};

export default class NotificationItem extends Component {
    static template = `
    <div
        class="sm-notification {{customClass}} {{closed ? 'state-hidden' : 'state-open'}}"
        style="top: {{top}}px"
        on-mouseenter="clearTimer"
        on-mouseleave="startTimer"
        on-click="handleClick">
        <san-icon
            san-if="type"
            class="sm-notification-type type-{{type}}"
            size="50">{{iconType}}</san-icon>
        <div class="sm-notification-group" >
            <p class="sm-notification-title">{{title}}</p>
            <div class="sm-notification-content">{{message}}</div>
            <div on-click="close($event)" class="sm-notification-close">
                <san-icon size="20" class="sm-notification-close-btn">close</san-icon>
            </div>
        </div>
    </div>
    `;

    initData() {
        return {
            title: '',
            message: '',
            duration: 3000,
            closed: true
        };
    }

    static components = {
        'san-icon': Icon
    };

    static computed = {
        iconType() {
            return typeMap[this.data.get('type')];
        }
    };

    handleClick() {
        this.fire('itemClick');
    }

    /**
     * close
     *
     * @param {Object} e event Object
     */
    close(e) {
        if (e) {
            e.stopPropagation();
        }
        this.data.set('closed', true);
        this.el.addEventListener('transitionend', () => {
            this.fire('close');
        });
    }

    /**
     * clear timer
     */
    clearTimer() {
        clearTimeout(this.timer);
    }

    /**
     * start timet
     */
    startTimer() {
        const duration = this.data.get('duration');
        if (duration > 0) {
            this.timer = setTimeout(() => {
                if (!this.closed) {
                    this.close();
                }
            }, duration);
        }
    }

    attached() {
        if (this.el.parentNode !== document.body) {
            document.body.appendChild(this.el);
        }
        requestAnimationFrame(() => {
            this.data.set('closed', false);
        });

        this.startTimer();
    }

    detached() {
        this.clearTimer();
    }
}