<commit_before>/**
 * @ngdoc service
 * @name umbraco.services.clipboardService
 *
 * @requires notificationsService
 * @requires eventsService
 *
 * @description
 * Service to handle clipboard in general across the application. Responsible for handling the data both storing and retrive.
 * The service has a set way for defining a data-set by a entryType and alias, which later will be used to retrive the posible entries for a paste scenario.
 *
 */
function clipboardService(notificationsService, eventsService) {

    var STORAGE_KEY = "umbClipboardService";

    var supportsLocalStorage = function () {
        var test = "test";

        try {
            window.localStorage.setItem(test, test);
            window.localStorage.removeItem(test);
            return true;
        } catch (e) {
            return false;
        }

        return false;
    }

    var retriveStorage = function() {
        if (supportsLocalStorage === false) {
            return null;
        }

        var dataJSON;
        var dataString = window.localStorage.getItem(STORAGE_KEY);
        if (dataString != null) {
            dataJSON = JSON.parse(dataString);
        }

        if(dataJSON == null) {
            dataJSON = new Object();
        }

        if(dataJSON.entries === undefined) {
            dataJSON.entries = [];
        }

        return dataJSON;
    }

    var saveStorage = function(storage) {
        var storageString = JSON.stringify(storage)

        try {
            var storageJSON = JSON.parse(storageString);
            window.localStorage.setItem(STORAGE_KEY, storageString);

            eventsService.emit("clipboardService.storageUpdate");

            return true;
        } catch(e) {
            return false;
        }

        return false;
    }

    var service = {};

    /**
    * @ngdoc method
    * @name umbraco.services.clipboardService#copy
    * @methodOf umbraco.services.clipboardService
    *
    * @description
    * Saves a single JS-object with a type and alias to the clipboard.
    */
    service.copy = function(type, alias, data) {

        var storage = retriveStorage();

        var shallowCloneData = Object.assign({}, data);// Notice only a shallow copy, since we dont need to deep copy. (that will happen when storing the data)
        delete shallowCloneData.key;
        delete shallowCloneData.$$hashKey;

        var key = data.key || data.$$hashKey || console.error("missing unique key for this content");

        // remove previous copies of this entry:
        storage.entries = storage.entries.filter(
            (entry) => {
                return entry.unique !== key;
            }
        );

        var entry = {unique:key, type:type, alias:alias, data:shallowCloneData};
        storage.entries.push(entry);

        if (saveStorage(storage) === true) {
            notificationsService.success("Clipboard", "Copied to clipboard.");
        } else {
            notificationsService.success("Clipboard", "Couldnt copy this data to clipboard.");
        }

    };

    /**
    * @ngdoc method
    * @name umbraco.services.supportsCopy#supported
    * @methodOf umbraco.services.clipboardService
    *
    * @description
    * Determins wether the current browser is able to performe its actions.
    */
    service.isSupported = supportsLocalStorage;

    /**
    * @ngdoc method
    * @name umbraco.services.supportsCopy#copy
    * @methodOf umbraco.services.clipboardService
    *
    * @description
    * Determins wether the current browser is able to performe a copy-action.
    */
    service.hasEntriesOfType = function(type, aliases) {

        if(service.retriveEntriesOfType(type, aliases).length > 0) {
            return true;
        }

        return false;
    };

    service.retriveEntriesOfType = function(type, aliases) {

        var storage = retriveStorage();

        // Find entries that are furfilling the criterias for this nodeTYpe and nodeTypesAliases.
        var filteretEntries = storage.entries.filter(
            (entry) => {
                return (entry.type === type && aliases.filter(alias => alias === entry.alias).length > 0);
            }
        );

        return filteretEntries;
    };

    service.retriveDataOfType = function(type, aliases) {
        return service.retriveEntriesOfType(type, aliases).map((x) => x.data);
    };

    service.clearEntriesOfType = function(type, aliases) {

        var storage = retriveStorage();

        // Find entries that are NOT furfilling the criterias for this nodeTYpe and nodeTypesAliases.
        var filteretEntries = storage.entries.filter(
            (entry) => {
                return !(entry.type === type && aliases.filter(alias => alias === entry.alias).length > 0);
            }
        );

        storage.entries = filteretEntries;

        saveStorage(storage);
    };

    return service;
}

angular.module("umbraco.services").factory("clipboardService", clipboardService);

<commit_msg>added missing documentation<commit_after>/**
 * @ngdoc service
 * @name umbraco.services.clipboardService
 *
 * @requires notificationsService
 * @requires eventsService
 *
 * @description
 * Service to handle clipboard in general across the application. Responsible for handling the data both storing and retrive.
 * The service has a set way for defining a data-set by a entryType and alias, which later will be used to retrive the posible entries for a paste scenario.
 *
 */
function clipboardService(notificationsService, eventsService) {

    var STORAGE_KEY = "umbClipboardService";

    var supportsLocalStorage = function () {
        var test = "test";

        try {
            window.localStorage.setItem(test, test);
            window.localStorage.removeItem(test);
            return true;
        } catch (e) {
            return false;
        }

        return false;
    }

    var retriveStorage = function() {
        if (supportsLocalStorage === false) {
            return null;
        }

        var dataJSON;
        var dataString = window.localStorage.getItem(STORAGE_KEY);
        if (dataString != null) {
            dataJSON = JSON.parse(dataString);
        }

        if(dataJSON == null) {
            dataJSON = new Object();
        }

        if(dataJSON.entries === undefined) {
            dataJSON.entries = [];
        }

        return dataJSON;
    }

    var saveStorage = function(storage) {
        var storageString = JSON.stringify(storage)

        try {
            var storageJSON = JSON.parse(storageString);
            window.localStorage.setItem(STORAGE_KEY, storageString);

            eventsService.emit("clipboardService.storageUpdate");

            return true;
        } catch(e) {
            return false;
        }

        return false;
    }

    var service = {};

    /**
    * @ngdoc method
    * @name umbraco.services.clipboardService#copy
    * @methodOf umbraco.services.clipboardService
    *
    * @description
    * Saves a single JS-object with a type and alias to the clipboard.
    */
    service.copy = function(type, alias, data) {

        var storage = retriveStorage();

        var shallowCloneData = Object.assign({}, data);// Notice only a shallow copy, since we dont need to deep copy. (that will happen when storing the data)
        delete shallowCloneData.key;
        delete shallowCloneData.$$hashKey;

        var key = data.key || data.$$hashKey || console.error("missing unique key for this content");

        // remove previous copies of this entry:
        storage.entries = storage.entries.filter(
            (entry) => {
                return entry.unique !== key;
            }
        );

        var entry = {unique:key, type:type, alias:alias, data:shallowCloneData};
        storage.entries.push(entry);

        if (saveStorage(storage) === true) {
            notificationsService.success("Clipboard", "Copied to clipboard.");
        } else {
            notificationsService.success("Clipboard", "Couldnt copy this data to clipboard.");
        }

    };

    /**
    * @ngdoc method
    * @name umbraco.services.supportsCopy#supported
    * @methodOf umbraco.services.clipboardService
    *
    * @description
    * Determins wether the current browser is able to performe its actions.
    */
    service.isSupported = supportsLocalStorage;

    /**
    * @ngdoc method
    * @name umbraco.services.supportsCopy#hasEntriesOfType
    * @methodOf umbraco.services.clipboardService
    *
    * @description
    * Determins wether the current clipboard has entries that matches given type and a one of the aliases.
    */
    service.hasEntriesOfType = function(type, aliases) {

        if(service.retriveEntriesOfType(type, aliases).length > 0) {
            return true;
        }

        return false;
    };

    /**
    * @ngdoc method
    * @name umbraco.services.supportsCopy#retriveEntriesOfType
    * @methodOf umbraco.services.clipboardService
    *
    * @description
    * Returns an array of entries matching the given type and one of the provided aliases.
    */
    service.retriveEntriesOfType = function(type, aliases) {

        var storage = retriveStorage();

        // Find entries that are furfilling the criterias for this nodeType and nodeTypesAliases.
        var filteretEntries = storage.entries.filter(
            (entry) => {
                return (entry.type === type && aliases.filter(alias => alias === entry.alias).length > 0);
            }
        );

        return filteretEntries;
    };

    /**
    * @ngdoc method
    * @name umbraco.services.supportsCopy#retriveEntriesOfType
    * @methodOf umbraco.services.clipboardService
    *
    * @description
    * Returns an array of data of entries matching the given type and one of the provided aliases.
    */
    service.retriveDataOfType = function(type, aliases) {
        return service.retriveEntriesOfType(type, aliases).map((x) => x.data);
    };

    /**
    * @ngdoc method
    * @name umbraco.services.supportsCopy#retriveEntriesOfType
    * @methodOf umbraco.services.clipboardService
    *
    * @description
    * Removes entries matching the given type and one of the provided aliases.
    */
    service.clearEntriesOfType = function(type, aliases) {

        var storage = retriveStorage();

        // Find entries that are NOT furfilling the criterias for this nodeType and nodeTypesAliases.
        var filteretEntries = storage.entries.filter(
            (entry) => {
                return !(entry.type === type && aliases.filter(alias => alias === entry.alias).length > 0);
            }
        );

        storage.entries = filteretEntries;

        saveStorage(storage);
    };

    return service;
}

angular.module("umbraco.services").factory("clipboardService", clipboardService);

<|endoftext|>


<commit_before>/**
 * A window for editing the short_name and long_name attributes of a BaseNode.
 * */
