<commit_before>/*
 *
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

/**
 *  Settings.js
 *  Presentation Editor
 *
 *  Created by Alexander Yuzhin on 11/22/16
 *  Copyright (c) 2018 Ascensio System SIA. All rights reserved.
 *
 */

define([
    'text!presentationeditor/mobile/app/template/Settings.template',
    'jquery',
    'underscore',
    'backbone'
], function (settingsTemplate, $, _, Backbone) {
    'use strict';

    PE.Views.Settings = Backbone.View.extend(_.extend((function() {
        // private
        var isEdit,
            canEdit = false,
            canDownload = false,
            canAbout = true,
            canHelp = true,
            canPrint = false,
            isShowMacros = true;

        return {
            // el: '.view-main',

            template: _.template(settingsTemplate),

            events: {
                //
            },

            initialize: function () {
                Common.NotificationCenter.on('settingscontainer:show', _.bind(this.initEvents, this));
                Common.Gateway.on('opendocument', _.bind(this.loadDocument, this));
            },

            initEvents: function () {
                var me = this;

                $('#settings-document-info').single('click', _.bind(me.showInfo, me));
                $('#settings-download').single('click', _.bind(me.showDownload, me));
                $('#settings-history').single('click', _.bind(me.showHistory, me));
                $('#settings-help').single('click', _.bind(me.showHelp, me));
                $('#settings-about').single('click', _.bind(me.showAbout, me));
                $('#settings-presentation-setup').single('click', _.bind(me.showSetup, me));
                $('#settings-application').single('click', _.bind(me.showSetApp, me));

                Common.Utils.addScrollIfNeed('.view[data-page=settings-root-view] .pages', '.view[data-page=settings-root-view] .page');
                me.initControls();
            },

            // Render layout
            render: function () {
                this.layout = $('
').append(this.template({
                    android: Common.SharedSettings.get('android'),
                    phone: Common.SharedSettings.get('phone'),
                    scope: this,
                    width: $(window).width(),
                    prodversion: '{{PRODUCT_VERSION}}',
                    publishername: '{{PUBLISHER_NAME}}',
                    publisheraddr: '{{PUBLISHER_ADDRESS}}',
                    publisherurl: '{{PUBLISHER_URL}}',
                    printed_url: ("{{PUBLISHER_URL}}").replace(/https?:\/{2}/, "").replace(/\/$/,""),
                    supportemail: '{{SUPPORT_EMAIL}}',
                    phonenum: '{{PUBLISHER_PHONE}}'
                }));

                return this;
            },

            setMode: function (mode) {
                isEdit = mode.isEdit;
                canEdit = !mode.isEdit && mode.canEdit && mode.canRequestEditRights;
                canDownload = mode.canDownload || mode.canDownloadOrigin;
                canPrint = mode.canPrint;

                if (mode.customization && mode.canBrandingExt) {
                    canAbout = (mode.customization.about!==false);
                }

                if (mode.customization) {
                    canHelp = (mode.customization.help!==false);
                    isShowMacros = (mode.customization.macros!==false);
                }
            },

            rootLayout: function () {
                if (this.layout) {
                    var $layour = this.layout.find('#settings-root-view'),
                        isPhone = Common.SharedSettings.get('phone');

                    if (isEdit) {
                        $layour.find('#settings-readermode').hide();
                        $layour.find('#settings-search .item-title').text(this.textFindAndReplace)
                    } else {
                        $layour.find('#settings-spellcheck').hide();
                        $layour.find('#settings-presentation-setup').hide();
                        $layour.find('#settings-readermode input:checkbox')
                            .attr('checked', Common.SharedSettings.get('readerMode'))
                            .prop('checked', Common.SharedSettings.get('readerMode'));
                    }
                    if (!canDownload) $layour.find('#settings-download').hide();
                    if (!canAbout) $layour.find('#settings-about').hide();
                    if (!canHelp) $layour.find('#settings-help').hide();
                    if (!canPrint) $layour.find('#settings-print').hide();
                    if (!isShowMacros) $layour.find('#settings-macros').hide();

                    return $layour.html();
                }

                return '';
            },

            initControls: function () {
                //
            },

            showPage: function (templateId) {
                var rootView = PE.getController('Settings').rootView();

                if (rootView && this.layout) {
                    var $content = this.layout.find(templateId);

                    // Android fix for navigation
                    if (Framework7.prototype.device.android) {
                        $content.find('.page').append($content.find('.navbar'));
                    }

                    rootView.router.load({
                        content: $content.html()
                    });

                    this.fireEvent('page:show',  [this, templateId]);
                }
            },

            showColorSchemes: function () {
                this.showPage('#color-schemes-view');
            },

            showInfo: function () {
                this.showPage('#settings-info-view');
            },

            showDownload: function () {
                this.showPage('#settings-download-view');
            },

            showHistory: function () {
                this.showPage('#settings-history-view');
            },

            showMacros: function () {
                this.showPage('#settings-macros-view');
            },

            showHelp: function () {
                var url = '{{HELP_URL}}';
                if (url.charAt(url.length-1) !== '/') {
                    url += '/';
                }
                if (Common.SharedSettings.get('sailfish')) {
                    url+='mobile-applications/documents/mobile-web-editors/android/index.aspx';
                } else if (Common.SharedSettings.get('android')) {
                    url+='mobile-applications/documents/mobile-web-editors/android/index.aspx';
                } else {
                    url+='mobile-applications/documents/mobile-web-editors/ios/index.aspx';
                }
                window.open(url, "_blank");
                PE.getController('Settings').hideModal();
            },

            showAbout: function () {
                this.showPage('#settings-about-view');
            },

            showSetup: function () {
                this.showPage('#settings-setup-view');
                $('#color-schemes').single('click', _.bind(this.showColorSchemes, this));
            },

            showSetApp: function () {
                this.showPage('#settings-application-view');
                $('.page[data-page=settings-application-view] .page-content > :not(.display-view)').hide();
                if (isShowMacros) {
                    $('#settings-macros').single('click', _.bind(this.showMacros, this));
                }
            },

            loadDocument: function (data) {
                var permissions = {};

                if (data.doc) {
                    permissions = _.extend(permissions, data.doc.permissions);

                    if (permissions.edit === false) {
                    }
                }
            },

            renderSchemaSettings: function(currentSchema, arrSchemas) {
                if (arrSchemas) {
                    var templateInsert = "";
                    _.each(arrSchemas, function (schema, index) {
                        var colors = schema.get_colors(),//schema.colors;
                            name = schema.get_name();
                        templateInsert += '
<input type="radio" name="color-schema" value="' + index + '"';
                        if (index === currentSchema) {
                            templateInsert += ' checked="checked"'
                        }
                        templateInsert += '>';
                        if (Framework7.prototype.device.android) {
                            templateInsert += '

';
                        }
                        templateInsert += '
';
                        for (var j = 2; j < 7; j++) {
                            var clr = '#' + Common.Utils.ThemeColor.getHexColor(colors[j].get_r(), colors[j].get_g(), colors[j].get_b());
                            templateInsert = templateInsert + ""
                        }
                        templateInsert += '' + name + '

';
                    }, this);
                    $('#color-schemes-content ul').html(templateInsert);
                }
            },

            unknownText: 'Unknown',
            textSettings: 'Settings',
            textFind: 'Find',
            textDone: 'Done',
            textEditPresent: 'Edit Presentation',
            textPresentSetup: 'Presentation Setup',
            textPresentSettings: 'Presentation Settings',
            textDownload: 'Download',
            textPresentInfo: 'Presentation Info',
            textHelp: 'Help',
            textAbout: 'About',
            textBack: 'Back',
            textPresentTitle: 'Presentation Title',
            textLoading: 'Loading...',
            textAuthor: 'Author',
            textCreateDate: 'Create date',
            textDownloadAs: 'Download As...',
            textVersion: 'Version',
            textAddress: 'address',
            textEmail: 'email',
            textTel: 'tel',
            textSlideSize: 'Slide Size',
            mniSlideStandard: 'Standard (4:3)',
            mniSlideWide: 'Widescreen (16:9)',
            textPoweredBy: 'Powered by',
            textFindAndReplace: 'Find and Replace',
            textSpellcheck: 'Spell Checking',
            textPrint: 'Print',
            textApplicationSettings: 'Application Settings',
            textUnitOfMeasurement: 'Unit of Measurement',
            textCentimeter: 'Centimeter',
            textPoint: 'Point',
            textInch: 'Inch',
            textColorSchemes: 'Color Schemes',
            textCollaboration: 'Collaboration',
            textSubject: 'Subject',
            textTitle: 'Title',
            textComment: 'Comment',
            textOwner: 'Owner',
            textApplication : 'Application',
            textCreated: 'Created',
            textLastModified: 'Last Modified',
            textLastModifiedBy: 'Last Modified By',
            textUploaded: 'Uploaded',
            textLocation: 'Location',
            textMacrosSettings: 'Macros Settings',
            textDisableAll: 'Disable All',
            textDisableAllMacrosWithoutNotification: 'Disable all macros without notification',
            textShowNotification: 'Show Notification',
            textDisableAllMacrosWithNotification: 'Disable all macros with notification',
            textEnableAll: 'Enable All',
            textEnableAllMacrosWithoutNotification: 'Enable all macros without notification'
        }
    })(), PE.Views.Settings || {}))
});<commit_msg>[PE] Fix Bug 47109<commit_after>/*
 *
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

/**
 *  Settings.js
 *  Presentation Editor
 *
 *  Created by Alexander Yuzhin on 11/22/16
 *  Copyright (c) 2018 Ascensio System SIA. All rights reserved.
 *
 */

