<commit_before>var path = require('path');
var webpack = require('webpack');
var node_modules = path.resolve(__dirname, 'node_modules');
var pathToReact = path.resolve(node_modules, 'react/dist/react.min.js');
var pathToReactDom = path.resolve(node_modules, 'react-dom/dist/react-dom.min.js');
var pathToOriginalJavascriptFilesInLib = path.resolve(__dirname, 'lib');
var pathToBookEditJS = path.resolve(__dirname, 'bookEdit/js');
var pathToOriginalJavascriptFilesInModified_Libraries = path.resolve(__dirname, 'modified_libraries');
var globule = require("globule");

//note: if you change this, change it in gulpfile.js & karma.conf.js as well
var outputDir ="../../output/browser";

//because our output directory does not have the same parent as our node_modules
//https://github.com/babel/babel-loader/issues/166
var babelQueryString = 'presets[]='+require.resolve('babel-preset-es2015')+',presets[]='+require.resolve('babel-preset-react');
var babelString =  require.resolve('babel-loader')+'?'+babelQueryString;

module.exports = {
    context: __dirname,
    devtool: 'source-map',
    //Bloom is not (yet) one webapp; it's actually a several loosely related ones.
    //So we have multiple "entry points" that we need to emit. Fortunately the
    //CommonsChunkPlugin extracts the code that is common to more than one into "commonBundle.js"
    entry: { editTabRootBundle:  './bookEdit/editViewFrame.ts',
             //editablePageBootstrap: './bookEdit/editablePageBootstrap.ts',
             readerSetupBundle: './bookEdit/toolbox/readers/readerSetup/readerSetup.ts',
             editablePageBundle: './bookEdit/editablePage.ts',
             bookPreviewBundle: './bookPreview/bookPreview.ts',
             toolboxBundle: './bookEdit/toolbox/toolboxBootstrap.ts',
             pageChooserBundle: ['./pageChooser/page-chooser.ts'],//https://github.com/webpack/webpack/issues/300
             pageThumbnailListBundle: './bookEdit/pageThumbnailList/pageThumbnailList.ts',
             testBundle: globule.find(["./**/*Spec.ts", "./**/*Spec.js", "!./node_modules/**"])//TODO this maybe slow if 1st it finds it all, then it excludes node_modules
             testBundle: globule.find(["./bookEdit/**/*Spec.ts", "./bookEdit/**/*Spec.js","./lib/**/*Spec.ts", "./lib/**/*Spec.js"])
//             testBundle: globule.find(["./**/*Spec.ts", "./**/*Spec.js", "!./node_modules/**"])//This slowed down webpack a ton, becuase the way it works is that it 1st it finds it all, then it excludes node_modules
           },

    output: {
        path: path.join(__dirname, outputDir),
        filename: "[name].js",

        libraryTarget: "var",

        //makes a single entry point module's epxorts accessible via Exports.
        //Note that if you include more than one entry point js in the frame, the second one will overwrite the Exports var
        // (see the other way of doing this, below, if that becomes necessary for some reason)
        library: "FrameExports"

    },

    resolve: {
        root: ['.'],
        alias: {
              'react-dom': pathToReactDom,
              'react': pathToReact // the point of this is to use the minified version. https://christianalfoni.github.io/react-webpack-cookbook/Optimizing-rebundling.html
            },
        modulesDirectories: [pathToOriginalJavascriptFilesInLib, node_modules, pathToBookEditJS,pathToOriginalJavascriptFilesInModified_Libraries],
        extensions: ['', '.js', '.jsx', '.ts', '.tsx'] //We may need to add .less here... otherwise maybe it will ignore them unless they are require()'d
    },
    plugins: [
           new webpack.optimize.CommonsChunkPlugin("common", "commonBundle.js"),
                         //answer on various legacy issues: http://stackoverflow.com/questions/28969861/managing-jquery-plugin-dependency-in-webpack?lq=1
            //prepend var $ = require("jquery") every time it encounters the global $ identifier or "jQuery".
            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery",
                "window.jQuery": "jquery"
            })
      ],
    module: {

        loaders: [
           { test: /\.ts(x?)$/, loader: 'ts-loader' },
           {
               test: /\.(js|jsx)$/,
               //jquery-ui is currently *not* excluded because we added some imports to it
               exclude: [/node_modules/, /ckeditor/, /jquery-ui/, /-min/, /qtip/, /xregexp-all-min.js/],
//               loader: 'babel?presets[]=react,presets[]=es2015',
               //loader: 'babel?presets[]='+__dirname+"/node_modules/babel-preset-es2015",
               loader: babelString
           },
            // { test: /\.ts(x?)$/, loader: 'babel-loader!ts-loader' },
            // { test: /\.less$/, loader: "style!css!less" }
        ],
        noParse: [pathToReactDom,pathToReact]
    }
};
<commit_msg>Fix merge problem<commit_after>var path = require('path');
var webpack = require('webpack');
var node_modules = path.resolve(__dirname, 'node_modules');
var pathToReact = path.resolve(node_modules, 'react/dist/react.min.js');
var pathToReactDom = path.resolve(node_modules, 'react-dom/dist/react-dom.min.js');
var pathToOriginalJavascriptFilesInLib = path.resolve(__dirname, 'lib');
var pathToBookEditJS = path.resolve(__dirname, 'bookEdit/js');
var pathToOriginalJavascriptFilesInModified_Libraries = path.resolve(__dirname, 'modified_libraries');
var globule = require("globule");

//note: if you change this, change it in gulpfile.js & karma.conf.js as well
var outputDir ="../../output/browser";

//because our output directory does not have the same parent as our node_modules
//https://github.com/babel/babel-loader/issues/166
var babelQueryString = 'presets[]='+require.resolve('babel-preset-es2015')+',presets[]='+require.resolve('babel-preset-react');
var babelString =  require.resolve('babel-loader')+'?'+babelQueryString;

module.exports = {
    context: __dirname,
    devtool: 'source-map',
    //Bloom is not (yet) one webapp; it's actually a several loosely related ones.
    //So we have multiple "entry points" that we need to emit. Fortunately the
    //CommonsChunkPlugin extracts the code that is common to more than one into "commonBundle.js"
    entry: { editTabRootBundle:  './bookEdit/editViewFrame.ts',
             //editablePageBootstrap: './bookEdit/editablePageBootstrap.ts',
             readerSetupBundle: './bookEdit/toolbox/readers/readerSetup/readerSetup.ts',
             editablePageBundle: './bookEdit/editablePage.ts',
             bookPreviewBundle: './bookPreview/bookPreview.ts',
             toolboxBundle: './bookEdit/toolbox/toolboxBootstrap.ts',
             pageChooserBundle: ['./pageChooser/page-chooser.ts'],//https://github.com/webpack/webpack/issues/300
             pageThumbnailListBundle: './bookEdit/pageThumbnailList/pageThumbnailList.ts',
             testBundle: globule.find(["./bookEdit/**/*Spec.ts", "./bookEdit/**/*Spec.js","./lib/**/*Spec.ts", "./lib/**/*Spec.js"])
//             testBundle: globule.find(["./**/*Spec.ts", "./**/*Spec.js", "!./node_modules/**"])//This slowed down webpack a ton, becuase the way it works is that it 1st it finds it all, then it excludes node_modules
           },

    output: {
        path: path.join(__dirname, outputDir),
        filename: "[name].js",

        libraryTarget: "var",

        //makes a single entry point module's epxorts accessible via Exports.
        //Note that if you include more than one entry point js in the frame, the second one will overwrite the Exports var
        // (see the other way of doing this, below, if that becomes necessary for some reason)
        library: "FrameExports"

    },

    resolve: {
        root: ['.'],
        alias: {
              'react-dom': pathToReactDom,
              'react': pathToReact // the point of this is to use the minified version. https://christianalfoni.github.io/react-webpack-cookbook/Optimizing-rebundling.html
            },
        modulesDirectories: [pathToOriginalJavascriptFilesInLib, node_modules, pathToBookEditJS,pathToOriginalJavascriptFilesInModified_Libraries],
        extensions: ['', '.js', '.jsx', '.ts', '.tsx'] //We may need to add .less here... otherwise maybe it will ignore them unless they are require()'d
    },
    plugins: [
           new webpack.optimize.CommonsChunkPlugin("common", "commonBundle.js"),
                         //answer on various legacy issues: http://stackoverflow.com/questions/28969861/managing-jquery-plugin-dependency-in-webpack?lq=1
            //prepend var $ = require("jquery") every time it encounters the global $ identifier or "jQuery".
            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery",
                "window.jQuery": "jquery"
            })
      ],
    module: {

        loaders: [
           { test: /\.ts(x?)$/, loader: 'ts-loader' },
           {
               test: /\.(js|jsx)$/,
               //jquery-ui is currently *not* excluded because we added some imports to it
               exclude: [/node_modules/, /ckeditor/, /jquery-ui/, /-min/, /qtip/, /xregexp-all-min.js/],
//               loader: 'babel?presets[]=react,presets[]=es2015',
               //loader: 'babel?presets[]='+__dirname+"/node_modules/babel-preset-es2015",
               loader: babelString
           },
            // { test: /\.ts(x?)$/, loader: 'babel-loader!ts-loader' },
            // { test: /\.less$/, loader: "style!css!less" }
        ],
        noParse: [pathToReactDom,pathToReact]
    }
};
<|endoftext|>


<commit_before>// For some reason, this property does not get set above.
global.Image = global.window.Image;

global.Range = function Range() {};

const createContextualFragment = html => {
  const div = document.createElement("div");
  div.innerHTML = html;
  return div.children[0]; // so hokey it's not even funny
};

Range.prototype.createContextualFragment = html =>
  createContextualFragment(html);

