<commit_before>//= require <activity>
//= require <string>
//= require <ui>
//= require <flash_comm>
//= require <circuit/breadboard>
//= require <circuit/multimeter2>
//= require <circuit/resistor-4band>
//= require <circuit/resistor-5band>
//= require "setup-common"
//= require "activity-log"
//= require "grader"
//= require "reporter"

/* FILE activity.js */

(function () {

    var sm = sparks.activities.sm;
    var flash = sparks.flash;
    var str = sparks.string;
    var util = sparks.util;

    sparks.config.flash_id = 'breadboardActivity1';

    sparks.config.debug = jQuery.url.param("debug") !== undefined;

    sm.Activity = function () {
        sm.Activity.uber.init.apply(this);
        this.log = new sm.ActivityLog();
        this.reporter = new sm.Reporter($('#report_area'));
        sparks.flash.activity = this;
    };

    sparks.config.Activity = sparks.activities.sm.Activity;

    sparks.extend(sm.Activity, sparks.Activity, {

        // Initial operation on document when it is loaded
        onDocumentReady: function () {
            var self = this;

            if (sparks.config.debug) {
                $('.debug_area').show();
            }
            else {
               $('.debug_area').hide();
            }
            $('#popup').hide();
            $('.next_button').click(function () {
                window.location.reload();
            });

            this.root_dir = sparks.config.root_dir + '/activities/module-2/series-measuring';
            $('body').scrollTop(0); //scroll to top

            this.forms = $('form');
            this.questionsArea = $('#questions_area');
            this.reportArea = $('#report_area').hide();

            $('button.submit').click(function (e) {
                self.submitButtonClicked();
                e.preventDefault();
            });
        },

        // Initializations that can be done only when the flash movie is loaded
        onFlashReady: function () {
            breadModel('insert', 'wire', 'left_positive_1,a23', 'wire1');
            breadModel('insert', 'wire', 'left_negative_1,c5', 'wire2');
            this.multimeter = new sparks.circuit.Multimeter2();

            this.startTry();
        },

        submitButtonClicked: function () {
            if (this.currentQuestion == 3) {
                this.completedTry();
            }
            else {
                ++ this.currentQuestion;
                this.disableForm(this.currentQuestion - 1);
                this.enableForm(this.currentQuestion);
            }
        },

        startTry: function () {
            $('.next_button').hide();

            var options = null;
            // this.resistor1 = new sparks.circuit.Resistor4band('resistor1');
            //             this.resistor1.randomize(options);
            //             breadModel('insert', 'resistor', 'b23,b17', this.resistor1.getRealValue(), 'resistor1');
            //             flash.sendCommand('insert_component', 'resistor', 'b23,b17','4band',this.resistor1.colors);

            var resistor1 = breadModel('addRandomResistor', 'resistor1', 'c17,c11');
            flash.sendCommand('insert_component', 'resistor', 'c17,c11','4band',resistor1.colors);

            var resistor2 = breadModel('addRandomResistor', 'resistor2', 'e17,e11');
            flash.sendCommand('insert_component', 'resistor', 'e17,e11','4band',resistor2.colors);

            // this.resistor4 = new sparks.circuit.Resistor4band('resistor4');
            //            this.resistor4.randomize(options);
            //            breadModel('insert', 'resistor', 'c11,c5', this.resistor4.getRealValue(), 'resistor3');
            //            flash.sendCommand('insert_component', 'resistor', 'c11,c5','4band',this.resistor4.colors);
            //
            // $('#dbg_rated_1').text(this.resistor1.getNominalValue());
            // $('#dbg_rated_2').text(this.resistor2.getNominalValue());
            // $('#dbg_rated_3').text(this.resistor3.getNominalValue());
            // $('#dbg_real_1').text(this.resistor1.getRealValue().toFixed(3));
            // $('#dbg_real_2').text(this.resistor2.getRealValue().toFixed(3));
            // $('#dbg_real_3').text(this.resistor3.getRealValue().toFixed(3));
            // $('#dbg_tol_1').text(this.resistor1.getTolerance());
            // $('#dbg_tol_2').text(this.resistor2.getTolerance());
            // $('#dbg_tol_3').text(this.resistor3.getTolerance());

            this.currentQuestion = 0;

            this.enableForm(0);
            for (var i = 1; i < this.forms.length; ++i) {
                this.disableForm(i);
            }
        },

        completedTry: function () {
            this.logResults();
            grader = new sm.Grader(this.log.session, {});
            feedback = grader.grade();
            this.reporter.report(this.log.session, feedback);
            this.questionsArea.hide();
            this.reportArea.show();
            $('.next_button').show();
        },

        resetCircuit: function () {
        },

        enableForm: function (k) {
            $(this.forms[k]).find('input, select, button').attr('disabled', false);
        },

        disableForm: function (k) {
            $(this.forms[k]).find('input, select, button').attr('disabled', true);
        },

        logResults: function () {
        },

        receiveEvent: function (name, value, time) {
            console.log('ENTER sm.Activity#receiveEvent');
            console.log('Received: ' + name + ', ' + value + ', ' + new Date(parseInt(time, 10)));

            var v;
            var t = '';
            var args = value.split('|');

            if (name === 'connect') {
                if (args[0] === 'probe') {
                    if (args[1] === 'probe_red') {
                        this.multimeter.redProbeConnection = args[2];
                    }
                    else if (args[1] === 'probe_black') {
                        this.multimeter.blackProbeConnection = args[2];
                    }
                    else {
                        alert('Activity#receiveEvent: connect: unknonw probe name ' + args[1]);
                    }
                }
                if (args[0] === 'resistor') {
                    // for now, we're just dealing with the situation of replacing one lead that had been lifted
                    if (!!args[3]){
                      breadModel('unmapHole', args[3]);
                    }
                }
                this.multimeter.update();
            } else if (name === 'disconnect') {
                if (args[0] === 'probe') {
                    if (args[1] === 'probe_red') {
                        this.multimeter.redProbeConnection = null;
                    }
                    else if (args[1] === 'probe_black') {
                        this.multimeter.blackProbeConnection = null;
                    }
                    else {
                        alert('Activity#receiveEvent: disconnect: Unknonw probe name ' + args[1]);
                    }
                } else if (args[0] === 'resistor') {
                  var location = args[2].split(",");
                  var hole = args[3];
                  var remainingHole = location[0] === hole ? location[1] : location[0];
                  var newHole = breadModel('getGhostHole', hole+"ghost");

                  breadModel('mapHole', hole, newHole.nodeName());
                }
                this.multimeter.update();
            } else if (name === 'probe') {
                $('#popup').dialog();

                v = breadModel('query', 'voltage', 'a23,a17');
                t += v.toFixed(3);
                v = breadModel('query', 'voltage', 'b17,b11');
                t += ' ' + v.toFixed(3);
                v = breadModel('query', 'voltage', 'c11,c5');
                t += ' ' + v.toFixed(3);
                $('#dbg_voltage').text(t);

                // Disconnect wire1
                breadModel('move', 'wire1', 'left_positive_1,a22');

                v = breadModel('query', 'resistance', 'a23,a17');
                t = v.toFixed(3);
                v = breadModel('query', 'resistance', 'b17,b11');
                t += ' ' + v.toFixed(3);
                v = breadModel('query', 'resistance', 'c11,c5');
                t += ' ' + v.toFixed(3);

                $('#dbg_resistance').text(t);

                v = breadModel('query', 'current', 'a22,a23');
                t = v.toFixed(3);

                breadModel('move', 'wire1', 'left_positive_1,a23');
                breadModel('move', 'resistor1', 'a23,a16');
                v = breadModel('query', 'current', 'a16,b17');
                t += ' ' + v.toFixed(3);

                breadModel('move', 'resistor1', 'a23,a17');
                breadModel('move', 'resistor2', 'b17,b10');
                v = breadModel('query', 'current', 'b10,c11');
                t += ' ' + v.toFixed(3);

                breadModel('move', 'resistor2', 'b17,b11');

                $('#dbg_current').text(t);

                $('#popup').dialog('close');
            } else if (name == 'multimeter_dial') {
                console.log('changed multimeter dial'+value);
                this.multimeter.dialPosition = value;
                this.multimeter.update();
                // activity.log.add(name, { value: this.multimeter.dialPosition });
            } else if (name == 'multimeter_power') {
                this.multimeter.powerOn = value == 'true' ? true : false;
                this.multimeter.update();
                // activity.log.add(name, { value: this.multimeter.powerOn });
                //                 if (value === 'true' && this.multimeter.allConnected()) {
                //                     activity.log.add('make_circuit');
                //                 } else if (value == 'false' && wasConnected) {
                //                     activity.log.add('break_circuit');
                //                 }
            }
        }

    });

})();
<commit_msg>Set up resistors for simple series circuit<commit_after>//= require <activity>
//= require <string>
//= require <ui>
//= require <flash_comm>
//= require <circuit/breadboard>
//= require <circuit/multimeter2>
//= require <circuit/resistor-4band>
//= require <circuit/resistor-5band>
//= require "setup-common"
//= require "activity-log"
//= require "grader"
//= require "reporter"

/* FILE activity.js */