define([
    'text!presentationeditor/mobile/app/template/Settings.template',
    'jquery',
    'underscore',
    'backbone'
], function (settingsTemplate, $, _, Backbone) {
    'use strict';

    PE.Views.Settings = Backbone.View.extend(_.extend((function() {
        // private
        var isEdit,
            canEdit = false,
            canDownload = false,
            canAbout = true,
            canHelp = true,
            canPrint = false,
            isShowMacros = true;

        return {
            // el: '.view-main',

            template: _.template(settingsTemplate),

            events: {
                //
            },

            initialize: function () {
                Common.NotificationCenter.on('settingscontainer:show', _.bind(this.initEvents, this));
                Common.Gateway.on('opendocument', _.bind(this.loadDocument, this));
            },

            initEvents: function () {
                var me = this;

                $('#settings-document-info').single('click', _.bind(me.showInfo, me));
                $('#settings-download').single('click', _.bind(me.showDownload, me));
                $('#settings-history').single('click', _.bind(me.showHistory, me));
                $('#settings-help').single('click', _.bind(me.showHelp, me));
                $('#settings-about').single('click', _.bind(me.showAbout, me));
                $('#settings-presentation-setup').single('click', _.bind(me.showSetup, me));
                $('#settings-application').single('click', _.bind(me.showSetApp, me));

                Common.Utils.addScrollIfNeed('.view[data-page=settings-root-view] .pages', '.view[data-page=settings-root-view] .page');
                me.initControls();
            },

            // Render layout
            render: function () {
                this.layout = $('
').append(this.template({
                    android: Common.SharedSettings.get('android'),
                    phone: Common.SharedSettings.get('phone'),
                    scope: this,
                    width: $(window).width(),
                    prodversion: '{{PRODUCT_VERSION}}',
                    publishername: '{{PUBLISHER_NAME}}',
                    publisheraddr: '{{PUBLISHER_ADDRESS}}',
                    publisherurl: '{{PUBLISHER_URL}}',
                    printed_url: ("{{PUBLISHER_URL}}").replace(/https?:\/{2}/, "").replace(/\/$/,""),
                    supportemail: '{{SUPPORT_EMAIL}}',
                    phonenum: '{{PUBLISHER_PHONE}}'
                }));

                return this;
            },

            setMode: function (mode) {
                isEdit = mode.isEdit;
                canEdit = !mode.isEdit && mode.canEdit && mode.canRequestEditRights;
                canDownload = mode.canDownload || mode.canDownloadOrigin;
                canPrint = mode.canPrint;

                if (mode.customization && mode.canBrandingExt) {
                    canAbout = (mode.customization.about!==false);
                }

                if (mode.customization) {
                    canHelp = (mode.customization.help!==false);
                    isShowMacros = (mode.customization.macros!==false);
                }
            },

            rootLayout: function () {
                if (this.layout) {
                    var $layour = this.layout.find('#settings-root-view'),
                        isPhone = Common.SharedSettings.get('phone');

                    if (isEdit) {
                        $layour.find('#settings-readermode').hide();
                        $layour.find('#settings-search .item-title').text(this.textFindAndReplace)
                    } else {
                        $layour.find('#settings-spellcheck').hide();
                        $layour.find('#settings-presentation-setup').hide();
                        $layour.find('#settings-readermode input:checkbox')
                            .attr('checked', Common.SharedSettings.get('readerMode'))
                            .prop('checked', Common.SharedSettings.get('readerMode'));
                    }
                    if (!canDownload) $layour.find('#settings-download').hide();
                    if (!canAbout) $layour.find('#settings-about').hide();
                    if (!canHelp) $layour.find('#settings-help').hide();
                    if (!canPrint) $layour.find('#settings-print').hide();
                    if (!isShowMacros) $layour.find('#settings-macros').hide();

                    return $layour.html();
                }

                return '';
            },

            initControls: function () {
                //
            },

            showPage: function (templateId) {
                var rootView = PE.getController('Settings').rootView();

                if (rootView && this.layout) {
                    var $content = this.layout.find(templateId);

                    // Android fix for navigation
                    if (Framework7.prototype.device.android) {
                        $content.find('.page').append($content.find('.navbar'));
                    }

                    rootView.router.load({
                        content: $content.html()
                    });

                    this.fireEvent('page:show',  [this, templateId]);
                }
            },

            showColorSchemes: function () {
                this.showPage('#color-schemes-view');
            },

            showInfo: function () {
                this.showPage('#settings-info-view');
            },

            showDownload: function () {
                this.showPage('#settings-download-view');
            },

            showHistory: function () {
                this.showPage('#settings-history-view');
            },

            showMacros: function () {
                this.showPage('#settings-macros-view');
            },

            showHelp: function () {
                var url = '{{HELP_URL}}';
                if (url.charAt(url.length-1) !== '/') {
                    url += '/';
                }
                if (Common.SharedSettings.get('sailfish')) {
                    url+='mobile-applications/documents/mobile-web-editors/android/index.aspx';
                } else if (Common.SharedSettings.get('android')) {
                    url+='mobile-applications/documents/mobile-web-editors/android/index.aspx';
                } else {
                    url+='mobile-applications/documents/mobile-web-editors/ios/index.aspx';
                }
                window.open(url, "_blank");
                PE.getController('Settings').hideModal();
            },

            showAbout: function () {
                this.showPage('#settings-about-view');
            },

            showSetup: function () {
                this.showPage('#settings-setup-view');
                $('#color-schemes').single('click', _.bind(this.showColorSchemes, this));
            },

            showSetApp: function () {
                this.showPage('#settings-application-view');
                if (!isEdit) {
                    $('.page[data-page=settings-application-view] .page-content > :not(.display-view)').hide();
                }
                if (isShowMacros) {
                    $('#settings-macros').single('click', _.bind(this.showMacros, this));
                }
            },

            loadDocument: function (data) {
                var permissions = {};

                if (data.doc) {
                    permissions = _.extend(permissions, data.doc.permissions);

                    if (permissions.edit === false) {
                    }
                }
            },

            renderSchemaSettings: function(currentSchema, arrSchemas) {
                if (arrSchemas) {
                    var templateInsert = "";
                    _.each(arrSchemas, function (schema, index) {
                        var colors = schema.get_colors(),//schema.colors;
                            name = schema.get_name();
                        templateInsert += '
<input type="radio" name="color-schema" value="' + index + '"';
                        if (index === currentSchema) {
                            templateInsert += ' checked="checked"'
                        }
                        templateInsert += '>';
                        if (Framework7.prototype.device.android) {
                            templateInsert += '

';
                        }
                        templateInsert += '
';
                        for (var j = 2; j < 7; j++) {
                            var clr = '#' + Common.Utils.ThemeColor.getHexColor(colors[j].get_r(), colors[j].get_g(), colors[j].get_b());
                            templateInsert = templateInsert + ""
                        }
                        templateInsert += '' + name + '

';
                    }, this);
                    $('#color-schemes-content ul').html(templateInsert);
                }
            },

            unknownText: 'Unknown',
            textSettings: 'Settings',
            textFind: 'Find',
            textDone: 'Done',
            textEditPresent: 'Edit Presentation',
            textPresentSetup: 'Presentation Setup',
            textPresentSettings: 'Presentation Settings',
            textDownload: 'Download',
            textPresentInfo: 'Presentation Info',
            textHelp: 'Help',
            textAbout: 'About',
            textBack: 'Back',
            textPresentTitle: 'Presentation Title',
            textLoading: 'Loading...',
            textAuthor: 'Author',
            textCreateDate: 'Create date',
            textDownloadAs: 'Download As...',
            textVersion: 'Version',
            textAddress: 'address',
            textEmail: 'email',
            textTel: 'tel',
            textSlideSize: 'Slide Size',
            mniSlideStandard: 'Standard (4:3)',
            mniSlideWide: 'Widescreen (16:9)',
            textPoweredBy: 'Powered by',
            textFindAndReplace: 'Find and Replace',
            textSpellcheck: 'Spell Checking',
            textPrint: 'Print',
            textApplicationSettings: 'Application Settings',
            textUnitOfMeasurement: 'Unit of Measurement',
            textCentimeter: 'Centimeter',
            textPoint: 'Point',
            textInch: 'Inch',
            textColorSchemes: 'Color Schemes',
            textCollaboration: 'Collaboration',
            textSubject: 'Subject',
            textTitle: 'Title',
            textComment: 'Comment',
            textOwner: 'Owner',
            textApplication : 'Application',
            textCreated: 'Created',
            textLastModified: 'Last Modified',
            textLastModifiedBy: 'Last Modified By',
            textUploaded: 'Uploaded',
            textLocation: 'Location',
            textMacrosSettings: 'Macros Settings',
            textDisableAll: 'Disable All',
            textDisableAllMacrosWithoutNotification: 'Disable all macros without notification',
            textShowNotification: 'Show Notification',
            textDisableAllMacrosWithNotification: 'Disable all macros with notification',
            textEnableAll: 'Enable All',
            textEnableAllMacrosWithoutNotification: 'Enable all macros without notification'
        }
    })(), PE.Views.Settings || {}))
});<|endoftext|>