// HACK: Polyfil that allows codemirror to render in a JSDOM env.
global.window.document.createRange = function createRange() {
  return {
    setEnd: () => {},
    setStart: () => {},
    getBoundingClientRect: () => ({ right: 0 }),
    getClientRects: () => [],
    createContextualFragment
  };
};
<commit_msg>configure enzyme for all using mockument<commit_after>// For some reason, this property does not get set above.
global.Image = global.window.Image;

global.Range = function Range() {};

import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";

configure({ adapter: new Adapter() });

const createContextualFragment = html => {
  const div = document.createElement("div");
  div.innerHTML = html;
  return div.children[0]; // so hokey it's not even funny
};

Range.prototype.createContextualFragment = html =>
  createContextualFragment(html);

// HACK: Polyfil that allows codemirror to render in a JSDOM env.
global.window.document.createRange = function createRange() {
  return {
    setEnd: () => {},
    setStart: () => {},
    getBoundingClientRect: () => ({ right: 0 }),
    getClientRects: () => [],
    createContextualFragment
  };
};
<|endoftext|>


<commit_before>// declare a new module called 'myApp', and make it require the `ng-admin` module as a dependency
var myApp = angular.module('myApp', ['ng-admin']);
// declare a function to run when the module bootstraps (during the 'config' phase)
myApp.config(['NgAdminConfigurationProvider', function (nga) {
    // create an admin application
    var admin = nga.application('Admin Tool', true).debug(true);
    admin.header(getHeader());
    // more configuation here later

    // --------- PROJECTS -----------------------------------
    var project = nga.entity('project')
    	.label("Projects");

    project.listView().fields([
	                          nga.field('name')
	                          	.label('Name')
	                          	.editable(true)
	                          	.isDetailLink(true),
	                          nga.field('active', 'boolean')
	                          	.label('Active'),
	                          nga.field('colorName')
	                          	.label('Color')
                            ]);
    project.creationView().fields([
        nga.field('name')
        	.label('Project Name')
        	.validation({ required: true, minlength: 1, maxlength: 20}),
        nga.field('active', 'boolean')
        	.label('Active')
        	.validation({ required: true })
        	.defaultValue(true),
        nga.field('colorName', 'choice')
        	.choices([
        	    { value: 'default', label: 'default '},
        	    { value: 'primary', label: 'primary'},
        	    { value: 'success', label: 'success'},
        	    { value: 'info', label: 'info'},
        	    { value: 'warning', label: 'warning'},
        	    { value: 'danger', label: 'danger'}
        	])
        	.label('Color Scheme')
        	.defaultValue('default')
        	.validation({ required: true })
	]);

    project.editionView().fields(project.creationView().fields())
    	.title('Edit Project "{{entry.values.name}}":');

    project.showView().fields(project.creationView().fields())
		.title('Project "{{entry.values.name}}":');

    admin.addEntity(project);

    // ------------- NOTIFICATION SCHEMAS -------------------------

    var notification_schema = nga.entity('notification_schema')
    	.label('Notification Schema');

    notification_schema.listView().fields([
        nga.field('name')
        	.label('Schema Name')
        	.editable(false)
        	.isDetailLink(true),
        nga.field('description')
        	.label('Description')
    ]);

    notification_schema.editionView().fields(notification_schema.listView().fields())
    	.title('Edit schema "{{entry.values.name}}":');

    admin.addEntity(notification_schema);

    // ------------- DOCUMENTS -------------------------

    var document = nga.entity('document')
		.label("Documents");

    document.listView().fields([
 	                          nga.field('name')
 	                          	.label('Name')
 	                          	.editable(true)
 	                          	.isDetailLink(true),
 	                          nga.field('deadline', 'date')
 	                          	.label('Deadline')
 	                          	.format('dd.MM.yyyy'),
 	                          nga.field('status')
 	                          	.label('Status'),
 	                          nga.field('projectId', 'reference')
 	                          	.targetEntity(project)
 	                          	.targetField(nga.field('name'))
 	                          	.label('Project Name'),
 	                          nga.field('notificationSchemaId', 'reference')
 	                          	.targetEntity(notification_schema)
 	                          	.targetField(nga.field('description'))
 	                          	.label('Notification Schema')
                             ])
                             .sortField('status')
                             .sortDir('DESC');

    document.creationView().fields([
		nga.field('name')
			.label('Name')
			.validation({ required : true, maxLength: 30}),
		nga.field('deadline', 'date')
			.label('Deadline')
			.format('dd.MM.yyyy')
			.validation({ required : true}),
		nga.field('status', 'choice')
			.label('Status')
			.choices([
		        	    { value: 'NEW', label: 'NEW '},
		        	    { value: 'FINISHED', label: 'FINISHED'}
		    ])
		    .defaultValue('NEW')
		    .validation({ required : true }),
		nga.field('projectId', 'reference')
			.targetEntity(project)
			.targetField(nga.field('name'))
			.label('Project')
			.validation({ required: true }),
		nga.field('notificationSchemaId', 'reference')
           	.targetEntity(notification_schema)
           	.targetField(nga.field('description'))
           	.label('Notification Schema')
    ]);

    document.editionView().fields(document.creationView().fields())
		.title('Edit Document "{{entry.values.name}}":');

    admin.addEntity(document);

// ------------- USERS -------------------------

    var user = nga.entity('user')
		.label("Users");

    user.listView().fields([
        nga.field('username')
           .label('Username')
           .validation({ required : true }),
        nga.field('email', 'email')
           .label('E-mail')
           .validation({ reuqired : true })
    ]);

    user.creationView().fields([
       nga.field('username')
           .label('Username')
           .validation({ required : true }),
       nga.field('email', 'email')
           .label('E-mail')
           .validation({ reuqired : true })
    ]);

    user.editionView().fields(user.creationView().fields())
		.title('Edit User "{{entry.values.name}}":');

    admin.addEntity(user);

    // attach the admin application to the DOM and execute it
    nga.configure(admin);

    function getHeader() {
    	var res =   	'\

 \

 \

Documents
 \

Settings
 \

Log Out
 \

 \

 \
		';
    	return res;
    }
}]);<commit_msg>document filters added but does not work<commit_after>// declare a new module called 'myApp', and make it require the `ng-admin` module as a dependency
var myApp = angular.module('myApp', ['ng-admin']);
// declare a function to run when the module bootstraps (during the 'config' phase)
myApp.config(['NgAdminConfigurationProvider', function (nga) {
    // create an admin application
    var admin = nga.application('Admin Tool', true).debug(true);
    admin.header(getHeader());
    // more configuation here later

    // --------- PROJECTS -----------------------------------
    var project = nga.entity('project')
    	.label("Projects");

    project.listView().fields([
	                          nga.field('name')
	                          	.label('Name')
	                          	.editable(true)
	                          	.isDetailLink(true),
	                          nga.field('active', 'boolean')
	                          	.label('Active'),
	                          nga.field('colorName')
	                          	.label('Color')
                            ]);
    project.creationView().fields([
        nga.field('name')
        	.label('Project Name')
        	.validation({ required: true, minlength: 1, maxlength: 20}),
        nga.field('active', 'boolean')
        	.label('Active')
        	.validation({ required: true })
        	.defaultValue(true),
        nga.field('colorName', 'choice')
        	.choices([
        	    { value: 'default', label: 'default '},
        	    { value: 'primary', label: 'primary'},
        	    { value: 'success', label: 'success'},
        	    { value: 'info', label: 'info'},
        	    { value: 'warning', label: 'warning'},
        	    { value: 'danger', label: 'danger'}
        	])
        	.label('Color Scheme')
        	.defaultValue('default')
        	.validation({ required: true })
	]);

    project.editionView().fields(project.creationView().fields())
    	.title('Edit Project "{{entry.values.name}}":');

    project.showView().fields(project.creationView().fields())
		.title('Project "{{entry.values.name}}":');

    admin.addEntity(project);

    // ------------- NOTIFICATION SCHEMAS -------------------------

    var notification_schema = nga.entity('notification_schema')
    	.label('Notification Schema');

    notification_schema.listView().fields([
        nga.field('name')
        	.label('Schema Name')
        	.editable(false)
        	.isDetailLink(true),
        nga.field('description')
        	.label('Description')
    ]);

    notification_schema.editionView().fields(notification_schema.listView().fields())
    	.title('Edit schema "{{entry.values.name}}":');

    admin.addEntity(notification_schema);

    // ------------- DOCUMENTS -------------------------

    var document = nga.entity('document')
		.label("Documents");

    document.listView().fields([
 	                          nga.field('name')
 	                          	.label('Name')
 	                          	.editable(true)
 	                          	.isDetailLink(true),
 	                          nga.field('deadline', 'date')
 	                          	.label('Deadline')
 	                          	.format('dd.MM.yyyy'),
 	                          nga.field('status')
 	                          	.label('Status'),
 	                          nga.field('projectId', 'reference')
 	                          	.targetEntity(project)
 	                          	.targetField(nga.field('name'))
 	                          	.label('Project Name'),
 	                          nga.field('notificationSchemaId', 'reference')
 	                          	.targetEntity(notification_schema)
 	                          	.targetField(nga.field('description'))
 	                          	.label('Notification Schema')
                             ])
                             .filters([
                                 nga.field('status', 'choice')
                                     .label('Status')
                                     .pinned(true)
                                     .defaultValue('NEW')
                                     .choices([
									        	    { value: 'NEW', label: 'NEW '},
									        	    { value: 'FINISHED', label: 'FINISHED'}
									    ]),
                                 nga.field('name')
                                 	.label('Name'),
                                 nga.field('project', 'reference')
                                 	.label('Project')
                                 	.targetEntity(project)
                                 	.targetField(nga.field('name'))
                             ])
                             .sortField(nga.field('status'))
                             .sortDir('DESC');

    document.creationView().fields([
		nga.field('name')
			.label('Name')
			.validation({ required : true, maxLength: 30}),
		nga.field('deadline', 'date')
			.label('Deadline')
			.format('dd.MM.yyyy')
			.validation({ required : true}),
		nga.field('status', 'choice')
			.label('Status')
			.choices([
		        	    { value: 'NEW', label: 'NEW '},
		        	    { value: 'FINISHED', label: 'FINISHED'}
		    ])
		    .defaultValue('NEW')
		    .validation({ required : true }),
		nga.field('projectId', 'reference')
			.targetEntity(project)
			.targetField(nga.field('name'))
			.label('Project')
			.validation({ required: true }),
		nga.field('notificationSchemaId', 'reference')
           	.targetEntity(notification_schema)
           	.targetField(nga.field('description'))
           	.label('Notification Schema')
    ]);

    document.editionView().fields(document.creationView().fields())
		.title('Edit Document "{{entry.values.name}}":');

    admin.addEntity(document);

// ------------- USERS -------------------------

    var user = nga.entity('user')
		.label("Users");

    user.listView().fields([
        nga.field('username')
           .label('Username')
           .validation({ required : true }),
        nga.field('email', 'email')
           .label('E-mail')
           .validation({ reuqired : true })
    ]);

    user.creationView().fields([
       nga.field('username')
           .label('Username')
           .validation({ required : true }),
       nga.field('email', 'email')
           .label('E-mail')
           .validation({ reuqired : true })
    ]);

    user.editionView().fields(user.creationView().fields())
		.title('Edit User "{{entry.values.name}}":');

    admin.addEntity(user);

    // attach the admin application to the DOM and execute it
    nga.configure(admin);

    function getHeader() {
    	var res =   	'\

 \

 \

Documents
 \

Settings
 \

Log Out
 \

 \

 \
		';
    	return res;
    }
}]);<|endoftext|>


