<commit_before>TornadoFaces.declareWidget('Table', function () {
    var widget, items;

    this.init = function () {
        widget = this;
        items = widget.elem.find('tbody tr').not('.table-expand-row');
        widget.bindEvents();
    };

    this.getFilterFn = function () {
        var filterFn = widget.conf.filterFn;
        if (!filterFn) {
            filterFn = function (item, query) {
                return item.text().toUpperCase().indexOf(query.toUpperCase()) > -1;
            };
            widget.conf.filterFn = filterFn;
        }
        return filterFn;
    };

    this.setFilterFn = function (filterFn) {
        widget.conf.filterFn = filterFn;
    };

    this.filter = function (query) {
        var doHighlight = widget.conf.highlightFilter;

        if (!query || query.length == 0 || query === '') {
            items.show();
            if (doHighlight)
                items.unhighlight();
        } else {
            var filterFn = widget.getFilterFn();
            var length = items.length;

            for (var idx = 0; idx < length; idx++) {
                var item = $(items[idx]);
                if (doHighlight)
                    item.unhighlight();

                if (filterFn(item, query, idx)) {
                    item.removeClass('is-hidden');
                    if (doHighlight)
                        item.highlight(query);
                } else {
                    item.addClass('is-hidden');
                }
            }
        }
    };

    this.onExpandRow = function (event) {
        var tr = $(event.target).closest('tr');
        this.expandRow(tr);
        event.preventDefault();
        return false;
    };

    this.expandRow = function (tr) {
        var toggle = tr.find('.row-toggler:first');
        var rowKey = tr.data('rk');

        if (toggle.hasClass('open')) {
            toggle.removeClass('open');
            var expand = tr.next();
            if (expand.hasClass('table-expand-row'))
                expand.remove();
        } else {
            toggle.addClass('open');

            var tableId = widget.elem.attr('id');
            var expandId = widget.elem.find('tbody.expand').attr('id');

            var props = {
                'javax.faces.behavior.event': 'rowToggle',
                execute: tableId,
                render: expandId,
                onevent: function (e) {
                    if (e.status == 'success')
                        widget.elem.find('tbody.expand tr:first').detach().insertAfter(tr);
                }
            };

            props[tableId + '_expand'] = rowKey;

            jsf.ajax.request(tableId, null, props);
        }
    };

    this.onSelectRow = function (event) {
        var tr = $(event.target).closest('tr');
        this.selectRow(tr);
        if (widget.conf.onSelectRow)
            widget.conf.onSelectRow(widget, tr);
    };

    this.ensureRowInView = function (tr) {
        if (tr && tr[0] && tr[0].scrollIntoView) {
            tr[0].scrollIntoView();
        }
    };

    this.selectRow = function (tr) {
        if (tr.length == 0)
            return;

        var doSelect = !tr.hasClass('selected');

        if (doSelect) {
            if ('single' == widget.conf.selectionMode)
                this.unselectAllRows();

            tr.addClass('selected');
            widget.ensureRowInView(tr);

            if (widget.conf.behaviors && widget.conf.behaviors.rowSelect) {
                var behaviors = widget.conf.behaviors.rowSelect;
                var render = "", execute = "", onevent, onerror;

                for (var i = 0; i < behaviors.length; i++) {
                    var b = behaviors[i];
                    if (b.render)
                        render = (render + " " + b.render).trim();
                    if (b.execute)
                        execute = (execute + " " + b.execute).trim();
                    if (b.onevent)
                        onevent = b.onevent;
                    if (b.onerror)
                        onerror = b.onerror;
                }

                var props = {
                    'javax.faces.behavior.event': 'rowSelect',
                    render: render,
                    execute: execute
                };

                if (onevent)
                    props.onevent = new Function('data', onevent);

                if (onerror)
                    props.onerror = new Function('data', onerror);

                var id = widget.elem.attr('id');

                props[id + '_selected'] = tr.data('rk');
                props[id + '_selection'] = widget.getSelectedRowKeys().join();

                jsf.ajax.request(id, null, props);
            }
        } else {
            tr.removeClass('selected');
        }
    };

    this.getSelectedRowKeys = function () {
        return items.filter('.selected').map(function () {
            return $(this).data('rk');
        }).get();
    };

    this.unselectAllRows = function () {
        items.removeClass('selected');
    };

    this.focus = function () {
        this.elem.focus();
    };

    this.isVisible = function () {
        return widget.elem.css('visibility') == 'visible';
    };

    this.isEmpty = function () {
        return items.length == 0;
    };

    this.selectFirstRow = function () {
        this.selectRow(items.not('.is-hidden').first());
    };

    this.selectLastRow = function () {
        this.selectRow(items.not('.is-hidden').last());
    };

    this.selectNextRow = function () {
        var selected = items.filter('.selected:first');
        var next = selected.next('tr');
        while (next.length == 1 && next.hasClass('is-hidden'))
            next = next.next('tr');

        if (next.length == 1) {
            this.selectRow(next);
        } else {
            var nextTable = TornadoFaces.nextWidget(widget, function (w) {
                return w.type == 'Table' && w.conf.selectionMode == 'single' && !w.isEmpty() && w.isVisible();
            });

            if (nextTable) {
                this.unselectAllRows();
                nextTable.selectFirstRow();
                nextTable.focus();
            } else {
                this.selectFirstRow();
            }
        }
    };

    this.selectPreviousRow = function () {
        var selected = items.filter('.selected:first');
        var prev = selected.prev('tr');
        while (prev.length == 1 && prev.hasClass('is-hidden'))
            prev = prev.prev('tr');

        if (prev.length == 1) {
            this.selectRow(prev);
        } else {
            var prevTable = TornadoFaces.previousWidget(widget, function (w) {
                return w.type == 'Table' && w.conf.selectionMode == 'single' && !w.isEmpty() && w.isVisible();
            });
            if (prevTable) {
                this.unselectAllRows();
                prevTable.selectLastRow();
                prevTable.focus();
            } else {
                this.selectLastRow();
            }
        }
    };

    this.bindEvents = function () {
        if (widget.conf.selectionMode) {
            // click to select row
            items.click(this.onSelectRow);

            if (!widget.elem.attr('tabindex'))
                widget.elem.attr('tabindex', 0);

            // keyboard navigation
            widget.elem.on('keydown', function (e) {
                switch (e.keyCode) {
                    case 38:
                        widget.selectPreviousRow();
                        e.preventDefault();
                        return false;
                    case 40:
                        widget.selectNextRow();
                        e.preventDefault();
                        return false;
                    case 13:
                        var selected = items.filter('.selected:first');

                        if (widget.conf.clickFirstLinkOnEnter === true) {
                            widget.clickFirstLinkInRow(selected);
                            e.preventDefault();
                        } else if (widget.conf.onEnterPressed) {
                            widget.conf.onEnterPressed(selected, e);
                        }

                        return false;
                }
            });
        }

        // hook row-toggler action
        items.find('.row-toggler').click(this.onExpandRow);
    };

    this.clickFirstLinkInRow = function (tr) {
        var a = tr.find('a:first');
        if (a.length == 1)
            a[0].click();
    }
});

TornadoFaces.Table = {
    getFirstNonEmpty: function () {
        return TornadoFaces.widgetById($('table').not('.is-empty').attr('id'));
    },

    focusFirstNonEmpty: function () {
        var t = TornadoFaces.Table.getFirstNonEmpty();
        if (t) {
            t.selectFirstRow();
            t.elem[0].focus();
        }
    }
};<commit_msg>Table filter works<commit_after>TornadoFaces.declareWidget('Table', function () {
    var widget, items;

    this.init = function () {
        widget = this;
        items = widget.elem.find('tbody tr').not('.table-expand-row');
        widget.bindEvents();
    };

    this.getFilterFn = function () {
        var filterFn = widget.conf.filterFn;
        if (!filterFn) {
            filterFn = function (item, query) {
                return item.text().toUpperCase().indexOf(query.toUpperCase()) > -1;
            };
            widget.conf.filterFn = filterFn;
        }
        return filterFn;
    };

    this.setFilterFn = function (filterFn) {
        widget.conf.filterFn = filterFn;
    };

    this.filter = function (query) {
        var doHighlight = widget.conf.highlightFilter;
        var filterFn = widget.getFilterFn();
        var length = items.length;

        for (var idx = 0; idx < length; idx++) {
            var item = $(items[idx]);
            if (doHighlight)
                item.unhighlight();

            var skipFilter = query === undefined || query.length === 0 || query === '';

            if (skipFilter || filterFn(item, query, idx)) {
                item.removeClass('is-hidden');
                if (doHighlight)
                    item.highlight(query);
            } else {
                item.addClass('is-hidden');
            }
        }
    };

    this.onExpandRow = function (event) {
        var tr = $(event.target).closest('tr');
        this.expandRow(tr);
        event.preventDefault();
        return false;
    };

    this.expandRow = function (tr) {
        var toggle = tr.find('.row-toggler:first');
        var rowKey = tr.data('rk');

        if (toggle.hasClass('open')) {
            toggle.removeClass('open');
            var expand = tr.next();
            if (expand.hasClass('table-expand-row'))
                expand.remove();
        } else {
            toggle.addClass('open');

            var tableId = widget.elem.attr('id');
            var expandId = widget.elem.find('tbody.expand').attr('id');

            var props = {
                'javax.faces.behavior.event': 'rowToggle',
                execute: tableId,
                render: expandId,
                onevent: function (e) {
                    if (e.status == 'success')
                        widget.elem.find('tbody.expand tr:first').detach().insertAfter(tr);
                }
            };

            props[tableId + '_expand'] = rowKey;

            jsf.ajax.request(tableId, null, props);
        }
    };

    this.onSelectRow = function (event) {
        var tr = $(event.target).closest('tr');
        this.selectRow(tr);
        if (widget.conf.onSelectRow)
            widget.conf.onSelectRow(widget, tr);
    };

    this.ensureRowInView = function (tr) {
        if (tr && tr[0] && tr[0].scrollIntoView) {
            tr[0].scrollIntoView();
        }
    };

    this.selectRow = function (tr) {
        if (tr.length == 0)
            return;

        var doSelect = !tr.hasClass('selected');

        if (doSelect) {
            if ('single' == widget.conf.selectionMode)
                this.unselectAllRows();

            tr.addClass('selected');
            widget.ensureRowInView(tr);

            if (widget.conf.behaviors && widget.conf.behaviors.rowSelect) {
                var behaviors = widget.conf.behaviors.rowSelect;
                var render = "", execute = "", onevent, onerror;

                for (var i = 0; i < behaviors.length; i++) {
                    var b = behaviors[i];
                    if (b.render)
                        render = (render + " " + b.render).trim();
                    if (b.execute)
                        execute = (execute + " " + b.execute).trim();
                    if (b.onevent)
                        onevent = b.onevent;
                    if (b.onerror)
                        onerror = b.onerror;
                }

                var props = {
                    'javax.faces.behavior.event': 'rowSelect',
                    render: render,
                    execute: execute
                };

                if (onevent)
                    props.onevent = new Function('data', onevent);

                if (onerror)
                    props.onerror = new Function('data', onerror);

                var id = widget.elem.attr('id');

                props[id + '_selected'] = tr.data('rk');
                props[id + '_selection'] = widget.getSelectedRowKeys().join();

                jsf.ajax.request(id, null, props);
            }
        } else {
            tr.removeClass('selected');
        }
    };

    this.getSelectedRowKeys = function () {
        return items.filter('.selected').map(function () {
            return $(this).data('rk');
        }).get();
    };

    this.unselectAllRows = function () {
        items.removeClass('selected');
    };

    this.focus = function () {
        this.elem.focus();
    };

    this.isVisible = function () {
        return widget.elem.css('visibility') == 'visible';
    };

    this.isEmpty = function () {
        return items.length == 0;
    };

    this.selectFirstRow = function () {
        this.selectRow(items.not('.is-hidden').first());
    };

    this.selectLastRow = function () {
        this.selectRow(items.not('.is-hidden').last());
    };

    this.selectNextRow = function () {
        var selected = items.filter('.selected:first');
        var next = selected.next('tr');
        while (next.length == 1 && next.hasClass('is-hidden'))
            next = next.next('tr');

        if (next.length == 1) {
            this.selectRow(next);
        } else {
            var nextTable = TornadoFaces.nextWidget(widget, function (w) {
                return w.type == 'Table' && w.conf.selectionMode == 'single' && !w.isEmpty() && w.isVisible();
            });

            if (nextTable) {
                this.unselectAllRows();
                nextTable.selectFirstRow();
                nextTable.focus();
            } else {
                this.selectFirstRow();
            }
        }
    };

    this.selectPreviousRow = function () {
        var selected = items.filter('.selected:first');
        var prev = selected.prev('tr');
        while (prev.length == 1 && prev.hasClass('is-hidden'))
            prev = prev.prev('tr');

        if (prev.length == 1) {
            this.selectRow(prev);
        } else {
            var prevTable = TornadoFaces.previousWidget(widget, function (w) {
                return w.type == 'Table' && w.conf.selectionMode == 'single' && !w.isEmpty() && w.isVisible();
            });
            if (prevTable) {
                this.unselectAllRows();
                prevTable.selectLastRow();
                prevTable.focus();
            } else {
                this.selectLastRow();
            }
        }
    };

    this.bindEvents = function () {
        if (widget.conf.selectionMode) {
            // click to select row
            items.click(this.onSelectRow);

            if (!widget.elem.attr('tabindex'))
                widget.elem.attr('tabindex', 0);

            // keyboard navigation
            widget.elem.on('keydown', function (e) {
                switch (e.keyCode) {
                    case 38:
                        widget.selectPreviousRow();
                        e.preventDefault();
                        return false;
                    case 40:
                        widget.selectNextRow();
                        e.preventDefault();
                        return false;
                    case 13:
                        var selected = items.filter('.selected:first');

                        if (widget.conf.clickFirstLinkOnEnter === true) {
                            widget.clickFirstLinkInRow(selected);
                            e.preventDefault();
                        } else if (widget.conf.onEnterPressed) {
                            widget.conf.onEnterPressed(selected, e);
                        }

                        return false;
                }
            });
        }

        // hook row-toggler action
        items.find('.row-toggler').click(this.onExpandRow);
    };

    this.clickFirstLinkInRow = function (tr) {
        var a = tr.find('a:first');
        if (a.length == 1)
            a[0].click();
    }
});