<commit_before>workflow_report.links = `
          Filter<input id="link_filter" type="text" class="form-control filter" data-selector=".available_workflow" name="filter" placeholder="Filter...">

          {{#data}}{{name}}{{/data}}

`;<commit_msg>and the file for compilation<commit_after>workflow_report.links = `
          Filter<input id="link_filter" type="text" class="form-control filter" data-selector=".available_workflow" name="filter" placeholder="Filter...">

          {{#data}}{{^unlisted}}{{name}}{{/unlisted}}{{/data}}

`;<|endoftext|>


<commit_before>/*
 * React component to display a graph
 */

import React from 'react';
import PureComponent from '../../immutable-component';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import debounce from '../../misc/debounce';

export default class Graph extends PureComponent {
    constructor(props) {
        super(props);

        const { width, height, padding } = props;

        this.state = {
            ctx: null,
            canvas: null,
            width,
            height,
            padding: padding || [0, 0, 0, 0],
            canvasProperties: {},
            outerProperties: {}
        };

        this.onResize = debounce(() => {
            if (window.innerWidth < this.width) {
                this.setState({
                    width: window.innerWidth
                });
            }
        }, 100);
    }
    draw() {
        if (!this.state.ctx) {
            return;
        }

        this.state.ctx.clearRect(0, 0, this.state.width, this.state.height);

        this.props.onDraw(this.props, this.state, this);
    }
    componentDidMount() {
        window.addEventListener('resize', this.onResize);
    }
    componentWillUnmount() {
        window.removeEventListener('resize', this.onResize);
    }
    componentDidUpdate() {
        this.draw();
    }
    render() {
        const { name, canvasClasses, before, after } = this.props;

        const className = classNames('graph-container', `graph-${name}`);

        const canvasRef = canvas => this.setState({
            canvas,
            ctx: canvas && canvas.getContext && canvas.getContext('2d')
        });

        return

            {before || null}
            <canvas
                ref={canvasRef}
                className={canvasClasses || ''}
                width={this.state.width}
                height={this.state.height}
                {...this.state.canvasProperties}
            />
            {after || null}

;
    }
}

Graph.propTypes = {
    name: PropTypes.string,
    width: PropTypes.number.isRequired,
    height: PropTypes.number.isRequired,
    padding: PropTypes.array,
    canvasClasses: PropTypes.string,
    before: PropTypes.object,
    after: PropTypes.object,
    onDraw: PropTypes.func.isRequired
};

<commit_msg>Resize graphs when resizing the window, if necessary<commit_after>/*
 * React component to display a graph
 */

import React from 'react';
import PureComponent from '../../immutable-component';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import debounce from '../../misc/debounce';

export default class Graph extends PureComponent {
    constructor(props) {
        super(props);

        const { width, height, padding } = props;

        this.state = {
            ctx: null,
            canvas: null,
            width,
            height,
            padding: padding || [0, 0, 0, 0],
            canvasProperties: {},
            outerProperties: {}
        };

        this.onResize = debounce(() => {
            if (window.innerWidth < this.state.width) {
                this.setState({
                    width: window.innerWidth
                });
            }
            else if (this.state.width < this.props.width) {
                this.setState({
                    width: this.props.width
                });
            }
        }, 100);
    }
    draw() {
        if (!this.state.ctx) {
            return;
        }

        this.state.ctx.clearRect(0, 0, this.state.width, this.state.height);

        this.props.onDraw(this.props, this.state, this);
    }
    componentDidMount() {
        window.addEventListener('resize', this.onResize);
    }
    componentWillUnmount() {
        window.removeEventListener('resize', this.onResize);
    }
    componentDidUpdate() {
        this.draw();
    }
    render() {
        const { name, canvasClasses, before, after } = this.props;

        const className = classNames('graph-container', `graph-${name}`);

        const canvasRef = canvas => this.setState({
            canvas,
            ctx: canvas && canvas.getContext && canvas.getContext('2d')
        });

        return

            {before || null}
            <canvas
                ref={canvasRef}
                className={canvasClasses || ''}
                width={this.state.width}
                height={this.state.height}
                {...this.state.canvasProperties}
            />
            {after || null}

;
    }
}

Graph.propTypes = {
    name: PropTypes.string,
    width: PropTypes.number.isRequired,
    height: PropTypes.number.isRequired,
    padding: PropTypes.array,
    canvasClasses: PropTypes.string,
    before: PropTypes.object,
    after: PropTypes.object,
    onDraw: PropTypes.func.isRequired
};

<|endoftext|>