<commit_before>/*
 * ShinyProxy
 *
 * Copyright (C) 2016-2021 Open Analytics
 *
 * ===========================================================================
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the Apache License as published by
 * The Apache Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Apache License for more details.
 *
 * You should have received a copy of the Apache License
 * along with this program.  If not, see <http://www.apache.org/licenses/>
 */
function ErrorHandlingWebSocket(url, protocols) {
    console.log("Called ErrorHandlingWebSocket");
    var res = new WebSocket(url, protocols);

    function handler() {
        console.log("Handling error of websocket connection.")
        setTimeout(Shiny.handleWebSocketError, 1); // execute async to not block other error handling code
    }

    res.addEventListener("error", function (event) {
        handler();
    });

    res.addEventListener("close", function (event) {
        if (!event.wasClean) {
            handler();
        }
    });

    return res;
}

ErrorHandlingWebSocket.prototype = WebSocket.prototype;

window.Shiny = {

    navigatingAway: false,
    containerPath: null,
    webSocketReconnectionMode: null,
    injectorIntervalId: null,
    appWasLoaded: false,
    tryingToReconnect: false,
    reloadAttempts: 0,
    maxReloadAttempts: 10,
    reloadDismissed: false,

    /**
     * Determines whether this is a Shiny app.
     */
    isShiny: function () {
        try {
            var _shinyFrame = document.getElementById('shinyframe');
            if (typeof _shinyFrame.contentWindow.Shiny !== 'undefined' &&
                typeof _shinyFrame.contentWindow.Shiny.shinyapp !== 'undefined' &&
                typeof _shinyFrame.contentWindow.Shiny.shinyapp.reconnect === 'function') {
                return true;
            }
        } catch (error) {

        }
        return false;
    },

    /**
     * Handles a WebSocket error (i.e. close).
     */
    handleWebSocketError: function () {
        if (Shiny.navigatingAway) {
            return;
        }
        if (Shiny.tryingToReconnect) {
            // ignore error
            return;
        }
        if (Shiny.webSocketReconnectionMode === "None") {
            // ignore error
            return;
        }
        if (Shiny.reloadDismissed) {
            // user already dismissed confirmation -> do not ask again
            return;
        }

        if (Shiny.webSocketReconnectionMode === "Auto"
            || (Shiny.webSocketReconnectionMode === "Confirm"
                && confirm("Connection to server lost, try to reconnect to the application?"))
                ) {
            Shiny.reloadPage();
        } else {
            Shiny.reloadDismissed = true;
        }
    },

    /**
     * Effectively reloads the application.
     */
    reloadPage: function () {
        var _shinyFrame = document.getElementById('shinyframe');
        Shiny.tryingToReconnect = true;
        Shiny.showLoading();
        Shiny.reloadAttempts++;
        if (Shiny.isShiny()) {
            setTimeout(() => {
                if (!_shinyFrame.contentWindow.Shiny.shinyapp.isConnected()) {
                    _shinyFrame.contentWindow.Shiny.shinyapp.reconnect();
                }
                Shiny.checkShinyReloadSucceeded();
            }, 50);
        } else {
            $("#shinyframe").remove();
            Shiny.setupIframe();
            Shiny.setShinyFrameHeight();
            Shiny.checkReloadSucceeded();
        }
    },

    /**
     * Reloads the page, after X seconds. X is the current amount of reload attempts.
     * Therefore, there will be more time between each attempt to reload the page, creating a backoff mechanism.
     * If the Shiny.maxReloadAttempts is reached, the user will be asked whether they want to perform a full reload.
     */
    reloadPageBackOff: function () {
        console.log("[Reload attempt " + Shiny.reloadAttempts + "/" + Shiny.maxReloadAttempts + "] Reload not succeeded, trying to reload again in " + Shiny.reloadAttempts + " seconds.");
        if (Shiny.reloadAttempts === Shiny.maxReloadAttempts) {
            // reload full page
            if (confirm("Cannot restore connection server, reload full page?")) {
                window.location.reload();
                return;
            }
            return;  // give up
        }
        setTimeout(Shiny.reloadPage, 1000 * Shiny.reloadAttempts);
    },

    /**
     * Check whether the iframe contains the message that ShinyProxy is starting up.
     * If this the case, the iframe looks like it has properly loaded, however, the iframe just contains a message
     * and not the appropriate app.
     */
    checkIfIframeHasStartupMessage: function() {
        try {
            var _shinyFrame = document.getElementById('shinyframe');
            return (_shinyFrame.contentDocument.documentElement.textContent || _shinyFrame.contentDocument.documentElement.innerText).indexOf('ShinyProxy is starting up') > -1;
        } catch {
        }
        return false;
    },

    /**
     * Checks whether the reload of the application was a success.
     * This is checked 4 times with 250ms between each check.
     * If after 5 checks the app isn't loaded yet, the application is reloaded using Shiny.reloadPageBackOff().
     */
    checkReloadSucceeded: function (checks = 0) {
        var completed = document.getElementById('shinyframe').contentDocument !== null
            && document.getElementById('shinyframe').contentDocument.readyState === "complete"
            && document.getElementById('shinyframe').contentDocument.baseURI !== "about:blank"
            && !Shiny.checkIfIframeHasStartupMessage();

        if (completed) {
            // we're ok
            Shiny.hideLoading();
            Shiny.tryingToReconnect = false;
            Shiny.reloadAttempts = 0;
            return;
        }

        if (checks === 4) {
            Shiny.reloadPageBackOff();
            return;
        }

        // re-check in 50 ms
        setTimeout(() => Shiny.checkReloadSucceeded(checks + 1), 200);
    },

    /**
     * Checks whether the reload of the application was a success in case this is a Shiny app.
     * This is checked 4 times with 250ms between each check.
     * If after 4 checks the app isn't loaded yet, the application is reloaded using Shiny.reloadPageBackOff().
     */
    checkShinyReloadSucceeded: function (checks = 0) {
        var _shinyFrame = document.getElementById('shinyframe');
        if (_shinyFrame.contentWindow.Shiny.shinyapp.$socket !== null && _shinyFrame.contentWindow.Shiny.shinyapp.$socket.readyState === WebSocket.OPEN) {
            Shiny.hideLoading();
            Shiny.tryingToReconnect = false;
            Shiny.reloadAttempts = 0;
            return;
        }

        if (checks === 4) {
            Shiny.reloadPageBackOff();
            return;
        }

        setTimeout(() => Shiny.checkShinyReloadSucceeded(checks + 1), 250);
    },

    /**
     * Injects the ErrorHandlingWebSocket into the iframe.
     */
    injectWebSocket: function () {
        document.getElementById('shinyframe').contentWindow.WebSocket = ErrorHandlingWebSocket;
        document.getElementById('shinyframe').contentWindow.document.querySelectorAll("iframe").forEach(d => d.contentWindow.document.WebSocket = ErrorHandlingWebSocket);
    },

    /**
     * Starts the injection of the ErrorHandlingWebSocket into the iframe.
     * The idea is to poll the iframe every 50ms for its readyState. If the readyState has changed from something
     * different than `complete` to `complete` we know that the injection was successful.
     *
     * The goal is to inject between the `interactive` and `DOMContentLoaded` states.
     * Unfortunately, there is no event generated by the browser which we could use. Therefore we have to fallback to
     * a polling approach.
     *
     * See: https://developer.mozilla.org/en-US/docs/Web/API/Document/readystatechange_event
     * See: https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState
     */
    startInjector: function () {
        if (Shiny.injectorIntervalId !== null) {
            Shiny.stopInjector();
        }

        var replaced = false;
        Shiny.injectorIntervalId = setInterval(function () {
            try {
                var state = document.getElementById('shinyframe').contentWindow.document.readyState
            } catch {
                return;
            }
            if (replaced && state === "complete") {
                // ok
                Shiny.stopInjector();
            } else if (state !== "complete") {
                Shiny.injectWebSocket("setInterval");
                replaced = true;
            }
        }, 50);
    },

    /**
     * Stops the Injector.
     */
    stopInjector: function () {
        clearInterval(Shiny.injectorIntervalId);
    },

    /***
     * Setups the iframe of the application.
     */
    setupIframe: function () {
        var $iframe = $('<iframe id="shinyframe" width="100%" style="display:none;" frameBorder="0"></iframe>')
        // IMPORTANT: start the injector before setting the `src` property of the iframe
        // This is required to ensure that the polling catches all events and therefore the injector works properly.
        Shiny.startInjector();
        $iframe.attr("src", Shiny.containerPath);
        $('#iframeinsert').before($iframe); // insert the iframe into the HTML.
        Shiny.setShinyFrameHeight();
    },

    /**
     * Shows the loading page.
     * If the application already has loaded, the message will contains `Reconnecting` instead of `Launching`.
     */
    showLoading: function () {
        $('#shinyframe').hide();
        if (!Shiny.appWasLoaded) {
            $("#loading").show();
        } else {
            $("#reconnecting").show();
        }
    },

    /**
     *  Hides the loading page.
     */
    hideLoading: function () {
        $('#shinyframe').show();
        if (!Shiny.appWasLoaded) {
            $("#loading").fadeOut("slow");
        } else {
            $("#reconnecting").fadeOut("slow");
        }
    },

    /**
     * Start the Shiny Application.
     * @param containerPath
     * @param webSocketReconnectionMode
     */
    start: function (containerPath, webSocketReconnectionMode) {
        if (containerPath === "") {
            Shiny.setShinyFrameHeight();
            Shiny.showLoading();
            $.post(window.location.pathname + window.location.search, function (response) {
                Shiny.containerPath = response.containerPath;
                Shiny.webSocketReconnectionMode = response.webSocketReconnectionMode;
                Shiny.setupIframe();
                Shiny.hideLoading();
                Shiny.appWasLoaded = true;
            }).fail(function (request) {
                var newDoc = document.open("text/html", "replace");
                newDoc.write(request.responseText);
                newDoc.close();
            });
        } else {
            Shiny.containerPath = containerPath;
            Shiny.webSocketReconnectionMode = webSocketReconnectionMode;
            Shiny.setupIframe();
            Shiny.hideLoading();
            Shiny.appWasLoaded = true;
        }
    },

    /**
     * Update the frame height.
     */
    setShinyFrameHeight: function () {
        $('#shinyframe').css('height', ($(window).height()) + 'px');
    }

};