TornadoFaces.Table = {
    getFirstNonEmpty: function () {
        return TornadoFaces.widgetById($('table').not('.is-empty').attr('id'));
    },

    focusFirstNonEmpty: function () {
        var t = TornadoFaces.Table.getFirstNonEmpty();
        if (t) {
            t.selectFirstRow();
            t.elem[0].focus();
        }
    }
};<|endoftext|>


<commit_before>import {tabelaParsing, tabelaCorrespondencia} from '../tabelaParsing';
import {palavraPorCodigo} from '../palavrasReservadas';
const VAZIO = 44;
const DIVISAO = 45;

function init(tokens) {
  this.tokens = tokens;
  this.posicao = 0;
  console.log('--2.', tabelaCorrespondencia);
  this.pilha.push(44);
  this.pilha.push(46);

  this.analisar();

}

function erro() {
  console.error('ERROR');
}

function analisar() {
  var topo = this.pilha.pop();
  console.log('topo', topo);

  var token = this.tokens[this.posicao++];
  console.log('token', token);

  var valor = tabelaParsing[topo][token.codigo];
  console.log('valor', valor);
  console.info('nolog', this.tokens.length ,'=', this.posicao);
  if (topo == token.codigo)
  {
    console.warn('this.pilhak', this.pilha);
    this.analisar();
    return;
    // topo = this.pilha.pop();
    // token =
    // console.log('[topo', topo);
    // console.log('[token', token);
    // console.warn('[this.pilha1', this.pilha);
  }

  if (topo == VAZIO && this.tokens.length == this.posicao-1 ) {
    console.log('SUCCESS');
    return;
  }
  else if (this.pilha.length < 1) {
    console.log('VAZIA');
    return;
  }
  else if (topo == VAZIO) {
    console.log('acabou erro');
    return;
  }
  else if (topo > DIVISAO) {
    console.warn('t1', topo);
    var corresps = tabelaCorrespondencia[valor];
    if (corresps)
    {
      for (var i = corresps.length - 1; i >= 0; i--) {
        console.log(corresps[i], '/', palavraPorCodigo(corresps[i]));
        this.pilha.push(corresps[i]);
      }
    }

    var top = this.pilha[this.pilha.length-1];
    if (top == token.codigo)
    {
      // this.analisar();
      // return;
      this.pilha.pop();
    }
    console.log('->', token, );
    // topo = this.pilha.pop();
  }

  // if (topo <= DIVISAO) {
    console.warn('this.pilha1', this.pilha);
    this.analisar();
  // }
  // else
  // {
  //   console.warn('this.pilha2', this.pilha);
  //   this.analisar();
  // }

    // if (token.codigo == topo)
    // {
    //   console.warn('t2');
    //   this.analisar();
    // }
    // else
    // {
    //   console.warn('t3');
    //   this.erro();
    // }
  // }
  // else {
  //   this.erro();
  // }

  // var valor = tabelaParsing[topo][token.codigo];
  // console.log('valor', valor);

  // var corresps = tabelaCorrespondencia[valor];
  // console.log('corresps', corresps);
  // if (corresps)
  // {
  //   for (var i = corresps.length - 1; i >= 0; i--) {
  //     this.pilha.push(corresps[i]);
  //   }
  // }

  // console.warn('pilha', this.pilha);
}

let analisadorSintatico = {
  init,
  analisar,
  erro,
  pilha: []
}

export default analisadorSintatico;<commit_msg>just another backup, D:<commit_after>import {tabelaParsing, tabelaCorrespondencia} from '../tabelaParsing';
import {palavraPorCodigo} from '../palavrasReservadas';
const VAZIO = 44;
const DIVISAO = 45;

function init(tokens) {
  this.tokens = tokens;
  this.posicao = 0;
  console.log('--2.', tabelaCorrespondencia);
  this.pilha.push(44);
  this.pilha.push(46);

  this.analisar();

}

function erro() {
  console.error('ERROR');
}

function analisar() {
  console.log('------------------------- analisar ------');
  var topo = this.pilha[this.pilha.length-1];
  // var topo = this.pilha.pop();
  console.log('topo', topo);

  console.log('OQUE PODIA SER: ')
  if (topo > DIVISAO)
  {
    for (var i = 0; i < 100; i++) {
      var kk = tabelaParsing[topo][i];
      if (kk)
      {
        console.log("1podiaser:", i, '/', palavraPorCodigo(i));
      }
    }
  }
  else
  {
    console.log("2podiaser:", topo, '/', palavraPorCodigo(topo));
  }

  var token = this.tokens[this.posicao++];
  console.log('token', token);

  if (!token)
  {
    console.warn('IXIE');
    return;
  }

  var valor = tabelaParsing[topo][token.codigo];
  console.log('valor', valor);
  // console.info('nolog', this.tokens.length ,'=', this.posicao);
  if (topo == token.codigo)
  {
    this.pilha.pop();
    console.warn('this.pilhak', this.pilha);
    this.analisar();
    return;
    // topo = this.pilha.pop();
    // token =
    // console.log('[topo', topo);
    // console.log('[token', token);
    // console.warn('[this.pilha1', this.pilha);
  }

  if (topo == VAZIO && this.tokens.length == this.posicao-1 ) {
    console.log('SUCCESS');
    return;
  }
  else if (this.pilha.length < 1) {
    console.log('VAZIA');
    return;
  }
  else if (topo == VAZIO) {
    console.log('acabou erro');
    return;
  }
  else if (topo > DIVISAO) {
    console.warn('t1', topo);
    var corresps = tabelaCorrespondencia[valor];
    if (corresps)
    {
      for (var i = corresps.length - 1; i >= 0; i--) {
        console.log(corresps[i], '/', palavraPorCodigo(corresps[i]));
        this.pilha.push(corresps[i]);
      }
    }

    // var top = this.pilha[this.pilha.length-1];
    //   console.log('pOPS', top);
    // if (top == token.codigo)
    // {
    //   this.pilha.pop();
    //   // this.analisar();
    //   // return;
    //   // this.pilha.pop();
    // }
    // console.log('->', token, );
    // topo = this.pilha.pop();
  }

  var top = this.pilha[this.pilha.length-1];
  console.log('pOPS', top);
  if (top == token.codigo)
  {
    this.pilha.pop();
    // this.analisar();
    // return;
    // this.pilha.pop();
  }

    // this.pilha.pop();
  // if (topo <= DIVISAO) {
    console.warn('this.pilha1', this.pilha);
    this.analisar();
  // }
  // else
  // {
  //   console.warn('this.pilha2', this.pilha);
  //   this.analisar();
  // }

    // if (token.codigo == topo)
    // {
    //   console.warn('t2');
    //   this.analisar();
    // }
    // else
    // {
    //   console.warn('t3');
    //   this.erro();
    // }
  // }
  // else {
  //   this.erro();
  // }

  // var valor = tabelaParsing[topo][token.codigo];
  // console.log('valor', valor);

  // var corresps = tabelaCorrespondencia[valor];
  // console.log('corresps', corresps);
  // if (corresps)
  // {
  //   for (var i = corresps.length - 1; i >= 0; i--) {
  //     this.pilha.push(corresps[i]);
  //   }
  // }

  // console.warn('pilha', this.pilha);
}

let analisadorSintatico = {
  init,
  analisar,
  erro,
  pilha: []
}

export default analisadorSintatico;<|endoftext|>


<commit_before>export { AddTwoTensors };

import * as TensorPlaceholder from "../TensorPlaceholder.js";
import * as BoundsArraySet from "../BoundsArraySet.js";
import { Base } from "./Operation_Base.js";