<commit_before>(function () {
var sharedDataMap = {},
    visibilityMap = { 'histogram': false, 'information': false };

    var getSharedData = function (model, container) {
        if (sharedDataMap.hasOwnProperty(model.getHash())) {
            return sharedDataMap[model.getHash()];
        } else {
            var layer = new cinema.models.LayerModel(model.getDefaultPipelineSetup(), { info: model }),
                control = new cinema.models.ControlModel({ info: model }),
                histogram = new cinema.models.CompositeHistogramModel({
                    layerModel: layer,
                    basePath: model.get('basePath'),
                    analysisInfo: model.attributes.metadata.analysis }),
                viewpoint = new cinema.models.ViewPointModel({ controlModel: control }),
                informationWidget = new cinema.views.SearchInformationWidget({
                        el: $('.c-information-panel', container),
                        model: model,
                        controlModel: control,
                        exclude: ['layer', 'filename'],
                        layers: layer,
                        toolbarSelector: '.c-panel-toolbar'
                    }),
                histogramWidget = new cinema.views.CompositeHistogramWidget({
                        el: $('.c-histogram-panel', container),
                        basePath: model.get('basePath'),
                        histogramModel: histogram,
                        viewpoint: viewpoint,
                        layerModel: layer,
                        toolbarSelector: '.c-panel-toolbar'
                    }),
                compositeToolsWidget = new cinema.views.CompositeToolsWidget({
                    el: $('.c-tools-panel', container),
                    model: model,
                    controlModel: control,
                    viewpoint: viewpoint,
                    layers: layer,
                    toolbarSelector: '.c-panel-toolbar'
                }),
                searchToolsWidget = new cinema.views.SearchToolsWidget({
                    el: $('.c-tools-panel', container),
                    model: model,
                    layers: layer,
                    toolbarSelector: '.c-panel-toolbar'
                }),
                shared = {
                    control: control,
                    histogram: histogram,
                    layer: layer,
                    viewpoint: viewpoint,
                    informationWidget: informationWidget,
                    histogramWidget: histogramWidget,
                    compositeToolsWidget: compositeToolsWidget,
                    searchToolsWidget: searchToolsWidget
                };
            sharedDataMap[model.getHash()] = shared;
            return shared;
        }
    };

    var visibility = function (name, value) {
        if (value === undefined) {
            return visibilityMap[name];
        } else {
            visibilityMap[name] = value;
        }
    };

    cinema.events.on('toggle-control-panel', function(event) {
        visibility(event.key, event.visible);
    });

    cinema.views.CompositeView = Backbone.View.extend({
        initialize: function (opts) {
            this.compositeModel = new cinema.decorators.Composite(this.model);
            this.compositeManager = new cinema.utilities.CompositeImageManager({ visModel: this.model });
            var sharedData = getSharedData(this.compositeModel, this.$el);

            this.controlModel = sharedData.control;
            this.viewpointModel = sharedData.viewpoint;
            this.layers = sharedData.layer;
            this._hasAnalysis = _.has(this.model.get('metadata'), 'analysis');

            this.compositeTools = sharedData.compositeToolsWidget;

            if (this._hasAnalysis) {
                this.histogramModel = sharedData.histogram;
                this.controlList = opts.defaultControls.slice(0); // copy
                this.compositeHistogram = sharedData.histogramWidget;
                this.searchInformation = sharedData.informationWidget;
                this.controlList.push(
                    { position: 'left', key: 'information', icon: 'icon-help', title: 'Information' },
                    { position: 'center', key: 'histogram', icon: 'icon-chart-bar', title: 'Histogram' }
                );
            }

            this.controlModel.on('change', this.refreshCamera, this);
            this.viewpointModel.on('change', this.refreshCamera, this);
            this.listenTo(cinema.events, 'c:resetCamera', this.resetCamera);
        },

        render: function () {
            if (this.renderView) {
                this.renderView.remove();
            }

            this.renderView = new cinema.views.VisualizationCanvasWidget({
                el: this.$('.c-body-container'),
                model: this.compositeModel,
                layers: this.layers,
                controls: this.controlModel,
                viewpoint: this.viewpointModel,
                compositeManager: this.compositeManager
            });

            new cinema.utilities.RenderViewMouseInteractor({
                renderView: this.renderView,
                camera: this.viewpointModel
            }).enableMouseWheelZoom({
                maxZoomLevel: 10,
                zoomIncrement: 0.05,
                invertControl: false
            }).enableDragPan({
                keyModifiers: cinema.keyModifiers.SHIFT
            }).enableDragRotation({
                keyModifiers: null
            });

            this.renderView.render().showViewpoint();
            //this.compositeTools.render();
            this.compositeTools.setElement(this.$('.c-tools-panel')).render();

            if (this._hasAnalysis) {
                //this.compositeHistogram.render();
                this.compositeHistogram.setElement(this.$('.c-histogram-panel')).render();
                // this.searchInformation.render();
                this.searchInformation.setElement(this.$('.c-information-panel')).render();
                this.$('.c-histogram-panel').toggle(visibility('histogram'));
                this.$('.c-information-panel').toggle(visibility('information'));
            }

            return this;
        },

        refreshCamera: function () {
            if (this.renderView) {
                this.renderView.showViewpoint();
            }
        },

        resetCamera: function () {
            if (this.renderView) {
                this.renderView.showViewpoint();
                this.renderView.resetCamera();
            }
        }
    });

    cinema.views.CompositeSearchView = Backbone.View.extend({
        initialize: function (opts) {
            this.compositeModel = new cinema.decorators.Composite(this.model);
            var sharedData = getSharedData(this.compositeModel, this.$el);
            this.controlModel = sharedData.control;
            this.viewpointModel = sharedData.viewpoint;
            this.layers = sharedData.layer;
            this._hasAnalysis = _.has(this.model.get('metadata'), 'analysis');

            this.searchTools = sharedData.searchToolsWidget;

            if (this._hasAnalysis) {
                this.histogramModel = sharedData.histogram;

                this.compositeHistogram = sharedData.histogramWidget;
                this.searchInformation = sharedData.informationWidget;

                this.controlList = opts.defaultControls.slice(0); // copy
                this.controlList.push(
                    { position: 'left', key: 'information', icon: 'icon-help', title: 'Information' },
                    { position: 'center', key: 'histogram', icon: 'icon-chart-bar', title: 'Histogram' }
                );
            }

            this.controlModel.on('change', this.refreshCamera, this);
            this.viewpointModel.on('change', this.refreshCamera, this);
            this.listenTo(cinema.events, 'c:resetCamera', this.resetCamera);
        },

        render: function () {
            if (this._hasAnalysis) {
                if (this.searchView) {
                    this.searchView.remove();
                }

                this.searchView = new cinema.views.CompositeSearchPage({
                    el: this.$('.c-body-container'),
                    basePath: this.model.get('basePath'),
                    histogramModel: this.histogramModel,
                    visModel: this.compositeModel,
                    layerModel: this.layers
                });

                this.searchView.render();

                //this.searchInformation.render();
                this.searchInformation.setElement(this.$('.c-information-panel')).render();
                this.compositeHistogram.setElement(this.$('.c-histogram-panel')).render();

                this.$('.c-histogram-panel').toggle(visibility('histogram'));
                this.$('.c-information-panel').toggle(visibility('information'));
            }

            //this.searchTools.render();
            this.searchTools.setElement(this.$('.c-tools-panel')).render();

            return this;
        }
    });
}());

cinema.viewMapper.registerView('composite-image-stack', 'view', cinema.views.CompositeView, {
    controls: [
        { position: 'right', key: 'tools', icon: 'icon-tools', title: 'Tools' }
    ]
});

cinema.viewMapper.registerView('composite-image-stack', 'search', cinema.views.CompositeSearchView, {
    controls: [
        { position: 'right', key: 'tools', icon: 'icon-tools', title: 'Tools' },
    ]
});
<commit_msg>closer to what I'm thinking of for refactoring<commit_after>(function () {
var sharedDataMap = {},
    visibilityMap = { 'histogram': false, 'information': false };

    var getSharedData = function (model, container) {
        if (sharedDataMap.hasOwnProperty(model.getHash())) {
            return sharedDataMap[model.getHash()];
        } else {
            var layer = new cinema.models.LayerModel(model.getDefaultPipelineSetup(), { info: model }),
                control = new cinema.models.ControlModel({
                    info: model
                }),
                histogram = new cinema.models.CompositeHistogramModel({
                    layerModel: layer,
                    basePath: model.get('basePath'),
                    analysisInfo: model.attributes.metadata.analysis
                }),
                viewpoint = new cinema.models.ViewPointModel({
                    controlModel: control
                }),
                informationWidget = new cinema.views.SearchInformationWidget({
                    el: $('.c-information-panel', container),
                    model: model,
                    controlModel: control,
                    exclude: ['layer', 'filename'],
                    layers: layer,
                    toolbarSelector: '.c-panel-toolbar'
                }),
                histogramWidget = new cinema.views.CompositeHistogramWidget({
                    el: $('.c-histogram-panel', container),
                    basePath: model.get('basePath'),
                    histogramModel: histogram,
                    viewpoint: viewpoint,
                    layerModel: layer,
                    toolbarSelector: '.c-panel-toolbar'
                }),
                compositeToolsWidget = new cinema.views.CompositeToolsWidget({
                    el: $('.c-tools-panel', container),
                    model: model,
                    controlModel: control,
                    viewpoint: viewpoint,
                    layers: layer,
                    toolbarSelector: '.c-panel-toolbar'
                }),
                searchToolsWidget = new cinema.views.SearchToolsWidget({
                    el: $('.c-tools-panel', container),
                    model: model,
                    layers: layer,
                    toolbarSelector: '.c-panel-toolbar'
                }),
                imageManager = new cinema.utilities.CompositeImageManager({
                    visModel: model
                }),
                renderView = new cinema.views.VisualizationCanvasWidget({
                    el: this.$('.c-body-container', container),
                    model: model,
                    layers: layer,
                    controls: control,
                    viewpoint: viewpoint,
                    compositeManager: imageManager
                }),
                searchView = new cinema.views.CompositeSearchPage({
                    el: $('.c-body-container', container),
                    basePath: model.get('basePath'),
                    histogramModel: histogram,
                    visModel: model,
                    layerModel: layer
                }),
                shared = {
                    control: control,
                    histogram: histogram,
                    layer: layer,
                    viewpoint: viewpoint,
                    informationWidget: informationWidget,
                    histogramWidget: histogramWidget,
                    compositeToolsWidget: compositeToolsWidget,
                    searchToolsWidget: searchToolsWidget,
                    imageManager: imageManager,
                    renderView: renderView,
                    searchView: searchView
                };
            sharedDataMap[model.getHash()] = shared;
            return shared;
        }
    };

    var visibility = function (name, value) {
        if (value === undefined) {
            return visibilityMap[name];
        } else {
            visibilityMap[name] = value;
        }
    };

    cinema.events.on('toggle-control-panel', function(event) {
        visibility(event.key, event.visible);
    });

    cinema.views.CompositeView = Backbone.View.extend({
        initialize: function (opts) {
            this.compositeModel = new cinema.decorators.Composite(this.model);
            var sharedData = getSharedData(this.compositeModel, this.$el);

            this.compositeManager = sharedData.imageManager;
            this.controlModel = sharedData.control;
            this.viewpointModel = sharedData.viewpoint;
            this.layers = sharedData.layer;
            this.renderView = sharedData.renderView;

            new cinema.utilities.RenderViewMouseInteractor({
                    renderView: this.renderView,
                    camera: this.viewpointModel
                }).enableMouseWheelZoom({
                    maxZoomLevel: 10,
                    zoomIncrement: 0.05,
                    invertControl: false
                }).enableDragPan({
                    keyModifiers: cinema.keyModifiers.SHIFT
                }).enableDragRotation({
                    keyModifiers: null
                });

            this.compositeTools = sharedData.compositeToolsWidget;

            this._hasAnalysis = _.has(this.model.get('metadata'), 'analysis');
            if (this._hasAnalysis) {
                this.histogramModel = sharedData.histogram;
                this.controlList = opts.defaultControls.slice(0);
                this.compositeHistogram = sharedData.histogramWidget;
                this.searchInformation = sharedData.informationWidget;
                this.controlList.push(
                    { position: 'left', key: 'information', icon: 'icon-help', title: 'Information' },
                    { position: 'center', key: 'histogram', icon: 'icon-chart-bar', title: 'Histogram' }
                );
            }

            this.controlModel.on('change', this.refreshCamera, this);
            this.viewpointModel.on('change', this.refreshCamera, this);
            this.listenTo(cinema.events, 'c:resetCamera', this.resetCamera);
        },

        render: function () {
            this.renderView.setElement(this.$('.c-body-container')).render().showViewpoint();
            this.compositeTools.setElement(this.$('.c-tools-panel')).render();
            if (this._hasAnalysis) {
                this.compositeHistogram.setElement(this.$('.c-histogram-panel')).render();
                this.searchInformation.setElement(this.$('.c-information-panel')).render();
                this.$('.c-histogram-panel').toggle(visibility('histogram'));
                this.$('.c-information-panel').toggle(visibility('information'));
            }

            return this;
        },

        refreshCamera: function () {
            if (this.renderView) {
                this.renderView.showViewpoint();
            }
        },

        resetCamera: function () {
            if (this.renderView) {
                this.renderView.showViewpoint();
                this.renderView.resetCamera();
            }
        }
    });

    cinema.views.CompositeSearchView = Backbone.View.extend({
        initialize: function (opts) {
            this.compositeModel = new cinema.decorators.Composite(this.model);
            var sharedData = getSharedData(this.compositeModel, this.$el);

            this.controlModel = sharedData.control;
            this.viewpointModel = sharedData.viewpoint;
            this.layers = sharedData.layer;
            this.searchView = sharedData.searchView;
            this.searchTools = sharedData.searchToolsWidget;

            this._hasAnalysis = _.has(this.model.get('metadata'), 'analysis');
            if (this._hasAnalysis) {
                this.histogramModel = sharedData.histogram;
                this.compositeHistogram = sharedData.histogramWidget;
                this.searchInformation = sharedData.informationWidget;
                this.controlList = opts.defaultControls.slice(0);
                this.controlList.push(
                    { position: 'left', key: 'information', icon: 'icon-help', title: 'Information' },
                    { position: 'center', key: 'histogram', icon: 'icon-chart-bar', title: 'Histogram' }
                );
            }

            this.controlModel.on('change', this.refreshCamera, this);
            this.viewpointModel.on('change', this.refreshCamera, this);
            this.listenTo(cinema.events, 'c:resetCamera', this.resetCamera);
        },

        render: function () {
            this.searchView.setElement(this.$('.c-body-container')).render();
            this.searchTools.setElement(this.$('.c-tools-panel')).render();
            if (this._hasAnalysis) {
                this.searchInformation.setElement(this.$('.c-information-panel')).render();
                this.compositeHistogram.setElement(this.$('.c-histogram-panel')).render();
                this.$('.c-histogram-panel').toggle(visibility('histogram'));
                this.$('.c-information-panel').toggle(visibility('information'));
            }

            return this;
        }
    });
}());