(function () {

    var sm = sparks.activities.sm;
    var flash = sparks.flash;
    var str = sparks.string;
    var util = sparks.util;

    sparks.config.flash_id = 'breadboardActivity1';

    sparks.config.debug = jQuery.url.param("debug") !== undefined;

    sm.Activity = function () {
        sm.Activity.uber.init.apply(this);
        this.log = new sm.ActivityLog();
        this.reporter = new sm.Reporter($('#report_area'));
        sparks.flash.activity = this;
    };

    sparks.config.Activity = sparks.activities.sm.Activity;

    sparks.extend(sm.Activity, sparks.Activity, {

        // Initial operation on document when it is loaded
        onDocumentReady: function () {
            var self = this;

            if (sparks.config.debug) {
                $('.debug_area').show();
            }
            else {
               $('.debug_area').hide();
            }
            $('#popup').hide();
            $('.next_button').click(function () {
                window.location.reload();
            });

            this.root_dir = sparks.config.root_dir + '/activities/module-2/series-measuring';
            $('body').scrollTop(0); //scroll to top

            this.forms = $('form');
            this.questionsArea = $('#questions_area');
            this.reportArea = $('#report_area').hide();

            $('button.submit').click(function (e) {
                self.submitButtonClicked();
                e.preventDefault();
            });
        },

        // Initializations that can be done only when the flash movie is loaded
        onFlashReady: function () {
            breadModel('insert', 'wire', 'left_positive_1,a23', 'wire1');
            breadModel('insert', 'wire', 'left_negative_1,c5', 'wire2');
            this.multimeter = new sparks.circuit.Multimeter2();

            this.startTry();
        },

        submitButtonClicked: function () {
            if (this.currentQuestion == 3) {
                this.completedTry();
            }
            else {
                ++ this.currentQuestion;
                this.disableForm(this.currentQuestion - 1);
                this.enableForm(this.currentQuestion);
            }
        },

        startTry: function () {
            $('.next_button').hide();

            var options = null;
            // this.resistor1 = new sparks.circuit.Resistor4band('resistor1');
            //             this.resistor1.randomize(options);
            //             breadModel('insert', 'resistor', 'b23,b17', this.resistor1.getRealValue(), 'resistor1');
            //             flash.sendCommand('insert_component', 'resistor', 'b23,b17','4band',this.resistor1.colors);

            var resistor1 = breadModel('addRandomResistor', 'resistor1', 'b23,b17');
            flash.sendCommand('insert_component', 'resistor', 'b23,b17','4band',resistor1.colors);

            var resistor2 = breadModel('addRandomResistor', 'resistor2', 'c17,c11');
            flash.sendCommand('insert_component', 'resistor', 'c17,c11','4band',resistor2.colors);

            var resistor3 = breadModel('addRandomResistor', 'resistor2', 'd11,d11');
            flash.sendCommand('insert_component', 'resistor', 'd11,d11','4band',resistor3.colors);

            // this.resistor4 = new sparks.circuit.Resistor4band('resistor4');
            //            this.resistor4.randomize(options);
            //            breadModel('insert', 'resistor', 'c11,c5', this.resistor4.getRealValue(), 'resistor3');
            //            flash.sendCommand('insert_component', 'resistor', 'c11,c5','4band',this.resistor4.colors);
            //
            // $('#dbg_rated_1').text(this.resistor1.getNominalValue());
            // $('#dbg_rated_2').text(this.resistor2.getNominalValue());
            // $('#dbg_rated_3').text(this.resistor3.getNominalValue());
            // $('#dbg_real_1').text(this.resistor1.getRealValue().toFixed(3));
            // $('#dbg_real_2').text(this.resistor2.getRealValue().toFixed(3));
            // $('#dbg_real_3').text(this.resistor3.getRealValue().toFixed(3));
            // $('#dbg_tol_1').text(this.resistor1.getTolerance());
            // $('#dbg_tol_2').text(this.resistor2.getTolerance());
            // $('#dbg_tol_3').text(this.resistor3.getTolerance());

            this.currentQuestion = 0;

            this.enableForm(0);
            for (var i = 1; i < this.forms.length; ++i) {
                this.disableForm(i);
            }
        },

        completedTry: function () {
            this.logResults();
            grader = new sm.Grader(this.log.session, {});
            feedback = grader.grade();
            this.reporter.report(this.log.session, feedback);
            this.questionsArea.hide();
            this.reportArea.show();
            $('.next_button').show();
        },

        resetCircuit: function () {
        },

        enableForm: function (k) {
            $(this.forms[k]).find('input, select, button').attr('disabled', false);
        },

        disableForm: function (k) {
            $(this.forms[k]).find('input, select, button').attr('disabled', true);
        },

        logResults: function () {
        },

        receiveEvent: function (name, value, time) {
            console.log('ENTER sm.Activity#receiveEvent');
            console.log('Received: ' + name + ', ' + value + ', ' + new Date(parseInt(time, 10)));

            var v;
            var t = '';
            var args = value.split('|');

            if (name === 'connect') {
                if (args[0] === 'probe') {
                    if (args[1] === 'probe_red') {
                        this.multimeter.redProbeConnection = args[2];
                    }
                    else if (args[1] === 'probe_black') {
                        this.multimeter.blackProbeConnection = args[2];
                    }
                    else {
                        alert('Activity#receiveEvent: connect: unknonw probe name ' + args[1]);
                    }
                }
                if (args[0] === 'resistor') {
                    // for now, we're just dealing with the situation of replacing one lead that had been lifted
                    if (!!args[3]){
                      breadModel('unmapHole', args[3]);
                    }
                }
                this.multimeter.update();
            } else if (name === 'disconnect') {
                if (args[0] === 'probe') {
                    if (args[1] === 'probe_red') {
                        this.multimeter.redProbeConnection = null;
                    }
                    else if (args[1] === 'probe_black') {
                        this.multimeter.blackProbeConnection = null;
                    }
                    else {
                        alert('Activity#receiveEvent: disconnect: Unknonw probe name ' + args[1]);
                    }
                } else if (args[0] === 'resistor') {
                  var location = args[2].split(",");
                  var hole = args[3];
                  var remainingHole = location[0] === hole ? location[1] : location[0];
                  var newHole = breadModel('getGhostHole', hole+"ghost");

                  breadModel('mapHole', hole, newHole.nodeName());
                }
                this.multimeter.update();
            } else if (name === 'probe') {
                $('#popup').dialog();

                v = breadModel('query', 'voltage', 'a23,a17');
                t += v.toFixed(3);
                v = breadModel('query', 'voltage', 'b17,b11');
                t += ' ' + v.toFixed(3);
                v = breadModel('query', 'voltage', 'c11,c5');
                t += ' ' + v.toFixed(3);
                $('#dbg_voltage').text(t);

                // Disconnect wire1
                breadModel('move', 'wire1', 'left_positive_1,a22');

                v = breadModel('query', 'resistance', 'a23,a17');
                t = v.toFixed(3);
                v = breadModel('query', 'resistance', 'b17,b11');
                t += ' ' + v.toFixed(3);
                v = breadModel('query', 'resistance', 'c11,c5');
                t += ' ' + v.toFixed(3);

                $('#dbg_resistance').text(t);

                v = breadModel('query', 'current', 'a22,a23');
                t = v.toFixed(3);

                breadModel('move', 'wire1', 'left_positive_1,a23');
                breadModel('move', 'resistor1', 'a23,a16');
                v = breadModel('query', 'current', 'a16,b17');
                t += ' ' + v.toFixed(3);

                breadModel('move', 'resistor1', 'a23,a17');
                breadModel('move', 'resistor2', 'b17,b10');
                v = breadModel('query', 'current', 'b10,c11');
                t += ' ' + v.toFixed(3);

                breadModel('move', 'resistor2', 'b17,b11');

                $('#dbg_current').text(t);

                $('#popup').dialog('close');
            } else if (name == 'multimeter_dial') {
                console.log('changed multimeter dial'+value);
                this.multimeter.dialPosition = value;
                this.multimeter.update();
                // activity.log.add(name, { value: this.multimeter.dialPosition });
            } else if (name == 'multimeter_power') {
                this.multimeter.powerOn = value == 'true' ? true : false;
                this.multimeter.update();
                // activity.log.add(name, { value: this.multimeter.powerOn });
                //                 if (value === 'true' && this.multimeter.allConnected()) {
                //                     activity.log.add('make_circuit');
                //                 } else if (value == 'false' && wasConnected) {
                //                     activity.log.add('break_circuit');
                //                 }
            }
        }

    });

})();
<|endoftext|>


<commit_before>var config = require('../config');

var gulp = require('gulp');
var gutil = require('gulp-util');

var filter = require('gulp-filter');
var sourcemaps = require('gulp-sourcemaps');
var plumber = require('gulp-plumber');
var uglify = require('gulp-uglify');

var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');

var watchify = require('watchify');
var browserify = require('browserify');

// transforms
var babelify = require('babelify');
var partialify = require('partialify');
var stripify = require('stripify');

gulp.task('browserify:dev', function() {
    var bundler = watchify(browserify({
        entries: [config.browserify.in],
        cache: {},
        packageCache: {},
        fullPaths: true
    }));

    var bundle = function() {
        return bundler.bundle()
            .pipe(plumber())
            .on('error', gutil.log.bind(gutil, 'Browserify Error'))
            .pipe(source(config.browserify.out))
            .pipe(buffer())
            .pipe(sourcemaps.init({
                loadMaps: true
            }))
            .pipe(sourcemaps.write('./'))
            .pipe(filter('*.min.js'))
            .pipe(gulp.dest(config.build));
    };

    bundler.on('error', gutil.log.bind(gutil, 'Browserify Error'));

    bundler.on('update', bundle);

    // bundler.on('log', function(msg) {
    //     gutil.log('Browserify build: ', gutil.colors.magenta(msg));
    // });

    return bundle();
});

gulp.task('browserify:build', function() {

    var bundler = browserify({
        entries: [config.browserify.in]
    });

    var bundle = function() {
        bundler
            .bundle()
            .pipe(source(config.browserify.out))
            .pipe(buffer())
            .pipe(gulp.dest(config.build));
        // Add transformation tasks to the pipeline here.

        return bundler
            .bundle()
            .pipe(source(config.browserify.minOut))
            .pipe(buffer())
            .pipe(uglify())
            .pipe(gulp.dest(config.build));
    };

    return bundle();
});
<commit_msg>fix(gulp): Fixes some build issues<commit_after>var config = require('../config');

var gulp = require('gulp');
var gutil = require('gulp-util');