window.onbeforeunload = function (e) {
    window.Shiny.navigatingAway = true;
};
window.addEventListener("load", Shiny.setShinyFrameHeight);
window.addEventListener("resize", Shiny.setShinyFrameHeight);
<commit_msg>Don't show undefined error when navigating away during load<commit_after>/*
 * ShinyProxy
 *
 * Copyright (C) 2016-2021 Open Analytics
 *
 * ===========================================================================
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the Apache License as published by
 * The Apache Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Apache License for more details.
 *
 * You should have received a copy of the Apache License
 * along with this program.  If not, see <http://www.apache.org/licenses/>
 */
function ErrorHandlingWebSocket(url, protocols) {
    console.log("Called ErrorHandlingWebSocket");
    var res = new WebSocket(url, protocols);

    function handler() {
        console.log("Handling error of websocket connection.")
        setTimeout(Shiny.handleWebSocketError, 1); // execute async to not block other error handling code
    }

    res.addEventListener("error", function (event) {
        handler();
    });

    res.addEventListener("close", function (event) {
        if (!event.wasClean) {
            handler();
        }
    });

    return res;
}

ErrorHandlingWebSocket.prototype = WebSocket.prototype;

window.Shiny = {

    navigatingAway: false,
    containerPath: null,
    webSocketReconnectionMode: null,
    injectorIntervalId: null,
    appWasLoaded: false,
    tryingToReconnect: false,
    reloadAttempts: 0,
    maxReloadAttempts: 10,
    reloadDismissed: false,

    /**
     * Determines whether this is a Shiny app.
     */
    isShiny: function () {
        try {
            var _shinyFrame = document.getElementById('shinyframe');
            if (typeof _shinyFrame.contentWindow.Shiny !== 'undefined' &&
                typeof _shinyFrame.contentWindow.Shiny.shinyapp !== 'undefined' &&
                typeof _shinyFrame.contentWindow.Shiny.shinyapp.reconnect === 'function') {
                return true;
            }
        } catch (error) {

        }
        return false;
    },

    /**
     * Handles a WebSocket error (i.e. close).
     */
    handleWebSocketError: function () {
        if (Shiny.navigatingAway) {
            return;
        }
        if (Shiny.tryingToReconnect) {
            // ignore error
            return;
        }
        if (Shiny.webSocketReconnectionMode === "None") {
            // ignore error
            return;
        }
        if (Shiny.reloadDismissed) {
            // user already dismissed confirmation -> do not ask again
            return;
        }

        if (Shiny.webSocketReconnectionMode === "Auto"
            || (Shiny.webSocketReconnectionMode === "Confirm"
                && confirm("Connection to server lost, try to reconnect to the application?"))
                ) {
            Shiny.reloadPage();
        } else {
            Shiny.reloadDismissed = true;
        }
    },

    /**
     * Effectively reloads the application.
     */
    reloadPage: function () {
        var _shinyFrame = document.getElementById('shinyframe');
        Shiny.tryingToReconnect = true;
        Shiny.showLoading();
        Shiny.reloadAttempts++;
        if (Shiny.isShiny()) {
            setTimeout(() => {
                if (!_shinyFrame.contentWindow.Shiny.shinyapp.isConnected()) {
                    _shinyFrame.contentWindow.Shiny.shinyapp.reconnect();
                }
                Shiny.checkShinyReloadSucceeded();
            }, 50);
        } else {
            $("#shinyframe").remove();
            Shiny.setupIframe();
            Shiny.setShinyFrameHeight();
            Shiny.checkReloadSucceeded();
        }
    },

    /**
     * Reloads the page, after X seconds. X is the current amount of reload attempts.
     * Therefore, there will be more time between each attempt to reload the page, creating a backoff mechanism.
     * If the Shiny.maxReloadAttempts is reached, the user will be asked whether they want to perform a full reload.
     */
    reloadPageBackOff: function () {
        console.log("[Reload attempt " + Shiny.reloadAttempts + "/" + Shiny.maxReloadAttempts + "] Reload not succeeded, trying to reload again in " + Shiny.reloadAttempts + " seconds.");
        if (Shiny.reloadAttempts === Shiny.maxReloadAttempts) {
            // reload full page
            if (confirm("Cannot restore connection server, reload full page?")) {
                window.location.reload();
                return;
            }
            return;  // give up
        }
        setTimeout(Shiny.reloadPage, 1000 * Shiny.reloadAttempts);
    },

    /**
     * Check whether the iframe contains the message that ShinyProxy is starting up.
     * If this the case, the iframe looks like it has properly loaded, however, the iframe just contains a message
     * and not the appropriate app.
     */
    checkIfIframeHasStartupMessage: function() {
        try {
            var _shinyFrame = document.getElementById('shinyframe');
            return (_shinyFrame.contentDocument.documentElement.textContent || _shinyFrame.contentDocument.documentElement.innerText).indexOf('ShinyProxy is starting up') > -1;
        } catch {
        }
        return false;
    },

    /**
     * Checks whether the reload of the application was a success.
     * This is checked 4 times with 250ms between each check.
     * If after 5 checks the app isn't loaded yet, the application is reloaded using Shiny.reloadPageBackOff().
     */
    checkReloadSucceeded: function (checks = 0) {
        var completed = document.getElementById('shinyframe').contentDocument !== null
            && document.getElementById('shinyframe').contentDocument.readyState === "complete"
            && document.getElementById('shinyframe').contentDocument.baseURI !== "about:blank"
            && !Shiny.checkIfIframeHasStartupMessage();

        if (completed) {
            // we're ok
            Shiny.hideLoading();
            Shiny.tryingToReconnect = false;
            Shiny.reloadAttempts = 0;
            return;
        }

        if (checks === 4) {
            Shiny.reloadPageBackOff();
            return;
        }

        // re-check in 50 ms
        setTimeout(() => Shiny.checkReloadSucceeded(checks + 1), 200);
    },

    /**
     * Checks whether the reload of the application was a success in case this is a Shiny app.
     * This is checked 4 times with 250ms between each check.
     * If after 4 checks the app isn't loaded yet, the application is reloaded using Shiny.reloadPageBackOff().
     */
    checkShinyReloadSucceeded: function (checks = 0) {
        var _shinyFrame = document.getElementById('shinyframe');
        if (_shinyFrame.contentWindow.Shiny.shinyapp.$socket !== null && _shinyFrame.contentWindow.Shiny.shinyapp.$socket.readyState === WebSocket.OPEN) {
            Shiny.hideLoading();
            Shiny.tryingToReconnect = false;
            Shiny.reloadAttempts = 0;
            return;
        }

        if (checks === 4) {
            Shiny.reloadPageBackOff();
            return;
        }

        setTimeout(() => Shiny.checkShinyReloadSucceeded(checks + 1), 250);
    },

    /**
     * Injects the ErrorHandlingWebSocket into the iframe.
     */
    injectWebSocket: function () {
        document.getElementById('shinyframe').contentWindow.WebSocket = ErrorHandlingWebSocket;
        document.getElementById('shinyframe').contentWindow.document.querySelectorAll("iframe").forEach(d => d.contentWindow.document.WebSocket = ErrorHandlingWebSocket);
    },

    /**
     * Starts the injection of the ErrorHandlingWebSocket into the iframe.
     * The idea is to poll the iframe every 50ms for its readyState. If the readyState has changed from something
     * different than `complete` to `complete` we know that the injection was successful.
     *
     * The goal is to inject between the `interactive` and `DOMContentLoaded` states.
     * Unfortunately, there is no event generated by the browser which we could use. Therefore we have to fallback to
     * a polling approach.
     *
     * See: https://developer.mozilla.org/en-US/docs/Web/API/Document/readystatechange_event
     * See: https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState
     */
    startInjector: function () {
        if (Shiny.injectorIntervalId !== null) {
            Shiny.stopInjector();
        }

        var replaced = false;
        Shiny.injectorIntervalId = setInterval(function () {
            try {
                var state = document.getElementById('shinyframe').contentWindow.document.readyState
            } catch {
                return;
            }
            if (replaced && state === "complete") {
                // ok
                Shiny.stopInjector();
            } else if (state !== "complete") {
                Shiny.injectWebSocket("setInterval");
                replaced = true;
            }
        }, 50);
    },

    /**
     * Stops the Injector.
     */
    stopInjector: function () {
        clearInterval(Shiny.injectorIntervalId);
    },

    /***
     * Setups the iframe of the application.
     */
    setupIframe: function () {
        var $iframe = $('<iframe id="shinyframe" width="100%" style="display:none;" frameBorder="0"></iframe>')
        // IMPORTANT: start the injector before setting the `src` property of the iframe
        // This is required to ensure that the polling catches all events and therefore the injector works properly.
        Shiny.startInjector();
        $iframe.attr("src", Shiny.containerPath);
        $('#iframeinsert').before($iframe); // insert the iframe into the HTML.
        Shiny.setShinyFrameHeight();
    },

    /**
     * Shows the loading page.
     * If the application already has loaded, the message will contains `Reconnecting` instead of `Launching`.
     */
    showLoading: function () {
        $('#shinyframe').hide();
        if (!Shiny.appWasLoaded) {
            $("#loading").show();
        } else {
            $("#reconnecting").show();
        }
    },

    /**
     *  Hides the loading page.
     */
    hideLoading: function () {
        $('#shinyframe').show();
        if (!Shiny.appWasLoaded) {
            $("#loading").fadeOut("slow");
        } else {
            $("#reconnecting").fadeOut("slow");
        }
    },

    /**
     * Start the Shiny Application.
     * @param containerPath
     * @param webSocketReconnectionMode
     */
    start: function (containerPath, webSocketReconnectionMode) {
        if (containerPath === "") {
            Shiny.setShinyFrameHeight();
            Shiny.showLoading();
            $.post(window.location.pathname + window.location.search, function (response) {
                Shiny.containerPath = response.containerPath;
                Shiny.webSocketReconnectionMode = response.webSocketReconnectionMode;
                Shiny.setupIframe();
                Shiny.hideLoading();
                Shiny.appWasLoaded = true;
            }).fail(function (request) {
                if (!Shiny.navigatingAway) {
                    var newDoc = document.open("text/html", "replace");
                    newDoc.write(request.responseText);
                    newDoc.close();
                }
            });
        } else {
            Shiny.containerPath = containerPath;
            Shiny.webSocketReconnectionMode = webSocketReconnectionMode;
            Shiny.setupIframe();
            Shiny.hideLoading();
            Shiny.appWasLoaded = true;
        }
    },

    /**
     * Update the frame height.
     */
    setShinyFrameHeight: function () {
        $('#shinyframe').css('height', ($(window).height()) + 'px');
    }

};