cinema.viewMapper.registerView('composite-image-stack', 'view', cinema.views.CompositeView, {
    controls: [
        { position: 'right', key: 'tools', icon: 'icon-tools', title: 'Tools' }
    ]
});

cinema.viewMapper.registerView('composite-image-stack', 'search', cinema.views.CompositeSearchView, {
    controls: [
        { position: 'right', key: 'tools', icon: 'icon-tools', title: 'Tools' },
    ]
});
<|endoftext|>


<commit_before>var _ = require('lodash');
var fs = require('fs');
var path = require('path');

var processCWD = process.cwd();
var defaultOptions = {
  // 当前工作目录
  cwd: process.cwd(),

  // 排除的文件或目录(glob格式)
  exclude: [],

  // 输出的主目录
  output: 'build',

  // hash版本号的长度，如果不想加就设置为0
  hash: 10,

  // hash版本号连接符
  hashConcat: '.',

  // 静态文件的域名
  domain: '',

  // 插件
  plugins: [],

  module: {
    // 前置任务
    preTasks: [],

    // 任务
    tasks: [],

    // 后置任务
    postTasks: [],

    taskMap: {},

    // 文件生成配置
    road: []
  },

  resolve: {
    alias: {},
    modulesDirectories: ['node_modules', 'bower_components'],
    fallback: [],
    packageMains: [],
    extensions: ['', '.js'],
    extensionAlias: {
      '.css': ['.less']
    }
  }
};

// 获取配置文件路径
function getConfigPath(argv) {
  // 配置文件列表
  var configPathList = [];

  if (argv.configPath) {
    configPathList.push(path.resolve(processCWD, argv.configPath));
  }

  if (argv.cwd) {
    configPathList.push(path.resolve(argv.cwd, 'miaow.config.js'));
  }

  configPathList.push(path.resolve(processCWD, 'miaow.config.js'));

  return _.find(configPathList, fs.existsSync);
}

function useTaskMap(tasks, taskMap) {
  return tasks.map(function(task) {
    return _.isString(task) ? taskMap[task] : task;
  });
}

module.exports = function(argv) {
  var options = {};

  var configPath = getConfigPath(argv);
  if (configPath) {
    options = require(configPath);

    if (_.isArray(options)) {
      if (argv.environment) {
        options = _.find(options, {environment: argv.environment});
        if (!options) {
          throw new Error('查不到运行环境为 ' + argv.environment + ' 的配置信息。');
        }
      } else {
        options = options[0];
      }
    }
  }

  // 设置工作目录和输出目录
  if (argv._.length) {
    options.cwd = path.resolve(processCWD, argv._[0]);

    if (argv._[1]) {
      options.output = path.resolve(processCWD, argv._[1]);
    }
  }

  if (argv.watch) {
    options.watch = true;
  }

  options = _.assign({}, defaultOptions, options);

  var module = options.module;
  module.preTasks = useTaskMap(module.preTasks, module.taskMap);
  module.tasks = useTaskMap(module.tasks, module.taskMap);
  module.postTasks = useTaskMap(module.postTasks, module.taskMap);

  return options;
};
<commit_msg>取消preTasks和postTasks<commit_after>var _ = require('lodash');
var fs = require('fs');
var path = require('path');

var processCWD = process.cwd();
var defaultOptions = {
  // 当前工作目录
  cwd: process.cwd(),

  // 排除的文件或目录(glob格式)
  exclude: [],

  // 输出的主目录
  output: 'build',

  // hash版本号的长度，如果不想加就设置为0
  hash: 10,

  // hash版本号连接符
  hashConcat: '.',

  // 静态文件的域名
  domain: '',

  // 插件
  plugins: [],

  module: {
    // 任务
    tasks: [],

    taskMap: {},

    // 文件生成配置
    road: []
  },

  resolve: {
    alias: {},
    modulesDirectories: ['node_modules', 'bower_components'],
    fallback: [],
    packageMains: [],
    extensions: ['', '.js'],
    extensionAlias: {
      '.css': ['.less']
    }
  }
};

// 获取配置文件路径
function getConfigPath(argv) {
  // 配置文件列表
  var configPathList = [];

  if (argv.configPath) {
    configPathList.push(path.resolve(processCWD, argv.configPath));
  }

  if (argv.cwd) {
    configPathList.push(path.resolve(argv.cwd, 'miaow.config.js'));
  }

  configPathList.push(path.resolve(processCWD, 'miaow.config.js'));

  return _.find(configPathList, fs.existsSync);
}

function useTaskMap(tasks, taskMap) {
  return tasks.map(function(task) {
    return _.isString(task) ? taskMap[task] : task;
  });
}

module.exports = function(argv) {
  var options = {};

  var configPath = getConfigPath(argv);
  if (configPath) {
    options = require(configPath);

    if (_.isArray(options)) {
      if (argv.environment) {
        options = _.find(options, {environment: argv.environment});
        if (!options) {
          throw new Error('查不到运行环境为 ' + argv.environment + ' 的配置信息。');
        }
      } else {
        options = options[0];
      }
    }
  }

  // 设置工作目录和输出目录
  if (argv._.length) {
    options.cwd = path.resolve(processCWD, argv._[0]);

    if (argv._[1]) {
      options.output = path.resolve(processCWD, argv._[1]);
    }
  }

  if (argv.watch) {
    options.watch = true;
  }

  options = _.assign({}, defaultOptions, options);

  var module = options.module;
  module.tasks = useTaskMap(module.tasks, module.taskMap);

  return options;
};
<|endoftext|>


<commit_before>import { createBuffer } from './buffer';

/**
 * Buffer Audio.
 * Be able to get parts of audio buffered.
 */

class BufferPlugin {
  /**
   * Constructor method.
   *
   * @param {object} options - Options to pass to the plugin.
   * @param {boolean} options.immediateStart - Immediately start with buffering.
   * @param {boolean} options.stopAfterRecording - Stop buffering when the
   * recorder stops recording.
   * @param {number} options.secondsToBuffer - Number of seconds to buffer.
   */
  constructor({
    immediateStart = false,
    stopAfterRecording = true,
    secondsToBuffer = 30,
  }) {
    this.immediateStart = immediateStart;
    this.stopAfterRecording = stopAfterRecording;
    this.secondsToBuffer = secondsToBuffer;

    this.bufferNode = null;
    this.recorder = null;

    this.startBuffering = this.startBuffering.bind(this);
    this.recordingStopped = this.recordingStopped.bind(this);
  }