var filter = require('gulp-filter');
var sourcemaps = require('gulp-sourcemaps');
var plumber = require('gulp-plumber');
var uglify = require('gulp-uglify');

var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');

var watchify = require('watchify');
var browserify = require('browserify');

// transforms
var babelify = require('babelify');
var partialify = require('partialify');
var stripify = require('stripify');

gulp.task('browserify:dev', function() {
    var bundler = watchify(browserify({
        entries: [config.browserify.in],
        exclude: ['lodash'],
        cache: {},
        packageCache: {},
        fullPaths: true
    }))
    .exclude('lodash');

    var bundle = function() {
        return bundler.bundle()
            .pipe(plumber())
            .on('error', gutil.log.bind(gutil, 'Browserify Error'))
            .pipe(source(config.browserify.out))
            .pipe(buffer())
            .pipe(sourcemaps.init({
                loadMaps: true
            }))
            .pipe(sourcemaps.write('./'))
            .pipe(filter('*.min.js'))
            .pipe(gulp.dest(config.build));
    };

    bundler.on('error', gutil.log.bind(gutil, 'Browserify Error'));

    bundler.on('update', bundle);

    // bundler.on('log', function(msg) {
    //     gutil.log('Browserify build: ', gutil.colors.magenta(msg));
    // });

    return bundle();
});

gulp.task('browserify:build', function() {

    var bundler = browserify({
        entries: [config.browserify.in],

    })
    .exclude('lodash');

    var bundle = function() {
        bundler
            .bundle()
            .pipe(source(config.browserify.out))
            .pipe(buffer())
            .pipe(gulp.dest(config.build));
        // Add transformation tasks to the pipeline here.

        return bundler
            .bundle()
            .pipe(source(config.browserify.minOut))
            .pipe(buffer())
            .pipe(uglify())
            .pipe(gulp.dest(config.build));
    };

    return bundle();
});
<|endoftext|>


<commit_before>import { define } from '../lib/obj-define.js';
import { reduceObjectProperty } from '../lib/reduce.js';
import { isString, isFunction } from '../lib/typeof.js';
import { matches } from '../lib/matches.js';
import { dispatch } from '../lib/dispatch.js';

/**
 * Check if an event has a selector in mathc in target list.
 * @private
 *
 * @param {Event} event The event to check.
 * @param {HTMLElement} node The root node.
 * @param {String} selector The CSS selector to match.
 * @return {HTMLElement} The element in target list which matches the selector.
 */
function checkDelegate(event, node, selector) {
    if (!selector) {
        return node;
    }
    let target = event.target;
    while (target && target !== node) {
        if (matches(target, selector)) {
            return target;
        }
        target = target.parentNode;
    }
    return null;
}
/**
 * Generate a delegate listener for an event.
 * @private
 *
 * @param {String} selector The CSS selector to match.
 * @param {Function} callback The original callback for the event.
 * @return {Function} Wrapped callback with a delegation check.
 */
function delegateCallback(selector, callback) {
    return (ev) => {
        let target = checkDelegate(ev, this.node, selector);
        if (target) {
            callback.call(this, ev, target);
        }
    };
}

/**
 * Simple Custom Component with events delegation,
 * It also implement a `dispatchEvent` wrapper named `trigger`.
 * @mixin EventsMixin
 * @memberof DNA.MIXINS.
 * @static
 *
 * @example
 * ```js
 * // my-component.js
 * import { BaseComponent } from '@dnajs/core';
 * export class MyComponent extends BaseComponent {
 *   get events() {
 *     return {
 *       'click button': 'onButtonClick'
 *     }
 *   }
 *   onButtonClick() {
 *     console.log('button clicked');
 *   }
 * }
 * ```
 * ```js
 * // app.js
 * import { define } from '@dnajs/core';
 * import { MyComponent } from './my-component.js';
 * define('my-component', MyComponent);
 * var element = new MyComponent();
 * var button = document.createElement('button');
 * button.innerText = 'Click me';
 * element.appendChild(button);
 * button.click(); // logs "button clicked"
 * ```
 */
export const EventsMixin = (SuperClass) => class extends SuperClass {
    /**
     * Iterate `events` properties.
     * @method constructor
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     */
    constructor(node) {
        super(node);
        let events = reduceObjectProperty(this, 'events');
        for (let k in events) {
            let callback = isString(events[k]) ?
                this[events[k]] :
                events[k];
            if (isFunction(callback)) {
                let selector = k.split(' ').slice(1).join(' ').trim();
                events[k] = delegateCallback.call(this, selector, callback);
            } else {
                throw new TypeError('Invalid callback for event.');
            }
        }
        define(this, 'events', { value: events });
    }
    /**
     * Attach and delegate events to the component.
     * @method connectedCallback
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     */
    connectedCallback() {
        super.connectedCallback();
        // bind events
        let events = this.events;
        for (let k in events) {
            let evName = k.split(' ').shift();
            this.node.addEventListener(evName, events[k]);
        }
    }
    /**
     * Detach and undelegate events from the component.
     * @method disconnectedCallback
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     */
    disconnectedCallback() {
        let events = this.events;
        for (let k in events) {
            let evName = k.split(' ').shift();
            this.node.removeEventListener(evName, events[k]);
        }
        super.disconnectedCallback();
    }
    /**
     * Delegate events to the component descendents.
     * @method delegate
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     *
     * @param {String} evName The name of the event to delegate.
     * @param {String} selector A CSS selector for descendents.
     * @param {Function} callback The callback to fire.
     */
    delegate(evName, selector, callback) {
        let wrapCallback = delegateCallback.call(this, selector, callback);
        this.node.addEventListener(evName, wrapCallback);
    }
    /**
     * `Node.prototype.dispatchEvent` wrapper.
     * @method trigger
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     *
     * @param {String} evName The name of the event to fire.
     * @param {Object} data A set of custom data to pass to the event.
     * @param {Boolean} bubbles Should the event bubble throw the DOM tree.
     * @param {Boolean} cancelable Can be the event cancel by a callback.
     * @return {Boolean} True if event propagation has not be stopped.
     */
    trigger(evName, data, bubbles = true, cancelable = true) {
        return dispatch(this.node, evName, data, bubbles, cancelable);
    }
};
<commit_msg>feat: add on and off methods to events mixin prototype<commit_after>import { define } from '../lib/obj-define.js';
import { reduceObjectProperty } from '../lib/reduce.js';
import { isString, isFunction } from '../lib/typeof.js';
import { matches } from '../lib/matches.js';
import { dispatch } from '../lib/dispatch.js';

/**
 * Check if an event has a selector in mathc in target list.
 * @private
 *
 * @param {Event} event The event to check.
 * @param {HTMLElement} node The root node.
 * @param {String} selector The CSS selector to match.
 * @return {HTMLElement} The element in target list which matches the selector.
 */
function checkDelegate(event, node, selector) {
    if (!selector) {
        return node;
    }
    let target = event.target;
    while (target && target !== node) {
        if (matches(target, selector)) {
            return target;
        }
        target = target.parentNode;
    }
    return null;
}
/**
 * Generate a delegate listener for an event.
 * @private
 *
 * @param {String} selector The CSS selector to match.
 * @param {Function} callback The original callback for the event.
 * @return {Function} Wrapped callback with a delegation check.
 */
function delegateCallback(selector, callback) {
    return (ev) => {
        let target = checkDelegate(ev, this.node, selector);
        if (target) {
            callback.call(this, ev, target);
        }
    };
}

/**
 * Simple Custom Component with events delegation,
 * It also implement a `dispatchEvent` wrapper named `trigger`.
 * @mixin EventsMixin
 * @memberof DNA.MIXINS.
 * @static
 *
 * @example
 * ```js
 * // my-component.js
 * import { BaseComponent } from '@dnajs/core';
 * export class MyComponent extends BaseComponent {
 *   get events() {
 *     return {
 *       'click button': 'onButtonClick'
 *     }
 *   }
 *   onButtonClick() {
 *     console.log('button clicked');
 *   }
 * }
 * ```
 * ```js
 * // app.js
 * import { define } from '@dnajs/core';
 * import { MyComponent } from './my-component.js';
 * define('my-component', MyComponent);
 * var element = new MyComponent();
 * var button = document.createElement('button');
 * button.innerText = 'Click me';
 * element.appendChild(button);
 * button.click(); // logs "button clicked"
 * ```
 */
export const EventsMixin = (SuperClass) => class extends SuperClass {
    /**
     * Iterate `events` properties.
     * @method constructor
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     */
    constructor(node) {
        super(node);
        let events = reduceObjectProperty(this, 'events');
        for (let k in events) {
            let callback = isString(events[k]) ?
                this[events[k]] :
                events[k];
            if (isFunction(callback)) {
                let selector = k.split(' ').slice(1).join(' ').trim();
                events[k] = delegateCallback.call(this, selector, callback);
            } else {
                throw new TypeError('Invalid callback for event.');
            }
        }
        define(this, 'events', { value: events });
    }
    /**
     * Attach and delegate events to the component.
     * @method connectedCallback
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     */
    connectedCallback() {
        super.connectedCallback();
        // bind events
        let events = this.events;
        for (let k in events) {
            let evName = k.split(' ').shift();
            this.on(evName, events[k]);
        }
    }
    /**
     * Detach and undelegate events from the component.
     * @method disconnectedCallback
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     */
    disconnectedCallback() {
        let events = this.events;
        for (let k in events) {
            let evName = k.split(' ').shift();
            this.off(evName, events[k]);
        }
        super.disconnectedCallback();
    }
    /**
     * Delegate events to the component descendents.
     * @method delegate
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     *
     * @param {String} evName The name of the event to delegate.
     * @param {String} selector A CSS selector for descendents.
     * @param {Function} callback The callback to fire.
     */
    delegate(evName, selector, callback) {
        let wrapCallback = delegateCallback.call(this, selector, callback);
        return this.on(evName, wrapCallback);
    }
    /**
     * `Node.prototype.addEventListener` wrapper.
     * @method on
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     *
     * @param {String} evName The name of the event to fire.
     * @param {Function} callback The callback to fire.
     * @param {Object} options Listener options.
     */
    on(evName, callback, options) {
        return this.node.addEventListener(evName, callback, options);
    }
    /**
     * `Node.prototype.removeEventListener` wrapper.
     * @method off
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     *
     * @param {String} evName The name of the event to unlisten.
     * @param {Function} callback The callback to trim.
     */
    off(evName, callback) {
        return this.node.removeEventListener(evName, callback);
    }
    /**
     * `Node.prototype.dispatchEvent` wrapper.
     * @method trigger
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     *
     * @param {String} evName The name of the event to fire.
     * @param {Object} data A set of custom data to pass to the event.
     * @param {Boolean} bubbles Should the event bubble throw the DOM tree.
     * @param {Boolean} cancelable Can be the event cancel by a callback.
     * @return {Boolean} True if event propagation has not be stopped.
     */
    trigger(evName, data, bubbles = true, cancelable = true) {
        return dispatch(this.node, evName, data, bubbles, cancelable);
    }
};
<|endoftext|>