window.onbeforeunload = function (e) {
    window.Shiny.navigatingAway = true;
};
window.addEventListener("load", Shiny.setShinyFrameHeight);
window.addEventListener("resize", Shiny.setShinyFrameHeight);
<|endoftext|>


<commit_before>"use strict";

var oo = require('../util/oo');
var JSONConverter = require('../model/JSONConverter');
var documentHelpers = require('../model/documentHelpers');
var ClipboardImporter = require('./ClipboardImporter');
var ClipboardExporter = require('./ClipboardExporter');
var substanceGlobals = require('../util/substanceGlobals');

/**
  The Clipboard is a Component which should be rendered as a sibling component
  of one or multiple Surfaces.

  It uses the JSONImporter and JSONExporter for internal copy'n'pasting,
  i.e., within one window or between two instances with the same DocumentSchema.

  For inter-application copy'n'paste, the ClipboardImporter and ClipboardExporter is used.
  For HTML coming from the clipboard we support a fixed set of content types:

    - Paragraph
    - Heading
    - Strong/Bold
    - Emphasis/Italic
    - Link
    - Table
    - List

  To make this work for a custom schema, you must include the default nodes into your schema.
  Otherwise, only plain text will be copied. If `Paragraph` is not present in your schema,
  `schema.getDefaultTextType()` is used instead.
*/
var Clipboard = function(surface) {

  this.surface = surface;
  var doc = surface.getDocument();
  var schema = doc.getSchema();

  this.htmlImporter = new ClipboardImporter({ schema: schema, DocumentClass: doc.constructor });
  this.htmlExporter = new ClipboardExporter();

  this.onCopy = this.onCopy.bind(this);
  this.onCut = this.onCut.bind(this);

  this.isIe = (window.navigator.userAgent.toLowerCase().indexOf("msie") != -1 || window.navigator.userAgent.toLowerCase().indexOf("trident") != -1);
  this.isFF = window.navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

  if (this.isIe) {
    this.onBeforePasteShim = this.onBeforePasteShim.bind(this);
    this.onPasteShim = this.onPasteShim.bind(this);
  } else {
    this.onPaste = this.onPaste.bind(this);
  }
};

Clipboard.Prototype = function() {

  this.getSurface = function() {
    return this.surface;
  };

  /*
    Called by to enable clipboard handling on a given root element.

    @private
    @param {util/jquery} a jQuery wrapped element
  */
  this.attach = function(el) {
    // TODO: we want to use ui/DOMElement instead of $
    // However, we need to inject an element into document.body, which can't be accessed via
    // DOMElement API atm.

    el.addEventListener('copy', null, this.onCopy, this);
    el.addEventListener('cut', null, this.onCut, this);

    if (this.isIe) {
      el.addEventListener('beforepaste', null, this.onBeforePasteShim, this);
      el.addEventListener('paste', null, this.onPasteShim, this);
    } else {
      el.addEventListener('paste', null, this.onPaste, this);
    }
  };

  this.didMount = function() {
    var el = this.surface;
    // Note: we need a hidden content-editable element to be able to intercept native pasting.
    // We put this element into document.body and share it among all Clipboard instances.
    // This element must be content-editable, thus it must not have `display:none` or `visibility:hidden`,
    // To hide it from the view we use a zero width and position it outside of the screen.
    if (!Clipboard._sharedPasteElement) {
      var root = el.getRoot();
      var body = root.find('body');
      if (body) {
        var _sharedPasteElement = root.createElement('div')
          .attr('contenteditable', true)
          .css({
            position: 'fixed',
            opacity: '0.0',
            bottom: '-1000px',
            width: '0px'
          });
        Clipboard._sharedPasteElement = _sharedPasteElement;
        body.append(_sharedPasteElement);
      }
    }
    this.el = Clipboard._sharedPasteElement;
  };

  /*
    Called by to disable clipboard handling.
  */
  this.detach = function(rootElement) {
    rootElement.off('copy', this.onCopy);
    rootElement.off('cut', this.onCut);
    if (this.isIe) {
      rootElement.off('beforepaste', this.onBeforePasteShim);
      rootElement.off('paste', this.onPasteShim);
    } else {
      rootElement.off('paste', this.onPaste);
    }
  };

  /*
    Called when copy event fired.

    @param {Event} event
  */
  this.onCopy = function(event) {
    // console.log("Clipboard.onCopy", arguments);
    var clipboardData = this._copy();
    // in the case that browser doesn't provide event.clipboardData
    // we keep the copied data for internal use.
    // Then we have copy'n'paste at least within one app
    Clipboard.clipboardData = clipboardData;
    // FOR DEBUGGING
    substanceGlobals.clipboardData = clipboardData;
    if (event.clipboardData && clipboardData.doc) {
      event.preventDefault();
      // convert the copied document to json
      var converter = new JSONConverter();
      var json = converter.exportDocument(clipboardData.doc);
      json.__id__ = clipboardData.doc.__id__;
      // store as json, plain text, and html
      event.clipboardData.setData('application/substance', JSON.stringify(json));
      event.clipboardData.setData('text/plain', clipboardData.text);
      event.clipboardData.setData('text/html', clipboardData.html);
    }
  };

  /*
    Called when cut event fired.

    @param {Event} event
  */
  this.onCut = function(event) {
    // preventing default behavior to avoid that contenteditable
    // destroys our DOM
    event.preventDefault();
    // console.log("Clipboard.onCut", arguments);
    this.onCopy(event);
    var surface = this.getSurface();
    if (!surface) return;
    surface.transaction(function(tx, args) {
      return surface.delete(tx, args);
    });
  };

  /*
    Called when paste event fired.

    @param {Event} event
  */
  // Works on Safari/Chrome/FF
  this.onPaste = function(event) {
    var clipboardData = event.clipboardData;
    var surface = this.getSurface();

    var types = {};
    for (var i = 0; i < clipboardData.types.length; i++) {
      types[clipboardData.types[i]] = true;
    }

    event.preventDefault();
    event.stopPropagation();

    var plainText;
    var html;
    var json;
    if (types['text/plain']) {
      plainText = clipboardData.getData('text/plain');
    }
    if (types['text/html']) {
      html = clipboardData.getData('text/html');
    }
    if (types['application/substance']) {
      json = clipboardData.getData('application/substance');
    }

    // FOR DEBUGGING
    substanceGlobals.clipboardData = {
      text: plainText,
      html: html,
      json: json
    };

    // WORKAROUND: FF does not provide HTML coming in from other applications
    // so fall back to the paste shim
    if (this.isFF && !json && !html) {
      this._pastePlainText(plainText);
      return;
    }

    // use internal data if available
    if (json) {
      json = JSON.parse(json);
      var schema = surface.getDocument().getSchema();
      // only paste via JSON if the schema is correct
      if (json.schema.name === schema.name && json.schema.version === schema.version) {
        return this._pasteSubstanceData(json, plainText);
      }
    }

    // if we have content given as HTML we let the importer assess the quality first
    // and fallback to plain text import if it's bad
    if (html) {
      if (this._pasteHtml(html, plainText)) {
        return;
      }
    }

    // Fallback to plain-text in other cases
    this._pastePlainText(plainText);
  };

  /*
    Pastes a given plain text into the surface.

    @param {String} plainText plain text
  */
  this._pastePlainText = function(plainText) {
    var surface = this.getSurface();
    surface.transaction(function(tx, args) {
      args.text = plainText;
      return surface.paste(tx, args);
    });
  };

  this.onBeforePasteShim = function() {
    var surface = this.getSurface();
    if (!surface) return;
    // console.log("Clipboard.onBeforePasteShim...");
    // HACK: need to work on the native element here
    var el = this._getNativeElement();
    el.focus();
    var range = document.createRange();
    range.selectNodeContents(el);
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
  };

  this.onPasteShim = function() {
    // HACK: need to work on the native element here
    var el = this._getNativeElement;
    el.innerHTML = "";
    var sel = this.surface.getSelection();
    // NOTE: this delay is necessary to let the browser paste into the paste bin
    window.setTimeout(function() {
      this.surface.selection = sel;
      var html = el.innerHTML;
      var text = el.textContent;
      el.innerHTML = "";

      // FOR DEBUGGING
      substanceGlobals.clipboardData = {
        text: text,
        html: html,
        json: null
      };

      return this._pasteHtml(html, el.textContent);
    }.bind(this));
  };

  /*
    Copies data from surface to clipboard.
  */
  this._copy = function() {
    var surface = this.getSurface();
    var sel = surface.getSelection();
    var doc = surface.getDocument();
    var clipboardDoc = null;
    var clipboardText = "";
    var clipboardHtml = "";
    if (!sel.isCollapsed()) {
      clipboardText = documentHelpers.getTextForSelection(doc, sel);
      clipboardDoc = surface.copy(doc, sel);
      clipboardHtml = this.htmlExporter.exportDocument(clipboardDoc);
    }
    return {
      doc: clipboardDoc,
      html: clipboardHtml,
      text: clipboardText
    };
  };

  /*
    Pastes substance data to surface.

    @param {Object} json substance document in json
    @param {String} text plain text representation used as a fallback
  */
  this._pasteSubstanceData = function(json, text) {
    var surface = this.getSurface();
    if (!surface) return;
    var doc = surface.getDocument();

    var content = doc.newInstance();
    var converter = new JSONConverter();
    converter.importDocument(content, json);

    surface.transaction(function(tx, args) {
      args.text = text;
      args.doc = content;
      return surface.paste(tx, args);
    });
  };

  /*
    Pastes a given parsed html document into the surface.

    @param {ui/DOMElement} docElement
    @param {String} text plain text representation used as a fallback
  */
  this._pasteHtml = function(html, text) {
    var surface = this.getSurface();
    if (!surface) return;
    // TODO: the clipboard importer should make sure
    // that the container exists
    var content = null;
    try {
      content = this.htmlImporter.importDocument(html);
    } catch (err) {
      return false;
    }
    if (content) {
      surface.transaction(function(tx, args) {
        args.text = text;
        args.doc = content;
        return surface.paste(tx, args);
      });
      return true;
    }
  };

  this._getNativeElement = function() {
    return this.el.el;
  };
};