/**
 * Add two tensor3d. They should have the same channel count. Their ( height x width ) should be either the same or one is ( 1 x 1 ).
 * It could destroy one or two of the input tensors.
 *
 * @member {boolean} bKeepInputTensor0
 *   If false, the first input tensor will be disposed after adding. If true, the first input tensor will be kept after adding.
 *
 * @member {boolean} bKeepInputTensor1
 *   If false, the second input tensor will be disposed after adding. If true, the second input tensor will be kept after adding.
 *
 * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray0
 *   The element value bounds (per channel) of this add-two-tensors operation's input0. It will be kept (not cloned) directly. So caller
 * should not modify them.
 *
 * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray1
 *   The element value bounds (per channel) of this add-two-tensors operation's input1. It will be kept (not cloned) directly. So caller
 * should not modify them.
 *
 * @member {BoundsArraySet.InputsOutputs} boundsArraySet
 *   The element value bounds (per channel) of this concatenation operation.
 *
 * @member {function} apply
 *   This is a method. It processes this.input0.realTensor and this.input1.realTensor as inputTensors. It puts to this.output0.realTensor
 * as outputTensor. Both inputTensors are tf.tensor3d and represents an images ( height x width x channel ) which will be added. They
 * should have the same channel count. Their ( height x width ) should be either the same or one is ( 1 x 1 ). The outputTensor
 * (tf.tensor3d) represents the result of adding the two inputs. The inputTensors may or may not be disposed. In fact, this method
 * calls one of Add_and_keep0_keep1(), Add_and_keep0_destroy1(), Add_and_destroy0_keep1(), Add_and_destroy0_destroy1() according to
 * the parameters.
 *
 */
class AddTwoTensors extends Base() {

  /**
   *
   */
  constructor(
    inputTensorPlaceholder0, inputTensorPlaceholder1,
    inputScaleBoundsArray0, inputScaleBoundsArray1,
    bKeepInputTensor0, bKeepInputTensor1
  ) {

    super( inputTensorPlaceholder0, inputTensorPlaceholder1, 1 );

    this.bKeepInputTensor0 = bKeepInputTensor0;
    this.bKeepInputTensor1 = bKeepInputTensor1;
    Base.adjust_pfn.call( this );
    Base.setup_BoundsArraySet.call( this, inputScaleBoundsArray0, inputScaleBoundsArray1 );
    Base.setup_output0_TensorPlaceholder.call( this );
  }

  /**
   * Adjust this.apply so that this.apply() will or will not dispose its inputTensors.
   */
  setKeepInputTensor0( bKeepInputTensor0 ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    Base.adjust_pfn.call( this );
  }

  /**
   * Adjust this.apply so that this.apply() will or will not dispose its inputTensors.
   */
  setKeepInputTensor1( bKeepInputTensor1 ) {
    this.bKeepInputTensor1 = bKeepInputTensor1;
    Base.adjust_pfn.call( this );
  }

  /**
   * Adjust this.apply so that this.apply() will or will not dispose its inputTensors.
   */
  setKeepInputTensor( bKeepInputTensor0, bKeepInputTensor1 ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    this.bKeepInputTensor1 = bKeepInputTensor1;
    Base.adjust_pfn.call( this );
  }

  /** Set this.apply according to this.bKeepInputTensor0 and this.bKeepInputTensor1. */
  static adjust_pfn() {
    if ( this.bKeepInputTensor0 ) {
      if ( this.bKeepInputTensor1 ) {
        this.apply = Base.Add_and_keep0_keep1;
      } else {
        this.apply = Base.Add_and_keep0_destroy1;
      }
    } else {
      if ( this.bKeepInputTensor1 ) {
        this.apply = Base.Add_and_destroy0_keep1;
      } else {
        this.apply = Base.Add_and_destroy0_destroy1;
      }
    }
  }

  /** Create this.boundsArraySet. */
  static setup_BoundsArraySet( inputScaleBoundsArray0, inputScaleBoundsArray1 ) {

    tf.util.assert( ( inputScaleBoundsArray0.channelCount == inputScaleBoundsArray1.channelCount ),
      `AddTwoTensors.setup_BoundsArraySet(): `
        + `input0 channel count ( ${inputScaleBoundsArray0.channelCount} ) should be the same as `
        + `input1 channel count ( ${inputScaleBoundsArray1.channelCount} ).`
    );

    this.boundsArraySet = new BoundsArraySet.InputsOutputs( inputScaleBoundsArray0, inputScaleBoundsArray1,
      inputScaleBoundsArray0.channelCount
    );

    this.boundsArraySet.output0
      .set_all_byScaleBoundsArray( inputScaleBoundsArray0 )
      .add_all_byScaleBoundsArray_all( inputScaleBoundsArray1 );
  }

  /** Setup this.output0. */
  static setup_output0_TensorPlaceholder() {

    // 1. Only same channel count adding is supported.
    if ( this.input0.channelCount == this.input1.channelCount ) {

      this.output0.channelCount = this.input0.channelCount; // Result always has the same channel count.

      // 1.1 Adding two same dimension tensors. The result dimension is the same of any one.
      if ( ( this.input0.height == this.input1.height ) && ( this.input0.width == this.input1.width ) ) {
        this.output0.height = this.input0.height;
        this.output0.width = this.input0.width;

      // 1.2 Adding by broadcasting input0 to input1. The result dimension is the same as input1 (the larger one).
      } else if ( ( this.input0.height == 1 ) && ( this.input0.width == 1 ) ) {
        this.output0.height = this.input1.height;
        this.output0.width = this.input1.width;

      // 1.3 Adding by broadcasting input1 to input0. The result dimension is the same as input0 (the larger one).
      } else if ( ( this.input1.height == 1 ) && ( this.input1.width == 1 ) ) {
        this.output0.height = this.input0.height;
        this.output0.width = this.input0.width;

      // 1.4 Unsupported adding (height and width).
      } else {
        tf.util.assert( false,
          `Operation.AddTwoTensors.setup_output0_TensorPlaceholder(): `
            + `input0 ( height, width ) = ( ${this.input0.height}, ${this.input0.width} ) and `
            + `input1 ( height, width ) = ( ${this.input1.height}, ${this.input1.width} ) `
            + `should be either the same or one is ( 1, 1 ) for broadcating.`
        );
      }

      // Only if both inputs' lower half and higher half channel count are the same, they are passed through to output.
      // Otherwise, absent them in the output.
      {
        if ( this.input0.channelCount_lowerHalf == this.input1.channelCount_lowerHalf ) {
          if ( this.input0.channelCount_lowerHalf != undefined )
            this.output0.channelCount_lowerHalf = this.this.input0.channelCount_lowerHalf;
        }

        if ( this.input0.channelCount_higherHalf == this.input1.channelCount_higherHalf ) {
          if ( this.input0.channelCount_higherHalf != undefined )
            this.output0.channelCount_higherHalf = this.this.input0.channelCount_higherHalf;
        }
      }

    // 2. Unsupported adding (different channel count).
    } else {
      tf.util.assert( false,
        `Operation.AddTwoTensors.setup_output0_TensorPlaceholder(): `
          + `input0 channel count ( ${this.input0.channelCount} ) and `
          + `input1 channel count ( ${this.input1.channelCount} ) `
          + `should be the same.`
      );
    }
  }

  /** Add. (Both the inputTensor0 and inputTensor1 will not be disposed. */
  static Add_and_keep0_keep1() {
    this.output0.realTensor = tf.add( this.input0.realTensor, this.input1.realTensor );
  }

  /** Add. (The inputTensors0 will not be disposed. The inputTensor1 will be disposed. */
  static Add_and_keep0_destroy1() {
    this.output0.realTensor = tf.add( this.input0.realTensor, this.input1.realTensor );
    this.input1.realTensor.dispose();
  }

  /** Add. (The inputTensor0 will be disposed. The inputTensor1 will not be disposed. */
  static Add_and_destroy0_keep1() {
    this.output0.realTensor = tf.add( this.input0.realTensor, this.input1.realTensor );
    this.input0.realTensor.dispose();
  }

  /** Add. (Both the inputTensor0 and inputTensor1 will be disposed. */
  static Add_and_destroy0_destroy1() {
    this.output0.realTensor = tf.add( this.input0.realTensor, this.input1.realTensor );
    this.input0.realTensor.dispose();
    this.input1.realTensor.dispose();
  }

}
<commit_msg>Update Operation_AddTwoTensors.js<commit_after>export { AddTwoTensors };

import * as TensorPlaceholder from "../TensorPlaceholder.js";
import * as BoundsArraySet from "../BoundsArraySet.js";
import { Base } from "./Operation_Base.js";

/**
 * Add two tensor3d. They should have the same channel count. Their ( height x width ) should be either the same or one is ( 1 x 1 ).
 * It could destroy one or two of the input tensors.
 *
 * @member {boolean} bKeepInputTensor0
 *   If false, the first input tensor will be disposed after adding. If true, the first input tensor will be kept after adding.
 *
 * @member {boolean} bKeepInputTensor1
 *   If false, the second input tensor will be disposed after adding. If true, the second input tensor will be kept after adding.
 *
 * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray0
 *   The element value bounds (per channel) of this add-two-tensors operation's input0. It will be kept (not cloned) directly. So caller
 * should not modify them.
 *
 * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray1
 *   The element value bounds (per channel) of this add-two-tensors operation's input1. It will be kept (not cloned) directly. So caller
 * should not modify them.
 *
 * @member {BoundsArraySet.InputsOutputs} boundsArraySet
 *   The element value bounds (per channel) of this concatenation operation.
 *
 * @member {function} apply
 *   This is a method. It processes this.input0.realTensor and this.input1.realTensor as inputTensors. It puts to this.output0.realTensor
 * as outputTensor. Both inputTensors are tf.tensor3d and represents an images ( height x width x channel ) which will be added. They
 * should have the same channel count. Their ( height x width ) should be either the same or one is ( 1 x 1 ). The outputTensor
 * (tf.tensor3d) represents the result of adding the two inputs. The inputTensors may or may not be disposed. In fact, this method
 * calls one of Add_and_keep0_keep1(), Add_and_keep0_destroy1(), Add_and_destroy0_keep1(), Add_and_destroy0_destroy1() according to
 * the parameters.
 *
 */
class AddTwoTensors extends Base() {

  /**
   *
   */
  constructor(
    inputTensorPlaceholder0, inputTensorPlaceholder1,
    inputScaleBoundsArray0, inputScaleBoundsArray1,
    bKeepInputTensor0, bKeepInputTensor1
  ) {

    super( inputTensorPlaceholder0, inputTensorPlaceholder1, 1 );

    this.bKeepInputTensor0 = bKeepInputTensor0;
    this.bKeepInputTensor1 = bKeepInputTensor1;
    Base.adjust_pfn.call( this );
    Base.setup_BoundsArraySet.call( this, inputScaleBoundsArray0, inputScaleBoundsArray1 );
    Base.setup_output0_TensorPlaceholder.call( this );
  }

  /**
   * Adjust this.apply so that this.apply() will or will not dispose its inputTensors.
   */
  setKeepInputTensor0( bKeepInputTensor0 ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    Base.adjust_pfn.call( this );
  }

