All files / src/attributes ContentDragCustomAttribute.ts

100% Statements 16/16
100% Branches 2/2
100% Functions 3/3
100% Lines 13/13
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          1x 1x                               1x     1x   4x 2x 2x 1x   2x     2x     4x 4x 4x    
/**
 * @module Attributes
 * 
 */ /** */
 
import { DragTypes } from '../Enums';
import { bindable, autoinject } from 'aurelia-framework';
import { Content } from 'sn-client-js';
 
 
 
/**
 * Custom attribute that allows you to handle custom content or contentlist drag events on your HTML element.
 * Usage example:
 * ```html
 * <div class="my-draggable-contentlist-element" 
 *      content-drag.bind="[draggableContent1, draggableContent2]"></div>
 * ```
 * The defined *content array* should contain Content items with a valid Stringify() method.
 * This attribute will stop the event propagation for *drag & drop* events, so it can be nested.
 */
@autoinject
export class ContentDragCustomAttribute{
 
    @bindable({primaryProperty: true})
    content: Content[];
 
    dragStart: (ev: DragEvent) => boolean = (ev) => {
        ev.stopPropagation();
        if (this.content.length === 1) {
            ev.dataTransfer.setData(DragTypes.Content, this.content[0].Stringify());
        } else {
            ev.dataTransfer.setData(DragTypes.ContentList, `[${ this.content.map(c => JSON.stringify(c.Stringify())).join(',')}]`)
        }
 
        return true;
    }
 
    constructor(private element: Element) {
       this.element.setAttribute('draggable', 'true');
       this.element.addEventListener('dragstart', this.dragStart as (...args) => void);
    }
}