Ext.define('devilry_subjectadmin.view.RenameBasenodeWindow', {
    extend: 'Ext.window.Window',
    cls: 'devilry_rename_basenode_window bootstrap',
    requires: [
        'devilry_extjsextras.DjangoRestframeworkProxyErrorHandler',
        'devilry_extjsextras.form.ErrorUtils',
        'devilry_extjsextras.AlertMessageList',
        'devilry_extjsextras.CancelButton',
        'devilry_extjsextras.form.Help',
        'devilry_extjsextras.SaveButton'
    ],
    mixins: {
        'handleProxyError': 'devilry_subjectadmin.utils.DjangoRestframeworkProxyErrorMixin'
    },

    /**
     * @cfg {Object} basenodeRecord (required)
     */

    _apply_template: function(tpl, data) {
        return Ext.create('Ext.XTemplate', tpl).apply(data);
    },

    initComponent: function() {
        var title = this._apply_template(gettext('Rename {something}'), {
            something: this.basenodeRecord.get('short_name')
        });
        Ext.apply(this, {
            layout: 'fit',
            width: 430,
            height: 370,
            closable: false,
            modal: true,
            title: title,
            items: {
                xtype: 'form',
                bodyPadding: 20,
                autoScroll: true,
                border: 0,
                layout: 'anchor',
                defaults: {
                    anchor: '100%',
                },
                items: [{
                    xtype: 'alertmessagelist'
                }, {
                    name: "short_name",
                    fieldLabel: gettext('Short name'),
                    xtype: 'textfield',
                    allowBlank: false,
                    listeners: {
                        scope: this,
                        render: function(field) {
                            Ext.defer(function() {
                                field.focus();
                            }, 100);
                        }
                    }
                }, {
                    xtype: 'formhelp',
                    html: gettext("A short name with at most 20 letters. Can only contain lowercase english letters (a-z), numbers, underscore ('_') and hyphen ('-'). This is used the the regular name takes to much space."),
                    margin: {top: 5}
                }, {
                    name: "long_name",
                    fieldLabel: gettext('Long name'),
                    xtype: 'textfield',
                    allowBlank: false,
                    margin: {top: 10}
                }, {
                    xtype: 'formhelp',
                    html: gettext("May contain any characters, including language-specific characters."),
                    margin: {top: 5}
                }],
                buttons: ['->', {
                    xtype: 'cancelbutton',
                    listeners: {
                        scope: this,
                        click: function() {
                            this._close();
                        }
                    }
                }, {
                    xtype: 'savebutton',
                    formBind: true,
                    listeners: {
                        scope: this,
                        click: this._onSave
                    }
                }],
                listeners: {
                    scope: this,
                    render: this._onRenderForm
                }
            }
        });
        this.callParent(arguments);

        this.mon(this.basenodeRecord.proxy, {
            scope:this,
            exception: this._onProxyError
        });
    },

    _getForm: function() {
        return this.down('form').getForm();
    },
    _getFormPanel: function() {
        return this.down('form');
    },

    _onRenderForm: function() {
        var form = this._getForm();
        form.loadRecord(this.basenodeRecord);

        this.down('form').keyNav = Ext.create('Ext.util.KeyNav', this.down('form').el, {
            enter: this._onSave,
            scope: this
        });
    },

    _getMaskElement: function() {
        return this.down('form');
    },

    _onSave: function() {
        var form = this._getForm();
        var values = form.getValues();
        var oldShortname = this.basenodeRecord.get('short_name');
        var newShortname = values.short_name;
        if(oldShortname != newShortname) {
            var basenodeRecord = this.basenodeRecord;
            form.updateRecord(basenodeRecord);
            this._getMaskElement().setLoading(gettext('Saving ...'));
            basenodeRecord.save({
                scope: this,
                success: this._onSaveSuccess
                //failure: this._onSaveFailure
            });
        } else {
            this._close();
        }
    },

    _onProxyError: function(proxy, response, operation) {
        this._unmask();
        var alertmessagelist = this.down('alertmessagelist');
        this.handleProxyError(alertmessagelist, this._getFormPanel(), response, operation);
    },

    _unmask: function() {
        this._getMaskElement().setLoading(false);
    },

    _onSaveSuccess: function() {
        this._unmask();
        this._close();
    },

    /** We reload the page on close even when there is no changes, because we
     * do not track if the cancel button was clicked after a failed save or
     * not, and failed save leaves the record changed. */
    _close: function() {
        window.location.reload();
    }
});
<commit_msg>devilry_subjectadmin...RenameBaseNodeWindow: Fix some issues.<commit_after>/**
 * A window for editing the short_name and long_name attributes of a BaseNode.
 * */
Ext.define('devilry_subjectadmin.view.RenameBasenodeWindow', {
    extend: 'Ext.window.Window',
    cls: 'devilry_rename_basenode_window bootstrap',
    requires: [
        'devilry_extjsextras.DjangoRestframeworkProxyErrorHandler',
        'devilry_extjsextras.form.ErrorUtils',
        'devilry_extjsextras.AlertMessageList',
        'devilry_extjsextras.CancelButton',
        'devilry_extjsextras.form.Help',
        'devilry_extjsextras.SaveButton'
    ],
    mixins: {
        'handleProxyError': 'devilry_subjectadmin.utils.DjangoRestframeworkProxyErrorMixin'
    },

    /**
     * @cfg {Object} basenodeRecord (required)
     */

    _apply_template: function(tpl, data) {
        return Ext.create('Ext.XTemplate', tpl).apply(data);
    },

    initComponent: function() {
        var title = this._apply_template(gettext('Rename {something}'), {
            something: this.basenodeRecord.get('short_name')
        });
        this.originalShortname = this.basenodeRecord.get('short_name');
        this.originalLongname = this.basenodeRecord.get('long_name');
        Ext.apply(this, {
            layout: 'fit',
            width: 430,
            height: 370,
            closable: false,
            modal: true,
            title: title,
            items: {
                xtype: 'form',
                bodyPadding: 20,
                autoScroll: true,
                border: 0,
                layout: 'anchor',
                defaults: {
                    anchor: '100%',
                },
                items: [{
                    xtype: 'alertmessagelist'
                }, {
                    name: "short_name",
                    fieldLabel: gettext('Short name'),
                    xtype: 'textfield',
                    allowBlank: false,
                    listeners: {
                        scope: this,
                        render: function(field) {
                            Ext.defer(function() {
                                field.focus();
                            }, 100);
                        }
                    }
                }, {
                    xtype: 'formhelp',
                    html: gettext("A short name with at most 20 letters. Can only contain lowercase english letters (a-z), numbers, underscore ('_') and hyphen ('-'). This is used the the regular name takes to much space."),
                    margin: {top: 5}
                }, {
                    name: "long_name",
                    fieldLabel: gettext('Long name'),
                    xtype: 'textfield',
                    allowBlank: false,
                    margin: {top: 10}
                }, {
                    xtype: 'formhelp',
                    html: gettext("May contain any characters, including language-specific characters."),
                    margin: {top: 5}
                }],
                buttons: ['->', {
                    xtype: 'cancelbutton',
                    listeners: {
                        scope: this,
                        click: function() {
                            this._close();
                        }
                    }
                }, {
                    xtype: 'savebutton',
                    formBind: true,
                    listeners: {
                        scope: this,
                        click: this._onSave
                    }
                }],
                listeners: {
                    scope: this,
                    render: this._onRenderForm
                }
            }
        });
        this.callParent(arguments);

        this.mon(this.basenodeRecord.proxy, {
            scope:this,
            exception: this._onProxyError
        });
    },

    _getForm: function() {
        return this.down('form').getForm();
    },
    _getFormPanel: function() {
        return this.down('form');
    },

    _onRenderForm: function() {
        var form = this._getForm();
        form.loadRecord(this.basenodeRecord);

        this.down('form').keyNav = Ext.create('Ext.util.KeyNav', this.down('form').el, {
            enter: this._onSave,
            scope: this
        });
    },

    _getMaskElement: function() {
        return this.down('form');
    },

    _onSave: function() {
        var form = this._getForm();
        var values = form.getValues();
        var newShortname = values.short_name;
        var newLongname = values.long_name;
        if(this.originalShortname != newShortname || this.originalLongname != newLongname) {
            var basenodeRecord = this.basenodeRecord;
            form.updateRecord(basenodeRecord);
            this._getMaskElement().setLoading(gettext('Saving ...'));
            basenodeRecord.save({
                scope: this,
                success: this._onSaveSuccess
                //failure: this._onSaveFailure
            });
        } else {
            this._close();
        }
    },

    _onProxyError: function(proxy, response, operation) {
        this._unmask();
        var alertmessagelist = this.down('alertmessagelist');
        alertmessagelist.removeAll();
        this.handleProxyError(alertmessagelist, this._getFormPanel(), response, operation);
    },

    _unmask: function() {
        this._getMaskElement().setLoading(false);
    },

    _onSaveSuccess: function() {
        this._unmask();
        this._close();
    },

    /** We reload the page on close even when there is no changes, because we
     * do not track if the cancel button was clicked after a failed save or
     * not, and failed save leaves the record changed. */
    _close: function() {
        window.location.reload();
    }
});
<|endoftext|>


<commit_before>'use strict';

const { resolve } = require('path');
const { URL } = require('url');
const fetch = require('node-fetch');
const Serverless = require('serverless');
const ServerlessOffline = require('../../../../src/ServerlessOffline.js');

jest.setTimeout(30000);