  /**
   * Read the buffer and return it as WAVE file.
   *
   * @param secondsToRead
   * @returns {Blob} - The requested buffer in a blob with WAVE as mimeType.
   */
  readBufferAsWAV(secondsToRead) {
    const data = this.bufferNode.readBufferAsWAV(secondsToRead);
    const event = new Event('bufferdataavailable');

    if (data) {
      event.data = data;

      // Dispatch the data!
      this.recorder.dispatchEvent(event);
    }
  }

  /**
   * Start buffering audio!
   */
  startBuffering() {
    this.bufferNode = createBuffer(this.recorder.stream, this.secondsToBuffer);
    this.recorder.requestBufferedData = secondsToRead => {
      this.readBufferAsWAV(secondsToRead);
    };
  }

  /**
   * Stop buffering audio!
   */
  stopBuffering() {
    this.bufferNode = null;
    delete this.recorder.requestBufferedData;
  }

  /**
   * Handler for the recorder, this gets executed as soon as the recorder stops
   * recording. Based on the options it will stop buffering.
   */
  recordingStopped() {
    if (this.stopAfterRecording) {
      this.stopBuffering();
    }
  }

  /**
   * Start the plugin.
   */
  startPlugin() {
    if (this.immediateStart) {
      this.startBuffering();
    }

    this.recorder.addEventListener('start', this.startBuffering);
    this.recorder.addEventListener('stop', this.recordingStopped);
  }

  /**
   * This function gets called from itslanguage recorder side. It will pass
   * the recorder to it so we can use it.
   *
   * @param {MediaRecorder} recorder - Recorder for which this plugin needs to be
   * active on.
   */
  applyPlugin(recorder) {
    this.recorder = recorder;
    this.startPlugin();
  }
}

export default BufferPlugin;
<commit_msg>fix: dont use default value for parent constructor<commit_after>import { createBuffer } from './buffer';

/**
 * Buffer Audio.
 * Be able to get parts of audio buffered.
 */

class BufferPlugin {
  /**
   * Constructor method.
   *
   * @param {object} options - Options to pass to the plugin.
   * @param {boolean} options.immediateStart - Immediately start with buffering.
   * @param {boolean} options.stopAfterRecording - Stop buffering when the
   * recorder stops recording.
   * @param {number} options.secondsToBuffer - Number of seconds to buffer.
   */
  constructor({
    immediateStart = false,
    stopAfterRecording = true,
    secondsToBuffer,
  }) {
    this.immediateStart = immediateStart;
    this.stopAfterRecording = stopAfterRecording;
    this.secondsToBuffer = secondsToBuffer;

    this.bufferNode = null;
    this.recorder = null;

    this.startBuffering = this.startBuffering.bind(this);
    this.recordingStopped = this.recordingStopped.bind(this);
  }

  /**
   * Read the buffer and return it as WAVE file.
   *
   * @param secondsToRead
   * @returns {Blob} - The requested buffer in a blob with WAVE as mimeType.
   */
  readBufferAsWAV(secondsToRead) {
    const data = this.bufferNode.readBufferAsWAV(secondsToRead);
    const event = new Event('bufferdataavailable');

    if (data) {
      event.data = data;

      // Dispatch the data!
      this.recorder.dispatchEvent(event);
    }
  }

  /**
   * Start buffering audio!
   */
  startBuffering() {
    this.bufferNode = createBuffer(this.recorder.stream, this.secondsToBuffer);
    this.recorder.requestBufferedData = secondsToRead => {
      this.readBufferAsWAV(secondsToRead);
    };
  }

  /**
   * Stop buffering audio!
   */
  stopBuffering() {
    this.bufferNode = null;
    delete this.recorder.requestBufferedData;
  }

  /**
   * Handler for the recorder, this gets executed as soon as the recorder stops
   * recording. Based on the options it will stop buffering.
   */
  recordingStopped() {
    if (this.stopAfterRecording) {
      this.stopBuffering();
    }
  }

  /**
   * Start the plugin.
   */
  startPlugin() {
    if (this.immediateStart) {
      this.startBuffering();
    }

    this.recorder.addEventListener('start', this.startBuffering);
    this.recorder.addEventListener('stop', this.recordingStopped);
  }

  /**
   * This function gets called from itslanguage recorder side. It will pass
   * the recorder to it so we can use it.
   *
   * @param {MediaRecorder} recorder - Recorder for which this plugin needs to be
   * active on.
   */
  applyPlugin(recorder) {
    this.recorder = recorder;
    this.startPlugin();
  }
}

export default BufferPlugin;
<|endoftext|>


<commit_before>import React from "react";
import ReactDOM from "react-dom";
import _ from "lodash";

import {Splitter} from "./common.js"
import MainView from "./mainview.js";
import Footer from "./footer.js";
import {Header, MainMenu} from "./header.js";
import EventLog from "./eventlog.js"
import {EventLogStore, FlowStore, SettingsStore} from "../store/store.js";
import {Query} from "../actions.js";
import {Key} from "../utils.js";

//TODO: Move out of here, just a stub.
var Reports = React.createClass({
    render: function () {
        return
ReportEditor
;
    }
});

var ProxyAppMain = React.createClass({
    childContextTypes: {
        flowStore: React.PropTypes.object.isRequired,
        eventStore: React.PropTypes.object.isRequired,
        returnFocus: React.PropTypes.func.isRequired,
        location: React.PropTypes.object.isRequired,
    },
    contextTypes: {
        location: React.PropTypes.object,
        router: React.PropTypes.object.isRequired
    },
    updateLocation: function (pathname, queryUpdate) {
        if (pathname === undefined) {
            pathname = this.context.location.pathname;
        }
        var query = this.context.location.query;
        if (queryUpdate !== undefined) {
            for (var i in queryUpdate) {
                if (queryUpdate.hasOwnProperty(i)) {
                    query[i] = queryUpdate[i] || undefined; //falsey values shall be removed.
                }
            }
        }
        this.context.router.replace({pathname, query});
    },
    getQuery: function () {
        // For whatever reason, react-router always returns the same object, which makes comparing
        // the current props with nextProps impossible. As a workaround, we just clone the query object.
        return _.clone(this.context.location.query);
    },
    componentDidMount: function () {
        this.focus();
        this.settingsStore.addListener("recalculate", this.onSettingsChange);
    },
    componentWillUnmount: function () {
        this.settingsStore.removeListener("recalculate", this.onSettingsChange);
    },
    onSettingsChange: function () {
        this.setState({ settings: this.settingsStore.dict });
    },
    getChildContext: function () {
        return {
            flowStore: this.state.flowStore,
            eventStore: this.state.eventStore,
            returnFocus: this.focus,
            location: this.props.location
        };
    },
    getInitialState: function () {
        var eventStore = new EventLogStore();
        var flowStore = new FlowStore();
        var settingsStore = new SettingsStore();

        this.settingsStore = settingsStore;
        // Default Settings before fetch
        _.extend(settingsStore.dict, {});
        return {
            settings: settingsStore.dict,
            flowStore: flowStore,
            eventStore: eventStore
        };
    },
    focus: function () {
        document.activeElement.blur();
        window.getSelection().removeAllRanges();
        ReactDOM.findDOMNode(this).focus();
    },
    getMainComponent: function () {
        return this.refs.view;
    },
    onKeydown: function (e) {

        var selectFilterInput = function (name) {
            var headerComponent = this.refs.header;
            headerComponent.setState({active: MainMenu}, function () {
                headerComponent.refs.active.refs[name].select();
            });
        }.bind(this);

        switch (e.keyCode) {
            case Key.I:
                selectFilterInput("intercept");
                break;
            case Key.L:
                selectFilterInput("search");
                break;
            case Key.H:
                selectFilterInput("highlight");
                break;
            default:
                var main = this.getMainComponent();
                if (main.onMainKeyDown) {
                    main.onMainKeyDown(e);
                }
                return; // don't prevent default then
        }
        e.preventDefault();
    },
    render: function () {
        var query = this.getQuery();
        var eventlog;
        if (this.props.location.query[Query.SHOW_EVENTLOG]) {
            eventlog = [
                <Splitter key="splitter" axis="y"/>,
                <EventLog key="eventlog" updateLocation={this.updateLocation}/>
            ];
        } else {
            eventlog = null;
        }
        return (

                {React.cloneElement(
                    this.props.children,
                    { ref: "view", location: this.props.location , updateLocation: this.updateLocation, query }
                )}
                {eventlog}

        );
    }
});

import { Route, Router as ReactRouter, hashHistory, Redirect} from "react-router";

export var app = (
    <ReactRouter history={hashHistory}>
        <Redirect from="/" to="/flows" />
        <Route path="/" component={ProxyAppMain}>
            <Route path="flows" component={MainView}/>
            <Route path="flows/:flowId/:detailTab" component={MainView}/>
            <Route path="reports" component={Reports}/>
        </Route>
    </ReactRouter>
);
<commit_msg>[web] use props.location instead of context.location<commit_after>import React from "react";
import ReactDOM from "react-dom";
import _ from "lodash";