<commit_before>import {
  callApiSync
} from '../util'

import {
  invoke
} from '../../bridge'

import {
  t
} from 'uni-core/helpers/i18n'

let toast
let toastType
let timeout

export function showLoading (args) {
  return callApiSync(showToast, Object.assign({}, args, {
    type: 'loading'
  }), 'showToast', 'showLoading')
}

export function hideLoading () {
  return callApiSync(hide, 'loading', 'hide', 'hideLoading')
}

export function showToast ({
  title = '',
  icon = 'success',
  image = '',
  duration = 1500,
  mask = false,
  position = '',
  type = 'toast',
  style
} = {}) {
  hide(null)
  toastType = type
  if (['top', 'center', 'bottom'].includes(position)) {
    // 仅可以关闭 richtext 类型，但 iOS 部分情况换行显示有问题
    plus.nativeUI.toast(title, {
      verticalAlign: position
    })
    toast = true
  } else {
    if (icon && !~['success', 'loading', 'error', 'none'].indexOf(icon)) {
      icon = 'success'
    }
    const waitingOptions = {
      modal: mask,
      back: 'transmit',
      padding: '10px',
      size: '16px' // 固定字体大小
    }
    if (!image && (!icon || icon === 'none')) { // 无图
      //       waitingOptions.width = '120px'
      //       waitingOptions.height = '40px'
      waitingOptions.loading = {
        display: 'none'
      }
    } else { // 有图
      waitingOptions.width = '140px'
      waitingOptions.height = '112px'
    }
    if (image) {
      waitingOptions.loading = {
        display: 'block',
        height: '55px',
        icon: image,
        interval: duration
      }
    } else {
      if (icon !== 'loading') {
        waitingOptions.loading = {
          display: 'block',
          height: '55px',
          icon: icon === 'success' ? '__uniappsuccess.png' : '__uniapperror.png',
          interval: duration
        }
      }
    }

    toast = plus.nativeUI.showWaiting(title, Object.assign(waitingOptions, style))
  }

  timeout = setTimeout(() => {
    hide(null)
  }, duration)
  return {
    errMsg: 'showToast:ok'
  }
}

export function hideToast () {
  return callApiSync(hide, 'toast', 'hide', 'hideToast')
}

export function hide (type = 'toast') {
  if (type && type !== toastType) {
    return
  }
  if (timeout) {
    clearTimeout(timeout)
    timeout = null
  }
  if (toast === true) {
    plus.nativeUI.closeToast()
  } else if (toast && toast.close) {
    toast.close()
  }
  toast = null
  toastType = null
  return {
    errMsg: 'hide:ok'
  }
}
export function showModal ({
  title = '',
  content = '',
  showCancel = true,
  cancelText,
  cancelColor,
  confirmText,
  confirmColor
} = {}, callbackId) {
  content = content || ' '
  plus.nativeUI.confirm(content, (e) => {
    if (showCancel) {
      invoke(callbackId, {
        errMsg: 'showModal:ok',
        confirm: e.index === 1,
        cancel: e.index === 0 || e.index === -1
      })
    } else {
      invoke(callbackId, {
        errMsg: 'showModal:ok',
        confirm: e.index === 0,
        cancel: false
      })
    }
  }, title, showCancel ? [cancelText, confirmText] : [confirmText])
}
export function showActionSheet ({
  itemList = [],
  itemColor = '#000000',
  title = '',
  popover
}, callbackId) {
  const options = {
    buttons: itemList.map(item => ({
      title: item,
      color: itemColor
    }))
  }
  if (title) {
    options.title = title
  }

  options.cancel = t('uni.showActionSheet.cancel')

  plus.nativeUI.actionSheet(Object.assign(options, {
    popover
  }), (e) => {
    if (e.index > 0) {
      invoke(callbackId, {
        errMsg: 'showActionSheet:ok',
        tapIndex: e.index - 1
      })
    } else {
      invoke(callbackId, {
        errMsg: 'showActionSheet:fail cancel'
      })
    }
  })
}
<commit_msg>fix(App): showToast 设置 icon 为 none 时，表现错误<commit_after>import {
  callApiSync
} from '../util'

import {
  invoke
} from '../../bridge'

import {
  t
} from 'uni-core/helpers/i18n'

let toast
let toastType
let timeout

export function showLoading (args) {
  return callApiSync(showToast, Object.assign({}, args, {
    type: 'loading'
  }), 'showToast', 'showLoading')
}

export function hideLoading () {
  return callApiSync(hide, 'loading', 'hide', 'hideLoading')
}

export function showToast ({
  title = '',
  icon = 'success',
  image = '',
  duration = 1500,
  mask = false,
  position = '',
  type = 'toast',
  style
} = {}) {
  hide(null)
  toastType = type
  if (['top', 'center', 'bottom'].includes(position)) {
    // 仅可以关闭 richtext 类型，但 iOS 部分情况换行显示有问题
    plus.nativeUI.toast(title, {
      verticalAlign: position
    })
    toast = true
  } else {
    if (icon && !~['success', 'loading', 'error', 'none'].indexOf(icon)) {
      icon = 'success'
    }
    const waitingOptions = {
      modal: mask,
      back: 'transmit',
      padding: '10px',
      size: '16px' // 固定字体大小
    }
    if (!image && (!icon || icon === 'none')) { // 无图
      //       waitingOptions.width = '120px'
      //       waitingOptions.height = '40px'
      waitingOptions.loading = {
        display: 'none'
      }
    } else { // 有图
      waitingOptions.width = '140px'
      waitingOptions.height = '112px'
    }
    if (image) {
      waitingOptions.loading = {
        display: 'block',
        height: '55px',
        icon: image,
        interval: duration
      }
    } else {
      if (['success', 'error'].indexOf(icon) !== -1) {
        waitingOptions.loading = {
          display: 'block',
          height: '55px',
          icon: icon === 'success' ? '__uniappsuccess.png' : '__uniapperror.png',
          interval: duration
        }
      }
    }

    toast = plus.nativeUI.showWaiting(title, Object.assign(waitingOptions, style))
  }

  timeout = setTimeout(() => {
    hide(null)
  }, duration)
  return {
    errMsg: 'showToast:ok'
  }
}

export function hideToast () {
  return callApiSync(hide, 'toast', 'hide', 'hideToast')
}