  /**
   * Adjust this.apply so that this.apply() will or will not dispose its inputTensors.
   */
  setKeepInputTensor1( bKeepInputTensor1 ) {
    this.bKeepInputTensor1 = bKeepInputTensor1;
    Base.adjust_pfn.call( this );
  }

  /**
   * Adjust this.apply so that this.apply() will or will not dispose its inputTensors.
   */
  setKeepInputTensor( bKeepInputTensor0, bKeepInputTensor1 ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    this.bKeepInputTensor1 = bKeepInputTensor1;
    Base.adjust_pfn.call( this );
  }

  /** Set this.apply according to this.bKeepInputTensor0 and this.bKeepInputTensor1. */
  static adjust_pfn() {
    if ( this.bKeepInputTensor0 ) {
      if ( this.bKeepInputTensor1 ) {
        this.apply = Base.Add_and_keep0_keep1;
      } else {
        this.apply = Base.Add_and_keep0_destroy1;
      }
    } else {
      if ( this.bKeepInputTensor1 ) {
        this.apply = Base.Add_and_destroy0_keep1;
      } else {
        this.apply = Base.Add_and_destroy0_destroy1;
      }
    }
  }

  /** Create this.boundsArraySet. */
  static setup_BoundsArraySet( inputScaleBoundsArray0, inputScaleBoundsArray1 ) {

    tf.util.assert( ( inputScaleBoundsArray0.channelCount == inputScaleBoundsArray1.channelCount ),
      `AddTwoTensors.setup_BoundsArraySet(): `
        + `input0 channel count ( ${inputScaleBoundsArray0.channelCount} ) should be the same as `
        + `input1 channel count ( ${inputScaleBoundsArray1.channelCount} ).`
    );

    this.boundsArraySet = new BoundsArraySet.InputsOutputs( inputScaleBoundsArray0, inputScaleBoundsArray1,
      inputScaleBoundsArray0.channelCount
    );

    this.boundsArraySet.output0
      .set_all_byScaleBoundsArray( inputScaleBoundsArray0 )
      .add_all_byScaleBoundsArray_all( inputScaleBoundsArray1 );
  }

  /** Setup this.output0.
   * This method should be called after setup_BoundsArraySet() because it uses BoundsArrarySet.
   */
  static setup_output0_TensorPlaceholder() {

    // 1. Only same channel count adding is supported.
    if ( this.input0.channelCount == this.input1.channelCount ) {

      this.output0.channelCount = this.input0.channelCount; // Result always has the same channel count.

      // 1.1 Adding two same dimension tensors. The result dimension is the same of any one.
      if ( ( this.input0.height == this.input1.height ) && ( this.input0.width == this.input1.width ) ) {
        this.output0.height = this.input0.height;
        this.output0.width = this.input0.width;

      // 1.2 Adding by broadcasting input0 to input1. The result dimension is the same as input1 (the larger one).
      } else if ( ( this.input0.height == 1 ) && ( this.input0.width == 1 ) ) {
        this.output0.height = this.input1.height;
        this.output0.width = this.input1.width;

      // 1.3 Adding by broadcasting input1 to input0. The result dimension is the same as input0 (the larger one).
      } else if ( ( this.input1.height == 1 ) && ( this.input1.width == 1 ) ) {
        this.output0.height = this.input0.height;
        this.output0.width = this.input0.width;

      // 1.4 Unsupported adding (height and width).
      } else {
        tf.util.assert( false,
          `Operation.AddTwoTensors.setup_output0_TensorPlaceholder(): `
            + `input0 ( height, width ) = ( ${this.input0.height}, ${this.input0.width} ) and `
            + `input1 ( height, width ) = ( ${this.input1.height}, ${this.input1.width} ) `
            + `should be either the same or one is ( 1, 1 ) for broadcating.`
        );
      }

      // Only if both inputs' lower half and higher half channel count are the same, they are passed through to output.
      // Otherwise, absent them in the output.
      {
        if ( this.input0.channelCount_lowerHalf == this.input1.channelCount_lowerHalf ) {
          if ( this.input0.channelCount_lowerHalf != undefined )
            this.output0.channelCount_lowerHalf = this.this.input0.channelCount_lowerHalf;
        }

        if ( this.input0.channelCount_higherHalf == this.input1.channelCount_higherHalf ) {
          if ( this.input0.channelCount_higherHalf != undefined )
            this.output0.channelCount_higherHalf = this.this.input0.channelCount_higherHalf;
        }
      }

      this.output0.scaleBoundsArray = this.boundsArraySet.output0;

    // 2. Unsupported adding (different channel count).
    } else {
      tf.util.assert( false,
        `Operation.AddTwoTensors.setup_output0_TensorPlaceholder(): `
          + `input0 channel count ( ${this.input0.channelCount} ) and `
          + `input1 channel count ( ${this.input1.channelCount} ) `
          + `should be the same.`
      );
    }
  }

  /** Add. (Both the inputTensor0 and inputTensor1 will not be disposed. */
  static Add_and_keep0_keep1() {
    this.output0.realTensor = tf.add( this.input0.realTensor, this.input1.realTensor );
  }

  /** Add. (The inputTensors0 will not be disposed. The inputTensor1 will be disposed. */
  static Add_and_keep0_destroy1() {
    this.output0.realTensor = tf.add( this.input0.realTensor, this.input1.realTensor );
    this.input1.realTensor.dispose();
  }

  /** Add. (The inputTensor0 will be disposed. The inputTensor1 will not be disposed. */
  static Add_and_destroy0_keep1() {
    this.output0.realTensor = tf.add( this.input0.realTensor, this.input1.realTensor );
    this.input0.realTensor.dispose();
  }

  /** Add. (Both the inputTensor0 and inputTensor1 will be disposed. */
  static Add_and_destroy0_destroy1() {
    this.output0.realTensor = tf.add( this.input0.realTensor, this.input1.realTensor );
    this.input0.realTensor.dispose();
    this.input1.realTensor.dispose();
  }

}
<|endoftext|>


<commit_before>(function(){

    var Ext = window.Ext4 || window.Ext;

    /**
    * shows print dialog for Iteration Progress App
    */
    Ext.define('Rally.apps.iterationtrackingboard.PrintDialog', {
        extend: 'Rally.ui.dialog.Dialog',
        alias:'widget.iterationprogessappprintdialog',
        requires: [
            'Rally.ui.Button'
        ],
        config: {
            autoShow: true,
            draggable: true,
            disableScroll: true,
            width: 520,
            height: 300,
            closable: true,
            title: 'Print'
        },
        layout: {
            type: 'vbox',
            align: 'left'
        },
        cls: 'iteration-progress-dialog print-dialog',
        items: [
            {
                xtype: 'container',
                html: 'What would you like to print?',
                cls: 'dialog-title'
            },
            {
                xtype: 'radiogroup',
                id: 'whattoprint',
                vertical: true,
                columns: 1,
                height: 70,
                items: [
                    {
                        boxLabel: 'Summary list of work items',
                        name: 'reportType',
                        inputValue: 'summary',
                        checked: true
                    },
                    {
                        boxLabel: 'Summary list of work items with children',
                        id: 'printDialogReportTypeIncludeChildren',
                        name: 'reportType',
                        inputValue: 'includechildren'
                    }
                ]
            }
        ],
        constructor: function(config) {
            this.initConfig(config || {});
            this.timeboxScope = this.config.timeboxScope;

            this.nodesToExpand = [];
            this.allRecords = [];

            this.callParent(arguments);
        },

        initComponent: function() {
            var warningTextClasses = this.showWarning ? 'print-warning' : 'print-warning hidden';
            this.items.push({
                xtype: 'container',
                html: '

 Iterations with more than 400 items may cause problems when printing.',
                cls: warningTextClasses,
                itemId: 'tooManyItems'
            });

            this.dockedItems = [{
                xtype: 'toolbar',
                dock: 'bottom',
                layout: {
                    type: 'hbox',
                    pack: 'center'
                },
                ui: 'footer',
                itemId: 'footer',
                defaults: {
                    xtype: 'rallybutton',
                    padding: '4 12',
                    scope: this
                },
                items: [
                    {
                        text: 'Print',
                        cls: 'primary medium',
                        handler: this._handlePrintClick
                    },
                    {
                        text: 'Cancel',
                        cls: 'secondary medium',
                        handler: this._handleCancelClick
                    }
                ]
            }];

            this.callParent(arguments);
        },

        _handlePrintClick: function() {
            var treeStoreBuilder = Ext.create('Rally.data.wsapi.TreeStoreBuilder');
            var storeConfig = this._buildStoreConfig();

            treeStoreBuilder.build(storeConfig);
        },

        _handleCancelClick: function(target, e) {
            this.destroy();
        },

        _buildStoreConfig: function() {
            var timeboxFilter = this.timeboxScope.getQueryFilter();
            var includeChildren = Ext.getCmp('whattoprint').getChecked()[0].inputValue === 'includechildren';

            return {
                models: ['User Story', 'Defect', 'Defect Suite', 'Test Set'],
                autoLoad: true,
                remoteSort: true,
                root: {expanded: includeChildren},
                enableHierarchy: includeChildren,
                childPageSizeEnabled: false,
                filters: [timeboxFilter],
                sorters: this.grid.getStore().getSorters(),
                listeners: {
                    load: this._onStoreLoad,
                    scope: this
                }
            };
        },

        _onStoreLoad: function(treeStore, node, records, success, eOpts) {
            if (_.isEmpty(this.allRecords)) {
                this.allRecords = records;
            }

            if (treeStore.enableHierarchy) {
                this.nodesToExpand = _.without(this.nodesToExpand, node.getId());

                _(records).filter(function(record) {
                    return !record.isLeaf();
                }).forEach(function(record) {
                    this.nodesToExpand.push(record.getId());
                    record.expand(true);
                }, this);
            }

            if (_.isEmpty(this.nodesToExpand)) {
                this._onDataReady();
            }
        },

        _onDataReady: function() {
            var timeboxScopeRecord = this.timeboxScope.getRecord();
            var iterationName = timeboxScopeRecord ? timeboxScopeRecord.get('Name') : 'Unscheduled';
            var treeGridPrinter = Ext.create('Rally.ui.grid.TreeGridPrinter', {
                records: this.allRecords,
                grid: this.grid,
                iterationName: iterationName
            });

            var printWindow = Rally.getWindow().open(Rally.environment.getServer().getContextUrl() + '/print/printContainer.html', 'printWindow', 'height=600,width=1000,toolbar=no,menubar=no,scrollbars=yes');
            if (!printWindow) {
                alert('It looks like you a popup blocker installed. Please turn this off to see the print window.');
                return;
            }
            treeGridPrinter.print(printWindow);

            this.destroy();
        }
    });
})();
<commit_msg>Fixed typo<commit_after>(function(){

    var Ext = window.Ext4 || window.Ext;

    /**
    * shows print dialog for Iteration Progress App
    */
    Ext.define('Rally.apps.iterationtrackingboard.PrintDialog', {
        extend: 'Rally.ui.dialog.Dialog',
        alias:'widget.iterationprogessappprintdialog',
        requires: [
            'Rally.ui.Button'
        ],
        config: {
            autoShow: true,
            draggable: true,
            disableScroll: true,
            width: 520,
            height: 300,
            closable: true,
            title: 'Print'
        },
        layout: {
            type: 'vbox',
            align: 'left'
        },
        cls: 'iteration-progress-dialog print-dialog',
        items: [
            {
                xtype: 'container',
                html: 'What would you like to print?',
                cls: 'dialog-title'
            },
            {
                xtype: 'radiogroup',
                id: 'whattoprint',
                vertical: true,
                columns: 1,
                height: 70,
                items: [
                    {
                        boxLabel: 'Summary list of work items',
                        name: 'reportType',
                        inputValue: 'summary',
                        checked: true
                    },
                    {
                        boxLabel: 'Summary list of work items with children',
                        id: 'printDialogReportTypeIncludeChildren',
                        name: 'reportType',
                        inputValue: 'includechildren'
                    }
                ]
            }
        ],
        constructor: function(config) {
            this.initConfig(config || {});
            this.timeboxScope = this.config.timeboxScope;

            this.nodesToExpand = [];
            this.allRecords = [];

            this.callParent(arguments);
        },

        initComponent: function() {
            var warningTextClasses = this.showWarning ? 'print-warning' : 'print-warning hidden';
            this.items.push({
                xtype: 'container',
                html: '

 Iterations with more than 400 items may cause problems when printing.',
                cls: warningTextClasses,
                itemId: 'tooManyItems'
            });

            this.dockedItems = [{
                xtype: 'toolbar',
                dock: 'bottom',
                layout: {
                    type: 'hbox',
                    pack: 'center'
                },
                ui: 'footer',
                itemId: 'footer',
                defaults: {
                    xtype: 'rallybutton',
                    padding: '4 12',
                    scope: this
                },
                items: [
                    {
                        text: 'Print',
                        cls: 'primary medium',
                        handler: this._handlePrintClick
                    },
                    {
                        text: 'Cancel',
                        cls: 'secondary medium',
                        handler: this._handleCancelClick
                    }
                ]
            }];

            this.callParent(arguments);
        },

        _handlePrintClick: function() {
            var treeStoreBuilder = Ext.create('Rally.data.wsapi.TreeStoreBuilder');
            var storeConfig = this._buildStoreConfig();

            treeStoreBuilder.build(storeConfig);
        },

        _handleCancelClick: function(target, e) {
            this.destroy();
        },

        _buildStoreConfig: function() {
            var timeboxFilter = this.timeboxScope.getQueryFilter();
            var includeChildren = Ext.getCmp('whattoprint').getChecked()[0].inputValue === 'includechildren';

            return {
                models: ['User Story', 'Defect', 'Defect Suite', 'Test Set'],
                autoLoad: true,
                remoteSort: true,
                root: {expanded: includeChildren},
                enableHierarchy: includeChildren,
                childPageSizeEnabled: false,
                filters: [timeboxFilter],
                sorters: this.grid.getStore().getSorters(),
                listeners: {
                    load: this._onStoreLoad,
                    scope: this
                }
            };
        },

        _onStoreLoad: function(treeStore, node, records, success, eOpts) {
            if (_.isEmpty(this.allRecords)) {
                this.allRecords = records;
            }

            if (treeStore.enableHierarchy) {
                this.nodesToExpand = _.without(this.nodesToExpand, node.getId());

                _(records).filter(function(record) {
                    return !record.isLeaf();
                }).forEach(function(record) {
                    this.nodesToExpand.push(record.getId());
                    record.expand(true);
                }, this);
            }

            if (_.isEmpty(this.nodesToExpand)) {
                this._onDataReady();
            }
        },

        _onDataReady: function() {
            var timeboxScopeRecord = this.timeboxScope.getRecord();
            var iterationName = timeboxScopeRecord ? timeboxScopeRecord.get('Name') : 'Unscheduled';
            var treeGridPrinter = Ext.create('Rally.ui.grid.TreeGridPrinter', {
                records: this.allRecords,
                grid: this.grid,
                iterationName: iterationName
            });

            var printWindow = Rally.getWindow().open(Rally.environment.getServer().getContextUrl() + '/print/printContainer.html', 'printWindow', 'height=600,width=1000,toolbar=no,menubar=no,scrollbars=yes');
            if (!printWindow) {
                alert('It looks like you have a popup blocker installed. Please turn this off to see the print window.');
                return;
            }
            treeGridPrinter.print(printWindow);

            this.destroy();
        }
    });
})();
<|endoftext|>


