link-channel.js 5.88 KB
/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright 2012 Adobe Systems Incorporated
 * All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
 */
(function(window, document, $, i18n) {
    'use strict';

    // class of the channels card
    var channels = '.screens-ChannelCollection';

    // id of the modal form
    var modal = '.screens-dcc-actions-assignchannel-dialog';

    // Constrain the role to be unique
    var constrainRole = function(exclude) {
        var currentValues = $('.foundation-collection-item', channels).map(function() {
            var role = $(this).find('.screens-ChannelLink-role').attr('value');
            return exclude && role === exclude ? null : role; // Filter out the exclude if specified
        });
        $('input[name="./role"]', modal).attr('pattern',
            currentValues.length ? '^(?!.*(^|\\s)(' + currentValues.get().join('|') + ')(\\s|$)).*$' : '.*');
    };

    $(document).on('coral-overlay:open', modal, function(e) {
        // Ignore if the omnisearch overlay is shown
        if ($('coral-overlay[open]').length) {
            return;
        }

        if (!$(e.target).is(modal)) {
            return;
        }
        var $modal = $(e.target);
        var $form = $modal.find('.coral-Form');
        constrainRole($('input[name="./role"]', $form).val());
    });

    // Ajax submit the channel linking form
    $(document).on('submit', modal, function(e) {
        // Ignore if the omnisearch overlay is shown
        if ($('coral-overlay[open]').length) {
            return true;
        }

        e.preventDefault();

        var $modal = $(modal);
        var $form = $modal.find('.coral-Form');

        // copy 'role' to 'name'
        var $role = $('input[name="./role"]', $form);
        var $name = $('input[name=":nameHint"]', $form);
        $name.val($role.val());

        // If the click event is set, make sure to also enable touchevents
        var $events = $('select[name="./events"]', $form);
        var eventsSuffix = '';
        if ($events.val() && $events.val().indexOf('click') > -1) {
            eventsSuffix += (['pointerup', 'touchend']).map(function(ev) { return '&.%2Fevents=' + ev; });
        }
        else if (!$events.val()) {
            // Force at least en empty value for the events
            $events.val('');
        }

        // Abort submission if role is not unique
        var $items = $('.foundation-collection-item').filter(function() {
            return $form.attr('action') !== this.getAttribute('data-foundation-collection-item-id')
                && this.getAttribute('data-foundation-collection-item-role') === $role.val();
        });
        var ui = $(window).adaptTo('foundation-ui');
        if ($items.length) {
            ui.alert(i18n.get('Error'), i18n.get('The channel role must be unique.'), 'error');
            return false;
        }

        $(modal).get(0).hide();

        ui.wait();
        $.ajax({
            method: 'POST',
            url: Granite.HTTP.externalize($form.attr('action')),
            data: $form.serialize() + eventsSuffix
        }).then(function(responseText) {
            // Only copy the offline config when we create a new assignment, not when we edit
            if ($form.attr('action').match(/\/$/)) {
                var resourcePath = $('#Location', responseText).text();

                // Update the offline content sync cache here as the HAF API does not yet allow to re-use the default
                // post servlet to update an assignment and the cache at the same time
                return $.ajax({
                    method: 'POST',
                    url: Granite.HTTP.externalize('/api/screens' + resourcePath + '.json'),
                    data: ':operation=update-cache'
                }).fail(function(jqXHR) { // eslint-disable-line max-nested-callbacks
                    var message = JSON.parse(jqXHR.responseText).properties['status.message']
                        || i18n.get('A server error occured while updating the assignment.');
                    ui.alert(i18n.get('Error'), message, 'error');
                });
            }
            return true;
        }).done(function(data, textStatus, jqXHR) {
            ui.clearWait();
            var content = $('.foundation-content').adaptTo('foundation-content');
            content.refresh();
            ui.notify(null, i18n.get('Channel assigned.'), 'success');
        }).fail(function(jqXHR) {
            ui.clearWait();
            var message = $('#Message', jqXHR.responseText).text();
            ui.alert(i18n.get('Error'), message, 'error');
        });
    });

    // Add cache busting parameter to the dialog src to make sure its data is updated after a modification
    // Remove once GRANITE-14378 has been tackled
    $(document).on('foundation-contentloaded', function(ev) {
        if ($('.screens-DisplayDashboard,.screens-ScheduleDashboard').length) {
            var $el = $('.screens-dcc-actions-ChannelLink-create-activator,.screens-dcc-actions-ChannelLink-edit-activator');
            $el.each(function(idx, el) {
                var action = $(el).data('foundationCollectionAction');
                action.data.src = action.data.src.replace(/[?&]t=\d+/, '');
                action.data.src += (action.data.src.match(/\?.*/) ? '&' : '?') + 't=' + Date.now();
                $(el).data('foundationCollectionAction', action);
            });
        }
    });

}(window, document, Granite.$, Granite.I18n));