import {Splitter} from "./common.js"
import MainView from "./mainview.js";
import Footer from "./footer.js";
import {Header, MainMenu} from "./header.js";
import EventLog from "./eventlog.js"
import {EventLogStore, FlowStore, SettingsStore} from "../store/store.js";
import {Query} from "../actions.js";
import {Key} from "../utils.js";

//TODO: Move out of here, just a stub.
var Reports = React.createClass({
    render: function () {
        return
ReportEditor
;
    }
});

var ProxyAppMain = React.createClass({
    childContextTypes: {
        flowStore: React.PropTypes.object.isRequired,
        eventStore: React.PropTypes.object.isRequired,
        returnFocus: React.PropTypes.func.isRequired,
        location: React.PropTypes.object.isRequired,
    },
    contextTypes: {
        router: React.PropTypes.object.isRequired
    },
    updateLocation: function (pathname, queryUpdate) {
        if (pathname === undefined) {
            pathname = this.props.location.pathname;
        }
        var query = this.props.location.query;
        if (queryUpdate !== undefined) {
            for (var i in queryUpdate) {
                if (queryUpdate.hasOwnProperty(i)) {
                    query[i] = queryUpdate[i] || undefined; //falsey values shall be removed.
                }
            }
        }
        this.context.router.replace({pathname, query});
    },
    getQuery: function () {
        // For whatever reason, react-router always returns the same object, which makes comparing
        // the current props with nextProps impossible. As a workaround, we just clone the query object.
        return _.clone(this.props.location.query);
    },
    componentDidMount: function () {
        this.focus();
        this.settingsStore.addListener("recalculate", this.onSettingsChange);
    },
    componentWillUnmount: function () {
        this.settingsStore.removeListener("recalculate", this.onSettingsChange);
    },
    onSettingsChange: function () {
        this.setState({ settings: this.settingsStore.dict });
    },
    getChildContext: function () {
        return {
            flowStore: this.state.flowStore,
            eventStore: this.state.eventStore,
            returnFocus: this.focus,
            location: this.props.location
        };
    },
    getInitialState: function () {
        var eventStore = new EventLogStore();
        var flowStore = new FlowStore();
        var settingsStore = new SettingsStore();

        this.settingsStore = settingsStore;
        // Default Settings before fetch
        _.extend(settingsStore.dict, {});
        return {
            settings: settingsStore.dict,
            flowStore: flowStore,
            eventStore: eventStore
        };
    },
    focus: function () {
        document.activeElement.blur();
        window.getSelection().removeAllRanges();
        ReactDOM.findDOMNode(this).focus();
    },
    getMainComponent: function () {
        return this.refs.view;
    },
    onKeydown: function (e) {

        var selectFilterInput = function (name) {
            var headerComponent = this.refs.header;
            headerComponent.setState({active: MainMenu}, function () {
                headerComponent.refs.active.refs[name].select();
            });
        }.bind(this);

        switch (e.keyCode) {
            case Key.I:
                selectFilterInput("intercept");
                break;
            case Key.L:
                selectFilterInput("search");
                break;
            case Key.H:
                selectFilterInput("highlight");
                break;
            default:
                var main = this.getMainComponent();
                if (main.onMainKeyDown) {
                    main.onMainKeyDown(e);
                }
                return; // don't prevent default then
        }
        e.preventDefault();
    },
    render: function () {
        var query = this.getQuery();
        var eventlog;
        if (this.props.location.query[Query.SHOW_EVENTLOG]) {
            eventlog = [
                <Splitter key="splitter" axis="y"/>,
                <EventLog key="eventlog" updateLocation={this.updateLocation}/>
            ];
        } else {
            eventlog = null;
        }
        return (

                {React.cloneElement(
                    this.props.children,
                    { ref: "view", location: this.props.location , updateLocation: this.updateLocation, query }
                )}
                {eventlog}

        );
    }
});

import { Route, Router as ReactRouter, hashHistory, Redirect} from "react-router";

export var app = (
    <ReactRouter history={hashHistory}>
        <Redirect from="/" to="/flows" />
        <Route path="/" component={ProxyAppMain}>
            <Route path="flows" component={MainView}/>
            <Route path="flows/:flowId/:detailTab" component={MainView}/>
            <Route path="reports" component={Reports}/>
        </Route>
    </ReactRouter>
);
<|endoftext|>


<commit_before>// Turn on a global notification. Set this to `true` to show
// the message in NotificationComponent to all users.
export const showGlobalNotification = () => true

export const isAnonymousUserSignInEnabled = () => false

export const isVariousAdSizesEnabled = () => false

export const isSearchPageEnabled = () =>
  process.env.REACT_APP_FEATURE_FLAG_SEARCH_PAGE_ENABLED === 'true'

export const shouldRedirectSearchToThirdParty = () =>
  process.env.REACT_APP_FEATURE_FLAG_REDIRECT_SEARCH_TO_THIRD_PARTY === 'true'
<commit_msg>End the April Charity Spotlight vote<commit_after>// Turn on a global notification. Set this to `true` to show
// the message in NotificationComponent to all users.
export const showGlobalNotification = () => false

export const isAnonymousUserSignInEnabled = () => false

export const isVariousAdSizesEnabled = () => false

export const isSearchPageEnabled = () =>
  process.env.REACT_APP_FEATURE_FLAG_SEARCH_PAGE_ENABLED === 'true'

export const shouldRedirectSearchToThirdParty = () =>
  process.env.REACT_APP_FEATURE_FLAG_REDIRECT_SEARCH_TO_THIRD_PARTY === 'true'
<|endoftext|>


<commit_before>import { createApp } from 'vue'
import Child from './Child.vue'

createApp({
  ...Child,
  name: 'IframeApp'
}).mount('#app')
<commit_msg>chore(dev): script setup in iframe<commit_after>import { createApp, h } from 'vue'
import Child from './Child.vue'
import SetupScript from './SetupScript.vue'

createApp({
  name: 'IframeApp',
  render: () => [
    h(Child),
    h(SetupScript)
  ]
}).mount('#app')
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Javascript that is being injected into the inspectable page
 * while debugging.
 */
goog.provide('devtools.Injected');

/**
 * Main injected object.
 * @constructor.
 */
devtools.Injected = function() {
};

/**
 * Dispatches given method with given args on the host object.
 * @param {string} method Method name.
 */
devtools.Injected.prototype.InspectorController = function(method, var_args) {
  var args = Array.prototype.slice.call(arguments, 1);
  return InspectorController[method].apply(InspectorController, args);
};

/**
 * Dispatches given method with given args on the InjectedScript.
 * @param {string} method Method name.
 */
devtools.Injected.prototype.InjectedScript = function(method, var_args) {
  var args = Array.prototype.slice.call(arguments, 1);
  var result = InjectedScript[method].apply(InjectedScript, args);
  return result;
};

// Plugging into upstreamed support.
InjectedScript._window = function() {
  return contentWindow;
};

Object.type = function(obj, win)
{
    if (obj === null)
        return "null";

    var type = typeof obj;
    if (type !== "object" && type !== "function")
        return type;

    win = win || window;

    if (obj instanceof win.Node)
        return (obj.nodeType === undefined ? type : "node");
    if (obj instanceof win.String)
        return "string";
    if (obj instanceof win.Array)
        return "array";
    if (obj instanceof win.Boolean)
        return "boolean";
    if (obj instanceof win.Number)
        return "number";
    if (obj instanceof win.Date)
        return "date";
    if (obj instanceof win.RegExp)
        return "regexp";
    if (obj instanceof win.Error)
        return "error";
    return type;
}

// Temporarily moved into the injected context.
Object.hasProperties = function(obj)
{
    if (typeof obj === "undefined" || typeof obj === "null")
        return false;
    for (var name in obj)
        return true;
    return false;
}

Object.describe = function(obj, abbreviated)
{
    var type1 = Object.type(obj);
    var type2 = (obj == null) ? "null" : obj.constructor.name;

    switch (type1) {
    case "object":
    case "node":
        return type2;
    case "array":
        return "[" + obj.toString() + "]";
    case "string":
        if (obj.length > 100)
            return "\"" + obj.substring(0, 100) + "\u2026\"";
        return "\"" + obj + "\"";
    case "function":
        var objectText = String(obj);
        if (!/^function /.test(objectText))
            objectText = (type2 == "object") ? type1 : type2;
        else if (abbreviated)
            objectText = /.*/.exec(obj)[0].replace(/ +$/g, "");
        return objectText;
    case "regexp":
        return String(obj).replace(/([\\\/])/g, "\\$1").replace(/\\(\/[gim]*)$/, "$1").substring(1);
    default:
        return String(obj);
    }
}

Function.prototype.bind = function(thisObject)
{
    var func = this;
    var args = Array.prototype.slice.call(arguments, 1);
    return function() { return func.apply(thisObject, args.concat(Array.prototype.slice.call(arguments, 0))) };
}