describe('handler payload tests', () => {
  let serverlessOffline;

  // init
  beforeAll(async () => {
    const serverless = new Serverless();
    serverless.config.servicePath = resolve(__dirname);
    await serverless.init();
    serverlessOffline = new ServerlessOffline(serverless, {});

    return serverlessOffline.start();
  });

  // cleanup
  afterAll(async () => {
    return serverlessOffline.end();
  });

  const url = new URL('http://localhost:3000');

  // issue: https://github.com/dherault/serverless-offline/issues/756
  // PR: https://github.com/dherault/serverless-offline/pull/757
  test('Uncategorized 1', async () => {
    url.pathname = 'uncategorized-1';
    const response = await fetch(url);
    const json = await response.json();
    expect(json).toEqual({ foo: 'bar' });
  });

  // issue: https://github.com/dherault/serverless-offline/issues/758
  // PR: https://github.com/dherault/serverless-offline/pull/759
  test('Uncategorized 2', async () => {
    url.pathname = 'uncategorized-2';
    const response = await fetch(url);
    const json = await response.json();
    expect(json).toEqual({ foo: 'bar' });
  });
});
<commit_msg>Fix test description<commit_after>'use strict';

const { resolve } = require('path');
const { URL } = require('url');
const fetch = require('node-fetch');
const Serverless = require('serverless');
const ServerlessOffline = require('../../../../src/ServerlessOffline.js');

jest.setTimeout(30000);

describe('uncategorized tests', () => {
  let serverlessOffline;

  // init
  beforeAll(async () => {
    const serverless = new Serverless();
    serverless.config.servicePath = resolve(__dirname);
    await serverless.init();
    serverlessOffline = new ServerlessOffline(serverless, {});

    return serverlessOffline.start();
  });

  // cleanup
  afterAll(async () => {
    return serverlessOffline.end();
  });

  const url = new URL('http://localhost:3000');

  // issue: https://github.com/dherault/serverless-offline/issues/756
  // PR: https://github.com/dherault/serverless-offline/pull/757
  test('Uncategorized 1', async () => {
    url.pathname = 'uncategorized-1';
    const response = await fetch(url);
    const json = await response.json();
    expect(json).toEqual({ foo: 'bar' });
  });

  // issue: https://github.com/dherault/serverless-offline/issues/758
  // PR: https://github.com/dherault/serverless-offline/pull/759
  test('Uncategorized 2', async () => {
    url.pathname = 'uncategorized-2';
    const response = await fetch(url);
    const json = await response.json();
    expect(json).toEqual({ foo: 'bar' });
  });
});
<|endoftext|>


<commit_before>'use strict';

var Funnel = require('broccoli-funnel');
var flatten = require('broccoli-flatten');
var htmlReplace = require('./html-replace');
var mergeTrees = require('broccoli-merge-trees');
var path = require('path');
var renderLodashTemplate = require('broccoli-lodash');
var replace = require('broccoli-replace');
var stew = require('broccoli-stew');
var ts2dart;
var TraceurCompiler;
var TypescriptCompiler;

var projectRootDir = path.normalize(path.join(__dirname, '..', '..'));

module.exports = function makeBroccoliTree(name) {
  if (!TraceurCompiler) TraceurCompiler = require('../../dist/broccoli/traceur');
  if (!TypescriptCompiler) TypescriptCompiler = require('../../dist/broccoli/typescript');
  if (!ts2dart) ts2dart = require('../../dist/broccoli/broccoli-ts2dart');

  switch (name) {
    case 'dev': return makeBrowserTree({name: name, typeAssertions: true});
    case 'prod': return makeBrowserTree({name: name, typeAssertions: false});
    case 'cjs': return makeCjsTree();
    case 'dart': return makeDartTree();
    default: throw new Error('Unknown build type: ' + name);
  }
};

function makeBrowserTree(options) {
  var modulesTree = new Funnel('modules', {
    include: ['**/**'],
    exclude: ['**/*.cjs', 'benchmarks/e2e_test/**'],
    destDir: '/'
  });

  // Use Traceur to transpile original sources to ES6
  var es6Tree = new TraceurCompiler(modulesTree, '.es6', '.map', {
    sourceMaps: true,
    annotations: true,      // parse annotations
    types: true,            // parse types
    script: false,          // parse as a module
    memberVariables: true,  // parse class fields
    modules: 'instantiate',
    typeAssertionModule: 'rtts_assert/rtts_assert',
    typeAssertions: options.typeAssertions,
    outputLanguage: 'es6'
  });

  // Call Traceur again to lower the ES6 build tree to ES5
  var es5Tree = new TraceurCompiler(es6Tree, '.js',  '.js.map', {modules: 'instantiate', sourceMaps: true});

  // Now we add a few more files to the es6 tree that Traceur should not see
  ['angular2', 'rtts_assert'].forEach(
    function (destDir) {
      var extras = new Funnel('tools/build', {files: ['es5build.js'], destDir: destDir});
      es6Tree = mergeTrees([es6Tree, extras]);
    });

  var vendorScriptsTree = flatten(new Funnel('.', {
    files: [
      'node_modules/es6-module-loader/dist/es6-module-loader-sans-promises.src.js',
      'node_modules/zone.js/zone.js',
      'node_modules/zone.js/long-stack-trace-zone.js',
      'node_modules/systemjs/dist/system.src.js',
      'node_modules/systemjs/lib/extension-register.js',
      'node_modules/systemjs/lib/extension-cjs.js',
      'node_modules/rx/dist/rx.all.js',
      'tools/build/snippets/runtime_paths.js',
      path.relative(projectRootDir, TraceurCompiler.RUNTIME_PATH)
    ]
  }));
  var vendorScripts_benchmark =
    new Funnel('tools/build/snippets', {files: ['url_params_to_form.js'], destDir: '/'});
  var vendorScripts_benchmarks_external =
    new Funnel('node_modules/angular', {files: ['angular.js'], destDir: '/'});

  var servingTrees = [];

  function copyVendorScriptsTo(destDir) {
    servingTrees.push(new Funnel(vendorScriptsTree, {srcDir: '/', destDir: destDir}));
    if (destDir.indexOf('benchmarks') > -1) {
      servingTrees.push(new Funnel(vendorScripts_benchmark, {srcDir: '/', destDir: destDir}));
    }
    if (destDir.indexOf('benchmarks_external') > -1) {
      servingTrees.push(
        new Funnel(vendorScripts_benchmarks_external, {srcDir: '/', destDir: destDir}));
    }
  }

  function writeScriptsForPath(relativePath, result) {
    copyVendorScriptsTo(path.dirname(relativePath));
    return result.replace('@@FILENAME_NO_EXT', relativePath.replace(/\.\w+$/, ''));
  }

  var htmlTree = new Funnel(modulesTree, {include: ['*/src/**/*.html'], destDir: '/'});
  htmlTree = replace(htmlTree, {
    files: ['examples*/**'],
    patterns: [{match: /\$SCRIPTS\$/, replacement: htmlReplace('SCRIPTS')}],
    replaceWithPath: writeScriptsForPath
  });
  htmlTree = replace(htmlTree, {
    files: ['benchmarks/**'],
    patterns: [{match: /\$SCRIPTS\$/, replacement: htmlReplace('SCRIPTS_benchmarks')}],
    replaceWithPath: writeScriptsForPath
  });
  htmlTree = replace(htmlTree, {
    files: ['benchmarks_external/**'],
    patterns: [{match: /\$SCRIPTS\$/, replacement: htmlReplace('SCRIPTS_benchmarks_external')}],
    replaceWithPath: writeScriptsForPath
  });

  // Copy all vendor scripts into all examples and benchmarks
  ['benchmarks/src', 'benchmarks_external/src', 'examples/src/benchpress'].forEach(
    copyVendorScriptsTo);

  var scripts = mergeTrees(servingTrees, {overwrite: true});
  var css = new Funnel(modulesTree, {include: ["**/*.css"]});
  var polymerFiles = new Funnel('.', {
    files: [
      'bower_components/polymer/lib/polymer.html',
      'tools/build/snippets/url_params_to_form.js'
    ]
  });
  var polymer = stew.mv(flatten(polymerFiles), 'benchmarks_external/src/tree/polymer');
  htmlTree = mergeTrees([htmlTree, scripts, polymer, css]);

  es5Tree = mergeTrees([es5Tree, htmlTree]);

  return mergeTrees([
    stew.mv(es6Tree, 'js/' + options.name + '/es6'),
    stew.mv(es5Tree, 'js/' + options.name + '/es5')
  ]);
}