<commit_before>import {
  AnnotationComponent
} from 'substance'
import {
  CompositeComponent
} from '../../kit'

// new model based components
import AuthorsListComponent from './AuthorsListComponent'
import FigureComponent from './FigureComponent'
import FigurePanelComponent from './FigurePanelComponent'
import HeadingComponent from './HeadingComponent'
import ManuscriptComponent from './ManuscriptComponent'
import UnsupportedNodeComponent from './UnsupportedNodeComponent'
import UnsupportedInlineNodeComponent from './UnsupportedInlineNodeComponent'
import NodeModelComponent from './NodeModelComponent'

// TODO: these needs to be revisited
import AffiliationsListComponent from './AffiliationsListComponent'
import BioComponent from './BioComponent'
import BreakComponent from './BreakComponent'
import EditorsListComponent from './EditorsListComponent'
import ElementNodeComponent from './ElementNodeComponent'
import ExtLinkComponent from './ExtLinkComponent'
import CaptionComponent from './CaptionComponent'
import ContainerNodeComponent from './ContainerNodeComponent'
import DispQuoteComponent from './DispQuoteComponent'
import DispFormulaComponent from './DispFormulaComponent'
import FootnoteComponent from './FootnoteComponent'
import GraphicComponent from './GraphicComponent'
import InlineFormulaComponent from './InlineFormulaComponent'
import ListComponent from './ListComponent'
import ListItemComponent from './ListItemComponent'
import ReferenceComponent from './ReferenceComponent'
import SigBlockComponent from './SigBlockComponent'
import TableComponent from './TableComponent'
import TableFigureComponent from './TableFigureComponent';
import XrefComponent from './XrefComponent'

import ModelPreviewComponent from './ModelPreviewComponent'

import SectionLabel from './SectionLabel'

export default {
  name: 'manuscript-content',
  configure (config) {
    config.addComponent('authors-list', AuthorsListComponent)
    config.addComponent('back-matter', CompositeComponent)
    config.addComponent('bibr', ReferenceComponent)
    config.addComponent('figure', FigureComponent)
    config.addComponent('figure-panel', FigurePanelComponent)
    config.addComponent('heading', HeadingComponent)
    config.addComponent('manuscript', ManuscriptComponent)
    config.addComponent('table-figure', TableFigureComponent)
    config.addComponent('unsupported', UnsupportedNodeComponent)
    config.addComponent('unsupported-inline-node', UnsupportedInlineNodeComponent)

    config.addComponent('entity', NodeModelComponent)
    config.addComponent('affiliations-list', AffiliationsListComponent)
    config.addComponent('editors-list', EditorsListComponent)
    config.addComponent('bio', BioComponent)
    config.addComponent('break', BreakComponent)
    config.addComponent('caption', CaptionComponent)
    config.addComponent('container', ContainerNodeComponent)
    config.addComponent('col', ElementNodeComponent)
    config.addComponent('colgroup', ElementNodeComponent)
    config.addComponent('disp-formula', DispFormulaComponent)
    config.addComponent('disp-quote', DispQuoteComponent)
    config.addComponent('fn', FootnoteComponent)
    config.addComponent('graphic', GraphicComponent)
    config.addComponent('inline-formula', InlineFormulaComponent)
    config.addComponent('inline-graphic', GraphicComponent)
    config.addComponent('list', ListComponent)
    config.addComponent('list-item', ListItemComponent)
    config.addComponent('sig-block', SigBlockComponent)
    config.addComponent('table', TableComponent)
    config.addComponent('xref', XrefComponent)

    config.addComponent('model-preview', ModelPreviewComponent)

    // ATTENTION: I have changed the behavior so that
    // unregistered annotations or inline-nodes are
    // rendered using the UnsupportedInlineNodeComponent
    // instead of rendering all by default with AnnotationComponent
    config.addComponent('bold', AnnotationComponent)
    config.addComponent('italic', AnnotationComponent)
    config.addComponent('sub', AnnotationComponent)
    config.addComponent('sup', AnnotationComponent)
    config.addComponent('monospace', AnnotationComponent)
    config.addComponent('ext-link', ExtLinkComponent)

    // Manuscript sections config
    config.addComponent('section-label', SectionLabel)
    config.addLabel('title-label', 'Title')
    config.addLabel('title-placeholder', 'Enter a title for your article')
    config.addLabel('abstract-label', 'Abstract')
    config.addLabel('abstract-placeholder', 'Please provide a short description of your article.')
    config.addLabel('body-label', 'Main text')
    config.addLabel('body-placeholder', 'Write your article here.')
    config.addLabel('authors-label', 'Authors')
    config.addLabel('references-label', 'References')
    config.addLabel('footnotes-label', 'Footnotes')

    // Figure sections config
    config.addLabel('label-label', 'Label')
    config.addLabel('caption-label', 'Caption')

    // Used for rendering warning in case of missing images
    config.addIcon('graphic-load-error', { 'fontawesome': 'fa-warning' })
    config.addLabel('graphic-load-error', 'We couldn\'t load an image, sorry.')
  }
}
<commit_msg>Fix linter<commit_after>import {
  AnnotationComponent
} from 'substance'
import {
  CompositeComponent
} from '../../kit'

// new model based components
import AuthorsListComponent from './AuthorsListComponent'
import FigureComponent from './FigureComponent'
import FigurePanelComponent from './FigurePanelComponent'
import HeadingComponent from './HeadingComponent'
import ManuscriptComponent from './ManuscriptComponent'
import UnsupportedNodeComponent from './UnsupportedNodeComponent'
import UnsupportedInlineNodeComponent from './UnsupportedInlineNodeComponent'
import NodeModelComponent from './NodeModelComponent'

// TODO: these needs to be revisited
import AffiliationsListComponent from './AffiliationsListComponent'
import BioComponent from './BioComponent'
import BreakComponent from './BreakComponent'
import EditorsListComponent from './EditorsListComponent'
import ElementNodeComponent from './ElementNodeComponent'
import ExtLinkComponent from './ExtLinkComponent'
import CaptionComponent from './CaptionComponent'
import ContainerNodeComponent from './ContainerNodeComponent'
import DispQuoteComponent from './DispQuoteComponent'
import DispFormulaComponent from './DispFormulaComponent'
import FootnoteComponent from './FootnoteComponent'
import GraphicComponent from './GraphicComponent'
import InlineFormulaComponent from './InlineFormulaComponent'
import ListComponent from './ListComponent'
import ListItemComponent from './ListItemComponent'
import ReferenceComponent from './ReferenceComponent'
import SigBlockComponent from './SigBlockComponent'
import TableComponent from './TableComponent'
import TableFigureComponent from './TableFigureComponent'
import XrefComponent from './XrefComponent'