oo.initClass(Clipboard);

/*
  A shim for browsers with an unsupported native clipboard.
*/
Clipboard.clipboardData = {
  doc: null,
  html: "",
  text: ""
};

module.exports = Clipboard;
<commit_msg>Fix Clipboard docs.<commit_after>"use strict";

var oo = require('../util/oo');
var JSONConverter = require('../model/JSONConverter');
var documentHelpers = require('../model/documentHelpers');
var ClipboardImporter = require('./ClipboardImporter');
var ClipboardExporter = require('./ClipboardExporter');
var substanceGlobals = require('../util/substanceGlobals');

/**
  The Clipboard is a Component which should be rendered as a sibling component
  of one or multiple Surfaces.

  It uses the JSONImporter and JSONExporter for internal copy'n'pasting,
  i.e., within one window or between two instances with the same DocumentSchema.

  For inter-application copy'n'paste, the ClipboardImporter and ClipboardExporter is used.
  For HTML coming from the clipboard we support a fixed set of content types:

    - Paragraph
    - Heading
    - Strong/Bold
    - Emphasis/Italic
    - Link
    - Table
    - List

  To make this work for a custom schema, you must include the default nodes into your schema.
  Otherwise, only plain text will be copied. If `Paragraph` is not present in your schema,
  `schema.getDefaultTextType()` is used instead.

  @class Clipboard
*/
var Clipboard = function(surface) {

  this.surface = surface;
  var doc = surface.getDocument();
  var schema = doc.getSchema();

  this.htmlImporter = new ClipboardImporter({ schema: schema, DocumentClass: doc.constructor });
  this.htmlExporter = new ClipboardExporter();

  this.onCopy = this.onCopy.bind(this);
  this.onCut = this.onCut.bind(this);

  this.isIe = (window.navigator.userAgent.toLowerCase().indexOf("msie") != -1 || window.navigator.userAgent.toLowerCase().indexOf("trident") != -1);
  this.isFF = window.navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

  if (this.isIe) {
    this.onBeforePasteShim = this.onBeforePasteShim.bind(this);
    this.onPasteShim = this.onPasteShim.bind(this);
  } else {
    this.onPaste = this.onPaste.bind(this);
  }
};