function makeCjsTree() {
  // list of npm packages that this build will create
  var outputPackages = ['angular2', 'benchpress', 'rtts_assert'];

  var modulesTree = new Funnel('modules', {
    include: ['angular2/**', 'benchpress/**', 'rtts_assert/**', '**/e2e_test/**'],
    exclude: ['angular2/src/core/zone/vm_turn_zone.es6']
  });

  // Use Traceur to transpile original sources to ES6
  var traceurOpts = {
    sourceMaps: true,
    annotations: true,      // parse annotations
    types: true,            // parse types
    script: false,          // parse as a module
    memberVariables: true,  // parse class fields
    typeAssertionModule: 'rtts_assert/rtts_assert',
    // Don't use type assertions since this is partly transpiled by typescript
    typeAssertions: false,
    modules: 'commonjs'
  }

  var cjsTree = new TraceurCompiler(modulesTree, '.js', '.map', traceurOpts);

  // Now we add the LICENSE file into all the folders that will become npm packages
  outputPackages.forEach(
    function(destDir) {
      var license = new Funnel('.', {files: ['LICENSE'], destDir: destDir});
      cjsTree = mergeTrees([cjsTree, license]);
    });

  // Get all docs and related assets and prepare them for js build
  var docs = new Funnel(modulesTree, {include: ['**/*.md', '**/*.png'], exclude: ['**/*.dart.md']});
  docs = stew.rename(docs, 'README.js.md', 'README.md');

  // Generate shared package.json info
  var BASE_PACKAGE_JSON = require(path.join(projectRootDir, 'package.json'));
  var COMMON_PACKAGE_JSON = {
    version: BASE_PACKAGE_JSON.version,
    homepage: BASE_PACKAGE_JSON.homepage,
    bugs: BASE_PACKAGE_JSON.bugs,
    license: BASE_PACKAGE_JSON.license,
    contributors: BASE_PACKAGE_JSON.contributors,
    dependencies: BASE_PACKAGE_JSON.dependencies,
    devDependencies: {
      "yargs": BASE_PACKAGE_JSON.devDependencies['yargs'],
      "gulp-sourcemaps": BASE_PACKAGE_JSON.devDependencies['gulp-sourcemaps'],
      "gulp-traceur": BASE_PACKAGE_JSON.devDependencies['gulp-traceur'],
      "gulp": BASE_PACKAGE_JSON.devDependencies['gulp'],
      "gulp-rename": BASE_PACKAGE_JSON.devDependencies['gulp-rename'],
      "through2": BASE_PACKAGE_JSON.devDependencies['through2']
    }
  };

  // Add a .template extension since renderLodashTemplate strips one extension
  var packageJsons = stew.rename(new Funnel(modulesTree, {include: ['**/package.json']}), '.json', '.json.template');
  packageJsons = renderLodashTemplate(packageJsons, {
    files: ["**/**"],
    context: { 'packageJson': COMMON_PACKAGE_JSON }
  });

  var typescriptTree = new TypescriptCompiler(modulesTree, {
    target: 'ES5',
    sourceMap: true,
    mapRoot: '', /* force sourcemaps to use relative path */
    module: /*system.js*/ 'commonjs',
    allowNonTsExtensions: false,
    typescript: require('typescript'),
    // declarationFiles: true,
    noEmitOnError: true,
    outDir: 'angular2'
  });

  // For now, we just overwrite the Traceur-compiled files with their Typescript equivalent
  cjsTree = mergeTrees([cjsTree, typescriptTree], { overwrite: true });
  cjsTree = mergeTrees([cjsTree, docs, packageJsons]);

  return stew.mv(cjsTree, 'js/cjs');
}