import ModelPreviewComponent from './ModelPreviewComponent'

import SectionLabel from './SectionLabel'

export default {
  name: 'manuscript-content',
  configure (config) {
    config.addComponent('authors-list', AuthorsListComponent)
    config.addComponent('back-matter', CompositeComponent)
    config.addComponent('bibr', ReferenceComponent)
    config.addComponent('figure', FigureComponent)
    config.addComponent('figure-panel', FigurePanelComponent)
    config.addComponent('heading', HeadingComponent)
    config.addComponent('manuscript', ManuscriptComponent)
    config.addComponent('table-figure', TableFigureComponent)
    config.addComponent('unsupported', UnsupportedNodeComponent)
    config.addComponent('unsupported-inline-node', UnsupportedInlineNodeComponent)

    config.addComponent('entity', NodeModelComponent)
    config.addComponent('affiliations-list', AffiliationsListComponent)
    config.addComponent('editors-list', EditorsListComponent)
    config.addComponent('bio', BioComponent)
    config.addComponent('break', BreakComponent)
    config.addComponent('caption', CaptionComponent)
    config.addComponent('container', ContainerNodeComponent)
    config.addComponent('col', ElementNodeComponent)
    config.addComponent('colgroup', ElementNodeComponent)
    config.addComponent('disp-formula', DispFormulaComponent)
    config.addComponent('disp-quote', DispQuoteComponent)
    config.addComponent('fn', FootnoteComponent)
    config.addComponent('graphic', GraphicComponent)
    config.addComponent('inline-formula', InlineFormulaComponent)
    config.addComponent('inline-graphic', GraphicComponent)
    config.addComponent('list', ListComponent)
    config.addComponent('list-item', ListItemComponent)
    config.addComponent('sig-block', SigBlockComponent)
    config.addComponent('table', TableComponent)
    config.addComponent('xref', XrefComponent)

    config.addComponent('model-preview', ModelPreviewComponent)

    // ATTENTION: I have changed the behavior so that
    // unregistered annotations or inline-nodes are
    // rendered using the UnsupportedInlineNodeComponent
    // instead of rendering all by default with AnnotationComponent
    config.addComponent('bold', AnnotationComponent)
    config.addComponent('italic', AnnotationComponent)
    config.addComponent('sub', AnnotationComponent)
    config.addComponent('sup', AnnotationComponent)
    config.addComponent('monospace', AnnotationComponent)
    config.addComponent('ext-link', ExtLinkComponent)

    // Manuscript sections config
    config.addComponent('section-label', SectionLabel)
    config.addLabel('title-label', 'Title')
    config.addLabel('title-placeholder', 'Enter a title for your article')
    config.addLabel('abstract-label', 'Abstract')
    config.addLabel('abstract-placeholder', 'Please provide a short description of your article.')
    config.addLabel('body-label', 'Main text')
    config.addLabel('body-placeholder', 'Write your article here.')
    config.addLabel('authors-label', 'Authors')
    config.addLabel('references-label', 'References')
    config.addLabel('footnotes-label', 'Footnotes')

    // Figure sections config
    config.addLabel('label-label', 'Label')
    config.addLabel('caption-label', 'Caption')

    // Used for rendering warning in case of missing images
    config.addIcon('graphic-load-error', { 'fontawesome': 'fa-warning' })
    config.addLabel('graphic-load-error', 'We couldn\'t load an image, sorry.')
  }
}
<|endoftext|>


<commit_before>// @ngInject
export default function estonianIdLogout(ENV, $rootScope) {
  $rootScope.$on('logoutStart', function() {
    const popup = $('');
    popup.hide();
    popup.attr('src', ENV.plugins.WALDUR_AUTH_OPENID.LOGOUT_URL);
    popup.on('load', function() {
      $(this).remove();
    });
    $('body').append(popup);
  });
}
<commit_msg>Skip logout if OpenID authentication is not enabled.<commit_after>// @ngInject
export default function estonianIdLogout(ENV, $rootScope) {
  if (!ENV.plugins.WALDUR_CORE.AUTHENTICATION_METHODS.includes('ESTONIAN_ID')) {
    return;
  }
  $rootScope.$on('logoutStart', function() {
    const popup = $('');
    popup.hide();
    popup.attr('src', ENV.plugins.WALDUR_AUTH_OPENID.LOGOUT_URL);
    popup.on('load', function() {
      $(this).remove();
    });
    $('body').append(popup);
  });
}
<|endoftext|>


<commit_before>// Global hash to save the popups
var Popups = {
	available_popups: $H(),
	open_popup: false
}

function showPopup(id)
{
	var popup = Popups.available_popups.get(id);
	if (popup)
		popup.open();
}

function closePopup(id)
{
	if (!id && Popups.open_popup)
		id = Popups.open_popup;

	var popup = Popups.available_popups.get(id);
	if (popup)
		popup.close();
}

function cancelProgress(id, url)
{
	var popup = Popups.available_popups.get(id);
	if (popup && popup.call_progress)
		popup.call_progress.cancel(url);
}

var Popup = Class.create({
	initialize: function(id, links)
	{
		this.id = id;
		this.links = links;
		this.divCont = $(this.id);
		this.call_progress = false;

		this.callback = function(action){}

		if (document.loaded)
			this.register()
		else
			document.observe('dom:loaded', this.register.bind(this));
	},
	register: function()
	{
		Popups.available_popups.set(this.id, this);
		document.body.insert(this.divCont);

		$H(this.links).each(function(pair)
		{
			var action = pair.key;
			var link_id = pair.value;
			$(link_id).observe('click', function(ev, action)
			{
				ev.stop();
				callback = this.callback(action);
				if (callback !== false)
					this.close();
			}.bindAsEventListener(this,action));
		}.bind(this));

		this.divCont.hide();
		this.divCont.fire('popup:registered');
	},
	open: function()
	{
		if (Popups.open_popup !== false)
			closePopup(Popups.open_popup);

		Popups.open_popup = this.id;
		document.body.insert(new Element('div',{className: 'popup_maya_veil'}).setOpacity(0.45));
		this.divCont.show();
		this.divCont.setStyle({
			top: document.viewport.getScrollOffsets().top + (document.viewport.getHeight()/2-this.divCont.getHeight()/2)+'px',
			left: document.viewport.getScrollOffsets().left + (document.viewport.getWidth()/2-this.divCont.getWidth()/2)+'px'
		});
		this.divCont.fire('popup:opened');
	},
	close: function()
	{
		Popups.open_popup = false;
		$$('.popup_maya_veil').each(Element.remove);
		this.divCont.hide();
		this.divCont.fire('popup:closed');
	},
	addCallback: function(procedure)
	{
		this.callback = procedure;
	}
});

//@todo: test the ProgressPopup

var ProgressPopup = Class.create({
	initialize: function(url, popup_id)
	{
		this.popup_id = popup_id;
		this.popup = Popups.available_popups.get(this.popup_id);
		this.popup.call_progress = this;

		this.can_continue = true;
		this.url_cancel = false;

		this.kill_popup();

		new Ajax.Request(url, {
			onComplete: this.completed.bind(this)
		});
	},
	completed: function(response)
	{
		if (response.responseJSON)
		{
			var json = response.responseJSON;
			this.popup.divCont.down('.msg').update(json.msg);

			if (json.erro == 0)
			{
				this.popup.divCont.down('.enchimento_da_barra').morph('width: '+json.porcentagem+'%', {duration: 3});
				if (json.porcentagem != 100)
				{
					if (this.can_continue)
					{
						new ProgressPopup(json.url_prox, this.popup_id);
					}
					else
					{
						this.call_cancel();
					}
				}
				else
				{
					this.show_end();
				}
			}
		}
		else
		{
			alert('Erro na comunicação.');
		}
	},
	kill_popup: function()
	{
		var links = this.popup.divCont.select('.callbacks a');
		links[0].show();
		links[1].hide();
	},
	show_end: function()
	{
		this.popup.divCont.down('.carregando').hide();

		var links = this.popup.divCont.select('.callbacks a');
		links[0].hide();
		links[1].show();
	},
	cancel: function(url)
	{
		openPopup(this.popup_id+'_cancelando');
		this.url_cancel = url;
		this.can_continue = false;
	},
	call_cancel: function()
	{
		if (this.url_cancel && this.url_cancel != '')
			new Ajax.Request(this.url_cancel,{
				onComplete:function(){closePopup(this.popup_id+'_cancelando');}.bind(this)
			});
		else
			closePopup(this.popup_id+'_cancelando');
	}
});<commit_msg>Fix a little, but important, bug on textile input.<commit_after>// Global hash to save the popups
var Popups = {
	available_popups: $H(),
	open_popup: false,
	add: function (obj)
	{
		Popups.available_popups.set(obj.id, obj);
	}
}

function showPopup(id)
{
	var popup = Popups.available_popups.get(id);
	if (popup)
		popup.open();
}

function closePopup(id)
{
	if (!id && Popups.open_popup)
		id = Popups.open_popup;

	var popup = Popups.available_popups.get(id);
	if (popup)
		popup.close();
}

function cancelProgress(id, url)
{
	var popup = Popups.available_popups.get(id);
	if (popup && popup.call_progress)
		popup.call_progress.cancel(url);
}

var Popup = Class.create({
	initialize: function(id, links)
	{
		console.log(id);
		this.id = id;
		this.links = links;
		this.divCont = $(this.id);
		this.call_progress = false;

		this.callback = function(action){}

		if (document.loaded)
			this.register()
		else
			document.observe('dom:loaded', this.register.bind(this));
	},
	register: function()
	{
		Popups.add(this);

		document.body.insert(this.divCont);

		$H(this.links).each(function(pair)
		{
			var action = pair.key;
			var link_id = pair.value;
			$(link_id).observe('click', function(ev, action)
			{
				ev.stop();
				callback = this.callback(action);
				if (callback !== false)
					this.close();
			}.bindAsEventListener(this,action));
		}.bind(this));

		this.divCont.hide();
		this.divCont.fire('popup:registered');
	},
	open: function()
	{
		if (Popups.open_popup !== false)
			closePopup(Popups.open_popup);

		Popups.open_popup = this.id;
		document.body.insert(new Element('div',{className: 'popup_maya_veil'}).setOpacity(0.45));
		this.divCont.show();
		this.divCont.setStyle({
			top: document.viewport.getScrollOffsets().top + (document.viewport.getHeight()/2-this.divCont.getHeight()/2)+'px',
			left: document.viewport.getScrollOffsets().left + (document.viewport.getWidth()/2-this.divCont.getWidth()/2)+'px'
		});
		this.divCont.fire('popup:opened');
	},
	close: function()
	{
		Popups.open_popup = false;
		$$('.popup_maya_veil').each(Element.remove);
		this.divCont.hide();
		this.divCont.fire('popup:closed');
	},
	addCallback: function(procedure)
	{
		this.callback = procedure;
	}
});