Clipboard.Prototype = function() {

  this.getSurface = function() {
    return this.surface;
  };

  /*
    Called by to enable clipboard handling on a given root element.

    @private
    @param {util/jquery} a jQuery wrapped element
  */
  this.attach = function(el) {
    // TODO: we want to use ui/DOMElement instead of $
    // However, we need to inject an element into document.body, which can't be accessed via
    // DOMElement API atm.

    el.addEventListener('copy', null, this.onCopy, this);
    el.addEventListener('cut', null, this.onCut, this);

    if (this.isIe) {
      el.addEventListener('beforepaste', null, this.onBeforePasteShim, this);
      el.addEventListener('paste', null, this.onPasteShim, this);
    } else {
      el.addEventListener('paste', null, this.onPaste, this);
    }
  };

  this.didMount = function() {
    var el = this.surface;
    // Note: we need a hidden content-editable element to be able to intercept native pasting.
    // We put this element into document.body and share it among all Clipboard instances.
    // This element must be content-editable, thus it must not have `display:none` or `visibility:hidden`,
    // To hide it from the view we use a zero width and position it outside of the screen.
    if (!Clipboard._sharedPasteElement) {
      var root = el.getRoot();
      var body = root.find('body');
      if (body) {
        var _sharedPasteElement = root.createElement('div')
          .attr('contenteditable', true)
          .css({
            position: 'fixed',
            opacity: '0.0',
            bottom: '-1000px',
            width: '0px'
          });
        Clipboard._sharedPasteElement = _sharedPasteElement;
        body.append(_sharedPasteElement);
      }
    }
    this.el = Clipboard._sharedPasteElement;
  };

  /*
    Called by to disable clipboard handling.
  */
  this.detach = function(rootElement) {
    rootElement.off('copy', this.onCopy);
    rootElement.off('cut', this.onCut);
    if (this.isIe) {
      rootElement.off('beforepaste', this.onBeforePasteShim);
      rootElement.off('paste', this.onPasteShim);
    } else {
      rootElement.off('paste', this.onPaste);
    }
  };

  /*
    Called when copy event fired.

    @param {Event} event
  */
  this.onCopy = function(event) {
    // console.log("Clipboard.onCopy", arguments);
    var clipboardData = this._copy();
    // in the case that browser doesn't provide event.clipboardData
    // we keep the copied data for internal use.
    // Then we have copy'n'paste at least within one app
    Clipboard.clipboardData = clipboardData;
    // FOR DEBUGGING
    substanceGlobals.clipboardData = clipboardData;
    if (event.clipboardData && clipboardData.doc) {
      event.preventDefault();
      // convert the copied document to json
      var converter = new JSONConverter();
      var json = converter.exportDocument(clipboardData.doc);
      json.__id__ = clipboardData.doc.__id__;
      // store as json, plain text, and html
      event.clipboardData.setData('application/substance', JSON.stringify(json));
      event.clipboardData.setData('text/plain', clipboardData.text);
      event.clipboardData.setData('text/html', clipboardData.html);
    }
  };

  /*
    Called when cut event fired.

    @param {Event} event
  */
  this.onCut = function(event) {
    // preventing default behavior to avoid that contenteditable
    // destroys our DOM
    event.preventDefault();
    // console.log("Clipboard.onCut", arguments);
    this.onCopy(event);
    var surface = this.getSurface();
    if (!surface) return;
    surface.transaction(function(tx, args) {
      return surface.delete(tx, args);
    });
  };

  /*
    Called when paste event fired.

    @param {Event} event
  */
  // Works on Safari/Chrome/FF
  this.onPaste = function(event) {
    var clipboardData = event.clipboardData;
    var surface = this.getSurface();

    var types = {};
    for (var i = 0; i < clipboardData.types.length; i++) {
      types[clipboardData.types[i]] = true;
    }

    event.preventDefault();
    event.stopPropagation();

    var plainText;
    var html;
    var json;
    if (types['text/plain']) {
      plainText = clipboardData.getData('text/plain');
    }
    if (types['text/html']) {
      html = clipboardData.getData('text/html');
    }
    if (types['application/substance']) {
      json = clipboardData.getData('application/substance');
    }

    // FOR DEBUGGING
    substanceGlobals.clipboardData = {
      text: plainText,
      html: html,
      json: json
    };

    // WORKAROUND: FF does not provide HTML coming in from other applications
    // so fall back to the paste shim
    if (this.isFF && !json && !html) {
      this._pastePlainText(plainText);
      return;
    }

    // use internal data if available
    if (json) {
      json = JSON.parse(json);
      var schema = surface.getDocument().getSchema();
      // only paste via JSON if the schema is correct
      if (json.schema.name === schema.name && json.schema.version === schema.version) {
        return this._pasteSubstanceData(json, plainText);
      }
    }

    // if we have content given as HTML we let the importer assess the quality first
    // and fallback to plain text import if it's bad
    if (html) {
      if (this._pasteHtml(html, plainText)) {
        return;
      }
    }

    // Fallback to plain-text in other cases
    this._pastePlainText(plainText);
  };

  /*
    Pastes a given plain text into the surface.

    @param {String} plainText plain text
  */
  this._pastePlainText = function(plainText) {
    var surface = this.getSurface();
    surface.transaction(function(tx, args) {
      args.text = plainText;
      return surface.paste(tx, args);
    });
  };

  this.onBeforePasteShim = function() {
    var surface = this.getSurface();
    if (!surface) return;
    // console.log("Clipboard.onBeforePasteShim...");
    // HACK: need to work on the native element here
    var el = this._getNativeElement();
    el.focus();
    var range = document.createRange();
    range.selectNodeContents(el);
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
  };

  this.onPasteShim = function() {
    // HACK: need to work on the native element here
    var el = this._getNativeElement;
    el.innerHTML = "";
    var sel = this.surface.getSelection();
    // NOTE: this delay is necessary to let the browser paste into the paste bin
    window.setTimeout(function() {
      this.surface.selection = sel;
      var html = el.innerHTML;
      var text = el.textContent;
      el.innerHTML = "";

      // FOR DEBUGGING
      substanceGlobals.clipboardData = {
        text: text,
        html: html,
        json: null
      };

      return this._pasteHtml(html, el.textContent);
    }.bind(this));
  };

  /*
    Copies data from surface to clipboard.
  */
  this._copy = function() {
    var surface = this.getSurface();
    var sel = surface.getSelection();
    var doc = surface.getDocument();
    var clipboardDoc = null;
    var clipboardText = "";
    var clipboardHtml = "";
    if (!sel.isCollapsed()) {
      clipboardText = documentHelpers.getTextForSelection(doc, sel);
      clipboardDoc = surface.copy(doc, sel);
      clipboardHtml = this.htmlExporter.exportDocument(clipboardDoc);
    }
    return {
      doc: clipboardDoc,
      html: clipboardHtml,
      text: clipboardText
    };
  };

  /*
    Pastes substance data to surface.

    @param {Object} json substance document in json
    @param {String} text plain text representation used as a fallback
  */
  this._pasteSubstanceData = function(json, text) {
    var surface = this.getSurface();
    if (!surface) return;
    var doc = surface.getDocument();

    var content = doc.newInstance();
    var converter = new JSONConverter();
    converter.importDocument(content, json);

    surface.transaction(function(tx, args) {
      args.text = text;
      args.doc = content;
      return surface.paste(tx, args);
    });
  };

  /*
    Pastes a given parsed html document into the surface.

    @param {ui/DOMElement} docElement
    @param {String} text plain text representation used as a fallback
  */
  this._pasteHtml = function(html, text) {
    var surface = this.getSurface();
    if (!surface) return;
    // TODO: the clipboard importer should make sure
    // that the container exists
    var content = null;
    try {
      content = this.htmlImporter.importDocument(html);
    } catch (err) {
      return false;
    }
    if (content) {
      surface.transaction(function(tx, args) {
        args.text = text;
        args.doc = content;
        return surface.paste(tx, args);
      });
      return true;
    }
  };

  this._getNativeElement = function() {
    return this.el.el;
  };
};

oo.initClass(Clipboard);

/*
  A shim for browsers with an unsupported native clipboard.
*/
Clipboard.clipboardData = {
  doc: null,
  html: "",
  text: ""
};

module.exports = Clipboard;
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/. */

'use strict';

treeherder.value("thPlatformNameMap", {
    "linux32": "Linux",
    "linux64": "Linux x64",
    "osx-10-6": "OS X 10.6",
    "osx-10-8": "OS X 10.8",
    "osx-10-9": "OS X 10.9",
    "windowsxp": "Windows XP",
    "windows7-32": "Windows 7",
    "windows8-32": "Windows 8",
    "windows8-64": "Windows 8 x64",
    "windows2012-64": "Windows 2012 x64",
    "android-2-2-armv6": "Android 2.2 Armv6",
    "android-2-2": "Android 2.2",
    "android-2-3-armv6": "Android 2.3 Armv6",
    "android-2-3": "Android 2.3",
    "android-2-3-armv7-api9": "Android 2.3 API9",
    "android-4-0": "Android 4.0",
    "android-4-0-armv7-api10": "Android 4.0 API10+",
    "android-4-0-armv7-api11": "Android 4.0 API11+",
    "android-4-2-x86": "Android 4.2 x86",
    "android-4-2": "Android 4.2",
    "android-4-2-armv7-api11": "Android 4.2 API11+",
    "android-4-3": "Android 4.3",
    "android-4-3-armv7-api11": "Android 4.3 API11+",
    "android-4-4": "Android 4.4",
    "android-4-4-armv7-api11": "Android 4.4 API11+",
    "android-5-0-armv7-api11": "Android 5.0 API11+",
    "b2g-linux32": "B2G Desktop Linux",
    "b2g-linux64": "B2G Desktop Linux x64",
    "b2g-osx": "B2G Desktop OS X",
    "b2g-win32": "B2G Desktop Windows",
    "b2g-emu-ics": "B2G ICS Emulator",
    "b2g-emu-jb": "B2G JB Emulator",
    "b2g-emu-kk": "B2G KK Emulator",
    "b2g-device-image" : "B2G Device Image",
    "mulet-linux32" : "Mulet Linux",
    "mulet-linux64" : "Mulet Linux x64",
    "mulet-osx": "Mulet OS X",
    "mulet-win32": "Mulet Windows",
    "other": "Other"
});

treeherder.value("thFailureResults", ["testfailed", "busted", "exception"]);

treeherder.value("thFavicons", {
    "closed": "img/tree_closed.png",
    "open": "img/tree_open.png",
    "approval required": "img/tree_open.png",
    "unavailable": "img/tree_open.png"
});

treeherder.value("thRepoGroupOrder", {
    "development": 1,
    "project repositories": 2,
    "try": 3,
    "release-stabilization": 4,
    "taskcluster": 5,
    "qa automation tests": 6
});

treeherder.value("thDefaultRepo", "mozilla-central");
<commit_msg>Bug 1119412 - treeherder should display results for 10.10 test jobs<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/. */

'use strict';

treeherder.value("thPlatformNameMap", {
    "linux32": "Linux",
    "linux64": "Linux x64",
    "osx-10-6": "OS X 10.6",
    "osx-10-8": "OS X 10.8",
    "osx-10-10": "OS X 10.10",
    "windowsxp": "Windows XP",
    "windows7-32": "Windows 7",
    "windows8-32": "Windows 8",
    "windows8-64": "Windows 8 x64",
    "windows2012-64": "Windows 2012 x64",
    "android-2-2-armv6": "Android 2.2 Armv6",
    "android-2-2": "Android 2.2",
    "android-2-3-armv6": "Android 2.3 Armv6",
    "android-2-3": "Android 2.3",
    "android-2-3-armv7-api9": "Android 2.3 API9",
    "android-4-0": "Android 4.0",
    "android-4-0-armv7-api10": "Android 4.0 API10+",
    "android-4-0-armv7-api11": "Android 4.0 API11+",
    "android-4-2-x86": "Android 4.2 x86",
    "android-4-2": "Android 4.2",
    "android-4-2-armv7-api11": "Android 4.2 API11+",
    "android-4-3": "Android 4.3",
    "android-4-3-armv7-api11": "Android 4.3 API11+",
    "android-4-4": "Android 4.4",
    "android-4-4-armv7-api11": "Android 4.4 API11+",
    "android-5-0-armv7-api11": "Android 5.0 API11+",
    "b2g-linux32": "B2G Desktop Linux",
    "b2g-linux64": "B2G Desktop Linux x64",
    "b2g-osx": "B2G Desktop OS X",
    "b2g-win32": "B2G Desktop Windows",
    "b2g-emu-ics": "B2G ICS Emulator",
    "b2g-emu-jb": "B2G JB Emulator",
    "b2g-emu-kk": "B2G KK Emulator",
    "b2g-device-image" : "B2G Device Image",
    "mulet-linux32" : "Mulet Linux",
    "mulet-linux64" : "Mulet Linux x64",
    "mulet-osx": "Mulet OS X",
    "mulet-win32": "Mulet Windows",
    "other": "Other"
});

treeherder.value("thFailureResults", ["testfailed", "busted", "exception"]);

treeherder.value("thFavicons", {
    "closed": "img/tree_closed.png",
    "open": "img/tree_open.png",
    "approval required": "img/tree_open.png",
    "unavailable": "img/tree_open.png"
});

treeherder.value("thRepoGroupOrder", {
    "development": 1,
    "project repositories": 2,
    "try": 3,
    "release-stabilization": 4,
    "taskcluster": 5,
    "qa automation tests": 6
});

treeherder.value("thDefaultRepo", "mozilla-central");
<|endoftext|>


<commit_before>/**
 * @fileoverview Lazy background image loader.
 */