export function hide (type = 'toast') {
  if (type && type !== toastType) {
    return
  }
  if (timeout) {
    clearTimeout(timeout)
    timeout = null
  }
  if (toast === true) {
    plus.nativeUI.closeToast()
  } else if (toast && toast.close) {
    toast.close()
  }
  toast = null
  toastType = null
  return {
    errMsg: 'hide:ok'
  }
}
export function showModal ({
  title = '',
  content = '',
  showCancel = true,
  cancelText,
  cancelColor,
  confirmText,
  confirmColor
} = {}, callbackId) {
  content = content || ' '
  plus.nativeUI.confirm(content, (e) => {
    if (showCancel) {
      invoke(callbackId, {
        errMsg: 'showModal:ok',
        confirm: e.index === 1,
        cancel: e.index === 0 || e.index === -1
      })
    } else {
      invoke(callbackId, {
        errMsg: 'showModal:ok',
        confirm: e.index === 0,
        cancel: false
      })
    }
  }, title, showCancel ? [cancelText, confirmText] : [confirmText])
}
export function showActionSheet ({
  itemList = [],
  itemColor = '#000000',
  title = '',
  popover
}, callbackId) {
  const options = {
    buttons: itemList.map(item => ({
      title: item,
      color: itemColor
    }))
  }
  if (title) {
    options.title = title
  }

  options.cancel = t('uni.showActionSheet.cancel')

  plus.nativeUI.actionSheet(Object.assign(options, {
    popover
  }), (e) => {
    if (e.index > 0) {
      invoke(callbackId, {
        errMsg: 'showActionSheet:ok',
        tapIndex: e.index - 1
      })
    } else {
      invoke(callbackId, {
        errMsg: 'showActionSheet:fail cancel'
      })
    }
  })
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { createPortal } from 'react-dom';
import classNames from 'classnames';
import { FormattedMessage, injectIntl, defineMessages } from 'react-intl';
import Icon from 'mastodon/components/icon';

const messages = defineMessages({
  show: { id: 'column_header.show_settings', defaultMessage: 'Show settings' },
  hide: { id: 'column_header.hide_settings', defaultMessage: 'Hide settings' },
  moveLeft: { id: 'column_header.moveLeft_settings', defaultMessage: 'Move column to the left' },
  moveRight: { id: 'column_header.moveRight_settings', defaultMessage: 'Move column to the right' },
});

export default @injectIntl
class ColumnHeader extends React.PureComponent {

  static contextTypes = {
    router: PropTypes.object,
  };

  static propTypes = {
    intl: PropTypes.object.isRequired,
    title: PropTypes.node,
    icon: PropTypes.string,
    active: PropTypes.bool,
    multiColumn: PropTypes.bool,
    extraButton: PropTypes.node,
    showBackButton: PropTypes.bool,
    children: PropTypes.node,
    pinned: PropTypes.bool,
    placeholder: PropTypes.bool,
    onPin: PropTypes.func,
    onMove: PropTypes.func,
    onClick: PropTypes.func,
    appendContent: PropTypes.node,
  };

  state = {
    collapsed: true,
    animating: false,
  };

  historyBack = () => {
    if (window.history && window.history.length === 1) {
      this.context.router.history.push('/');
    } else {
      this.context.router.history.goBack();
    }
  }

  handleToggleClick = (e) => {
    e.stopPropagation();
    this.setState({ collapsed: !this.state.collapsed, animating: true });
  }

  handleTitleClick = () => {
    this.props.onClick();
  }

  handleMoveLeft = () => {
    this.props.onMove(-1);
  }

  handleMoveRight = () => {
    this.props.onMove(1);
  }

  handleBackClick = () => {
    this.historyBack();
  }

  handleTransitionEnd = () => {
    this.setState({ animating: false });
  }

  handlePin = () => {
    if (!this.props.pinned) {
      this.historyBack();
    }
    this.props.onPin();
  }

  render () {
    const { title, icon, active, children, pinned, multiColumn, extraButton, showBackButton, intl: { formatMessage }, placeholder, appendContent } = this.props;
    const { collapsed, animating } = this.state;

    const wrapperClassName = classNames('column-header__wrapper', {
      'active': active,
    });

    const buttonClassName = classNames('column-header', {
      'active': active,
    });

    const collapsibleClassName = classNames('column-header__collapsible', {
      'collapsed': collapsed,
      'animating': animating,
    });

    const collapsibleButtonClassName = classNames('column-header__button', {
      'active': !collapsed,
    });

    let extraContent, pinButton, moveButtons, backButton, collapseButton;

    if (children) {
      extraContent = (

          {children}

      );
    }

    if (multiColumn && pinned) {
      pinButton = <button key='pin-button' className='text-btn column-header__setting-btn' onClick={this.handlePin}><Icon id='times' /> <FormattedMessage id='column_header.unpin' defaultMessage='Unpin' /></button>;

      moveButtons = (

          <button title={formatMessage(messages.moveLeft)} aria-label={formatMessage(messages.moveLeft)} className='text-btn column-header__setting-btn' onClick={this.handleMoveLeft}><Icon id='chevron-left' /></button>
          <button title={formatMessage(messages.moveRight)} aria-label={formatMessage(messages.moveRight)} className='text-btn column-header__setting-btn' onClick={this.handleMoveRight}><Icon id='chevron-right' /></button>

      );
    } else if (multiColumn && this.props.onPin) {
      pinButton = <button key='pin-button' className='text-btn column-header__setting-btn' onClick={this.handlePin}><Icon id='plus' /> <FormattedMessage id='column_header.pin' defaultMessage='Pin' /></button>;
    }

    if (!pinned && (multiColumn || showBackButton)) {
      backButton = (
        <button onClick={this.handleBackClick} className='column-header__back-button'>
          <Icon id='chevron-left' className='column-back-button__icon' fixedWidth />
          <FormattedMessage id='column_back_button.label' defaultMessage='Back' />
        </button>
      );
    }

    const collapsedContent = [
      extraContent,
    ];

    if (multiColumn) {
      collapsedContent.push(moveButtons);
      collapsedContent.push(pinButton);
    }

    if (children || (multiColumn && this.props.onPin)) {
      collapseButton = <button className={collapsibleButtonClassName} title={formatMessage(collapsed ? messages.show : messages.hide)} aria-label={formatMessage(collapsed ? messages.show : messages.hide)} aria-pressed={collapsed ? 'false' : 'true'} onClick={this.handleToggleClick}><Icon id='sliders' /></button>;
    }

    const hasTitle = icon && title;

    const component = (

          {hasTitle && (
            <button onClick={this.handleTitleClick}>
              <Icon id={icon} fixedWidth className='column-header__icon' />
              {title}
            </button>
          )}

          {!hasTitle && backButton}

            {hasTitle && backButton}
            {extraButton}
            {collapseButton}

            {(!collapsed || animating) && collapsedContent}

        {appendContent}

    );

    if (multiColumn || placeholder) {
      return component;
    } else {
      // The portal container and the component may be rendered to the DOM in
      // the same React render pass, so the container might not be available at
      // the time `render()` is called.
      const container = document.getElementById('tabs-bar__portal');
      if (container === null) {
        // The container wasn't available, force a re-render so that the
        // component can eventually be inserted in the container and not scroll
        // with the rest of the area.
        this.forceUpdate();
        return component;
      } else {
        return createPortal(component, container);
      }
    }
  }

}
<commit_msg>Fix pinning a column in web UI sometimes redirecting out of web UI (#13376)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { createPortal } from 'react-dom';
import classNames from 'classnames';
import { FormattedMessage, injectIntl, defineMessages } from 'react-intl';
import Icon from 'mastodon/components/icon';

const messages = defineMessages({
  show: { id: 'column_header.show_settings', defaultMessage: 'Show settings' },
  hide: { id: 'column_header.hide_settings', defaultMessage: 'Hide settings' },
  moveLeft: { id: 'column_header.moveLeft_settings', defaultMessage: 'Move column to the left' },
  moveRight: { id: 'column_header.moveRight_settings', defaultMessage: 'Move column to the right' },
});

export default @injectIntl
class ColumnHeader extends React.PureComponent {

  static contextTypes = {
    router: PropTypes.object,
  };

  static propTypes = {
    intl: PropTypes.object.isRequired,
    title: PropTypes.node,
    icon: PropTypes.string,
    active: PropTypes.bool,
    multiColumn: PropTypes.bool,
    extraButton: PropTypes.node,
    showBackButton: PropTypes.bool,
    children: PropTypes.node,
    pinned: PropTypes.bool,
    placeholder: PropTypes.bool,
    onPin: PropTypes.func,
    onMove: PropTypes.func,
    onClick: PropTypes.func,
    appendContent: PropTypes.node,
  };

  state = {
    collapsed: true,
    animating: false,
  };

  historyBack = () => {
    if (window.history && window.history.length === 1) {
      this.context.router.history.push('/');
    } else {
      this.context.router.history.goBack();
    }
  }

  handleToggleClick = (e) => {
    e.stopPropagation();
    this.setState({ collapsed: !this.state.collapsed, animating: true });
  }

  handleTitleClick = () => {
    this.props.onClick();
  }

  handleMoveLeft = () => {
    this.props.onMove(-1);
  }

  handleMoveRight = () => {
    this.props.onMove(1);
  }

  handleBackClick = () => {
    this.historyBack();
  }

  handleTransitionEnd = () => {
    this.setState({ animating: false });
  }

  handlePin = () => {
    if (!this.props.pinned) {
      this.context.router.history.replace('/');
    }

    this.props.onPin();
  }

  render () {
    const { title, icon, active, children, pinned, multiColumn, extraButton, showBackButton, intl: { formatMessage }, placeholder, appendContent } = this.props;
    const { collapsed, animating } = this.state;

    const wrapperClassName = classNames('column-header__wrapper', {
      'active': active,
    });

    const buttonClassName = classNames('column-header', {
      'active': active,
    });

    const collapsibleClassName = classNames('column-header__collapsible', {
      'collapsed': collapsed,
      'animating': animating,
    });

    const collapsibleButtonClassName = classNames('column-header__button', {
      'active': !collapsed,
    });

    let extraContent, pinButton, moveButtons, backButton, collapseButton;

    if (children) {
      extraContent = (

          {children}

      );
    }

    if (multiColumn && pinned) {
      pinButton = <button key='pin-button' className='text-btn column-header__setting-btn' onClick={this.handlePin}><Icon id='times' /> <FormattedMessage id='column_header.unpin' defaultMessage='Unpin' /></button>;

      moveButtons = (

          <button title={formatMessage(messages.moveLeft)} aria-label={formatMessage(messages.moveLeft)} className='text-btn column-header__setting-btn' onClick={this.handleMoveLeft}><Icon id='chevron-left' /></button>
          <button title={formatMessage(messages.moveRight)} aria-label={formatMessage(messages.moveRight)} className='text-btn column-header__setting-btn' onClick={this.handleMoveRight}><Icon id='chevron-right' /></button>

      );
    } else if (multiColumn && this.props.onPin) {
      pinButton = <button key='pin-button' className='text-btn column-header__setting-btn' onClick={this.handlePin}><Icon id='plus' /> <FormattedMessage id='column_header.pin' defaultMessage='Pin' /></button>;
    }

    if (!pinned && (multiColumn || showBackButton)) {
      backButton = (
        <button onClick={this.handleBackClick} className='column-header__back-button'>
          <Icon id='chevron-left' className='column-back-button__icon' fixedWidth />
          <FormattedMessage id='column_back_button.label' defaultMessage='Back' />
        </button>
      );
    }

    const collapsedContent = [
      extraContent,
    ];

    if (multiColumn) {
      collapsedContent.push(moveButtons);
      collapsedContent.push(pinButton);
    }

    if (children || (multiColumn && this.props.onPin)) {
      collapseButton = <button className={collapsibleButtonClassName} title={formatMessage(collapsed ? messages.show : messages.hide)} aria-label={formatMessage(collapsed ? messages.show : messages.hide)} aria-pressed={collapsed ? 'false' : 'true'} onClick={this.handleToggleClick}><Icon id='sliders' /></button>;
    }

    const hasTitle = icon && title;

    const component = (

          {hasTitle && (
            <button onClick={this.handleTitleClick}>
              <Icon id={icon} fixedWidth className='column-header__icon' />
              {title}
            </button>
          )}

          {!hasTitle && backButton}

            {hasTitle && backButton}
            {extraButton}
            {collapseButton}

            {(!collapsed || animating) && collapsedContent}

        {appendContent}

    );

    if (multiColumn || placeholder) {
      return component;
    } else {
      // The portal container and the component may be rendered to the DOM in
      // the same React render pass, so the container might not be available at
      // the time `render()` is called.
      const container = document.getElementById('tabs-bar__portal');
      if (container === null) {
        // The container wasn't available, force a re-render so that the
        // component can eventually be inserted in the container and not scroll
        // with the rest of the area.
        this.forceUpdate();
        return component;
      } else {
        return createPortal(component, container);
      }
    }
  }

}
<|endoftext|>


<commit_before>/**
 * Copyright JS Foundation and other contributors, http://js.foundation
 *
 * 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.
 **/

module.exports = function(RED) {
    "use strict";

    function ChangeNode(n) {
        RED.nodes.createNode(this, n);
        var node = this;

        this.rules = n.rules;
        var rule;
        if (!this.rules) {
            rule = {
                t:(n.action=="replace"?"set":n.action),
                p:n.property||""
            }

            if ((rule.t === "set")||(rule.t === "move")) {
                rule.to = n.to||"";
            } else if (rule.t === "change") {
                rule.from = n.from||"";
                rule.to = n.to||"";
                rule.re = (n.reg===null||n.reg);
            }
            this.rules = [rule];
        }

        var valid = true;
        for (var i=0;i<this.rules.length;i++) {
            rule = this.rules[i];
            // Migrate to type-aware rules
            if (!rule.pt) {
                rule.pt = "msg";
            }
            if (rule.t === "change" && rule.re) {
                rule.fromt = 're';
                delete rule.re;
            }
            if (rule.t === "set" && !rule.tot) {
                if (rule.to.indexOf("msg.") === 0 && !rule.tot) {
                    rule.to = rule.to.substring(4);
                    rule.tot = "msg";
                }
            }
            if (!rule.tot) {
                rule.tot = "str";
            }
            if (!rule.fromt) {
                rule.fromt = "str";
            }
            if (rule.t === "change" && rule.fromt !== 'msg' && rule.fromt !== 'flow' && rule.fromt !== 'global') {
                rule.fromRE = rule.from;
                if (rule.fromt !== 're') {
                    rule.fromRE = rule.fromRE.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
                }
                try {
                    rule.fromRE = new RegExp(rule.fromRE, "g");
                } catch (e) {
                    valid = false;
                    this.error(RED._("change.errors.invalid-from",{error:e.message}));
                }
            }
            if (rule.tot === 'num') {
                rule.to = Number(rule.to);
            } else if (rule.tot === 'json' || rule.tot === 'bin') {
                try {
                    // check this is parsable JSON
                    JSON.parse(rule.to);
                } catch(e2) {
                    valid = false;
                    this.error(RED._("change.errors.invalid-json"));
                }
            } else if (rule.tot === 'bool') {
                rule.to = /^true$/i.test(rule.to);
            } else if (rule.tot === 'jsonata') {
                try {
                    rule.to = RED.util.prepareJSONataExpression(rule.to,this);
                } catch(e) {
                    valid = false;
                    this.error(RED._("change.errors.invalid-expr",{error:e.message}));
                }
            } else if (rule.tot === 'env') {
                rule.to = RED.util.evaluateNodeProperty(rule.to,'env',node);
            }
        }

        function getToValue(msg,rule,done) {
            var value = rule.to;
            if (rule.tot === 'json') {
                value = JSON.parse(rule.to);
            } else if (rule.tot === 'bin') {
                value = Buffer.from(JSON.parse(rule.to))
            }
            if (rule.tot === "msg") {
                value = RED.util.getMessageProperty(msg,rule.to);
            } else if ((rule.tot === 'flow') || (rule.tot === 'global')) {
                RED.util.evaluateNodeProperty(rule.to, rule.tot, node, msg, (err,value) => {
                    if (err) {
                        done(undefined,undefined);
                    } else {
                        done(undefined,value);
                    }
                });
                return
            } else if (rule.tot === 'date') {
                value = Date.now();
            } else if (rule.tot === 'jsonata') {
                RED.util.evaluateJSONataExpression(rule.to,msg, (err, value) => {
                    if (err) {
                        done(RED._("change.errors.invalid-expr",{error:err.message}))
                    } else {
                        done(undefined, value);
                    }
                });
                return;
            }
            done(undefined,value);
        }

        function getFromValueType(fromValue, done) {
            var fromType;
            var fromRE;
            if (typeof fromValue === 'number' || fromValue instanceof Number) {
                fromType = 'num';
            } else if (typeof fromValue === 'boolean') {
                fromType = 'bool'
            } else if (fromValue instanceof RegExp) {
                fromType = 're';
                fromRE = fromValue;
            } else if (typeof fromValue === 'string') {
                fromType = 'str';
                fromRE = fromValue.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
                try {
                    fromRE = new RegExp(fromRE, "g");
                } catch (e) {
                    done(new Error(RED._("change.errors.invalid-from",{error:e.message})));
                }
            } else {
                done(new Error(RED._("change.errors.invalid-from",{error:"unsupported type: "+(typeof fromValue)})));
            }
            done(undefined,{
                fromType,
                fromValue,
                fromRE
            });
        }
        function getFromValue(msg,rule, done) {
            var fromValue;
            var fromType;
            var fromRE;
            if (rule.t === 'change') {
                if (rule.fromt === 'msg' || rule.fromt === 'flow' || rule.fromt === 'global') {
                    if (rule.fromt === "msg") {
                        return getFromValueType(RED.util.getMessageProperty(msg,rule.from),done);
                    } else if (rule.fromt === 'flow' || rule.fromt === 'global') {
                        var contextKey = RED.util.parseContextStore(rule.from);
                        if (/\[msg\./.test(context.key)) {
                            // The key has a nest msg. reference to evaluate first
                            context.key = RED.util.normalisePropertyExpression(contextKey.key,msg,true);
                        }
                        node.context()[rule.fromt].get(contextKey.key, contextKey.store, (err,fromValue) => {
                            if (err) {
                                done(err)
                            } else {
                                getFromValueType(fromValue,done);
                            }
                        });
                        return;
                    }
                } else {
                    fromType = rule.fromt;
                    fromValue = rule.from;
                    fromRE = rule.fromRE;
                }
            }
            done(undefined, {
                fromType,
                fromValue,
                fromRE
            });
        }
        function applyRule(msg,rule,done) {
            var property = rule.p;
            var current;
            var fromValue;
            var fromType;
            var fromRE;

            try {
                getToValue(msg,rule,(err,value) => {
                    if (err) {
                        node.error(err, msg);
                        return done(undefined,null);
                    } else {
                        if (rule.dc) {
                            value = RED.util.cloneMessage(value);
                        }
                        getFromValue(msg,rule,(err,fromParts) => {
                            if (err) {
                                node.error(err, msg);
                                return done(undefined,null);
                            } else {
                                fromValue = fromParts.fromValue;
                                fromType = fromParts.fromType;
                                fromRE = fromParts.fromRE;
                                if (rule.pt === 'msg') {
                                    try {
                                        if (rule.t === 'delete') {
                                            RED.util.setMessageProperty(msg,property,undefined);
                                        } else if (rule.t === 'set') {
                                            if (!RED.util.setMessageProperty(msg,property,value)) {
                                                node.warn(RED._("change.errors.no-override",{property:property}));
                                            }
                                        } else if (rule.t === 'change') {
                                            current = RED.util.getMessageProperty(msg,property);
                                            if (typeof current === 'string') {
                                                if ((fromType === 'num' || fromType === 'bool' || fromType === 'str') && current === fromValue) {
                                                    // str representation of exact from number/boolean
                                                    // only replace if they match exactly
                                                    RED.util.setMessageProperty(msg,property,value);
                                                } else {
                                                    current = current.replace(fromRE,value);
                                                    RED.util.setMessageProperty(msg,property,current);
                                                }
                                            } else if ((typeof current === 'number' || current instanceof Number) && fromType === 'num') {
                                                if (current == Number(fromValue)) {
                                                    RED.util.setMessageProperty(msg,property,value);
                                                }
                                            } else if (typeof current === 'boolean' && fromType === 'bool') {
                                                if (current.toString() === fromValue) {
                                                    RED.util.setMessageProperty(msg,property,value);
                                                }
                                            }
                                        }
                                    } catch(err) {}
                                    return done(undefined,msg);
                                } else if (rule.pt === 'flow' || rule.pt === 'global') {
                                    var contextKey = RED.util.parseContextStore(property);
                                    if (/\[msg/.test(contextKey.key)) {
                                        // The key has a nest msg. reference to evaluate first
                                        contextKey.key = RED.util.normalisePropertyExpression(contextKey.key, msg, true)
                                    }
                                    var target = node.context()[rule.pt];
                                    var callback = err => {
                                        if (err) {
                                            node.error(err, msg);
                                            return done(undefined,null);
                                        } else {
                                            done(undefined,msg);
                                        }
                                    }
                                    if (rule.t === 'delete') {
                                        target.set(contextKey.key,undefined,contextKey.store,callback);
                                    } else if (rule.t === 'set') {
                                        target.set(contextKey.key,value,contextKey.store,callback);
                                    } else if (rule.t === 'change') {
                                        target.get(contextKey.key,contextKey.store,(err,current) => {
                                            if (err) {
                                                node.error(err, msg);
                                                return done(undefined,null);
                                            }
                                            if (typeof current === 'string') {
                                                if ((fromType === 'num' || fromType === 'bool' || fromType === 'str') && current === fromValue) {
                                                    // str representation of exact from number/boolean
                                                    // only replace if they match exactly
                                                    target.set(contextKey.key,value,contextKey.store,callback);
                                                } else {
                                                    current = current.replace(fromRE,value);
                                                    target.set(contextKey.key,current,contextKey.store,callback);
                                                }
                                            } else if ((typeof current === 'number' || current instanceof Number) && fromType === 'num') {
                                                if (current == Number(fromValue)) {
                                                    target.set(contextKey.key,value,contextKey.store,callback);
                                                }
                                            } else if (typeof current === 'boolean' && fromType === 'bool') {
                                                if (current.toString() === fromValue) {
                                                    target.set(contextKey.key,value,contextKey.store,callback);
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                        })
                    }
                });
            } catch(err) {
                // This is an okay error
                done(undefined,msg);
            }
        }
        function completeApplyingRules(msg,currentRule,done) {
            if (!msg) {
                return done();
            } else if (currentRule === node.rules.length - 1) {
                return done(undefined, msg);
            } else {
                applyRules(msg, currentRule+1,done);
            }
        }
        function applyRules(msg, currentRule, done) {
            if (currentRule >= node.rules.length) {
                return done(undefined,msg);
            }
            var r = node.rules[currentRule];
            if (r.t === "move") {
                if ((r.tot !== r.pt) || (r.p.indexOf(r.to) !== -1)) {
                    applyRule(msg,{t:"set", p:r.to, pt:r.tot, to:r.p, tot:r.pt},(err,msg) => {
                        applyRule(msg,{t:"delete", p:r.p, pt:r.pt}, (err,msg) => {
                            completeApplyingRules(msg,currentRule,done);
                        })
                    });
                } else { // 2 step move if we are moving from a child
                    applyRule(msg,{t:"set", p:"_temp_move", pt:r.tot, to:r.p, tot:r.pt},(err,msg)=> {
                        applyRule(msg,{t:"delete", p:r.p, pt:r.pt},(err,msg)=> {
                            applyRule(msg,{t:"set", p:r.to, pt:r.tot, to:"_temp_move", tot:r.pt},(err,msg)=> {
                                applyRule(msg,{t:"delete", p:"_temp_move", pt:r.pt},(err,msg)=> {
                                    completeApplyingRules(msg,currentRule,done);
                                });
                            });
                        });
                    });
                }
            } else {
                applyRule(msg,r,(err,msg)=> { completeApplyingRules(msg,currentRule,done); });
            }
        }

        if (valid) {
            this.on('input', function(msg, send, done) {
                applyRules(msg, 0, (err,msg) => {
                    if (err) {
                        done(err);
                    } else if (msg) {
                        send(msg);
                        done();
                    }
                })
            });
        }
    }
    RED.nodes.registerType("change", ChangeNode);
};
<commit_msg>Fix change node, not handling from field properly when using context<commit_after>/**
 * Copyright JS Foundation and other contributors, http://js.foundation
 *
 * 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.
 **/

module.exports = function(RED) {
    "use strict";

    function ChangeNode(n) {
        RED.nodes.createNode(this, n);
        var node = this;

        this.rules = n.rules;
        var rule;
        if (!this.rules) {
            rule = {
                t:(n.action=="replace"?"set":n.action),
                p:n.property||""
            }

            if ((rule.t === "set")||(rule.t === "move")) {
                rule.to = n.to||"";
            } else if (rule.t === "change") {
                rule.from = n.from||"";
                rule.to = n.to||"";
                rule.re = (n.reg===null||n.reg);
            }
            this.rules = [rule];
        }

        var valid = true;
        for (var i=0;i<this.rules.length;i++) {
            rule = this.rules[i];
            // Migrate to type-aware rules
            if (!rule.pt) {
                rule.pt = "msg";
            }
            if (rule.t === "change" && rule.re) {
                rule.fromt = 're';
                delete rule.re;
            }
            if (rule.t === "set" && !rule.tot) {
                if (rule.to.indexOf("msg.") === 0 && !rule.tot) {
                    rule.to = rule.to.substring(4);
                    rule.tot = "msg";
                }
            }
            if (!rule.tot) {
                rule.tot = "str";
            }
            if (!rule.fromt) {
                rule.fromt = "str";
            }
            if (rule.t === "change" && rule.fromt !== 'msg' && rule.fromt !== 'flow' && rule.fromt !== 'global') {
                rule.fromRE = rule.from;
                if (rule.fromt !== 're') {
                    rule.fromRE = rule.fromRE.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
                }
                try {
                    rule.fromRE = new RegExp(rule.fromRE, "g");
                } catch (e) {
                    valid = false;
                    this.error(RED._("change.errors.invalid-from",{error:e.message}));
                }
            }
            if (rule.tot === 'num') {
                rule.to = Number(rule.to);
            } else if (rule.tot === 'json' || rule.tot === 'bin') {
                try {
                    // check this is parsable JSON
                    JSON.parse(rule.to);
                } catch(e2) {
                    valid = false;
                    this.error(RED._("change.errors.invalid-json"));
                }
            } else if (rule.tot === 'bool') {
                rule.to = /^true$/i.test(rule.to);
            } else if (rule.tot === 'jsonata') {
                try {
                    rule.to = RED.util.prepareJSONataExpression(rule.to,this);
                } catch(e) {
                    valid = false;
                    this.error(RED._("change.errors.invalid-expr",{error:e.message}));
                }
            } else if (rule.tot === 'env') {
                rule.to = RED.util.evaluateNodeProperty(rule.to,'env',node);
            }
        }

        function getToValue(msg,rule,done) {
            var value = rule.to;
            if (rule.tot === 'json') {
                value = JSON.parse(rule.to);
            } else if (rule.tot === 'bin') {
                value = Buffer.from(JSON.parse(rule.to))
            }
            if (rule.tot === "msg") {
                value = RED.util.getMessageProperty(msg,rule.to);
            } else if ((rule.tot === 'flow') || (rule.tot === 'global')) {
                RED.util.evaluateNodeProperty(rule.to, rule.tot, node, msg, (err,value) => {
                    if (err) {
                        done(undefined,undefined);
                    } else {
                        done(undefined,value);
                    }
                });
                return
            } else if (rule.tot === 'date') {
                value = Date.now();
            } else if (rule.tot === 'jsonata') {
                RED.util.evaluateJSONataExpression(rule.to,msg, (err, value) => {
                    if (err) {
                        done(RED._("change.errors.invalid-expr",{error:err.message}))
                    } else {
                        done(undefined, value);
                    }
                });
                return;
            }
            done(undefined,value);
        }

        function getFromValueType(fromValue, done) {
            var fromType;
            var fromRE;
            if (typeof fromValue === 'number' || fromValue instanceof Number) {
                fromType = 'num';
            } else if (typeof fromValue === 'boolean') {
                fromType = 'bool'
            } else if (fromValue instanceof RegExp) {
                fromType = 're';
                fromRE = fromValue;
            } else if (typeof fromValue === 'string') {
                fromType = 'str';
                fromRE = fromValue.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
                try {
                    fromRE = new RegExp(fromRE, "g");
                } catch (e) {
                    done(new Error(RED._("change.errors.invalid-from",{error:e.message})));
                }
            } else {
                done(new Error(RED._("change.errors.invalid-from",{error:"unsupported type: "+(typeof fromValue)})));
            }
            done(undefined,{
                fromType,
                fromValue,
                fromRE
            });
        }
        function getFromValue(msg,rule, done) {
            var fromValue;
            var fromType;
            var fromRE;
            if (rule.t === 'change') {
                if (rule.fromt === 'msg' || rule.fromt === 'flow' || rule.fromt === 'global') {
                    if (rule.fromt === "msg") {
                        return getFromValueType(RED.util.getMessageProperty(msg,rule.from),done);
                    } else if (rule.fromt === 'flow' || rule.fromt === 'global') {
                        var contextKey = RED.util.parseContextStore(rule.from);
                        if (/\[msg\./.test(contextKey.key)) {
                            // The key has a nest msg. reference to evaluate first
                            contextKey.key = RED.util.normalisePropertyExpression(contextKey.key,msg,true);
                        }
                        node.context()[rule.fromt].get(contextKey.key, contextKey.store, (err,fromValue) => {
                            if (err) {
                                done(err)
                            } else {
                                getFromValueType(fromValue,done);
                            }
                        });
                        return;
                    }
                } else {
                    fromType = rule.fromt;
                    fromValue = rule.from;
                    fromRE = rule.fromRE;
                }
            }
            done(undefined, {
                fromType,
                fromValue,
                fromRE
            });
        }
        function applyRule(msg,rule,done) {
            var property = rule.p;
            var current;
            var fromValue;
            var fromType;
            var fromRE;

            try {
                getToValue(msg,rule,(err,value) => {
                    if (err) {
                        node.error(err, msg);
                        return done(undefined,null);
                    } else {
                        if (rule.dc) {
                            value = RED.util.cloneMessage(value);
                        }
                        getFromValue(msg,rule,(err,fromParts) => {
                            if (err) {
                                node.error(err, msg);
                                return done(undefined,null);
                            } else {
                                fromValue = fromParts.fromValue;
                                fromType = fromParts.fromType;
                                fromRE = fromParts.fromRE;
                                if (rule.pt === 'msg') {
                                    try {
                                        if (rule.t === 'delete') {
                                            RED.util.setMessageProperty(msg,property,undefined);
                                        } else if (rule.t === 'set') {
                                            if (!RED.util.setMessageProperty(msg,property,value)) {
                                                node.warn(RED._("change.errors.no-override",{property:property}));
                                            }
                                        } else if (rule.t === 'change') {
                                            current = RED.util.getMessageProperty(msg,property);
                                            if (typeof current === 'string') {
                                                if ((fromType === 'num' || fromType === 'bool' || fromType === 'str') && current === fromValue) {
                                                    // str representation of exact from number/boolean
                                                    // only replace if they match exactly
                                                    RED.util.setMessageProperty(msg,property,value);
                                                } else {
                                                    current = current.replace(fromRE,value);
                                                    RED.util.setMessageProperty(msg,property,current);
                                                }
                                            } else if ((typeof current === 'number' || current instanceof Number) && fromType === 'num') {
                                                if (current == Number(fromValue)) {
                                                    RED.util.setMessageProperty(msg,property,value);
                                                }
                                            } else if (typeof current === 'boolean' && fromType === 'bool') {
                                                if (current.toString() === fromValue) {
                                                    RED.util.setMessageProperty(msg,property,value);
                                                }
                                            }
                                        }
                                    } catch(err) {}
                                    return done(undefined,msg);
                                } else if (rule.pt === 'flow' || rule.pt === 'global') {
                                    var contextKey = RED.util.parseContextStore(property);
                                    if (/\[msg/.test(contextKey.key)) {
                                        // The key has a nest msg. reference to evaluate first
                                        contextKey.key = RED.util.normalisePropertyExpression(contextKey.key, msg, true)
                                    }
                                    var target = node.context()[rule.pt];
                                    var callback = err => {
                                        if (err) {
                                            node.error(err, msg);
                                            return done(undefined,null);
                                        } else {
                                            done(undefined,msg);
                                        }
                                    }
                                    if (rule.t === 'delete') {
                                        target.set(contextKey.key,undefined,contextKey.store,callback);
                                    } else if (rule.t === 'set') {
                                        target.set(contextKey.key,value,contextKey.store,callback);
                                    } else if (rule.t === 'change') {
                                        target.get(contextKey.key,contextKey.store,(err,current) => {
                                            if (err) {
                                                node.error(err, msg);
                                                return done(undefined,null);
                                            }
                                            if (typeof current === 'string') {
                                                if ((fromType === 'num' || fromType === 'bool' || fromType === 'str') && current === fromValue) {
                                                    // str representation of exact from number/boolean
                                                    // only replace if they match exactly
                                                    target.set(contextKey.key,value,contextKey.store,callback);
                                                } else {
                                                    current = current.replace(fromRE,value);
                                                    target.set(contextKey.key,current,contextKey.store,callback);
                                                }
                                            } else if ((typeof current === 'number' || current instanceof Number) && fromType === 'num') {
                                                if (current == Number(fromValue)) {
                                                    target.set(contextKey.key,value,contextKey.store,callback);
                                                }
                                            } else if (typeof current === 'boolean' && fromType === 'bool') {
                                                if (current.toString() === fromValue) {
                                                    target.set(contextKey.key,value,contextKey.store,callback);
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                        })
                    }
                });
            } catch(err) {
                // This is an okay error
                done(undefined,msg);
            }
        }
        function completeApplyingRules(msg,currentRule,done) {
            if (!msg) {
                return done();
            } else if (currentRule === node.rules.length - 1) {
                return done(undefined, msg);
            } else {
                applyRules(msg, currentRule+1,done);
            }
        }
        function applyRules(msg, currentRule, done) {
            if (currentRule >= node.rules.length) {
                return done(undefined,msg);
            }
            var r = node.rules[currentRule];
            if (r.t === "move") {
                if ((r.tot !== r.pt) || (r.p.indexOf(r.to) !== -1)) {
                    applyRule(msg,{t:"set", p:r.to, pt:r.tot, to:r.p, tot:r.pt},(err,msg) => {
                        applyRule(msg,{t:"delete", p:r.p, pt:r.pt}, (err,msg) => {
                            completeApplyingRules(msg,currentRule,done);
                        })
                    });
                } else { // 2 step move if we are moving from a child
                    applyRule(msg,{t:"set", p:"_temp_move", pt:r.tot, to:r.p, tot:r.pt},(err,msg)=> {
                        applyRule(msg,{t:"delete", p:r.p, pt:r.pt},(err,msg)=> {
                            applyRule(msg,{t:"set", p:r.to, pt:r.tot, to:"_temp_move", tot:r.pt},(err,msg)=> {
                                applyRule(msg,{t:"delete", p:"_temp_move", pt:r.pt},(err,msg)=> {
                                    completeApplyingRules(msg,currentRule,done);
                                });
                            });
                        });
                    });
                }
            } else {
                applyRule(msg,r,(err,msg)=> { completeApplyingRules(msg,currentRule,done); });
            }
        }

        if (valid) {
            this.on('input', function(msg, send, done) {
                applyRules(msg, 0, (err,msg) => {
                    if (err) {
                        done(err);
                    } else if (msg) {
                        send(msg);
                        done();
                    }
                })
            });
        }
    }
    RED.nodes.registerType("change", ChangeNode);
};
<|endoftext|>


<commit_before>import DSLFilterTypes from "#SRC/js/constants/DSLFilterTypes";
import DSLFilter from "#SRC/js/structs/DSLFilter";

/**
 * This filter handles the `text` attributes against taks's `name` value
 */
class TaskNameTextFilter extends DSLFilter {
  /**
   * Handle all `name` attribute filters that we can handle.
   *
   * @override
   */
  filterCanHandle(filterType) {
    return (
      filterType === DSLFilterTypes.EXACT || filterType === DSLFilterTypes.FUZZY
    );
  }

  /**
   * Keep only tasks whose name contains part of the filter's text
   *
   * @override
   */
  filterApply(resultSet, filterType, filterArguments) {
    return resultSet.filterItems(task => {
      return (
        (task.id && task.id.indexOf(filterArguments.text) !== -1) ||
        (task.name && task.name.indexOf(filterArguments.text) !== -1)
      );
    });
  }
}

module.exports = TaskNameTextFilter;
<commit_msg>fix(tasknametextfilter): change indexOf to includes (#2876)<commit_after>import DSLFilterTypes from "#SRC/js/constants/DSLFilterTypes";
import DSLFilter from "#SRC/js/structs/DSLFilter";

/**
 * This filter handles the `text` attributes against taks's `name` value
 */
class TaskNameTextFilter extends DSLFilter {
  /**
   * Handle all `name` attribute filters that we can handle.
   *
   * @override
   */
  filterCanHandle(filterType) {
    return (
      filterType === DSLFilterTypes.EXACT || filterType === DSLFilterTypes.FUZZY
    );
  }

  /**
   * Keep only tasks whose name contains part of the filter's text
   *
   * @override
   */
  filterApply(resultSet, filterType, filterArguments) {
    return resultSet.filterItems(task => {
      return (
        (task.id && task.id.includes(filterArguments.text)) ||
        (task.name && task.name.includes(filterArguments.text))
      );
    });
  }
}

module.exports = TaskNameTextFilter;
<|endoftext|>


<commit_before>var Overlay = new Class({
    Implements: Options,
    options:{
        opacity: 0.5,
        hideObjects: true,
        indicator: true
    },

    initialize: function(parentElement, options) {
        Asset.css('overlay.css');
        this.setOptions(options);

        //определяем родительский элемент
        parentElement = parentElement ? parentElement : document.body;
        if (!parentElement.getElement) parentElement = document;
        this.parentElement = parentElement;
        //создаем елемент но не присоединяем его
        this.element = new Element('div', {'class': 'e-overlay' + ((this.options.indicator) ? ' e-overlay-loading' : ''), 'styles':{'opacity': 0}});
    },
    show: function() {
        this.setupObjects(true);
        if (!(this.parentElement.getElement('.e-overlay'))) {
            this.element.injectInside(this.parentElement);
        }
        this.element.fade(this.options.opacity);
    },

    hide: function() {
        var fx = new Fx.Tween(this.element, {property: 'opacity'});
        this.setupObjects(false);
        fx.start(this.options.opacity, 0).chain(
            function() {
                this.start(0);
            },
            function() {
                this.element = this.element.dispose();
            }.bind(this)
        );
    },
    setupObjects: function(hide) {

        var body;
        if (!this.options.hideObjects) return;
        var elements = $A((body = $(document.body)).getElements('object'));
        elements.extend(
            $A(body.getElements(Browser.Engine.trident ? 'select' : 'embed'))
        );
        elements.each(function(element) {
            element.style.visibility = hide ? 'hidden' : '';
        });
    }
});
<commit_msg>Исправлен оверлей для режима управления блоками<commit_after>var Overlay = new Class({
    Implements: Options,
    options:{
        opacity: 0.5,
        hideObjects: true,
        indicator: true
    },

    initialize: function(parentElement, options) {
        Asset.css('overlay.css');
        this.setOptions(options);

        //определяем родительский элемент
        parentElement = parentElement ? parentElement : document.body;
        if (!parentElement.getElement) parentElement = document;
        this.parentElement = parentElement;
        //создаем елемент но не присоединяем его
        this.element = new Element('div', {'class': 'e-overlay' + ((this.options.indicator) ? ' e-overlay-loading' : ''), 'styles':{'opacity': 0}});
    },
    show: function() {
        this.setupObjects(true);
        if (!this.parentElement.getChildren('.e-overlay').length) {
            this.element.injectInside(this.parentElement);

        }
        this.element.fade(this.options.opacity);
    },

    hide: function() {
        var fx = new Fx.Tween(this.element, {property: 'opacity'});
        this.setupObjects(false);
        fx.start(this.options.opacity, 0).chain(
            function() {
                this.start(0);
            },
            function() {
                this.element = this.element.dispose();
            }.bind(this)
        );
    },
    setupObjects: function(hide) {

        var body;
        if (!this.options.hideObjects) return;
        var elements = $A((body = $(document.body)).getElements('object'));
        elements.extend(
            $A(body.getElements(Browser.Engine.trident ? 'select' : 'embed'))
        );
        elements.each(function(element) {
            element.style.visibility = hide ? 'hidden' : '';
        });
    }
});
<|endoftext|>