function makeDartTree() {
  // Transpile everything in 'modules'...
  var modulesTree = new Funnel('modules', {
    include: ['**/*.js', '**/*.ts', '**/*.dart'],  // .dart file available means don't translate.
    exclude: ['rtts_assert/**/*'],  // ... except for the rtts_asserts (don't apply to Dart).
    destDir: '/'                    // Remove the 'modules' prefix.
  });

  // Transpile to dart.
  var dartTree = ts2dart.transpile(modulesTree);

  // Move around files to match Dart's layout expectations.
  dartTree = stew.rename(dartTree, function(relativePath) {
    // If a file matches the `pattern`, insert the given `insertion` as the second path part.
    var replacements = [
      {pattern: /^benchmarks\/test\//, insertion: ''},
      {pattern: /^benchmarks\//, insertion: 'web'},
      {pattern: /^benchmarks_external\/test\//, insertion: ''},
      {pattern: /^benchmarks_external\//, insertion: 'web'},
      {pattern: /^example.?\//, insertion: 'web/'},
      {pattern: /^example.?\/test\//, insertion: ''},
      {pattern: /^[^\/]*\/test\//, insertion: ''},
      {pattern: /^./, insertion: 'lib'},  // catch all.
    ];

    for (var i = 0; i < replacements.length; i++) {
      var repl = replacements[i];
      if (relativePath.match(repl.pattern)) {
        var parts = relativePath.split('/');
        parts.splice(1, 0, repl.insertion);
        return path.join.apply(path, parts);
      }
    }
    throw new Error('Failed to match any path', relativePath);
  });

  // Move the tree under the 'dart' folder.
  return stew.mv(dartTree, 'dart');
}
<commit_msg>chore(build): inline Traceur options just like we do everywhere<commit_after>'use strict';

var Funnel = require('broccoli-funnel');
var flatten = require('broccoli-flatten');
var htmlReplace = require('./html-replace');
var mergeTrees = require('broccoli-merge-trees');
var path = require('path');
var renderLodashTemplate = require('broccoli-lodash');
var replace = require('broccoli-replace');
var stew = require('broccoli-stew');
var ts2dart;
var TraceurCompiler;
var TypescriptCompiler;

var projectRootDir = path.normalize(path.join(__dirname, '..', '..'));

module.exports = function makeBroccoliTree(name) {
  if (!TraceurCompiler) TraceurCompiler = require('../../dist/broccoli/traceur');
  if (!TypescriptCompiler) TypescriptCompiler = require('../../dist/broccoli/typescript');
  if (!ts2dart) ts2dart = require('../../dist/broccoli/broccoli-ts2dart');

  switch (name) {
    case 'dev': return makeBrowserTree({name: name, typeAssertions: true});
    case 'prod': return makeBrowserTree({name: name, typeAssertions: false});
    case 'cjs': return makeCjsTree();
    case 'dart': return makeDartTree();
    default: throw new Error('Unknown build type: ' + name);
  }
};

function makeBrowserTree(options) {
  var modulesTree = new Funnel('modules', {
    include: ['**/**'],
    exclude: ['**/*.cjs', 'benchmarks/e2e_test/**'],
    destDir: '/'
  });

  // Use Traceur to transpile original sources to ES6
  var es6Tree = new TraceurCompiler(modulesTree, '.es6', '.map', {
    sourceMaps: true,
    annotations: true,      // parse annotations
    types: true,            // parse types
    script: false,          // parse as a module
    memberVariables: true,  // parse class fields
    modules: 'instantiate',
    typeAssertionModule: 'rtts_assert/rtts_assert',
    typeAssertions: options.typeAssertions,
    outputLanguage: 'es6'
  });

  // Call Traceur again to lower the ES6 build tree to ES5
  var es5Tree = new TraceurCompiler(es6Tree, '.js',  '.js.map', {modules: 'instantiate', sourceMaps: true});

  // Now we add a few more files to the es6 tree that Traceur should not see
  ['angular2', 'rtts_assert'].forEach(
    function (destDir) {
      var extras = new Funnel('tools/build', {files: ['es5build.js'], destDir: destDir});
      es6Tree = mergeTrees([es6Tree, extras]);
    });

  var vendorScriptsTree = flatten(new Funnel('.', {
    files: [
      'node_modules/es6-module-loader/dist/es6-module-loader-sans-promises.src.js',
      'node_modules/zone.js/zone.js',
      'node_modules/zone.js/long-stack-trace-zone.js',
      'node_modules/systemjs/dist/system.src.js',
      'node_modules/systemjs/lib/extension-register.js',
      'node_modules/systemjs/lib/extension-cjs.js',
      'node_modules/rx/dist/rx.all.js',
      'tools/build/snippets/runtime_paths.js',
      path.relative(projectRootDir, TraceurCompiler.RUNTIME_PATH)
    ]
  }));
  var vendorScripts_benchmark =
    new Funnel('tools/build/snippets', {files: ['url_params_to_form.js'], destDir: '/'});
  var vendorScripts_benchmarks_external =
    new Funnel('node_modules/angular', {files: ['angular.js'], destDir: '/'});

  var servingTrees = [];

  function copyVendorScriptsTo(destDir) {
    servingTrees.push(new Funnel(vendorScriptsTree, {srcDir: '/', destDir: destDir}));
    if (destDir.indexOf('benchmarks') > -1) {
      servingTrees.push(new Funnel(vendorScripts_benchmark, {srcDir: '/', destDir: destDir}));
    }
    if (destDir.indexOf('benchmarks_external') > -1) {
      servingTrees.push(
        new Funnel(vendorScripts_benchmarks_external, {srcDir: '/', destDir: destDir}));
    }
  }

  function writeScriptsForPath(relativePath, result) {
    copyVendorScriptsTo(path.dirname(relativePath));
    return result.replace('@@FILENAME_NO_EXT', relativePath.replace(/\.\w+$/, ''));
  }

  var htmlTree = new Funnel(modulesTree, {include: ['*/src/**/*.html'], destDir: '/'});
  htmlTree = replace(htmlTree, {
    files: ['examples*/**'],
    patterns: [{match: /\$SCRIPTS\$/, replacement: htmlReplace('SCRIPTS')}],
    replaceWithPath: writeScriptsForPath
  });
  htmlTree = replace(htmlTree, {
    files: ['benchmarks/**'],
    patterns: [{match: /\$SCRIPTS\$/, replacement: htmlReplace('SCRIPTS_benchmarks')}],
    replaceWithPath: writeScriptsForPath
  });
  htmlTree = replace(htmlTree, {
    files: ['benchmarks_external/**'],
    patterns: [{match: /\$SCRIPTS\$/, replacement: htmlReplace('SCRIPTS_benchmarks_external')}],
    replaceWithPath: writeScriptsForPath
  });

  // Copy all vendor scripts into all examples and benchmarks
  ['benchmarks/src', 'benchmarks_external/src', 'examples/src/benchpress'].forEach(
    copyVendorScriptsTo);

  var scripts = mergeTrees(servingTrees, {overwrite: true});
  var css = new Funnel(modulesTree, {include: ["**/*.css"]});
  var polymerFiles = new Funnel('.', {
    files: [
      'bower_components/polymer/lib/polymer.html',
      'tools/build/snippets/url_params_to_form.js'
    ]
  });
  var polymer = stew.mv(flatten(polymerFiles), 'benchmarks_external/src/tree/polymer');
  htmlTree = mergeTrees([htmlTree, scripts, polymer, css]);

  es5Tree = mergeTrees([es5Tree, htmlTree]);

  return mergeTrees([
    stew.mv(es6Tree, 'js/' + options.name + '/es6'),
    stew.mv(es5Tree, 'js/' + options.name + '/es5')
  ]);
}

function makeCjsTree() {
  // list of npm packages that this build will create
  var outputPackages = ['angular2', 'benchpress', 'rtts_assert'];

  var modulesTree = new Funnel('modules', {
    include: ['angular2/**', 'benchpress/**', 'rtts_assert/**', '**/e2e_test/**'],
    exclude: ['angular2/src/core/zone/vm_turn_zone.es6']
  });

  var cjsTree = new TraceurCompiler(modulesTree, '.js', '.map', {
    sourceMaps: true,
    annotations: true,      // parse annotations
    types: true,            // parse types
    script: false,          // parse as a module
    memberVariables: true,  // parse class fields
    typeAssertionModule: 'rtts_assert/rtts_assert',
    // Don't use type assertions since this is partly transpiled by typescript
    typeAssertions: false,
    modules: 'commonjs'
  });

  // Now we add the LICENSE file into all the folders that will become npm packages
  outputPackages.forEach(
    function(destDir) {
      var license = new Funnel('.', {files: ['LICENSE'], destDir: destDir});
      cjsTree = mergeTrees([cjsTree, license]);
    });

  // Get all docs and related assets and prepare them for js build
  var docs = new Funnel(modulesTree, {include: ['**/*.md', '**/*.png'], exclude: ['**/*.dart.md']});
  docs = stew.rename(docs, 'README.js.md', 'README.md');

  // Generate shared package.json info
  var BASE_PACKAGE_JSON = require(path.join(projectRootDir, 'package.json'));
  var COMMON_PACKAGE_JSON = {
    version: BASE_PACKAGE_JSON.version,
    homepage: BASE_PACKAGE_JSON.homepage,
    bugs: BASE_PACKAGE_JSON.bugs,
    license: BASE_PACKAGE_JSON.license,
    contributors: BASE_PACKAGE_JSON.contributors,
    dependencies: BASE_PACKAGE_JSON.dependencies,
    devDependencies: {
      "yargs": BASE_PACKAGE_JSON.devDependencies['yargs'],
      "gulp-sourcemaps": BASE_PACKAGE_JSON.devDependencies['gulp-sourcemaps'],
      "gulp-traceur": BASE_PACKAGE_JSON.devDependencies['gulp-traceur'],
      "gulp": BASE_PACKAGE_JSON.devDependencies['gulp'],
      "gulp-rename": BASE_PACKAGE_JSON.devDependencies['gulp-rename'],
      "through2": BASE_PACKAGE_JSON.devDependencies['through2']
    }
  };

  // Add a .template extension since renderLodashTemplate strips one extension
  var packageJsons = stew.rename(new Funnel(modulesTree, {include: ['**/package.json']}), '.json', '.json.template');
  packageJsons = renderLodashTemplate(packageJsons, {
    files: ["**/**"],
    context: { 'packageJson': COMMON_PACKAGE_JSON }
  });

  var typescriptTree = new TypescriptCompiler(modulesTree, {
    target: 'ES5',
    sourceMap: true,
    mapRoot: '', /* force sourcemaps to use relative path */
    module: /*system.js*/ 'commonjs',
    allowNonTsExtensions: false,
    typescript: require('typescript'),
    // declarationFiles: true,
    noEmitOnError: true,
    outDir: 'angular2'
  });

  // For now, we just overwrite the Traceur-compiled files with their Typescript equivalent
  cjsTree = mergeTrees([cjsTree, typescriptTree], { overwrite: true });
  cjsTree = mergeTrees([cjsTree, docs, packageJsons]);

  return stew.mv(cjsTree, 'js/cjs');
}

function makeDartTree() {
  // Transpile everything in 'modules'...
  var modulesTree = new Funnel('modules', {
    include: ['**/*.js', '**/*.ts', '**/*.dart'],  // .dart file available means don't translate.
    exclude: ['rtts_assert/**/*'],  // ... except for the rtts_asserts (don't apply to Dart).
    destDir: '/'                    // Remove the 'modules' prefix.
  });

  // Transpile to dart.
  var dartTree = ts2dart.transpile(modulesTree);

  // Move around files to match Dart's layout expectations.
  dartTree = stew.rename(dartTree, function(relativePath) {
    // If a file matches the `pattern`, insert the given `insertion` as the second path part.
    var replacements = [
      {pattern: /^benchmarks\/test\//, insertion: ''},
      {pattern: /^benchmarks\//, insertion: 'web'},
      {pattern: /^benchmarks_external\/test\//, insertion: ''},
      {pattern: /^benchmarks_external\//, insertion: 'web'},
      {pattern: /^example.?\//, insertion: 'web/'},
      {pattern: /^example.?\/test\//, insertion: ''},
      {pattern: /^[^\/]*\/test\//, insertion: ''},
      {pattern: /^./, insertion: 'lib'},  // catch all.
    ];

    for (var i = 0; i < replacements.length; i++) {
      var repl = replacements[i];
      if (relativePath.match(repl.pattern)) {
        var parts = relativePath.split('/');
        parts.splice(1, 0, repl.insertion);
        return path.join.apply(path, parts);
      }
    }
    throw new Error('Failed to match any path', relativePath);
  });

  // Move the tree under the 'dart' folder.
  return stew.mv(dartTree, 'dart');
}
<|endoftext|>


<commit_before>/*!
 * modernizr v3.3.1
 * Build https://modernizr.com/download?-setclasses-dontmin
 *
 * Copyright (c)
 *  Faruk Ates
 *  Paul Irish
 *  Alex Sexton
 *  Ryan Seddon
 *  Patrick Kettner
 *  Stu Cox
 *  Richard Herrera

 * MIT License
 */

/*
 * Modernizr tests which native CSS3 and HTML5 features are available in the
 * current UA and makes the results available to you in two ways: as properties on
 * a global `Modernizr` object, and as classes on the `<html>` element. This
 * information allows you to progressively enhance your pages with a granular level
 * of control over the experience.
*/

;(function(window, document, undefined){
  var tests = [];

  /**
   *
   * ModernizrProto is the constructor for Modernizr
   *
   * @class
   * @access public
   */

  var ModernizrProto = {
    // The current version, dummy
    _version: '3.3.1',

    // Any settings that don't work as separate modules
    // can go in here as configuration.
    _config: {
      'classPrefix': '',
      'enableClasses': true,
      'enableJSClass': true,
      'usePrefixes': true
    },

    // Queue of tests
    _q: [],

    // Stub these for people who are listening
    on: function(test, cb) {
      // I don't really think people should do this, but we can
      // safe guard it a bit.
      // -- NOTE:: this gets WAY overridden in src/addTest for actual async tests.
      // This is in case people listen to synchronous tests. I would leave it out,
      // but the code to *disallow* sync tests in the real version of this
      // function is actually larger than this.
      var self = this;
      setTimeout(function() {
        cb(self[test]);
      }, 0);
    },

    addTest: function(name, fn, options) {
      tests.push({name: name, fn: fn, options: options});
    },

    addAsyncTest: function(fn) {
      tests.push({name: null, fn: fn});
    }
  };

  // Fake some of Object.create so we can force non test results to be non "own" properties.
  var Modernizr = function() {};
  Modernizr.prototype = ModernizrProto;

  // Leak modernizr globally when you `require` it rather than force it here.
  // Overwrite name so constructor name is nicer :D
  Modernizr = new Modernizr();

  var classes = [];

  /**
   * is returns a boolean if the typeof an obj is exactly type.
   *
   * @access private
   * @function is
   * @param {*} obj - A thing we want to check the type of
   * @param {string} type - A string to compare the typeof against
   * @returns {boolean}
   */

  function is(obj, type) {
    return typeof obj === type;
  }
  ;

  /**
   * Run through all tests and detect their support in the current UA.
   *
   * @access private
   */

  function testRunner() {
    var featureNames;
    var feature;
    var aliasIdx;
    var result;
    var nameIdx;
    var featureName;
    var featureNameSplit;

    for (var featureIdx in tests) {
      if (tests.hasOwnProperty(featureIdx)) {
        featureNames = [];
        feature = tests[featureIdx];
        // run the test, throw the return value into the Modernizr,
        // then based on that boolean, define an appropriate className
        // and push it into an array of classes we'll join later.
        //
        // If there is no name, it's an 'async' test that is run,
        // but not directly added to the object. That should
        // be done with a post-run addTest call.
        if (feature.name) {
          featureNames.push(feature.name.toLowerCase());

          if (feature.options && feature.options.aliases && feature.options.aliases.length) {
            // Add all the aliases into the names list
            for (aliasIdx = 0; aliasIdx < feature.options.aliases.length; aliasIdx++) {
              featureNames.push(feature.options.aliases[aliasIdx].toLowerCase());
            }
          }
        }

        // Run the test, or use the raw value if it's not a function
        result = is(feature.fn, 'function') ? feature.fn() : feature.fn;

        // Set each of the names on the Modernizr object
        for (nameIdx = 0; nameIdx < featureNames.length; nameIdx++) {
          featureName = featureNames[nameIdx];
          // Support dot properties as sub tests. We don't do checking to make sure
          // that the implied parent tests have been added. You must call them in
          // order (either in the test, or make the parent test a dependency).
          //
          // Cap it to TWO to make the logic simple and because who needs that kind of subtesting
          // hashtag famous last words
          featureNameSplit = featureName.split('.');

          if (featureNameSplit.length === 1) {
            Modernizr[featureNameSplit[0]] = result;
          } else {
            // cast to a Boolean, if not one already
            if (Modernizr[featureNameSplit[0]] && !(Modernizr[featureNameSplit[0]] instanceof Boolean)) {
              Modernizr[featureNameSplit[0]] = new Boolean(Modernizr[featureNameSplit[0]]);
            }

            Modernizr[featureNameSplit[0]][featureNameSplit[1]] = result;
          }

          classes.push((result ? '' : 'no-') + featureNameSplit.join('-'));
        }
      }
    }
  }
  ;

  /**
   * docElement is a convenience wrapper to grab the root element of the document
   *
   * @access private
   * @returns {HTMLElement|SVGElement} The root element of the document
   */

  var docElement = document.documentElement;

  /**
   * A convenience helper to check if the document we are running in is an SVG document
   *
   * @access private
   * @returns {boolean}
   */

  var isSVG = docElement.nodeName.toLowerCase() === 'svg';

  /**
   * setClasses takes an array of class names and adds them to the root element
   *
   * @access private
   * @function setClasses
   * @param {string[]} classes - Array of class names
   */

  // Pass in an and array of class names, e.g.:
  //  ['no-webp', 'borderradius', ...]
  function setClasses(classes) {
    var className = docElement.className;
    var classPrefix = Modernizr._config.classPrefix || '';

    if (isSVG) {
      className = className.baseVal;
    }

    // Change `no-js` to `js` (independently of the `enableClasses` option)
    // Handle classPrefix on this too
    if (Modernizr._config.enableJSClass) {
      var reJS = new RegExp('(^|\\s)' + classPrefix + 'no-js(\\s|$)');
      className = className.replace(reJS, '$1' + classPrefix + 'js$2');
    }

    if (Modernizr._config.enableClasses) {
      // Add the new classes
      className += ' ' + classPrefix + classes.join(' ' + classPrefix);
      if (isSVG) {
        docElement.className.baseVal = className;
      } else {
        docElement.className = className;
      }
    }

  }

  ;

  // Run each test
  testRunner();

  // Remove the "no-js" class if it exists
  setClasses(classes);

  delete ModernizrProto.addTest;
  delete ModernizrProto.addAsyncTest;

  // Run the things that are supposed to run after the tests
  for (var i = 0; i < Modernizr._q.length; i++) {
    Modernizr._q[i]();
  }

  // Leak Modernizr namespace
  window.Modernizr = Modernizr;

;

})(window, document);<commit_msg>remove accidently commited file<commit_after><|endoftext|>


<commit_before>idrinth.tier = {
    list: { },
    addTagged: function ( name ) {
        if ( !name || !this.list.hasOwnProperty ( name ) || typeof this.list[name] === 'function' || document.getElementById ( 'idrinth-tier-box-' + name ) ) {
            return;
        }
        var boss = this.list[name];
        var make = function ( x, name ) {
            var makeElement = function ( label, number, description ) {
                return {
                    content: label + ' ' + idrinth.ui.formatNumber ( number ),
                    attributes: [ {
                            name: 'title',
                            value: description
                        } ]
                };
            };
            var info = [
                makeElement ( 'FS', boss.fs.nm, 'Fair share' ),
                makeElement ( 'AP', boss.ap, 'Achievement point damage' )
            ];
            if ( boss.os && boss.os.nm ) {
                info.push ( makeElement ( 'OS', boss.os.nm, 'Optimal share' ) );
                info.unshift ( makeElement ( 'MA', boss.nm[boss.nm.length - 1], 'Maximum/highest tier' ) );
                info.unshift ( makeElement ( 'MI', boss.nm[0], 'Minimum/lowest tier' ) );
            }
            info.unshift (
                    {
                        type: 'strong',
                        content: boss.name.replace ( /\(.*$/, '' )
                    } );
            this.taggedSlots[x] = idrinth.ui.buildElement (
                    {
                        id: 'idrinth-tier-box-' + name,
                        css: 'idrinth-hovering-box idrinth-tier-box',
                        children: [ {
                                children: info
                            } ],
                        attributes: [
                            {
                                name: 'title',
                                value: 'click to close'
                            },
                            {
                                name: 'onclick',
                                value: 'idrinth.ui.removeElement(this.id);idrinth.tier.taggedSlots[\'' + x + '\']=null;'
                            },
                            {
                                name: 'style',
                                value: 'left:' + x + 'px;background-image: url(https://dotd.idrinth.de/static/raid-image-service/' + this.list[name].url + '/);'
                            }
                        ]
                    }
            );
            idrinth.ui.body.appendChild ( this.taggedSlots[x] );
        };
        for (var key in this.taggedSlots) {
            if ( this.taggedSlots.hasOwnProperty ( key ) && typeof key !== 'function' && this.taggedSlots[key] === null ) {
                return make ( key, name );
            }
        }
        idrinth.alert ( 'There is no space for another tier-box at the moment, please close one first.' );
    },
    taggedSlots: { },
    start: function () {
        'use strict';
        var pos = 1;
        while ( 0 < window.innerWidth - 140 * ( pos + 2 ) ) {
            this.taggedSlots[( pos * 140 ).toString ()] = null;
            pos++;
        }
        idrinth.runAjax (
                'https://dotd.idrinth.de/' + idrinth.platform + '/tier-service/',
                function ( text ) {
                    idrinth.tier.import ( text );
                },
                function ( ) {
                    window.setTimeout ( idrinth.tier.start, 10000 );
                },
                function ( ) {
                    window.setTimeout ( idrinth.tier.start, 10000 );
                }
        );
    },
    import: function ( data ) {
        'use strict';
        data = JSON.parse ( data );
        if ( data ) {
            idrinth.tier.list = data;
        } else {
            window.setTimeout ( idrinth.tier.start, 1000 );
        }
    },
    getTierForName: function ( name ) {
        var clearInnerHtml = function ( elem ) {
            elem.innerHTML = '';
        };

        var makeList = function ( list ) {
            var makeField = function ( listKey, difficulty, ic ) {
                var ln = {
                    type: 'td'
                };
                try {
                    ln.styles = idrinth.tier.list[listKey].os[difficulty] === idrinth.tier[listKey][difficulty][ic] ? 'is-os' : '';
                } catch ( E ) {
                    idrinth.log ( E.toString ( ) );
                }
                try {
                    ln.content = idrinth.ui.formatNumber ( idrinth.tier.list[listKey][difficulty][ic] ) + ' ' +
                            idrinth.tier.list[listKey].epics[difficulty][ic] + 'E';
                } catch ( E2 ) {
                    idrinth.log ( E2.toString ( ) );
                    try {
                        ln.content = idrinth.ui.formatNumber ( idrinth.tier.list[listKey][difficulty][ic] );
                    } catch ( E3 ) {
                        idrinth.log ( E3.toString ( ) );
                    }
                }
                return ln;
            };
            var makeRow = function ( title, dataset ) {
                return {
                    type: 'tr',
                    children: [
                        {
                            type: 'th',
                            content: title
                        },
                        {
                            type: 'td',
                            content: idrinth.ui.formatNumber ( dataset.n )
                        },
                        {
                            type: 'td',
                            content: idrinth.ui.formatNumber ( dataset.h )
                        },
                        {
                            type: 'td',
                            content: idrinth.ui.formatNumber ( dataset.l )
                        },
                        {
                            type: 'td',
                            content: idrinth.ui.formatNumber ( dataset.nm )
                        }
                    ]
                };
            };
            var wrapper = document.getElementById ( 'idrinth-tierlist' );
            clearInnerHtml ( wrapper );
            for (var count = list.length - 1; count >= 0; count--) {
                var sub = idrinth.ui.buildElement ( {
                    css: 'tier-wrapper',
                    children: [
                        {
                            type: 'img',
                            attributes: [ {
                                    name: 'src',
                                    value: 'https://dotd.idrinth.de/static/raid-image-service/' + idrinth.tier.list[list[count]].url + '/'
                                } ]
                        },
                        {
                            type: 'strong',
                            content: idrinth.tier.list[list[count]].name
                        },
                        {
                            type: 'button',
                            content: 'Tag to screen-top',
                            attributes: [
                                {
                                    name: 'onclick',
                                    value: 'idrinth.tier.addTagged(\'' + list[count].replace ( /'/g, '\\\'' ) + '\');'
                                },
                                {
                                    name: 'type',
                                    value: 'action'
                                }
                            ]
                        },
                        {
                            type: 'span',
                            content: 'AP: ' + idrinth.ui.formatNumber ( idrinth.tier.list[list[count]].ap )
                        },
                        {
                            type: 'table',
                            children: [
                                {
                                    type: 'thead',
                                    children: [
                                        {
                                            type: 'tr',
                                            children: [
                                                {
                                                    type: 'th',
                                                    content: '#'
                                                },
                                                {
                                                    type: 'th',
                                                    content: 'Normal'
                                                },
                                                {
                                                    type: 'th',
                                                    content: 'Hard'
                                                },
                                                {
                                                    type: 'th',
                                                    content: 'Legend'
                                                },
                                                {
                                                    type: 'th',
                                                    content: 'Nightmare'
                                                }
                                            ]
                                        }
                                    ]
                                },
                                {
                                    type: 'tbody',
                                    children: [
                                        makeRow ( 'FS', idrinth.tier.list[list[count]].fs ),
                                        makeRow ( 'OS', idrinth.tier.list[list[count]].os ),
                                        makeRow ( '', {
                                            n: '',
                                            l: '',
                                            h: '',
                                            nm: ''
                                        } )
                                    ]
                                }
                            ]
                        }
                    ]
                } );
                var maxTiers = Math.max ( idrinth.tier.list[list[count]].n.length, idrinth.tier.list[list[count]].h.length, idrinth.tier.list[list[count]].l.length, idrinth.tier.list[list[count]].nm.length );
                for (var ic = 0; ic < maxTiers; ic++) {
                    sub.lastChild.lastChild.appendChild ( idrinth.ui.buildElement ( {
                        type: 'tr',
                        children: [
                            {
                                type: 'th',
                                content: ic + 1
                            },
                            makeField ( list[count], 'n', ic ),
                            makeField ( list[count], 'h', ic ),
                            makeField ( list[count], 'l', ic ),
                            makeField ( list[count], 'nm', ic )
                        ]
                    } ) );
                }
                wrapper.appendChild ( sub );
            }
        };
        if ( !name || name.length === 0 ) {
            clearInnerHtml ( document.getElementById ( 'idrinth-tierlist' ) );
            return;
        }
        var result = [ ];
        var regExp = new RegExp ( name, 'i' );
        for (var key in idrinth.tier.list) {
            if ( key.match ( regExp ) ) {
                result.push ( key );
            }
        }
        makeList ( result );
    }
};<commit_msg>fixing scope-issues of this<commit_after>idrinth.tier = {
    list: { },
    addTagged: function ( name ) {
        if ( !name || !this.list.hasOwnProperty ( name ) || typeof this.list[name] === 'function' || document.getElementById ( 'idrinth-tier-box-' + name ) ) {
            return;
        }
        var boss = this.list[name];
        var make = function ( x, name ) {
            var makeElement = function ( label, number, description ) {
                return {
                    content: label + ' ' + idrinth.ui.formatNumber ( number ),
                    attributes: [ {
                            name: 'title',
                            value: description
                        } ]
                };
            };
            var info = [
                makeElement ( 'FS', boss.fs.nm, 'Fair share' ),
                makeElement ( 'AP', boss.ap, 'Achievement point damage' )
            ];
            if ( boss.os && boss.os.nm ) {
                info.push ( makeElement ( 'OS', boss.os.nm, 'Optimal share' ) );
                info.unshift ( makeElement ( 'MA', boss.nm[boss.nm.length - 1], 'Maximum/highest tier' ) );
                info.unshift ( makeElement ( 'MI', boss.nm[0], 'Minimum/lowest tier' ) );
            }
            info.unshift (
                    {
                        type: 'strong',
                        content: boss.name.replace ( /\(.*$/, '' )
                    } );
            this.taggedSlots[x] = idrinth.ui.buildElement (
                    {
                        id: 'idrinth-tier-box-' + name,
                        css: 'idrinth-hovering-box idrinth-tier-box',
                        children: [ {
                                children: info
                            } ],
                        attributes: [
                            {
                                name: 'title',
                                value: 'click to close'
                            },
                            {
                                name: 'onclick',
                                value: 'idrinth.ui.removeElement(this.id);idrinth.tier.taggedSlots[\'' + x + '\']=null;'
                            },
                            {
                                name: 'style',
                                value: 'left:' + x + 'px;background-image: url(https://dotd.idrinth.de/static/raid-image-service/' + boss.url + '/);'
                            }
                        ]
                    }
            );
            idrinth.ui.body.appendChild ( this.taggedSlots[x] );
        };
        for (var key in this.taggedSlots) {
            if ( this.taggedSlots.hasOwnProperty ( key ) && typeof key !== 'function' && this.taggedSlots[key] === null ) {
                return make ( key, name );
            }
        }
        idrinth.alert ( 'There is no space for another tier-box at the moment, please close one first.' );
    },
    taggedSlots: { },
    start: function () {
        'use strict';
        var pos = 1;
        while ( 0 < window.innerWidth - 140 * ( pos + 2 ) ) {
            this.taggedSlots[( pos * 140 ).toString ()] = null;
            pos++;
        }
        idrinth.runAjax (
                'https://dotd.idrinth.de/' + idrinth.platform + '/tier-service/',
                function ( text ) {
                    idrinth.tier.import ( text );
                },
                function ( ) {
                    window.setTimeout ( idrinth.tier.start, 10000 );
                },
                function ( ) {
                    window.setTimeout ( idrinth.tier.start, 10000 );
                }
        );
    },
    import: function ( data ) {
        'use strict';
        data = JSON.parse ( data );
        if ( data ) {
            idrinth.tier.list = data;
        } else {
            window.setTimeout ( idrinth.tier.start, 1000 );
        }
    },
    getTierForName: function ( name ) {
        var clearInnerHtml = function ( elem ) {
            elem.innerHTML = '';
        };

        var makeList = function ( list ) {
            var makeField = function ( listKey, difficulty, ic ) {
                var ln = {
                    type: 'td'
                };
                try {
                    ln.styles = idrinth.tier.list[listKey].os[difficulty] === idrinth.tier[listKey][difficulty][ic] ? 'is-os' : '';
                } catch ( E ) {
                    idrinth.log ( E.toString ( ) );
                }
                try {
                    ln.content = idrinth.ui.formatNumber ( idrinth.tier.list[listKey][difficulty][ic] ) + ' ' +
                            idrinth.tier.list[listKey].epics[difficulty][ic] + 'E';
                } catch ( E2 ) {
                    idrinth.log ( E2.toString ( ) );
                    try {
                        ln.content = idrinth.ui.formatNumber ( idrinth.tier.list[listKey][difficulty][ic] );
                    } catch ( E3 ) {
                        idrinth.log ( E3.toString ( ) );
                    }
                }
                return ln;
            };
            var makeRow = function ( title, dataset ) {
                return {
                    type: 'tr',
                    children: [
                        {
                            type: 'th',
                            content: title
                        },
                        {
                            type: 'td',
                            content: idrinth.ui.formatNumber ( dataset.n )
                        },
                        {
                            type: 'td',
                            content: idrinth.ui.formatNumber ( dataset.h )
                        },
                        {
                            type: 'td',
                            content: idrinth.ui.formatNumber ( dataset.l )
                        },
                        {
                            type: 'td',
                            content: idrinth.ui.formatNumber ( dataset.nm )
                        }
                    ]
                };
            };
            var wrapper = document.getElementById ( 'idrinth-tierlist' );
            clearInnerHtml ( wrapper );
            for (var count = list.length - 1; count >= 0; count--) {
                var sub = idrinth.ui.buildElement ( {
                    css: 'tier-wrapper',
                    children: [
                        {
                            type: 'img',
                            attributes: [ {
                                    name: 'src',
                                    value: 'https://dotd.idrinth.de/static/raid-image-service/' + idrinth.tier.list[list[count]].url + '/'
                                } ]
                        },
                        {
                            type: 'strong',
                            content: idrinth.tier.list[list[count]].name
                        },
                        {
                            type: 'button',
                            content: 'Tag to screen-top',
                            attributes: [
                                {
                                    name: 'onclick',
                                    value: 'idrinth.tier.addTagged(\'' + list[count].replace ( /'/g, '\\\'' ) + '\');'
                                },
                                {
                                    name: 'type',
                                    value: 'action'
                                }
                            ]
                        },
                        {
                            type: 'span',
                            content: 'AP: ' + idrinth.ui.formatNumber ( idrinth.tier.list[list[count]].ap )
                        },
                        {
                            type: 'table',
                            children: [
                                {
                                    type: 'thead',
                                    children: [
                                        {
                                            type: 'tr',
                                            children: [
                                                {
                                                    type: 'th',
                                                    content: '#'
                                                },
                                                {
                                                    type: 'th',
                                                    content: 'Normal'
                                                },
                                                {
                                                    type: 'th',
                                                    content: 'Hard'
                                                },
                                                {
                                                    type: 'th',
                                                    content: 'Legend'
                                                },
                                                {
                                                    type: 'th',
                                                    content: 'Nightmare'
                                                }
                                            ]
                                        }
                                    ]
                                },
                                {
                                    type: 'tbody',
                                    children: [
                                        makeRow ( 'FS', idrinth.tier.list[list[count]].fs ),
                                        makeRow ( 'OS', idrinth.tier.list[list[count]].os ),
                                        makeRow ( '', {
                                            n: '',
                                            l: '',
                                            h: '',
                                            nm: ''
                                        } )
                                    ]
                                }
                            ]
                        }
                    ]
                } );
                var maxTiers = Math.max ( idrinth.tier.list[list[count]].n.length, idrinth.tier.list[list[count]].h.length, idrinth.tier.list[list[count]].l.length, idrinth.tier.list[list[count]].nm.length );
                for (var ic = 0; ic < maxTiers; ic++) {
                    sub.lastChild.lastChild.appendChild ( idrinth.ui.buildElement ( {
                        type: 'tr',
                        children: [
                            {
                                type: 'th',
                                content: ic + 1
                            },
                            makeField ( list[count], 'n', ic ),
                            makeField ( list[count], 'h', ic ),
                            makeField ( list[count], 'l', ic ),
                            makeField ( list[count], 'nm', ic )
                        ]
                    } ) );
                }
                wrapper.appendChild ( sub );
            }
        };
        if ( !name || name.length === 0 ) {
            clearInnerHtml ( document.getElementById ( 'idrinth-tierlist' ) );
            return;
        }
        var result = [ ];
        var regExp = new RegExp ( name, 'i' );
        for (var key in idrinth.tier.list) {
            if ( key.match ( regExp ) ) {
                result.push ( key );
            }
        }
        makeList ( result );
    }
};<|endoftext|>


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

import {LitElement, html} from "/web_modules/lit-element.js";
import UtilsNew from "../../../utilsNew.js";

export default class SelectTokenFilter extends LitElement {

    constructor() {
        super();
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            config: {
                type: Object
            },
            placeholder: {
                type: String
            },
            resource: {
                type: String
            },
            value: {
                type: String
            }
        };
    }

    _init() {
        this._prefix = "tk-" + UtilsNew.randomString(6) + "_";
    }

    connectedCallback() {
        super.connectedCallback();
        this._config = {...this.getDefaultConfig(), ...this.config};
    }

    firstUpdated(_changedProperties) {
        super.firstUpdated(_changedProperties);
        $(".tokenize", this).tokenize2({
            placeholder: this.placeholder || "Start typing",
            tokensMaxItems: this._config.maxItems,
            dropdownMaxItems: 10,
            searchMinLength: this._config.searchMinLength,
            dataSource: (term, object) => {
                console.log(term, object, this._config);
                const filters = {
                    study: this.opencgaSession.study.fqn,
                    limit: this._config.limit,
                    count: false,
                    // include: "id",
                    id: "~^" + term.toUpperCase()
                };
                this.client().search(filters).then( restResponse => {
                    const results = restResponse.getResults();
                    object.trigger("tokenize:dropdown:fill", [results.map( result => ({text: result.id, value: result.id}))]);
                });
            }
        });
        $(".tokenize", this).on("tokenize:tokens:added", (e, value, text) => {
            console.log("added", e, value, text);
            console.log("added list", $(e.target).val());
            this.filterChange(e);
        });
        $(".tokenize", this).on("tokenize:tokens:remove", (e, value) => {
            console.log("removed", e, value);
            console.log("removed list", $(e.target).val());
            this.filterChange(e);
        });
    }

    updated(_changedProperties) {
        if (_changedProperties.has("config")) {
            this.propertyObserver();
        }
        if (_changedProperties.has("value")) {
            if (this.value) {
                if (this.value.split(",").length) {
                    //$(".tokenize", this).tokenize2().trigger("tokenize:clear");
                    console.log("changing")
                    this.silentClear()
                    this.value.split(",").forEach( v => $(".tokenize", this).tokenize2().trigger("tokenize:tokens:add", [v, v, true]));
                }
            } else {
                $(".tokenize", this).tokenize2().trigger("tokenize:clear");
            }
        }

    }

    filterChange(e) {
        const selection = $(e.target).val();
        let val;
        if (selection && selection.length) {
            // val = this.multiple ? selection.join(",") : selection[0];
            val = selection.join(",");
        }
        this.value = val ? val : null; // this allow users to get the selected values using DOMElement.value
        // console.log("select filterChange", val);
        const event = new CustomEvent("filterChange", {
            detail: {
                value: this.value
            }
        });
        this.dispatchEvent(event);
    }

    client() {
        switch (this.resource) {
            case "FILE":
                return this.opencgaSession.opencgaClient.files();
            case "SAMPLE":
                return this.opencgaSession.opencgaClient.samples();
            case "INDIVIDUAL":
                return this.opencgaSession.opencgaClient.individuals();
            case "COHORT":
                return this.opencgaSession.opencgaClient.cohorts();
            case "FAMILY":
                return this.opencgaSession.opencgaClient.families();
            case "CLINICAL_ANALYSIS":
                return this.opencgaSession.opencgaClient.clinical();
            case "JOB":
                return this.opencgaSession.opencgaClient.jobs();
            default:
                console.error("Resource not recognized");
        }
    }

    getDefaultConfig() {
        return {
            limit: 10,
            searchMinLength: 3,
            maxItems: 0
        };
    }

    readFile(event) {
        //console.log(event);
        const input = event.target;
        const reader = new FileReader();
        reader.readAsText(input.files[0]);
        reader.onload = function() {
            const dataURL = reader.result;
            console.log(dataURL);
        };
    }

    onDragOver(e) {
        e.preventDefault();
        e.stopPropagation();
        $(e.currentTarget).addClass("dragover");
    }

    onDragLeave(e) {
        e.preventDefault();
        e.stopPropagation();
        $(e.currentTarget).removeClass("dragover");
    }

    // it silently clear the input field without triggering  tokenize:tokens:remove which fire the filterChange
    silentClear(){
        //$("select.tokenize").empty()
        $(".tokens-container li.token").remove();
        $(".tokens-container li.placeholder").show();

    }

    render() {
        return html`

        <form action="" method="POST" enctype="multipart/form-data">

            Upload File

Choose an text file or drag it here.

              <input type="file" class="dropzone" />

        </form>

        <button @click="${this.click}"> click</button>

            <select class="tokenize" multiple></select>

        `;
    }

}

customElements.define("select-token-filter", SelectTokenFilter);
<commit_msg>select-token-filter.js review in progress<commit_after>/**
 * Copyright 2015-2019 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {LitElement, html} from "/web_modules/lit-element.js";
import UtilsNew from "../../../utilsNew.js";

/**
 * TODO
 * 1. find a better way than silendClear() to clear the tokens without triggering filterChange(). We need that in updated().
 * 2. avoid pointless remote requests each click on the blank area of the select.
 * 3. custom template in dropdown
 * 4. debug
 */

export default class SelectTokenFilter extends LitElement {

    constructor() {
        super();
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            config: {
                type: Object
            },
            placeholder: {
                type: String
            },
            resource: {
                type: String
            },
            value: {
                type: String
            }
        };
    }

    _init() {
        this._prefix = "tk-" + UtilsNew.randomString(6) + "_";
    }

    connectedCallback() {
        super.connectedCallback();
        this._config = {...this.getDefaultConfig(), ...this.config};
    }

    firstUpdated(_changedProperties) {
        super.firstUpdated(_changedProperties);
        $(".tokenize", this).tokenize2({
            placeholder: this.placeholder || "Start typing",
            tokensMaxItems: this._config.maxItems,
            dropdownMaxItems: 10,
            searchMinLength: this._config.searchMinLength,
            dataSource: (term, object) => {
                console.log(term, object, this._config);
                const filters = {
                    study: this.opencgaSession.study.fqn,
                    limit: this._config.limit,
                    count: false,
                    // include: "id",
                    id: "~^" + term.toUpperCase()
                };
                this.client().search(filters).then( restResponse => {
                    const results = restResponse.getResults();
                    object.trigger("tokenize:dropdown:fill", [results.map( result => ({text: result.id, value: result.id}))]);
                });
            }
        });
        $(".tokenize", this).on("tokenize:tokens:added", (e, value, text) => {
            console.log("added", e, value, text);
            console.log("added list", $(e.target).val());
            this.filterChange(e);
        });
        $(".tokenize", this).on("tokenize:tokens:remove", (e, value) => {
            console.log("removed", e, value);
            console.log("removed list", $(e.target).val());
            this.filterChange(e);
        });
    }

    updated(_changedProperties) {
        if (_changedProperties.has("config")) {
            this._config = {...this.getDefaultConfig(), ...this.config};
        }
        if (_changedProperties.has("value")) {
            if (this.value) {
                if (this.value.split(",").length) {
                    //$(".tokenize", this).tokenize2().trigger("tokenize:clear");
                    console.log("changing")
                    this.silentClear()
                    this.value.split(",").forEach( v => $(".tokenize", this).tokenize2().trigger("tokenize:tokens:add", [v, v, true]));
                }
            } else {
                $(".tokenize", this).tokenize2().trigger("tokenize:clear");
            }
        }

    }

    filterChange(e) {
        const selection = $(e.target).val();
        let val;
        if (selection && selection.length) {
            // val = this.multiple ? selection.join(",") : selection[0];
            val = selection.join(",");
        }
        this.value = val ? val : null; // this allow users to get the selected values using DOMElement.value
        // console.log("select filterChange", val);
        const event = new CustomEvent("filterChange", {
            detail: {
                value: this.value
            }
        });
        this.dispatchEvent(event);
    }

    client() {
        switch (this.resource) {
            case "FILE":
                return this.opencgaSession.opencgaClient.files();
            case "SAMPLE":
                return this.opencgaSession.opencgaClient.samples();
            case "INDIVIDUAL":
                return this.opencgaSession.opencgaClient.individuals();
            case "COHORT":
                return this.opencgaSession.opencgaClient.cohorts();
            case "FAMILY":
                return this.opencgaSession.opencgaClient.families();
            case "CLINICAL_ANALYSIS":
                return this.opencgaSession.opencgaClient.clinical();
            case "JOB":
                return this.opencgaSession.opencgaClient.jobs();
            default:
                console.error("Resource not recognized");
        }
    }

    getDefaultConfig() {
        return {
            limit: 10,
            searchMinLength: 3,
            maxItems: 0
        };
    }

    readFile(event) {
        //console.log(event);
        const input = event.target;
        const reader = new FileReader();
        reader.readAsText(input.files[0]);
        reader.onload = function() {
            const dataURL = reader.result;
            console.log(dataURL);
        };
    }

    onDragOver(e) {
        e.preventDefault();
        e.stopPropagation();
        $(e.currentTarget).addClass("dragover");
    }

    onDragLeave(e) {
        e.preventDefault();
        e.stopPropagation();
        $(e.currentTarget).removeClass("dragover");
    }

    // it silently clear the input field without triggering  tokenize:tokens:remove which fire the filterChange
    silentClear(){
        //$("select.tokenize").empty()
        $(".tokens-container li.token").remove();
        $(".tokens-container li.placeholder").show();

    }

    render() {
        return html`

        <form action="" method="POST" enctype="multipart/form-data">

            Upload File

Choose an text file or drag it here.

              <input type="file" class="dropzone" />

        </form>

        <button @click="${this.click}"> click</button>

            <select class="tokenize" multiple></select>

        `;
    }

}

customElements.define("select-token-filter", SelectTokenFilter);
<|endoftext|>