var classes = require('../utils/classes');
var objects = require('../utils/objects');
var scrolldelegator = require('../scrolldelegator');
var ui = require('../ui');

var LazyImageLoader = function(selector, attributeName, loadedClassNames) {
  this.selector = selector;
  this.attributeName = attributeName;
  this.loadedClassNames = loadedClassNames;
};

LazyImageLoader.DefaultConfig = {
  selector: "['data-ak-lazy-src']",
  attributeName: 'data-ak-lazy-src',
  loadedClassNames: ['ak-lazy--loaded']
};

LazyImageLoader.prototype.update = function() {
  var els = document.querySelectorAll(this.selector);
  [].forEach.call(els, function(el) {
    if (!el.hasAttribute(this.attributeName)
        || !ui.isElementInView(el, null, true)) {
      return;
    }
    var src = el.getAttribute(this.attributeName);
    if (!src) {
      return;
    }
    var imageLoader = new Image();
    var onLoad = function() {
      if (!el.hasAttribute(this.attributeName)) {
        return;
      }
      el.style.backgroundImage = 'url(' + src + ')';
      el.removeAttribute(this.attributeName);
      if (this.loadedClassNames) {
        [].forEach.call(this.loadedClassNames, function(className) {
          classes.enable(el, className, true);
        });
      }
    }.bind(this);
    imageLoader.addEventListener('load', onLoad);
    imageLoader.src = src;
  }.bind(this));
};

LazyImageLoader.prototype.onScroll = function() {
  this.update();
};

var init = function(opt_config) {
  var config = objects.clone(LazyImageLoader.DefaultConfig);
  if (opt_config) {
    objects.merge(config, opt_config);
  }
  var loader = new LazyImageLoader(
      config.selector, config.attributeName, config.loadedClassNames);
  loader.onScroll();
  scrolldelegator.addDelegate(loader);
  scrolldelegator.start();
  // TODO: Remove this and build into scrolldelegator.
  document.addEventListener('DOMContentLoaded', function() {
    loader.onScroll();
  });
  return loader;
};

module.exports = {
  init: init
};
<commit_msg>Export update method to run across all instances.<commit_after>/**
 * @fileoverview Lazy background image loader.
 */

var classes = require('../utils/classes');
var objects = require('../utils/objects');
var scrolldelegator = require('../scrolldelegator');
var ui = require('../ui');

var instances = [];

var LazyImageLoader = function(selector, attributeName, loadedClassNames) {
  this.selector = selector;
  this.attributeName = attributeName;
  this.loadedClassNames = loadedClassNames;
};

LazyImageLoader.DefaultConfig = {
  selector: "['data-ak-lazy-src']",
  attributeName: 'data-ak-lazy-src',
  loadedClassNames: ['ak-lazy--loaded']
};

LazyImageLoader.prototype.update = function() {
  var els = document.querySelectorAll(this.selector);
  [].forEach.call(els, function(el) {
    if (!el.hasAttribute(this.attributeName)
        || !ui.isElementInView(el, null, true)) {
      return;
    }
    var src = el.getAttribute(this.attributeName);
    if (!src) {
      return;
    }
    var imageLoader = new Image();
    var onLoad = function() {
      if (!el.hasAttribute(this.attributeName)) {
        return;
      }
      el.style.backgroundImage = 'url(' + src + ')';
      el.removeAttribute(this.attributeName);
      if (this.loadedClassNames) {
        [].forEach.call(this.loadedClassNames, function(className) {
          classes.enable(el, className, true);
        });
      }
    }.bind(this);
    imageLoader.addEventListener('load', onLoad);
    imageLoader.src = src;
  }.bind(this));
};

LazyImageLoader.prototype.onScroll = function() {
  this.update();
};

var init = function(opt_config) {
  var config = objects.clone(LazyImageLoader.DefaultConfig);
  if (opt_config) {
    objects.merge(config, opt_config);
  }
  var loader = new LazyImageLoader(
      config.selector, config.attributeName, config.loadedClassNames);
  loader.onScroll();
  scrolldelegator.addDelegate(loader);
  scrolldelegator.start();
  // TODO: Remove this and build into scrolldelegator.
  document.addEventListener('DOMContentLoaded', function() {
    loader.onScroll();
  });
  instances.push(loader);
  return loader;
};

/** Updates all initialized instances. */
var update = function() {
  [].forEach.call(instances, function(instance) {
    instance.update();
  });
};

module.exports = {
  update: update,
  init: init
};
<|endoftext|>


<commit_before>$(document).ready(function(){
    $("#one_post").click(function(){
        var obj = document.getElementById("post");
        var theName = obj.value;
        var x = JSON.parse(theName);
        console.log(theName);
        jQuery.ajax( {
            url: 'https://api.yaas.io/product/v3/tutorialinjs/products',
            type: 'POST',
            data: JSON.stringify(x),
            contentType:"application/json",
            beforeSend : function( xhr ) {
                var id = "Bearer " + $('#token').html();
                xhr.setRequestHeader( "Authorization", id);
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            success: function(response) {
                //alert("Success!" + response.id + response.link);
                $('#get_response').html("Success!" + "\nid: " + response.id + "\nlink: " + response.link);

            }
        } );
    });
});<commit_msg>Update post_ajax.js<commit_after>/*
 * [y] hybris Platform
 *
 * Copyright (c) 2000-2015 hybris AG
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of hybris
 * ("Confidential Information"). You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the
 * license agreement you entered into with hybris.
 */

$(document).ready(function(){
    $("#one_post").click(function(){
        var obj = document.getElementById("post");
        var theName = obj.value;
        var x = JSON.parse(theName);
        console.log(theName);
        jQuery.ajax( {
            url: 'https://api.yaas.io/product/v3/tutorialinjs/products',
            type: 'POST',
            data: JSON.stringify(x),
            contentType:"application/json",
            beforeSend : function( xhr ) {
                var id = "Bearer " + $('#token').html();
                xhr.setRequestHeader( "Authorization", id);
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            success: function(response) {
                //alert("Success!" + response.id + response.link);
                $('#get_response').html("Success!" + "\nid: " + response.id + "\nlink: " + response.link);

            }
        } );
    });
});
<|endoftext|>


<commit_before>jQuery(function() {
	// link up the events
	$('#events .event .paginator a').live('click', function(event) {
		event.preventDefault();
		var url = $(this).attr('href')
		var d   = new Date( parseFloat(url.substring(8, 12)),
		                    parseFloat(url.substring(13, 15)) - 1,
		                    parseFloat(url.substring(16, 18)) );
	    var months = new Array( "January",  "February", "March",
	                            "April",    "May",      "June",
	                            "July",     "August",   "September",
	                            "October",  "November", "December" );
		$.ajax({
		    url:      url,
		    type:     "GET",
		    dataType: "html",
            success: function(data, textStatus, xhr) {
				$('#events .event .date').html( "Meeting:  " +
					                            months[d.getMonth()] + " "  +
				                                d.getDate()          + ", " +
				                                d.getFullYear()      +
				                                "" );
		        $('#events .event .details').html(data);
				$('#events .event .paginator').fadeIn();
            }
        });
	});
	$('#events .event .paginator').fadeIn();

	// rotate member profiles every five seconds
	$('#members .full_list').shuffle();
	setInterval(function() {
		var member = $('#members .full_list a:first').detach();
		$.ajax({
		    url:      member.attr('href'),
		    type:     "GET",
		    dataType: "html",
            success: function(data, textStatus, xhr) {
		        $('#members .member').fadeOut(function() {
			        $('#members .member').html(data);
			        $('#members .member').fadeIn();
				});
            }
        });
		$(member).appendTo('#members .full_list');
	}, 8000);

	// extend presentation listing
	$('#presentations .extender a').live('click', function(event) {
		event.preventDefault();
		$('#more_presentations').show();
		$(this).parent().hide();
	});
});
<commit_msg>Specify a member name in the url hash to view their profile.<commit_after>jQuery(function() {
	// link up the events
	$('#events .event .paginator a').live('click', function(event) {
		event.preventDefault();
		var url = $(this).attr('href')
		var d   = new Date( parseFloat(url.substring(8, 12)),
		                    parseFloat(url.substring(13, 15)) - 1,
		                    parseFloat(url.substring(16, 18)) );
	    var months = new Array( "January",  "February", "March",
	                            "April",    "May",      "June",
	                            "July",     "August",   "September",
	                            "October",  "November", "December" );
		$.ajax({
		    url:      url,
		    type:     "GET",
		    dataType: "html",
            success: function(data, textStatus, xhr) {
				$('#events .event .date').html( "Meeting:  " +
					                            months[d.getMonth()] + " "  +
				                                d.getDate()          + ", " +
				                                d.getFullYear()      +
				                                "" );
		        $('#events .event .details').html(data);
				$('#events .event .paginator').fadeIn();
            }
        });
	});
	$('#events .event .paginator').fadeIn();

	if(location.hash != '') {
		$.get($('a[text='+location.hash.replace(/^#/, '').replace('_', ' ')+']').attr('href'),
			function(data) { $('#members .member').html(data) });
	} else {
		// rotate member profiles every five seconds
		$('#members .full_list').shuffle();
		setInterval(function() {
			var member = $('#members .full_list a:first').detach();
			$.ajax({
			    url:      member.attr('href'),
			    type:     "GET",
			    dataType: "html",
	            success: function(data, textStatus, xhr) {
			        $('#members .member').fadeOut(function() {
				        $('#members .member').html(data);
				        $('#members .member').fadeIn();
					});
	            }
	        });
			$(member).appendTo('#members .full_list');
		}, 8000);
	}

	// extend presentation listing
	$('#presentations .extender a').live('click', function(event) {
		event.preventDefault();
		$('#more_presentations').show();
		$(this).parent().hide();
	});
});
<|endoftext|>