//@todo: test the ProgressPopup

var ProgressPopup = Class.create({
	initialize: function(url, popup_id)
	{
		this.popup_id = popup_id;
		this.popup = Popups.available_popups.get(this.popup_id);
		this.popup.call_progress = this;

		this.can_continue = true;
		this.url_cancel = false;

		this.kill_popup();

		new Ajax.Request(url, {
			onComplete: this.completed.bind(this)
		});
	},
	completed: function(response)
	{
		if (response.responseJSON)
		{
			var json = response.responseJSON;
			this.popup.divCont.down('.msg').update(json.msg);

			if (json.erro == 0)
			{
				this.popup.divCont.down('.enchimento_da_barra').morph('width: '+json.porcentagem+'%', {duration: 3});
				if (json.porcentagem != 100)
				{
					if (this.can_continue)
					{
						new ProgressPopup(json.url_prox, this.popup_id);
					}
					else
					{
						this.call_cancel();
					}
				}
				else
				{
					this.show_end();
				}
			}
		}
		else
		{
			alert('Erro na comunicação.');
		}
	},
	kill_popup: function()
	{
		var links = this.popup.divCont.select('.callbacks a');
		links[0].show();
		links[1].hide();
	},
	show_end: function()
	{
		this.popup.divCont.down('.carregando').hide();

		var links = this.popup.divCont.select('.callbacks a');
		links[0].hide();
		links[1].show();
	},
	cancel: function(url)
	{
		openPopup(this.popup_id+'_cancelando');
		this.url_cancel = url;
		this.can_continue = false;
	},
	call_cancel: function()
	{
		if (this.url_cancel && this.url_cancel != '')
			new Ajax.Request(this.url_cancel,{
				onComplete:function(){closePopup(this.popup_id+'_cancelando');}.bind(this)
			});
		else
			closePopup(this.popup_id+'_cancelando');
	}
});<|endoftext|>


<commit_before>// Copyright 2011-2018, The Trustees of Indiana University and Northwestern
//   University.  Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
//   under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
//   CONDITIONS OF ANY KIND, either express or implied. See the License for the
//   specific language governing permissions and limitations under the License.

'use strict';

/**
 * Add Markers To Playlist plugin
 *
 * A custom Avalon MediaElement 4 plugin for adding a marker to a playlist
 */

// If plugin needs translations, put here English one in this format:
// mejs.i18n.en["mejs.id1"] = "String 1";
// mejs.i18n.en["mejs.id2"] = "String 2";

// Feature configuration
Object.assign(mejs.MepDefaults, {
  // Any variable that can be configured by the end user belongs here.
  // Make sure is unique by checking API and Configuration file.
  // Add comments about the nature of each of these variables.
});