String.prototype.escapeCharacters = function(chars)
{
    var foundChar = false;
    for (var i = 0; i < chars.length; ++i) {
        if (this.indexOf(chars.charAt(i)) !== -1) {
            foundChar = true;
            break;
        }
    }

    if (!foundChar)
        return this;

    var result = "";
    for (var i = 0; i < this.length; ++i) {
        if (chars.indexOf(this.charAt(i)) !== -1)
            result += "\\";
        result += this.charAt(i);
    }

    return result;
}
<commit_msg>DevTools: Remove context functions that are not available in InjectedScript.js upstream.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Javascript that is being injected into the inspectable page
 * while debugging.
 */
goog.provide('devtools.Injected');

/**
 * Main injected object.
 * @constructor.
 */
devtools.Injected = function() {
};

/**
 * Dispatches given method with given args on the host object.
 * @param {string} method Method name.
 */
devtools.Injected.prototype.InspectorController = function(method, var_args) {
  var args = Array.prototype.slice.call(arguments, 1);
  return InspectorController[method].apply(InspectorController, args);
};

/**
 * Dispatches given method with given args on the InjectedScript.
 * @param {string} method Method name.
 */
devtools.Injected.prototype.InjectedScript = function(method, var_args) {
  var args = Array.prototype.slice.call(arguments, 1);
  var result = InjectedScript[method].apply(InjectedScript, args);
  return result;
};

// Plugging into upstreamed support.
InjectedScript._window = function() {
  return contentWindow;
};

// Plugging into upstreamed support.
Object.className = function(obj) {
  return (obj == null) ? "null" : obj.constructor.name;
};
<|endoftext|>


<commit_before>/*global Backbone, jQuery, _, ENTER_KEY */
var app = app || {};

(function ($) {
	'use strict';

	// The Application
	// ---------------

	// Our overall **AppView** is the top-level piece of UI.
	app.AppView = Backbone.View.extend({

		// Instead of generating a new element, bind to the existing skeleton of
		// the App already present in the HTML.
		el: '#todoapp',

		// Our template for the line of statistics at the bottom of the app.
		statsTemplate: _.template($('#stats-template').html()),

		// Delegated events for creating new items, and clearing completed ones.
		events: {
			'keypress #new-todo': 'createOnEnter',
			'click #clear-completed': 'clearCompleted',
			'click #toggle-all': 'toggleAllComplete'
		},

		// At initialization we bind to the relevant events on the `Todos`
		// collection, when items are added or changed. Kick things off by
		// loading any preexisting todos that might be saved in *localStorage*.
		initialize: function () {
			this.allCheckbox = this.$('#toggle-all')[0];
			this.$input = this.$('#new-todo');
			this.$footer = this.$('#footer');
			this.$main = this.$('#main');

			this.listenTo(app.todos, 'add', this.addOne);
			this.listenTo(app.todos, 'reset', this.addAll);
			this.listenTo(app.todos, 'change:completed', this.filterOne);
			this.listenTo(app.todos, 'filter', this.filterAll);
			this.listenTo(app.todos, 'all', this.render);

			//suppresses 'add' events with {reset: true} and prevents the app view
			//from being re-rendered for every model.
			//Only renders when the 'reset' event is triggered at the end of the fetch.
			app.todos.fetch({reset: true});
		},

		// Re-rendering the App just means refreshing the statistics -- the rest
		// of the app doesn't change.
		render: function () {
			var completed = app.todos.completed().length;
			var remaining = app.todos.remaining().length;

			if (app.todos.length) {
				this.$main.show();
				this.$footer.show();

				this.$footer.html(this.statsTemplate({
					completed: completed,
					remaining: remaining
				}));

				this.$('#filters li a')
					.removeClass('selected')
					.filter('[href="#/' + (app.TodoFilter || '') + '"]')
					.addClass('selected');
			} else {
				this.$main.hide();
				this.$footer.hide();
			}

			this.allCheckbox.checked = !remaining;
		},

		// Add a single todo item to the list by creating a view for it, and
		// appending its element to the `<ul>`.
		addOne: function (todo) {
			var view = new app.TodoView({ model: todo });
			$('#todo-list').append(view.render().el);
		},

		// Add all items in the **Todos** collection at once.
		addAll: function () {
			this.$('#todo-list').html('');
			app.todos.each(this.addOne, this);
		},

		filterOne: function (todo) {
			todo.trigger('visible');
		},

		filterAll: function () {
			app.todos.each(this.filterOne, this);
		},

		// Generate the attributes for a new Todo item.
		newAttributes: function () {
			return {
				title: this.$input.val().trim(),
				order: app.todos.nextOrder(),
				completed: false
			};
		},

		// If you hit return in the main input field, create new **Todo** model,
		// persisting it to *localStorage*.
		createOnEnter: function (e) {
			if (e.which !== ENTER_KEY || !this.$input.val().trim()) {
				return;
			}

			app.todos.create(this.newAttributes());
			this.$input.val('');
		},

		// Clear all completed todo items, destroying their models.
		clearCompleted: function () {
			_.invoke(app.todos.completed(), 'destroy');
			return false;
		},

		toggleAllComplete: function () {
			var completed = this.allCheckbox.checked;

			app.todos.each(function (todo) {
				todo.save({
					'completed': completed
				});
			});
		}
	});
})(jQuery);
<commit_msg>comment formatting per style guide<commit_after>/*global Backbone, jQuery, _, ENTER_KEY */
var app = app || {};

(function ($) {
	'use strict';

	// The Application
	// ---------------

	// Our overall **AppView** is the top-level piece of UI.
	app.AppView = Backbone.View.extend({

		// Instead of generating a new element, bind to the existing skeleton of
		// the App already present in the HTML.
		el: '#todoapp',

		// Our template for the line of statistics at the bottom of the app.
		statsTemplate: _.template($('#stats-template').html()),

		// Delegated events for creating new items, and clearing completed ones.
		events: {
			'keypress #new-todo': 'createOnEnter',
			'click #clear-completed': 'clearCompleted',
			'click #toggle-all': 'toggleAllComplete'
		},

		// At initialization we bind to the relevant events on the `Todos`
		// collection, when items are added or changed. Kick things off by
		// loading any preexisting todos that might be saved in *localStorage*.
		initialize: function () {
			this.allCheckbox = this.$('#toggle-all')[0];
			this.$input = this.$('#new-todo');
			this.$footer = this.$('#footer');
			this.$main = this.$('#main');

			this.listenTo(app.todos, 'add', this.addOne);
			this.listenTo(app.todos, 'reset', this.addAll);
			this.listenTo(app.todos, 'change:completed', this.filterOne);
			this.listenTo(app.todos, 'filter', this.filterAll);
			this.listenTo(app.todos, 'all', this.render);

			// Suppresses 'add' events with {reset: true} and prevents the app view
			// from being re-rendered for every model. Only renders when the 'reset'
			// event is triggered at the end of the fetch.
			app.todos.fetch({reset: true});
		},

		// Re-rendering the App just means refreshing the statistics -- the rest
		// of the app doesn't change.
		render: function () {
			var completed = app.todos.completed().length;
			var remaining = app.todos.remaining().length;

			if (app.todos.length) {
				this.$main.show();
				this.$footer.show();

				this.$footer.html(this.statsTemplate({
					completed: completed,
					remaining: remaining
				}));

				this.$('#filters li a')
					.removeClass('selected')
					.filter('[href="#/' + (app.TodoFilter || '') + '"]')
					.addClass('selected');
			} else {
				this.$main.hide();
				this.$footer.hide();
			}

			this.allCheckbox.checked = !remaining;
		},

		// Add a single todo item to the list by creating a view for it, and
		// appending its element to the `<ul>`.
		addOne: function (todo) {
			var view = new app.TodoView({ model: todo });
			$('#todo-list').append(view.render().el);
		},

		// Add all items in the **Todos** collection at once.
		addAll: function () {
			this.$('#todo-list').html('');
			app.todos.each(this.addOne, this);
		},

		filterOne: function (todo) {
			todo.trigger('visible');
		},

		filterAll: function () {
			app.todos.each(this.filterOne, this);
		},

		// Generate the attributes for a new Todo item.
		newAttributes: function () {
			return {
				title: this.$input.val().trim(),
				order: app.todos.nextOrder(),
				completed: false
			};
		},

		// If you hit return in the main input field, create new **Todo** model,
		// persisting it to *localStorage*.
		createOnEnter: function (e) {
			if (e.which !== ENTER_KEY || !this.$input.val().trim()) {
				return;
			}

			app.todos.create(this.newAttributes());
			this.$input.val('');
		},

		// Clear all completed todo items, destroying their models.
		clearCompleted: function () {
			_.invoke(app.todos.completed(), 'destroy');
			return false;
		},

		toggleAllComplete: function () {
			var completed = this.allCheckbox.checked;

			app.todos.each(function (todo) {
				todo.save({
					'completed': completed
				});
			});
		}
	});
})(jQuery);
<|endoftext|>