Object.assign(MediaElementPlayer.prototype, {
  // Public variables (also documented according to JSDoc specifications)

  /**
   * Feature constructor.
   *
   * Always has to be prefixed with `build` and the name that will be used in MepDefaults.features list
   * @param {MediaElementPlayer} player
   * @param {HTMLElement} controls
   * @param {HTMLElement} layers
   * @param {HTMLElement} media
   */
  buildaddMarkerToPlaylist(player, controls, layers, media) {
    // This allows us to access options and other useful elements already set.
    // Adding variables to the object is a good idea if you plan to reuse
    // those variables in further operations.
    const t = this;
    const addTitle = 'Add Marker to Playlist';
    let addMarkerObj = t.addMarkerObj;
    addMarkerObj.mejsMarkersHelper = new MEJSMarkersHelper();

    // Make player instance available outside of this method
    addMarkerObj.player = player;
    addMarkerObj.controls = controls;
    addMarkerObj.media = media;

    // Configure player control button to toggle plugin Adding Marker functionality
    player.addMarkerToPlaylistButton = document.createElement('div');
    player.addMarkerToPlaylistButton.className =
      t.options.classPrefix +
      'button ' +
      t.options.classPrefix +
      'add-marker-to-playlist-button';
    player.addMarkerToPlaylistButton.innerHTML = `<button type="button" aria-controls="${
      t.id
    }" title="${addTitle}" aria-label="${addTitle}" tabindex="0">${addTitle}</button>`;

    // Add control button to player
    t.addControlElement(
      player.addMarkerToPlaylistButton,
      'addMarkerToPlaylist'
    );

    // Set up click listener for the control button which opens
    // and closes the Add Marker to Playlist form
    player.addMarkerToPlaylistButton.addEventListener(
      'click',
      addMarkerObj.handleControlClick.bind(t)
    );

    // Variable references to the click event listener callback.  Pass this to avoid duplicate event processing
    addMarkerObj.bindHandleAdd = addMarkerObj.handleAdd.bind(addMarkerObj);
    addMarkerObj.bindHandleCancel = addMarkerObj.handleCancel.bind(
      addMarkerObj
    );

    // Add all other Markers related event listeners
    addMarkerObj.addEventListeners();
  },

  // Optionally, each feature can be destroyed setting a `clean` method

  /**
   * Feature destructor.
   *
   * Always has to be prefixed with `clean` and the name that was used in MepDefaults.features list
   * @param {MediaElementPlayer} player
   * @param {HTMLElement} controls
   * @param {HTMLElement} layers
   * @param {HTMLElement} media
   */
  cleanaddMarkerToPlaylist(player, controls, layers, media) {
    const t = this;

    if (t.addMarkerObj.addButton) {
      t.addMarkerObj.addButton.removeEventListener(
        'click',
        t.addMarkerObj.bindHandleAdd
      );
    }
    if (t.addMarkerObj.cancelButton) {
      t.addMarkerObj.cancelButton.removeEventListener(
        'click',
        t.addMarkerObj.bindHandleCancel
      );
    }

    $(t.addMarkerObj.alertEl).hide();
    $(t.addMarkerObj.formWrapperEl).hide();
    t.addMarkerObj.resetForm();
  },

  // Other optional public methods (all documented according to JSDoc specifications)

  /**
   * The 'addMarkerObj' object acts as a namespacer for all Add to Playlist
   * specific variables and methods, so as not to pollute global or MEJS scope.
   * @type {Object}
   */
  addMarkerObj: {
    active: false,
    addButton: document.getElementById('add_marker_submit'),
    alertEl: document.getElementById('add_marker_to_playlist_item_alert'),
    bindHandleCancel: null,
    bindHandleAdd: null,
    cancelButton: document.getElementById('add_marker_cancel'),
    formInputs: {
      offset: document.getElementById('marker_start'),
      title: document.getElementById('marker_title')
    },
    formWrapperEl: document.getElementById('add_marker_to_playlist_item'),
    markersEl: document.getElementById('markers'),
    player: null,

    /**
     * Add event (mostly click) listeners for marker interaction elements
     * @return {void}
     */
    addEventListeners: function() {
      let t = this;

      // Set click listeners for Add Marker to Playlist form elements
      if (t.addButton) {
        t.addButton.addEventListener('click', t.bindHandleAdd);
      }
      if (t.cancelButton) {
        t.cancelButton.addEventListener('click', t.bindHandleCancel);
      }
      // Set click listeners on the current markers UI table
      // t.mejsMarkersHelper.addMarkersTableListeners();
    },

    /**
     * Clear the Add marker to playlist alert box of previous messages
     * @function clearAddAlert
     * @return {void}
     */
    clearAddAlert: function() {
      let alertEl = this.alertEl;

      alertEl.classList.remove('alert-success');
      alertEl.classList.remove('alert-danger');
      $(alertEl)
        .find('p')
        .remove();
    },

    /**
     * Handle the 'Add' button click; post form data via ajax and handle response
     * @function handleAdd
     * @param  {MouseEvent} e Event generated when Cancel form button clicked
     * @return {void}
     */
    handleAdd: function(e) {
      const t = this;
      const playlistIds = t.mejsMarkersHelper.getCurrentPlaylistIds();

      // Clear out alerts
      t.clearAddAlert();

      $.ajax({
        url: '/avalon_marker',
        type: 'POST',
        data: {
          marker: {
            master_file_id: mejs4AvalonPlayer.currentStreamInfo.id,
            playlist_item_id: playlistIds.playlistItemId,
            start_time: $('#marker_start').val(),
            title: $('#marker_title').val()
          }
        }
      })
        .done(t.handleAddSuccess.bind(t, $('#marker_start').val(), playlistIds))
        .fail(t.handleAddError.bind(t));
    },

    /**
     * Add to playlist AJAX error handler
     * @function handleAddError
     * @param  {Object} error AJAX response
     * @return {void}
     */
    handleAddError: function(error) {
      const t = this;
      let alertEl = t.addMarkerObj.alertEl;

      alertEl.classList.add('alert-danger');
      alertEl.classList.add('add_to_playlist_alert_error');
      error.responseJSON.message.forEach(message => {
        $(alertEl).append('
' + message + '
');
      });
      $(alertEl).slideDown();
    },

    /**
     * Add to playlist AJAX success handler
     * @function handleAddSuccess
     * @param {string} startTime The marker start time text input value
     * @param  {Object} response AJAX response
     * @return {void}
     */
    handleAddSuccess: function(startTime, playlistIds, response) {
      const t = this;
      const alertEl = t.alertEl;
      let $alertEl = $(alertEl);
      const offset = mejs.Utils.convertSMPTEtoSeconds(startTime);

      alertEl.classList.add('alert-success');
      $alertEl.append('
' + response.message + '
');
      // Add page refresh message if needed
      if (!t.markersEl) {
        $alertEl.append('
Please wait while the page refreshes...
');
      }
      $alertEl.show('slow');
      $(t.formWrapperEl).slideUp();
      t.resetForm();

      // Update visual markers in player's time rail
      t.mejsMarkersHelper.updateVisualMarkers();

      if (t.markersEl) {
        // Rebuild Markers table
        t.mejsMarkersHelper.rebuildMarkersTable();
      } else {
        // No markers section exists in the DOM yet,
        // need a page refresh to build it (most efficient way)
        window.location.reload();
      }
    },

    /**
     * Handle cancel button click; hide form and alert windows.
     * @function handleCancel
     * @param  {MouseEvent} e Event generated when Cancel form button clicked
     * @return {void}
     */
    handleCancel: function(e) {
      const t = this;

      $(t.alertEl).slideUp();
      $(t.formWrapperEl).slideUp();
      t.resetForm();
    },

    /**
     * Handle control button click to toggle Add Playlist display
     * @function handleControlClick
     * @param  {MouseEvent} e Event generated when Add to Playlist control button clicked
     * @return {void}
     */
    handleControlClick: function(e) {
      const t = this;
      let addMarkerObj = t.addMarkerObj;

      if (!addMarkerObj.active) {
        // Close any open alert displays
        $(t.addMarkerObj.alertEl).slideUp();
        // Load default values into form fields
        t.addMarkerObj.populateFormValues.apply(this);
      }
      // Toggle form display
      $(t.addMarkerObj.formWrapperEl).slideToggle();
      // Update active (is showing) state
      t.addMarkerObj.active = !t.addMarkerObj.active;
    },

    /**
     * Populate all form fields with default values
     * @function populateFormValues
     * @return {void}
     */
    populateFormValues: function() {
      let addMarkerObj = this.addMarkerObj;

      addMarkerObj.formInputs.offset.value = mejs.Utils.secondsToTimeCode(
        addMarkerObj.player.getCurrentTime(), true, false, 25, 3);
    },

    /**
     * Reset all form fields to initial values
     * @function resetForm
     * @return {void}
     */
    resetForm: function() {
      const t = this;
      let formInputs = t.formInputs;

      for (const prop in formInputs) {
        if (formInputs.hasOwnProperty(prop) && formInputs[prop]) {
          formInputs[prop].value = '';
        }
      }
      t.active = false;
    }
  }
});
<commit_msg>Exit fullscreen when adding a marker in playlists<commit_after>// Copyright 2011-2018, The Trustees of Indiana University and Northwestern
//   University.  Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
//   under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
//   CONDITIONS OF ANY KIND, either express or implied. See the License for the
//   specific language governing permissions and limitations under the License.

'use strict';

/**
 * Add Markers To Playlist plugin
 *
 * A custom Avalon MediaElement 4 plugin for adding a marker to a playlist
 */

// If plugin needs translations, put here English one in this format:
// mejs.i18n.en["mejs.id1"] = "String 1";
// mejs.i18n.en["mejs.id2"] = "String 2";

// Feature configuration
Object.assign(mejs.MepDefaults, {
  // Any variable that can be configured by the end user belongs here.
  // Make sure is unique by checking API and Configuration file.
  // Add comments about the nature of each of these variables.
});

Object.assign(MediaElementPlayer.prototype, {
  // Public variables (also documented according to JSDoc specifications)

  /**
   * Feature constructor.
   *
   * Always has to be prefixed with `build` and the name that will be used in MepDefaults.features list
   * @param {MediaElementPlayer} player
   * @param {HTMLElement} controls
   * @param {HTMLElement} layers
   * @param {HTMLElement} media
   */
  buildaddMarkerToPlaylist(player, controls, layers, media) {
    // This allows us to access options and other useful elements already set.
    // Adding variables to the object is a good idea if you plan to reuse
    // those variables in further operations.
    const t = this;
    const addTitle = 'Add Marker to Playlist';
    let addMarkerObj = t.addMarkerObj;
    addMarkerObj.mejsMarkersHelper = new MEJSMarkersHelper();

    // Make player instance available outside of this method
    addMarkerObj.player = player;
    addMarkerObj.controls = controls;
    addMarkerObj.media = media;

    // Configure player control button to toggle plugin Adding Marker functionality
    player.addMarkerToPlaylistButton = document.createElement('div');
    player.addMarkerToPlaylistButton.className =
      t.options.classPrefix +
      'button ' +
      t.options.classPrefix +
      'add-marker-to-playlist-button';
    player.addMarkerToPlaylistButton.innerHTML = `<button type="button" aria-controls="${
      t.id
    }" title="${addTitle}" aria-label="${addTitle}" tabindex="0">${addTitle}</button>`;

    // Add control button to player
    t.addControlElement(
      player.addMarkerToPlaylistButton,
      'addMarkerToPlaylist'
    );

    // Set up click listener for the control button which opens
    // and closes the Add Marker to Playlist form
    player.addMarkerToPlaylistButton.addEventListener(
      'click',
      addMarkerObj.handleControlClick.bind(t)
    );

    // Variable references to the click event listener callback.  Pass this to avoid duplicate event processing
    addMarkerObj.bindHandleAdd = addMarkerObj.handleAdd.bind(addMarkerObj);
    addMarkerObj.bindHandleCancel = addMarkerObj.handleCancel.bind(
      addMarkerObj
    );

    // Add all other Markers related event listeners
    addMarkerObj.addEventListeners();
  },

  // Optionally, each feature can be destroyed setting a `clean` method

  /**
   * Feature destructor.
   *
   * Always has to be prefixed with `clean` and the name that was used in MepDefaults.features list
   * @param {MediaElementPlayer} player
   * @param {HTMLElement} controls
   * @param {HTMLElement} layers
   * @param {HTMLElement} media
   */
  cleanaddMarkerToPlaylist(player, controls, layers, media) {
    const t = this;

    if (t.addMarkerObj.addButton) {
      t.addMarkerObj.addButton.removeEventListener(
        'click',
        t.addMarkerObj.bindHandleAdd
      );
    }
    if (t.addMarkerObj.cancelButton) {
      t.addMarkerObj.cancelButton.removeEventListener(
        'click',
        t.addMarkerObj.bindHandleCancel
      );
    }

    $(t.addMarkerObj.alertEl).hide();
    $(t.addMarkerObj.formWrapperEl).hide();
    t.addMarkerObj.resetForm();
  },

  // Other optional public methods (all documented according to JSDoc specifications)

  /**
   * The 'addMarkerObj' object acts as a namespacer for all Add to Playlist
   * specific variables and methods, so as not to pollute global or MEJS scope.
   * @type {Object}
   */
  addMarkerObj: {
    active: false,
    addButton: document.getElementById('add_marker_submit'),
    alertEl: document.getElementById('add_marker_to_playlist_item_alert'),
    bindHandleCancel: null,
    bindHandleAdd: null,
    cancelButton: document.getElementById('add_marker_cancel'),
    formInputs: {
      offset: document.getElementById('marker_start'),
      title: document.getElementById('marker_title')
    },
    formWrapperEl: document.getElementById('add_marker_to_playlist_item'),
    markersEl: document.getElementById('markers'),
    player: null,

    /**
     * Add event (mostly click) listeners for marker interaction elements
     * @return {void}
     */
    addEventListeners: function() {
      let t = this;

      // Set click listeners for Add Marker to Playlist form elements
      if (t.addButton) {
        t.addButton.addEventListener('click', t.bindHandleAdd);
      }
      if (t.cancelButton) {
        t.cancelButton.addEventListener('click', t.bindHandleCancel);
      }
      // Set click listeners on the current markers UI table
      // t.mejsMarkersHelper.addMarkersTableListeners();
    },

    /**
     * Clear the Add marker to playlist alert box of previous messages
     * @function clearAddAlert
     * @return {void}
     */
    clearAddAlert: function() {
      let alertEl = this.alertEl;

      alertEl.classList.remove('alert-success');
      alertEl.classList.remove('alert-danger');
      $(alertEl)
        .find('p')
        .remove();
    },

    /**
     * Handle the 'Add' button click; post form data via ajax and handle response
     * @function handleAdd
     * @param  {MouseEvent} e Event generated when Cancel form button clicked
     * @return {void}
     */
    handleAdd: function(e) {
      const t = this;
      const playlistIds = t.mejsMarkersHelper.getCurrentPlaylistIds();

      // Clear out alerts
      t.clearAddAlert();

      $.ajax({
        url: '/avalon_marker',
        type: 'POST',
        data: {
          marker: {
            master_file_id: mejs4AvalonPlayer.currentStreamInfo.id,
            playlist_item_id: playlistIds.playlistItemId,
            start_time: $('#marker_start').val(),
            title: $('#marker_title').val()
          }
        }
      })
        .done(t.handleAddSuccess.bind(t, $('#marker_start').val(), playlistIds))
        .fail(t.handleAddError.bind(t));
    },

    /**
     * Add to playlist AJAX error handler
     * @function handleAddError
     * @param  {Object} error AJAX response
     * @return {void}
     */
    handleAddError: function(error) {
      const t = this;
      let alertEl = t.addMarkerObj.alertEl;

      alertEl.classList.add('alert-danger');
      alertEl.classList.add('add_to_playlist_alert_error');
      error.responseJSON.message.forEach(message => {
        $(alertEl).append('
' + message + '
');
      });
      $(alertEl).slideDown();
    },

    /**
     * Add to playlist AJAX success handler
     * @function handleAddSuccess
     * @param {string} startTime The marker start time text input value
     * @param  {Object} response AJAX response
     * @return {void}
     */
    handleAddSuccess: function(startTime, playlistIds, response) {
      const t = this;
      const alertEl = t.alertEl;
      let $alertEl = $(alertEl);
      const offset = mejs.Utils.convertSMPTEtoSeconds(startTime);

      alertEl.classList.add('alert-success');
      $alertEl.append('
' + response.message + '
');
      // Add page refresh message if needed
      if (!t.markersEl) {
        $alertEl.append('
Please wait while the page refreshes...
');
      }
      $alertEl.show('slow');
      $(t.formWrapperEl).slideUp();
      t.resetForm();

      // Update visual markers in player's time rail
      t.mejsMarkersHelper.updateVisualMarkers();

      if (t.markersEl) {
        // Rebuild Markers table
        t.mejsMarkersHelper.rebuildMarkersTable();
      } else {
        // No markers section exists in the DOM yet,
        // need a page refresh to build it (most efficient way)
        window.location.reload();
      }
    },

    /**
     * Handle cancel button click; hide form and alert windows.
     * @function handleCancel
     * @param  {MouseEvent} e Event generated when Cancel form button clicked
     * @return {void}
     */
    handleCancel: function(e) {
      const t = this;

      $(t.alertEl).slideUp();
      $(t.formWrapperEl).slideUp();
      t.resetForm();
    },

    /**
     * Handle control button click to toggle Add marker to playlist item display
     * @function handleControlClick
     * @param  {MouseEvent} e Event generated when Add Marker to Playlist control button clicked
     * @return {void}
     */
    handleControlClick: function(e) {
      const t = this;
      let addMarkerObj = t.addMarkerObj;

      // Exit full screen
      if(addMarkerObj.player.isFullScreen) {
        addMarkerObj.player.exitFullScreen();
        // Reload the form with new values
        if(addMarkerObj.active) {
          $(t.addMarkerObj.formWrapperEl).slideToggle();
          t.addMarkerObj.active = !t.addMarkerObj.active;
        }
      }

      if (!addMarkerObj.active) {
        // Close any open alert displays
        $(t.addMarkerObj.alertEl).slideUp();
        // Load default values into form fields
        t.addMarkerObj.populateFormValues.apply(this);
      }
      // Toggle form display
      $(t.addMarkerObj.formWrapperEl).slideToggle();
      // Update active (is showing) state
      t.addMarkerObj.active = !t.addMarkerObj.active;
    },

    /**
     * Populate all form fields with default values
     * @function populateFormValues
     * @return {void}
     */
    populateFormValues: function() {
      let addMarkerObj = this.addMarkerObj;

      addMarkerObj.formInputs.offset.value = mejs.Utils.secondsToTimeCode(
        addMarkerObj.player.getCurrentTime(), true, false, 25, 3);
    },

    /**
     * Reset all form fields to initial values
     * @function resetForm
     * @return {void}
     */
    resetForm: function() {
      const t = this;
      let formInputs = t.formInputs;

      for (const prop in formInputs) {
        if (formInputs.hasOwnProperty(prop) && formInputs[prop]) {
          formInputs[prop].value = '';
        }
      }
      t.active = false;
    }
  }
});
<|endoftext|>