code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
// Test how stepping interacts with switch statements. var g = newGlobal(); g.eval('function bob() { return "bob"; }'); // Stepping into a sparse switch should not stop on literal cases. evaluate(`function lit(x) { // 1 debugger; // 2 switch(x) { // 3 case "nope": // 4 break; // 5 case "bob": // 6 break; // 7 } // 8 }`, {lineNumber: 1, global: g}); // Stepping into a sparse switch should stop on non-literal cases. evaluate(`function nonlit(x) { // 1 debugger; // 2 switch(x) { // 3 case bob(): // 4 break; // 5 } // 6 }`, {lineNumber: 1, global: g}); var dbg = Debugger(g); var badStep = false; function test(s, okLine) { dbg.onDebuggerStatement = function(frame) { frame.onStep = function() { let thisLine = this.script.getOffsetLocation(this.offset).lineNumber; // The stop at line 3 is the switch. if (thisLine > 3) { assertEq(thisLine, okLine) frame.onStep = undefined; } }; }; g.eval(s); } test("lit('bob');", 7); test("nonlit('bob');", 4);
cstipkovic/spidermonkey-research
js/src/jit-test/tests/debug/Frame-onStep-14.js
JavaScript
mpl-2.0
1,295
// species_data_url, previously_selected_species_ids, and species_options come in via django and must be set before including this file var species_counter = 0; // This is the counter to make new species elements so that we don't have to worry about array splicing when we remove a species. var species_on_page = []; // This is just a list of the on-page species ids so that ids can be added and removed without having to worry about array splicing. var species_already_used = []; // This is a list of the actual species ids so that we can remove (or add) species from other lists so that we don't have duplicates. var on_page_species_to_saved_species_map = {}; // This is used to have an easy way to add/remove/update species that will be saved. Example: {27: 1} where 27 would be the on-page species id and the 1 is the in-database species id var species_to_load = previously_selected_species_ids.length; $(document).ready(function() { var i; // Disable enter from triggering a form submission $(window).keydown(function(event) { if(event.keyCode == 13) { event.preventDefault(); return false; } }); // Save the scenario id data_to_save['scenario_id'] = $('#scenario_id').val(); // Initialize the species list data_to_save['species'] = []; if (previously_selected_species_ids.length == 0) { add_species(-1); } else { for (i = 0; i < previously_selected_species_ids.length; i++) { add_species(i); } } // This reenables the second set of save buttons. Just a visual thing. Initially the second set is hidden because // it looks tacky if they are showing, but after everything is loaded, then the buttons are displayed again. $('#save_buttons_2').show(); $('#form-is-valid').val(true); }); // If previously_selected_species_ids_index is -1, then this is a brand new species, as opposed to one from a previous // visit to this page. function add_species(previously_selected_species_ids_index) { var new_species_html = $('#species-template').html(); var new_species_wrapper; var new_species_remove_button; var new_species_description; var new_species_parameters; var new_species_id; if (species_already_used.length == species_options.length) { alert("All species already added."); return; } $('#species-section').append(new_species_html); new_species_wrapper = $('.species-wrapper').last(); new_species_wrapper.attr('id', 'species' + species_counter + '-wrapper'); // Example: id="species1-wrapper" new_species_remove_button = new_species_wrapper.find('.species-remove-button'); new_species_remove_button.attr('onclick', 'remove_species(' + species_counter + ')'); // Example: onclick="remove_species(1)" add_species_select(new_species_wrapper, species_counter, previously_selected_species_ids_index); new_species_description = new_species_wrapper.find('.species-description'); new_species_description.attr('id', 'species' + species_counter + '-description'); // Example: id="species1-description" new_species_parameters = new_species_wrapper.find('.species-parameters'); new_species_parameters.attr('id', 'species' + species_counter + '-parameters'); // Example: id="species1-parameters" species_on_page.push(species_counter); new_species_id = $('#species' + species_counter + '-select').val(); species_already_used.push(new_species_id); remove_species_from_select_lists(species_counter, new_species_id); on_page_species_to_saved_species_map[species_counter] = data_to_save['species'].length; // Store the species data to be saved data_to_save['species'].push({}); update_species(species_counter); // This handles adding everything about the species species_counter++; } function add_species_select(new_species_wrapper, on_page_species_id, previously_selected_species_ids_index) { var new_species_select; var i; var j; var id_should_be_skipped; var species_option_html; var default_species = -1; new_species_select = new_species_wrapper.find('.species-select'); new_species_select.attr('id', 'species' + on_page_species_id + '-select'); // Example: id="species1-select" // Example: <option value="1" selected>Farauti</option> // <option value="2">Dirus</option> for (i = 0; i < species_options.length; i++) { id_should_be_skipped = false; for (j = 0; j < species_already_used.length; j++) { if (species_options[i]['id'] == species_already_used[j]) { id_should_be_skipped = true; } } if (id_should_be_skipped) { continue; } species_option_html = '<option value="' + species_options[i]['id'] + '"'; if (previously_selected_species_ids_index != -1) { if (species_options[i]['id'] == previously_selected_species_ids[previously_selected_species_ids_index]) { species_option_html += ' selected'; default_species = species_options[i]['id']; } } species_option_html += '>' + species_options[i]['name'] + '</option>'; new_species_select.append(species_option_html); } new_species_select.change({select_id: on_page_species_id}, function(event) { update_species(event.data.select_id); remove_species_from_select_lists(event.data.select_id, default_species); }); // Save the currently selected value and name so we can use it later when it is changed new_species_select.data("previous_id", new_species_select.val()); new_species_select.data("previous_name", new_species_select.find(":selected").text().trim()); } function update_species(on_page_species_id) { var species_select = $('#species' + on_page_species_id + '-select'); var new_species_id = species_select.val(); var the_url = species_data_url + new_species_id + "/"; var species_list_position; var species_parameters_section = $('#species' + on_page_species_id + '-parameters'); var species_parameters_html = ""; var i; var j; var horizontal_line = '<hr size="1" style="margin: 1px; background-color: black; border:none">'; var parameter_name; var parameter_value; $.ajax( { type: "GET", url: the_url }).success(function(species_data) { $('#species' + on_page_species_id + '-description').html(species_data['description'] + '<br><br>'); for (i = 0; i < species_data['parameters'].length; i++) { parameter_name = species_data['parameters'][i]['name']; // This is to make sure we display the values correctly if there is more than 1 (ie larval habitat). if (typeof species_data['parameters'][i]['value'] === 'object') { parameter_value = ''; for (j = 0; j < species_data['parameters'][i]['value'].length; j++) { parameter_value += species_data['parameters'][i]['value'][j] + '<br>'; } } else // Else must be a number { parameter_value = parseFloat(species_data['parameters'][i]['value']).toFixed(3); } species_parameters_html += '<div class="row">' + '<div class="span8">' + horizontal_line + '</div>' + '<div class="span3">' + parameter_name + ':' + '</div>' + '<div class="span2">' + parameter_value + '</div>' + '</div>'; } species_parameters_section.html(species_parameters_html); // This if statement reads as "if we aren't updating the choice to the same value", however, this isn't // really possible because if you select the currently selected option, it will not trigger a change(). Instead, // this check is here to skip this section if we are adding the species for the first time. if (species_select.data("previous_id") != species_select.val()) { // Add the old value to the other select lists add_species_to_lists(on_page_species_id, species_select.data("previous_id"), species_select.data("previous_name")); // Remove the old value from the used list for (i = 0; i < species_already_used.length; i++) { if (species_already_used[i] == species_select.data("previous_id")) { species_already_used.splice(i, 1); break; } } // Add the new value to the used list species_already_used.push(new_species_id); // Remove the new value from the other lists remove_species_from_select_lists(on_page_species_id, new_species_id); } // Update the stored data (Doesn't save until the save button is pressed) species_list_position = on_page_species_to_saved_species_map[on_page_species_id]; // Check the map to find the correct species data to update data_to_save['species'][species_list_position]['species_id'] = new_species_id; // Update the select previous data to the new selection species_select.data("previous_value", species_select.val()); species_select.data("previous_name", species_select.find(":selected").text().trim()); }); if (species_to_load > 0) { species_to_load -= 1; } else { $('.save-button').attr('style', ''); } } function add_species_to_lists(list_that_species_was_chosen_from, id_to_add, name_to_add) { var i; var species_select; for (i = 0; i < species_on_page.length; i++) { if (list_that_species_was_chosen_from != i) { species_select = $('#species' + i + '-select'); species_option_html = '<option value="' + id_to_add + '"'; species_option_html += '>' + name_to_add + '</option>'; species_select.append(species_option_html); } } } function remove_species(on_page_species_id) { var species_select = species_select = $('#species' + on_page_species_id + '-select'); var species_id = species_select.val(); var species_name = species_select.find(":selected").text().trim(); if (species_already_used.length == 1) { alert('You cannot remove the last species.'); return; } remove_species_from_data_to_save(on_page_species_id); add_species_to_lists(species_id, species_name); remove_from_species_already_used_list(species_id); $('#species' + on_page_species_id + '-wrapper').remove(); } function remove_species_from_select_lists(list_that_species_was_chosen_from, value_to_remove) { var i; for (i = 0; i < species_on_page.length; i++) { if (list_that_species_was_chosen_from != i) { $('#species' + i + '-select option').each(function() { if ($(this).val() == value_to_remove) { $(this).remove(); } }); } } } function remove_species_from_data_to_save(on_page_species_id) { var species_list_position = on_page_species_to_saved_species_map[on_page_species_id]; // Check the map to find the correct species data to update data_to_save['species'].splice(species_list_position, 1); } function remove_from_species_already_used_list(species_id) { var index = -1; var i; for (i = 0; i < species_already_used.length; i++) { if (species_already_used[i] == species_id) { index = i; break; } } if (index != -1) { species_already_used.splice(index, 1); } else { alert("Species is not in species_already_used_list."); } }
tph-thuering/vnetsource
ts_repr/static/ts_repr/js/creation/species.js
JavaScript
mpl-2.0
12,181
/* 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/. */ define(function (require, exports, module) { 'use strict'; var Account = require('models/account'); var assert = require('chai').assert; var Broker = require('models/auth_brokers/base'); var p = require('lib/promise'); var Relier = require('models/reliers/relier'); var SignUpMixin = require('views/mixins/signup-mixin'); var sinon = require('sinon'); describe('views/mixins/signup-mixin', function () { it('exports correct interface', function () { assert.isObject(SignUpMixin); assert.lengthOf(Object.keys(SignUpMixin), 2); assert.isFunction(SignUpMixin.signUp); assert.isFunction(SignUpMixin.onSignUpSuccess); }); describe('signUp', function () { var account; var broker; var relier; var view; beforeEach(function () { account = new Account({ email: 'testuser@testuser.com' }); broker = new Broker(); relier = new Relier(); view = { _formPrefill: { clear: sinon.spy() }, broker: broker, getStringifiedResumeToken: sinon.spy(), invokeBrokerMethod: sinon.spy(function () { return p(); }), logViewEvent: sinon.spy(), navigate: sinon.spy(), onSignUpSuccess: SignUpMixin.onSignUpSuccess, relier: relier, signUp: SignUpMixin.signUp, user: { signUpAccount: sinon.spy(function (account) { return p(account); }) } }; }); describe('account needs permissions', function () { beforeEach(function () { sinon.stub(relier, 'accountNeedsPermissions', function () { return true; }); return view.signUp(account, 'password'); }); it('redirects to the `signup_permissions` screen', function () { assert.isTrue(view.navigate.calledOnce); var args = view.navigate.args[0]; assert.equal(args[0], 'signup_permissions'); assert.deepEqual(args[1].account, account); assert.isFunction(args[1].onSubmitComplete); }); it('does not log any events', function () { assert.isFalse(view.logViewEvent.called); }); }); describe('broker supports chooseWhatToSync', function () { beforeEach(function () { sinon.stub(broker, 'hasCapability', function (capabilityName) { return capabilityName === 'chooseWhatToSyncWebV1'; }); return view.signUp(account, 'password'); }); it('redirects to the `choose_what_to_sync` screen', function () { assert.isTrue(view.navigate.calledOnce); var args = view.navigate.args[0]; assert.equal(args[0], 'choose_what_to_sync'); assert.deepEqual(args[1].account, account); assert.isFunction(args[1].onSubmitComplete); }); it('does not log any events', function () { assert.isFalse(view.logViewEvent.called); }); }); describe('verified account', function () { beforeEach(function () { account.set('verified', true); return view.signUp(account, 'password'); }); it('calls view.logViewEvent correctly', function () { assert.equal(view.logViewEvent.callCount, 3); assert.isTrue(view.logViewEvent.calledWith('success')); assert.isTrue(view.logViewEvent.calledWith('signup.success')); assert.isTrue(view.logViewEvent.calledWith('preverified.success')); }); it('calls view._formPrefill.clear', function () { assert.equal(view._formPrefill.clear.callCount, 1); }); it('calls view.invokeBrokerMethod correctly', function () { assert.equal(view.invokeBrokerMethod.callCount, 2); var args = view.invokeBrokerMethod.args[0]; assert.lengthOf(args, 2); assert.equal(args[0], 'beforeSignIn'); assert.equal(args[1], 'testuser@testuser.com'); args = view.invokeBrokerMethod.args[1]; assert.lengthOf(args, 2); assert.equal(args[0], 'afterSignIn'); assert.deepEqual(args[1], account); }); it('calls view.navigate correctly', function () { assert.equal(view.navigate.callCount, 1); var args = view.navigate.args[0]; assert.lengthOf(args, 1); assert.equal(args[0], 'signup_complete'); }); }); describe('unverified account', function () { beforeEach(function () { account.set('verified', false); return view.signUp(account, 'password'); }); it('calls view.logViewEvent correctly', function () { assert.equal(view.logViewEvent.callCount, 2); assert.isTrue(view.logViewEvent.calledWith('success')); assert.isTrue(view.logViewEvent.calledWith('signup.success')); }); it('calls view._formPrefill.clear correctly', function () { assert.equal(view._formPrefill.clear.callCount, 1); assert.lengthOf(view._formPrefill.clear.args[0], 0); }); it('calls view.invokeBrokerMethod correctly', function () { assert.equal(view.invokeBrokerMethod.callCount, 2); var args = view.invokeBrokerMethod.args[0]; assert.lengthOf(args, 2); assert.equal(args[0], 'beforeSignIn'); assert.equal(args[1], 'testuser@testuser.com'); args = view.invokeBrokerMethod.args[1]; assert.lengthOf(args, 2); assert.equal(args[0], 'afterSignUp'); assert.deepEqual(args[1], account); }); it('calls view.navigate correctly', function () { assert.equal(view.navigate.callCount, 1); var args = view.navigate.args[0]; assert.lengthOf(args, 2); assert.equal(args[0], 'confirm'); assert.isObject(args[1]); assert.lengthOf(Object.keys(args[1]), 1); assert.equal(args[1].account, account); }); }); describe('_formPrefill undefined', function () { beforeEach(function () { view._formPrefill = undefined; }); it('does not throw', function () { assert.doesNotThrow(function () { return view.onSignUpSuccess(account); }); }); }); }); }); });
swatilk/fxa-content-server
app/tests/spec/views/mixins/signup-mixin.js
JavaScript
mpl-2.0
6,670
/* Copyright <YEAR(S)> <AUTHOR(S)> * License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). */ odoo.define_section('module_name', ['module_name.ExportedObject'], function(test) { "use strict"; test('It should demonstrate a PhantomJS test for web (backend)', function(assert, ExportedObject) { var expect = 'Expected Return', result = new ExportedObject(); assert.assertStrictEqual( result, expect, "Result !== Expect and the test failed with this message" ); } ); });
jpablio/Directrices-JPV
template/module/static/tests/js/module_name.js
JavaScript
agpl-3.0
611
(function(Juvia){ Base64 = { _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function(input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); } return output; } }; })(Juvia);
railskumar/comments
app/assets/javascripts/api/base64.js
JavaScript
agpl-3.0
895
/* eslint-disable newline-per-chained-call */ var monitoring = require('./helpers/monitoring'), authoring = require('./helpers/authoring'), ctrlKey = require('./helpers/utils').ctrlKey, commandKey = require('./helpers/utils').commandKey, ctrlShiftKey = require('./helpers/utils').ctrlShiftKey, assertToastMsg = require('./helpers/utils').assertToastMsg, nav = require('./helpers/utils').nav, dictionaries = require('./helpers/dictionaries'), workspace = require('./helpers/workspace'); describe('authoring', () => { beforeEach(() => { monitoring.openMonitoring(); }); it('add an embed and respect the order', () => { // try with same block content monitoring.actionOnItem('Edit', 2, 0); authoring.cleanBodyHtmlElement(); authoring.writeText('line\n'); authoring.addEmbed('embed'); var thirdBlockContext = element(by.model('item.body_html')).all(by.repeater('block in vm.blocks')).get(2); thirdBlockContext.element(by.css('.editor-type-html')).sendKeys('line\n'); authoring.addEmbed('embed', thirdBlockContext); authoring.blockContains(0, 'line'); authoring.blockContains(1, 'embed'); authoring.blockContains(2, 'line'); authoring.blockContains(3, 'embed'); authoring.close(); authoring.ignore(); // with different block content monitoring.actionOnItem('Edit', 2, 0); authoring.cleanBodyHtmlElement(); function generateLines(from, to) { var lines = ''; for (var i = from; i < to; i++) { lines += 'line ' + i + '\n'; } return lines; } var body1 = generateLines(0, 8); var body2 = generateLines(8, 15); var body3 = generateLines(15, 20); authoring.writeText(body1 + body2 + body3); for (var i = 0; i < 5; i++) { authoring.writeText(protractor.Key.UP); } authoring.writeText(protractor.Key.ENTER); authoring.writeText(protractor.Key.UP); authoring.addEmbed('Embed at position 15'); authoring.blockContains(0, (body1 + body2).replace(/\n$/, '')); authoring.blockContains(2, body3.replace(/\n$/, '')); element(by.model('item.body_html')).all(by.css('.editor-type-html')).get(0).click(); authoring.writeText(protractor.Key.ENTER); authoring.addEmbed('Embed at position 8'); authoring.blockContains(0, body1.replace(/\n$/, '')); authoring.blockContains(2, body2.replace(/\n$/, '')); authoring.blockContains(4, body3.replace(/\n$/, '')); }); it('authoring operations', () => { // undo and redo operations by using CTRL+Z and CTRL+y ... // ... from a new item authoring.createTextItem(); browser.sleep(1000); authoring.writeText('to be undone'); expect(authoring.getBodyText()).toBe('to be undone'); browser.sleep(1000); ctrlKey('z'); expect(authoring.getBodyText()).toBe(''); ctrlKey('y'); expect(authoring.getBodyText()).toBe('to be undone'); authoring.writeText(protractor.Key.ENTER); authoring.writeText(protractor.Key.UP); authoring.addEmbed('Embed'); authoring.blockContains(1, 'Embed'); authoring.blockContains(2, 'to be undone'); commandKey('z'); authoring.blockContains(0, 'to be undone'); commandKey('y'); authoring.blockContains(1, 'Embed'); authoring.blockContains(2, 'to be undone'); authoring.cutBlock(1); authoring.blockContains(0, 'to be undone'); ctrlKey('z'); authoring.blockContains(1, 'Embed'); authoring.blockContains(2, 'to be undone'); authoring.close(); authoring.ignore(); // ... from an existing item expect(monitoring.getTextItem(2, 0)).toBe('item5'); monitoring.actionOnItem('Edit', 2, 0); expect(authoring.getBodyText()).toBe('item5 text'); authoring.writeText('Two'); expect(authoring.getBodyText()).toBe('Twoitem5 text'); authoring.writeText('Words'); expect(authoring.getBodyText()).toBe('TwoWordsitem5 text'); ctrlKey('z'); expect(authoring.getBodyText()).toBe('Twoitem5 text'); ctrlKey('y'); expect(authoring.getBodyText()).toBe('TwoWordsitem5 text'); authoring.save(); authoring.close(); // allows to create a new empty package monitoring.createItemAction('create_package'); expect(element(by.className('packaging-screen')).isDisplayed()).toBe(true); authoring.close(); // can edit packages in which the item was linked expect(monitoring.getTextItem(2, 1)).toBe('item9'); monitoring.actionOnItem('Edit', 2, 1); authoring.showPackages(); expect(authoring.getPackages().count()).toBe(1); expect(authoring.getPackage(0).getText()).toMatch('PACKAGE2'); authoring.getPackage(0).element(by.tagName('a')).click(); authoring.showInfo(); expect(authoring.getGUID().getText()).toMatch('package2'); authoring.close(); // can change normal theme expect(monitoring.getTextItem(3, 2)).toBe('item6'); monitoring.actionOnItem('Edit', 3, 2); authoring.changeNormalTheme('dark-theme'); expect(monitoring.hasClass(element(by.className('main-article')), 'dark-theme')).toBe(true); authoring.close(); // can change proofread theme expect(monitoring.getTextItem(3, 2)).toBe('item6'); monitoring.actionOnItem('Edit', 3, 2); authoring.changeProofreadTheme('dark-theme-mono'); expect(monitoring.hasClass(element(by.className('main-article')), 'dark-theme-mono')).toBe(true); authoring.close(); // publish & kill item expect(monitoring.getTextItem(2, 0)).toBe('item5'); monitoring.actionOnItem('Edit', 2, 0); authoring.publish(); browser.sleep(300); monitoring.filterAction('text'); monitoring.actionOnItem('Kill item', 5, 0); expect(authoring.send_kill_button.isDisplayed()).toBeTruthy(); authoring.cancel(); browser.sleep(300); // publish & correct item // reset filters monitoring.filterAction('all'); expect(monitoring.getTextItem(3, 2)).toBe('item6'); monitoring.actionOnItem('Edit', 3, 2); authoring.publish(); browser.sleep(300); monitoring.filterAction('text'); monitoring.actionOnItem('Correct item', 5, 0); expect(authoring.send_correction_button.isDisplayed()).toBeTruthy(); authoring.cancel(); expect(monitoring.getTextItem(5, 0)).toBe('item6'); monitoring.actionOnItem('Open', 5, 0); expect(authoring.edit_correct_button.isDisplayed()).toBe(true); expect(authoring.edit_kill_button.isDisplayed()).toBe(true); authoring.close(); browser.sleep(300); monitoring.filterAction('all'); // reset filter // update(rewrite) item monitoring.openMonitoring(); // reset filters monitoring.filterAction('all'); expect(monitoring.getTextItem(2, 1)).toBe('item7'); monitoring.actionOnItem('Edit', 2, 1); authoring.publish(); browser.sleep(300); monitoring.filterAction('text'); expect(monitoring.getTextItem(5, 0)).toBe('item7'); monitoring.actionOnItem('Open', 5, 0); expect(authoring.update_button.isDisplayed()).toBe(true); authoring.update_button.click(); monitoring.compactActionDropdown().click(); monitoring.filterAction('all'); expect(monitoring.getTextItem(0, 0)).toBe('item7'); expect(monitoring.getTextItem(5, 0)).toBe('item7'); }); it('authoring history', () => { // view item history create-fetch operation expect(monitoring.getTextItem(3, 2)).toBe('item6'); monitoring.actionOnItem('Edit', 3, 2); authoring.showHistory(); expect(authoring.getHistoryItems().count()).toBe(1); expect(authoring.getHistoryItem(0).getText()).toMatch(/Fetched by first name last name Today/); authoring.close(); // view item history move operation expect(monitoring.getTextItem(2, 3)).toBe('item8'); monitoring.actionOnItem('Edit', 2, 3); authoring.writeText('Two'); authoring.save(); expect(authoring.sendToButton.isDisplayed()).toBe(true); authoring.showHistory(); expect(authoring.getHistoryItems().count()).toBe(2); authoring.sendTo('Politic Desk', 'two'); authoring.confirmSendTo(); expect(monitoring.getTextItem(3, 0)).toBe('item8'); monitoring.actionOnItem('Edit', 3, 0); authoring.showHistory(); expect(authoring.getHistoryItems().count()).toBe(3); expect(authoring.getHistoryItem(2).getText()).toMatch(/Moved by first name last name Today/); authoring.close(); // view item history editable for newly created unsaved item authoring.createTextItem(); authoring.showHistory(); expect(authoring.getHistoryItems().count()).toBe(1); expect(authoring.getHistoryItem(0).getText()).toMatch(/Created by first name last name Today/); expect(authoring.save_button.isDisplayed()).toBe(true); authoring.getHistoryItem(0).click(); expect(authoring.save_button.isDisplayed()).toBe(true); // expect save button still available authoring.close(); // view item history create-update operations authoring.createTextItem(); authoring.writeTextToHeadline('new item'); authoring.writeText('some text'); authoring.save(); authoring.showHistory(); expect(authoring.getHistoryItems().count()).toBe(2); expect(authoring.getHistoryItem(0).getText()).toMatch(/Created by first name last name Today/); expect(authoring.getHistoryItem(1).getText()).toMatch(/Updated by.*/); authoring.save(); authoring.close(); // view item history publish operation expect(monitoring.getTextItem(3, 3)).toBe('item6'); monitoring.actionOnItem('Edit', 3, 3); authoring.addHelpline('Children'); expect(authoring.getBodyFooter()).toMatch(/Kids Helpline*/); expect(authoring.save_button.getAttribute('disabled')).toBe(null); authoring.save(); authoring.publish(); monitoring.filterAction('text'); monitoring.actionOnItem('Open', 5, 0); authoring.showHistory(); expect(authoring.getHistoryItems().count()).toBe(3); expect(authoring.getHistoryItem(0).getText()).toMatch(/Fetched by.*/); expect(authoring.getHistoryItem(1).getText()).toMatch(/Updated by.*/); expect(authoring.getHistoryItem(2).getText()).toMatch(/Published by.*/); var transmissionDetails = authoring.showTransmissionDetails(2); expect(transmissionDetails.count()).toBe(1); transmissionDetails.get(0).click(); expect(element(by.className('modal__body')).getText()).toMatch(/Kids Helpline*/); element(by.css('[ng-click="hideFormattedItem()"]')).click(); monitoring.compactActionDropdown().click(); monitoring.filterAction('text'); authoring.close(); // view item history spike-unspike operations browser.sleep(5000); monitoring.showMonitoring(); expect(monitoring.getTextItem(2, 2)).toBe('item7'); monitoring.actionOnItem('Spike', 2, 2); monitoring.showSpiked(); expect(monitoring.getSpikedTextItem(0)).toBe('item7'); monitoring.unspikeItem(0, 'Politic desk', 'Incoming Stage'); monitoring.showMonitoring(); expect(monitoring.getTextItem(1, 0)).toBe('item7'); monitoring.actionOnItem('Edit', 1, 0); authoring.showHistory(); expect(authoring.getHistoryItems().count()).toBe(3); expect(authoring.getHistoryItem(1).getText()).toMatch(/Spiked by first name last name Today/); expect(authoring.getHistoryItem(2).getText()).toMatch(/Unspiked by first name last name Today/); authoring.close(); // view item history duplicate operation expect(monitoring.getTextItem(2, 0)).toBe('item5'); monitoring.actionOnItemSubmenu('Duplicate', 'Duplicate in place', 2, 0, true); expect(monitoring.getTextItem(0, 0)).toBe('item5'); monitoring.actionOnItem('Edit', 0, 0); authoring.showHistory(); expect(authoring.getHistoryItems().count()).toBe(2); expect(authoring.getHistoryItem(1).getText()).toMatch(/Duplicated by/); authoring.close(); }); it('keyboard shortcuts', () => { monitoring.actionOnItem('Edit', 2, 0); authoring.writeText('z'); element(by.cssContainingText('label', 'Dateline')).click(); ctrlShiftKey('s'); browser.wait(() => element(by.buttonText('Save')).getAttribute('disabled'), 500); authoring.close(); monitoring.actionOnItem('Edit', 2, 0); browser.sleep(300); expect(authoring.getBodyText()).toBe('zitem5 text'); element(by.cssContainingText('label', 'Headline')).click(); ctrlShiftKey('e'); browser.sleep(300); expect(element.all(by.css('.authoring-embedded .embedded-auth-view')).count()).toBe(0); }); it('can display monitoring after publishing an item using full view of authoring', () => { monitoring.actionOnItem('Edit', 3, 2); monitoring.showHideList(); authoring.publish(); expect(monitoring.getGroups().count()).toBe(6); }); it('broadcast operation', () => { expect(monitoring.getTextItem(2, 0)).toBe('item5'); monitoring.actionOnItem('Edit', 2, 0); authoring.publish(); monitoring.filterAction('text'); monitoring.actionOnItem('Create Broadcast', 5, 0); expect(authoring.getHeaderSluglineText()).toContain('item5'); }); it('can calculate word counts', () => { expect(monitoring.getTextItem(2, 0)).toBe('item5'); monitoring.actionOnItem('Edit', 2, 0); authoring.cleanBodyHtmlElement(); authoring.writeText('There are seven words in this sentence.\n'); authoring.writeText('There are eight words in this new sentence.'); authoring.writeText(protractor.Key.ENTER); authoring.writeText(' '); authoring.writeText(protractor.Key.ENTER); authoring.writeText('There are nine words, in this final last sentence.\n'); expect(authoring.getEditorWordCount()).toBe('24 words'); authoring.save(); authoring.close(); expect(monitoring.getMonitoringWordCount('item5')).toBe('24'); monitoring.actionOnItem('Edit', 2, 0); authoring.cleanBodyHtmlElement(); expect(authoring.getEditorWordCount()).toBe('0 words'); authoring.save(); authoring.close(); expect(monitoring.getMonitoringWordCount('item5')).toBe('0'); }); it('can update sign off manually', () => { expect(monitoring.getTextItem(2, 0)).toBe('item5'); monitoring.actionOnItem('Edit', 2, 0); expect(authoring.getSignoffText()).toBe('fl'); authoring.writeSignoffText('ABC'); authoring.save(); authoring.close(); expect(monitoring.getTextItem(2, 0)).toBe('item5'); monitoring.actionOnItem('Edit', 2, 0); expect(authoring.getSignoffText()).toBe('ABC'); authoring.writeText('z'); authoring.save(); expect(authoring.getSignoffText()).toBe('ABC/fl'); }); it('toggle auto spellcheck and hold changes', () => { monitoring.actionOnItem('Edit', 2, 1); expect(element(by.model('spellcheckMenu.isAuto')).getAttribute('checked')).toBeTruthy(); authoring.toggleAutoSpellCheck(); expect(element(by.model('spellcheckMenu.isAuto')).getAttribute('checked')).toBeFalsy(); authoring.close(); monitoring.actionOnItem('Edit', 2, 2); expect(element(by.model('spellcheckMenu.isAuto')).getAttribute('checked')).toBeFalsy(); }); it('spellcheck hilite sentence word for capitalization and ignore the word after abbreviations', () => { nav('/settings/dictionaries'); dictionaries.edit('Test 1'); expect(dictionaries.getWordsCount()).toBe(0); dictionaries.search('abbrev.'); dictionaries.saveWord(); dictionaries.search('abbrev'); dictionaries.saveWord(); expect(dictionaries.getWordsCount()).toBe(2); dictionaries.save(); browser.sleep(200); monitoring.openMonitoring(); authoring.createTextItem(); authoring.writeText('some is a sentence word, but words come after an abbrev. few are not'); browser.sleep(200); expect(authoring.getBodyInnerHtml()).toContain('<span class="sderror sdhilite sdCapitalize" data-word="some" ' + 'data-index="0" data-sentence-word="true">some</span>'); expect(authoring.getBodyInnerHtml()).not.toContain('<span class="sderror sdhilite sdCapitalize" ' + 'data-word="few" data-index="57">few</span>'); expect(authoring.getBodyInnerHtml()).toContain('<span class="sderror sdhilite" data-word="few" ' + 'data-index="57">few</span>'); }); it('related item widget', () => { monitoring.actionOnItem('Edit', 2, 1); authoring.writeText('something'); authoring.save(); authoring.close(); authoring.createTextItem(); browser.sleep(1000); authoring.writeText('something'); authoring.setHeaderSluglineText('item test'); authoring.save(); authoring.close(); authoring.createTextItem(); browser.sleep(1000); authoring.writeText('something'); authoring.setHeaderSluglineText('item test'); authoring.save(); authoring.openRelatedItem(); authoring.searchRelatedItems(); expect(authoring.getRelatedItems().count()).toBe(1); authoring.searchRelatedItems('slugline'); expect(authoring.getRelatedItems().count()).toBe(0); authoring.openRelatedItemConfiguration(); authoring.setRelatedItemConfigurationSlugline('ANY'); authoring.setRelatedItemConfigurationLastUpdate('now-48h'); authoring.saveRelatedItemConfiguration(); browser.sleep(1000); authoring.searchRelatedItems(); expect(authoring.getRelatedItems().count()).toBe(1); }); it('related item widget can open published item', () => { expect(monitoring.getGroups().count()).toBe(6); expect(monitoring.getTextItem(2, 1)).toBe('item9'); expect(monitoring.getTextItemBySlugline(2, 1)).toContain('ITEM9 SLUGLINE'); monitoring.actionOnItem('Edit', 2, 1); authoring.publish(); // item9 published monitoring.filterAction('text'); monitoring.actionOnItem('Update', 5, 0); // duplicate item9 text published item expect(monitoring.getGroupItems(0).count()).toBe(1); monitoring.actionOnItem('Edit', 0, 0); authoring.openRelatedItem(); // opens related item widget browser.sleep(10000); expect(authoring.getRelatedItemBySlugline(0).getText()).toContain('item9 slugline'); authoring.actionOpenRelatedItem(0); // Open item expect(authoring.getHeaderSluglineText()).toContain('item9 slugline'); }); it('Kill Template apply', () => { expect(monitoring.getTextItem(2, 0)).toBe('item5'); monitoring.actionOnItem('Edit', 2, 0); authoring.publish(); monitoring.filterAction('text'); monitoring.actionOnItem('Kill item', 5, 0); browser.sleep(500); expect(authoring.getBodyText()).toBe('This is kill template. Slugged item5 slugline one/two.'); expect(authoring.getHeadlineText()).toBe('KILL NOTICE'); expect(authoring.getHeadlineText()).toBe('KILL NOTICE'); expect(authoring.send_kill_button.isDisplayed()).toBeTruthy(); }); it('Emptied body text fails to validate', () => { expect(monitoring.getTextItem(2, 0)).toBe('item5'); monitoring.actionOnItem('Edit', 2, 0); authoring.writeText(''); ctrlShiftKey(protractor.Key.END); ctrlKey('x'); authoring.save(); authoring.publish(true); assertToastMsg('error', 'BODY_HTML empty values not allowed'); }); it('keyboard navigation operations on subject dropdown', () => { // Open any item in Edit mode monitoring.actionOnItem('Edit', 2, 1); // Open subject metadata dropdown field authoring.getSubjectMetadataDropdownOpened(); browser.sleep(500); // wait a bit // Perform down arrow would focus/active next element in list browser.actions().sendKeys(protractor.Key.DOWN).perform(); browser.sleep(200); expect(browser.driver.switchTo().activeElement().getText()).toEqual('arts, culture and entertainment'); // Perform right arrow would navigate to next level of focused category and selected as input term browser.actions().sendKeys(protractor.Key.RIGHT).perform(); var selectedTerm = authoring.getNextLevelSelectedCategory(); expect(selectedTerm.get(0).getText()).toBe('arts, culture and entertainment'); // Perform Left arrow key would back to one level up in tree and should be focused/active browser.actions().sendKeys(protractor.Key.LEFT).perform(); browser.sleep(200); expect(browser.driver.switchTo().activeElement().getText()).toEqual('arts, culture and entertainment'); // now type some search term an check if down arrow navigates the search list browser.actions().sendKeys('cri').perform(); browser.sleep(200); browser.actions().sendKeys(protractor.Key.DOWN).perform(); expect(browser.driver.switchTo().activeElement().getText()).toEqual('crime, law and justice'); }); it('hide multi-edit option when action is kill', () => { expect(monitoring.getTextItem(2, 0)).toBe('item5'); monitoring.actionOnItem('Edit', 2, 0); authoring.moreActionsButton.click(); expect(authoring.multieditButton.isDisplayed()).toBe(true); authoring.publish(); monitoring.filterAction('text'); monitoring.actionOnItem('Kill item', 5, 0); authoring.moreActionsButton.click(); expect(authoring.multieditButton.isDisplayed()).toBe(false); }); it('Compare versions operations of an opened article via Compare versions menu option', () => { expect(monitoring.getTextItem(2, 0)).toBe('item5'); monitoring.actionOnItem('Edit', 2, 0); // Provide another version on save authoring.writeTextToHeadline('updated '); authoring.save(); expect(authoring.getHeadlineText()).toBe('updated item5'); // Open selected versions in compare-versions screen boards authoring.openCompareVersionsScreen(); expect(authoring.getCompareVersionsBoards().count()).toBe(2); expect(authoring.getArticleHeadlineOfBoard(0)).toEqual('updated item5'); expect(authoring.getInnerDropdownItemVersions(1).count()).toBe(1); authoring.closeCompareVersionsScreen(); // expect the article should be open on closing compare-versions screen expect(authoring.headline.isDisplayed()).toBe(true); expect(authoring.getHeadlineText()).toBe('updated item5'); // Update article headline again to get third version authoring.writeTextToHeadline('newly '); authoring.save(); expect(authoring.getHeadlineText()).toBe('newly updated item5'); authoring.openCompareVersionsScreen(); expect(authoring.getArticleHeadlineOfBoard(0)).toEqual('newly updated item5'); expect(authoring.getInnerDropdownItemVersions(1).count()).toBe(2); authoring.openItemVersionInBoard(1, 0); expect(authoring.getInnerDropdownItemVersions(0).count()).toBe(1); expect(authoring.getHtmlArticleHeadlineOfBoard(0)).toContain( '<ins style="background:#e6ffe6;">newly </ins><span>updated item5</span>' ); expect(authoring.getArticleHeadlineOfBoard(1)).toEqual('updated item5'); }); it('open publish item with footer text without <br> tag', () => { expect(monitoring.getTextItem(2, 0)).toBe('item5'); monitoring.actionOnItem('Edit', 2, 0); authoring.addHelpline('Suicide'); expect(authoring.getBodyFooter()).toMatch(/Readers seeking support and information about suicide*/); expect(authoring.save_button.isEnabled()).toBe(true); authoring.save(); authoring.publish(); monitoring.filterAction('text'); monitoring.actionOnItem('Open', 5, 0); expect(authoring.getBodyFooterPreview()).not.toContain('<br>'); }); it('maintains helpline first option always selected', () => { expect(monitoring.getTextItem(2, 0)).toBe('item5'); monitoring.actionOnItem('Edit', 2, 0); authoring.addHelpline('Suicide'); expect(authoring.getBodyFooter()).toMatch(/Readers seeking support and information about suicide*/); expect(authoring.save_button.isEnabled()).toBe(true); expect(authoring.getHelplineSelectedOption(0)).toBe('true'); // first option remained selected expect(authoring.getHelplineSelectedOption(1)).toBe(null); // Suicide not remained selected // select another helpline authoring.addHelpline('Children'); expect(authoring.getHelplineSelectedOption(0)).toBe('true'); // first option remained selected expect(authoring.getHelplineSelectedOption(2)).toBe(null); // Children not remained selected }); it('Not be able to Ctrl-z to the original, actionable text when killing an item', () => { expect(monitoring.getTextItem(2, 0)).toBe('item5'); monitoring.actionOnItem('Edit', 2, 0); expect(authoring.getHeadlineText()).toBe('item5'); // original, actionable headline text expect(authoring.getBodyText()).toBe('item5 text'); // original, actionable body text authoring.publish(); monitoring.filterAction('text'); monitoring.actionOnItem('Kill item', 5, 0); // Body: // undo without editing body text ctrlKey('z'); expect(authoring.getBodyText()).toBe('This is kill template. Slugged item5 slugline one/two.'); // now edit body text authoring.writeText('Edit kill notice body text:'); expect(authoring.getBodyText()) .toBe('Edit kill notice body text:This is kill template. Slugged item5 slugline one/two.'); // undo edited body text ctrlKey('z'); expect(authoring.getBodyText()).toBe('This is kill template. Slugged item5 slugline one/two.'); // undo one more time and expect body text not to be the original body text. ctrlKey('z'); expect(authoring.getBodyText()).not.toBe('item5 text'); expect(authoring.getBodyText()).toBe('This is kill template. Slugged item5 slugline one/two.'); // Headline: // undo without editing headline text ctrlKey('z'); expect(authoring.getHeadlineText()).toBe('KILL NOTICE'); // now edit headline text authoring.writeTextToHeadline('Edit kill headline:'); expect(authoring.getHeadlineText()).toBe('Edit kill headline:KILL NOTICE'); // undo edited headline text ctrlKey('z'); expect(authoring.getHeadlineText()).toBe('KILL NOTICE'); // undo one more time and expect headline text not to be the original headline text. ctrlKey('z'); expect(authoring.getHeadlineText()).not.toBe('item5'); expect(authoring.getHeadlineText()).toBe('KILL NOTICE'); expect(authoring.send_kill_button.isDisplayed()).toBeTruthy(); }); it('after undo/redo save last version', () => { monitoring.actionOnItem('Edit', 2, 0); authoring.cleanBodyHtmlElement(); browser.sleep(2000); authoring.writeText('one\ntwo\nthree'); browser.sleep(2000); // wait for autosave authoring.backspaceBodyHtml(5); browser.sleep(2000); ctrlKey('z'); browser.sleep(1000); authoring.save(); authoring.close(); monitoring.actionOnItem('Edit', 2, 0); expect(authoring.getBodyText()).toBe('one\ntwo\nthree'); }); it('can send and publish', () => { workspace.selectDesk('Sports Desk'); expect(monitoring.getGroupItems(0).count()).toBe(0); expect(monitoring.getGroupItems(1).count()).toBe(0); expect(monitoring.getGroupItems(2).count()).toBe(1); expect(monitoring.getGroupItems(3).count()).toBe(0); expect(monitoring.getGroupItems(4).count()).toBe(1); expect(monitoring.getGroupItems(5).count()).toBe(0); // no published content. workspace.selectDesk('Politic Desk'); expect(monitoring.getGroupItems(5).count()).toBe(0); // desk output expect(monitoring.getTextItem(3, 2)).toBe('item6'); monitoring.actionOnItem('Edit', 3, 2); authoring.writeTextToHeadline('testing send and publish'); authoring.save(); authoring.writeText(''); ctrlShiftKey(protractor.Key.END); ctrlKey('x'); authoring.sendAndpublish('Sports Desk'); authoring.confirmSendTo(); // confirm unsaved changes authoring.publishFrom('Sports Desk'); assertToastMsg('error', 'BODY_HTML empty values not allowed'); // validation takes place authoring.writeText('Testing'); authoring.save(); authoring.publishFrom('Sports Desk'); // desk output count zero as content publish from sport desk expect(monitoring.getGroupItems(5).count()).toBe(0); workspace.selectDesk('Sports Desk'); expect(monitoring.getGroupItems(5).count()).toBe(1); }, 600000); it('can minimize story while a correction and kill is being written', () => { workspace.selectDesk('Politic Desk'); expect(monitoring.getTextItem(3, 2)).toBe('item6'); monitoring.actionOnItem('Edit', 3, 2); authoring.publish(); monitoring.filterAction('text'); monitoring.actionOnItem('Correct item', 5, 0); // Edit for correction authoring.minimize(); // minimize before publishing the correction expect(monitoring.getTextItem(2, 1)).toBe('item9'); monitoring.actionOnItem('Edit', 2, 1); authoring.publish(); monitoring.actionOnItem('Kill item', 5, 0); // Edit for kill authoring.minimize(); // minimize before publishing the kill authoring.maximize('item6'); expect(authoring.send_correction_button.isDisplayed()).toBeTruthy(); authoring.maximize('item9'); expect(authoring.send_kill_button.isDisplayed()).toBeTruthy(); }); });
gbbr/superdesk-client-core
spec/authoring_spec.js
JavaScript
agpl-3.0
31,226
angular.module('editor', [ 'ui.router', 'editor.conf.persistence', 'editor.conf.loadingbar', 'editor.views.recipes', 'editor.views.recipes.recipe', 'editor.views.recipes.sheet', 'editor.views.ingredients', 'editor.views.equipments', 'editor.views.equipments.equipment' ]) .config(['$urlRouterProvider', '$urlMatcherFactoryProvider', function($urlRouterProvider, $urlMatcherFactoryProvider) { $urlRouterProvider.when('', '/recipes'); $urlMatcherFactoryProvider.strictMode(false); }]);
vieuxsinge/editor
editor/main.js
JavaScript
agpl-3.0
515
// Copyright (C) 2015 Sam Parkinson // This program is free software; you can redistribute it and/or // modify it under the terms of the The GNU Affero General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // You should have received a copy of the GNU Affero General Public // License along with this library; if not, write to the Free Software // Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA // window.platform = { android: /Android/i.test(navigator.userAgent), FF: /Firefox/i.test(navigator.userAgent), mobile: /Mobi/i .test(navigator.userAgent), tablet: /Tablet/i .test(navigator.userAgent) } platform.androidWebkit = platform.android && !platform.FF; platform.FFOS = platform.FF && (platform.mobile || platform.tablet) && !platform.android; console.log('On platform: ', platform); window.platformColor = { header: platform.FF? '#00539F' : '#2196F3', doHeaderShadow: !platform.FF, background: platform.FF? '#00CAF2' : '#96D3F3' } document.querySelector('meta[name=theme-color]') .content = platformColor.header; function showButtonHighlight(x, y, r, event, scale, stage) { if (platform.FFOS) return {}; return showMaterialHighlight(x, y, r, event, scale, stage); }
Daksh/turtleblocksjs
js/platformstyle.js
JavaScript
agpl-3.0
1,373
/*! * Jade - nodes - Filter * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ /** * Module dependencies. */ var Node = require('./node'); /** * Initialize a `Filter` node with the given * filter `name` and `block`. * * @param {String} name * @param {Block|Node} block * @api public */ var Filter = module.exports = function Filter(name, block, attrs) { this.name = name; this.block = block; this.attrs = attrs; }; /** * Inherit from `Node`. */ Filter.prototype.__proto__ = Node.prototype;
diffalot/memetec
node_modules/.npm/jade/0.9.1/package/lib/nodes/filter.js
JavaScript
agpl-3.0
541
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ placeholder: { id: 'search.placeholder', defaultMessage: 'Search' }, }); class Search extends React.PureComponent { static propTypes = { value: PropTypes.string.isRequired, submitted: PropTypes.bool, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClear: PropTypes.func.isRequired, onShow: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleChange = (e) => { this.props.onChange(e.target.value); } handleClear = (e) => { e.preventDefault(); if (this.props.value.length > 0 || this.props.submitted) { this.props.onClear(); } } handleKeyDown = (e) => { if (e.key === 'Enter') { e.preventDefault(); this.props.onSubmit(); } } noop () { } handleFocus = () => { this.props.onShow(); } render () { const { intl, value, submitted } = this.props; const hasValue = value.length > 0 || submitted; return ( <div className='search'> <input className='search__input' type='text' placeholder={intl.formatMessage(messages.placeholder)} value={value} onChange={this.handleChange} onKeyUp={this.handleKeyDown} onFocus={this.handleFocus} /> <div role='button' tabIndex='0' className='search__icon' onClick={this.handleClear}> <i className={`fa fa-search ${hasValue ? '' : 'active'}`} /> <i aria-label={intl.formatMessage(messages.placeholder)} className={`fa fa-times-circle ${hasValue ? 'active' : ''}`} /> </div> </div> ); } } export default injectIntl(Search);
h-izumi/mastodon
app/javascript/mastodon/features/compose/components/search.js
JavaScript
agpl-3.0
1,817
/** * Module util.js * Its static common helpers methods */ (function (window) { if (!Array.isArray) { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } var util = {}; /** * Deeply extends two objects * @param {Object} destination The destination object, This object will change * @param {Object} source The custom options to extend destination by * @return {Object} The desination object */ util.extend = function (destination, source) { var property; for (property in source) { if (source[property] && source[property].constructor && source[property].constructor === Object) { destination[property] = destination[property] || {}; util.extend(destination[property], source[property]); } else { destination[property] = source[property]; } } return destination; }; /** * Clone object * @param {Object} source * @returns {*} */ util.objClone = function (source) { if (source === null || typeof source !== 'object') return source; var temp = source.constructor(); for (var key in source) temp[key] = util.objClone(source[key]); return temp; }; /** * Count object length * @param {Object} source * @returns {number} */ util.objLen = function (source) { var it = 0; for (var k in source) it++; return it; }; /** * Merge an object `src` into the object `objectBase` * @param objectBase main object of merge * @param src the elements of this object will be added/replaced to main object `obj` * @returns {*} object result */ util.objMerge = function (objectBase, src) { if (typeof objectBase !== 'object' || typeof src !== 'object') return false; if (Object.key) { Object.keys(src).forEach(function (key) { objectBase[key] = src[key]; }); return objectBase; } else { for (var key in src) if (src.hasOwnProperty(key)) objectBase[key] = src[key]; return objectBase; } }; /** * Merge objects if `objectBase` key not exists * @param objectBase * @param src * @returns {*} */ util.objMergeNotExists = function (objectBase, src) { for (var key in src) if (objectBase[key] === undefined) objectBase[key] = src[key]; return objectBase; }; /** * Merge objects if `objectBase` key is exists * @param objectBase * @param src * @returns {*} */ util.objMergeOnlyExists = function (objectBase, src) { for (var key in src) if (objectBase[key] !== undefined) objectBase[key] = src[key]; return objectBase; }; /** * Merge an array `src` into the array `arrBase` * @param arrBase * @param src * @returns {*} */ util.arrMerge = function (arrBase, src) { if (!Array.isArray(arrBase) || !Array.isArray(src)) return false; for (var i = 0; i < src.length; i++) arrBase.push(src[i]) return arrBase; }; /** * Computes the difference of arrays * Compares arr1 against one or more other arrays and returns the values in arr1 * that are not present in any of the other arrays. * @param arr1 * @param arr2 * @returns {*} */ util.arrDiff = function (arr1, arr2) { if (util.isArr(arr1) && util.isArr(arr2)) { return arr1.slice(0).filter(function (item) { return arr2.indexOf(item) === -1; }) } return false; }; util.objToArr = function (obj) { return [].slice.call(obj); }; util.realObjToArr = function (obj) { var arr = []; for (var key in obj) arr.push(obj[key]) return arr; }; util.cloneFunction = function (func) { var temp = function temporary() { return func.apply(this, arguments); }; for (var key in this) { if (this.hasOwnProperty(key)) { temp[key] = this[key]; } } return temp; }; /** * Check on typeof is string a param * @param param * @returns {boolean} */ util.isStr = function (param) { return typeof param === 'string'; }; /** * Check on typeof is array a param * @param param * @returns {boolean} */ util.isArr = function (param) { return Array.isArray(param); }; /** * Check on typeof is object a param * @param param * @returns {boolean} */ util.isObj = function (param) { return (param !== null && typeof param == 'object'); }; /** * Determine param is a number or a numeric string * @param param * @returns {boolean} */ util.isNum = function (param) { return !isNaN(param); }; // Determine whether a variable is empty util.isEmpty = function (param) { return (param === "" || param === 0 || param === "0" || param === null || param === undefined || param === false || (util.isArr(param) && param.length === 0)); }; util.isHtml = function (param) { if (util.isNode(param)) return true; return util.isNode(util.html2node(param)); }; util.isNode = function (param) { var types = [1, 9, 11]; if (typeof param === 'object' && types.indexOf(param.nodeType) !== -1) return true; else return false; }; /** * * Node.ELEMENT_NODE - 1 - ELEMENT * Node.TEXT_NODE - 3 - TEXT * Node.PROCESSING_INSTRUCTION_NODE - 7 - PROCESSING * Node.COMMENT_NODE - 8 - COMMENT * Node.DOCUMENT_NODE - 9 - DOCUMENT * Node.DOCUMENT_TYPE_NODE - 10 - DOCUMENT_TYPE * Node.DOCUMENT_FRAGMENT_NODE - 11 - FRAGMENT * Uses: Util.isNodeType(elem, 'element') */ util.isNodeType = function (param, type) { type = String((type ? type : 1)).toUpperCase(); if (typeof param === 'object') { switch (type) { case '1': case 'ELEMENT': return param.nodeType === Node.ELEMENT_NODE; break; case '3': case 'TEXT': return param.nodeType === Node.TEXT_NODE; break; case '7': case 'PROCESSING': return param.nodeType === Node.PROCESSING_INSTRUCTION_NODE; break; case '8': case 'COMMENT': return param.nodeType === Node.COMMENT_NODE; break; case '9': case 'DOCUMENT': return param.nodeType === Node.DOCUMENT_NODE; break; case '10': case 'DOCUMENT_TYPE': return param.nodeType === Node.DOCUMENT_TYPE_NODE; break; case '11': case 'FRAGMENT': return param.nodeType === Node.DOCUMENT_FRAGMENT_NODE; break; default: return false; } } else return false; }; /** * Determine param to undefined type * @param param * @returns {boolean} */ util.defined = function (param) { return typeof(param) != 'undefined'; }; /** * Javascript object to JSON data * @param data */ util.objToJson = function (data) { return JSON.stringify(data); }; /** * JSON data to Javascript object * @param data */ util.jsonToObj = function (data) { return JSON.parse(data); }; /** * Cleans the array of empty elements * @param src * @returns {Array} */ util.cleanArr = function (src) { var arr = []; for (var i = 0; i < src.length; i++) if (src[i]) arr.push(src[i]); return arr; }; /** * Return type of data as name object "Array", "Object", "String", "Number", "Function" * @param data * @returns {string} */ util.typeOf = function (data) { return Object.prototype.toString.call(data).slice(8, -1); }; /** * Convert HTML form to encode URI string * @param form * @param asObject * @returns {*} */ util.formData = function (form, asObject) { var obj = {}, str = ''; for (var i = 0; i < form.length; i++) { var f = form[i]; if (f.type == 'submit' || f.type == 'button') continue; if ((f.type == 'radio' || f.type == 'checkbox') && f.checked == false) continue; var fName = f.nodeName.toLowerCase(); if (fName == 'input' || fName == 'select' || fName == 'textarea') { obj[f.name] = f.value; str += ((str == '') ? '' : '&') + f.name + '=' + encodeURIComponent(f.value); } } return (asObject === true) ? obj : str; }; /** * HTML string convert to DOM Elements Object * @param data * @returns {*} */ util.toNode = function (data) { var parser = new DOMParser(); var node = parser.parseFromString(data, "text/xml"); console.log(node); if (typeof node == 'object' && node.firstChild.nodeType == Node.ELEMENT_NODE) return node.firstChild; else return false; }; /** * Removes duplicate values from an array * @param arr * @returns {Array} */ util.uniqueArr = function (arr) { var tmp = []; for (var i = 0; i < arr.length; i++) { if (tmp.indexOf(arr[i]) == "-1") tmp.push(arr[i]); } return tmp; }; /** * Reads entire file into a string, synchronously * This function uses XmlHttpRequest and cannot retrieve resource from different domain. * @param url * @returns {*|string|null|string} */ util.fileGetContents = function (url) { var req = null; try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { req = new XMLHttpRequest(); } catch (e) { } } } if (req == null) throw new Error('XMLHttpRequest not supported'); req.open("GET", url, false); req.send(null); return req.responseText; }; /** * Calculates the position and size of elements. * * @param elem * @returns {{y: number, x: number, width: number, height: number}} */ util.getPosition = function (elem) { var top = 0, left = 0; if (elem.getBoundingClientRect) { var box = elem.getBoundingClientRect(); var body = document.body; var docElem = document.documentElement; var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop; var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft; var clientTop = docElem.clientTop || body.clientTop || 0; var clientLeft = docElem.clientLeft || body.clientLeft || 0; top = box.top + scrollTop - clientTop; left = box.left + scrollLeft - clientLeft; return {y: Math.round(top), x: Math.round(left), width: elem.offsetWidth, height: elem.offsetHeight}; } else { //fallback to naive approach while (elem) { top = top + parseInt(elem.offsetTop, 10); left = left + parseInt(elem.offsetLeft, 10); elem = elem.offsetParent; } return {x: left, y: top, width: elem.offsetWidth, height: elem.offsetHeight}; } }; /** * Returns the coordinates of the mouse on any element * @param event * @param element * @returns {{x: number, y: number}} */ util.getMousePosition = function (event, element) { var positions = {x: 0, y: 0}; element = element || document.body; if (element instanceof HTMLElement && event instanceof MouseEvent) { if (element.getBoundingClientRect) { var rect = element.getBoundingClientRect(); positions.x = event.clientX - rect.left; positions.y = event.clientY - rect.top; } else { positions.x = event.pageX - element.offsetLeft; positions.y = event.pageY - element.offsetTop; } } return positions; }; /** * Creator of styles, return style-element or style-text. * * <pre>var style = createStyle('body','font-size:10px'); *style.add('body','font-size:10px') // added style *style.add( {'background-color':'red'} ) // added style *style.getString() // style-text *style.getObject() // style-element</pre> * * @param selector name of selector styles * @param property string "display:object" or object {'background-color':'red'} * @returns {*} return object with methods : getString(), getObject(), add() */ util.createStyle = function (selector, property) { var o = { content: '', getString: function () { return '<style rel="stylesheet">' + "\n" + o.content + "\n" + '</style>'; }, getObject: function () { var st = document.createElement('style'); st.setAttribute('rel', 'stylesheet'); st.textContent = o.content; return st; }, add: function (select, prop) { if (typeof prop === 'string') { o.content += select + "{" + ( (prop.substr(-1) == ';') ? prop : prop + ';' ) + "}"; } else if (typeof prop === 'object') { o.content += select + "{"; for (var key in prop) o.content += key + ':' + prop[key] + ';'; o.content += "}"; } return this; } }; return o.add(selector, property); }; /** * Create new NodeElement * @param tag element tag name 'p, div, h3 ... other' * @param attrs object with attributes key=value * @param inner text, html or NodeElement * @returns {Element} */ util.createElement = function (tag, attrs, inner) { var elem = document.createElement(tag); if (typeof attrs === 'object') { for (var key in attrs) elem.setAttribute(key, attrs[key]); } if (typeof inner === 'string') { elem.innerHTML = inner; } else if (typeof inner === 'object') { elem.appendChild(elem); } return elem; }; /** * Returns a random integer between min, max, if not specified the default of 0 to 100 * @param min * @param max * @returns {number} */ util.rand = function (min, max) { min = min || 0; max = max || 100; return Math.floor(Math.random() * (max - min + 1) + min); }; /** * Returns random string color, HEX format * @returns {string} */ util.randColor = function () { var letters = '0123456789ABCDEF'.split(''), color = '#'; for (var i = 0; i < 6; i++) color += letters[Math.floor(Math.random() * 16)]; return color; }; /** * Converts degrees to radians * @param deg * @returns {number} */ util.degreesToRadians = function (deg) { return (deg * Math.PI) / 180; }; /** * Converts radians to degrees * @param rad * @returns {number} */ util.radiansToDegrees = function (rad) { return (rad * 180) / Math.PI; }; /** * The calculation of the distance between points * The point is an object with properties `x` and `y` {x:100,y:100} * @param point1 * @param point2 * @returns {number} */ util.distanceBetween = function (point1, point2) { var dx = point2.x - point1.x; var dy = point2.y - point1.y; return Math.sqrt(dx * dx + dy * dy); }; /** * Encode URI params * @param data Object key=value * @returns {*} query string */ util.encodeData = function (data) { if (typeof data === 'string') return data; if (typeof data !== 'object') return ''; var convertData = []; Object.keys(data).forEach(function (key) { convertData.push(key + '=' + encodeURIComponent(data[key])); }); return convertData.join('&'); }; /** * Parse URI Request data into object * @param url * @returns {{}} */ util.parseGet = function (url) { url = url || document.location; var params = {}; var parser = document.createElement('a'); parser.href = url; if (parser.search.length > 1) { parser.search.substr(1).split('&').forEach(function (part) { var item = part.split('='); params[item[0]] = decodeURIComponent(item[1]); }); } return params; }; /** * Parse Url string/location into object * @param url * @returns {{}} */ util.parseUrl = function (url) { url = url || document.location; var params = {}; var parser = document.createElement('a'); parser.href = url; params.protocol = parser.protocol; params.host = parser.host; params.hostname = parser.hostname; params.port = parser.port; params.pathname = parser.pathname; params.hash = parser.hash; params.search = parser.search; params.get = util.parseGet(parser.search); return params; }; util.each = function (data, callback) { if (util.isArr(data)) { for (var i = 0; i < data.length; i++) callback.call(null, data[i]); } else if (util.isObj(data)) { for (var k in data) callback.call(null, k, data[k]); } else return false; }; util.ucfirst = function (string) { return string && string[0].toUpperCase() + string.slice(1); }; util.node2html = function (element) { var container = document.createElement("div"); container.appendChild(element.cloneNode(true)); return container.innerHTML; }; util.html2node = function (string) { var i, fragment = document.createDocumentFragment(), container = document.createElement("div"); container.innerHTML = string; while (i = container.firstChild) fragment.appendChild(i); return fragment.childNodes.length === 1 ? fragment.firstChild : fragment; }; util.base64encode = function (str) { var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var b64encoded = ''; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; for (var i = 0; i < str.length;) { chr1 = str.charCodeAt(i++); chr2 = str.charCodeAt(i++); chr3 = str.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = isNaN(chr2) ? 64 : (((chr2 & 15) << 2) | (chr3 >> 6)); enc4 = isNaN(chr3) ? 64 : (chr3 & 63); b64encoded += b64chars.charAt(enc1) + b64chars.charAt(enc2) + b64chars.charAt(enc3) + b64chars.charAt(enc4); } return b64encoded; }; util.base64decode = function (str) { var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var b64decoded = ''; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; str = str.replace(/[^a-z0-9\+\/\=]/gi, ''); for (var i = 0; i < str.length;) { enc1 = b64chars.indexOf(str.charAt(i++)); enc2 = b64chars.indexOf(str.charAt(i++)); enc3 = b64chars.indexOf(str.charAt(i++)); enc4 = b64chars.indexOf(str.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; b64decoded = b64decoded + String.fromCharCode(chr1); if (enc3 < 64) { b64decoded += String.fromCharCode(chr2); } if (enc4 < 64) { b64decoded += String.fromCharCode(chr3); } } return b64decoded; }; /** * Cross-browser function for the character of the event keypress: * @param event event.type must keypress * @returns {*} */ util.getChar = function (event) { if (event.which == null) { if (event.keyCode < 32) return null; return String.fromCharCode(event.keyCode) } if (event.which != 0 && event.charCode != 0) { if (event.which < 32) return null; return String.fromCharCode(event.which); } return null; }; util.Date = function () { }; util.Date.time = function (date) { "use strict"; return date instanceof Date ? date.getTime() : (new Date).getTime(); }; /** * Add days to some date * @param day number of days. 0.04 - 1 hour, 0.5 - 12 hour, 1 - 1 day * @param startDate type Date, start date * @returns {*} type Date */ util.Date.addDays = function (day, startDate) { var date = startDate ? new Date(startDate) : new Date(); date.setTime(date.getTime() + (day * 86400000)); return date; }; util.Date.daysBetween = function (date1, date2) { var ONE_DAY = 86400000, date1_ms = date1.getTime(), date2_ms = date2.getTime(); return Math.round((Math.abs(date1_ms - date2_ms)) / ONE_DAY) }; util.Storage = function (name, value) { if (!name) { return false; } else if (value === undefined) { return util.Storage.get(name); } else if (!value) { return util.Storage.remove(name); } else { return util.Storage.set(name, value); } }; util.Storage.set = function (name, value) { try { value = JSON.stringify(value) } catch (error) { } return window.localStorage.setItem(name, value); }; util.Storage.get = function (name) { var value = window.localStorage.getItem(name); if (value) try { value = JSON.parse(value) } catch (error) { } return value; }; util.Storage.remove = function (name) { return window.localStorage.removeItem(name); }; util.Storage.key = function (name) { return window.localStorage.key(key); }; // when invoked, will empty all keys out of the storage. util.Storage.clear = function () { return window.localStorage.clear(); }; // returns an integer representing the number of data items stored in the Storage object. util.Storage.length = function () { return window.localStorage.length; }; /** * возвращает cookie с именем name, если есть, если нет, то undefined * @param name * @param value */ util.Cookie = function (name, value) { "use strict"; if (value === undefined) { return util.Cookie.get(name); } else if (value === false || value === null) { util.Cookie.delete(name); } else { util.Cookie.set(name, value); } }; util.Cookie.get = function (name) { var matches = document.cookie.match(new RegExp( "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)" )); return matches ? decodeURIComponent(matches[1]) : undefined; }; /** * * @param name * @param value * @param {{}} options {expires: 0, path: '/', domain: 'site.com', secure: false} * expires - ms, Date, -1, 0 */ util.Cookie.set = function (name, value, options) { options = options || {}; var expires = options.expires; if (typeof expires == "number" && expires) { var d = new Date(); d.setTime(d.getTime() + expires * 1000); expires = options.expires = d; } if (expires && expires.toUTCString) { options.expires = expires.toUTCString(); } value = encodeURIComponent(value); var updatedCookie = name + "=" + value; for (var propName in options) { updatedCookie += "; " + propName; var propValue = options[propName]; if (propValue !== true) { updatedCookie += "=" + propValue; } } document.cookie = updatedCookie; }; util.Cookie.delete = util.Cookie.remove = function (name, option) { "use strict"; option = typeof option === 'object' ? option : {}; option.expires = -1; util.Cookie.set(name, "", option); }; util.getURLParameter = function (name) { var reg = (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]; return reg === null ? undefined : decodeURI(reg); }; /** * An asynchronous for-each loop * * @param {Array} array The array to loop through * * @param {function} done Callback function (when the loop is finished or an error occurs) * * @param {function} iterator * The logic for each iteration. Signature is `function(item, index, next)`. * Call `next()` to continue to the next item. Call `next(Error)` to throw an error and cancel the loop. * Or don't call `next` at all to break out of the loop. */ util.asyncForEach = function (array, done, iterator) { var i = 0; next(); function next(err) { if (err) done(err); else if (i >= array.length) done(); else if (i < array.length) { var item = array[i++]; setTimeout(function () { iterator(item, i - 1, next); }, 0); } } }; /** * Calls the callback in a given interval until it returns true * @param {function} callback * @param {number} interval in milliseconds */ util.waitFor = function (callback, interval) { var internalCallback = function () { if (callback() !== true) { setTimeout(internalCallback, interval); } }; internalCallback(); }; /** * Remove item from array * @param item * @param stack * @returns {Array} */ util.rmInArray = function (item, stack) { var newStack = []; for (var i = 0; i < stack.length; i++) { if (stack[i] && stack[i] != item) newStack.push(stack[i]); } return newStack; }; /** * @param text * @returns {string|void|XML} */ util.toTranslit = function (text) { return text.replace(/([а-яё])|([\s_-])|([^a-z\d])/gi, function (all, ch, space, words, i) { if (space || words) return space ? '-' : ''; var code = ch.charCodeAt(0), index = code == 1025 || code == 1105 ? 0 : code > 1071 ? code - 1071 : code - 1039, t = ['yo', 'a', 'b', 'v', 'g', 'd', 'e', 'zh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'ch', 'sh', 'shch', '', 'y', '', 'e', 'yu', 'ya']; return t[index]; }); }; window.Util = util; })(window);
raceface2nd/owncollab
owncollab_talks/js/libs/util.js
JavaScript
agpl-3.0
28,701
/* * 3dhtml Core Library * http://3dhtml.netzministerium.de * Version 1.1, 27/02/2002 * * Copyright (c) 2001, 2002 by Till Nagel and René Sander * Written by Till Nagel <till@netzministerium.de> and René Sander <rene@netzministerium.de> * Performance optimization by Fabian Guisset. * * Distributed under the terms of the GNU Lesser General Public. * (See http://3dhtml.netzministerium.de/licence.txt for details) */ // For more scripts like this visit IceBox: // i.eire-media.com // flag to print debug messages var DEBUG_3DHTML = false; // the default offset values - where the origin O(0, 0, 0) lies. var OFFSET_X_3DHTML = 300; var OFFSET_Y_3DHTML = 300; var OFFSET_Z_3DHTML = 0; // the default scene model /* * Point3D * A single point in 3-dimensional space. * This is used to represent the models' points. * */ /* * Point3D * Constructs a Point3D. * * Parameters * int x - the x position * int y - the y position * int z - the z position * int materialId - the material id * (reference to the material array of the parent model) * * Returns * a new Point3D object */ function Point3D(x, y, z, materialId) { // set point position this.x = x; this.y = y; this.z = z; // w coordinate this.w = 1; // if no material sub id has been submitted, use 0 this.materialId = materialId ? materialId : 0; return this; } Point3D.prototype.transform = Point3DTransform; Point3D.prototype.homogenize = Point3DHomogenize; Point3D.prototype.refresh = Point3DRefresh; Point3D.prototype.duplicate = Point3DDuplicate; Point3D.prototype.setPosition = Point3DSetPosition; Point3D.prototype.toString = Point3DToString; /* * Point3D.transform * Transforms the point with the given matrix. * * Parameters * Matrix matrix - the matrix to transform the point with * */ function Point3DTransform(matrix) { var aX = this.x; var aY = this.y; var aZ = this.z; var aW = this.w; this.x = aX * matrix.a00 + aY * matrix.a01 + aZ * matrix.a02 + aW * matrix.a03; this.y = aX * matrix.a10 + aY * matrix.a11 + aZ * matrix.a12 + aW * matrix.a13; this.z = aX * matrix.a20 + aY * matrix.a21 + aZ * matrix.a22 + aW * matrix.a23; this.w = aX * matrix.a30 + aY * matrix.a31 + aZ * matrix.a32 + aW * matrix.a33; } /* * Point3D.homogenize * Homogenizes the point. * */ function Point3DHomogenize() { // if not yet homogenized if (this.w != 1) { this.x /= this.w; this.y /= this.w; this.z /= this.w; this.w = 1; } } /* * Point3D.refresh * This handler is called when the point is drawn. * */ function Point3DRefresh() { } /* * Point3D.duplicate * Duplicates this Point3D. * * Returns * The new Point3D */ function Point3DDuplicate() { return new Point3D(this.x, this.y, this.z, this.materialId); } /* * Point3D.setPosition * Sets the position of this Point3D. * * Parameters * int x - the x position * int y - the y position * int z - the z position * */ function Point3DSetPosition(x, y, z) { this.x = x; this.y = y; this.z = z; this.w = 1; } /* * Point3D.toString * Returns a string representation of the point. * * Returns * A string of the format (x, y, z, w) * */ function Point3DToString() { return "(" + this.x + ", " + this.y + ", " + this.z + ", " + this.w + ")"; } // --------------------------------------------------------------------------- Model.prototype.createPointCode = ModelCreatePointCode; Model.prototype.assignLayers = ModelAssignLayers; Model.prototype.transform = ModelTransform; Model.prototype.draw = ModelDraw; Model.prototype.show = ModelShow; Model.prototype.hide = ModelHide; Model.prototype.setPoints = ModelSetPoints; Model.prototype.setPivot = ModelSetPivot; Model.prototype.duplicate = ModelDuplicate; Model.prototype.copyPointsFrom = ModelCopyPointsFrom; Model.prototype.copyPointLayerRefsFrom = ModelCopyPointLayerRefsFrom; Model.prototype.storePointValues = ModelStorePointValues; Model.prototype.restorePointValues = ModelRestorePointValues; Model.prototype.linkTo = ModelLinkTo; Model.prototype.getPointInWorldCoordinates = ModelGetPointInWorldCoordinates; Model.prototype.getCompleteSgMatrix = ModelGetCompleteSgMatrix; Model.prototype.toString = ModelToString; /* * Model * A collection of points that make up a model * */ /* * Model * Constructs a new model at (0,0,0) without any points. * * Parameters * String id - The name of the model * Material material - The mandatory material (materialId = 0) * * Returns * Model - the new model object * */ function Model(id, material) { // sets object properties this.id = id; this.points = new Array(); this.storedPointValues = new Array(); this.visibility = true; // creates new pivot (origin in model coordinates system) this.pivot = new Point3D(0, 0, 0); // creates new parentPivot (origin in parent coordinate system) // used to transform the points from model coordinate system to parent coordinate system // e.g. to the world coordinate system // this.parentPivot = new Point3D(100, 0, 0); // e.g. link to other objects // this.parentPivot = otherModel.points[ pointIndex ]; this.parentModel = null; this.parentPointIndex = null; // a scene graph matrix to store the transformations this.sgMatrix = rawMatrix; // creates an array to store the material objects this.materials = new Array(); // sets the first material this.materials[0] = material; // links the model to the default scene // therefore every model has this default scene // which is not drawable and marks the end of the scene graph. if (this.id != "defaultScene3dhtml") { this.linkTo(defaultScene3dhtmlModel, 0); } return this; } /* * Model.createPointCode * Writes all layers into the document (and also stores references * to the DIVs in the respective Point3D objects) * The naming convention used for the DIV elements: * pnt + {model-ID} + {point-ID} * * IMPLEMENTATION NOTES * The HTML is written directly within the method, preceeding * the initialization of the corresponding points with their * respective layer references. This is not left to the user. * */ function ModelCreatePointCode() { var s = ""; var i = 0; var length = this.points.length; // creates HTML code for all points for (i = 0; i < length; i++) { // DIV with unique id s += '<div id="p' + this.id + i + '" style="position:absolute;z-Index:0">'; // the DIV content is determined by the material element assigned to the point. // adds the material's body to the output string if the material exists m = this.materials[this.points[i].materialId]; // if point has a materialId not defined in the material collection of the model // the point is not visible, i.e. an empty layer. s += m ? m : ""; // closes the DIV s += "</div>\n"; } // writes the divs into the document document.write(s); // Netscape 4.x cannot access the layers we've just written instantly. // Assigns layer references for the written points // (except for Netscape where this has to be done manually in the onLoad-handler) if (!ns) { this.assignLayers(); } } /* * Model.assignLayers * Assigns layer references for all points of the model. * */ function ModelAssignLayers() { if (!this.layersAssigned) { var i = 0; var length = this.points.length; // assigns layer references to the respective point objects for (i = 0; i < length; i++) { this.points[i].lyr = new LyrObj( "p" + this.id + i ); } this.layersAssigned = true; } } /* * Model.transform * Transforms the model with the given matrix. * * Parameters * Matrix matrx - the transformation matrix (e.g. a rotation matrix) * */ function ModelTransform(matrix) { var i = 0; var length = this.points.length; // transforms each single point for (i = 0; i < length; i++) { this.points[i].transform(matrix); this.points[i].homogenize(); } // transforms the pivot // see pivotTest3d_neuer.html //this.pivot.transform(matrix); //this.pivot.homogenize(); // adds the transformation to the scene graph // #1 premultiplication // var tmpMatrix = matrix.getCopy(); // Avoid a matrix copy // tmpMatrix.compose(this.sgMatrix); // this.sgMatrix = tmpMatrix; this.sgMatrix = matrix.composeNoModification(this.sgMatrix); // #1 postmultiplication //this.sgMatrix.compose(matrix); } /* * Model.draw * Draws the points of the model (ie positioning the point layers on the screen). * */ function ModelDraw() { // don't draw invisible models to speed up performance // all child objects will be drawn correctly, though. if (!this.visibility) return; // model-coordinates to world-coordinates mapping var completeSgMatrix = this.parentModel.getCompleteSgMatrix(); //var completeSgMatrix = this.getCompleteSgMatrix(); //var completeSgMatrix = this.parentModel.sgMatrix; //alert(this + "\nsgMatrix=\n" + this.sgMatrix + "\nparent: " + this.parentModel + "\nparent.sgMatrix:\n" + this.parentModel.sgMatrix + "\ncompleteSgMatrix:\n" + completeSgMatrix); this.storePointValues(); var pivotMatrix = rawMatrix.translateNoModification(this.pivot.x,this.pivot.y,this.pivot.z); // var m2wMatrix = new Matrix(); // m2wMatrix.compose(completeSgMatrix); // m2wMatrix.compose(pivotMatrix); var tempMatrix = rawMatrix.composeNoModification(completeSgMatrix); tempMatrix = tempMatrix.composeNoModification(pivotMatrix); this.transform(tempMatrix); //alert(this + "\nsgMatrix=\n" + this.sgMatrix + "\nparent: " + this.parentModel + "\nparent.sgMatrix:\n" + this.parentModel.sgMatrix + "\ncompleteSgMatrix:\n" + completeSgMatrix); var length = this.points.length; // draws all points for (dw = 0; dw < length; dw++) { p = this.points[dw]; // sets the layer properties p.lyr.setPos("left", p.x); p.lyr.setPos("top", p.y); p.lyr.setzIndex(p.z + OFFSET_Z_3DHTML); // refreshs the material if method is available m = this.materials[p.materialId]; if (m && m.refresh) m.refresh(p); } // discards the wc model instead of backtransforming // (other approach: transform back in model coordinates: this.transform(-m2wMatrix);) this.restorePointValues(); } /* * Model.show * Shows the model by setting all of its points visible * */ function ModelShow() { p = this.points; var length = p.length; for (i = 0; i < length; i++) { p[i].lyr.show(); } this.visibility = true; } /* * Model.hide * Hides the model by setting all of its points invisible * */ function ModelHide() { p = this.points; var length = p.length; for (i = 0; i < length; i++) { p[i].lyr.hide(); } this.visibility = false; } /* * Model.linkTo * Assigns a parent model to this model. * Links this model as child to the parentModel to build a scene graph * All children will be drawn from their parent model. * * Parameters * Model parentModel - the model to link to * int pointIndex - the index of the parent model's point that this model is linked to. * NOTE: THE pointIndex PARAMETER IS NOT USED AT THE MOMENT * */ function ModelLinkTo(parentModel, pointIndex) { // stores the new parent model reference this.parentModel = parentModel; /* // uses the point (points[pointIndex]) to translate the child object // so the point is the child object's new pivot. // (if no point parameter the the pivot of the parent model is used) if (pointIndex) { var pivm = new Matrix(); with (this.parentModel.points[pointIndex]) { pivm.translate(x, y, z); // translates with the point positions of the moment (all following trans won't work) } this.transform(pivm); } //this.parentPointIndex = pointIndex; // old: not in use anymore */ } /* * Model.setPoints * Sets the points array of the model. * * Parameters * Point3D[] newPoints - an array containing the new model points * */ function ModelSetPoints(newPoints) { this.points = newPoints; //this.storePointValues(); } /* * Model.setPivot * Sets the model's pivot. * * Parameters * Point3D pivot - the new pivot * */ function ModelSetPivot(pivot) { // sets the pivot // will be used to translate at Model.draw(); this.pivot = pivot; /* // other approach: // renders new point coordinates (calculates pivot into the points) var length = this.points.length; for (i = 0; i < length; i++) { this.points[i].x = pivot.x - this.points[i].x; this.points[i].y = pivot.y - this.points[i].y this.points[i].z = pivot.z - this.points[i].z } */ } /* * Model.copyPointsFrom * Copies the points from the source model into this model. * To preserve the layer reference this method just copies * the position attributes. * * Parameters * Model source - The model to copy the points from * */ function ModelCopyPointsFrom( source ) { var p = source.points; var length = p.length; for ( var i = 0; i < length; i++ ) { this.points[i].x = p[i].x; this.points[i].y = p[i].y; this.points[i].z = p[i].z; this.points[i].w = p[i].w; } } /* * Model.copyPointLayerRefsFrom * Copies the layer references from the source model into this model. * Combined with copyPointsFrom it is used to create the scene graph. * * Parameters * Model source - the source Model * */ function ModelCopyPointLayerRefsFrom( source ) { var p = source.points; var length = p.length; for ( var i = 0; i < length; i++ ) { //this.points[i].lyr = p[i].lyr; } } /* * Model.duplicate * Duplicates a model. * * Parameters * String newId - the id of the new model. * * Returns * Model - the dup model. */ function ModelDuplicate( newId ) { // if there is no newId create a new one // (known bug: duplicating the same model twice // without specifying a newId results in two // objects with same id) if (newId == null) newId = this.id + "Dup"; m = new Model(newid, new Material("")); // deepcopy model.points into m.points var length = this.points.length; for ( var i = 0; i < length; i++ ) { m.points[i] = this.points[i]; } // deepcopy model.materials into m.naterials for (i = 0; i < length; i++) { m.materials[i] = this.materials[i]; } m.pivot = new Point3D(this.pivot); return m; } /* * Model.storePointValues * Stores the values of the points to restore them later. * */ function ModelStorePointValues() { var i = 0; var length = this.points.length; for (i = 0; i < length; i++ ) { this.storedPointValues[i] = this.points[i].duplicate(); } this.sgMatrixCopy = this.sgMatrix; //this.sgMatrixCopy.setMatrixValues(this.sgMatrix); } /* * Model. restorePointValues * Restores values of stored points. * */ function ModelRestorePointValues() { var i = 0; var length = this.points.length; for (i = 0; i < length; i++ ) { this.points[i].x = this.storedPointValues[i].x; this.points[i].y = this.storedPointValues[i].y; this.points[i].z = this.storedPointValues[i].z; } this.sgMatrix = this.sgMatrixCopy; } /* * Model.getPointInWorldCoordinates * Returns one of the model's points (specified by pointIndex, the point * number) in world coordinates. This does not alter the actual point. * * Parameters * int pointIndex - the index number of the point to convert * * Returns * Point3D - The point in world coordinates * */ function ModelGetPointInWorldCoordinates( pointIndex ) { var pwc = new Point3D(); pwc.x = this.points[pointIndex].x; pwc.y = this.points[pointIndex].y; pwc.z = this.points[pointIndex].z; pwc.w = this.points[pointIndex].w; //var pmid = (this.parentModel != null) ? this.parentModel.id : "null"; //alert(this.id + ".getPointInWC()\n parentModel=" + pmid + "\n expr=" + (this.parentModel != null) + "\n ppi=" + this.parentPointIndex); if (this.parentModel != null) { var ppwc = this.parentModel.getPointInWorldCoordinates( this.parentPointIndex ); pwc.x += ppwc.x; pwc.y += ppwc.y; pwc.z += ppwc.z; pwc.w += ppwc.w; } return pwc; } /* * Model.getCompleteSgMatrix * X * * Returns * Matrix - the scene graph matrix * */ function ModelGetCompleteSgMatrix() { var completeSgMatrix = this.sgMatrix; if (this.parentModel != null) { completeSgMatrix = this.parentModel.getCompleteSgMatrix(); //completeSgMatrix.compose(this.sgMatrix); var tmpMatrix = completeSgMatrix.getCopy(); tmpMatrix.compose(this.sgMatrix); completeSgMatrix = tmpMatrix; } return completeSgMatrix; } /* * Model.toString * This returns a string of the format * {modelId} * @{pivot} * {list of materials} * {list of points} * * Returns * String - a string representation of the model. */ function ModelToString() { var s = ""; // concatenates main attributes of the model s += this.id + "\n"; s += "@" + this.pivot + "\n"; s += this.materials + "\n"; for (i = 0; i < this.points.length; i++) { s += this.points[i].toString() + "\n"; } return s; } // --------------------------------------------------------------------------- /* * Matrix * A matrix object used to define transformations. * */ /** * Matrix * Constructs a 4x4 Matrix you will need to transform points. * Preconfigured as identity matrix, i.e. * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * 0 0 0 1 * * Returns * a new Matrix object */ function Matrix() { // sets identity matrix this.a01 = this.a02 = this.a03 = 0; this.a10 = this.a12 = this.a13 = 0; this.a20 = this.a21 = this.a23 = 0; this.a30 = this.a31 = this.a32 = 0; this.a00 = this.a11 = this.a22 = this.a33 = 1; return this; } Matrix.prototype.rotateX = MatrixRotateX; Matrix.prototype.rotateY = MatrixRotateY; Matrix.prototype.rotateZ = MatrixRotateZ; Matrix.prototype.scale = MatrixScale; Matrix.prototype.translate = MatrixTranslate; Matrix.prototype.translateNoModification = MatrixTranslateNoModification; Matrix.prototype.compose = MatrixCompose; Matrix.prototype.composeNoModification = MatrixComposeNoModification; Matrix.prototype.getCopy = MatrixGetCopy; Matrix.prototype.setMatrixValues = MatrixSetMatrixValues; Matrix.prototype.toString = MatrixToString; /* * Matrix.rotateX * Rotates along the x-axis with phi degree. * * Parameters * float phi - the radiant value to rotate with * */ function MatrixRotateX(phi) { var myMatrix = new Matrix(); myMatrix.a00 = 1; myMatrix.a01 = myMatrix.a02 = myMatrix.a03 = 0; myMatrix.a10 = 0; myMatrix.a11 = Math.cos(phi); myMatrix.a12 = -Math.sin(phi); myMatrix.a13 = 0; myMatrix.a20 = 0; myMatrix.a21 = Math.sin(phi); myMatrix.a22 = Math.cos(phi); myMatrix.a23 = 0; myMatrix.a30 = myMatrix.a31 = myMatrix.a32 = 0; myMatrix.a33 = 1; // old //this.compose(myMatrix); // new myMatrix.compose(this); this.setMatrixValues(myMatrix); } /* * Matrix.rotateY * Rotates along the y-axis with phi degree. * * Parameters * float phi - the radiant value to rotate with * */ function MatrixRotateY(phi) { var myMatrix = new Matrix(); myMatrix.a00 = Math.cos(phi); myMatrix.a01 = 0; myMatrix.a02 = Math.sin(phi); myMatrix.a03 = 0; myMatrix.a10 = myMatrix.a13 = myMatrix.a12 = 0; myMatrix.a11 = 1; myMatrix.a20 = -Math.sin(phi); myMatrix.a21 = 0; myMatrix.a22 = Math.cos(phi); myMatrix.a23 = 0; myMatrix.a30 = myMatrix.a31 = myMatrix.a32 = 0; myMatrix.a33 = 1; myMatrix.compose(this); this.setMatrixValues(myMatrix); } /* * Matrix.rotateZ * Rotates along the z-axis with phi degree. * * Parameters * float phi - the radiant value to rotate with * */ function MatrixRotateZ(phi) { var myMatrix = new Matrix(); myMatrix.a00 = Math.cos(phi); myMatrix.a01 = -Math.sin(phi); myMatrix.a02 = 0; myMatrix.a03 = 0; myMatrix.a10 = Math.sin(phi); myMatrix.a11 = Math.cos(phi); myMatrix.a12 = 0; myMatrix.a13 = 0; myMatrix.a20 = myMatrix.a21 = 0; myMatrix.a22 = 1; myMatrix.a23 = 0; myMatrix.a30 = myMatrix.a31 = myMatrix.a32 = 0; myMatrix.a33 = 1; myMatrix.compose(this); this.setMatrixValues(myMatrix); } /* * Matrix.scale * Scale with the scale factors. * * Parameters * float sx - the x scale factor * float sy - the y scale factor * float sz - the z scale factor * */ function MatrixScale(sx, sy, sz) { var myMatrix = new Matrix(); myMatrix.a00 = sx; myMatrix.a01 = myMatrix.a02 = myMatrix.a03 = 0; myMatrix.a10 = 0; myMatrix.a11 = sy; myMatrix.a12 = myMatrix.a13 = 0; myMatrix.a20 = myMatrix.a21 = 0; myMatrix.a22 = sz; myMatrix.a23 = 0; myMatrix.a30 = myMatrix.a31 = myMatrix.a32 = 0; myMatrix.a33 = 1; myMatrix.compose(this); this.setMatrixValues(myMatrix); } /* * Matrix.translate * Translate with the translation values. * * Parameters * float dx - the x value to translate with * float dy - the y value to translate with * float dz - the z value to translate with * */ function MatrixTranslate(dx, dy, dz) { var myMatrix = new Matrix(); myMatrix.a00 = 1; myMatrix.a01 = myMatrix.a02 = 0; myMatrix.a03 = dx; myMatrix.a10 = 0; myMatrix.a11 = 1; myMatrix.a12 = 0; myMatrix.a13 = dy; myMatrix.a20 = myMatrix.a21 = 0; myMatrix.a22 = 1; myMatrix.a23 = dz; myMatrix.a30 = myMatrix.a31 = myMatrix.a32 = 0; myMatrix.a33 = 1; myMatrix.compose(this); this.setMatrixValues(myMatrix); } function MatrixTranslateNoModification(dx, dy, dz) { var myMatrix = new Matrix(); myMatrix.a00 = 1; myMatrix.a01 = myMatrix.a02 = 0; myMatrix.a03 = dx; myMatrix.a10 = 0; myMatrix.a11 = 1; myMatrix.a12 = 0; myMatrix.a13 = dy; myMatrix.a20 = myMatrix.a21 = 0; myMatrix.a22 = 1; myMatrix.a23 = dz; myMatrix.a30 = myMatrix.a31 = myMatrix.a32 = 0; myMatrix.a33 = 1; myMatrix = myMatrix.composeNoModification(this); return myMatrix; } /* * Matrix.compose * Composes this matrix with the given matrix m * * Parameters * Matrix m - the matrix to compose with * */ function MatrixCompose(m) { var r, c; var myMatrix = new Matrix(); // matrices multiplication for(r = 0; r < 4; r++) for(c = 0; c < 4; c++) { myMatrix["a" + r + c] = this["a" + r + "0"] * m["a0" + c] + this["a" + r + "1"] * m["a1" + c] + this["a" + r + "2"] * m["a2" + c] + this["a" + r + "3"] * m["a3" + c]; } // copies the new matrix to this for(r = 0; r < 4; r++) { for(c = 0; c < 4; c++) { this["a" + r + c] = myMatrix["a" + r + c]; } } } /* * Matrix.composeNoModification * Composes this matrix with the given matrix m, but do not modify "this". * Return a copy instead. * * Parameters * Matrix m - the matrix to compose with * * Returns * Matrix myMatrix - the copy of the composed matrix. */ function MatrixComposeNoModification(m) { var r, c; var myMatrix = new Matrix(); // matrices multiplication for(r = 0; r < 4; r++) for(c = 0; c < 4; c++) { myMatrix["a" + r + c] = this["a" + r + "0"] * m["a0" + c] + this["a" + r + "1"] * m["a1" + c] + this["a" + r + "2"] * m["a2" + c] + this["a" + r + "3"] * m["a3" + c]; } return myMatrix; } /* * Matrix.setMatrixValues * Sets the values of this matrix to the values of the sourceMatrix. * (Ergo it copies them) * * Parameters * Matrix sourceMatrix - the matrix to copy the values from */ function MatrixSetMatrixValues(sourceMatrix) { with (sourceMatrix) { this.a00 = a00; this.a01 = a01; this.a02 = a02; this.a03 = a03; this.a10 = a10; this.a11 = a11; this.a12 = a12; this.a13 = a13; this.a20 = a20; this.a21 = a21; this.a22 = a22; this.a23 = a23; this.a30 = a30; this.a31 = a31; this.a32 = a32; this.a33 = a33; } } /* * Matrix.getCopy * Copies the values of this matrix to a new one and returns it. * * Returns * Matrix - a new Matrix with values copied from this Matrix. * */ function MatrixGetCopy() { var destMatrix = new Matrix(); with (destMatrix) { a00 = this.a00; a01 = this.a01; a02 = this.a02; a03 = this.a03; a10 = this.a10; a11 = this.a11; a12 = this.a12; a13 = this.a13; a20 = this.a20; a21 = this.a21; a22 = this.a22; a23 = this.a23; a30 = this.a30; a31 = this.a31; a32 = this.a32; a33 = this.a33; } return destMatrix; } /* * Matrix.toString * Returns a string representation of the matrix * * Returns * a string representation of the Matrix object, * e.g. * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * 0 0 0 1 * */ function MatrixToString() { var tab = "\t"; return this.a00 + tab + this.a01 + tab + this.a02 + tab + this.a03 + "\n" + this.a10 + tab + this.a11 + tab + this.a12 + tab + this.a13 + "\n" + this.a20 + tab + this.a21 + tab + this.a22 + tab + this.a23 + "\n" + this.a30 + tab + this.a31 + tab + this.a32 + tab + this.a33 + "\n"; } // --------------------------------------------------------------------------- /* * Material * A material has a body, basically containing a string with HTML code * (which will make up the content of a point's DIV). Additionally it * has a JavaScript statement - the refresh() method - that is called * when drawing the points, so the material appearance can be changed * by changing what is happening in the DIV. * */ /* * Material * Constructs a Material. * * Parameters * String body - an HTML snippet (e.g. '<font color=red>+</font>') * Function refresh - the function to call if model was drawn * * Returns * Material - The new Material object * */ function Material(body, refresh) { this.body = body; // stores reference to the specified refresh method this.refresh = refresh; return this; } Material.prototype.toString = MaterialToString; /* * Material.toString * Returns the string representation of this Material. * * Returns * String - the Material's body * */ function MaterialToString() { return this.body; } // --------------------------------------------------------------------------- /* * Modulator * This is basically an object encapsulating a function of some sort. It can * be used to influence parameters such as the scaling of a model, its movement * or the color of a point. * * For an example, see implementation of MouseModulator.js. * */ /** * Modulator * Constructs a Modulator. * * Returns * a new Modulator object */ function Modulator() { this.matrix = new Matrix(); this.getMatrix = ModulatorGetMatrix; this.animate = ModulatorAnimate; return this; } /* * Modulator.getMatrix * * Returns * the modulator's internal matrix */ function ModulatorGetMatrix() { return this.matrix; } /* * Modulator.animate * The (empty) default implementation of the animate method, * which is used in modulators to update their internal matrix. * */ function ModulatorAnimate() { } // --------------------------------------------------------------------------- /* * Helper functions * */ /* * normalize * Normalizes a value to project it to a given range. * Example: v=5, source=[1, 10], destination=[1, 5] * result = 2.22 * * Parameters * float v - the value to project (within source range) * float sMin - the min value of the source range * float sMax - the max value of the source range * float dMin - the min value of the destination range * float dMax - the max value of the destination range * * Returns * float - The normalized value */ function normalize(v, sMin, sMax, dMin, dMax) { return Math.min(Math.max( ((dMax - dMin) / (sMax - sMin)) * ((v - sMin) + dMin), dMin), dMax); } /* * degToRad * Converts degree value to radiant value. * * Parameters * float v - The degree value * * Returns * float - The rad value */ function degToRad(v) { return v / (360 / (2 * Math.PI)); } /* * radToDeg * Converts radiant value to degree value. * * Parameters * float v - The rad value * * Returns * float - The degree value */ function radToDeg(v) { return v * (360 / (2 * Math.PI)); } var rawMatrix = new Matrix(); var defaultScene3dhtmlModel = new Model("defaultScene3dhtml"); defaultScene3dhtmlModel.setPoints( new Array( new Point3D(0, 0, 0) ) ); // translates the default scene model to its start position // e.g. use constants or calculate center of the screen var ds3dhtmlMatrix=new Matrix(); ds3dhtmlMatrix.translate(OFFSET_X_3DHTML, OFFSET_Y_3DHTML, OFFSET_Z_3DHTML); defaultScene3dhtmlModel.transform(ds3dhtmlMatrix);
SoHiggo/3dhtml
js/3dhtml.js
JavaScript
lgpl-2.1
27,963
if (Highcharts != null) { if (Highcharts.charts == null) { Highcharts.charts = {}; } if (Highcharts.getChart == null) { Highcharts.getChart = function(chartId, containerId) { var opts = Highcharts.charts[chartId]; opts.chart.renderTo = containerId; return opts; } } Highcharts.charts['basicTimeSeries'] = { chart: { renderTo: 'container', type: 'spline', animation: false }, title: { text: 'Sentiment' }, xAxis: { type: 'datetime' }, yAxis: { title: { text: 'Coefficient (m)' } }, tooltip: { shared: true }, legend: { enabled: false } } }
secondfoundation/Second-Foundation-Src
src/haruspex/nodejs/websocket/public/js/charts/basicTimeSeries.js
JavaScript
lgpl-2.1
623
asynctest( 'browser.tinymce.plugins.table.ClipboardTest', [ 'ephox.agar.api.Pipeline', 'ephox.mcagar.api.LegacyUnit', 'ephox.mcagar.api.TinyLoader', 'tinymce.core.util.Tools', 'tinymce.plugins.table.Plugin', 'tinymce.themes.modern.Theme' ], function (Pipeline, LegacyUnit, TinyLoader, Tools, Plugin, Theme) { var success = arguments[arguments.length - 2]; var failure = arguments[arguments.length - 1]; var suite = LegacyUnit.createSuite(); Plugin(); Theme(); var cleanTableHtml = function (html) { return html.replace(/<p>(&nbsp;|<br[^>]+>)<\/p>$/, ''); }; var selectRangeXY = function (editor, start, end) { start = editor.$(start)[0]; end = editor.$(end)[0]; editor.fire('mousedown', { target: start }); editor.fire('mouseover', { target: end }); editor.fire('mouseup', { target: end }); }; suite.test("mceTablePasteRowBefore command", function (editor) { editor.setContent( '<table>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>2</td><td>3</td></tr>' + '</table>' ); LegacyUnit.setSelection(editor, 'tr:nth-child(1) td', 0); editor.execCommand('mceTableCopyRow'); LegacyUnit.setSelection(editor, 'tr:nth-child(2) td', 0); editor.execCommand('mceTablePasteRowBefore'); LegacyUnit.equal( cleanTableHtml(editor.getContent()), '<table>' + '<tbody>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>2</td><td>3</td></tr>' + '</tbody>' + '</table>' ); LegacyUnit.setSelection(editor, 'tr:nth-child(2) td', 0); editor.execCommand('mceTablePasteRowBefore'); LegacyUnit.equal( cleanTableHtml(editor.getContent()), '<table>' + '<tbody>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>2</td><td>3</td></tr>' + '</tbody>' + '</table>' ); }); suite.test("mceTablePasteRowAfter command", function (editor) { editor.setContent( '<table>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>2</td><td>3</td></tr>' + '</table>' ); LegacyUnit.setSelection(editor, 'tr:nth-child(1) td', 0); editor.execCommand('mceTableCopyRow'); LegacyUnit.setSelection(editor, 'tr:nth-child(2) td', 0); editor.execCommand('mceTablePasteRowAfter'); LegacyUnit.equal( cleanTableHtml(editor.getContent()), '<table>' + '<tbody>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>2</td><td>3</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '</tbody>' + '</table>' ); LegacyUnit.setSelection(editor, 'tr:nth-child(2) td', 0); editor.execCommand('mceTablePasteRowAfter'); LegacyUnit.equal( cleanTableHtml(editor.getContent()), '<table>' + '<tbody>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>2</td><td>3</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '</tbody>' + '</table>' ); }); suite.test("mceTablePasteRowAfter from merged row source", function (editor) { editor.setContent( '<table>' + '<tbody>' + '<tr><td colspan="2">1 2</td><td rowspan="2">3</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '</tbody>' + '</table>' ); LegacyUnit.setSelection(editor, 'tr:nth-child(1) td', 0); editor.execCommand('mceTableCopyRow'); LegacyUnit.setSelection(editor, 'tr:nth-child(2) td:nth-child(2)', 0); editor.execCommand('mceTablePasteRowAfter'); LegacyUnit.equal( cleanTableHtml(editor.getContent()), '<table>' + '<tbody>' + '<tr><td colspan="2">1 2</td><td rowspan="2">3</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td colspan="2">1 2</td><td>3</td></tr>' + '</tbody>' + '</table>' ); }); suite.test("mceTablePasteRowAfter from merged row source to merged row target", function (editor) { editor.setContent( '<table>' + '<tbody>' + '<tr><td colspan="2">1 2</td><td rowspan="2">3</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '</tbody>' + '</table>' ); LegacyUnit.setSelection(editor, 'tr:nth-child(1) td', 0); editor.execCommand('mceTableCopyRow'); LegacyUnit.setSelection(editor, 'tr:nth-child(1) td', 0); editor.execCommand('mceTablePasteRowAfter'); LegacyUnit.equal( cleanTableHtml(editor.getContent()), '<table>' + '<tbody>' + '<tr><td colspan="2">1 2</td><td>3</td></tr>' + '<tr><td colspan="2">1 2</td><td>3</td></tr>' + '<tr><td>1</td><td>2</td><td>&nbsp;</td></tr>' + '</tbody>' + '</table>' ); }); suite.test("mceTablePasteRowAfter to wider table", function (editor) { editor.setContent( '<table>' + '<tbody>' + '<tr><td>1a</td><td>2a</td><td>3a</td></tr>' + '</tbody>' + '</table>' + '<table>' + '<tbody>' + '<tr><td>1b</td><td>2b</td><td>3b</td><td>4b</td></tr>' + '</tbody>' + '</table>' ); LegacyUnit.setSelection(editor, 'table:nth-child(1) tr:nth-child(1) td', 0); editor.execCommand('mceTableCopyRow'); LegacyUnit.setSelection(editor, 'table:nth-child(2) td', 0); editor.execCommand('mceTablePasteRowAfter'); LegacyUnit.equal( cleanTableHtml(editor.getContent()), '<table>' + '<tbody>' + '<tr><td>1a</td><td>2a</td><td>3a</td></tr>' + '</tbody>' + '</table>' + '<table>' + '<tbody>' + '<tr><td>1b</td><td>2b</td><td>3b</td><td>4b</td></tr>' + '<tr><td>1a</td><td>2a</td><td>3a</td><td>&nbsp;</td></tr>' + '</tbody>' + '</table>' ); }); suite.test("mceTablePasteRowAfter to narrower table", function (editor) { editor.setContent( '<table>' + '<tbody>' + '<tr><td>1a</td><td>2a</td><td>3a</td><td>4a</td><td>5a</td></tr>' + '<tr><td>1a</td><td colspan="3">2a</td><td>5a</td></tr>' + '</tbody>' + '</table>' + '<table>' + '<tbody>' + '<tr><td>1b</td><td>2b</td><td>3b</td></tr>' + '</tbody>' + '</table>' ); selectRangeXY(editor, 'table:nth-child(1) tr:nth-child(1) td:nth-child(1)', 'table:nth-child(1) tr:nth-child(2) td:nth-child(3)'); editor.execCommand('mceTableCopyRow'); LegacyUnit.setSelection(editor, 'table:nth-child(2) tr td', 0); editor.execCommand('mceTablePasteRowAfter'); LegacyUnit.equal( cleanTableHtml(editor.getContent()), '<table>' + '<tbody>' + '<tr><td>1a</td><td>2a</td><td>3a</td><td>4a</td><td>5a</td></tr>' + '<tr><td>1a</td><td colspan="3">2a</td><td>5a</td></tr>' + '</tbody>' + '</table>' + '<table>' + '<tbody>' + '<tr><td>1b</td><td>2b</td><td>3b</td></tr>' + '<tr><td>1a</td><td>2a</td><td>3a</td></tr>' + '<tr><td>1a</td><td colspan="2">2a</td></tr>' + '</tbody>' + '</table>' ); }); suite.test("Copy/paste several rows with multiple rowspans", function (editor) { editor.setContent( '<table>' + '<tbody>' + '<tr><td rowspan="2">1</td><td>2</td><td>3</td></tr>' + '<tr><td>2</td><td rowspan="3">3</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '</tbody>' + '</table>' ); selectRangeXY(editor, 'table tr:nth-child(1) td:nth-child(1)', 'table tr:nth-child(3) td:nth-child(2)'); editor.execCommand('mceTableCopyRow'); LegacyUnit.setSelection(editor, 'table tr:nth-child(4) td', 0); editor.execCommand('mceTablePasteRowAfter'); LegacyUnit.equal( cleanTableHtml(editor.getContent()), '<table>' + '<tbody>' + '<tr><td rowspan="2">1</td><td>2</td><td>3</td></tr>' + '<tr><td>2</td><td rowspan="3">3</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td rowspan="2">1</td><td>2</td><td>3</td></tr>' + '<tr><td>2</td><td rowspan="2">3</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '</tbody>' + '</table>' ); }); suite.test("row clipboard api", function (editor) { var clipboardRows; function createRow(cellContents) { var tr = editor.dom.create('tr'); Tools.each(cellContents, function (html) { tr.appendChild(editor.dom.create('td', null, html)); }); return tr; } editor.setContent( '<table>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>2</td><td>3</td></tr>' + '</table>' ); LegacyUnit.setSelection(editor, 'tr:nth-child(1) td', 0); editor.execCommand('mceTableCopyRow'); clipboardRows = editor.plugins.table.getClipboardRows(); LegacyUnit.equal(clipboardRows.length, 1); LegacyUnit.equal(clipboardRows[0].tagName, 'TR'); editor.plugins.table.setClipboardRows(clipboardRows.concat([ createRow(['a', 'b']), createRow(['c', 'd']) ])); LegacyUnit.setSelection(editor, 'tr:nth-child(2) td', 0); editor.execCommand('mceTablePasteRowAfter'); LegacyUnit.equal( cleanTableHtml(editor.getContent()), '<table>' + '<tbody>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>2</td><td>3</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>a</td><td>b</td></tr>' + '<tr><td>c</td><td>d</td></tr>' + '</tbody>' + '</table>' ); }); TinyLoader.setup(function (editor, onSuccess, onFailure) { Pipeline.async({}, suite.toSteps(editor), onSuccess, onFailure); }, { plugins: 'table', indent: false, valid_styles: { '*': 'width,height,vertical-align,text-align,float,border-color,background-color,border,padding,border-spacing,border-collapse' }, skin_url: '/project/src/skins/lightgray/dist/lightgray' }, success, failure); } );
aduth/tinymce
src/plugins/table/src/test/js/browser/ClipboardTest.js
JavaScript
lgpl-2.1
10,535
import { defineComponent, mount, Html } from 'js-surface'; import { Component } from 'js-surface/common'; const { br, div } = Html; const Parent = defineComponent({ displayName: 'Parent', properties: { masterValue: { type: String, defaultValue: 'default-value' } }, childContext: ['value'], main: class extends Component { getChildContext() { return { value: this.props.masterValue }; } render() { return ( div(null, div(null, `Provided value: ${this.props.masterValue}`), br(), div(null, ChildFunctionBased(), ChildClassBased(), ChildFunctionBased({ value: 'with explicit value' }), ChildClassBased({ value: 'with another explicit value' }))) ); } } }); const ChildFunctionBased = defineComponent({ displayName: 'ChildFunctionBased', properties: { value: { type: String, inject: true, defaultValue: 'default value' } }, render(props) { return ( div(null, `ChildFunctionBased(${props.value})`) ); } }); const ChildClassBased = defineComponent({ displayName: 'ChildClassBased', properties: { value: { type: String, inject: true, defaultValue: 'default value' } }, main: class extends Component { render () { return ( div(null, `ChildClassBased(${this.props.value})`) ); } } }); mount(Parent({ masterValue: 'the injected value' }), 'main-content');
mcjazzyfunky/js-surface
boxroom/archive/backup-js-surface-2018-02-19/src/demo/class-based/injection/injection.js
JavaScript
lgpl-3.0
1,881
'use strict'; // dependencies var DataManager = require('./../../core/DataManager'); var Enums = require('./../../core/Enums'); var makeTokenParameters = require('../../core/Utils').makeTokenParameters; /** * It exports a object with StaticDataSeries controllers (get/new/edit) * @return {Object} A object with controllers with http method as key (get/new/edit) */ module.exports = function(app) { return { get: function(request, response) { var parameters = makeTokenParameters(request.query.token, app); response.render('configuration/staticData', Object.assign({}, parameters, {"Enums": Enums})); }, new: function(request, response) { response.render('configuration/dataset', {type: "static", "Enums": Enums}); }, edit: function(request, response) { var dataSeriesId = request.params.id; DataManager.getDataSeries({id: dataSeriesId}).then(function(dataSeriesResult) { response.render('configuration/dataset', {type: "static", "Enums": Enums, dataSeries: {input: dataSeriesResult.rawObject()}}); }).catch(function(err) { response.render('base/404'); }) } }; };
pauloremoli/terrama2
webapp/controllers/configuration/StaticDataSeries.js
JavaScript
lgpl-3.0
1,157
var searchData= [ ['tester',['tester',['../classcontrol_vue.html#a92d898224293b741e5c6d3a3576a2193',1,'controlVue']]], ['testerappuyer',['testerAppuyer',['../class_vue.html#a7fb0d20950a6596a3eef78e244628682',1,'Vue']]], ['testerdossier',['testerDossier',['../classcontrol_vue.html#a630d60f73a0cdb77d2f7f92050983da7',1,'controlVue']]], ['testerfic',['testerFic',['../classcontrol_vue.html#a8139fd2a944a2fca901809edd2468a1e',1,'controlVue']]], ['teststruct',['testStruct',['../classurl_validator.html#a337a9edaa44e76bda5a7ed3a345b0b78',1,'urlValidator']]], ['testurls',['testUrls',['../classparseur_fic.html#ad2c99c1283f03ac105a2927aa9826021',1,'parseurFic']]], ['testvie',['testVie',['../classurl_validator.html#a9993e82ddcaf00c655e3ad9221a10232',1,'urlValidator']]] ];
emeric254/ACSIGroupe35Curling
doc/html/search/functions_74.js
JavaScript
unlicense
783
import { useQuery } from '@apollo/react-hooks' import { makeStyles } from '@material-ui/core' import { Formik, Form, Field } from 'formik' import gql from 'graphql-tag' import React, { useState } from 'react' import * as Yup from 'yup' import PromptWhenDirty from 'src/components/PromptWhenDirty' import { Button } from 'src/components/buttons' import { RadioGroup } from 'src/components/inputs/formik' import { H4 } from 'src/components/typography' import styles from './Shared.styles' const useStyles = makeStyles(styles) const GET_CONFIG = gql` { cryptoCurrencies { code display } } ` const schema = Yup.object().shape({ coin: Yup.string().required() }) const ChooseCoin = ({ addData }) => { const classes = useStyles() const [error, setError] = useState(false) const { data } = useQuery(GET_CONFIG) const cryptoCurrencies = data?.cryptoCurrencies ?? [] const onSubmit = it => { if (!schema.isValidSync(it)) return setError(true) if (it.coin !== 'BTC') { return addData({ coin: it.coin, zeroConf: 'none', zeroConfLimit: 0 }) } addData(it) } return ( <> <H4 className={error && classes.error}> Choose your first cryptocurrency </H4> <Formik validateOnBlur={false} validateOnChange={false} enableReinitialize initialValues={{ coin: '' }} onSubmit={onSubmit}> <Form onChange={() => setError(false)}> <PromptWhenDirty /> <Field component={RadioGroup} name="coin" labelClassName={classes.radioLabel} className={classes.radioGroup} options={cryptoCurrencies} /> { <Button size="lg" type="submit" className={classes.button}> Continue </Button> } </Form> </Formik> </> ) } export default ChooseCoin
lamassu/lamassu-server
new-lamassu-admin/src/pages/Wizard/components/Wallet/ChooseCoin.js
JavaScript
unlicense
1,915
var reportResource = "/public/Samples/Reports/States"; visualize({ auth: { name: "joeuser", password: "joeuser", organization: "organization_1" } }, function (v) { v("#main").report({ resource: reportResource, linkOptions: { events: { "click": function (ev, link) { if (link.type == "ReportExecution") { v("#drill-down").report({ resource: link.parameters._report, params: { state: [link.parameters.store_state] }, }); console.log(link.parameters.store_state); } } } }, error: function (err) { alert(err.message); } }); });
ernestoongaro/vis.js-simple-live
reports-hyperlink-passing/demo.js
JavaScript
unlicense
904
/* */ var convert = require('./convert'); module.exports = convert('partial', require('../partial'));
EpitaJS/js-class-2016-episode-2
jspm_packages/npm/lodash@4.6.1/fp/partial.js
JavaScript
unlicense
103
// Auto-generated. Do not edit! // (in-package gf_beacon.srv) "use strict"; const _serializer = _ros_msg_utils.Serialize; const _arraySerializer = _serializer.Array; const _deserializer = _ros_msg_utils.Deserialize; const _arrayDeserializer = _deserializer.Array; const _finder = _ros_msg_utils.Find; const _getByteLength = _ros_msg_utils.getByteLength; //----------------------------------------------------------- //----------------------------------------------------------- class gf_encodingRequest { constructor(initObj={}) { if (initObj === null) { // initObj === null is a special case for deserialization where we don't initialize fields this.lng_deg = null; this.lat_deg = null; this.alt_agl_m = null; this.speed_mph = null; this.heading_deg = null; this.battery_level = null; this.flying_state_on = null; this.return_to_home_state_on = null; this.forced_landing_state_on = null; } else { if (initObj.hasOwnProperty('lng_deg')) { this.lng_deg = initObj.lng_deg } else { this.lng_deg = 0.0; } if (initObj.hasOwnProperty('lat_deg')) { this.lat_deg = initObj.lat_deg } else { this.lat_deg = 0.0; } if (initObj.hasOwnProperty('alt_agl_m')) { this.alt_agl_m = initObj.alt_agl_m } else { this.alt_agl_m = 0.0; } if (initObj.hasOwnProperty('speed_mph')) { this.speed_mph = initObj.speed_mph } else { this.speed_mph = 0.0; } if (initObj.hasOwnProperty('heading_deg')) { this.heading_deg = initObj.heading_deg } else { this.heading_deg = 0.0; } if (initObj.hasOwnProperty('battery_level')) { this.battery_level = initObj.battery_level } else { this.battery_level = 0.0; } if (initObj.hasOwnProperty('flying_state_on')) { this.flying_state_on = initObj.flying_state_on } else { this.flying_state_on = 0; } if (initObj.hasOwnProperty('return_to_home_state_on')) { this.return_to_home_state_on = initObj.return_to_home_state_on } else { this.return_to_home_state_on = 0; } if (initObj.hasOwnProperty('forced_landing_state_on')) { this.forced_landing_state_on = initObj.forced_landing_state_on } else { this.forced_landing_state_on = 0; } } } static serialize(obj, buffer, bufferOffset) { // Serializes a message object of type gf_encodingRequest // Serialize message field [lng_deg] bufferOffset = _serializer.float64(obj.lng_deg, buffer, bufferOffset); // Serialize message field [lat_deg] bufferOffset = _serializer.float64(obj.lat_deg, buffer, bufferOffset); // Serialize message field [alt_agl_m] bufferOffset = _serializer.float64(obj.alt_agl_m, buffer, bufferOffset); // Serialize message field [speed_mph] bufferOffset = _serializer.float64(obj.speed_mph, buffer, bufferOffset); // Serialize message field [heading_deg] bufferOffset = _serializer.float64(obj.heading_deg, buffer, bufferOffset); // Serialize message field [battery_level] bufferOffset = _serializer.float64(obj.battery_level, buffer, bufferOffset); // Serialize message field [flying_state_on] bufferOffset = _serializer.uint16(obj.flying_state_on, buffer, bufferOffset); // Serialize message field [return_to_home_state_on] bufferOffset = _serializer.uint16(obj.return_to_home_state_on, buffer, bufferOffset); // Serialize message field [forced_landing_state_on] bufferOffset = _serializer.uint16(obj.forced_landing_state_on, buffer, bufferOffset); return bufferOffset; } static deserialize(buffer, bufferOffset=[0]) { //deserializes a message object of type gf_encodingRequest let len; let data = new gf_encodingRequest(null); // Deserialize message field [lng_deg] data.lng_deg = _deserializer.float64(buffer, bufferOffset); // Deserialize message field [lat_deg] data.lat_deg = _deserializer.float64(buffer, bufferOffset); // Deserialize message field [alt_agl_m] data.alt_agl_m = _deserializer.float64(buffer, bufferOffset); // Deserialize message field [speed_mph] data.speed_mph = _deserializer.float64(buffer, bufferOffset); // Deserialize message field [heading_deg] data.heading_deg = _deserializer.float64(buffer, bufferOffset); // Deserialize message field [battery_level] data.battery_level = _deserializer.float64(buffer, bufferOffset); // Deserialize message field [flying_state_on] data.flying_state_on = _deserializer.uint16(buffer, bufferOffset); // Deserialize message field [return_to_home_state_on] data.return_to_home_state_on = _deserializer.uint16(buffer, bufferOffset); // Deserialize message field [forced_landing_state_on] data.forced_landing_state_on = _deserializer.uint16(buffer, bufferOffset); return data; } static getMessageSize(object) { return 54; } static datatype() { // Returns string type for a service object return 'gf_beacon/gf_encodingRequest'; } static md5sum() { //Returns md5sum for a message object return 'b4f5ff271c45bb829d5e504e08e16e34'; } static messageDefinition() { // Returns full string definition for message return ` float64 lng_deg float64 lat_deg float64 alt_agl_m float64 speed_mph float64 heading_deg float64 battery_level uint16 flying_state_on uint16 return_to_home_state_on uint16 forced_landing_state_on `; } static Resolve(msg) { // deep-construct a valid message object instance of whatever was passed in if (typeof msg !== 'object' || msg === null) { msg = {}; } const resolved = new gf_encodingRequest(null); if (msg.lng_deg !== undefined) { resolved.lng_deg = msg.lng_deg; } else { resolved.lng_deg = 0.0 } if (msg.lat_deg !== undefined) { resolved.lat_deg = msg.lat_deg; } else { resolved.lat_deg = 0.0 } if (msg.alt_agl_m !== undefined) { resolved.alt_agl_m = msg.alt_agl_m; } else { resolved.alt_agl_m = 0.0 } if (msg.speed_mph !== undefined) { resolved.speed_mph = msg.speed_mph; } else { resolved.speed_mph = 0.0 } if (msg.heading_deg !== undefined) { resolved.heading_deg = msg.heading_deg; } else { resolved.heading_deg = 0.0 } if (msg.battery_level !== undefined) { resolved.battery_level = msg.battery_level; } else { resolved.battery_level = 0.0 } if (msg.flying_state_on !== undefined) { resolved.flying_state_on = msg.flying_state_on; } else { resolved.flying_state_on = 0 } if (msg.return_to_home_state_on !== undefined) { resolved.return_to_home_state_on = msg.return_to_home_state_on; } else { resolved.return_to_home_state_on = 0 } if (msg.forced_landing_state_on !== undefined) { resolved.forced_landing_state_on = msg.forced_landing_state_on; } else { resolved.forced_landing_state_on = 0 } return resolved; } }; class gf_encodingResponse { constructor(initObj={}) { if (initObj === null) { // initObj === null is a special case for deserialization where we don't initialize fields this.encoded = null; } else { if (initObj.hasOwnProperty('encoded')) { this.encoded = initObj.encoded } else { this.encoded = ''; } } } static serialize(obj, buffer, bufferOffset) { // Serializes a message object of type gf_encodingResponse // Serialize message field [encoded] bufferOffset = _serializer.string(obj.encoded, buffer, bufferOffset); return bufferOffset; } static deserialize(buffer, bufferOffset=[0]) { //deserializes a message object of type gf_encodingResponse let len; let data = new gf_encodingResponse(null); // Deserialize message field [encoded] data.encoded = _deserializer.string(buffer, bufferOffset); return data; } static getMessageSize(object) { let length = 0; length += object.encoded.length; return length + 4; } static datatype() { // Returns string type for a service object return 'gf_beacon/gf_encodingResponse'; } static md5sum() { //Returns md5sum for a message object return 'd37e4f1e46761defdf5b003341acd010'; } static messageDefinition() { // Returns full string definition for message return ` string encoded `; } static Resolve(msg) { // deep-construct a valid message object instance of whatever was passed in if (typeof msg !== 'object' || msg === null) { msg = {}; } const resolved = new gf_encodingResponse(null); if (msg.encoded !== undefined) { resolved.encoded = msg.encoded; } else { resolved.encoded = '' } return resolved; } }; module.exports = { Request: gf_encodingRequest, Response: gf_encodingResponse, md5sum() { return '916bededc1f7b96442f9b7ace1020840'; }, datatype() { return 'gf_beacon/gf_encoding'; } };
geofrenzy/utm-mbsb
ros-src/catkin_ws/install/share/gennodejs/ros/gf_beacon/srv/gf_encoding.js
JavaScript
apache-2.0
9,288
Object.defineProperty(exports,"__esModule",{value:true});var _reactNative=require('react-native');Object.keys(_reactNative).forEach(function(key){if(key==="default"||key==="__esModule")return;Object.defineProperty(exports,key,{enumerable:true,get:function get(){return _reactNative[key];}});});
RahulDesai92/PHR
node_modules/react-native-vector-icons/dist/react-native.js
JavaScript
apache-2.0
294
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * 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. */ CLASS({ name: 'GSnippetMetadatum', package: 'foam.navigator.views', documentation: function() {/* Specify $$DOC{.view} as a view object or $$DOC{.text} (and optionally $$DOC{.url}). */}, properties: [ { name: 'text', type: 'String' }, { name: 'url', type: 'String' }, { name: 'view', defaultValue: '' }, { name: 'label', defaultValue: '' } ] });
jlhughes/foam
js/foam/navigator/views/GSnippetMetadatum.js
JavaScript
apache-2.0
1,077
let mix = require('laravel-mix'); let fs = require('fs'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel application. By default, we are compiling the Sass | file for the application as well as bundling up all the JS files. | */ mix.disableNotifications(); mix.sourceMaps(!mix.inProduction()); mix.setResourceRoot('/assets/{name}/'); // More documents see: https://laravel.com/docs/master/mix if (mix.inProduction()) { mix.setPublicPath('assets'); mix.js('resources/assets/main.js', 'assets/app.js'); // Dev build. } else { mix.setPublicPath('../../public/assets/{name}/'); if (mix.config.hmr === true) { mix.setResourceRoot('http://127.0.0.1:8080/'); } mix.js('resources/assets/main.js', '../../public/assets/{name}/app.js'); }
slimkit/thinksns-plus
resources/stubs/package/webpack.mix.js
JavaScript
apache-2.0
986
/* 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/. */ /* General nsIUpdateCheckListener onload and onerror error code and statusText Tests */ // Errors tested: // 200, 403, 404, 500, 2152398849, 2152398862, 2152398864, 2152398867, // 2152398868, 2152398878, 2152398890, 2152398919, 2152398920, 2153390069, // 2152398918, 2152398861 var gNextRunFunc; var gExpectedStatusCode; var gExpectedStatusText; function run_test() { do_test_pending(); do_register_cleanup(end_test); removeUpdateDirsAndFiles(); setUpdateURLOverride(); standardInit(); // The mock XMLHttpRequest is MUCH faster overrideXHR(callHandleEvent); do_execute_soon(run_test_pt1); } function end_test() { cleanUp(); } // Callback function used by the custom XMLHttpRequest implementation to // call the nsIDOMEventListener's handleEvent method for onload. function callHandleEvent() { gXHR.status = gExpectedStatusCode; var e = { target: gXHR }; gXHR.onload(e); } // Helper functions for testing nsIUpdateCheckListener statusText function run_test_helper(aNextRunFunc, aExpectedStatusCode, aMsg) { gStatusCode = null; gStatusText = null; gCheckFunc = check_test_helper; gNextRunFunc = aNextRunFunc; gExpectedStatusCode = aExpectedStatusCode; logTestInfo(aMsg, Components.stack.caller); gUpdateChecker.checkForUpdates(updateCheckListener, true); } function check_test_helper() { do_check_eq(gStatusCode, gExpectedStatusCode); var expectedStatusText = getStatusText(gExpectedStatusCode); do_check_eq(gStatusText, expectedStatusText); gNextRunFunc(); } /** * The following tests use a custom XMLHttpRequest to return the status codes */ // default onerror error message (error code 399 is not defined) function run_test_pt1() { gStatusCode = null; gStatusText = null; gCheckFunc = check_test_pt1; gExpectedStatusCode = 399; logTestInfo("testing default onerror error message"); gUpdateChecker.checkForUpdates(updateCheckListener, true); } function check_test_pt1() { do_check_eq(gStatusCode, gExpectedStatusCode); var expectedStatusText = getStatusText(404); do_check_eq(gStatusText, expectedStatusText); run_test_pt2(); } // file malformed - 200 function run_test_pt2() { run_test_helper(run_test_pt3, 200, "testing file malformed"); } // access denied - 403 function run_test_pt3() { run_test_helper(run_test_pt4, 403, "testing access denied"); } // file not found - 404 function run_test_pt4() { run_test_helper(run_test_pt5, 404, "testing file not found"); } // internal server error - 500 function run_test_pt5() { run_test_helper(run_test_pt6, 500, "testing internal server error"); } // failed (unknown reason) - NS_BINDING_FAILED (2152398849) function run_test_pt6() { run_test_helper(run_test_pt7, AUS_Cr.NS_BINDING_FAILED, "testing failed (unknown reason)"); } // connection timed out - NS_ERROR_NET_TIMEOUT (2152398862) function run_test_pt7() { run_test_helper(run_test_pt8, AUS_Cr.NS_ERROR_NET_TIMEOUT, "testing connection timed out"); } // network offline - NS_ERROR_OFFLINE (2152398864) function run_test_pt8() { run_test_helper(run_test_pt9, AUS_Cr.NS_ERROR_OFFLINE, "testing network offline"); } // port not allowed - NS_ERROR_PORT_ACCESS_NOT_ALLOWED (2152398867) function run_test_pt9() { run_test_helper(run_test_pt10, AUS_Cr.NS_ERROR_PORT_ACCESS_NOT_ALLOWED, "testing port not allowed"); } // no data was received - NS_ERROR_NET_RESET (2152398868) function run_test_pt10() { run_test_helper(run_test_pt11, AUS_Cr.NS_ERROR_NET_RESET, "testing no data was received"); } // update server not found - NS_ERROR_UNKNOWN_HOST (2152398878) function run_test_pt11() { run_test_helper(run_test_pt12, AUS_Cr.NS_ERROR_UNKNOWN_HOST, "testing update server not found"); } // proxy server not found - NS_ERROR_UNKNOWN_PROXY_HOST (2152398890) function run_test_pt12() { run_test_helper(run_test_pt13, AUS_Cr.NS_ERROR_UNKNOWN_PROXY_HOST, "testing proxy server not found"); } // data transfer interrupted - NS_ERROR_NET_INTERRUPT (2152398919) function run_test_pt13() { run_test_helper(run_test_pt14, AUS_Cr.NS_ERROR_NET_INTERRUPT, "testing data transfer interrupted"); } // proxy server connection refused - NS_ERROR_PROXY_CONNECTION_REFUSED (2152398920) function run_test_pt14() { run_test_helper(run_test_pt15, AUS_Cr.NS_ERROR_PROXY_CONNECTION_REFUSED, "testing proxy server connection refused"); } // server certificate expired - 2153390069 function run_test_pt15() { run_test_helper(run_test_pt16, 2153390069, "testing server certificate expired"); } // network is offline - NS_ERROR_DOCUMENT_NOT_CACHED (2152398918) function run_test_pt16() { run_test_helper(run_test_pt17, AUS_Cr.NS_ERROR_DOCUMENT_NOT_CACHED, "testing network is offline"); } // connection refused - NS_ERROR_CONNECTION_REFUSED (2152398861) function run_test_pt17() { run_test_helper(do_test_finished, AUS_Cr.NS_ERROR_CONNECTION_REFUSED, "testing connection refused"); }
sergecodd/FireFox-OS
B2G/gecko/toolkit/mozapps/update/test/unit/test_0050_general.js
JavaScript
apache-2.0
5,376
var React = require('react'); var request = require('superagent'); var GHRelease = React.createClass({ getInitialState: function() { return { windows: null } }, componentDidMount: function() { request.get( 'https://api.github.com/repos/musicpicker/MusicPickerDevice/releases/latest' ).end(function(err, res) { if (!err) { var data = res.body; var url = data.assets.filter(function(item) { if (item.name === 'setup.exe') { return true; } })[0].browser_download_url; this.setState({windows: url}); } }.bind(this)); }, render: function() { var buttons = ( <span>Fetching latest releases...</span> ); if (this.state.windows !== null) { buttons = <a href={this.state.windows} className="btn btn-primary">Windows</a> } return ( <div className="panel panel-primary"> <div className="panel-body"> <div className="row"> <div className="col-md-2"> <span style={{fontSize: '3em'}} className="glyphicon glyphicon-download-alt"></span> </div> <div className="col-md-10"> <p><b>Get Musicpicker player</b><br /> <small>OS X and Linux support coming soon</small></p> {buttons} </div> </div> </div> </div> ); } }) module.exports.GHRelease = GHRelease;
musicpicker/musicpicker
client/js/ghrelease.js
JavaScript
apache-2.0
1,448
function pushRegisterError(_data, _callback) { _callback && _callback({ success: false, error: _data }); } function pushRegisterSuccess(_userId, _data, _callback) { var token = _data.deviceToken; Cloud.PushNotifications.unsubscribe({ device_token: Ti.App.Properties.getString("android.deviceToken"), user_id: _userId, type: "ios" }, function() { exports.subscribe("friends", token, function(_resp1) { _callback(_resp1.success ? { success: true, msg: "Subscribe to channel: friends", data: _data } : { success: false, error: _resp2.data, msg: "Error Subscribing to channel: friends" }); }); }); } var Cloud = require("ti.cloud"); var AndroidPush = null; exports.initialize = function(_user, _pushRcvCallback, _callback) { USER_ID = _user.get("id"); if ("Simulator" === Ti.Platform.model) { alert("Push ONLY works on Devices!"); return; } var userId = _user.get("id"); userId ? Ti.Network.registerForPushNotifications({ types: [ Ti.Network.NOTIFICATION_TYPE_BADGE, Ti.Network.NOTIFICATION_TYPE_ALERT, Ti.Network.NOTIFICATION_TYPE_SOUND ], success: function(_data) { pushRegisterSuccess(userId, _data, _callback); }, error: function(_data) { pushRegisterError(_data, _callback); }, callback: function(_data) { _pushRcvCallback(_data.data); } }) : _callback && _callback({ success: false, msg: "Must have User for Push Notifications" }); }; exports.subscribe = function(_channel, _token, _callback) { Cloud.PushNotifications.subscribe({ channel: _channel, device_token: _token, type: "ios" }, function(_event) { var msgStr = "Subscribed to " + _channel + " Channel"; Ti.API.debug(msgStr + ": " + _event.success); _callback(_event.success ? { success: true, error: null, msg: msgStr } : { success: false, error: _event.data, msg: "Error Subscribing to All Channels" }); }); }; exports.pushUnsubscribe = function(_data, _callback) { Cloud.PushNotifications.unsubscribe(_data, function(e) { if (e.success) { Ti.API.debug("Unsubscribed from: " + _data.channel); _callback({ success: true, error: null }); } else { Ti.API.error("Error unsubscribing: " + _data.channel); Ti.API.error(JSON.stringify(e, null, 2)); _callback({ success: false, error: e }); } }); }; exports.sendPush = function(_params, _callback) { if (null === Alloy.Globals.pushToken) { _callback({ success: false, error: "Device Not Registered For Notifications!" }); return; } var data = { channel: "friends", payload: _params.payload }; _params.friends && (data.friends = _params.friends); _params.to_ids && (data.to_ids = _params.to_ids); Cloud.PushNotifications.notify(data, function(e) { if (e.success) _callback({ success: true }); else { var eStr = e.error && e.message || JSON.stringify(e); Ti.API.error(eStr); _callback({ success: false, error: eStr }); } }); }; exports.getChannels = function(_user, _callback) { var xhr = Ti.Network.createHTTPClient(); var isProduction = "production" === Titanium.App.deployType; var acsKeyName = "acs-api-key-" + (isProduction ? "production" : "development"); var url = "https://api.cloud.appcelerator.com/v1/push_notification/query.json?key="; url += Ti.App.Properties.getString(acsKeyName); url += "&user_id=" + _user.id; xhr.open("GET", url); xhr.setRequestHeader("Accept", "application/json"); xhr.onerror = function(e) { alert(e); Ti.API.info(" " + String(e)); }; xhr.onload = function() { try { Ti.API.debug(" " + xhr.responseText); var data = JSON.parse(xhr.responseText); var subscriptions = data.response.subscriptions[0]; Ti.API.info(JSON.stringify(subscriptions)); _callback && _callback({ success: true, data: subscriptions }); } catch (E) { Ti.API.error(" " + String(E)); _callback && _callback({ success: false, data: null, error: E }); } }; xhr.send(); };
TeamAir4385/Production
build/mobileweb/iphone/pushNotifications.js
JavaScript
apache-2.0
4,865
import EmberObject from '@ember/object'; import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; let testSerializedData = { 'hello.txt': { content_type: 'text/plain', data: 'aGVsbG8gd29ybGQ=', digest: "md5-7mkg+nM0HN26sZkLN8KVSA==" // CouchDB doesn't add 'length' }, 'stub.txt': { stub: true, content_type: 'text/plain', digest: "md5-7mkg+nM0HN26sZkLN8KVSA==", length: 11 }, }; let testDeserializedData = [ EmberObject.create({ name: 'hello.txt', content_type: 'text/plain', data: 'aGVsbG8gd29ybGQ=', digest: 'md5-7mkg+nM0HN26sZkLN8KVSA==' }), EmberObject.create({ name: 'stub.txt', content_type: 'text/plain', stub: true, digest: 'md5-7mkg+nM0HN26sZkLN8KVSA==', length: 11 }) ]; module('Unit | Transform | attachments', function(hooks) { setupTest(hooks); test('it serializes an attachment', function(assert) { let transform = this.owner.lookup('transform:attachments'); assert.equal(transform.serialize(null), null); assert.equal(transform.serialize(undefined), null); assert.deepEqual(transform.serialize([]), {}); let serializedData = transform.serialize(testDeserializedData); let hello = testDeserializedData[0].get('name'); assert.equal(hello, 'hello.txt'); assert.equal(serializedData[hello].content_type, testSerializedData[hello].content_type); assert.equal(serializedData[hello].data, testSerializedData[hello].data); let stub = testDeserializedData[1].get('name'); assert.equal(stub, 'stub.txt'); assert.equal(serializedData[stub].content_type, testSerializedData[stub].content_type); assert.equal(serializedData[stub].stub, true); }); test('it deserializes an attachment', function(assert) { let transform = this.owner.lookup('transform:attachments'); assert.deepEqual(transform.deserialize(null), []); assert.deepEqual(transform.deserialize(undefined), []); let deserializedData = transform.deserialize(testSerializedData); assert.equal(deserializedData[0].get('name'), testDeserializedData[0].get('name')); assert.equal(deserializedData[0].get('content_type'), testDeserializedData[0].get('content_type')); assert.equal(deserializedData[0].get('data'), testDeserializedData[0].get('data')); assert.equal(deserializedData[0].get('digest'), testDeserializedData[0].get('digest')); assert.equal(deserializedData[1].get('name'), testDeserializedData[1].get('name')); assert.equal(deserializedData[1].get('content_type'), testDeserializedData[1].get('content_type')); assert.equal(deserializedData[1].get('stub'), true); assert.equal(deserializedData[1].get('digest'), testDeserializedData[1].get('digest')); assert.equal(deserializedData[1].get('length'), testDeserializedData[1].get('length')); }); });
pouchdb-community/ember-pouch
tests/unit/transforms/attachments-test.js
JavaScript
apache-2.0
2,849
"use strict"; var List = require("./list"); var FastSet = require("./fast-set"); var GenericCollection = require("./generic-collection"); var GenericSet = require("./generic-set"); var ObservableObject = require("pop-observe/observable-object"); var ObservableRange = require("pop-observe/observable-range"); var equalsOperator = require("pop-equals"); var hashOperator = require("pop-hash"); var copy = require("./copy"); module.exports = Set; function Set(values, equals, hash, getDefault) { if (!(this instanceof Set)) { return new Set(values, equals, hash, getDefault); } equals = equals || equalsOperator; hash = hash || hashOperator; getDefault = getDefault || noop; this.contentEquals = equals; this.contentHash = hash; this.getDefault = getDefault; // a list of values in insertion order, used for all operations that depend // on iterating in insertion order this.order = new this.Order(undefined, equals); // a set of nodes from the order list, indexed by the corresponding value, // used for all operations that need to quickly seek value in the list this.store = new this.Store( undefined, function (a, b) { return equals(a.value, b.value); }, function (node) { return hash(node.value); } ); this.length = 0; this.addEach(values); } Set.Set = Set; // hack for MontageJS copy(Set.prototype, GenericCollection.prototype); copy(Set.prototype, GenericSet.prototype); copy(Set.prototype, ObservableObject.prototype); copy(Set.prototype, ObservableRange.prototype); Set.prototype.Order = List; Set.prototype.Store = FastSet; Set.prototype.constructClone = function (values) { return new this.constructor(values, this.contentEquals, this.contentHash, this.getDefault); }; Set.prototype.has = function (value) { var node = new this.order.Node(value); return this.store.has(node); }; Set.prototype.get = function (value) { var node = new this.order.Node(value); node = this.store.get(node); if (node) { return node.value; } else { return this.getDefault(value); } }; Set.prototype.add = function (value) { var node = new this.order.Node(value); if (!this.store.has(node)) { var index = this.length; if (this.dispatchesRangeChanges) { this.dispatchRangeWillChange([value], [], index); } this.order.add(value); node = this.order.head.prev; this.store.add(node); this.length++; if (this.dispatchesRangeChanges) { this.dispatchRangeChange([value], [], index); } return true; } return false; }; Set.prototype["delete"] = function (value) { var node = new this.order.Node(value); if (this.store.has(node)) { var node = this.store.get(node); if (this.dispatchesRangeChanges) { this.dispatchRangeWillChange([], [value], node.index); } this.store["delete"](node); // removes from the set this.order.splice(node, 1); // removes the node from the list this.length--; if (this.dispatchesRangeChanges) { this.dispatchRangeChange([], [value], node.index); } return true; } return false; }; Set.prototype.pop = function () { if (this.length) { var result = this.order.head.prev.value; this["delete"](result); return result; } }; Set.prototype.shift = function () { if (this.length) { var result = this.order.head.next.value; this["delete"](result); return result; } }; Set.prototype.one = function () { if (this.length > 0) { return this.store.one().value; } }; Set.prototype.clear = function () { var clearing; if (this.dispatchesRangeChanges) { clearing = this.toArray(); this.dispatchRangeWillChange([], clearing, 0); } this.store.clear(); this.order.clear(); this.length = 0; if (this.dispatchesRangeChanges) { this.dispatchRangeChange([], clearing, 0); } }; Set.prototype.reduce = function (callback, basis /*, thisp*/) { var thisp = arguments[2]; var list = this.order; var index = 0; return list.reduce(function (basis, value) { return callback.call(thisp, basis, value, index++, this); }, basis, this); }; Set.prototype.reduceRight = function (callback, basis /*, thisp*/) { var thisp = arguments[2]; var list = this.order; var index = this.length - 1; return list.reduceRight(function (basis, value) { return callback.call(thisp, basis, value, index--, this); }, basis, this); }; Set.prototype.toArray = function () { return this.order.toArray(); }; Set.prototype.iterate = function () { return this.order.iterate(); }; Set.prototype.log = function () { var set = this.store; return set.log.apply(set, arguments); }; Set.prototype.makeRangeChangesObservable = function () { this.order.makeRangeChangesObservable(); }; function noop() {}
leogoesger/bloc-frontend-project-starter
node_modules/collections/set.js
JavaScript
apache-2.0
5,090
// Copyright 2013 Google Inc. // // 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. /** * @fileoverview Speech rules for mathml and mathjax nodes. * @author sorge@google.com (Volker Sorge) */ goog.provide('cvox.MathmlStoreRules'); goog.require('cvox.MathStore'); goog.require('cvox.MathmlStore'); goog.require('cvox.MathmlStoreUtil'); goog.require('cvox.StoreUtil'); /** * Rule initialization. * @constructor */ cvox.MathmlStoreRules = function() { // Custom functions used in the rules. cvox.MathmlStoreRules.initCustomFunctions_(); cvox.MathmlStoreRules.initDefaultRules_(); // MathML rules. cvox.MathmlStoreRules.initMathjaxRules_(); // MathJax Rules cvox.MathmlStoreRules.initAliases_(); // MathJax Aliases for MathML rules. cvox.MathmlStoreRules.initSpecializationRules_(); // Square, cube, etc. cvox.MathmlStoreRules.initSemanticRules_(); }; goog.addSingletonGetter(cvox.MathmlStoreRules); /** * @type {cvox.MathStore} */ cvox.MathmlStoreRules.mathStore = cvox.MathmlStore.getInstance(); /** * @override */ cvox.MathmlStoreRules.mathStore.initialize = cvox.MathmlStoreRules.getInstance; // These are used to work around Closure's rules for aliasing. /** @private */ cvox.MathmlStoreRules.defineDefaultMathmlRule_ = goog.bind( cvox.MathmlStoreRules.mathStore.defineDefaultMathmlRule, cvox.MathmlStoreRules.mathStore); /** @private */ cvox.MathmlStoreRules.defineRule_ = goog.bind( cvox.MathmlStoreRules.mathStore.defineRule, cvox.MathmlStoreRules.mathStore); /** @private */ cvox.MathmlStoreRules.defineRuleAlias_ = goog.bind( cvox.MathmlStoreRules.mathStore.defineRuleAlias, cvox.MathmlStoreRules.mathStore); /** @private */ cvox.MathmlStoreRules.addContextFunction_ = goog.bind( cvox.MathmlStoreRules.mathStore.contextFunctions.add, cvox.MathmlStoreRules.mathStore.contextFunctions); /** @private */ cvox.MathmlStoreRules.addCustomQuery_ = goog.bind( cvox.MathmlStoreRules.mathStore.customQueries.add, cvox.MathmlStoreRules.mathStore.customQueries); goog.scope(function() { var defineDefaultMathmlRule = cvox.MathmlStoreRules.defineDefaultMathmlRule_; var defineRule = cvox.MathmlStoreRules.defineRule_; var defineRuleAlias = cvox.MathmlStoreRules.defineRuleAlias_; var addCTXF = cvox.MathmlStoreRules.addContextFunction_; var addCQF = cvox.MathmlStoreRules.addCustomQuery_; /** * Initialize the custom functions. * @private */ cvox.MathmlStoreRules.initCustomFunctions_ = function() { addCTXF('CTXFnodeCounter', cvox.StoreUtil.nodeCounter); addCTXF('CTXFmfSeparators', cvox.MathmlStoreUtil.mfencedSeparators); addCTXF('CTXFcontentIterator', cvox.MathmlStoreUtil.contentIterator); addCQF('CQFextender', cvox.MathmlStoreUtil.retrieveMathjaxExtender); addCQF('CQFmathmlmunder', cvox.MathmlStoreUtil.checkMathjaxMunder); addCQF('CQFmathmlmover', cvox.MathmlStoreUtil.checkMathjaxMover); addCQF('CQFmathmlmsub', cvox.MathmlStoreUtil.checkMathjaxMsub); addCQF('CQFmathmlmsup', cvox.MathmlStoreUtil.checkMathjaxMsup); addCQF('CQFlookupleaf', cvox.MathmlStoreUtil.retrieveMathjaxLeaf); }; /** * Initialize the default mathrules. * @private */ cvox.MathmlStoreRules.initDefaultRules_ = function() { // Initial rule defineDefaultMathmlRule('math', '[m] ./*'); defineDefaultMathmlRule('semantics', '[n] ./*[1]'); // Space elements defineDefaultMathmlRule('mspace', '[p] (pause:250)'); defineDefaultMathmlRule('mstyle', '[m] ./*'); defineDefaultMathmlRule('mpadded', '[m] ./*'); defineDefaultMathmlRule('merror', '[m] ./*'); defineDefaultMathmlRule('mphantom', '[m] ./*'); // Token elements. defineDefaultMathmlRule('mtext', '[t] text(); [p] (pause:200)'); defineDefaultMathmlRule('mi', '[n] text()'); defineDefaultMathmlRule('mo', '[n] text() (rate:-0.1)'); defineDefaultMathmlRule('mn', '[n] text()'); // Dealing with fonts. defineRule('mtext-variant', 'default.default', '[t] "comece"; [t] @mathvariant (pause:150);' + '[t] text() (pause:150); [t] "fim"; ' + '[t] @mathvariant (pause:200)', 'self::mathml:mtext', '@mathvariant', '@mathvariant!="normal"'); defineRule('mi-variant', 'default.default', '[t] @mathvariant; [n] text()', 'self::mathml:mi', '@mathvariant', '@mathvariant!="normal"'); defineRuleAlias('mi-variant', 'self::mathml:mn', // mn '@mathvariant', '@mathvariant!="normal"'); defineRule('mo-variant', 'default.default', '[t] @mathvariant; [n] text() (rate:-0.1)', 'self::mathml:mo', '@mathvariant', '@mathvariant!="normal"'); defineDefaultMathmlRule( 'ms', '[t] "cadeia" (pitch:0.5, rate:0.5); [t] text()'); // Script elements. defineDefaultMathmlRule( 'msup', '[n] ./*[1]; [t] "super";' + '[n] ./*[2] (pitch:0.35); [p] (pause:300)'); defineDefaultMathmlRule( 'msubsup', '[n] ./*[1]; [t] "sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);' + '[t] "super"; [n] ./*[3] (pitch:0.35); [p] (pause:300)' ); defineDefaultMathmlRule( 'msub', '[n] ./*[1]; [t] "sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:300)'); defineDefaultMathmlRule( 'mover', '[n] ./*[2] (pitch:0.35); [p] (pause:200);' + ' [t] "mais"; [n] ./*[1]; [p] (pause:400)'); defineDefaultMathmlRule( 'munder', '[n] ./*[2] (pitch:-0.35); [t] "sob"; [n] ./*[1]; [p] (pause:400)'); // defineDefaultMathmlRule( // 'munderover', // '[n] ./*[2] (pitch:-0.35); [t] "em e"; [n] ./*[3] (pitch:0.35);' + // ' [t] "mais"; [n] ./*[1]; [p] (pause:400)'); defineDefaultMathmlRule( 'munderover', '[t] "somatório de"; [n] ./*[2] (pitch:-0.35);' + ' [t] "até" ; [n] ./*[3] (pitch:0.35); [p] (pause:400)'); // Layout elements. defineDefaultMathmlRule('mrow', '[m] ./*'); defineDefaultMathmlRule( 'msqrt', '[t] "Raiz quadrada de"; [m] ./* (rate:0.2); [p] (pause:400)'); defineDefaultMathmlRule( 'mroot', '[t] "raiz de"; [n] ./*[2]; [t] "de";' + '[n] ./*[1] (rate:0.2); [p] (pause:400)'); defineDefaultMathmlRule( 'mfrac', ' [p] (pause:400); [n] ./*[1] (pitch:0.3);' + ' [t] "dividido por"; [n] ./*[2] (pitch:-0.3); [p] (pause:400)'); defineRule( 'mfenced-single', 'default.default', '[t] @open (context:"opening"); [m] ./* (separator:@separators);' + '[t] @close (context:"closing")', 'self::mathml:mfenced', 'string-length(string(@separators))=1'); defineRule( 'mfenced-empty', 'default.default', '[t] @open (context:"opening"); [m] ./*;' + '[t] @close (context:"closing")', 'self::mathml:mfenced', 'string-length(string(@separators))=1', 'string(@separators)=" "'); defineRule( 'mfenced-comma', 'default.default', '[t] @open (context:"opening"); [m] ./* (separator:"comma");' + '[t] @close (context:"closing")', 'self::mathml:mfenced'); defineRule( 'mfenced-multi', 'default.default', '[t] @open (context:"opening"); [m] ./* (sepFunc:CTXFmfSeparators,' + 'separator:@separators); [t] @close (context:"closing")', 'self::mathml:mfenced', 'string-length(string(@separators))>1'); // Mtable rules. defineRule( 'mtable', 'default.default', '[t] "matriz"; [m] ./* (ctxtFunc:CTXFnodeCounter,' + 'context:"row",pause:100)', 'self::mathml:mtable'); defineRule( 'mtr', 'default.default', '[m] ./* (ctxtFunc:CTXFnodeCounter,context:"column",pause:100)', 'self::mathml:mtr'); defineRule( 'mtd', 'default.default', '[m] ./*', 'self::mathml:mtd'); // Mtable superbrief rules. defineRule( 'mtable', 'default.superbrief', '[t] count(child::mathml:mtr); [t] "por";' + '[t] count(child::mathml:mtr[1]/mathml:mtd); [t] "matriz";', 'self::mathml:mtable'); // Mtable short rules. defineRule( 'mtable', 'default.short', '[t] "matriz"; [m] ./*', 'self::mathml:mtable'); defineRule( 'mtr', 'default.short', '[m] ./*', 'self::mathml:mtr'); defineRule( 'mtd', 'default.short', '[t] "Elemento"; [t] count(./preceding-sibling::mathml:mtd)+1;' + '[t] count(./parent::mathml:mtr/preceding-sibling::mathml:mtr)+1;' + '[p] (pause:500); [m] ./*', 'self::mathml:mtd'); // Mmultiscripts rules. defineRule( 'mmultiscripts-4', 'default.default', '[n] ./*[1]; [p] (pause:200);' + '[t] "esquerda sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + '[t] "deixou super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);' + '[t] "direito sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);' + '[t] "direito super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);', 'self::mathml:mmultiscripts'); defineRule( 'mmultiscripts-3-1', 'default.default', '[n] ./*[1]; [p] (pause:200);' + '[t] "esquerda sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + '[t] "deixou super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);' + '[t] "direito super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);', 'self::mathml:mmultiscripts', './mathml:none=./*[2]', './mathml:mprescripts=./*[4]'); defineRule( 'mmultiscripts-3-2', 'default.default', '[n] ./*[1]; [p] (pause:200);' + '[t] "esquerda sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + '[t] "deixou super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);' + '[t] "direito sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);', 'self::mathml:mmultiscripts', './mathml:none=./*[3]', './mathml:mprescripts=./*[4]'); defineRule( 'mmultiscripts-3-3', 'default.default', '[n] ./*[1]; [p] (pause:200);' + '[t] "deixou super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);' + '[t] "direito sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);' + '[t] "direito super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);', 'self::mathml:mmultiscripts', './mathml:none=./*[5]', './mathml:mprescripts=./*[4]'); defineRule( 'mmultiscripts-3-4', 'default.default', '[n] ./*[1]; [p] (pause:200);' + '[t] "esquerda sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + '[t] "direito sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);' + '[t] "direito super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);', 'self::mathml:mmultiscripts', './mathml:none=./*[6]', './mathml:mprescripts=./*[4]'); defineRule( 'mmultiscripts-2-1', 'default.default', '[n] ./*[1]; [p] (pause:200);' + '[t] "esquerda sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + '[t] "deixou super"; [n] ./*[6] (pitch:0.35); [p] (pause:300);', 'self::mathml:mmultiscripts', './mathml:none=./*[2]', './mathml:none=./*[3]', './mathml:mprescripts=./*[4]'); defineRule( 'mmultiscripts-1-1', 'default.default', '[n] ./*[1]; [p] (pause:200);' + '[t] "deixou super"; [n] ./*[6] (pitch:0.35); [p] (pause:300);', 'self::mathml:mmultiscripts', './mathml:none=./*[2]', './mathml:none=./*[3]', './mathml:mprescripts=./*[4]', './mathml:none=./*[5]'); defineRule( 'mmultiscripts-1-2', 'default.default', '[n] ./*[1]; [p] (pause:200);' + '[t] "esquerda sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);', 'self::mathml:mmultiscripts', './mathml:none=./*[2]', './mathml:none=./*[3]', './mathml:mprescripts=./*[4]', './mathml:none=./*[6]'); }; /** * Initialize mathJax Rules * @private */ cvox.MathmlStoreRules.initMathjaxRules_ = function() { // Initial rule defineRule('mj-math', 'default.default', '[n] ./*[1]/*[1]/*[1]', 'self::span[@class="math"]'); // Token Elements defineRule( 'mj-leaf', 'default.default', '[n] CQFlookupleaf', 'self::span[@class="mi"]'); defineRuleAlias('mj-leaf', 'self::span[@class="mo"]'); defineRuleAlias('mj-leaf', 'self::span[@class="mn"]'); defineRuleAlias('mj-leaf', 'self::span[@class="mtext"]'); defineRule( 'mj-mo-ext', 'default.default', '[n] CQFextender', 'self::span[@class="mo"]', './*[1]/*[1]/text()', './*[1]/*[2]/text()'); defineRule( 'mj-texatom', 'default.default', '[n] ./*[1]', 'self::span[@class="texatom"]'); // Script elements. defineRule( 'mj-msubsup', 'default.default', '[n] ./*[1]/*[1]/*[1]; [t] "sub"; [n] ./*[1]/*[3]/*[1] (pitch:-0.35);' + '[p] (pause:200); [t] "super"; [n] ./*[1]/*[2]/*[1] (pitch:0.35);' + '[p] (pause:300)', 'self::span[@class="msubsup"]'); defineRule( 'mj-msub', 'default.default', '[n] ./*[1]/*[1]/*[1]; [t] "sub";' + '[n] ./*[1]/*[2]/*[1] (pitch:-0.35); [p] (pause:300)', 'self::span[@class="msub"]'); defineRule( 'mj-msup', 'default.default', '[n] ./*[1]/*[1]/*[1]; [t] "super";' + '[n] ./*[1]/*[2]/*[1] (pitch:0.35); [p] (pause:300)', 'self::span[@class="msup"]'); defineRule( 'mj-munderover', 'default.default', '[n] ./*[1]/*[2]/*[1] (pitch:0.35); [t] "em e";' + '[n] ./*[1]/*[3]/*[1] (pitch:-0.35); [t] "mais";' + '[n] ./*[1]/*[1]/*[1]; [p] (pause:400)', 'self::span[@class="munderover"]'); defineRule( 'mj-munder', 'default.default', '[n] ./*[1]/*[2]/*[1] (pitch:0.35); [t] "sob";' + '[n] ./*[1]/*[1]/*[1]; [p] (pause:400)', 'self::span[@class="munder"]'); defineRule( 'mj-mover', 'default.default', '[n] ./*[1]/*[2]/*[1] (pitch:0.35); [t] "mais";' + '[n] ./*[1]/*[1]/*[1]; [p] (pause:400)', 'self::span[@class="mover"]'); // Layout elements. defineRule( 'mj-mfrac', 'default.default', '[p] (pause:250); [n] ./*[1]/*[1]/*[1] (pitch:0.3); [p] (pause:250);' + ' [t] "dividido por"; [n] ./*[1]/*[2]/*[1] (pitch:-0.3);' + '[p] (pause:400)', 'self::span[@class="mfrac"]'); defineRule( 'mj-msqrt', 'default.default', '[t] "Raiz quadrada de";' + '[n] ./*[1]/*[1]/*[1] (rate:0.2); [p] (pause:400)', 'self::span[@class="msqrt"]'); defineRule( 'mj-mroot', 'default.default', '[t] "raiz de"; [n] ./*[1]/*[4]/*[1]; [t] "de";' + '[n] ./*[1]/*[1]/*[1] (rate:0.2); [p] (pause:400)', 'self::span[@class="mroot"]'); defineRule( 'mj-mfenced', 'default.default', '[t] "abertura"; [n] ./*[1]; ' + '[m] ./*[position()>1 and position()<last()];' + ' [t] "fechar"; [n] ./*[last()]', 'self::span[@class="mfenced"]'); // Mtable short rules. defineRuleAlias('mj-leaf', 'self::span[@class="mtable"]'); // Mmultiscripts rules. defineRuleAlias('mj-leaf', 'self::span[@class="mmultiscripts"]'); }; /** * Initialize mathJax Aliases * @private */ cvox.MathmlStoreRules.initAliases_ = function() { // Space elements defineRuleAlias('mspace', 'self::span[@class="mspace"]'); defineRuleAlias('mstyle', 'self::span[@class="mstyle"]'); defineRuleAlias('mpadded', 'self::span[@class="mpadded"]'); defineRuleAlias('merror', 'self::span[@class="merror"]'); defineRuleAlias('mphantom', 'self::span[@class="mphantom"]'); // Token elements. defineRuleAlias('ms', 'self::span[@class="ms"]'); // Layout elements. defineRuleAlias('mrow', 'self::span[@class="mrow"]'); // The following rules fix bugs in MathJax's LaTeX translation. defineRuleAlias( 'mj-msub', 'self::span[@class="msubsup"]', 'CQFmathmlmsub'); defineRuleAlias( 'mj-msup', 'self::span[@class="msubsup"]', 'CQFmathmlmsup'); defineRuleAlias( 'mj-munder', 'self::span[@class="munderover"]', 'CQFmathmlmunder'); defineRuleAlias( 'mj-mover', 'self::span[@class="munderover"]', 'CQFmathmlmover'); }; /** * Initialize specializations wrt. content of nodes. * @private */ cvox.MathmlStoreRules.initSpecializationRules_ = function() { // Some special nodes for square and cube. // MathML defineRule( 'square', 'default.default', '[n] ./*[1]; [t] "quadrado" (pitch:0.35); [p] (pause:300)', 'self::mathml:msup', './*[2][text()=2]'); defineRuleAlias( 'square', 'self::mathml:msup', './mathml:mrow=./*[2]', 'count(./*[2]/*)=1', './*[2]/*[1][text()=2]'); defineRule( 'cube', 'default.default', '[n] ./*[1]; [t] "cubo" (pitch:0.35); [p] (pause:300)', 'self::mathml:msup', './*[2][text()=3]'); defineRuleAlias( 'cube', 'self::mathml:msup', './mathml:mrow=./*[2]', 'count(./*[2]/*)=1', './*[2]/*[1][text()=3]'); defineRule( 'square-sub', 'default.default', '[n] ./*[1]; [t] "sub"; [n] ./*[2] (pitch:-0.35);' + '[p] (pause:300); [t] "quadrado" (pitch:0.35); [p] (pause:400)', 'self::mathml:msubsup', './*[3][text()=2]'); defineRuleAlias( 'square-sub', 'self::mathml:msubsup', './mathml:mrow=./*[3]', 'count(./*[3]/*)=1', './*[3]/*[1][text()=2]'); defineRule( 'cube-sub', 'default.default', '[n] ./*[1]; [t] "sub"; [n] ./*[2] (pitch:-0.35);' + '[p] (pause:300); [t] "cubo" (pitch:0.35); [p] (pause:400)', 'self::mathml:msubsup', './*[3][text()=3]'); defineRuleAlias( 'cube-sub', 'self::mathml:msubsup', './mathml:mrow=./*[3]', 'count(./*[3]/*)=1', './*[3]/*[1][text()=3]'); // MathJax defineRule( 'mj-square', 'default.default', '[n] ./*[1]/*[1]/*[1]; [t] "quadrado" (pitch:0.35); [p] (pause:300)', 'self::span[@class="msup"]', './*[1]/*[2]/*[1][text()=2]'); defineRuleAlias( 'mj-square', 'self::span[@class="msup"]', './*[1]/*[2]/*[1]=./*[1]/*[2]/span[@class="mrow"]', 'count(./*[1]/*[2]/*[1]/*)=1', './*[1]/*[2]/*[1]/*[1][text()=2]'); defineRuleAlias( 'mj-square', 'self::span[@class="msubsup"]', 'CQFmathmlmsup', './*[1]/*[2]/*[1][text()=2]'); defineRuleAlias( 'mj-square', 'self::span[@class="msubsup"]', 'CQFmathmlmsup', './*[1]/*[2]/*[1]=./*[1]/*[2]/span[@class="mrow"]', 'count(./*[1]/*[2]/*[1]/*)=1', './*[1]/*[2]/*[1]/*[1][text()=2]'); defineRule( 'mj-cube', 'default.default', '[n] ./*[1]/*[1]/*[1]; [t] "cubo" (pitch:0.35); [p] (pause:300)', 'self::span[@class="msup"]', './*[1]/*[2]/*[1][text()=3]'); defineRuleAlias( 'mj-cube', 'self::span[@class="msup"]', './*[1]/*[2]/*[1]=./*[1]/*[2]/span[@class="mrow"]', 'count(./*[1]/*[2]/*[1]/*)=1', './*[1]/*[2]/*[1]/*[1][text()=3]'); defineRuleAlias( 'mj-cube', 'self::span[@class="msubsup"]', 'CQFmathmlmsup', './*[1]/*[2]/*[1][text()=3]'); defineRuleAlias( 'mj-cube', 'self::span[@class="msubsup"]', 'CQFmathmlmsup', './*[1]/*[2]/*[1]=./*[1]/*[2]/span[@class="mrow"]', 'count(./*[1]/*[2]/*[1]/*)=1', './*[1]/*[2]/*[1]/*[1][text()=3]'); defineRule( 'mj-square-sub', 'default.default', '[n] ./*[1]/*[1]/*[1]; [t] "sub"; [n] ./*[1]/*[3]/*[1] (pitch:-0.35); ' + '[p] (pause:300); [t] "quadrado" (pitch:0.35); [p] (pause:400)', 'self::span[@class="msubsup"]', './*[1]/*[2]/*[1][text()=2]'); defineRuleAlias( 'mj-square-sub', 'self::span[@class="msubsup"]', './*[1]/*[2]/*[1]=./*[1]/*[2]/span[@class="mrow"]', 'count(./*[1]/*[2]/*[1]/*)=1', './*[1]/*[2]/*[1]/*[1][text()=2]'); defineRule( 'mj-cube-sub', 'default.default', '[n] ./*[1]/*[1]/*[1]; [t] "sub"; [n] ./*[1]/*[3]/*[1] (pitch:-0.35); ' + '[p] (pause:300); [t] "cubo" (pitch:0.35); [p] (pause:400)', 'self::span[@class="msubsup"]', './*[1]/*[2]/*[1][text()=3]'); defineRuleAlias( 'mj-cube-sub', 'self::span[@class="msubsup"]', './*[1]/*[2]/*[1]=./*[1]/*[2]/span[@class="mrow"]', 'count(./*[1]/*[2]/*[1]/*)=1', './*[1]/*[2]/*[1]/*[1][text()=3]'); }; /** * Initialize mathJax Aliases * @private */ cvox.MathmlStoreRules.initSemanticRules_ = function() { // Initial rule defineRule( 'stree', 'default.default', '[n] ./*[1]', 'self::stree'); defineRule( 'multrel', 'default.default', '[t] "multirelation"; [m] children/* (sepFunc:CTXFcontentIterator)', 'self::multirel'); defineRule( 'variable-equality', 'default.default', '[t] "equação de sequência"; [m] ./children/* ' + '(context:"part",ctxtFunc:CTXFnodeCounter,separator:./text())', 'self::relseq[@role="equality"]', 'count(./children/*)>2', './children/punct[@role="ellipsis"]');// Make that better! defineRule( 'multi-equality', 'default.default', '[t] "equação de sequência"; [m] ./children/* ' + '(context:"part",ctxtFunc:CTXFnodeCounter,separator:./text())', 'self::relseq[@role="equality"]', 'count(./children/*)>2'); defineRule( 'multi-equality', 'default.short', '[t] "equação de sequência"; [m] ./children/* ' + '(separator:./text())', 'self::relseq[@role="equality"]', 'count(./children/*)>2'); defineRule( 'equality', 'default.default', '[t] "equação"; [t] "lado esquerdo"; [n] children/*[1];' + '[p] (pause:200); [n] text() (pause:200);' + '[t] "lado direito"; [n] children/*[2]', 'self::relseq[@role="equality"]', 'count(./children/*)=2'); defineRule( 'simple-equality', 'default.default', '[n] children/*[1]; [p] (pause:200); [n] text() (pause:200);' + '[n] children/*[2]', 'self::relseq[@role="equality"]', 'count(./children/*)=2', './children/identifier or ./children/number'); defineRule( 'simple-equality2', 'default.default', '[n] children/*[1]; [p] (pause:200); [n] text() (pause:200);' + '[n] children/*[2]', 'self::relseq[@role="equality"]', 'count(./children/*)=2', './children/function or ./children/appl'); defineRule( 'multrel', 'default.default', '[m] children/* (separator:./text())', 'self::relseq'); defineRule( 'binary-operation', 'default.default', '[m] children/* (separator:text());', 'self::infixop'); defineRule( 'variable-addition', 'default.default', '[t] "soma com número variável de summands";' + '[p] (pause:400); [m] children/* (separator:./text())', 'self::infixop[@role="addition"]', 'count(children/*)>2', 'children/punct[@role="ellipsis"]');// Make that better! defineRule( 'multi-addition', 'default.default', '[t] "soma,"; [t] count(./children/*); [t] ", summands";' + '[p] (pause:400); [m] ./children/* (separator:./text())', 'self::infixop[@role="addition"]', 'count(./children/*)>2'); // Prefix Operator defineRule( 'prefix', 'default.default', '[t] "prefixo"; [n] text(); [t] "de" (pause 150);' + '[n] children/*[1]', 'self::prefixop'); defineRule( 'negative', 'default.default', '[t] "negativo"; [n] children/*[1]', 'self::prefixop', 'self::prefixop[@role="negative"]'); // Postfix Operator defineRule( 'postfix', 'default.default', '[n] children/*[1]; [t] "postfix"; [n] text() (pause 300)', 'self::postfixop'); defineRule( 'identifier', 'default.default', '[n] text()', 'self::identifier'); defineRule( 'number', 'default.default', '[n] text()', 'self::number'); defineRule( 'fraction', 'default.default', '[p] (pause:250); [n] children/*[1] (pitch:0.3); [p] (pause:250);' + ' [t] "dividido por"; [n] children/*[2] (pitch:-0.3); [p] (pause:400)', 'self::fraction'); defineRule( 'superscript', 'default.default', '[n] children/*[1]; [t] "super"; [n] children/*[2] (pitch:0.35);' + '[p] (pause:300)', 'self::superscript'); defineRule( 'subscript', 'default.default', '[n] children/*[1]; [t] "sub"; [n] children/*[2] (pitch:-0.35);' + '[p] (pause:300)', 'self::subscript'); defineRule( 'ellipsis', 'default.default', '[p] (pause:200); [t] "dot dot dot"; [p] (pause:300)', 'self::punct', 'self::punct[@role="ellipsis"]'); defineRule( 'fence-single', 'default.default', '[n] text()', 'self::punct', 'self::punct[@role="openfence"]'); defineRuleAlias('fence-single', 'self::punct', 'self::punct[@role="closefence"]'); defineRuleAlias('fence-single', 'self::punct', 'self::punct[@role="vbar"]'); defineRuleAlias('fence-single', 'self::punct', 'self::punct[@role="application"]'); // TODO (sorge) Refine punctuations further. defineRule( 'omit-punct', 'default.default', '[p] (pause:200);', 'self::punct'); defineRule( 'omit-empty', 'default.default', '', 'self::empty'); // Fences rules. defineRule( 'fences-open-close', 'default.default', '[p] (pause:100); [t] "aberto"; [n] children/*[1]; [p] (pause:200);' + '[t] "fechar"', 'self::fenced[@role="leftright"]'); defineRule( 'fences-open-close-in-appl', 'default.default', '[p] (pause:100); [n] children/*[1]; [p] (pause:200);', 'self::fenced[@role="leftright"]', './parent::children/parent::appl'); defineRule( 'fences-neutral', 'default.default', '[p] (pause:100); [t] "valor absoluto de"; [n] children/*[1];' + '[p] (pause:350);', 'self::fenced', 'self::fenced[@role="neutral"]'); defineRule( 'omit-fences', 'default.default', '[p] (pause:500); [n] children/*[1]; [p] (pause:200);', 'self::fenced'); // Matrix rules. defineRule( 'matrix', 'default.default', '[t] "matriz"; [m] children/* ' + '(ctxtFunc:CTXFnodeCounter,context:"row",pause:100)', 'self::matrix'); defineRule( 'matrix-row', 'default.default', '[m] children/* (ctxtFunc:CTXFnodeCounter,context:"column",pause:100)', 'self::row[@role="matrix"]'); defineRule( 'matrix-cell', 'default.default', '[n] children/*[1]', 'self::cell[@role="matrix"]'); // Vector rules. defineRule( 'vector', 'default.default', '[t] "vector"; [m] children/* ' + '(ctxtFunc:CTXFnodeCounter,context:"element",pause:100)', 'self::vector'); // Cases rules. defineRule( 'cases', 'default.default', '[t] "caso, declaração de"; [m] children/* ' + '(ctxtFunc:CTXFnodeCounter,context:"case",pause:100)', 'self::cases'); defineRule( 'cases-row', 'default.default', '[m] children/*', 'self::row[@role="cases"]'); defineRule( 'cases-cell', 'default.default', '[n] children/*[1]', 'self::cell[@role="cases"]'); defineRule( 'row', 'default.default', '[m] ./* (ctxtFunc:CTXFnodeCounter,context:"column",pause:100)', 'self::row"'); defineRule( 'cases-end', 'default.default', '[t] "caso, declaração de"; ' + '[m] children/* (ctxtFunc:CTXFnodeCounter,context:"case",pause:100);' + '[t] "fim casos"', 'self::cases', 'following-sibling::*'); // Multiline rules. defineRule( 'multiline', 'default.default', '[t] "várias linhas equação";' + '[m] children/* (ctxtFunc:CTXFnodeCounter,context:"line",pause:100)', 'self::multiline'); defineRule( 'line', 'default.default', '[m] children/*', 'self::line'); // Table rules. defineRule( 'table', 'default.default', '[t] "várias linhas equação";' + '[m] children/* (ctxtFunc:CTXFnodeCounter,context:"row",pause:200)', 'self::table'); defineRule( 'table-row', 'default.default', '[m] children/* (pause:100)', 'self::row[@role="table"]'); defineRuleAlias( 'cases-cell', 'self::cell[@role="table"]'); // Rules for punctuated expressions. defineRule( 'end-punct', 'default.default', '[m] children/*; [p] (pause:300)', 'self::punctuated', '@role="endpunct"'); defineRule( 'start-punct', 'default.default', '[n] content/*[1]; [p] (pause:200); [m] children/*', 'self::punctuated', '@role="startpunct"'); defineRule( 'integral-punct', 'default.default', '[n] children/*[1] (rate:0.2); [n] children/*[3] (rate:0.2)', 'self::punctuated', '@role="integral"'); defineRule( 'punctuated', 'default.default', '[m] children/* (pause:100)', 'self::punctuated'); // Function rules defineRule( 'function', 'default.default', '[n] text()', 'self::function'); defineRule( 'appl', 'default.default', '[n] children/*[1]; [n] content/*[1]; [n] children/*[2]', 'self::appl'); // Limit operator rules defineRule( 'limboth', 'default.default', '[n] children/*[1]; [t] "a partir de"; [n] children/*[2]; [t] "para";' + '[n] children/*[3]', 'self::limboth'); defineRule( 'sum-only', 'default.default', '[n] children/*[1]; [p] (pause 100); [t] "mais"; [n] children/*[2];' + '[p] (pause 250);', 'self::limboth', 'self::limboth[@role="sum"]'); defineRule( 'limlower', 'default.default', '[n] children/*[1]; [t] "mais"; [n] children/*[2];', 'self::limlower'); defineRule( 'limupper', 'default.default', '[n] children/*[1]; [t] "sob"; [n] children/*[2];', 'self::limupper'); // Bigoperator rules defineRule( 'largeop', 'default.default', '[n] text()', 'self::largeop'); defineRule( 'bigop', 'default.default', '[n] children/*[1]; [p] (pause 100); [t] "mais"; [n] children/*[2];' + '[p] (pause 250);', 'self::bigop'); // Integral rules defineRule( 'integral', 'default.default', '[n] children/*[1]; [p] (pause 100); [n] children/*[2]; [p] (pause 200);' + '[n] children/*[3] (rate:0.35);', 'self::integral'); defineRule( 'sqrt', 'default.default', '[t] "dividido por"; [n] children/*[1] (rate:0.2); [p] (pause:400)', 'self::sqrt'); defineRule( 'square', 'default.default', '[n] children/*[1]; [t] "quadrado" (pitch:0.35); [p] (pause:300)', 'self::superscript', 'children/*[2][text()=2]'); defineRule( 'text-no-mult', 'default.default', '[n] children/*[1]; [p] (pause:200); [n] children/*[2]', 'self::infixop', 'children/text'); }; }); // goog.scope
gabriel-76/NavMatBr
math_tokens/mathmaps/PT-BR/Yandex/mathml_store_rules.js
JavaScript
apache-2.0
29,518
define(['modules/dashboard/module'], function (module) { "use strict"; module.registerController('DashboardCtrl', ['$scope', '$log', '$moment', 'Socket', 'toastr', 'Device', function ($scope, $log, $moment, Socket, toastr, Device) { $(".view").css("min-height", $(window).height() - $('.header').height() - 100); $('#datatable-measures').DataTable({columns: [{ "targets": 'measure.value', "title": "Value mg/dL", "data": 'value', "type": "number"}, { "targets": 'measure.date', "title": "Date", "data": 'date', "type": "date", "render": function ( data, type, full, meta ) { if (data != undefined && data != null) return $moment(data).format('DD/MM/YYYY HH:mm'); else return null; }}], fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { if ( aData.value < "60" ) { $('td', nRow).css('background-color', '#E91632'); } else if ( aData.value > "120" ) { $('td', nRow).css('background-color', '#E91632'); } }}); // set textbox filter style $('.dataTables_filter input').attr('type', 'text'); // get push event: measure Socket.on('events', function(ptname) { getMeasures(); }) $scope.$parent.onDeviceChange = function(device) { // inject the datasource to datatable $('table').dataTable().fnClearTable(); $('table').dataTable().fnAddData(device.measures); //if ($scope.device.measures.length > 0) { // var oTT = $('table').dataTable().fnGetInstance( 'datatable-measures' ); //oTT.fnSelect($('table tbody tr')[0]); //} } function getMeasures() { Device.getMeasures() .$promise .then(function(value, responseHeaders) { $('table').dataTable().fnClearTable(); if (value !== undefined) { var devices = JSON.parse(angular.toJson(value)) // set head dashboard $scope.$parent.devices = devices; if (devices.length > 0) { $scope.$parent.device = devices[0]; // inject the datasource to datatable $('table').dataTable().fnAddData(devices[0].measures); //if ($scope.device.measures.length > 0) { // var oTT = $('table').dataTable().fnGetInstance( 'datatable-measures' ); //oTT.fnSelect($('table tbody tr')[0]); //} } } }, function(httpResponse) { var error = httpResponse.data.error; console.log('Error getting measures - ' + error.status + ": " + error.message); }); } getMeasures(); }]) });
masalinas/glukose-cloud
client/modules/dashboard/controllers/DashboardCtrl.js
JavaScript
apache-2.0
3,336
// Copyright 2012 Twitter, Inc // http://www.apache.org/licenses/LICENSE-2.0 var TwitterCldr = require('../../../lib/assets/javascripts/twitter_cldr/core.js'); var data = require('../../../lib/assets/javascripts/twitter_cldr/en.js'); describe("NumberParser", function() { var separators, parser; beforeEach(function() { TwitterCldr.set_data(data); separators = [",", "\\."]; parser = new TwitterCldr.NumberParser(); }); describe("#group_separator()", function() { it("returns the correct group separator", function() { expect(parser.group_separator()).toEqual(","); }); }); describe("#decimal_separator()", function() { it("returns the correct decimal separator", function() { expect(parser.decimal_separator()).toEqual("\\\."); }); }); describe("#identify", function() { it("properly identifies a numeric value", function() { expect( parser.identify("7841", separators[0], separators[1]) ).toEqual({value: "7841", type: "numeric"}); }); it("properly identifies a decimal separator", function() { expect( parser.identify(".", separators[0], separators[1]) ).toEqual({value: ".", type: "decimal"}); }); it("properly identifies a group separator", function() { expect( parser.identify(",", separators[0], separators[1]) ).toEqual({value: ",", type: "group"}); }); it("returns nil if the text doesn't match a number or either separators", function() { expect( parser.identify("abc", separators[0], separators[1]) ).toEqual({value: "abc", type: null}); }); }); describe("#tokenize", function() { it("splits text by numericality and group/decimal separators", function() { expect( parser.tokenize("1,33.00", separators[0], separators[1]) ).toEqual([ {value: "1", type: "numeric"}, {value: ",", type: "group"}, {value: "33", type: "numeric"}, {value: ".", type: "decimal"}, {value: "00", type: "numeric"} ]); }); it("returns an empty array for a non-numeric string", function() { expect(parser.tokenize("abc", separators[0], separators[1])).toEqual([]); }); }); describe("#get_separators", function() { it("returns all separators when strict mode is off", function() { var found_separators = parser.get_separators(false); expect(found_separators.group).toEqual('\\.,\\s'); expect(found_separators.decimal).toEqual('\\.,\\s'); }); it("returns only locale-specific separators when strict mode is on", function() { var found_separators = parser.get_separators(true); expect(found_separators.group).toEqual(','); expect(found_separators.decimal).toEqual('\\.'); }); }); describe("#is_punct_valid", function() { function strip_numerics(token_list) { var tokens = []; for (var idx in token_list) { if (token_list[idx].type != "numeric") { tokens.push(token_list[idx]); } } return tokens; } it("correctly validates a number with no decimal", function() { var tokens = strip_numerics(parser.tokenize("1.337", separators[0], separators[1])); expect(parser.is_punct_valid(tokens)).toEqual(true); }); it("correctly validates a number with a decimal", function() { var tokens = strip_numerics(parser.tokenize("1,337.00", separators[0], separators[1])); expect(parser.is_punct_valid(tokens)).toEqual(true); }); it("reports on an invalid number when it has more than one decimal", function() { var tokens = strip_numerics(parser.tokenize("1.337.00", separators[0], separators[1])); expect(parser.is_punct_valid(tokens)).toEqual(false); }); }); describe("#is_numeric?", function() { it("returns true if the text is numeric", function() { expect(TwitterCldr.NumberParser.is_numeric("4839", "")).toEqual(true); expect(TwitterCldr.NumberParser.is_numeric("1", "")).toEqual(true); }); it("returns false if the text is not purely numeric", function() { expect(TwitterCldr.NumberParser.is_numeric("abc", "")).toEqual(false); expect(TwitterCldr.NumberParser.is_numeric("123abc", "")).toEqual(false); }); it("returns false if the text is blank", function() { expect(TwitterCldr.NumberParser.is_numeric("", "")).toEqual(false); }); it("accepts the given characters as valid numerics", function() { expect(TwitterCldr.NumberParser.is_numeric("a123a", "a")).toEqual(true); expect(TwitterCldr.NumberParser.is_numeric("1,234.56")).toEqual(true); // default separator chars used here }); }); describe("#valid?", function() { it("correctly identifies a series of valid cases", function() { var nums = ["5", "5.0", "1,337", "1,337.0", "0.05", ".5", "1,337,000.00"]; for (var idx in nums) { expect(parser.is_valid(nums[idx])).toEqual(true); } }); it("correctly identifies a series of invalid cases", function() { var nums = ["12.0.0", "5.", "5,"]; for (var idx in nums) { expect(parser.is_valid(nums[idx])).toEqual(false); } }); }); describe("#parse", function() { it("correctly parses a series of valid numbers", function() { var cases = { "5": 5, "5.0": 5.0, "1,337": 1337, "1,337.0": 1337.0, "0.05": 0.05, ".5": 0.5, // Borked "1,337,000.00": 1337000.0 }; for (var text in cases) { var expected = cases[text]; expect(parser.parse(text)).toEqual(expected); } }); it("correctly raises an error when asked to parse invalid numbers", function() { var cases = ["12.0.0", "5.", "5,"]; for (var idx in cases) { expect(function() { parser.parse(cases[idx]) }).toThrow(new Error("Invalid number")); } }); describe("non-strict", function() { it("succeeds in parsing even if inexact punctuation is used", function() { expect(parser.parse("5 100", {strict: false})).toEqual(5100); }); }); }); describe("#try_parse", function() { it("parses correctly with a valid number", function() { expect(parser.try_parse("1,234")).should == 1234; }); it("parses correctly with a valid number and calls the callback", function() { var pre_result = null; parser.try_parse("1,234", null, function(result) { pre_result = result; }); pre_result.should == 1234 }); it("falls back on the default value if the number is invalid", function() { expect(parser.try_parse("5.")).toEqual(null); expect(parser.try_parse("5.", 0)).toEqual(0); }); it("falls back on the block if the number is invalid", function() { var pre_result = null; parser.try_parse("5.", null, function(result) { pre_result = 9 }); expect(pre_result).toEqual(9); }); it("re-raises any unexpected errors", function() { expect(function() { parser.try_parse({}) }).toThrow(); }); it("parses zero correctly", function() { expect(parser.try_parse('0')).toEqual(0); }); }); });
radzinzki/twitter-cldr-js
spec/js/parsers/number_parser.spec.js
JavaScript
apache-2.0
7,207
(function() { function config($stateProvider, $locationProvider) { $locationProvider .html5Mode({ enabled: true, requireBase: false }); $stateProvider .state('landing', { url: '/', controller: 'LandingCtrl as landing', templateUrl: '/templates/landing.html' }) .state('collection', { url: '/collection', controller: 'CollectionCtrl as collection', templateUrl: '/templates/collection.html' }) .state('album', { url: '/album', controller: 'AlbumCtrl as album', templateUrl: '/templates/album.html' }); } angular .module('blocJams', ['ui.router']) .config(config); })();
cuzoaru90/bloc-jams-angular
dist/scripts/app.js
JavaScript
apache-2.0
717
// This module is compiled away! // // micromark works based on character codes. // This module contains constants for the ASCII block and the replacement // character. // A couple of them are handled in a special way, such as the line endings // (CR, LF, and CR+LF, commonly known as end-of-line: EOLs), the tab (horizontal // tab) and its expansion based on what column it’s at (virtual space), // and the end-of-file (eof) character. // As values are preprocessed before handling them, the actual characters LF, // CR, HT, and NUL (which is present as the replacement character), are // guaranteed to not exist. // // Unicode basic latin block. exports.carriageReturn = -5 exports.lineFeed = -4 exports.carriageReturnLineFeed = -3 exports.horizontalTab = -2 exports.virtualSpace = -1 exports.eof = null exports.nul = 0 exports.soh = 1 exports.stx = 2 exports.etx = 3 exports.eot = 4 exports.enq = 5 exports.ack = 6 exports.bel = 7 exports.bs = 8 exports.ht = 9 // `\t` exports.lf = 10 // `\n` exports.vt = 11 // `\v` exports.ff = 12 // `\f` exports.cr = 13 // `\r` exports.so = 14 exports.si = 15 exports.dle = 16 exports.dc1 = 17 exports.dc2 = 18 exports.dc3 = 19 exports.dc4 = 20 exports.nak = 21 exports.syn = 22 exports.etb = 23 exports.can = 24 exports.em = 25 exports.sub = 26 exports.esc = 27 exports.fs = 28 exports.gs = 29 exports.rs = 30 exports.us = 31 exports.space = 32 exports.exclamationMark = 33 // `!` exports.quotationMark = 34 // `"` exports.numberSign = 35 // `#` exports.dollarSign = 36 // `$` exports.percentSign = 37 // `%` exports.ampersand = 38 // `&` exports.apostrophe = 39 // `'` exports.leftParenthesis = 40 // `(` exports.rightParenthesis = 41 // `)` exports.asterisk = 42 // `*` exports.plusSign = 43 // `+` exports.comma = 44 // `,` exports.dash = 45 // `-` exports.dot = 46 // `.` exports.slash = 47 // `/` exports.digit0 = 48 // `0` exports.digit1 = 49 // `1` exports.digit2 = 50 // `2` exports.digit3 = 51 // `3` exports.digit4 = 52 // `4` exports.digit5 = 53 // `5` exports.digit6 = 54 // `6` exports.digit7 = 55 // `7` exports.digit8 = 56 // `8` exports.digit9 = 57 // `9` exports.colon = 58 // `:` exports.semicolon = 59 // `;` exports.lessThan = 60 // `<` exports.equalsTo = 61 // `=` exports.greaterThan = 62 // `>` exports.questionMark = 63 // `?` exports.atSign = 64 // `@` exports.uppercaseA = 65 // `A` exports.uppercaseB = 66 // `B` exports.uppercaseC = 67 // `C` exports.uppercaseD = 68 // `D` exports.uppercaseE = 69 // `E` exports.uppercaseF = 70 // `F` exports.uppercaseG = 71 // `G` exports.uppercaseH = 72 // `H` exports.uppercaseI = 73 // `I` exports.uppercaseJ = 74 // `J` exports.uppercaseK = 75 // `K` exports.uppercaseL = 76 // `L` exports.uppercaseM = 77 // `M` exports.uppercaseN = 78 // `N` exports.uppercaseO = 79 // `O` exports.uppercaseP = 80 // `P` exports.uppercaseQ = 81 // `Q` exports.uppercaseR = 82 // `R` exports.uppercaseS = 83 // `S` exports.uppercaseT = 84 // `T` exports.uppercaseU = 85 // `U` exports.uppercaseV = 86 // `V` exports.uppercaseW = 87 // `W` exports.uppercaseX = 88 // `X` exports.uppercaseY = 89 // `Y` exports.uppercaseZ = 90 // `Z` exports.leftSquareBracket = 91 // `[` exports.backslash = 92 // `\` exports.rightSquareBracket = 93 // `]` exports.caret = 94 // `^` exports.underscore = 95 // `_` exports.graveAccent = 96 // `` ` `` exports.lowercaseA = 97 // `a` exports.lowercaseB = 98 // `b` exports.lowercaseC = 99 // `c` exports.lowercaseD = 100 // `d` exports.lowercaseE = 101 // `e` exports.lowercaseF = 102 // `f` exports.lowercaseG = 103 // `g` exports.lowercaseH = 104 // `h` exports.lowercaseI = 105 // `i` exports.lowercaseJ = 106 // `j` exports.lowercaseK = 107 // `k` exports.lowercaseL = 108 // `l` exports.lowercaseM = 109 // `m` exports.lowercaseN = 110 // `n` exports.lowercaseO = 111 // `o` exports.lowercaseP = 112 // `p` exports.lowercaseQ = 113 // `q` exports.lowercaseR = 114 // `r` exports.lowercaseS = 115 // `s` exports.lowercaseT = 116 // `t` exports.lowercaseU = 117 // `u` exports.lowercaseV = 118 // `v` exports.lowercaseW = 119 // `w` exports.lowercaseX = 120 // `x` exports.lowercaseY = 121 // `y` exports.lowercaseZ = 122 // `z` exports.leftCurlyBrace = 123 // `{` exports.verticalBar = 124 // `|` exports.rightCurlyBrace = 125 // `}` exports.tilde = 126 // `~` exports.del = 127 // Unicode Specials block. exports.byteOrderMarker = 65279 // Unicode Specials block. exports.replacementCharacter = 65533 // `�`
kyleterry/sufr
pkg/ui/node_modules/micromark/lib/character/codes.js
JavaScript
apache-2.0
4,439
/** * Copyright 2009 Google Inc. * * 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("dateutils"); import("execution"); import("fastJSON"); import("fileutils"); import("jsutils.{eachProperty,keys}"); import("stringutils.{randomHash,startsWith,endsWith}"); import("sync"); jimport("net.appjet.common.util.ExpiringMapping"); jimport("net.spy.memcached.MemcachedClient"); jimport("java.net.InetSocketAddress"); import("etherpad.log"); //---------------------------------------------------------------- var _DEFAULT_COOKIE_NAME = "SessionID"; var _DEFAULT_SERVER_EXPIRATION = 3*24*60*60*1000; // 72 hours var _WRITE_SESSIONS_TO_DISK_INTERVAL = 10*60*1000; // 10 minutes var _BUFFER_SIZE = 10 * 1024 * 1024; // 10 MB function getSessionId(cookieName, createIfNotPresent, domain) { if (request.isComet || request.isCron || !request.isDefined) { return null; } if (request.cookies[cookieName]) { return request.cookies[cookieName]; } if (!createIfNotPresent) { return null; } // Keep sessionId in requestCache so this function can be called multiple // times per request without multiple calls to setCookie(). if (!appjet.requestCache.sessionId) { var sessionId = randomHash(16); response.setCookie({ name: cookieName, value: sessionId, path: "/", domain: (domain || undefined), secure: appjet.config.useHttpsUrls, httpOnly: true /* disallow client js access */ }); appjet.requestCache.sessionId = sessionId; } return appjet.requestCache.sessionId; } function getSessionIdSubdomains(sessionId) { var map = _getCachedDb().map; if (map) { return map.get(sessionId) || {}; } return {}; } function _getExpiringSessionMap(db) { sync.callsyncIfTrue(db, function() { return (!db.map); }, function() { db.map = new ExpiringMapping(_DEFAULT_SERVER_EXPIRATION); }); return db.map; } function _getCachedDb() { return appjet.cacheRoot("net.appjet.ajstdlib.session"); } function _getMemcachedClient() { var mc = appjet.cache['memcache-client']; if (!mc) { mc = new MemcachedClient(new InetSocketAddress(appjet.config.memcached, 11211)); appjet.cache['memcache-client'] = mc; // store existing sessions var map = _getCachedDb().map; if (map) { var keyIterator = map.listAllKeys().iterator(); while (keyIterator.hasNext()) { var key = keyIterator.next(); var session = map.get(key); if (keys(session).length == 0) { continue; } var json = fastJSON.stringify(session); mc.set("sessions." + key, _DEFAULT_SERVER_EXPIRATION / 1000, json); } } } return mc; } function _getSessionDataKey(opts) { // Session options. if (!opts) { opts = {}; } var cookieName = opts.cookieName || _DEFAULT_COOKIE_NAME; // get cookie ID (sets response cookie if necessary) var sessionId = getSessionId(cookieName, true, opts.domain); if (!sessionId) { return null; } // get session data object var domainKey = "." + request.domain; return [sessionId, domainKey]; } //---------------------------------------------------------------- function getSession(opts) { var dataKey = _getSessionDataKey(opts); if (!dataKey) { return null; } if (appjet.requestCache.sessionDomains) { return appjet.requestCache.sessionDomains[dataKey[1]]; } if (appjet.config.memcached) { var json = _getMemcachedClient().get("sessions." + dataKey[0]); var sessionData = json ? fastJSON.parse(json) : {}; //log.info("MEMCACHE GOT SESSION:" + dataKey+ " VAL:" + json); appjet.requestCache.sessionDomains = sessionData; return sessionData[dataKey[1]]; } else { // get expiring session map var db = _getCachedDb(); var map = _getExpiringSessionMap(db); var sessionData = map.get(dataKey[0]) || {}; if (!sessionData[dataKey[1]]) { sessionData[dataKey[1]] = {}; map.put(dataKey[0], sessionData); } else { map.touch(dataKey[0]); } appjet.requestCache.sessionDomains = sessionData; return sessionData[dataKey[1]]; } } function saveSession(opts) { if (!appjet.config.memcached) { return; } if (!appjet.requestCache.sessionDomains) { return; } var json = fastJSON.stringify(appjet.requestCache.sessionDomains); if (json == "{}") { return; } var dataKey = _getSessionDataKey(opts); _getMemcachedClient().set("sessions." + dataKey[0], _DEFAULT_SERVER_EXPIRATION / 1000, json); //log.info("MEMCACHE SAVED SESSION:" + dataKey+ " VAL:" + json); } function destroySession(opts) { var dataKey = _getSessionDataKey(opts); if (!dataKey) { return null; } if (appjet.config.memcached) { // todo: delete from memcache? } else { // get expiring session map var db = _getCachedDb(); var map = _getExpiringSessionMap(db); map.remove(dataKey[0]); appjet.requestCache.sessionDomains = null; } } function writeSessionsToDisk() { try { var dateString = dateutils.dateFormat(new Date(), "yyyy-MM-dd"); var dataFile = new Packages.java.io.File(appjet.config.sessionStoreDir+"/sessions-"+dateString+".jslog"); var tmpFile = new Packages.java.io.File(dataFile.toString() + ".tmp"); dataFile.getParentFile().mkdirs(); var writer = new java.io.BufferedWriter(new java.io.FileWriter(tmpFile), _BUFFER_SIZE); var map = _getCachedDb().map; if (! map) { return; } var keyIterator = map.listAllKeys().iterator(); while (keyIterator.hasNext()) { var key = keyIterator.next(); var session = map.get(key); if (!session) { continue; } // don't write sessions that don't have accounts // they're ok to lose on restart var hasAccount = false; for (domain in session) { if ('proAccount' in session[domain]) { hasAccount = true; break; } } if (!hasAccount) { continue; } if (keys(session).length == 0) { continue; } var obj = { key: key, session: session }; var json = fastJSON.stringify(obj); writer.write(json); writer.write("\n"); } writer.flush(); writer.close(); tmpFile.renameTo(dataFile); } finally { _scheduleWriteToDisk(); } } function cleanUpSessions(shouldDiscardSession) { var map = _getCachedDb().map; if (! map) { return; } var keyIterator = map.listAllKeys().iterator(); var keysToDelete = []; while (keyIterator.hasNext()) { var key = keyIterator.next(); var session = map.get(key); if (!session) { continue; } for (domain in session) { if (shouldDiscardSession(session[domain])) { keysToDelete.push(key); break; } } } keysToDelete.forEach(function(key) { map.remove(key); }) return keysToDelete.length; } function _extractDate(fname) { var datePart = fname.substr("sessions-".length, "2009-09-24".length); return Number(datePart.split("-").join("")); } function readLatestSessionsFromDisk() { var dir = new Packages.java.io.File(appjet.config.sessionStoreDir); if (! dir.exists()) { return; } var files = dir.listFiles(new Packages.java.io.FilenameFilter({ accept: function(dir, name) { return startsWith(name, "sessions") && endsWith(name, ".jslog") } })); if (files.length == 0) { return; } var latestFile = files[0]; for (var i = 1; i < files.length; ++i) { if (_extractDate(files[i].getName()) > _extractDate(latestFile.getName())) { latestFile = files[i]; } } var map = _getExpiringSessionMap(_getCachedDb()); fileutils.eachFileLine(latestFile, function(json) { try { var obj = fastJSON.parse(json, true /* parseDate */); var key = obj.key; var session = obj.session; map.put(key, session); } catch (err) { Packages.java.lang.System.out.println("Error reading sessions file on line '"+json+"': "+String(err)); } }); latestFile.renameTo(new Packages.java.io.File(latestFile.getParent()+"/used-"+latestFile.getName())); execution.initTaskThreadPool('sessions', 1); _scheduleWriteToDisk(); } function _scheduleWriteToDisk() { if (appjet.cache.shutdownHandlerIsRunning) { return; } execution.scheduleTask('sessions', 'sessionsWriteToDisk', _WRITE_SESSIONS_TO_DISK_INTERVAL, []); }
whackpad/whackpad
infrastructure/framework-src/modules/sessions.js
JavaScript
apache-2.0
8,795
CKEDITOR.plugins.setLang("colordialog","az",{clear:"Təmizlə",highlight:"Ayırmaq",options:"Rəng seçimləri",selected:"Seçilmiş rəng",title:"Rəngi seç"});
AK-47-D/cms
src/main/resources/static/manage/bower_components/ckeditor/plugins/colordialog/lang/az.js
JavaScript
apache-2.0
168
(function (factory) { if (typeof module === 'object' && typeof module.exports === 'object') { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === 'function' && define.amd) { define(["require", "exports", '@angular/core'], factory); } })(function (require, exports) { "use strict"; var core_1 = require('@angular/core'); /** * \@name Thumbnail * \@module ionic * \@description * A Thumbnail is a component that creates a squared image for an item. * Thumbnails can be place on the left or right side of an item with the `item-left` or `item-right` directive. * @see {\@link /docs/v2/components/#thumbnail-list Thumbnail Component Docs} */ var Thumbnail = (function () { function Thumbnail() { } Thumbnail.decorators = [ { type: core_1.Directive, args: [{ selector: 'ion-thumbnail' },] }, ]; /** @nocollapse */ Thumbnail.ctorParameters = function () { return []; }; return Thumbnail; }()); exports.Thumbnail = Thumbnail; function Thumbnail_tsickle_Closure_declarations() { /** @type {?} */ Thumbnail.decorators; /** * @nocollapse * @type {?} */ Thumbnail.ctorParameters; } }); //# sourceMappingURL=thumbnail.js.map
sajithaliyanage/Travel_SriLanka
node_modules/ionic-angular/umd/components/thumbnail/thumbnail.js
JavaScript
apache-2.0
1,435
(function() { 'use strict'; angular .module('gpmrApp') .factory('PasswordResetInit', PasswordResetInit); PasswordResetInit.$inject = ['$resource']; function PasswordResetInit($resource) { var service = $resource('api/account/reset_password/init', {}, {}); return service; } })();
chrislovecnm/gpmr
pet-race-ui/src/main/webapp/app/services/auth/password-reset-init.service.js
JavaScript
apache-2.0
336
/** * @author mrdoob / http://mrdoob.com/ * @author ryg / http://farbrausch.de/~fg * @author mraleph / http://mrale.ph/ * @author daoshengmu / http://dsmu.me/ */ THREE.SoftwareRenderer = function ( parameters ) { console.log( 'THREE.SoftwareRenderer', THREE.REVISION ); parameters = parameters || {}; var canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ); var context = canvas.getContext( '2d', { alpha: parameters.alpha === true } ); var alpha = parameters.alpha; var shaders = {}; var textures = {}; var canvasWidth, canvasHeight; var canvasWBlocks, canvasHBlocks; var viewportXScale, viewportYScale, viewportZScale; var viewportXOffs, viewportYOffs, viewportZOffs; var clearColor = new THREE.Color( 0x000000 ); var imagedata, data, zbuffer; var numBlocks, blockMaxZ, blockFlags; var BLOCK_ISCLEAR = ( 1 << 0 ); var BLOCK_NEEDCLEAR = ( 1 << 1 ); var subpixelBits = 4; var subpixelBias = ( 1 << subpixelBits ) - 1; var blockShift = 3; var blockSize = 1 << blockShift; var maxZVal = ( 1 << 24 ); // Note: You want to size this so you don't get overflows. var lineMode = false; var lookVector = new THREE.Vector3( 0, 0, 1 ); var crossVector = new THREE.Vector3(); var rectx1 = Infinity, recty1 = Infinity; var rectx2 = 0, recty2 = 0; var prevrectx1 = Infinity, prevrecty1 = Infinity; var prevrectx2 = 0, prevrecty2 = 0; var projector = new THREE.Projector(); var spriteV1 = new THREE.Vector4(); var spriteV2 = new THREE.Vector4(); var spriteV3 = new THREE.Vector4(); var spriteUV1 = new THREE.Vector2(); var spriteUV2 = new THREE.Vector2(); var spriteUV3 = new THREE.Vector2(); var mpVPool = []; var mpVPoolCount = 0; var mpNPool = []; var mpNPoolCount = 0; var mpUVPool = []; var mpUVPoolCount = 0; this.domElement = canvas; this.autoClear = true; // WebGLRenderer compatibility this.supportsVertexTextures = function () {}; this.setFaceCulling = function () {}; this.setClearColor = function ( color ) { clearColor.set( color ); clearColorBuffer( clearColor ); }; this.setPixelRatio = function () {}; this.setSize = function ( width, height ) { canvasWBlocks = Math.floor( width / blockSize ); canvasHBlocks = Math.floor( height / blockSize ); canvasWidth = canvasWBlocks * blockSize; canvasHeight = canvasHBlocks * blockSize; var fixScale = 1 << subpixelBits; viewportXScale = fixScale * canvasWidth / 2; viewportYScale = - fixScale * canvasHeight / 2; viewportZScale = maxZVal / 2; viewportXOffs = fixScale * canvasWidth / 2 + 0.5; viewportYOffs = fixScale * canvasHeight / 2 + 0.5; viewportZOffs = maxZVal / 2 + 0.5; canvas.width = canvasWidth; canvas.height = canvasHeight; context.fillStyle = alpha ? "rgba(0, 0, 0, 0)" : clearColor.getStyle(); context.fillRect( 0, 0, canvasWidth, canvasHeight ); imagedata = context.getImageData( 0, 0, canvasWidth, canvasHeight ); data = imagedata.data; zbuffer = new Int32Array( data.length / 4 ); numBlocks = canvasWBlocks * canvasHBlocks; blockMaxZ = new Int32Array( numBlocks ); blockFlags = new Uint8Array( numBlocks ); for ( var i = 0, l = zbuffer.length; i < l; i ++ ) { zbuffer[ i ] = maxZVal; } for ( var i = 0; i < numBlocks; i ++ ) { blockFlags[ i ] = BLOCK_ISCLEAR; } clearColorBuffer( clearColor ); }; this.setSize( canvas.width, canvas.height ); this.clear = function () { rectx1 = Infinity; recty1 = Infinity; rectx2 = 0; recty2 = 0; mpVPoolCount = 0; mpNPoolCount = 0; mpUVPoolCount = 0; for ( var i = 0; i < numBlocks; i ++ ) { blockMaxZ[ i ] = maxZVal; blockFlags[ i ] = ( blockFlags[ i ] & BLOCK_ISCLEAR ) ? BLOCK_ISCLEAR : BLOCK_NEEDCLEAR; } }; this.render = function ( scene, camera ) { // TODO: Check why autoClear can't be false. this.clear(); var background = scene.background; if ( background && background.isColor ) { clearColorBuffer( background ); } var renderData = projector.projectScene( scene, camera, false, false ); var elements = renderData.elements; for ( var e = 0, el = elements.length; e < el; e ++ ) { var element = elements[ e ]; var material = element.material; var shader = getMaterialShader( material ); if ( ! shader ) continue; if ( element instanceof THREE.RenderableFace ) { if ( ! element.uvs ) { drawTriangle( element.v1.positionScreen, element.v2.positionScreen, element.v3.positionScreen, null, null, null, shader, element, material ); } else { drawTriangle( element.v1.positionScreen, element.v2.positionScreen, element.v3.positionScreen, element.uvs[ 0 ], element.uvs[ 1 ], element.uvs[ 2 ], shader, element, material ); } } else if ( element instanceof THREE.RenderableSprite ) { var scaleX = element.scale.x * 0.5; var scaleY = element.scale.y * 0.5; spriteV1.copy( element ); spriteV1.x -= scaleX; spriteV1.y += scaleY; spriteV2.copy( element ); spriteV2.x -= scaleX; spriteV2.y -= scaleY; spriteV3.copy( element ); spriteV3.x += scaleX; spriteV3.y += scaleY; if ( material.map ) { spriteUV1.set( 0, 1 ); spriteUV2.set( 0, 0 ); spriteUV3.set( 1, 1 ); drawTriangle( spriteV1, spriteV2, spriteV3, spriteUV1, spriteUV2, spriteUV3, shader, element, material ); } else { drawTriangle( spriteV1, spriteV2, spriteV3, null, null, null, shader, element, material ); } spriteV1.copy( element ); spriteV1.x += scaleX; spriteV1.y += scaleY; spriteV2.copy( element ); spriteV2.x -= scaleX; spriteV2.y -= scaleY; spriteV3.copy( element ); spriteV3.x += scaleX; spriteV3.y -= scaleY; if ( material.map ) { spriteUV1.set( 1, 1 ); spriteUV2.set( 0, 0 ); spriteUV3.set( 1, 0 ); drawTriangle( spriteV1, spriteV2, spriteV3, spriteUV1, spriteUV2, spriteUV3, shader, element, material ); } else { drawTriangle( spriteV1, spriteV2, spriteV3, null, null, null, shader, element, material ); } } else if ( element instanceof THREE.RenderableLine ) { var shader = getMaterialShader( material ); drawLine( element.v1.positionScreen, element.v2.positionScreen, element.vertexColors[ 0 ], element.vertexColors[ 1 ], shader, material ); } } finishClear(); var x = Math.min( rectx1, prevrectx1 ); var y = Math.min( recty1, prevrecty1 ); var width = Math.max( rectx2, prevrectx2 ) - x; var height = Math.max( recty2, prevrecty2 ) - y; /* // debug; draw zbuffer for ( var i = 0, l = zbuffer.length; i < l; i++ ) { var o = i * 4; var v = (65535 - zbuffer[ i ]) >> 3; data[ o + 0 ] = v; data[ o + 1 ] = v; data[ o + 2 ] = v; data[ o + 3 ] = 255; } */ if ( x !== Infinity ) { context.putImageData( imagedata, 0, 0, x, y, width, height ); } prevrectx1 = rectx1; prevrecty1 = recty1; prevrectx2 = rectx2; prevrecty2 = recty2; }; function setSize( width, height ) { canvasWBlocks = Math.floor( width / blockSize ); canvasHBlocks = Math.floor( height / blockSize ); canvasWidth = canvasWBlocks * blockSize; canvasHeight = canvasHBlocks * blockSize; var fixScale = 1 << subpixelBits; viewportXScale = fixScale * canvasWidth / 2; viewportYScale = -fixScale * canvasHeight / 2; viewportZScale = maxZVal / 2; viewportXOffs = fixScale * canvasWidth / 2 + 0.5; viewportYOffs = fixScale * canvasHeight / 2 + 0.5; viewportZOffs = maxZVal / 2 + 0.5; canvas.width = canvasWidth; canvas.height = canvasHeight; context.fillStyle = alpha ? "rgba(0, 0, 0, 0)" : clearColor.getStyle(); context.fillRect( 0, 0, canvasWidth, canvasHeight ); imagedata = context.getImageData( 0, 0, canvasWidth, canvasHeight ); data = imagedata.data; zbuffer = new Int32Array( data.length / 4 ); numBlocks = canvasWBlocks * canvasHBlocks; blockMaxZ = new Int32Array( numBlocks ); blockFlags = new Uint8Array( numBlocks ); for ( var i = 0, l = zbuffer.length; i < l; i ++ ) { zbuffer[ i ] = maxZVal; } for ( var i = 0; i < numBlocks; i ++ ) { blockFlags[ i ] = BLOCK_ISCLEAR; } clearColorBuffer( clearColor ); } function clearColorBuffer( color ) { var size = canvasWidth * canvasHeight * 4; for ( var i = 0; i < size; i += 4 ) { data[ i ] = color.r * 255 | 0; data[ i + 1 ] = color.g * 255 | 0; data[ i + 2 ] = color.b * 255 | 0; data[ i + 3 ] = alpha ? 0 : 255; } context.fillStyle = alpha ? "rgba(0, 0, 0, 0)" : color.getStyle(); context.fillRect( 0, 0, canvasWidth, canvasHeight ); } function getPalette( material, bSimulateSpecular ) { var i = 0, j = 0; var diffuseR = material.color.r * 255; var diffuseG = material.color.g * 255; var diffuseB = material.color.b * 255; var palette = new Uint8Array( 256 * 3 ); if ( bSimulateSpecular ) { while ( i < 204 ) { palette[ j ++ ] = Math.min( i * diffuseR / 204, 255 ); palette[ j ++ ] = Math.min( i * diffuseG / 204, 255 ); palette[ j ++ ] = Math.min( i * diffuseB / 204, 255 ); ++ i; } while ( i < 256 ) { // plus specular highlight palette[ j ++ ] = Math.min( diffuseR + ( i - 204 ) * ( 255 - diffuseR ) / 82, 255 ); palette[ j ++ ] = Math.min( diffuseG + ( i - 204 ) * ( 255 - diffuseG ) / 82, 255 ); palette[ j ++ ] = Math.min( diffuseB + ( i - 204 ) * ( 255 - diffuseB ) / 82, 255 ); ++ i; } } else { while ( i < 256 ) { palette[ j ++ ] = Math.min( i * diffuseR / 255, 255 ); palette[ j ++ ] = Math.min( i * diffuseG / 255, 255 ); palette[ j ++ ] = Math.min( i * diffuseB / 255, 255 ); ++ i; } } return palette; } function basicMaterialShader( buffer, depthBuf, offset, depth, u, v, n, face, material ) { var colorOffset = offset * 4; var texture = textures[ material.map.id ]; if ( ! texture.data ) return; var tdim = texture.width; var isTransparent = material.transparent; var tbound = tdim - 1; var tdata = texture.data; var tIndex = ( ( ( v * tdim ) & tbound ) * tdim + ( ( u * tdim ) & tbound ) ) * 4; if ( ! isTransparent ) { buffer[ colorOffset ] = tdata[ tIndex ]; buffer[ colorOffset + 1 ] = tdata[ tIndex + 1 ]; buffer[ colorOffset + 2 ] = tdata[ tIndex + 2 ]; buffer[ colorOffset + 3 ] = ( material.opacity << 8 ) - 1; depthBuf[ offset ] = depth; } else { var srcR = tdata[ tIndex ]; var srcG = tdata[ tIndex + 1 ]; var srcB = tdata[ tIndex + 2 ]; var opaci = tdata[ tIndex + 3 ] * material.opacity / 255; var destR = buffer[ colorOffset ]; var destG = buffer[ colorOffset + 1 ]; var destB = buffer[ colorOffset + 2 ]; buffer[ colorOffset ] = ( srcR * opaci + destR * ( 1 - opaci ) ); buffer[ colorOffset + 1 ] = ( srcG * opaci + destG * ( 1 - opaci ) ); buffer[ colorOffset + 2 ] = ( srcB * opaci + destB * ( 1 - opaci ) ); buffer[ colorOffset + 3 ] = ( material.opacity << 8 ) - 1; if ( buffer[ colorOffset + 3 ] == 255 ) // Only opaue pixls write to the depth buffer depthBuf[ offset ] = depth; } } function lightingMaterialShader( buffer, depthBuf, offset, depth, u, v, n, face, material ) { var colorOffset = offset * 4; var texture = textures[ material.map.id ]; if ( ! texture.data ) return; var tdim = texture.width; var isTransparent = material.transparent; var cIndex = ( n > 0 ? ( ~~ n ) : 0 ) * 3; var tbound = tdim - 1; var tdata = texture.data; var tIndex = ( ( ( v * tdim ) & tbound ) * tdim + ( ( u * tdim ) & tbound ) ) * 4; if ( ! isTransparent ) { buffer[ colorOffset ] = ( material.palette[ cIndex ] * tdata[ tIndex ] ) >> 8; buffer[ colorOffset + 1 ] = ( material.palette[ cIndex + 1 ] * tdata[ tIndex + 1 ] ) >> 8; buffer[ colorOffset + 2 ] = ( material.palette[ cIndex + 2 ] * tdata[ tIndex + 2 ] ) >> 8; buffer[ colorOffset + 3 ] = ( material.opacity << 8 ) - 1; depthBuf[ offset ] = depth; } else { var foreColorR = material.palette[ cIndex ] * tdata[ tIndex ]; var foreColorG = material.palette[ cIndex + 1 ] * tdata[ tIndex + 1 ]; var foreColorB = material.palette[ cIndex + 2 ] * tdata[ tIndex + 2 ]; var opaci = tdata[ tIndex + 3 ] * material.opacity / 256; var destR = buffer[ colorOffset ]; var destG = buffer[ colorOffset + 1 ]; var destB = buffer[ colorOffset + 2 ]; buffer[ colorOffset ] = foreColorR * opaci + destR * ( 1 - opaci ); buffer[ colorOffset + 1 ] = foreColorG * opaci + destG * ( 1 - opaci ); buffer[ colorOffset + 2 ] = foreColorB * opaci + destB * ( 1 - opaci ); buffer[ colorOffset + 3 ] = ( material.opacity << 8 ) - 1; if ( buffer[ colorOffset + 3 ] == 255 ) // Only opaue pixls write to the depth buffer depthBuf[ offset ] = depth; } } function getMaterialShader( material ) { var id = material.id; var shader = shaders[ id ]; if ( shader && material.map && !textures[ material.map.id ] ) delete shaders[ id ]; if ( shaders[ id ] === undefined || material.needsUpdate === true ) { if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial || material instanceof THREE.SpriteMaterial ) { if ( material instanceof THREE.MeshLambertMaterial ) { // Generate color palette if ( ! material.palette ) { material.palette = getPalette( material, false ); } } else if ( material instanceof THREE.MeshPhongMaterial ) { // Generate color palette if ( ! material.palette ) { material.palette = getPalette( material, true ); } } var string; if ( material.map ) { var texture = new THREE.SoftwareRenderer.Texture(); texture.fromImage( material.map.image ); if ( ! texture.data ) return; textures[ material.map.id ] = texture; if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.SpriteMaterial ) { shader = basicMaterialShader; } else { shader = lightingMaterialShader; } } else { if ( material.vertexColors === THREE.FaceColors ) { string = [ 'var colorOffset = offset * 4;', 'buffer[ colorOffset ] = face.color.r * 255;', 'buffer[ colorOffset + 1 ] = face.color.g * 255;', 'buffer[ colorOffset + 2 ] = face.color.b * 255;', 'buffer[ colorOffset + 3 ] = material.opacity * 255;', 'depthBuf[ offset ] = depth;' ].join( '\n' ); } else { string = [ 'var colorOffset = offset * 4;', 'buffer[ colorOffset ] = material.color.r * 255;', 'buffer[ colorOffset + 1 ] = material.color.g * 255;', 'buffer[ colorOffset + 2 ] = material.color.b * 255;', 'buffer[ colorOffset + 3 ] = material.opacity * 255;', 'depthBuf[ offset ] = depth;' ].join( '\n' ); } shader = new Function( 'buffer, depthBuf, offset, depth, u, v, n, face, material', string ); } } else if ( material instanceof THREE.LineBasicMaterial ) { var string = [ 'var colorOffset = offset * 4;', 'buffer[ colorOffset ] = material.color.r * (color1.r+color2.r) * 0.5 * 255;', 'buffer[ colorOffset + 1 ] = material.color.g * (color1.g+color2.g) * 0.5 * 255;', 'buffer[ colorOffset + 2 ] = material.color.b * (color1.b+color2.b) * 0.5 * 255;', 'buffer[ colorOffset + 3 ] = 255;', 'depthBuf[ offset ] = depth;' ].join( '\n' ); shader = new Function( 'buffer, depthBuf, offset, depth, color1, color2, material', string ); } else { var string = [ 'var colorOffset = offset * 4;', 'buffer[ colorOffset ] = u * 255;', 'buffer[ colorOffset + 1 ] = v * 255;', 'buffer[ colorOffset + 2 ] = 0;', 'buffer[ colorOffset + 3 ] = 255;', 'depthBuf[ offset ] = depth;' ].join( '\n' ); shader = new Function( 'buffer, depthBuf, offset, depth, u, v, n, face, material', string ); } shaders[ id ] = shader; material.needsUpdate = false; } return shader; } /* function clearRectangle( x1, y1, x2, y2 ) { var xmin = Math.max( Math.min( x1, x2 ), 0 ); var xmax = Math.min( Math.max( x1, x2 ), canvasWidth ); var ymin = Math.max( Math.min( y1, y2 ), 0 ); var ymax = Math.min( Math.max( y1, y2 ), canvasHeight ); var offset = ( xmin + ymin * canvasWidth ) * 4 + 3; var linestep = ( canvasWidth - ( xmax - xmin ) ) * 4; for ( var y = ymin; y < ymax; y ++ ) { for ( var x = xmin; x < xmax; x ++ ) { data[ offset += 4 ] = 0; } offset += linestep; } } */ function drawTriangle( v1, v2, v3, uv1, uv2, uv3, shader, face, material ) { // TODO: Implement per-pixel z-clipping if ( v1.z < - 1 || v1.z > 1 || v2.z < - 1 || v2.z > 1 || v3.z < - 1 || v3.z > 1 ) return; // https://gist.github.com/2486101 // explanation: http://pouet.net/topic.php?which=8760&page=1 var fixscale = ( 1 << subpixelBits ); // 28.4 fixed-point coordinates var x1 = ( v1.x * viewportXScale + viewportXOffs ) | 0; var x2 = ( v2.x * viewportXScale + viewportXOffs ) | 0; var x3 = ( v3.x * viewportXScale + viewportXOffs ) | 0; var y1 = ( v1.y * viewportYScale + viewportYOffs ) | 0; var y2 = ( v2.y * viewportYScale + viewportYOffs ) | 0; var y3 = ( v3.y * viewportYScale + viewportYOffs ) | 0; var bHasNormal = face.vertexNormalsModel && face.vertexNormalsModel.length; var bHasUV = uv1 && uv2 && uv3; var longestSide = Math.max( Math.sqrt( ( x1 - x2 ) * ( x1 - x2 ) + ( y1 - y2 ) * ( y1 - y2 ) ), Math.sqrt( ( x2 - x3 ) * ( x2 - x3 ) + ( y2 - y3 ) * ( y2 - y3 ) ), Math.sqrt( ( x3 - x1 ) * ( x3 - x1 ) + ( y3 - y1 ) * ( y3 - y1 ) ) ); if ( ! ( face instanceof THREE.RenderableSprite ) && ( longestSide > 100 * fixscale ) ) { // 1 // |\ // |a\ // |__\ // |\c|\ // |b\|d\ // |__\__\ // 2 3 var tempFace = { vertexNormalsModel: [], color: face.color }; var mpUV12, mpUV23, mpUV31; if ( bHasUV ) { if ( mpUVPoolCount === mpUVPool.length ) { mpUV12 = new THREE.Vector2(); mpUVPool.push( mpUV12 ); ++mpUVPoolCount; mpUV23 = new THREE.Vector2(); mpUVPool.push( mpUV23 ); ++mpUVPoolCount; mpUV31 = new THREE.Vector2(); mpUVPool.push( mpUV31 ); ++mpUVPoolCount; } else { mpUV12 = mpUVPool[ mpUVPoolCount ]; ++mpUVPoolCount; mpUV23 = mpUVPool[ mpUVPoolCount ]; ++mpUVPoolCount; mpUV31 = mpUVPool[ mpUVPoolCount ]; ++mpUVPoolCount; } var weight; weight = ( 1 + v2.z ) * ( v2.w / v1.w ) / ( 1 + v1.z ); mpUV12.copy( uv1 ).multiplyScalar( weight ).add( uv2 ).multiplyScalar( 1 / ( weight + 1 ) ); weight = ( 1 + v3.z ) * ( v3.w / v2.w ) / ( 1 + v2.z ); mpUV23.copy( uv2 ).multiplyScalar( weight ).add( uv3 ).multiplyScalar( 1 / ( weight + 1 ) ); weight = ( 1 + v1.z ) * ( v1.w / v3.w ) / ( 1 + v3.z ); mpUV31.copy( uv3 ).multiplyScalar( weight ).add( uv1 ).multiplyScalar( 1 / ( weight + 1 ) ); } var mpV12, mpV23, mpV31; if ( mpVPoolCount === mpVPool.length ) { mpV12 = new THREE.Vector4(); mpVPool.push( mpV12 ); ++mpVPoolCount; mpV23 = new THREE.Vector4(); mpVPool.push( mpV23 ); ++mpVPoolCount; mpV31 = new THREE.Vector4(); mpVPool.push( mpV31 ); ++mpVPoolCount; } else { mpV12 = mpVPool[ mpVPoolCount ]; ++mpVPoolCount; mpV23 = mpVPool[ mpVPoolCount ]; ++mpVPoolCount; mpV31 = mpVPool[ mpVPoolCount ]; ++mpVPoolCount; } mpV12.copy( v1 ).add( v2 ).multiplyScalar( 0.5 ); mpV23.copy( v2 ).add( v3 ).multiplyScalar( 0.5 ); mpV31.copy( v3 ).add( v1 ).multiplyScalar( 0.5 ); var mpN12, mpN23, mpN31; if ( bHasNormal ) { if ( mpNPoolCount === mpNPool.length ) { mpN12 = new THREE.Vector3(); mpNPool.push( mpN12 ); ++mpNPoolCount; mpN23 = new THREE.Vector3(); mpNPool.push( mpN23 ); ++mpNPoolCount; mpN31 = new THREE.Vector3(); mpNPool.push( mpN31 ); ++mpNPoolCount; } else { mpN12 = mpNPool[ mpNPoolCount ]; ++mpNPoolCount; mpN23 = mpNPool[ mpNPoolCount ]; ++mpNPoolCount; mpN31 = mpNPool[ mpNPoolCount ]; ++mpNPoolCount; } mpN12.copy( face.vertexNormalsModel[ 0 ] ).add( face.vertexNormalsModel[ 1 ] ).normalize(); mpN23.copy( face.vertexNormalsModel[ 1 ] ).add( face.vertexNormalsModel[ 2 ] ).normalize(); mpN31.copy( face.vertexNormalsModel[ 2 ] ).add( face.vertexNormalsModel[ 0 ] ).normalize(); } // a if ( bHasNormal ) { tempFace.vertexNormalsModel[ 0 ] = face.vertexNormalsModel[ 0 ]; tempFace.vertexNormalsModel[ 1 ] = mpN12; tempFace.vertexNormalsModel[ 2 ] = mpN31; } drawTriangle( v1, mpV12, mpV31, uv1, mpUV12, mpUV31, shader, tempFace, material ); // b if ( bHasNormal ) { tempFace.vertexNormalsModel[ 0 ] = face.vertexNormalsModel[ 1 ]; tempFace.vertexNormalsModel[ 1 ] = mpN23; tempFace.vertexNormalsModel[ 2 ] = mpN12; } drawTriangle( v2, mpV23, mpV12, uv2, mpUV23, mpUV12, shader, tempFace, material ); // c if ( bHasNormal ) { tempFace.vertexNormalsModel[ 0 ] = mpN12; tempFace.vertexNormalsModel[ 1 ] = mpN23; tempFace.vertexNormalsModel[ 2 ] = mpN31; } drawTriangle( mpV12, mpV23, mpV31, mpUV12, mpUV23, mpUV31, shader, tempFace, material ); // d if ( bHasNormal ) { tempFace.vertexNormalsModel[ 0 ] = face.vertexNormalsModel[ 2 ]; tempFace.vertexNormalsModel[ 1 ] = mpN31; tempFace.vertexNormalsModel[ 2 ] = mpN23; } drawTriangle( v3, mpV31, mpV23, uv3, mpUV31, mpUV23, shader, tempFace, material ); return; } // Z values (.28 fixed-point) var z1 = ( v1.z * viewportZScale + viewportZOffs ) | 0; var z2 = ( v2.z * viewportZScale + viewportZOffs ) | 0; var z3 = ( v3.z * viewportZScale + viewportZOffs ) | 0; // UV values var bHasUV = false; var tu1, tv1, tu2, tv2, tu3, tv3; if ( uv1 && uv2 && uv3 ) { bHasUV = true; tu1 = uv1.x; tv1 = 1 - uv1.y; tu2 = uv2.x; tv2 = 1 - uv2.y; tu3 = uv3.x; tv3 = 1 - uv3.y; } // Normal values var n1, n2, n3, nz1, nz2, nz3; if ( bHasNormal ) { n1 = face.vertexNormalsModel[ 0 ]; n2 = face.vertexNormalsModel[ 1 ]; n3 = face.vertexNormalsModel[ 2 ]; nz1 = n1.z * 255; nz2 = n2.z * 255; nz3 = n3.z * 255; } // Deltas var dx12 = x1 - x2, dy12 = y2 - y1; var dx23 = x2 - x3, dy23 = y3 - y2; var dx31 = x3 - x1, dy31 = y1 - y3; // Bounding rectangle var minx = Math.max( ( Math.min( x1, x2, x3 ) + subpixelBias ) >> subpixelBits, 0 ); var maxx = Math.min( ( Math.max( x1, x2, x3 ) + subpixelBias ) >> subpixelBits, canvasWidth ); var miny = Math.max( ( Math.min( y1, y2, y3 ) + subpixelBias ) >> subpixelBits, 0 ); var maxy = Math.min( ( Math.max( y1, y2, y3 ) + subpixelBias ) >> subpixelBits, canvasHeight ); rectx1 = Math.min( minx, rectx1 ); rectx2 = Math.max( maxx, rectx2 ); recty1 = Math.min( miny, recty1 ); recty2 = Math.max( maxy, recty2 ); // Block size, standard 8x8 (must be power of two) var q = blockSize; // Start in corner of 8x8 block minx &= ~ ( q - 1 ); miny &= ~ ( q - 1 ); // Constant part of half-edge functions var minXfixscale = ( minx << subpixelBits ); var minYfixscale = ( miny << subpixelBits ); var c1 = dy12 * ( ( minXfixscale ) - x1 ) + dx12 * ( ( minYfixscale ) - y1 ); var c2 = dy23 * ( ( minXfixscale ) - x2 ) + dx23 * ( ( minYfixscale ) - y2 ); var c3 = dy31 * ( ( minXfixscale ) - x3 ) + dx31 * ( ( minYfixscale ) - y3 ); // Correct for fill convention if ( dy12 > 0 || ( dy12 == 0 && dx12 > 0 ) ) c1 ++; if ( dy23 > 0 || ( dy23 == 0 && dx23 > 0 ) ) c2 ++; if ( dy31 > 0 || ( dy31 == 0 && dx31 > 0 ) ) c3 ++; // Note this doesn't kill subpixel precision, but only because we test for >=0 (not >0). // It's a bit subtle. :) c1 = ( c1 - 1 ) >> subpixelBits; c2 = ( c2 - 1 ) >> subpixelBits; c3 = ( c3 - 1 ) >> subpixelBits; // Z interpolation setup var dz12 = z1 - z2, dz31 = z3 - z1; var invDet = 1.0 / ( dx12 * dy31 - dx31 * dy12 ); var dzdx = ( invDet * ( dz12 * dy31 - dz31 * dy12 ) ); // dz per one subpixel step in x var dzdy = ( invDet * ( dz12 * dx31 - dx12 * dz31 ) ); // dz per one subpixel step in y // Z at top/left corner of rast area var cz = ( z1 + ( ( minXfixscale ) - x1 ) * dzdx + ( ( minYfixscale ) - y1 ) * dzdy ) | 0; // Z pixel steps dzdx = ( dzdx * fixscale ) | 0; dzdy = ( dzdy * fixscale ) | 0; var dtvdx, dtvdy, cbtu, cbtv; if ( bHasUV ) { // UV interpolation setup var dtu12 = tu1 - tu2, dtu31 = tu3 - tu1; var dtudx = ( invDet * ( dtu12 * dy31 - dtu31 * dy12 ) ); // dtu per one subpixel step in x var dtudy = ( invDet * ( dtu12 * dx31 - dx12 * dtu31 ) ); // dtu per one subpixel step in y var dtv12 = tv1 - tv2, dtv31 = tv3 - tv1; dtvdx = ( invDet * ( dtv12 * dy31 - dtv31 * dy12 ) ); // dtv per one subpixel step in x dtvdy = ( invDet * ( dtv12 * dx31 - dx12 * dtv31 ) ); // dtv per one subpixel step in y // UV at top/left corner of rast area cbtu = ( tu1 + ( minXfixscale - x1 ) * dtudx + ( minYfixscale - y1 ) * dtudy ); cbtv = ( tv1 + ( minXfixscale - x1 ) * dtvdx + ( minYfixscale - y1 ) * dtvdy ); // UV pixel steps dtudx = dtudx * fixscale; dtudy = dtudy * fixscale; dtvdx = dtvdx * fixscale; dtvdy = dtvdy * fixscale; } var dnzdy, cbnz; if ( bHasNormal ) { // Normal interpolation setup var dnz12 = nz1 - nz2, dnz31 = nz3 - nz1; var dnzdx = ( invDet * ( dnz12 * dy31 - dnz31 * dy12 ) ); // dnz per one subpixel step in x var dnzdy = ( invDet * ( dnz12 * dx31 - dx12 * dnz31 ) ); // dnz per one subpixel step in y // Normal at top/left corner of rast area cbnz = ( nz1 + ( minXfixscale - x1 ) * dnzdx + ( minYfixscale - y1 ) * dnzdy ); // Normal pixel steps dnzdx = ( dnzdx * fixscale ); dnzdy = ( dnzdy * fixscale ); } // Set up min/max corners var qm1 = q - 1; // for convenience var nmin1 = 0, nmax1 = 0; var nmin2 = 0, nmax2 = 0; var nmin3 = 0, nmax3 = 0; var nminz = 0, nmaxz = 0; if ( dx12 >= 0 ) nmax1 -= qm1 * dx12; else nmin1 -= qm1 * dx12; if ( dy12 >= 0 ) nmax1 -= qm1 * dy12; else nmin1 -= qm1 * dy12; if ( dx23 >= 0 ) nmax2 -= qm1 * dx23; else nmin2 -= qm1 * dx23; if ( dy23 >= 0 ) nmax2 -= qm1 * dy23; else nmin2 -= qm1 * dy23; if ( dx31 >= 0 ) nmax3 -= qm1 * dx31; else nmin3 -= qm1 * dx31; if ( dy31 >= 0 ) nmax3 -= qm1 * dy31; else nmin3 -= qm1 * dy31; if ( dzdx >= 0 ) nmaxz += qm1 * dzdx; else nminz += qm1 * dzdx; if ( dzdy >= 0 ) nmaxz += qm1 * dzdy; else nminz += qm1 * dzdy; // Loop through blocks var linestep = canvasWidth - q; var cb1 = c1; var cb2 = c2; var cb3 = c3; var cbz = cz; var qstep = - q; var e1x = qstep * dy12; var e2x = qstep * dy23; var e3x = qstep * dy31; var ezx = qstep * dzdx; var etux, etvx; if ( bHasUV ) { etux = qstep * dtudx; etvx = qstep * dtvdx; } var enzx; if ( bHasNormal ) { enzx = qstep * dnzdx; } var x0 = minx; for ( var y0 = miny; y0 < maxy; y0 += q ) { // New block line - keep hunting for tri outer edge in old block line dir while ( x0 >= minx && x0 < maxx && cb1 >= nmax1 && cb2 >= nmax2 && cb3 >= nmax3 ) { x0 += qstep; cb1 += e1x; cb2 += e2x; cb3 += e3x; cbz += ezx; if ( bHasUV ) { cbtu += etux; cbtv += etvx; } if ( bHasNormal ) { cbnz += enzx; } } // Okay, we're now in a block we know is outside. Reverse direction and go into main loop. qstep = - qstep; e1x = - e1x; e2x = - e2x; e3x = - e3x; ezx = - ezx; if ( bHasUV ) { etux = - etux; etvx = - etvx; } if ( bHasNormal ) { enzx = - enzx; } while ( 1 ) { // Step everything x0 += qstep; cb1 += e1x; cb2 += e2x; cb3 += e3x; cbz += ezx; if ( bHasUV ) { cbtu += etux; cbtv += etvx; } if ( bHasNormal ) { cbnz += enzx; } // We're done with this block line when at least one edge completely out // If an edge function is too small and decreasing in the current traversal // dir, we're done with this line. if ( x0 < minx || x0 >= maxx ) break; if ( cb1 < nmax1 ) if ( e1x < 0 ) break; else continue; if ( cb2 < nmax2 ) if ( e2x < 0 ) break; else continue; if ( cb3 < nmax3 ) if ( e3x < 0 ) break; else continue; // We can skip this block if it's already fully covered var blockX = x0 >> blockShift; var blockY = y0 >> blockShift; var blockId = blockX + blockY * canvasWBlocks; var minz = cbz + nminz; // farthest point in block closer than closest point in our tri? if ( blockMaxZ[ blockId ] < minz ) continue; // Need to do a deferred clear? var bflags = blockFlags[ blockId ]; if ( bflags & BLOCK_NEEDCLEAR ) clearBlock( blockX, blockY ); blockFlags[ blockId ] = bflags & ~ ( BLOCK_ISCLEAR | BLOCK_NEEDCLEAR ); // Offset at top-left corner var offset = x0 + y0 * canvasWidth; // Accept whole block when fully covered if ( cb1 >= nmin1 && cb2 >= nmin2 && cb3 >= nmin3 ) { var maxz = cbz + nmaxz; blockMaxZ[ blockId ] = Math.min( blockMaxZ[ blockId ], maxz ); var cy1 = cb1; var cy2 = cb2; var cyz = cbz; var cytu, cytv; if ( bHasUV ) { cytu = cbtu; cytv = cbtv; } var cynz; if ( bHasNormal ) { cynz = cbnz; } for ( var iy = 0; iy < q; iy ++ ) { var cx1 = cy1; var cx2 = cy2; var cxz = cyz; var cxtu; var cxtv; if ( bHasUV ) { cxtu = cytu; cxtv = cytv; } var cxnz; if ( bHasNormal ) { cxnz = cynz; } for ( var ix = 0; ix < q; ix ++ ) { var z = cxz; if ( z < zbuffer[ offset ] ) { shader( data, zbuffer, offset, z, cxtu, cxtv, cxnz, face, material ); } cx1 += dy12; cx2 += dy23; cxz += dzdx; if ( bHasUV ) { cxtu += dtudx; cxtv += dtvdx; } if ( bHasNormal ) { cxnz += dnzdx; } offset ++; } cy1 += dx12; cy2 += dx23; cyz += dzdy; if ( bHasUV ) { cytu += dtudy; cytv += dtvdy; } if ( bHasNormal ) { cynz += dnzdy; } offset += linestep; } } else { // Partially covered block var cy1 = cb1; var cy2 = cb2; var cy3 = cb3; var cyz = cbz; var cytu, cytv; if ( bHasUV ) { cytu = cbtu; cytv = cbtv; } var cynz; if ( bHasNormal ) { cynz = cbnz; } for ( var iy = 0; iy < q; iy ++ ) { var cx1 = cy1; var cx2 = cy2; var cx3 = cy3; var cxz = cyz; var cxtu; var cxtv; if ( bHasUV ) { cxtu = cytu; cxtv = cytv; } var cxnz; if ( bHasNormal ) { cxnz = cynz; } for ( var ix = 0; ix < q; ix ++ ) { if ( ( cx1 | cx2 | cx3 ) >= 0 ) { var z = cxz; if ( z < zbuffer[ offset ] ) { shader( data, zbuffer, offset, z, cxtu, cxtv, cxnz, face, material ); } } cx1 += dy12; cx2 += dy23; cx3 += dy31; cxz += dzdx; if ( bHasUV ) { cxtu += dtudx; cxtv += dtvdx; } if ( bHasNormal ) { cxnz += dnzdx; } offset ++; } cy1 += dx12; cy2 += dx23; cy3 += dx31; cyz += dzdy; if ( bHasUV ) { cytu += dtudy; cytv += dtvdy; } if ( bHasNormal ) { cynz += dnzdy; } offset += linestep; } } } // Advance to next row of blocks cb1 += q * dx12; cb2 += q * dx23; cb3 += q * dx31; cbz += q * dzdy; if ( bHasUV ) { cbtu += q * dtudy; cbtv += q * dtvdy; } if ( bHasNormal ) { cbnz += q * dnzdy; } } } // When drawing line, the blockShiftShift has to be zero. In order to clean pixel // Using color1 and color2 to interpolation pixel color // LineWidth is according to material.linewidth function drawLine( v1, v2, color1, color2, shader, material ) { // While the line mode is enable, blockSize has to be changed to 0. if ( ! lineMode ) { lineMode = true; blockShift = 0; blockSize = 1 << blockShift; setSize( canvas.width, canvas.height ); } // TODO: Implement per-pixel z-clipping if ( v1.z < - 1 || v1.z > 1 || v2.z < - 1 || v2.z > 1 ) return; var halfLineWidth = Math.floor( ( material.linewidth - 1 ) * 0.5 ); // https://gist.github.com/2486101 // explanation: http://pouet.net/topic.php?which=8760&page=1 // 28.4 fixed-point coordinates var x1 = ( v1.x * viewportXScale + viewportXOffs ) | 0; var x2 = ( v2.x * viewportXScale + viewportXOffs ) | 0; var y1 = ( v1.y * viewportYScale + viewportYOffs ) | 0; var y2 = ( v2.y * viewportYScale + viewportYOffs ) | 0; var z1 = ( v1.z * viewportZScale + viewportZOffs ) | 0; var z2 = ( v2.z * viewportZScale + viewportZOffs ) | 0; // Deltas var dx12 = x1 - x2, dy12 = y1 - y2, dz12 = z1 - z2; // Bounding rectangle var minx = Math.max( ( Math.min( x1, x2 ) + subpixelBias ) >> subpixelBits, 0 ); var maxx = Math.min( ( Math.max( x1, x2 ) + subpixelBias ) >> subpixelBits, canvasWidth ); var miny = Math.max( ( Math.min( y1, y2 ) + subpixelBias ) >> subpixelBits, 0 ); var maxy = Math.min( ( Math.max( y1, y2 ) + subpixelBias ) >> subpixelBits, canvasHeight ); var minz = Math.max( ( Math.min( z1, z2 ) + subpixelBias ) >> subpixelBits, 0 ); var maxz = ( Math.max( z1, z2 ) + subpixelBias ) >> subpixelBits; rectx1 = Math.min( minx, rectx1 ); rectx2 = Math.max( maxx, rectx2 ); recty1 = Math.min( miny, recty1 ); recty2 = Math.max( maxy, recty2 ); // Get the line's unit vector and cross vector var length = Math.sqrt( ( dy12 * dy12 ) + ( dx12 * dx12 ) ); var unitX = ( dx12 / length ); var unitY = ( dy12 / length ); var unitZ = ( dz12 / length ); var pixelX, pixelY, pixelZ; var pX, pY, pZ; crossVector.set( unitX, unitY, unitZ ); crossVector.cross( lookVector ); crossVector.normalize(); while ( length > 0 ) { // Get this pixel. pixelX = x2 + length * unitX; pixelY = y2 + length * unitY; pixelZ = z2 + length * unitZ; pixelX = ( pixelX + subpixelBias ) >> subpixelBits; pixelY = ( pixelY + subpixelBias ) >> subpixelBits; pZ = ( pixelZ + subpixelBias ) >> subpixelBits; // Draw line with line width for ( var i = - halfLineWidth; i <= halfLineWidth; ++ i ) { // Compute the line pixels. // Get the pixels on the vector that crosses to the line vector pX = Math.floor( ( pixelX + crossVector.x * i ) ); pY = Math.floor( ( pixelY + crossVector.y * i ) ); // if pixel is over the rect. Continue if ( rectx1 >= pX || rectx2 <= pX || recty1 >= pY || recty2 <= pY ) continue; // Find this pixel at which block var blockX = pX >> blockShift; var blockY = pY >> blockShift; var blockId = blockX + blockY * canvasWBlocks; // Compare the pixel depth width z block. if ( blockMaxZ[ blockId ] < minz ) continue; blockMaxZ[ blockId ] = Math.min( blockMaxZ[ blockId ], maxz ); var bflags = blockFlags[ blockId ]; if ( bflags & BLOCK_NEEDCLEAR ) clearBlock( blockX, blockY ); blockFlags[ blockId ] = bflags & ~( BLOCK_ISCLEAR | BLOCK_NEEDCLEAR ); // draw pixel var offset = pX + pY * canvasWidth; if ( pZ < zbuffer[ offset ] ) { shader( data, zbuffer, offset, pZ, color1, color2, material ); } } --length; } } function clearBlock( blockX, blockY ) { var zoffset = blockX * blockSize + blockY * blockSize * canvasWidth; var poffset = zoffset * 4; var zlinestep = canvasWidth - blockSize; var plinestep = zlinestep * 4; for ( var y = 0; y < blockSize; y ++ ) { for ( var x = 0; x < blockSize; x ++ ) { zbuffer[ zoffset ++ ] = maxZVal; data[ poffset ++ ] = clearColor.r * 255 | 0; data[ poffset ++ ] = clearColor.g * 255 | 0; data[ poffset ++ ] = clearColor.b * 255 | 0; data[ poffset ++ ] = alpha ? 0 : 255; } zoffset += zlinestep; poffset += plinestep; } } function finishClear( ) { var block = 0; for ( var y = 0; y < canvasHBlocks; y ++ ) { for ( var x = 0; x < canvasWBlocks; x ++ ) { if ( blockFlags[ block ] & BLOCK_NEEDCLEAR ) { clearBlock( x, y ); blockFlags[ block ] = BLOCK_ISCLEAR; } block ++; } } } }; THREE.SoftwareRenderer.Texture = function () { var canvas; this.fromImage = function ( image ) { if ( ! image || image.width <= 0 || image.height <= 0 ) return; if ( canvas === undefined ) { canvas = document.createElement( 'canvas' ); } var size = image.width > image.height ? image.width : image.height; size = THREE.Math.nextPowerOfTwo( size ); if ( canvas.width != size || canvas.height != size ) { canvas.width = size; canvas.height = size; } var ctx = canvas.getContext( '2d' ); ctx.clearRect( 0, 0, size, size ); ctx.drawImage( image, 0, 0, size, size ); var imgData = ctx.getImageData( 0, 0, size, size ); this.data = imgData.data; this.width = size; this.height = size; this.srcUrl = image.src; }; };
RicoLiu/es_building_front_end
public/javascripts/SoftwareRenderer.js
JavaScript
apache-2.0
54,790
/* --- name: MooEditable description: Class for creating a WYSIWYG editor, for contentEditable-capable browsers. license: MIT-style license authors: - Lim Chee Aun - Radovan Lozej - Ryan Mitchell - Olivier Refalo - T.J. Leahy requires: - Core/Class.Extras - Core/Element.Event - Core/Element.Dimensions inspiration: - Code inspired by Stefan's work [Safari Supports Content Editing!](http://www.xs4all.nl/~hhijdra/stefan/ContentEditable.html) from [safari gets contentEditable](http://walkah.net/blog/walkah/safari-gets-contenteditable) - Main reference from Peter-Paul Koch's [execCommand compatibility](http://www.quirksmode.org/dom/execCommand.html) - Some ideas and code inspired by [TinyMCE](http://tinymce.moxiecode.com/) - Some functions inspired by Inviz's [Most tiny wysiwyg you ever seen](http://forum.mootools.net/viewtopic.php?id=746), [mooWyg (Most tiny WYSIWYG 2.0)](http://forum.mootools.net/viewtopic.php?id=5740) - Some regex from Cameron Adams's [widgEditor](http://widgeditor.googlecode.com/) - Some code from Juan M Martinez's [jwysiwyg](http://jwysiwyg.googlecode.com/) - Some reference from MoxieForge's [PunyMCE](http://punymce.googlecode.com/) - IE support referring Robert Bredlau's [Rich Text Editing](http://www.rbredlau.com/drupal/node/6) provides: [MooEditable, MooEditable.Selection, MooEditable.UI, MooEditable.Actions] ... */ (function(){ var blockEls = /^(H[1-6]|HR|P|DIV|ADDRESS|PRE|FORM|TABLE|LI|OL|UL|TD|CAPTION|BLOCKQUOTE|CENTER|DL|DT|DD|SCRIPT|NOSCRIPT|STYLE)$/i; var urlRegex = /^(https?|ftp|rmtp|mms):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i; var protectRegex = /<(script|noscript|style)[\u0000-\uFFFF]*?<\/(script|noscript|style)>/g; this.MooEditable = new Class({ Implements: [Events, Options], options: { toolbar: true, cleanup: true, paragraphise: true, xhtml : true, semantics : true, actions: 'bold italic underline strikethrough | insertunorderedlist insertorderedlist indent outdent | undo redo | createlink unlink | urlimage | toggleview', handleSubmit: true, handleLabel: true, disabled: false, baseCSS: 'html{ height: 100%; cursor: text; } body{ font-family: sans-serif; }', extraCSS: '', externalCSS: '', html: '<!DOCTYPE html><html><head><meta charset="UTF-8">{BASEHREF}<style>{BASECSS} {EXTRACSS}</style>{EXTERNALCSS}</head><body></body></html>', rootElement: 'p', baseURL: '', dimensions: null }, initialize: function(el, options){ // check for content editable and design mode support if (!("contentEditable" in document.body) && !("designMode" in document)){ return; } this.setOptions(options); this.textarea = document.id(el); this.textarea.store('MooEditable', this); this.actions = this.options.actions.clean().split(' '); this.keys = {}; this.dialogs = {}; this.protectedElements = []; this.actions.each(function(action){ var act = MooEditable.Actions[action]; if (!act) return; if (act.options){ var key = act.options.shortcut; if (key) this.keys[key] = action; } if (act.dialogs){ Object.each(act.dialogs, function(dialog, name){ dialog = dialog.attempt(this); dialog.name = action + ':' + name; if (typeOf(this.dialogs[action]) != 'object') this.dialogs[action] = {}; this.dialogs[action][name] = dialog; }, this); } if (act.events){ Object.each(act.events, function(fn, event){ this.addEvent(event, fn); }, this); } }.bind(this)); this.render(); }, toElement: function(){ return this.textarea; }, render: function(){ var self = this; // Dimensions var dimensions = this.options.dimensions || this.textarea.getSize(); // Build the container this.container = new Element('div', { id: (this.textarea.id) ? this.textarea.id + '-mooeditable-container' : null, 'class': 'mooeditable-container', styles: { width: dimensions.x } }); // Override all textarea styles this.textarea.addClass('mooeditable-textarea').setStyle('height', dimensions.y); // Build the iframe this.iframe = new IFrame({ 'class': 'mooeditable-iframe', frameBorder: 0, src: 'javascript:""', // Workaround for HTTPs warning in IE6/7 styles: { height: dimensions.y } }); this.toolbar = new MooEditable.UI.Toolbar({ onItemAction: function(){ var args = Array.from(arguments); var item = args[0]; self.action(item.name, args); } }); this.attach.delay(1, this); // Update the event for textarea's corresponding labels if (this.options.handleLabel && this.textarea.id) $$('label[for="'+this.textarea.id+'"]').addEvent('click', function(e){ if (self.mode != 'iframe') return; e.preventDefault(); self.focus(); }); // Update & cleanup content before submit if (this.options.handleSubmit){ this.form = this.textarea.getParent('form'); if (this.form) { this.form.addEvent('submit', function(){ if (self.mode == 'iframe') self.saveContent(); }); } } this.fireEvent('render', this); }, attach: function(){ var self = this; // Assign view mode this.mode = 'iframe'; // Editor iframe state this.editorDisabled = false; // Put textarea inside container this.container.wraps(this.textarea); this.textarea.setStyle('display', 'none'); this.iframe.setStyle('display', '').inject(this.textarea, 'before'); Object.each(this.dialogs, function(action, name){ Object.each(action, function(dialog){ document.id(dialog).inject(self.iframe, 'before'); var range; dialog.addEvents({ open: function(){ range = self.selection.getRange(); self.editorDisabled = true; self.toolbar.disable(name); self.fireEvent('dialogOpen', this); }, close: function(){ self.toolbar.enable(); self.editorDisabled = false; self.focus(); if (range) self.selection.setRange(range); self.fireEvent('dialogClose', this); } }); }); }); // contentWindow and document references this.win = this.iframe.contentWindow; this.doc = this.win.document; // Deal with weird quirks on Gecko if (Browser.firefox) this.doc.designMode = 'On'; // Build the content of iframe var docHTML = this.options.html.substitute({ BASECSS: this.options.baseCSS, EXTRACSS: this.options.extraCSS, EXTERNALCSS: (this.options.externalCSS) ? '<link rel="stylesheet" type="text/css" media="screen" href="' + this.options.externalCSS + '" />': '', BASEHREF: (this.options.baseURL) ? '<base href="' + this.options.baseURL + '" />': '' }); this.doc.open(); this.doc.write(docHTML); this.doc.close(); // Turn on Design Mode // IE fired load event twice if designMode is set (Browser.ie) ? this.doc.body.contentEditable = true : this.doc.designMode = 'On'; // Mootoolize window, document and body Object.append(this.win, new Window); Object.append(this.doc, new Document); if (Browser.Element){ var winElement = this.win.Element.prototype; for (var method in Element){ // methods from Element generics if (!method.test(/^[A-Z]|\$|prototype|mooEditable/)){ winElement[method] = Element.prototype[method]; } } } else { document.id(this.doc.body); } this.setContent(this.textarea.get('value')); // Bind all events this.doc.addEvents({ mouseup: this.editorMouseUp.bind(this), mousedown: this.editorMouseDown.bind(this), mouseover: this.editorMouseOver.bind(this), mouseout: this.editorMouseOut.bind(this), mouseenter: this.editorMouseEnter.bind(this), mouseleave: this.editorMouseLeave.bind(this), contextmenu: this.editorContextMenu.bind(this), click: this.editorClick.bind(this), dblclick: this.editorDoubleClick.bind(this), keypress: this.editorKeyPress.bind(this), keyup: this.editorKeyUp.bind(this), keydown: this.editorKeyDown.bind(this), focus: this.editorFocus.bind(this), blur: this.editorBlur.bind(this) }); this.win.addEvents({ focus: this.editorFocus.bind(this), blur: this.editorBlur.bind(this) }); ['cut', 'copy', 'paste'].each(function(event){ self.doc.body.addListener(event, self['editor' + event.capitalize()].bind(self)); }); this.textarea.addEvent('keypress', this.textarea.retrieve('mooeditable:textareaKeyListener', this.keyListener.bind(this))); // Fix window focus event not firing on Firefox 2 if (Browser.firefox2) this.doc.addEvent('focus', function(){ self.win.fireEvent('focus').focus(); }); // IE9 is also not firing focus event if (this.doc.addEventListener) this.doc.addEventListener('focus', function(){ self.win.fireEvent('focus'); }, true); // styleWithCSS, not supported in IE and Opera if (!Browser.ie && !Browser.opera){ var styleCSS = function(){ self.execute('styleWithCSS', false, false); self.doc.removeEvent('focus', styleCSS); }; this.win.addEvent('focus', styleCSS); } if (this.options.toolbar){ document.id(this.toolbar).inject(this.container, 'top'); this.toolbar.render(this.actions); } if (this.options.disabled) this.disable(); this.selection = new MooEditable.Selection(this.win); this.oldContent = this.getContent(); this.fireEvent('attach', this); return this; }, detach: function(){ this.saveContent(); this.textarea.setStyle('display', '').removeClass('mooeditable-textarea').inject(this.container, 'before'); this.textarea.removeEvent('keypress', this.textarea.retrieve('mooeditable:textareaKeyListener')); this.container.dispose(); this.fireEvent('detach', this); return this; }, enable: function(){ this.editorDisabled = false; this.toolbar.enable(); return this; }, disable: function(){ this.editorDisabled = true; this.toolbar.disable(); return this; }, editorFocus: function(e){ this.oldContent = ''; this.fireEvent('editorFocus', [e, this]); }, editorBlur: function(e){ this.oldContent = this.saveContent().getContent(); this.fireEvent('editorBlur', [e, this]); }, editorMouseUp: function(e){ if (this.editorDisabled){ e.stop(); return; } if (this.options.toolbar) this.checkStates(); this.fireEvent('editorMouseUp', [e, this]); }, editorMouseDown: function(e){ if (this.editorDisabled){ e.stop(); return; } this.fireEvent('editorMouseDown', [e, this]); }, editorMouseOver: function(e){ if (this.editorDisabled){ e.stop(); return; } this.fireEvent('editorMouseOver', [e, this]); }, editorMouseOut: function(e){ if (this.editorDisabled){ e.stop(); return; } this.fireEvent('editorMouseOut', [e, this]); }, editorMouseEnter: function(e){ if (this.editorDisabled){ e.stop(); return; } if (this.oldContent && this.getContent() != this.oldContent){ this.focus(); this.fireEvent('editorPaste', [e, this]); } this.fireEvent('editorMouseEnter', [e, this]); }, editorMouseLeave: function(e){ if (this.editorDisabled){ e.stop(); return; } this.fireEvent('editorMouseLeave', [e, this]); }, editorContextMenu: function(e){ if (this.editorDisabled){ e.stop(); return; } this.fireEvent('editorContextMenu', [e, this]); }, editorClick: function(e){ // make images selectable and draggable in Safari if (Browser.safari || Browser.chrome){ var el = e.target; if (Element.get(el, 'tag') == 'img'){ // safari doesnt like dragging locally linked images if (this.options.baseURL){ if (el.getProperty('src').indexOf('http://') == -1){ el.setProperty('src', this.options.baseURL + el.getProperty('src')); } } this.selection.selectNode(el); this.checkStates(); } } this.fireEvent('editorClick', [e, this]); }, editorDoubleClick: function(e){ this.fireEvent('editorDoubleClick', [e, this]); }, editorKeyPress: function(e){ if (this.editorDisabled){ e.stop(); return; } this.keyListener(e); this.fireEvent('editorKeyPress', [e, this]); }, editorKeyUp: function(e){ if (this.editorDisabled){ e.stop(); return; } var c = e.code; // 33-36 = pageup, pagedown, end, home; 45 = insert if (this.options.toolbar && (/^enter|left|up|right|down|delete|backspace$/i.test(e.key) || (c >= 33 && c <= 36) || c == 45 || e.meta || e.control)){ if (Browser.ie6){ // Delay for less cpu usage when you are typing clearTimeout(this.checkStatesDelay); this.checkStatesDelay = this.checkStates.delay(500, this); } else { this.checkStates(); } } this.fireEvent('editorKeyUp', [e, this]); }, editorKeyDown: function(e){ if (this.editorDisabled){ e.stop(); return; } if (e.key == 'enter'){ if (this.options.paragraphise){ if (e.shift && (Browser.safari || Browser.chrome)){ var s = this.selection; var r = s.getRange(); // Insert BR element var br = this.doc.createElement('br'); r.insertNode(br); // Place caret after BR r.setStartAfter(br); r.setEndAfter(br); s.setRange(r); // Could not place caret after BR then insert an nbsp entity and move the caret if (s.getSelection().focusNode == br.previousSibling){ var nbsp = this.doc.createTextNode('\u00a0'); var p = br.parentNode; var ns = br.nextSibling; (ns) ? p.insertBefore(nbsp, ns) : p.appendChild(nbsp); s.selectNode(nbsp); s.collapse(1); } // Scroll to new position, scrollIntoView can't be used due to bug: http://bugs.webkit.org/show_bug.cgi?id=16117 this.win.scrollTo(0, Element.getOffsets(s.getRange().startContainer).y); e.preventDefault(); } else if (Browser.firefox || Browser.safari || Browser.chrome){ var node = this.selection.getNode(); var isBlock = Element.getParents(node).include(node).some(function(el){ return el.nodeName.test(blockEls); }); if (!isBlock) this.execute('insertparagraph'); } } else { if (Browser.ie){ var r = this.selection.getRange(); var node = this.selection.getNode(); if (r && node.get('tag') != 'li'){ this.selection.insertContent('<br>'); this.selection.collapse(false); } e.preventDefault(); } } } if (Browser.opera){ var ctrlmeta = e.control || e.meta; if (ctrlmeta && e.key == 'x'){ this.fireEvent('editorCut', [e, this]); } else if (ctrlmeta && e.key == 'c'){ this.fireEvent('editorCopy', [e, this]); } else if ((ctrlmeta && e.key == 'v') || (e.shift && e.code == 45)){ this.fireEvent('editorPaste', [e, this]); } } this.fireEvent('editorKeyDown', [e, this]); }, editorCut: function(e){ if (this.editorDisabled){ e.stop(); return; } this.fireEvent('editorCut', [e, this]); }, editorCopy: function(e){ if (this.editorDisabled){ e.stop(); return; } this.fireEvent('editorCopy', [e, this]); }, editorPaste: function(e){ if (this.editorDisabled){ e.stop(); return; } this.fireEvent('editorPaste', [e, this]); }, keyListener: function(e){ //mootools 1.5.X //var key = (Browser.Platform.mac) ? e.meta : e.control; var key = (Browser.platform == "mac") ? e.meta : e.control; if (!key || !this.keys[e.key]) return; e.preventDefault(); var item = this.toolbar.getItem(this.keys[e.key]); item.action(e); }, focus: function(){ (this.mode == 'iframe' ? this.win : this.textarea).focus(); this.fireEvent('focus', this); return this; }, action: function(command, args){ var action = MooEditable.Actions[command]; if (action.command && typeOf(action.command) == 'function'){ action.command.apply(this, args); } else { this.focus(); this.execute(command, false, args); if (this.mode == 'iframe') this.checkStates(); } }, execute: function(command, param1, param2){ if (this.busy) return; this.busy = true; this.doc.execCommand(command, param1, param2); this.saveContent(); this.busy = false; return false; }, toggleView: function(){ this.fireEvent('beforeToggleView', this); if (this.mode == 'textarea'){ this.mode = 'iframe'; this.iframe.setStyle('display', ''); this.setContent(this.textarea.value); this.textarea.setStyle('display', 'none'); } else { this.saveContent(); this.mode = 'textarea'; this.textarea.setStyle('display', ''); this.iframe.setStyle('display', 'none'); } this.fireEvent('toggleView', this); this.focus.delay(10, this); return this; }, getContent: function(){ var protect = this.protectedElements; var html = this.doc.body.get('html').replace(/<!-- mooeditable:protect:([0-9]+) -->/g, function(a, b){ return protect[b.toInt()]; }); return this.cleanup(this.ensureRootElement(html)); }, setContent: function(content){ var protect = this.protectedElements; content = content.replace(protectRegex, function(a){ protect.push(a); return '<!-- mooeditable:protect:' + (protect.length-1) + ' -->'; }); this.doc.body.set('html', this.ensureRootElement(content)); return this; }, saveContent: function(){ if (this.mode == 'iframe'){ this.textarea.set('value', this.getContent()); } //add event! this.fireEvent("change"); return this; }, ensureRootElement: function(val){ if (this.options.rootElement){ var el = new Element('div', {html: val.trim()}); var start = -1; var create = false; var html = ''; var length = el.childNodes.length; for (var i=0; i<length; i++){ var childNode = el.childNodes[i]; var nodeName = childNode.nodeName; if (!nodeName.test(blockEls) && nodeName !== '#comment'){ if (nodeName === '#text'){ if (childNode.nodeValue.trim()){ if (start < 0) start = i; html += childNode.nodeValue; } } else { if (start < 0) start = i; html += new Element('div').adopt($(childNode).clone()).get('html'); } } else { create = true; } if (i == (length-1)) create = true; if (start >= 0 && create){ var newel = new Element(this.options.rootElement, {html: html}); el.replaceChild(newel, el.childNodes[start]); for (var k=start+1; k<i; k++){ el.removeChild(el.childNodes[k]); length--; i--; k--; } start = -1; create = false; html = ''; } } val = el.get('html').replace(/\n\n/g, ''); } return val; }, checkStates: function(){ var element = this.selection.getNode(); if (!element) return; if (typeOf(element) != 'element') return; this.actions.each(function(action){ var item = this.toolbar.getItem(action); if (!item) return; item.deactivate(); var states = MooEditable.Actions[action]['states']; if (!states) return; // custom checkState if (typeOf(states) == 'function'){ states.attempt([document.id(element), item], this); return; } try{ if (this.doc.queryCommandState(action)){ item.activate(); return; } } catch(e){} if (states.tags){ var el = element; do { var tag = el.tagName.toLowerCase(); if (states.tags.contains(tag)){ item.activate(tag); break; } } while ((el = Element.getParent(el)) != null); } if (states.css){ var el = element; do { var found = false; for (var prop in states.css){ var css = states.css[prop]; if (el.style[prop.camelCase()].contains(css)){ item.activate(css); found = true; } } if (found || el.tagName.test(blockEls)) break; } while ((el = Element.getParent(el)) != null); } }.bind(this)); }, cleanup: function(source){ if (!this.options.cleanup) return source.trim(); do { var oSource = source; // replace base URL references: ie localize links if (this.options.baseURL){ source = source.replace('="' + this.options.baseURL, '="'); } // Webkit cleanup source = source.replace(/<br class\="webkit-block-placeholder">/gi, "<br />"); source = source.replace(/<span class="Apple-style-span">(.*)<\/span>/gi, '$1'); source = source.replace(/ class="Apple-style-span"/gi, ''); source = source.replace(/<span style="">/gi, ''); // Remove padded paragraphs source = source.replace(/<p>\s*<br ?\/?>\s*<\/p>/gi, '<p>\u00a0</p>'); source = source.replace(/<p>(&nbsp;|\s)*<\/p>/gi, '<p>\u00a0</p>'); if (!this.options.semantics){ source = source.replace(/\s*<br ?\/?>\s*<\/p>/gi, '</p>'); } // Replace improper BRs (only if XHTML : true) if (this.options.xhtml){ source = source.replace(/<br>/gi, "<br />"); } if (this.options.semantics){ //remove divs from <li> if (Browser.ie){ source = source.replace(/<li>\s*<div>(.+?)<\/div><\/li>/g, '<li>$1</li>'); } //remove stupid apple divs if (Browser.safari || Browser.chrome){ source = source.replace(/^([\w\s]+.*?)<div>/i, '<p>$1</p><div>'); source = source.replace(/<div>(.+?)<\/div>/ig, '<p>$1</p>'); } //<p> tags around a list will get moved to after the list if (!Browser.ie){ //not working properly in safari? source = source.replace(/<p>[\s\n]*(<(?:ul|ol)>.*?<\/(?:ul|ol)>)(.*?)<\/p>/ig, '$1<p>$2</p>'); source = source.replace(/<\/(ol|ul)>\s*(?!<(?:p|ol|ul|img).*?>)((?:<[^>]*>)?\w.*)$/g, '</$1><p>$2</p>'); } source = source.replace(/<br[^>]*><\/p>/g, '</p>'); // remove <br>'s that end a paragraph here. source = source.replace(/<p>\s*(<img[^>]+>)\s*<\/p>/ig, '$1\n'); // if a <p> only contains <img>, remove the <p> tags //format the source source = source.replace(/<p([^>]*)>(.*?)<\/p>(?!\n)/g, '<p$1>$2</p>\n'); // break after paragraphs source = source.replace(/<\/(ul|ol|p)>(?!\n)/g, '</$1>\n'); // break after </p></ol></ul> tags source = source.replace(/><li>/g, '>\n\t<li>'); // break and indent <li> source = source.replace(/([^\n])<\/(ol|ul)>/g, '$1\n</$2>'); //break before </ol></ul> tags source = source.replace(/([^\n])<img/ig, '$1\n<img'); // move images to their own line source = source.replace(/^\s*$/g, ''); // delete empty lines in the source code (not working in opera) } // Remove leading and trailing BRs source = source.replace(/<br ?\/?>$/gi, ''); source = source.replace(/^<br ?\/?>/gi, ''); // Remove useless BRs if (this.options.paragraphise) source = source.replace(/(h[1-6]|p|div|address|pre|li|ol|ul|blockquote|center|dl|dt|dd)><br ?\/?>/gi, '$1>'); // Remove BRs right before the end of blocks source = source.replace(/<br ?\/?>\s*<\/(h1|h2|h3|h4|h5|h6|li|p)/gi, '</$1'); // Semantic conversion source = source.replace(/<span style="font-weight: bold;">(.*)<\/span>/gi, '<strong>$1</strong>'); source = source.replace(/<span style="font-style: italic;">(.*)<\/span>/gi, '<em>$1</em>'); source = source.replace(/<b\b[^>]*>(.*?)<\/b[^>]*>/gi, '<strong>$1</strong>'); source = source.replace(/<i\b[^>]*>(.*?)<\/i[^>]*>/gi, '<em>$1</em>'); source = source.replace(/<u\b[^>]*>(.*?)<\/u[^>]*>/gi, '<span style="text-decoration: underline;">$1</span>'); source = source.replace(/<strong><span style="font-weight: normal;">(.*)<\/span><\/strong>/gi, '$1'); source = source.replace(/<em><span style="font-weight: normal;">(.*)<\/span><\/em>/gi, '$1'); source = source.replace(/<span style="text-decoration: underline;"><span style="font-weight: normal;">(.*)<\/span><\/span>/gi, '$1'); source = source.replace(/<strong style="font-weight: normal;">(.*)<\/strong>/gi, '$1'); source = source.replace(/<em style="font-weight: normal;">(.*)<\/em>/gi, '$1'); // Replace uppercase element names with lowercase source = source.replace(/<[^> ]*/g, function(match){return match.toLowerCase();}); // Replace uppercase attribute names with lowercase source = source.replace(/<[^>]*>/g, function(match){ match = match.replace(/ [^=]+=/g, function(match2){return match2.toLowerCase();}); return match; }); // Put quotes around unquoted attributes source = source.replace(/<[^!][^>]*>/g, function(match){ match = match.replace(/( [^=]+=)([^"][^ >]*)/g, "$1\"$2\""); return match; }); //make img tags xhtml compatible <img>,<img></img> -> <img/> if (this.options.xhtml){ source = source.replace(/<img([^>]+)(\s*[^\/])>(<\/img>)*/gi, '<img$1$2 />'); } //remove double <p> tags and empty <p> tags source = source.replace(/<p>(?:\s*)<p>/g, '<p>'); source = source.replace(/<\/p>\s*<\/p>/g, '</p>'); // Replace <br>s inside <pre> automatically added by some browsers source = source.replace(/<pre[^>]*>.*?<\/pre>/gi, function(match){ return match.replace(/<br ?\/?>/gi, '\n'); }); // Final trim source = source.trim(); } while (source != oSource); return source; } }); MooEditable.Selection = new Class({ initialize: function(win){ this.win = win; }, getSelection: function(){ this.win.focus(); return (this.win.getSelection) ? this.win.getSelection() : this.win.document.selection; }, getRange: function(){ var s = this.getSelection(); if (!s) return null; try { return s.rangeCount > 0 ? s.getRangeAt(0) : (s.createRange ? s.createRange() : null); } catch(e) { // IE bug when used in frameset return this.doc.body.createTextRange(); } }, setRange: function(range){ if (range.select){ Function.attempt(function(){ range.select(); }); } else { var s = this.getSelection(); if (s.addRange){ s.removeAllRanges(); s.addRange(range); } } }, selectNode: function(node, collapse){ var r = this.getRange(); var s = this.getSelection(); if (r.moveToElementText){ Function.attempt(function(){ r.moveToElementText(node); r.select(); }); } else if (s.addRange){ collapse ? r.selectNodeContents(node) : r.selectNode(node); s.removeAllRanges(); s.addRange(r); } else { s.setBaseAndExtent(node, 0, node, 1); } return node; }, isCollapsed: function(){ var r = this.getRange(); if (r.item) return false; return r.boundingWidth == 0 || this.getSelection().isCollapsed; }, collapse: function(toStart){ var r = this.getRange(); var s = this.getSelection(); if (r.select){ r.collapse(toStart); r.select(); } else { toStart ? s.collapseToStart() : s.collapseToEnd(); } }, getContent: function(){ var r = this.getRange(); var body = new Element('body'); if (this.isCollapsed()) return ''; if (r.cloneContents){ body.appendChild(r.cloneContents()); } else if (r.item != undefined || r.htmlText != undefined){ body.set('html', r.item ? r.item(0).outerHTML : r.htmlText); } else { body.set('html', r.toString()); } var content = body.get('html'); return content; }, getText : function(){ var r = this.getRange(); var s = this.getSelection(); return this.isCollapsed() ? '' : r.text || (s.toString ? s.toString() : ''); }, getNode: function(){ var r = this.getRange(); if (!Browser.ie || Browser.version >= 9){ var el = null; if (r){ el = r.commonAncestorContainer; // Handle selection a image or other control like element such as anchors if (!r.collapsed) if (r.startContainer == r.endContainer) if (r.startOffset - r.endOffset < 2) if (r.startContainer.hasChildNodes()) el = r.startContainer.childNodes[r.startOffset]; while (typeOf(el) != 'element') el = el.parentNode; } return document.id(el); } return document.id(r.item ? r.item(0) : r.parentElement()); }, insertContent: function(content){ if (Browser.ie){ var r = this.getRange(); if (r.pasteHTML){ r.pasteHTML(content); r.collapse(false); r.select(); } else if (r.insertNode){ r.deleteContents(); if (r.createContextualFragment){ r.insertNode(r.createContextualFragment(content)); } else { var doc = this.win.document; var fragment = doc.createDocumentFragment(); var temp = doc.createElement('div'); fragment.appendChild(temp); temp.outerHTML = content; r.insertNode(fragment); } } } else { this.win.document.execCommand('insertHTML', false, content); } } }); // Avoiding Locale dependency // Wrapper functions to be used internally and for plugins, defaults to en-US var phrases = {}; MooEditable.Locale = { define: function(key, value){ if (typeOf(window.Locale) != 'null') return Locale.define('en-US', 'MooEditable', key, value); if (typeOf(key) == 'object') Object.merge(phrases, key); else phrases[key] = value; }, get: function(key){ if (typeOf(window.Locale) != 'null') return Locale.get('MooEditable.' + key); return key ? phrases[key] : ''; } }; MooEditable.Locale.define({ ok: 'OK', cancel: 'Cancel', bold: 'Bold', italic: 'Italic', underline: 'Underline', strikethrough: 'Strikethrough', unorderedList: 'Unordered List', orderedList: 'Ordered List', indent: 'Indent', outdent: 'Outdent', undo: 'Undo', redo: 'Redo', removeHyperlink: 'Remove Hyperlink', addHyperlink: 'Add Hyperlink', selectTextHyperlink: 'Please select the text you wish to hyperlink.', enterURL: 'Enter URL', enterImageURL: 'Enter image URL', addImage: 'Add Image', toggleView: 'Toggle View' }); MooEditable.UI = {}; MooEditable.UI.Toolbar= new Class({ Implements: [Events, Options], options: { /* onItemAction: function(){}, */ 'class': '' }, initialize: function(options){ this.setOptions(options); this.el = new Element('div', {'class': 'mooeditable-ui-toolbar ' + this.options['class']}); this.items = {}; this.content = null; }, toElement: function(){ return this.el; }, render: function(actions){ if (this.content){ this.el.adopt(this.content); } else { this.content = actions.map(function(action){ if (action == '|') { return this.addSeparator(); } else if (action == '/') { return this.addLineSeparator(); } return this.addItem(action); }.bind(this)); } return this; }, addItem: function(action){ var self = this; var act = MooEditable.Actions[action]; if (!act) return; var type = act.type || 'button'; var options = act.options || {}; var item = new MooEditable.UI[type.camelCase().capitalize()](Object.append(options, { name: action, 'class': action + '-item toolbar-item', title: act.title, onAction: self.itemAction.bind(self) })); this.items[action] = item; document.id(item).inject(this.el); return item; }, getItem: function(action){ return this.items[action]; }, addSeparator: function(){ return new Element('span.toolbar-separator').inject(this.el); }, addLineSeparator: function(){ return new Element('div.toolbar-line-separator').inject(this.el); }, itemAction: function(){ this.fireEvent('itemAction', arguments); }, disable: function(except){ Object.each(this.items, function(item){ (item.name == except) ? item.activate() : item.deactivate().disable(); }); return this; }, enable: function(){ Object.each(this.items, function(item){ item.enable(); }); return this; }, show: function(){ this.el.setStyle('display', ''); return this; }, hide: function(){ this.el.setStyle('display', 'none'); return this; } }); MooEditable.UI.Button = new Class({ Implements: [Events, Options], options: { /* onAction: function(){}, */ title: '', name: '', text: 'Button', 'class': '', shortcut: '', mode: 'icon' }, initialize: function(options){ this.setOptions(options); this.name = this.options.name; this.render(); }, toElement: function(){ return this.el; }, render: function(){ var self = this; //mootools 1.5.x //var key = (Browser.Platform.mac) ? 'Cmd' : 'Ctrl'; var key = (Browser.platform == "mac") ? 'Cmd' : 'Ctrl'; var shortcut = (this.options.shortcut) ? ' ( ' + key + '+' + this.options.shortcut.toUpperCase() + ' )' : ''; var text = this.options.title || name; var title = text + shortcut; this.el = new Element('button', { 'class': 'mooeditable-ui-button ' + self.options['class'], title: title, html: '<span class="button-icon"></span><span class="button-text">' + text + '</span>', events: { click: self.click.bind(self), mousedown: function(e){ e.preventDefault(); } } }); if (this.options.mode != 'icon') this.el.addClass('mooeditable-ui-button-' + this.options.mode); this.active = false; this.disabled = false; // add hover effect for IE if (Browser.ie) this.el.addEvents({ mouseenter: function(e){ this.addClass('hover'); }, mouseleave: function(e){ this.removeClass('hover'); } }); return this; }, click: function(e){ e.preventDefault(); if (this.disabled) return; this.action(e); }, action: function(){ this.fireEvent('action', [this].concat(Array.from(arguments))); }, enable: function(){ if (this.active) this.el.removeClass('onActive'); if (!this.disabled) return; this.disabled = false; this.el.removeClass('disabled').set({ disabled: false, opacity: 1 }); return this; }, disable: function(){ if (this.disabled) return; this.disabled = true; this.el.addClass('disabled').set({ disabled: true, opacity: 0.4 }); return this; }, activate: function(){ if (this.disabled) return; this.active = true; this.el.addClass('onActive'); return this; }, deactivate: function(){ this.active = false; this.el.removeClass('onActive'); return this; } }); MooEditable.UI.Dialog = new Class({ Implements: [Events, Options], options:{ /* onOpen: function(){}, onClose: function(){}, */ 'class': '', contentClass: '' }, initialize: function(html, options){ this.setOptions(options); this.html = html; var self = this; this.el = new Element('div', { 'class': 'mooeditable-ui-dialog ' + self.options['class'], html: '<div class="dialog-content ' + self.options.contentClass + '">' + html + '</div>', styles: { 'display': 'none' }, events: { click: self.click.bind(self) } }); }, toElement: function(){ return this.el; }, click: function(){ this.fireEvent('click', arguments); return this; }, open: function(){ this.el.setStyle('display', ''); this.fireEvent('open', this); return this; }, close: function(){ this.el.setStyle('display', 'none'); this.fireEvent('close', this); return this; } }); MooEditable.UI.AlertDialog = function(alertText){ if (!alertText) return; var html = alertText + ' <button class="dialog-ok-button">' + MooEditable.Locale.get('ok') + '</button>'; return new MooEditable.UI.Dialog(html, { 'class': 'mooeditable-alert-dialog', onOpen: function(){ var button = this.el.getElement('.dialog-ok-button'); (function(){ button.focus(); }).delay(10); }, onClick: function(e){ e.preventDefault(); if (e.target.tagName.toLowerCase() != 'button') return; if (document.id(e.target).hasClass('dialog-ok-button')) this.close(); } }); }; MooEditable.UI.PromptDialog = function(questionText, answerText, fn){ if (!questionText) return; var html = '<label class="dialog-label">' + questionText + ' <input type="text" class="text dialog-input" value="' + answerText + '">' + '</label> <button class="dialog-button dialog-ok-button">' + MooEditable.Locale.get('ok') + '</button>' + '<button class="dialog-button dialog-cancel-button">' + MooEditable.Locale.get('cancel') + '</button>'; return new MooEditable.UI.Dialog(html, { 'class': 'mooeditable-prompt-dialog', onOpen: function(){ var input = this.el.getElement('.dialog-input'); (function(){ input.focus(); input.select(); }).delay(10); }, onClick: function(e){ e.preventDefault(); if (e.target.tagName.toLowerCase() != 'button') return; var button = document.id(e.target); var input = this.el.getElement('.dialog-input'); if (button.hasClass('dialog-cancel-button')){ input.set('value', answerText); this.close(); } else if (button.hasClass('dialog-ok-button')){ var answer = input.get('value'); input.set('value', answerText); this.close(); if (fn) fn.attempt(answer, this); } } }); }; MooEditable.Actions = { bold: { title: MooEditable.Locale.get('bold'), options: { shortcut: 'b' }, states: { tags: ['b', 'strong'], css: {'font-weight': 'bold'} }, events: { beforeToggleView: function(){ if(Browser.firefox){ var value = this.textarea.get('value'); var newValue = value.replace(/<strong([^>]*)>/gi, '<b$1>').replace(/<\/strong>/gi, '</b>'); if (value != newValue) this.textarea.set('value', newValue); } }, attach: function(){ if(Browser.firefox){ var value = this.textarea.get('value'); var newValue = value.replace(/<strong([^>]*)>/gi, '<b$1>').replace(/<\/strong>/gi, '</b>'); if (value != newValue){ this.textarea.set('value', newValue); this.setContent(newValue); } } } } }, italic: { title: MooEditable.Locale.get('italic'), options: { shortcut: 'i' }, states: { tags: ['i', 'em'], css: {'font-style': 'italic'} }, events: { beforeToggleView: function(){ if (Browser.firefox){ var value = this.textarea.get('value'); var newValue = value.replace(/<embed([^>]*)>/gi, '<tmpembed$1>') .replace(/<em([^>]*)>/gi, '<i$1>') .replace(/<tmpembed([^>]*)>/gi, '<embed$1>') .replace(/<\/em>/gi, '</i>'); if (value != newValue) this.textarea.set('value', newValue); } }, attach: function(){ if (Browser.firefox){ var value = this.textarea.get('value'); var newValue = value.replace(/<embed([^>]*)>/gi, '<tmpembed$1>') .replace(/<em([^>]*)>/gi, '<i$1>') .replace(/<tmpembed([^>]*)>/gi, '<embed$1>') .replace(/<\/em>/gi, '</i>'); if (value != newValue){ this.textarea.set('value', newValue); this.setContent(newValue); } } } } }, underline: { title: MooEditable.Locale.get('underline'), options: { shortcut: 'u' }, states: { tags: ['u'], css: {'text-decoration': 'underline'} }, events: { beforeToggleView: function(){ if(Browser.firefox || Browser.ie){ var value = this.textarea.get('value'); var newValue = value.replace(/<span style="text-decoration: underline;"([^>]*)>/gi, '<u$1>').replace(/<\/span>/gi, '</u>'); if (value != newValue) this.textarea.set('value', newValue); } }, attach: function(){ if(Browser.firefox || Browser.ie){ var value = this.textarea.get('value'); var newValue = value.replace(/<span style="text-decoration: underline;"([^>]*)>/gi, '<u$1>').replace(/<\/span>/gi, '</u>'); if (value != newValue){ this.textarea.set('value', newValue); this.setContent(newValue); } } } } }, strikethrough: { title: MooEditable.Locale.get('strikethrough'), options: { shortcut: 's' }, states: { tags: ['s', 'strike'], css: {'text-decoration': 'line-through'} } }, insertunorderedlist: { title: MooEditable.Locale.get('unorderedList'), states: { tags: ['ul'] } }, insertorderedlist: { title: MooEditable.Locale.get('orderedList'), states: { tags: ['ol'] } }, indent: { title: MooEditable.Locale.get('indent'), states: { tags: ['blockquote'] } }, outdent: { title: MooEditable.Locale.get('outdent') }, undo: { title: MooEditable.Locale.get('undo'), options: { shortcut: 'z' } }, redo: { title: MooEditable.Locale.get('redo'), options: { shortcut: 'y' } }, unlink: { title: MooEditable.Locale.get('removeHyperlink') }, createlink: { title: MooEditable.Locale.get('addHyperlink'), options: { shortcut: 'l' }, states: { tags: ['a'] }, dialogs: { alert: MooEditable.UI.AlertDialog.pass(MooEditable.Locale.get('selectTextHyperlink')), prompt: function(editor){ return MooEditable.UI.PromptDialog(MooEditable.Locale.get('enterURL'), 'http://', function(url){ editor.execute('createlink', false, url.trim()); }); } }, command: function(){ var selection = this.selection; var dialogs = this.dialogs.createlink; if (selection.isCollapsed()){ var node = selection.getNode(); if (node.get('tag') == 'a' && node.get('href')){ selection.selectNode(node); var prompt = dialogs.prompt; prompt.el.getElement('.dialog-input').set('value', node.get('href')); prompt.open(); } else { dialogs.alert.open(); } } else { var text = selection.getText(); var prompt = dialogs.prompt; if (urlRegex.test(text)) prompt.el.getElement('.dialog-input').set('value', text); prompt.open(); } } }, urlimage: { title: MooEditable.Locale.get('addImage'), options: { shortcut: 'm' }, dialogs: { prompt: function(editor){ return MooEditable.UI.PromptDialog(MooEditable.Locale.get('enterImageURL'), 'http://', function(url){ editor.execute('insertimage', false, url.trim()); }); } }, command: function(){ this.dialogs.urlimage.prompt.open(); } }, toggleview: { title: MooEditable.Locale.get('toggleView'), command: function(){ (this.mode == 'textarea') ? this.toolbar.enable() : this.toolbar.disable('toggleview'); this.toggleView(); } } }; MooEditable.Actions.Settings = {}; Element.Properties.mooeditable = { get: function(){ return this.retrieve('MooEditable'); } }; Element.implement({ mooEditable: function(options){ var mooeditable = this.get('mooeditable'); if (!mooeditable) mooeditable = new MooEditable(this, options); return mooeditable; } }); })();
tateshitah/jspwiki
jspwiki-war/src/main/webapp/scripts/mooeditable/Source/MooEditable/MooEditable.js
JavaScript
apache-2.0
41,511
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // 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. goog.provide('goog.ui.ControlRendererTest'); goog.setTestOnly('goog.ui.ControlRendererTest'); goog.require('goog.a11y.aria'); goog.require('goog.a11y.aria.Role'); goog.require('goog.a11y.aria.State'); goog.require('goog.dom'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.TagName'); goog.require('goog.dom.classlist'); goog.require('goog.object'); goog.require('goog.style'); goog.require('goog.testing.ExpectedFailures'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.jsunit'); goog.require('goog.ui.Component'); goog.require('goog.ui.Control'); goog.require('goog.ui.ControlRenderer'); goog.require('goog.userAgent'); var control, controlRenderer, testRenderer, propertyReplacer; var sandbox; var expectedFailures; function setUpPage() { sandbox = goog.dom.getElement('sandbox'); expectedFailures = new goog.testing.ExpectedFailures(); } /** * A subclass of ControlRenderer that overrides `getAriaRole` and * `getStructuralCssClass` for testing purposes. * @constructor * @extends {goog.ui.ControlRenderer} */ function TestRenderer() { goog.ui.ControlRenderer.call(this); } goog.inherits(TestRenderer, goog.ui.ControlRenderer); goog.addSingletonGetter(TestRenderer); TestRenderer.CSS_CLASS = 'goog-button'; TestRenderer.IE6_CLASS_COMBINATIONS = [ ['combined', 'goog-base-hover', 'goog-button'], ['combined', 'goog-base-disabled', 'goog-button'], ['combined', 'combined2', 'goog-base-hover', 'goog-base-rtl', 'goog-button'] ]; /** @override */ TestRenderer.prototype.getAriaRole = function() { return goog.a11y.aria.Role.BUTTON; }; /** @override */ TestRenderer.prototype.getCssClass = function() { return TestRenderer.CSS_CLASS; }; /** @override */ TestRenderer.prototype.getStructuralCssClass = function() { return 'goog-base'; }; /** @override */ TestRenderer.prototype.getIe6ClassCombinations = function() { return TestRenderer.IE6_CLASS_COMBINATIONS; }; /** * @return {boolean} Whether we're on Mac Safari 3.x. */ function isMacSafari3() { return goog.userAgent.WEBKIT && goog.userAgent.MAC && !goog.userAgent.isVersionOrHigher('527'); } /** * @return {boolean} Whether we're on IE6 or lower. */ function isIe6() { return goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('7'); } function setUp() { control = new goog.ui.Control('Hello'); controlRenderer = goog.ui.ControlRenderer.getInstance(); testRenderer = TestRenderer.getInstance(); propertyReplacer = new goog.testing.PropertyReplacer(); } function tearDown() { propertyReplacer.reset(); control.dispose(); expectedFailures.handleTearDown(); control = null; controlRenderer = null; testRenderer = null; goog.dom.removeChildren(sandbox); } function testConstructor() { assertNotNull( 'ControlRenderer singleton instance must not be null', controlRenderer); assertNotNull( 'TestRenderer singleton instance must not be null', testRenderer); } function testGetCustomRenderer() { var cssClass = 'special-css-class'; var renderer = goog.ui.ControlRenderer.getCustomRenderer( goog.ui.ControlRenderer, cssClass); assertEquals( 'Renderer should have returned the custom CSS class.', cssClass, renderer.getCssClass()); } function testGetAriaRole() { assertUndefined( 'ControlRenderer\'s ARIA role must be undefined', controlRenderer.getAriaRole()); assertEquals( 'TestRenderer\'s ARIA role must have expected value', goog.a11y.aria.Role.BUTTON, testRenderer.getAriaRole()); } function testCreateDom() { assertHTMLEquals( 'ControlRenderer must create correct DOM', '<div class="goog-control">Hello</div>', goog.dom.getOuterHtml(controlRenderer.createDom(control))); assertHTMLEquals( 'TestRenderer must create correct DOM', '<div class="goog-button goog-base">Hello</div>', goog.dom.getOuterHtml(testRenderer.createDom(control))); } function testGetContentElement() { assertEquals( 'getContentElement() must return its argument', sandbox, controlRenderer.getContentElement(sandbox)); } function testEnableExtraClassName() { // enableExtraClassName() must be a no-op if control has no DOM. controlRenderer.enableExtraClassName(control, 'foo', true); control.createDom(); var element = control.getElement(); controlRenderer.enableExtraClassName(control, 'foo', true); assertSameElements( 'Extra class name must have been added', ['goog-control', 'foo'], goog.dom.classlist.get(element)); controlRenderer.enableExtraClassName(control, 'foo', true); assertSameElements( 'Enabling existing extra class name must be a no-op', ['goog-control', 'foo'], goog.dom.classlist.get(element)); controlRenderer.enableExtraClassName(control, 'bar', false); assertSameElements( 'Disabling nonexistent class name must be a no-op', ['goog-control', 'foo'], goog.dom.classlist.get(element)); controlRenderer.enableExtraClassName(control, 'foo', false); assertSameElements( 'Extra class name must have been removed', ['goog-control'], goog.dom.classlist.get(element)); } function testCanDecorate() { assertTrue('canDecorate() must return true', controlRenderer.canDecorate()); } function testDecorate() { sandbox.innerHTML = '<div id="foo">Hello, world!</div>'; var foo = goog.dom.getElement('foo'); var element = controlRenderer.decorate(control, foo); assertEquals('decorate() must return its argument', foo, element); assertEquals('Decorated control\'s ID must be set', 'foo', control.getId()); assertTrue( 'Decorated control\'s content must be a text node', control.getContent().nodeType == goog.dom.NodeType.TEXT); assertEquals( 'Decorated control\'s content must have expected value', 'Hello, world!', control.getContent().nodeValue); assertEquals( 'Decorated control\'s state must be as expected', 0x00, control.getState()); assertSameElements( 'Decorated element\'s classes must be as expected', ['goog-control'], goog.dom.classlist.get(element)); } function testDecorateComplexDom() { sandbox.innerHTML = '<div id="foo"><i>Hello</i>,<b>world</b>!</div>'; var foo = goog.dom.getElement('foo'); var element = controlRenderer.decorate(control, foo); assertEquals('decorate() must return its argument', foo, element); assertEquals('Decorated control\'s ID must be set', 'foo', control.getId()); assertTrue( 'Decorated control\'s content must be an array', goog.isArray(control.getContent())); assertEquals( 'Decorated control\'s content must have expected length', 4, control.getContent().length); assertEquals( 'Decorated control\'s state must be as expected', 0x00, control.getState()); assertSameElements( 'Decorated element\'s classes must be as expected', ['goog-control'], goog.dom.classlist.get(element)); } function testDecorateWithClasses() { sandbox.innerHTML = '<div id="foo" class="app goog-base-disabled goog-base-hover"></div>'; var foo = goog.dom.getElement('foo'); control.addClassName('extra'); var element = testRenderer.decorate(control, foo); assertEquals('decorate() must return its argument', foo, element); assertEquals('Decorated control\'s ID must be set', 'foo', control.getId()); assertNull('Decorated control\'s content must be null', control.getContent()); assertEquals( 'Decorated control\'s state must be as expected', goog.ui.Component.State.DISABLED | goog.ui.Component.State.HOVER, control.getState()); assertSameElements( 'Decorated element\'s classes must be as expected', [ 'app', 'extra', 'goog-base', 'goog-base-disabled', 'goog-base-hover', 'goog-button' ], goog.dom.classlist.get(element)); } function testDecorateOptimization() { // Temporarily replace goog.dom.classlist.set(). propertyReplacer.set(goog.dom.classlist, 'set', function() { fail('goog.dom.classlist.set() must not be called'); }); // Since foo has all required classes, goog.dom.classlist.set() must not be // called at all. sandbox.innerHTML = '<div id="foo" class="goog-control">Foo</div>'; controlRenderer.decorate(control, goog.dom.getElement('foo')); // Since bar has all required classes, goog.dom.classlist.set() must not be // called at all. sandbox.innerHTML = '<div id="bar" class="goog-base goog-button">Bar' + '</div>'; testRenderer.decorate(control, goog.dom.getElement('bar')); // Since baz has all required classes, goog.dom.classlist.set() must not be // called at all. sandbox.innerHTML = '<div id="baz" class="goog-base goog-button ' + 'goog-button-disabled">Baz</div>'; testRenderer.decorate(control, goog.dom.getElement('baz')); } function testInitializeDom() { var renderer = new goog.ui.ControlRenderer(); // Replace setRightToLeft(). renderer.setRightToLeft = function() { fail('setRightToLeft() must not be called'); }; // When a control with default render direction enters the document, // setRightToLeft() must not be called. control.setRenderer(renderer); control.render(sandbox); // When a control in the default state (enabled, visible, focusable) // enters the document, it must get a tab index. // Expected to fail on Mac Safari 3, because it doesn't support tab index. expectedFailures.expectFailureFor(isMacSafari3()); try { assertTrue( 'Enabled, visible, focusable control must have tab index', goog.dom.isFocusableTabIndex(control.getElement())); } catch (e) { expectedFailures.handleException(e); } } function testInitializeDomDecorated() { var renderer = new goog.ui.ControlRenderer(); // Replace setRightToLeft(). renderer.setRightToLeft = function() { fail('setRightToLeft() must not be called'); }; sandbox.innerHTML = '<div id="foo" class="goog-control">Foo</div>'; // When a control with default render direction enters the document, // setRightToLeft() must not be called. control.setRenderer(renderer); control.decorate(goog.dom.getElement('foo')); // When a control in the default state (enabled, visible, focusable) // enters the document, it must get a tab index. // Expected to fail on Mac Safari 3, because it doesn't support tab index. expectedFailures.expectFailureFor(isMacSafari3()); try { assertTrue( 'Enabled, visible, focusable control must have tab index', goog.dom.isFocusableTabIndex(control.getElement())); } catch (e) { expectedFailures.handleException(e); } } function testInitializeDomDisabledBiDi() { var renderer = new goog.ui.ControlRenderer(); // Replace setFocusable(). renderer.setFocusable = function() { fail('setFocusable() must not be called'); }; // When a disabled control enters the document, setFocusable() must not // be called. control.setEnabled(false); control.setRightToLeft(true); control.setRenderer(renderer); control.render(sandbox); // When a right-to-left control enters the document, special stying must // be applied. assertSameElements( 'BiDi control must have right-to-left class', ['goog-control', 'goog-control-disabled', 'goog-control-rtl'], goog.dom.classlist.get(control.getElement())); } function testInitializeDomDisabledBiDiDecorated() { var renderer = new goog.ui.ControlRenderer(); // Replace setFocusable(). renderer.setFocusable = function() { fail('setFocusable() must not be called'); }; sandbox.innerHTML = '<div dir="rtl">\n' + ' <div id="foo" class="goog-control-disabled">Foo</div>\n' + '</div>\n'; // When a disabled control enters the document, setFocusable() must not // be called. control.setRenderer(renderer); control.decorate(goog.dom.getElement('foo')); // When a right-to-left control enters the document, special stying must // be applied. assertSameElements( 'BiDi control must have right-to-left class', ['goog-control', 'goog-control-disabled', 'goog-control-rtl'], goog.dom.classlist.get(control.getElement())); } function testSetAriaRole() { sandbox.innerHTML = '<div id="foo">Foo</div><div id="bar">Bar</div>'; var foo = goog.dom.getElement('foo'); assertNotNull(foo); controlRenderer.setAriaRole(foo); assertEvaluatesToFalse( 'The role should be empty.', goog.a11y.aria.getRole(foo)); var bar = goog.dom.getElement('bar'); assertNotNull(bar); testRenderer.setAriaRole(bar); assertEquals( 'Element must have expected ARIA role', goog.a11y.aria.Role.BUTTON, goog.a11y.aria.getRole(bar)); } function testSetAriaStatesHidden() { sandbox.innerHTML = '<div id="foo">Foo</div><div id="bar">Bar</div>'; var foo = goog.dom.getElement('foo'); control.setVisible(true); controlRenderer.setAriaStates(control, foo); assertEquals( 'ControlRenderer did not set aria-hidden.', '', goog.a11y.aria.getState(foo, goog.a11y.aria.State.HIDDEN)); control.setVisible(false); controlRenderer.setAriaStates(control, foo); assertEquals( 'ControlRenderer did not set aria-hidden.', 'true', goog.a11y.aria.getState(foo, goog.a11y.aria.State.HIDDEN)); } function testSetAriaStatesDisabled() { sandbox.innerHTML = '<div id="foo">Foo</div><div id="bar">Bar</div>'; var foo = goog.dom.getElement('foo'); control.setEnabled(true); controlRenderer.setAriaStates(control, foo); assertEquals( 'ControlRenderer did not set aria-disabled.', '', goog.a11y.aria.getState(foo, goog.a11y.aria.State.DISABLED)); control.setEnabled(false); controlRenderer.setAriaStates(control, foo); assertEquals( 'ControlRenderer did not set aria-disabled.', 'true', goog.a11y.aria.getState(foo, goog.a11y.aria.State.DISABLED)); } function testSetAriaStatesSelected() { sandbox.innerHTML = '<div id="foo">Foo</div><div id="bar">Bar</div>'; var foo = goog.dom.getElement('foo'); control.setSupportedState(goog.ui.Component.State.SELECTED, true); control.setSelected(true); controlRenderer.setAriaStates(control, foo); assertEquals( 'ControlRenderer did not set aria-selected.', 'true', goog.a11y.aria.getState(foo, goog.a11y.aria.State.SELECTED)); control.setSelected(false); controlRenderer.setAriaStates(control, foo); assertEquals( 'ControlRenderer did not set aria-selected.', 'false', goog.a11y.aria.getState(foo, goog.a11y.aria.State.SELECTED)); } function testSetAriaStatesChecked() { sandbox.innerHTML = '<div id="foo">Foo</div><div id="bar">Bar</div>'; var foo = goog.dom.getElement('foo'); control.setSupportedState(goog.ui.Component.State.CHECKED, true); control.setChecked(true); controlRenderer.setAriaStates(control, foo); assertEquals( 'ControlRenderer did not set aria-checked.', 'true', goog.a11y.aria.getState(foo, goog.a11y.aria.State.CHECKED)); control.setChecked(false); controlRenderer.setAriaStates(control, foo); assertEquals( 'ControlRenderer did not set aria-checked.', 'false', goog.a11y.aria.getState(foo, goog.a11y.aria.State.CHECKED)); } function testSetAriaStatesExpanded() { sandbox.innerHTML = '<div id="foo">Foo</div><div id="bar">Bar</div>'; var foo = goog.dom.getElement('foo'); control.setSupportedState(goog.ui.Component.State.OPENED, true); control.setOpen(true); controlRenderer.setAriaStates(control, foo); assertEquals( 'ControlRenderer did not set aria-expanded.', 'true', goog.a11y.aria.getState(foo, goog.a11y.aria.State.EXPANDED)); control.setOpen(false); controlRenderer.setAriaStates(control, foo); assertEquals( 'ControlRenderer did not set aria-expanded.', 'false', goog.a11y.aria.getState(foo, goog.a11y.aria.State.EXPANDED)); } function testSetAllowTextSelection() { sandbox.innerHTML = '<div id="foo"><span>Foo</span></div>'; var foo = goog.dom.getElement('foo'); controlRenderer.setAllowTextSelection(foo, false); assertTrue( 'Parent element must be unselectable on all browsers', goog.style.isUnselectable(foo)); if (goog.userAgent.IE || goog.userAgent.OPERA) { assertTrue( 'On IE and Opera, child element must also be unselectable', goog.style.isUnselectable(foo.firstChild)); } else { assertFalse( 'On browsers other than IE and Opera, the child element ' + 'must not be unselectable', goog.style.isUnselectable(foo.firstChild)); } controlRenderer.setAllowTextSelection(foo, true); assertFalse( 'Parent element must be selectable', goog.style.isUnselectable(foo)); assertFalse( 'Child element must be unselectable', goog.style.isUnselectable(foo.firstChild)); } function testSetRightToLeft() { sandbox.innerHTML = '<div id="foo">Foo</div><div id="bar">Bar</div>'; var foo = goog.dom.getElement('foo'); controlRenderer.setRightToLeft(foo, true); assertSameElements( 'Element must have right-to-left class applied', ['goog-control-rtl'], goog.dom.classlist.get(foo)); controlRenderer.setRightToLeft(foo, false); assertSameElements( 'Element must not have right-to-left class applied', [], goog.dom.classlist.get(foo)); var bar = goog.dom.getElement('bar'); testRenderer.setRightToLeft(bar, true); assertSameElements( 'Element must have right-to-left class applied', ['goog-base-rtl'], goog.dom.classlist.get(bar)); testRenderer.setRightToLeft(bar, false); assertSameElements( 'Element must not have right-to-left class applied', [], goog.dom.classlist.get(bar)); } function testIsFocusable() { control.render(sandbox); // Expected to fail on Mac Safari 3, because it doesn't support tab index. expectedFailures.expectFailureFor(isMacSafari3()); try { assertTrue( 'Control\'s key event target must be focusable', controlRenderer.isFocusable(control)); } catch (e) { expectedFailures.handleException(e); } } function testIsFocusableForNonFocusableControl() { control.setSupportedState(goog.ui.Component.State.FOCUSED, false); control.render(sandbox); assertFalse( 'Non-focusable control\'s key event target must not be ' + 'focusable', controlRenderer.isFocusable(control)); } function testIsFocusableForControlWithoutKeyEventTarget() { // Unrendered control has no key event target. assertNull( 'Unrendered control must not have key event target', control.getKeyEventTarget()); assertFalse( 'isFocusable() must return null if no key event target', controlRenderer.isFocusable(control)); } function testSetFocusable() { control.render(sandbox); controlRenderer.setFocusable(control, false); assertFalse( 'Control\'s key event target must not have tab index', goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); controlRenderer.setFocusable(control, true); // Expected to fail on Mac Safari 3, because it doesn't support tab index. expectedFailures.expectFailureFor(isMacSafari3()); try { assertTrue( 'Control\'s key event target must have focusable tab index', goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); } catch (e) { expectedFailures.handleException(e); } } function testSetFocusableForNonFocusableControl() { control.setSupportedState(goog.ui.Component.State.FOCUSED, false); control.render(sandbox); assertFalse( 'Non-focusable control\'s key event target must not be ' + 'focusable', goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); controlRenderer.setFocusable(control, true); assertFalse( 'Non-focusable control\'s key event target must not be ' + 'focusable, even after calling setFocusable(true)', goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); } function testSetVisible() { sandbox.innerHTML = '<div id="foo">Foo</div>'; var foo = goog.dom.getElement('foo'); assertTrue('Element must be visible', foo.style.display != 'none'); controlRenderer.setVisible(foo, true); assertEquals( 'ControlRenderer did not set aria-hidden.', 'false', goog.a11y.aria.getState(foo, goog.a11y.aria.State.HIDDEN)); assertTrue('Element must still be visible', foo.style.display != 'none'); controlRenderer.setVisible(foo, false); assertEquals( 'ControlRenderer did not set aria-hidden.', 'true', goog.a11y.aria.getState(foo, goog.a11y.aria.State.HIDDEN)); assertTrue('Element must be hidden', foo.style.display == 'none'); } function testSetState() { control.setRenderer(testRenderer); control.createDom(); var element = control.getElement(); assertNotNull(element); assertSameElements( 'Control must have expected class names', ['goog-button', 'goog-base'], goog.dom.classlist.get(element)); assertEquals( 'Control must not have disabled ARIA state', '', goog.a11y.aria.getState(element, goog.a11y.aria.State.DISABLED)); testRenderer.setState(control, goog.ui.Component.State.DISABLED, true); assertSameElements( 'Control must have disabled class name', ['goog-button', 'goog-base', 'goog-base-disabled'], goog.dom.classlist.get(element)); assertEquals( 'Control must have disabled ARIA state', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.DISABLED)); testRenderer.setState(control, goog.ui.Component.State.DISABLED, false); assertSameElements( 'Control must no longer have disabled class name', ['goog-button', 'goog-base'], goog.dom.classlist.get(element)); assertEquals( 'Control must not have disabled ARIA state', 'false', goog.a11y.aria.getState(element, goog.a11y.aria.State.DISABLED)); testRenderer.setState(control, 0xFFFFFF, true); assertSameElements( 'Class names must be unchanged for invalid state', ['goog-button', 'goog-base'], goog.dom.classlist.get(element)); } function testUpdateAriaStateDisabled() { control.createDom(); var element = control.getElement(); assertNotNull(element); controlRenderer.updateAriaState( element, goog.ui.Component.State.DISABLED, true); assertEquals( 'Control must have disabled ARIA state', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.DISABLED)); controlRenderer.updateAriaState( element, goog.ui.Component.State.DISABLED, false); assertEquals( 'Control must no longer have disabled ARIA state', 'false', goog.a11y.aria.getState(element, goog.a11y.aria.State.DISABLED)); } function testSetAriaStatesRender_ariaStateDisabled() { control.setEnabled(false); var renderer = new goog.ui.ControlRenderer(); control.setRenderer(renderer); control.render(sandbox); var element = control.getElement(); assertNotNull(element); assertFalse('Control must be disabled', control.isEnabled()); assertEquals( 'Control must have disabled ARIA state', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.DISABLED)); } function testSetAriaStatesDecorate_ariaStateDisabled() { sandbox.innerHTML = '<div id="foo" class="app goog-base-disabled"></div>'; var element = goog.dom.getElement('foo'); control.setRenderer(testRenderer); control.decorate(element); assertNotNull(element); assertFalse('Control must be disabled', control.isEnabled()); assertEquals( 'Control must have disabled ARIA state', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.DISABLED)); } function testUpdateAriaStateSelected() { control.createDom(); var element = control.getElement(); assertNotNull(element); controlRenderer.updateAriaState( element, goog.ui.Component.State.SELECTED, true); assertEquals( 'Control must have selected ARIA state', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.SELECTED)); controlRenderer.updateAriaState( element, goog.ui.Component.State.SELECTED, false); assertEquals( 'Control must no longer have selected ARIA state', 'false', goog.a11y.aria.getState(element, goog.a11y.aria.State.SELECTED)); } function testSetAriaStatesRender_ariaStateSelected() { control.setSupportedState(goog.ui.Component.State.SELECTED, true); control.setSelected(true); var renderer = new goog.ui.ControlRenderer(); control.setRenderer(renderer); control.render(sandbox); var element = control.getElement(); assertNotNull(element); assertTrue('Control must be selected', control.isSelected()); assertEquals( 'Control must have selected ARIA state', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.SELECTED)); } function testSetAriaStatesRender_ariaStateNotSelected() { control.setSupportedState(goog.ui.Component.State.SELECTED, true); var renderer = new goog.ui.ControlRenderer(); control.setRenderer(renderer); control.render(sandbox); var element = control.getElement(); assertNotNull(element); assertFalse('Control must not be selected', control.isSelected()); assertEquals( 'Control must have not-selected ARIA state', 'false', goog.a11y.aria.getState(element, goog.a11y.aria.State.SELECTED)); } function testSetAriaStatesDecorate_ariaStateSelected() { control.setSupportedState(goog.ui.Component.State.SELECTED, true); sandbox.innerHTML = '<div id="foo" class="app goog-control-selected"></div>'; var element = goog.dom.getElement('foo'); control.setRenderer(controlRenderer); control.decorate(element); assertNotNull(element); assertTrue('Control must be selected', control.isSelected()); assertEquals( 'Control must have selected ARIA state', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.SELECTED)); } function testUpdateAriaStateChecked() { control.createDom(); var element = control.getElement(); assertNotNull(element); controlRenderer.updateAriaState( element, goog.ui.Component.State.CHECKED, true); assertEquals( 'Control must have checked ARIA state', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.CHECKED)); controlRenderer.updateAriaState( element, goog.ui.Component.State.CHECKED, false); assertEquals( 'Control must no longer have checked ARIA state', 'false', goog.a11y.aria.getState(element, goog.a11y.aria.State.CHECKED)); } function testSetAriaStatesRender_ariaStateChecked() { control.setSupportedState(goog.ui.Component.State.CHECKED, true); control.setChecked(true); var renderer = new goog.ui.ControlRenderer(); control.setRenderer(renderer); control.render(sandbox); var element = control.getElement(); assertNotNull(element); assertTrue('Control must be checked', control.isChecked()); assertEquals( 'Control must have checked ARIA state', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.CHECKED)); } function testSetAriaStatesDecorate_ariaStateChecked() { sandbox.innerHTML = '<div id="foo" class="app goog-control-checked"></div>'; var element = goog.dom.getElement('foo'); control.setSupportedState(goog.ui.Component.State.CHECKED, true); control.decorate(element); assertNotNull(element); assertTrue('Control must be checked', control.isChecked()); assertEquals( 'Control must have checked ARIA state', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.CHECKED)); } function testUpdateAriaStateOpened() { control.createDom(); var element = control.getElement(); assertNotNull(element); controlRenderer.updateAriaState( element, goog.ui.Component.State.OPENED, true); assertEquals( 'Control must have expanded ARIA state', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.EXPANDED)); controlRenderer.updateAriaState( element, goog.ui.Component.State.OPENED, false); assertEquals( 'Control must no longer have expanded ARIA state', 'false', goog.a11y.aria.getState(element, goog.a11y.aria.State.EXPANDED)); } function testSetAriaStatesRender_ariaStateOpened() { control.setSupportedState(goog.ui.Component.State.OPENED, true); control.setOpen(true); var renderer = new goog.ui.ControlRenderer(); control.setRenderer(renderer); control.render(sandbox); var element = control.getElement(); assertNotNull(element); assertTrue('Control must be opened', control.isOpen()); assertEquals( 'Control must have expanded ARIA state', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.EXPANDED)); } function testSetAriaStatesDecorate_ariaStateOpened() { sandbox.innerHTML = '<div id="foo" class="app goog-base-open"></div>'; var element = goog.dom.getElement('foo'); control.setSupportedState(goog.ui.Component.State.OPENED, true); control.setRenderer(testRenderer); control.decorate(element); assertNotNull(element); assertTrue('Control must be opened', control.isOpen()); assertEquals( 'Control must have expanded ARIA state', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.EXPANDED)); } function testSetAriaStateRoleNotInMap() { sandbox.innerHTML = '<div id="foo" role="option">Hello, world!</div>'; control.setRenderer(controlRenderer); control.setSupportedState(goog.ui.Component.State.CHECKED, true); var element = goog.dom.getElement('foo'); control.decorate(element); assertEquals( 'Element should have ARIA role option.', goog.a11y.aria.Role.OPTION, goog.a11y.aria.getRole(element)); control.setStateInternal(goog.ui.Component.State.DISABLED, true); controlRenderer.setAriaStates(control, element); assertEquals( 'Element should have aria-disabled true', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.DISABLED)); control.setStateInternal(goog.ui.Component.State.CHECKED, true); controlRenderer.setAriaStates(control, element); assertEquals( 'Element should have aria-checked true', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.CHECKED)); } function testSetAriaStateRoleInMapMatches() { sandbox.innerHTML = '<div id="foo" role="checkbox">Hello, world!</div>'; control.setRenderer(controlRenderer); control.setSupportedState(goog.ui.Component.State.CHECKED, true); var element = goog.dom.getElement('foo'); control.decorate(element); assertEquals( 'Element should have ARIA role checkbox.', goog.a11y.aria.Role.CHECKBOX, goog.a11y.aria.getRole(element)); control.setStateInternal(goog.ui.Component.State.DISABLED, true); controlRenderer.setAriaStates(control, element); assertEquals( 'Element should have aria-disabled true', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.DISABLED)); control.setStateInternal(goog.ui.Component.State.CHECKED, true); controlRenderer.setAriaStates(control, element); assertEquals( 'Element should have aria-checked true', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.CHECKED)); } function testSetAriaStateRoleInMapNotMatches() { sandbox.innerHTML = '<div id="foo" role="button">Hello, world!</div>'; control.setRenderer(controlRenderer); control.setSupportedState(goog.ui.Component.State.CHECKED, true); var element = goog.dom.getElement('foo'); control.decorate(element); assertEquals( 'Element should have ARIA role button.', goog.a11y.aria.Role.BUTTON, goog.a11y.aria.getRole(element)); control.setStateInternal(goog.ui.Component.State.DISABLED, true); controlRenderer.setAriaStates(control, element); assertEquals( 'Element should have aria-disabled true', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.DISABLED)); control.setStateInternal(goog.ui.Component.State.CHECKED, true); controlRenderer.setAriaStates(control, element); assertEquals( 'Element should have aria-pressed true', 'true', goog.a11y.aria.getState(element, goog.a11y.aria.State.PRESSED)); assertEquals( 'Element should not have aria-checked', '', goog.a11y.aria.getState(element, goog.a11y.aria.State.CHECKED)); } function testToggleAriaStateMap() { var map = goog.object.create( goog.a11y.aria.Role.BUTTON, goog.a11y.aria.State.PRESSED, goog.a11y.aria.Role.CHECKBOX, goog.a11y.aria.State.CHECKED, goog.a11y.aria.Role.MENU_ITEM, goog.a11y.aria.State.SELECTED, goog.a11y.aria.Role.MENU_ITEM_CHECKBOX, goog.a11y.aria.State.CHECKED, goog.a11y.aria.Role.MENU_ITEM_RADIO, goog.a11y.aria.State.CHECKED, goog.a11y.aria.Role.RADIO, goog.a11y.aria.State.CHECKED, goog.a11y.aria.Role.TAB, goog.a11y.aria.State.SELECTED, goog.a11y.aria.Role.TREEITEM, goog.a11y.aria.State.SELECTED); for (var key in map) { assertTrue( 'Toggle ARIA state map incorrect.', key in goog.ui.ControlRenderer.TOGGLE_ARIA_STATE_MAP_); assertEquals( 'Toggle ARIA state map incorrect.', map[key], goog.ui.ControlRenderer.TOGGLE_ARIA_STATE_MAP_[key]); } } function testSetContent() { goog.dom.setTextContent(sandbox, 'Hello, world!'); controlRenderer.setContent(sandbox, 'Not so fast!'); assertEquals( 'Element must contain expected text value', 'Not so fast!', goog.dom.getTextContent(sandbox)); } function testSetContentNull() { goog.dom.setTextContent(sandbox, 'Hello, world!'); controlRenderer.setContent(sandbox, null); assertEquals( 'Element must have no child nodes', 0, sandbox.childNodes.length); assertEquals( 'Element must contain expected text value', '', goog.dom.getTextContent(sandbox)); } function testSetContentEmpty() { goog.dom.setTextContent(sandbox, 'Hello, world!'); controlRenderer.setContent(sandbox, ''); assertEquals('Element must not have children', 0, sandbox.childNodes.length); assertEquals( 'Element must contain expected text value', '', goog.dom.getTextContent(sandbox)); } function testSetContentWhitespace() { goog.dom.setTextContent(sandbox, 'Hello, world!'); controlRenderer.setContent(sandbox, ' '); assertEquals('Element must have one child', 1, sandbox.childNodes.length); assertEquals( 'Child must be a text node', goog.dom.NodeType.TEXT, sandbox.firstChild.nodeType); assertEquals( 'Element must contain expected text value', ' ', goog.dom.getTextContent(sandbox)); } function testSetContentTextNode() { goog.dom.setTextContent(sandbox, 'Hello, world!'); controlRenderer.setContent(sandbox, document.createTextNode('Text')); assertEquals('Element must have one child', 1, sandbox.childNodes.length); assertEquals( 'Child must be a text node', goog.dom.NodeType.TEXT, sandbox.firstChild.nodeType); assertEquals( 'Element must contain expected text value', 'Text', goog.dom.getTextContent(sandbox)); } function testSetContentElementNode() { goog.dom.setTextContent(sandbox, 'Hello, world!'); controlRenderer.setContent( sandbox, goog.dom.createDom(goog.dom.TagName.DIV, {id: 'foo'}, 'Foo')); assertEquals('Element must have one child', 1, sandbox.childNodes.length); assertEquals( 'Child must be an element node', goog.dom.NodeType.ELEMENT, sandbox.firstChild.nodeType); assertHTMLEquals( 'Element must contain expected HTML', '<div id="foo">Foo</div>', sandbox.innerHTML); } function testSetContentArray() { goog.dom.setTextContent(sandbox, 'Hello, world!'); controlRenderer.setContent( sandbox, ['Hello, ', goog.dom.createDom(goog.dom.TagName.B, null, 'world'), '!']); assertEquals( 'Element must have three children', 3, sandbox.childNodes.length); assertEquals( '1st child must be a text node', goog.dom.NodeType.TEXT, sandbox.childNodes[0].nodeType); assertEquals( '2nd child must be an element', goog.dom.NodeType.ELEMENT, sandbox.childNodes[1].nodeType); assertEquals( '3rd child must be a text node', goog.dom.NodeType.TEXT, sandbox.childNodes[2].nodeType); assertHTMLEquals( 'Element must contain expected HTML', 'Hello, <b>world</b>!', sandbox.innerHTML); } function testSetContentNodeList() { goog.dom.setTextContent(sandbox, 'Hello, world!'); var div = goog.dom.createDom( goog.dom.TagName.DIV, null, 'Hello, ', goog.dom.createDom(goog.dom.TagName.B, null, 'world'), '!'); controlRenderer.setContent(sandbox, div.childNodes); assertEquals( 'Element must have three children', 3, sandbox.childNodes.length); assertEquals( '1st child must be a text node', goog.dom.NodeType.TEXT, sandbox.childNodes[0].nodeType); assertEquals( '2nd child must be an element', goog.dom.NodeType.ELEMENT, sandbox.childNodes[1].nodeType); assertEquals( '3rd child must be a text node', goog.dom.NodeType.TEXT, sandbox.childNodes[2].nodeType); assertHTMLEquals( 'Element must contain expected HTML', 'Hello, <b>world</b>!', sandbox.innerHTML); } function testGetKeyEventTarget() { assertNull( 'Key event target for unrendered control must be null', controlRenderer.getKeyEventTarget(control)); control.createDom(); assertEquals( 'Key event target for rendered control must be its element', control.getElement(), controlRenderer.getKeyEventTarget(control)); } function testGetCssClass() { assertEquals( 'ControlRenderer\'s CSS class must have expected value', goog.ui.ControlRenderer.CSS_CLASS, controlRenderer.getCssClass()); assertEquals( 'TestRenderer\'s CSS class must have expected value', TestRenderer.CSS_CLASS, testRenderer.getCssClass()); } function testGetStructuralCssClass() { assertEquals( 'ControlRenderer\'s structural class must be its CSS class', controlRenderer.getCssClass(), controlRenderer.getStructuralCssClass()); assertEquals( 'TestRenderer\'s structural class must have expected value', 'goog-base', testRenderer.getStructuralCssClass()); } function testGetClassNames() { // These tests use assertArrayEquals, because the order is significant. assertArrayEquals( 'ControlRenderer must return expected class names ' + 'in the expected order', ['goog-control'], controlRenderer.getClassNames(control)); assertArrayEquals( 'TestRenderer must return expected class names ' + 'in the expected order', ['goog-button', 'goog-base'], testRenderer.getClassNames(control)); } function testGetClassNamesForControlWithState() { control.setStateInternal( goog.ui.Component.State.HOVER | goog.ui.Component.State.ACTIVE); // These tests use assertArrayEquals, because the order is significant. assertArrayEquals( 'ControlRenderer must return expected class names ' + 'in the expected order', ['goog-control', 'goog-control-hover', 'goog-control-active'], controlRenderer.getClassNames(control)); assertArrayEquals( 'TestRenderer must return expected class names ' + 'in the expected order', ['goog-button', 'goog-base', 'goog-base-hover', 'goog-base-active'], testRenderer.getClassNames(control)); } function testGetClassNamesForControlWithExtraClassNames() { control.addClassName('foo'); control.addClassName('bar'); // These tests use assertArrayEquals, because the order is significant. assertArrayEquals( 'ControlRenderer must return expected class names ' + 'in the expected order', ['goog-control', 'foo', 'bar'], controlRenderer.getClassNames(control)); assertArrayEquals( 'TestRenderer must return expected class names ' + 'in the expected order', ['goog-button', 'goog-base', 'foo', 'bar'], testRenderer.getClassNames(control)); } function testGetClassNamesForControlWithStateAndExtraClassNames() { control.setStateInternal( goog.ui.Component.State.HOVER | goog.ui.Component.State.ACTIVE); control.addClassName('foo'); control.addClassName('bar'); // These tests use assertArrayEquals, because the order is significant. assertArrayEquals( 'ControlRenderer must return expected class names ' + 'in the expected order', [ 'goog-control', 'goog-control-hover', 'goog-control-active', 'foo', 'bar' ], controlRenderer.getClassNames(control)); assertArrayEquals( 'TestRenderer must return expected class names ' + 'in the expected order', [ 'goog-button', 'goog-base', 'goog-base-hover', 'goog-base-active', 'foo', 'bar' ], testRenderer.getClassNames(control)); } function testGetClassNamesForState() { // These tests use assertArrayEquals, because the order is significant. assertArrayEquals( 'ControlRenderer must return expected class names ' + 'in the expected order', ['goog-control-hover', 'goog-control-checked'], controlRenderer.getClassNamesForState( goog.ui.Component.State.HOVER | goog.ui.Component.State.CHECKED)); assertArrayEquals( 'TestRenderer must return expected class names ' + 'in the expected order', ['goog-base-hover', 'goog-base-checked'], testRenderer.getClassNamesForState( goog.ui.Component.State.HOVER | goog.ui.Component.State.CHECKED)); } function testGetClassForState() { var renderer = new goog.ui.ControlRenderer(); assertUndefined( 'State-to-class map must not exist until first use', renderer.classByState_); assertEquals( 'Renderer must return expected class name for SELECTED', 'goog-control-selected', renderer.getClassForState(goog.ui.Component.State.SELECTED)); assertUndefined( 'Renderer must return undefined for invalid state', renderer.getClassForState('foo')); } function testGetStateFromClass() { var renderer = new goog.ui.ControlRenderer(); assertUndefined( 'Class-to-state map must not exist until first use', renderer.stateByClass_); assertEquals( 'Renderer must return expected state', goog.ui.Component.State.SELECTED, renderer.getStateFromClass('goog-control-selected')); assertEquals( 'Renderer must return 0x00 for unknown class', 0x00, renderer.getStateFromClass('goog-control-annoyed')); } function testIe6ClassCombinationsCreateDom() { control.setRenderer(testRenderer); control.enableClassName('combined', true); control.createDom(); var element = control.getElement(); testRenderer.setState(control, goog.ui.Component.State.DISABLED, true); var expectedClasses = ['combined', 'goog-base', 'goog-base-disabled', 'goog-button']; if (isIe6()) { assertSameElements( 'IE6 and lower should have one combined class', expectedClasses.concat(['combined_goog-base-disabled_goog-button']), goog.dom.classlist.get(element)); } else { assertSameElements( 'Non IE6 browsers should not have a combined class', expectedClasses, goog.dom.classlist.get(element)); } testRenderer.setState(control, goog.ui.Component.State.DISABLED, false); testRenderer.setState(control, goog.ui.Component.State.HOVER, true); var expectedClasses = ['combined', 'goog-base', 'goog-base-hover', 'goog-button']; if (isIe6()) { assertSameElements( 'IE6 and lower should have one combined class', expectedClasses.concat(['combined_goog-base-hover_goog-button']), goog.dom.classlist.get(element)); } else { assertSameElements( 'Non IE6 browsers should not have a combined class', expectedClasses, goog.dom.classlist.get(element)); } testRenderer.setRightToLeft(element, true); testRenderer.enableExtraClassName(control, 'combined2', true); var expectedClasses = [ 'combined', 'combined2', 'goog-base', 'goog-base-hover', 'goog-base-rtl', 'goog-button' ]; if (isIe6()) { assertSameElements( 'IE6 and lower should have two combined class', expectedClasses.concat([ 'combined_goog-base-hover_goog-button', 'combined_combined2_goog-base-hover_goog-base-rtl_goog-button' ]), goog.dom.classlist.get(element)); } else { assertSameElements( 'Non IE6 browsers should not have a combined class', expectedClasses, goog.dom.classlist.get(element)); } } function testIe6ClassCombinationsDecorate() { sandbox.innerHTML = '<div id="foo" class="combined goog-base-hover"></div>'; var foo = goog.dom.getElement('foo'); var element = testRenderer.decorate(control, foo); var expectedClasses = ['combined', 'goog-base', 'goog-base-hover', 'goog-button']; if (isIe6()) { assertSameElements( 'IE6 and lower should have one combined class', expectedClasses.concat(['combined_goog-base-hover_goog-button']), goog.dom.classlist.get(element)); } else { assertSameElements( 'Non IE6 browsers should not have a combined class', expectedClasses, goog.dom.classlist.get(element)); } }
teppeis/closure-library
closure/goog/ui/controlrenderer_test.js
JavaScript
apache-2.0
45,576
/** * @author Trilogis Srl * @author Gustavo German Soria * * Search DAO queries module */ /** * Import of the line model * @type {exports} */ var line = require('./../models/line.js'); /** * Import of the road model * @type {exports} */ var road = require('./../models/road.js'); /** * Import of the polygon model * @type {exports} */ var polygon = require('./../models/polygon.js'); /** * Import of the point model * @type {exports} */ var point = require('./../models/point.js'); /** * Import of the validation module * @type {exports} */ var val = require('./../util/validator.js'); /** * Import of the parameters module * @type {exports} */ var params = require('./../util/params.js'); /** * Internal use: it retrieves the correct table name (entity table) from the given entity type identifier stored in the callback object * @param callback Callback object in which is stored the entity type identifier * @returns {String} a table name */ var getTable = function(callback){ /* validation of the entity type identifier */ val.assertType(callback); /* variable for the table name, initialized as undefined */ var table = undefined; /* select the correct value for the table variable */ switch (callback.params.type) { case params.LINE : { table = line.model.table; } break; case params.POLYGON : { table = polygon.model.table; } break; case params.ROAD : { table = road.model.table; } break; case params.POINT : { table = point.model.table; } break; } /* validation of the table variable */ val.assertNotUndefined(table); return table; } /** * Internal use: it retrieves the correct table name (name table) from the given entity type identifier stored in the callback object * @param callback Callback object in which is stored the entity type identifier * @returns {String} a table name */ var getNameTable = function(callback){ /* validation of the entity type identifier */ val.assertType(callback); /* variable for the table name, initialized as undefined */ var table = undefined; /* select the correct value for the table variable */ switch (callback.params.type) { case params.LINE : { table = line.model.nameTable; } break; case params.POLYGON : { table = polygon.model.nameTable; } break; case params.ROAD : { table = road.model.nameTable; } break; case params.POINT : { table = point.model.nameTable; } break; } /* validation of the table variable */ val.assertNotUndefined(table); return table; } /** * Internal use: it retrieves the correct table name (name relationship table) from the given entity type identifier stored in the callback object * @param callback Callback object in which is stored the entity type identifier * @returns {String} a table name */ var getNameRelTable = function(callback){ /* validation of the entity type identifier */ val.assertType(callback); /* variable for the table name, initialized as undefined */ var table = undefined; /* select the correct value for the table variable */ switch (callback.params.type) { case params.LINE : { table = line.model.nameRelTable; } break; case params.POLYGON : { table = polygon.model.nameRelTable; } break; case params.ROAD : { table = road.model.nameRelTable; } break; case params.POINT : { table = point.model.nameRelTable; } break; } /* validation of the table variable */ val.assertNotUndefined(table); return table; } /** * Internal use: it retrieves the correct table name (style table) from the given entity type identifier stored in the callback object * @param callback Callback object in which is stored the entity type identifier * @returns {String} a table name */ var getStyleTable = function(callback){ /* validation of the entity type identifier */ val.assertType(callback); /* variable for the table name, initialized as undefined */ var table = undefined; /* select the correct value for the table variable */ switch (callback.params.type) { case params.LINE : { table = line.model.styleTable; } break; case params.POLYGON : { table = polygon.model.styleTable; } break; case params.ROAD : { table = road.model.styleTable; } break; case params.POINT : { table = point.model.styleTable; } break; } /* validation of the table variable */ val.assertNotUndefined(table); return table; } var getByPartialName = function(callback){ /** * Table names. They are retrieved from the entity type identifier stored in the callback object * @type {String} the table name */ var table = getTable(callback); var nameTable = getNameTable(callback); var nameRelTable = getNameRelTable(callback); var styleTable = getStyleTable(callback); var _query = "" + "SELECT osm_id, name, lod FROM "+table+" NATURAL JOIN "+styleTable+" WHERE is_deleted = false AND lod <= $1::integer AND osm_id IN (SELECT DISTINCT osm_id FROM "+nameRelTable+" WHERE name_id IN (SELECT name_id FROM "+nameTable+" WHERE name ILIKE $2::varchar)) ORDER BY lod"; return _query; } module.exports.getByPartialName = getByPartialName;
Gagaus/wwwOSM
backend/www-osm/queries/search-dao-queries.js
JavaScript
apache-2.0
6,098
// Copyright 2017 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. InspectorTest.log('Tests how multiple sessions interact while pausing, stepping, setting breakpoints and blackboxing.'); var contextGroup = new InspectorTest.ContextGroup(); contextGroup.addScript(` function foo() { return 1; } function baz() { return 2; } function stepping() { debugger; var a = 1; var b = 1; } //# sourceURL=test.js`, 9, 25); contextGroup.addScript(` function bar() { debugger; } //# sourceURL=test2.js`, 23, 25); (async function test() { InspectorTest.log('Connecting session 1'); var session1 = contextGroup.connect(); await session1.Protocol.Debugger.enable(); InspectorTest.log('Pausing in 1'); session1.Protocol.Runtime.evaluate({expression: 'debugger;'}); await waitForPaused(session1, 1); InspectorTest.log('Connecting session 2'); var session2 = contextGroup.connect(); var enabledPromise = session2.Protocol.Debugger.enable(); await waitForPaused(session2, 2); await enabledPromise; InspectorTest.log('Resuming in 2'); session2.Protocol.Debugger.resume(); await waitForBothResumed(); InspectorTest.log('Setting breakpoints in 1'); await session1.Protocol.Debugger.setBreakpointByUrl({url: 'test.js', lineNumber: 11}); await session1.Protocol.Debugger.setBreakpointByUrl({url: 'test.js', lineNumber: 14}); InspectorTest.log('Setting breakpoints in 2'); await session2.Protocol.Debugger.setBreakpointByUrl({url: 'test.js', lineNumber: 11}); InspectorTest.log('Evaluating common breakpoint in 1'); session1.Protocol.Runtime.evaluate({expression: 'foo();'}); await waitForBothPaused(); InspectorTest.log('Resuming in 1'); session1.Protocol.Debugger.resume(); await waitForBothResumed(); InspectorTest.log('Evaluating debugger in 1'); session1.Protocol.Runtime.evaluate({expression: 'bar();'}); await waitForBothPaused(); InspectorTest.log('Resuming in 2'); session2.Protocol.Debugger.resume(); await waitForBothResumed(); InspectorTest.log('Evaluating exclusive breakpoint in 1'); session1.Protocol.Runtime.evaluate({expression: 'baz();'}); await waitForBothPaused(); InspectorTest.log('Resuming in 1'); session1.Protocol.Debugger.resume(); await waitForBothResumed(); InspectorTest.log('Evaluating common breakpoint in 2'); session2.Protocol.Runtime.evaluate({expression: 'foo();'}); await waitForBothPaused(); InspectorTest.log('Resuming in 2'); session2.Protocol.Debugger.resume(); await waitForBothResumed(); InspectorTest.log('Evaluating debugger in 2'); session2.Protocol.Runtime.evaluate({expression: 'bar();'}); await waitForBothPaused(); InspectorTest.log('Resuming in 2'); session2.Protocol.Debugger.resume(); await waitForBothResumed(); InspectorTest.log('Evaluating exclusive breakpoint in 2'); session2.Protocol.Runtime.evaluate({expression: 'baz();'}); await waitForBothPaused(); InspectorTest.log('Resuming in 1'); session1.Protocol.Debugger.resume(); await waitForBothResumed(); InspectorTest.log('Evaluating stepping in 1'); session1.Protocol.Runtime.evaluate({expression: 'stepping();'}); await waitForBothPaused(); InspectorTest.log('Stepping into in 2'); session2.Protocol.Debugger.stepInto(); await waitForBothResumed(); await waitForBothPaused(); InspectorTest.log('Stepping over in 1'); session1.Protocol.Debugger.stepOver(); await waitForBothResumed(); await waitForBothPaused(); InspectorTest.log('Stepping out in 2'); session2.Protocol.Debugger.stepOut(); await waitForBothResumed(); await waitForBothPaused(); InspectorTest.log('Resuming in 1'); session1.Protocol.Debugger.resume(); await waitForBothResumed(); InspectorTest.log('Pausing in next statement'); contextGroup.schedulePauseOnNextStatement('some-reason', JSON.stringify({a: 42})); session2.Protocol.Runtime.evaluate({expression: 'var a = 1;'}); await waitForBothPaused(); InspectorTest.log('Resuming in 1'); session1.Protocol.Debugger.resume(); await waitForBothResumed(); InspectorTest.log('Pausing in next statement'); contextGroup.schedulePauseOnNextStatement('some-reason', JSON.stringify({a: 42})); session2.Protocol.Runtime.evaluate({expression: 'var a = 1;'}); await waitForBothPaused(); InspectorTest.log('Resuming in 2'); session2.Protocol.Debugger.resume(); await waitForBothResumed(); InspectorTest.log('Blackboxing bar() in 2'); await session2.Protocol.Debugger.setBlackboxPatterns({patterns: ['test2.js']}); InspectorTest.log('Evaluating bar() in 2'); session2.Protocol.Runtime.evaluate({expression: 'bar();'}); await waitForPaused(session1, 1); InspectorTest.log('Resuming in 1'); session1.Protocol.Debugger.resume(); await waitForResumed(session1, 1); InspectorTest.log('Blackboxing bar() in 1'); await session1.Protocol.Debugger.setBlackboxPatterns({patterns: ['test2.js']}); InspectorTest.log('Evaluating bar() in 2'); await session2.Protocol.Runtime.evaluate({expression: 'bar();'}); InspectorTest.log('Skipping pauses in 1'); await session1.Protocol.Debugger.setSkipAllPauses({skip: true}); InspectorTest.log('Evaluating common breakpoint in 1'); session1.Protocol.Runtime.evaluate({expression: 'foo();'}); await waitForPaused(session2, 2); InspectorTest.log('Resuming in 2'); session2.Protocol.Debugger.resume(); await waitForResumed(session2, 2); InspectorTest.log('Skipping pauses in 2'); await session2.Protocol.Debugger.setSkipAllPauses({skip: true}); InspectorTest.log('Evaluating common breakpoint in 1'); await session1.Protocol.Runtime.evaluate({expression: 'foo();'}); InspectorTest.log('Unskipping pauses in 1'); await session1.Protocol.Debugger.setSkipAllPauses({skip: false}); InspectorTest.log('Unskipping pauses in 2'); await session2.Protocol.Debugger.setSkipAllPauses({skip: false}); InspectorTest.log('Deactivating breakpoints in 1'); await session1.Protocol.Debugger.setBreakpointsActive({active: false}); InspectorTest.log('Evaluating common breakpoint in 1'); session1.Protocol.Runtime.evaluate({expression: 'foo();'}); await waitForPaused(session2, 2); InspectorTest.log('Resuming in 2'); session2.Protocol.Debugger.resume(); await waitForResumed(session2, 2); InspectorTest.log('Deactivating breakpoints in 2'); await session2.Protocol.Debugger.setBreakpointsActive({active: false}); InspectorTest.log('Evaluating common breakpoint in 1'); await session1.Protocol.Runtime.evaluate({expression: 'foo();'}); InspectorTest.log('Activating breakpoints in 1'); await session1.Protocol.Debugger.setBreakpointsActive({active: true}); InspectorTest.log('Activating breakpoints in 2'); await session2.Protocol.Debugger.setBreakpointsActive({active: true}); InspectorTest.log('Disabling debugger agent in 1'); await session1.Protocol.Debugger.disable(); InspectorTest.log('Evaluating breakpoint in 1 (should not be triggered)'); session2.Protocol.Runtime.evaluate({expression: 'baz();\ndebugger;'}); await waitForPaused(session2, 2); InspectorTest.completeTest(); function waitForBothPaused() { return Promise.all([waitForPaused(session1, 1), waitForPaused(session2, 2)]); } function waitForBothResumed() { return Promise.all([waitForResumed(session1, 1), waitForResumed(session2, 2)]); } })(); function waitForPaused(session, num) { return session.Protocol.Debugger.oncePaused().then(message => { InspectorTest.log(`Paused in ${num}:`); InspectorTest.log(` reason: ${message.params.reason}`); InspectorTest.log(` hit breakpoints: ${(message.params.hitBreakpoints || []).join(';')}`); var callFrame = message.params.callFrames[0]; InspectorTest.log(` location: ${callFrame.functionName || '<anonymous>'}@${callFrame.location.lineNumber}`); InspectorTest.log(` data: ${JSON.stringify(message.params.data || null)}`); }); } function waitForResumed(session, num) { return session.Protocol.Debugger.onceResumed().then(message => { InspectorTest.log(`Resumed in ${num}`); }); }
macchina-io/macchina.io
platform/JS/V8/v8/test/inspector/sessions/debugger-stepping-and-breakpoints.js
JavaScript
apache-2.0
8,154
goog.module('grrUi.cron.newCronJobWizard.formDirective'); goog.module.declareLegacyNamespace(); const {DEFAULT_PLUGIN_URL} = goog.require('grrUi.hunt.newHuntWizard.formDirective'); /** * Controller for FormDirective. * * @param {!angular.Scope} $scope * @param {!grrUi.core.reflectionService.ReflectionService} grrReflectionService * @param {!grrUi.core.apiService.ApiService} grrApiService * @constructor * @ngInject */ const FormController = function($scope, grrReflectionService, grrApiService) { /** @private {!angular.Scope} */ this.scope_ = $scope; /** @private {!grrUi.core.reflectionService.ReflectionService} */ this.grrReflectionService_ = grrReflectionService; /** @private {!grrUi.core.apiService.ApiService} */ this.grrApiService_ = grrApiService; /** @private {!Object<string, Object>} */ this.descriptors_ = {}; /** @private {?string} */ this.defaultOutputPluginName; this.grrApiService_.get(DEFAULT_PLUGIN_URL).then(function(response) { if (angular.isDefined(response['data']['value'])) { this.defaultOutputPluginName = response['data']['value']['value']; } return this.grrReflectionService_.getRDFValueDescriptor( 'ApiCreateCronJobArgs', true); }.bind(this)).then(function(descriptors) { angular.extend(this.descriptors_, descriptors); this.scope_.$watch('createCronJobArgs', this.onCronJobCreateArgsChange_.bind(this)); }.bind(this)); // Aliasing hunt runner arguments which are themselves a part of // CreateAndRunGenericHuntFlow args - purely for convenience when // when using it in the template. this.scope_.$watch('createCronJobArgs.value.hunt_runner_args', function(newValue) { this.huntRunnerArgs = newValue; }.bind(this)); this.scope_.$watch('createCronJobArgs.value.description.value', this.onCronJobDescriptionChange_.bind(this)); }; /** * Called when cron job's description changes. Updates hunt's description. * * @param {?string} newValue New value. * @param {?string} oldValue Old value. * @private */ FormController.prototype.onCronJobDescriptionChange_ = function( newValue, oldValue) { if (newValue && this.huntRunnerArgs) { oldValue = oldValue || ''; var huntDescription; if (angular.isDefined(this.huntRunnerArgs.value.description)) { huntDescription = this.huntRunnerArgs.value.description.value; } var cronSuffix = ' (cron)'; if (angular.isUndefined(huntDescription) || huntDescription == oldValue + cronSuffix) { this.huntRunnerArgs.value.description = { type: 'RDFString', value: newValue + cronSuffix }; } } }; /** * Called when 'createCronJobArgs' binding changes. * * @param {Object} newValue New binding value. * @private */ FormController.prototype.onCronJobCreateArgsChange_ = function(newValue) { /** * In order to make forms work, we have to make sure that all the structures * and values, that are going to be edited, are initialized to their * defaults. * TODO(user): This code is clunky and error-prone. Remove the need * to specify ['value'] key every time. Make initialization a standard * routine of grrReflectionService. */ // If cronJob is not initialized, initialize it with default // ApiCronJob value. if (angular.isUndefined(newValue)) { newValue = this.scope_['createCronJobArgs'] = angular.copy(this.descriptors_['ApiCreateCronJobArgs']['default']); } // If periodicity is not set, set it to 7 days. if (angular.isUndefined(newValue['value']['periodicity'])) { newValue['value']['periodicity'] = { type: 'DurationSeconds', value: 60 * 60 * 24 * 7 }; } // If lifetime is not set, set it to 1 hour. if (angular.isUndefined(newValue['value']['lifetime'])) { newValue['value']['lifetime'] = { type: 'DurationSeconds', value: 60 * 60 * 1 }; } // If flow_name is not initialized, initialize it to RDFString default. if (angular.isUndefined(newValue['value']['flow_name'])) { newValue['value']['flow_name'] = angular.copy(this.descriptors_['RDFString']['default']); } // If CreateGenericHuntFlowArgs.hunt_runner_args is not initialized, // initialize it to HuntRunnerArgs default. if (angular.isUndefined(newValue['value']['hunt_runner_args'])) { newValue['value']['hunt_runner_args'] = angular.copy(this.descriptors_['HuntRunnerArgs']['default']); } var huntRunnerArgs = newValue['value']['hunt_runner_args']['value']; // Initialize CreateGenericHuntFlowArgs.hunt_runner_args.client_rule_set if (angular.isUndefined(huntRunnerArgs['client_rule_set'])) { huntRunnerArgs['client_rule_set'] = angular.copy( this.descriptors_['ForemanClientRuleSet']['default']); } // If CreateGenericHuntFlowArgs.hunt_runner_args.output_plugins is // not initialized, initialize it to default output plugins list (if any). if (angular.isUndefined(huntRunnerArgs['output_plugins'])) { if (this.defaultOutputPluginName) { var defaultPluginDescriptor = angular.copy( this.descriptors_['OutputPluginDescriptor']['default']); defaultPluginDescriptor['value']['plugin_name'] = angular.copy( this.descriptors_['RDFString']['default']); defaultPluginDescriptor['value']['plugin_name']['value'] = this.defaultOutputPluginName; huntRunnerArgs['output_plugins'] = [defaultPluginDescriptor]; } else { huntRunnerArgs['output_plugins'] = []; } } }; /** * Sends cron creation request to the server. * * @export */ FormController.prototype.sendRequest = function() { this.grrApiService_.post('/cron-jobs', this.scope_['createCronJobArgs'], true).then( function resolve(response) { this.serverResponse = response; this.scope_['cronJob'] = response['data']; }.bind(this), function reject(response) { this.serverResponse = response; this.serverResponse['error'] = true; }.bind(this)); }; /** * Directive for showing wizard-like forms with multiple named steps/pages. * * @return {!angular.Directive} Directive definition object. * @ngInject * @export */ exports.FormDirective = function() { return { scope: { createCronJobArgs: '=?', cronJob: '=?', onResolve: '&', onReject: '&' }, restrict: 'E', templateUrl: '/static/angular-components/cron/new-cron-job-wizard/' + 'form.html', controller: FormController, controllerAs: 'controller' }; }; /** * Directive's name in Angular. * * @const * @export */ exports.FormDirective.directive_name = 'grrNewCronJobWizardForm';
dunkhong/grr
grr/server/grr_response_server/gui/static/angular-components/cron/new-cron-job-wizard/form-directive.js
JavaScript
apache-2.0
6,793
(function() { function config($stateProvider, $locationProvider) { $locationProvider .html5Mode({ enabled: true, requireBase: false }); $stateProvider .state('landing', { url: '/', controller: 'LandingCtrl as landing', templateUrl: '/templates/landing.html' }) .state('album', { url: '/album', controller: 'AlbumCtrl as album', templateUrl: '/templates/album.html' }) .state('collection', { url: '/collection', controller: 'CollectionCtrl as collection', templateUrl: '/templates/collection.html' }); } angular .module('blocJams', ['ui.router']) .config(config); })();
steefnee/bloc-jams-angular
dist/scripts/app.js
JavaScript
apache-2.0
764
/* * Copyright 2013 Mirantis, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. **/ module.exports = function(grunt) { var pkg = grunt.file.readJSON('package.json'); var staticDir = grunt.option('static-dir') || '/tmp/static_compressed'; grunt.initConfig({ pkg: pkg, requirejs: { compile: { options: { baseUrl: '.', appDir: 'static', dir: staticDir, mainConfigFile: 'static/js/main.js', waitSeconds: 60, optimize: 'uglify2', optimizeCss: 'standard', pragmas: { compressed: true }, map: { '*': { 'css': 'require-css' } }, modules: [ { name: 'js/main', exclude: ['css/normalize'] } ] } } }, jslint: { client: { src: [ 'static/js/**/*.js', '!static/js/libs/**', '!static/js/expression_parser.js' ], directives: { predef: ['requirejs', 'require', 'define', 'app', 'Backbone', '$', '_'], ass: true, browser: true, unparam: true, nomen: true, eqeq: true, vars: true, white: true, es5: false } } }, less: { all: { src: 'static/css/styles.less', dest: 'static/css/styles.css', } }, bower: { install: { options: { //set install to true to load Bower packages from inet install: true, targetDir: 'static/js/libs/bower', verbose: true, cleanTargetDir: false, cleanBowerDir: true, layout: "byComponent", bowerOptions: { production: true, install: '--offline' } } } }, clean: { trim: { expand: true, cwd: staticDir, src: [ '**/*.js', '!js/main.js', '!js/libs/bower/requirejs/js/require.js', '**/*.css', '**/*.less', '!css/styles.css', 'templates', 'i18n' ] }, options: { force: true } }, cleanempty: { trim: { expand: true, cwd: staticDir, src: ['**'] }, options: { files: false, force: true } }, replace: { sha: { src: 'static/index.html', dest: staticDir + '/', replacements: [{ from: '__COMMIT_SHA__', to: function() { return grunt.config.get('meta.revision'); } }] } }, revision: { options: { short: false } }, jison: { target : { src: 'static/config_expression.jison', dest: 'static/js/expression_parser.js', options: { moduleType: 'js' } } } }); Object.keys(pkg.devDependencies) .filter(function(npmTaskName) { return npmTaskName.indexOf('grunt-') === 0; }) .forEach(grunt.loadNpmTasks.bind(grunt)); grunt.registerTask('trimstatic', ['clean', 'cleanempty']); grunt.registerTask('build', ['bower', 'less', 'requirejs', 'trimstatic', 'revision', 'replace']); grunt.registerTask('default', ['build']); grunt.task.loadTasks('grunt'); };
koder-ua/nailgun-fcert
nailgun/Gruntfile.js
JavaScript
apache-2.0
4,971
var _servicio = '../php/servicios/proc-pedidos.php'; var _idPedidoX = 0, _docGenerate = '', _serieUsar = ''; (function($){ var _cboProd = []; var template = Handlebars.compile($("#result-template").html()); var empty = Handlebars.compile($("#empty-template").html()); $(document).ready(function(){ /* -------------------------------------- */ $('#txtProducto').autoComplete({ source: function(term, response){ $.post('../php/servicios/get_prods_lotes.php', { q: term }, function(data){ response(data); },'json'); }, renderItem: function (item, search){ var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi"); var _html = ''; _html += '<div class="autocomplete-suggestion" data-prodi="'+item[0]+'" data-lote="'+item[1]+'" data-val="'+search+'" data-idprod="'+item[5]+'" data-idum="'+item[6]+'" data-precio="'+item[4]+'" data-idlote="'+item[7]+'" >'; _html += item[0].replace(re, "<b>$1</b>")+' Precio <strong>S/. '+item[4]+'</strong>, Stock: '+item[2]+', Lote: '+item[1]+', Vence: '+item[3]; _html += '</div>'; return _html; }, onSelect: function(e, term, item){ $('#idProd').val( item.data('idprod') ); $('#idUM').val( item.data('idum') ); $('#txtPrecio').val( item.data('precio') ); $('#txtProducto').val( item.data('prodi') ); $('#idLote').val( item.data('idlote') ); $('#txtCantidad').focus(); //alert('Item "'+item.data('prodi')+' Lote: '+item.data('lote')+' " selected by '+(e.type == 'keydown' ? 'pressing enter' : 'mouse click')+'.'); e.preventDefault(); } }); /* -------------------------------------- */ _cboCLiente = $('#cboCliente').selectize({ options: _json_clientes, labelField: 'texto', valueField: 'id', }); if( _idCliente > 0 ){ _cboCLiente[0].selectize.setValue(_idCliente); }else{ _cboCLiente[0].selectize.setValue("1"); } /* -------------------------------------- */ $('#txtVence').datepicker({ format: 'dd/mm/yyyy', startDate: '-3d', language : 'es', startView : 'year' }); /* -------------------------------------- */ $('#txtFecha').datepicker({ format: 'dd/mm/yyyy', startDate: '-3d', language : 'es', startView : 'day' }); /* -------------------------------------- */ $('[data-toggle="tooltip"]').tooltip(); /* -------------------------------------- */ $(document).delegate('.copiarPedido', 'click', function(event) { /**/ var _idPedido = $(this).attr('href'); $('#CopiarModal').modal('show'); $.post( _servicio , {f:'copy',idp:_idPedido} , function(data, textStatus, xhr) { $('#CopiarModal').modal('hide'); document.location.reload(); },'json'); event.preventDefault(); /**/ }); /* -------------------------------------- */ $('#addNuevoItem').click(function(event) { resetAddItems(); $('#editorProducto').fadeIn('fast'); $('#txtProducto').focus(); event.preventDefault(); }); /* -------------------------------------- */ $('#cerrarProd').click(function(event) { resetAddItems(); $('#editorProducto').fadeOut('fast'); event.preventDefault(); }); /* -------------------------------------- */ $('#txtCantidad').keypress(function(event) { /* Act on the event */ if( event.keyCode == 13 ){ $('#addProducto').focus(); } }); /* -------------------------------------- */ $('#SavePedido').click(function(event) { /* Act on the event */ var _data = $('#frmData').serialize(); var $btn = $(this).button('loading') $.post( _servicio , _data , function(data, textStatus, xhr) { if( data.error == '' ){ $('#idPedido').val( data.idPedido ); _idPedidoX = data.idPedido; $('#labelidPedido').html( 'Pre venta #'+data.idPedido ); $('#labelPedido').html( '#'+data.idPedido ); alertify.alert('Pre venta generado #'+data.idPedido,function(){ document.location.href = 'nuevo-pedido.php?idpedido='+data.idPedido; }); $('#panelFacturar').show(); } $btn.button('reset'); },'json'); event.preventDefault(); }); /* -------------------------------------- */ $('#NuevoItem').click(function(event) { /* Act on the event */ $('#myModal').modal('show'); $('#myModalLabel').html('Nuevo Pedido'); event.preventDefault(); }); /* -------------------------------------- */ //$('.jChosen').chosen({width: "100%"}); /* -------------------------------------- */ $('#addProducto').click(function(event) { $(this).attr({'disabled':'disabled'}); // var _data = $('#frmEditor').serialize(); // $.post( _servicio , _data , function(data, textStatus, xhr) { $('#addProducto').removeAttr('disabled'); loadTablita(data); resetAddItems(); $('#txtProducto').val(''); $('#txtProducto').focus(); alertify.success('Producto agregado'); },'json'); event.preventDefault(); }); /* -------------------------------------- */ $('#txtPrecio').keyup(function(event) { var _cant = $('#txtCantidad').val(), _precio = $(this).val(); var _total = _cant * _precio; $('#txtTotal').val(_total); }); /* -------------------------------------- */ $('#txtCantidad').keyup(function(event) { var _cant = $(this).val(), _precio = $('#txtPrecio').val(); var _total = _cant * _precio; $('#txtTotal').val(_total); }); /* -------------------------------------- */ $(document).delegate('.quitarProd', 'click', function(event) { /* Quitar un item de la lista y volver a dibujar la tabla. */ var _Nombre = $(this).attr('rel'), _idd = $(this).attr('href'); alertify.confirm('Confirme quitar Item: '+_Nombre,function(e){ if(e){ $.post( _servicio , {f:'delItem',idItem:_idd,'idp':_idPedido} , function(data, textStatus, xhr) { $('#Fila_'+_idd).hide('slow'); loadTablita(data); alertify.error('Producto quitado.'); },'json'); } }); event.preventDefault(); }); /* -------------------------------------- */ $(document).delegate('.ItemLista', 'click', function(event) { /* Agregar un item de la lista y volver a dibujar la tabla. */ var _idp = $(this).attr('href'); $.post( _servicio , { f:'getItem', idp:_idp } , function(data, textStatus, xhr) { LoadItem( data ); },'json'); event.preventDefault(); }); /* -------------------------------------- */ $(document).delegate('.goPedido', 'click', function(event) { var _idp = $(this).attr('href'); $('#myModal').modal('show'); event.preventDefault(); }); /* -------------------------------------- */ $('#btnGoFacturar').click(function(event) { var _filtro = ''; _docGenerate = $('#Documento').val(); _serieUsar = $('#Correlativo').val(); var _idPedido = $('#idPedido').val(); _filtro = 'goBoleta'; /**/ $.post( _servicio , { f:_filtro, idp:_idPedido, 'TipoDoc':_docGenerate, serie:_serieUsar} , function(data, textStatus, xhr) { if( data.idVenta > 0 ){ switch(_docGenerate){ case 'B': document.location.href = 'nueva-boleta.php?id='+data.idVenta; break; case 'F': document.location.href = 'nueva-factura.php?id='+data.idVenta; break; case 'R': document.location.href = 'nuevo-recibo.php?id='+data.idVenta; break; } } },'json'); /**/ event.preventDefault(); }); /* -------------------------------------- */ }); })(jQuery); function LoadItem( json ){ if( json.data != undefined || json.data != null ){ var _html = '', _item = []; for (var i = 0; i < json.data.length; i++) { _item = json.data[0]; $('#txtCantidad').val( _item.int_Cantidad ); //$('#txtProducto').val( _item.var_Nombre+' x '+_item.unidadMedida ); $('#txtPrecio').val( _item.flt_Precio ); $('#txtTotal').val( _item.flt_Total ); // $('#idProd').val( _item.int_IdProducto ); $('#idUM').val( _item.int_IdUnidadMedida ); $('#idItem').val( _item.int_IdDetallePedido ); $('#editorProducto').fadeIn('fast'); }; } } function resetAddItems(){ $('#containerProducto').removeClass().addClass('form-group'); $('#idProd').val('0'); $('#idUM').val('0'); $('#txtPrecio').val( '0' ); $('#txtCantidad').val( '' ); $('#txtTotal').val( '0' ); //$("#txtProducto").val(''); $("#idItem").val('0'); } function loadTablita( json ){ if( json.data != undefined || json.data != null ){ var _fila = [], _html = '', _total = 0; for (var i = 0; i < json.data.length; i++) { _fila = json.data[i]; _html += '<tr id="Fila_'+_fila.int_IdDetallePedido+'" >'; _html += '<td>'; _html += '<span class="fa fa-barcode" ></span> '+_fila.prod+' x '+_fila.um+''; if( _fila.int_IdPromo != null ){ _html += '<br/><small>'+_fila.var_Promo+' antes ('+_fila.flt_Precio+')</small>'; } _html += '</td>'; _html += '<td>'+_fila.lote+'</td>'; if( _fila.int_IdPromo != null ){ _html += '<td class="text-right" >S/. '+_fila.flt_Promo+'</td>'; }else{ _html += '<td class="text-right" >S/. '+_fila.flt_Precio+'</td>'; } _html += '<td class="text-right" >'+_fila.cant+'</td>'; _total = _total + parseFloat(_fila.flt_Total); _html += '<td class="text-right" >'+_fila.flt_Total+'</td>'; _html += '<td>'; _html += '<a href="'+_fila.int_IdDetallePedido+'" class="pull-right quitarProd" rel="'+_fila.prod+'" ><span class="glyphicon glyphicon-remove" ></span></a>'; _html += '</td>'; }; $('#TotalPedido').val( _total ); $('#LabelTotal').html('Total Pre venta: '+_total); $('#Tablita tbody').html( _html ); } } /*Solo Numeros*/ /* onkeypress="return validar(event);" */ function validar(e) { tecla = (document.all)?e.keyCode:e.which;//ascii //alert(tecla); switch(tecla){ case 8: return true; break; case 46://punto return true; break; case 43://Mas return true; break; case 45://Menos return true; break; case 44://Coma return true; break; case 0://Suprimir return true; break; default: break; } patron = /\d/; te = String.fromCharCode(tecla); return patron.test(te); }
dxnydlc/Ziel-Farmacia
dist/js/nuevo-pedido.js
JavaScript
apache-2.0
10,275
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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. --> <script type="text/javascript"> <!-- function s${SEQNUM}_addFieldMapping() { if (editjob.s${SEQNUM}_fieldmapping_source.value == "") { alert("$Encoder.bodyEscape($ResourceBundle.getString('SolrIngester.NoFieldNameSpecified'))"); editjob.s${SEQNUM}_fieldmapping_source.focus(); return; } editjob.s${SEQNUM}_fieldmapping_op.value="Add"; postFormSetAnchor("s${SEQNUM}_fieldmapping"); } function s${SEQNUM}_deleteFieldMapping(i) { // Set the operation eval("editjob.s${SEQNUM}_fieldmapping_op_"+i+".value=\"Delete\""); // Submit if (editjob.s${SEQNUM}_fieldmapping_count.value==i) postFormSetAnchor("s${SEQNUM}_fieldmapping"); else postFormSetAnchor("s${SEQNUM}_fieldmapping_"+i) // Undo, so we won't get two deletes next time eval("editjob.s${SEQNUM}_fieldmapping_op_"+i+".value=\"Continue\""); } //--> </script>
apache/manifoldcf
connectors/solr/connector/src/main/resources/org/apache/manifoldcf/crawler/connectors/solr/editSpecification_job_parameters.js
JavaScript
apache-2.0
1,635
'use strict'; angular.module('friendflixApp') .controller('SocialRegisterController', function ($scope, $filter, $stateParams) { $scope.provider = $stateParams.provider; $scope.providerLabel = $filter('capitalize')($scope.provider); $scope.success = $stateParams.success; $scope.error = !$scope.success; });
bhattsachin/friendflix
projects/src/main/webapp/scripts/app/account/social/social-register.controller.js
JavaScript
apache-2.0
349
/** * Copyright 2020 The AMP HTML Authors. All Rights Reserved. * * 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 {loadScript, validateData} from '#3p/3p'; /** * @param {!Window} global * @param {!Object} data */ export function relappro(global, data) { validateData(data, [], ['slotId', 'nameAdUnit', 'requirements']); global.params = data; loadScript( global, 'https://cdn.relappro.com/adservices/amp/relappro.amp.min.js' ); }
rsimha-amp/amphtml
ads/vendors/relappro.js
JavaScript
apache-2.0
972
CKEDITOR.plugins.setLang("image2","it",{alt:"Testo alternativo",btnUpload:"Invia al server",captioned:"Captioned image",infoTab:"Informazioni immagine",lockRatio:"Blocca rapporto",menu:"Proprietà immagine",pathName:"image",pathNameCaption:"caption",resetSize:"Reimposta dimensione",resizer:"Click and drag to resize",title:"Proprietà immagine",uploadTab:"Carica",urlMissing:"Manca l'URL dell'immagine."});
viticm/pfadmin
vendor/frozennode/administrator/public/js/ckeditor/plugins/image2/lang/it.js
JavaScript
apache-2.0
407
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ var isThisGoodResolution; var oldSelectedTab; /* flagActiveTab valid values * MEM_R_GRAPH_DEF, * MEM_TREE_MAP_DEF, MEM_TREE_MAP_SG, MEM_TREE_MAP_RZ, DATA_TREE_MAP_DEF, * MEM_GRID_DEF, MEM_GRID_SG, MEM_GRID_RZ, DATA_GRID_DEF */ var flagActiveTab = ""; var currentActiveNotificationTab = "ALL"; // valid values 'ALL', 'SEVERE', 'ERROR', 'WARNING' var currentActivePerspective = "MEMBER"; // valid values 'MEMBER', 'DATA' var hotspotAttributes = []; // For Hotspot var currentHotspotAttribiute = null; // For Hotspot function checkMedia() { $('.scroll-pane').jScrollPane();/* * custom scroll bar on body load for 1st tab */ $('.scroll-pane_1').jScrollPane(); $('.pointGridData').jScrollPane(); $('.regionMembersSearchBlock').jScrollPane(); $('.ui-jqgrid-bdiv').jScrollPane(); if (document.getElementById('canvasWidth') != null) { var winW, winH; if (document.body && document.body.offsetWidth) { winW = document.body.offsetWidth; winH = document.body.offsetHeight; } if (document.compatMode == 'CSS1Compat' && document.documentElement && document.documentElement.offsetWidth) { winW = document.documentElement.offsetWidth; winH = document.documentElement.offsetHeight; } if (window.innerWidth && window.innerHeight) { winW = window.innerWidth; winH = window.innerHeight; } document.getElementById('canvasWidth').style.width = "1258px"; // alert('Weight: ' + winW ); // alert('Height: ' + winH ); if (winW <= 1024) { document.getElementById('canvasWidth').style.width = "1002px"; // document.getElementById("overLapLinkBlock").style.display = // 'none'; /* onload hide first top tab block */ $('#TopTab_All').hide(); $('#btnTopTab_All').removeClass('TopTabLinkActive'); isThisGoodResolution = false; } else { document.getElementById('canvasWidth').style.width = "1258px"; isThisGoodResolution = true; // document.getElementById("overLapLinkBlock").style.display = // 'block'; } } } /* Version Details Popup handler */ $(document).ready(function() { // popHandler handles the display of pop up window on click event on link function popupHandler(e) { // Cancel the link behavior e.preventDefault(); // Get the A tag var id = $(this).attr('href'); // Get the screen height and width var maskHeight = $(document).height(); var maskWidth = $(window).width(); // Set height and width to mask to fill up the whole screen $('#mask').css({ 'width' : maskWidth, 'height' : maskHeight }); // transition effect $('#mask').fadeIn(1000); $('#mask').fadeTo("fast", 0.8); // Get the window height and width var winH = $(window).height(); var winW = $(window).width(); // Set the popup window to center $(id).css('top', winH / 2 - $(id).height() / 2); $(id).css('left', winW / 2 - $(id).width() / 2); // transition effect $(id).fadeIn(1500); } // end of popupHandler // Add popupHandler on click of version details link $('[id=pulseVersionDetailsLink]').click(popupHandler); // if close button is clicked $('.window .closePopup').click(function(e) { // Cancel the link behavior e.preventDefault(); $('#mask').hide(); $('.window').hide(); }); // if input close button is clicked $('.window .closePopupInputButton').click(function(e) { // Cancel the link behavior e.preventDefault(); $('#mask').hide(); $('.window').hide(); }); // if mask is clicked $('#mask').click(function() { $(this).hide(); $('.window').hide(); }); }); /* About Dropdown */ $(document).ready(function() { $(".aboutClicked-Off").click(function(e) { e.preventDefault(); $("div#detailsAbout").toggle(); $(".aboutClicked-Off").toggleClass("aboutClicked-On"); }); $("div#detailsAbout").mouseup(function() { return false; }); $(document).mouseup(function(e) { if ($(e.target).parent("a.aboutClicked-Off").length == 0) { $(".aboutClicked-Off").removeClass("aboutClicked-On"); $("div#detailsAbout").hide(); } }); }); /* Members name Dropdown */ $(document).ready(function() { $(".memberClicked-Off").click(function(e) { e.preventDefault(); $("div#setting").toggle(); $(".memberClicked-Off").toggleClass("memberClicked-On"); $('.jsonSuggestScrollFilter').jScrollPane(); }); $("div#setting").mouseup(function() { return false; }); $(document).mouseup(function(e) { if ($(e.target).parent("a.memberClicked-Off").length == 0) { $(".memberClicked-Off").removeClass("memberClicked-On"); $("div#setting").hide(); } }); /* on off switch */ $('#membersButton').addClass('switchActive'); $('#switchLinks').show(); $("#membersButton").click(function(e) { $('#membersButton').addClass('switchActive'); $('#dataButton').removeClass('switchActive'); $('#switchLinks').show(); }); $("#dataButton").click(function(e) { $('#membersButton').removeClass('switchActive'); $('#dataButton').addClass('switchActive'); $('#switchLinks').hide(); }); }); /* show block function */ function showDiv(divSelected) { $('#' + divSelected).show(); } /* hide block function */ function hideDiv(divSelected) { $('#' + divSelected).hide(); } /* Toggle Top Tab */ function toggleTab(divSelected) { /* * $(document).mouseup(function(e) { $('#'+divSelected).hide(); }); */ if (!isThisGoodResolution) { $('#' + divSelected).toggle(); $('.scroll-pane').jScrollPane(); if (oldSelectedTab == divSelected) { $('#' + 'btn' + oldSelectedTab).removeClass('TopTabLinkActive'); oldSelectedTab = ""; } else { oldSelectedTab = divSelected; } } } /* toggle block function */ function toggleDiv(divSelected) { $('#' + divSelected).toggle(); if ($('#' + 'btn' + divSelected).hasClass('minusIcon')) { $('#' + 'btn' + divSelected).addClass('plusIcon'); $('#' + 'btn' + divSelected).removeClass('minusIcon'); } else { $('#' + 'btn' + divSelected).addClass('minusIcon'); $('#' + 'btn' + divSelected).removeClass('plusIcon'); } } /*---Accordion-----*/ function accordion() { $('.accordion .heading').prepend('<span class="spriteArrow"></span>'); $('.accordion .heading').click( function() { var accordionId = $(this).parent().parent().attr('id'); accordionId = ('#' + accordionId); if ($(this).is('.inactive')) { $(accordionId + ' .active').toggleClass('active').toggleClass( 'inactive').next().slideToggle(); $(this).toggleClass('active').toggleClass('inactive'); $(this).next().slideToggle(); $(this).next().find('.n-heading').removeClass('n-active'); $(this).next().find('.n-heading').addClass('n-inactive'); $(this).next().find('.n-accordion-content').hide(); } else { $(this).toggleClass('active').toggleClass('inactive'); $(this).next().slideToggle(); } /* custom scroll bar */ $('.ScrollPaneBlock').jScrollPane(); }); // onload keep open $('.accordion .heading').not('.active').addClass('inactive'); $('.accordion .heading.active').next().show(); } /*---Accordion Nested-----*/ function accordionNested() { $('.accordionNested .n-heading').prepend( '<span class="n-spriteArrow"></span>'); $('.accordionNested .n-heading').click( function() { /* Custom scroll */ var accordionIdNested = $(this).parent().parent().attr('id'); accordionIdNested = ('#' + accordionIdNested); if ($(this).is('.n-inactive')) { $(accordionIdNested + ' .n-active').toggleClass('n-active') .toggleClass('n-inactive').next().slideToggle(); $(this).toggleClass('n-active').toggleClass('n-inactive'); $(this).next().slideToggle(); /* Custom scroll */ $('.ui-jqgrid-bdiv').jScrollPane(); } else { $(this).toggleClass('n-active').toggleClass('n-inactive'); $(this).next().slideToggle(); } }); // onload keep open $('.accordionNested .n-heading').not('.n-active').addClass('n-inactive'); $('.accordionNested .n-heading.n-active').next().show(); /* Custom scroll */ $('.ui-jqgrid-bdiv').jScrollPane(); } /* show panel */ function tabGridNew(parentId) { $('#gridBlocks_Panel').hide(); destroyScrollPane(parentId); $('#gridBlocks_Panel').show(); $('#chartBlocks_Panel').hide(); $('#graphBlocks_Panel').hide(); /* Custom scroll */ $('.ui-jqgrid-bdiv').each(function(index) { var tempName = $(this).parent().attr('id'); if (tempName == parentId) { $(this).jScrollPane({maintainPosition : true, stickToRight : true}); } }); $('#btngridIcon').addClass('gridIconActive'); $('#btngridIcon').removeClass('gridIcon'); $('#btnchartIcon').addClass('chartIcon'); $('#btnchartIcon').removeClass('chartIconActive'); $('#btngraphIcon').addClass('graphIcon'); $('#btngraphIcon').removeClass('graphIconActive'); } function tabChart() { $('#gridBlocks_Panel').hide(); $('#chartBlocks_Panel').show(); $('#graphBlocks_Panel').hide(); $('#btngridIcon').addClass('gridIcon'); $('#btngridIcon').removeClass('gridIconActive'); $('#btnchartIcon').addClass('chartIconActive'); $('#btnchartIcon').removeClass('chartIcon'); $('#btngraphIcon').addClass('graphIcon'); $('#btngraphIcon').removeClass('graphIconActive'); } /* Top tab Panel */ function tabAll() { // update currentActiveNotificationTab value currentActiveNotificationTab = "ALL"; if (isThisGoodResolution) { $('#TopTab_All').show(); } $('#TopTab_Error').hide(); $('#TopTab_Warning').hide(); $('#TopTab_Severe').hide(); $('#btnTopTab_All').addClass('TopTabLinkActive'); $('#btnTopTab_Error').removeClass('TopTabLinkActive'); $('#btnTopTab_Warning').removeClass('TopTabLinkActive'); $('#btnTopTab_Severe').removeClass('TopTabLinkActive'); $('.scroll-pane').jScrollPane(); } function tabError() { // update currentActiveNotificationTab value currentActiveNotificationTab = "ERROR"; $('#TopTab_All').hide(); if (isThisGoodResolution) { $('#TopTab_Error').show(); } $('#TopTab_Warning').hide(); $('#TopTab_Severe').hide(); $('#btnTopTab_All').removeClass('TopTabLinkActive'); $('#btnTopTab_Error').addClass('TopTabLinkActive'); $('#btnTopTab_Warning').removeClass('TopTabLinkActive'); $('#btnTopTab_Severe').removeClass('TopTabLinkActive'); $('.scroll-pane').jScrollPane(); } function tabWarning() { // update currentActiveNotificationTab value currentActiveNotificationTab = "WARNING"; $('#TopTab_All').hide(); $('#TopTab_Error').hide(); if (isThisGoodResolution) { $('#TopTab_Warning').show(); } $('#TopTab_Severe').hide(); $('#btnTopTab_All').removeClass('TopTabLinkActive'); $('#btnTopTab_Error').removeClass('TopTabLinkActive'); $('#btnTopTab_Warning').addClass('TopTabLinkActive'); $('#btnTopTab_Severe').removeClass('TopTabLinkActive'); $('.scroll-pane').jScrollPane(); } function tabSevere() { // update currentActiveNotificationTab value currentActiveNotificationTab = "SEVERE"; $('#TopTab_All').hide(); $('#TopTab_Error').hide(); $('#TopTab_Warning').hide(); if (isThisGoodResolution) { $('#TopTab_Severe').show(); } $('#btnTopTab_All').removeClass('TopTabLinkActive'); $('#btnTopTab_Error').removeClass('TopTabLinkActive'); $('#btnTopTab_Warning').removeClass('TopTabLinkActive'); $('#btnTopTab_Severe').addClass('TopTabLinkActive'); $('.scroll-pane').jScrollPane(); } /* Auto Complete box */ /** * function used for opening Cluster View */ function openClusterDetail() { location.href = 'clusterDetail.html'; } /** * function used for opening Data View */ function openDataView() { location.href = 'dataView.html'; } /** * function used for opening Data Browser */ function openDataBrowser() { location.href = 'dataBrowser.html'; } /** * function used for opening Query statistics */ function openQueryStatistics() { location.href = 'queryStatistics.html'; } function destroyScrollPane(scrollPaneParentId) { $('.ui-jqgrid-bdiv').each(function(index) { var tempName = $(this).parent().attr('id'); if (tempName == scrollPaneParentId) { var api = $(this).data('jsp'); api.destroy(); } }); } //Initial set up for hotspot drop down function initHotspotDropDown() { var htmlHotSpotList = generateHotSpotListHTML(hotspotAttributes); // Set list height if(hotspotAttributes.length <= 5){ $("#hotspotListContainer").height(hotspotAttributes.length * 26); }else{ $("#hotspotListContainer").height(5 * 26); } $('#hotspotList').html(htmlHotSpotList); $('.jsonSuggestScrollFilter').jScrollPane(); currentHotspotAttribiute = hotspotAttributes[0].id; $('#currentHotSpot').html(hotspotAttributes[0].name); // Hot Spot List event handlers $(".hotspotClicked-Off").click(function(e) { e.preventDefault(); $("div#hotspotSetting").toggle(); $(".hotspotClicked-Off").toggleClass("hotspotClicked-On"); $('.jsonSuggestScrollFilter').jScrollPane(); }); $("div#hotspotSetting").mouseup(function() { return false; }); $(document).mouseup(function(e) { if ($(e.target).parent("a.hotspotClicked-Off").length == 0) { $(".hotspotClicked-Off").removeClass("hotspotClicked-On"); $("div#hotspotSetting").hide(); } }); } //Function to be called on when Hot Spot selection changes function onHotspotChange(element) { if (element != currentHotspotAttribiute) { for ( var cnt = 0; cnt < hotspotAttributes.length; cnt++) { if (element == hotspotAttributes[cnt].id) { currentHotspotAttribiute = hotspotAttributes[cnt].id; $('#currentHotSpot').html(hotspotAttributes[cnt].name); applyHotspot(); } } } // Hide drop down $(".hotspotClicked-Off").removeClass("hotspotClicked-On"); $("div#hotspotSetting").hide(); } //Function to generate HTML for Hot Spot list drop down function generateHotSpotListHTML(hotspotAttributes) { var htmlHotSpotList = ''; for ( var i = 0; i < hotspotAttributes.length; i++) { htmlHotSpotList += '<div class="resultItemFilter">' + '<a href="#" onclick="onHotspotChange(\'' + hotspotAttributes[i].id + '\');" >' + hotspotAttributes[i].name + '</a></div>'; } return htmlHotSpotList; } //Merged 3102 from 702X_maint function destroyScrollPane(scrollPaneParentId) { $('.ui-jqgrid-bdiv').each(function(index) { var tempName = $(this).parent().attr('id'); if (tempName == scrollPaneParentId) { var api = $(this).data('jsp'); api.destroy(); } }); }
jdeppe-pivotal/geode
geode-pulse/src/main/webapp/scripts/lib/common.js
JavaScript
apache-2.0
15,450
'use strict'; (function (scope) { /** * Bar input component * * @class MusicBarInputComponent * @extends AbstractMusicInputComponent * @constructor */ function MusicBarInputComponent() { this.type = 'bar'; this.value = new scope.MusicBarInput(); } /** * Inheritance property */ MusicBarInputComponent.prototype = new scope.AbstractMusicInputComponent(); /** * Constructor property */ MusicBarInputComponent.prototype.constructor = MusicBarInputComponent; /** * Get bar input component value * * @method getValue * @returns {MusicBarInput} */ MusicBarInputComponent.prototype.getValue = function () { return this.value; }; /** * Set bar input component value * * @method setValue * @param {MusicBarInput} value */ MusicBarInputComponent.prototype.setValue = function (value) { this.value = value; }; // Export scope.MusicBarInputComponent = MusicBarInputComponent; })(MyScript);
countshadow/MyScriptJS
src/input/music/components/musicBarInputComponent.js
JavaScript
apache-2.0
1,075
Cufon.replace('h2, .font2, h3, .call1', { fontFamily: 'Molengo', hover:true }); Cufon.replace('#menu a, #slogan, .font1, .call2', { fontFamily: 'Expletus Sans', hover:true }); Cufon.replace('.date', { fontFamily: 'Expletus Sans', hover:true, color: '-linear-gradient(#747474, #595959, #383838)' });
peter-watters/WebPortfolio
officialfootballaccumulators/js/lib/cufon-replace.js
JavaScript
apache-2.0
300
function buildDistanceInWordsLocale () { var distanceInWordsLocale = { lessThanXSeconds: { one: '1秒以下', other: '{{count}}秒以下' }, xSeconds: { one: '1秒', other: '{{count}}秒' }, halfAMinute: '30秒ぐらい', lessThanXMinutes: { one: '1分以下', other: '{{count}}分以下' }, xMinutes: { one: '1分', other: '{{count}}分' }, aboutXHours: { one: '1時間ぐらい', other: '{{count}}時間ぐらい' }, xHours: { one: '1時間', other: '{{count}}時間' }, xDays: { one: '1日', other: '{{count}}日' }, aboutXMonths: { one: '1ヶ月ぐらい', other: '{{count}}ヶ月ぐらい' }, xMonths: { one: '1ヶ月', other: '{{count}}ヶ月' }, aboutXYears: { one: '1年ぐらい', other: '{{count}}年ぐらい' }, xYears: { one: '1年', other: '{{count}}年' }, overXYears: { one: '1年以上', other: '{{count}}年以上' }, almostXYears: { one: '1年以下', other: '{{count}}年以下', oneWithSuffix: '1年ぐらい', otherWithSuffix: '{{count}}年ぐらい' } } function localize (token, count, options) { options = options || {} var result if (typeof distanceInWordsLocale[token] === 'string') { result = distanceInWordsLocale[token] } else if (count === 1) { if (options.addSuffix && distanceInWordsLocale[token].oneWithSuffix) { result = distanceInWordsLocale[token].oneWithSuffix } else { result = distanceInWordsLocale[token].one } } else { if (options.addSuffix && distanceInWordsLocale[token].otherWithSuffix) { result = distanceInWordsLocale[token].otherWithSuffix.replace('{{count}}', count) } else { result = distanceInWordsLocale[token].other.replace('{{count}}', count) } } if (options.addSuffix) { if (options.comparison > 0) { return result + '後' } else { return result + '前' } } return result } return { localize: localize } } module.exports = buildDistanceInWordsLocale
simhawk/simhawk.github.io
node_modules/date-fns/locale/ja/build_distance_in_words_locale/index.js
JavaScript
apache-2.0
2,260
/* Copyright (c) Lightstreamer Srl Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * Module DataProvider export. * * @ignore */ exports.DataProvider = require('./dataprovider').DataProvider; /** * Module MetadataProvider export. * * @ignore */ exports.MetadataProvider = require('./metadataprovider').MetadataProvider;
Weswit/Lightstreamer-lib-node-adapter
lib/lightstreamer-adapter.js
JavaScript
apache-2.0
842
exports.definition = { config: { adapter: { type: "properties", collection_name: "loggedInUser" } }, extendModel: function(Model) { _.extend(Model.prototype, { /** * Backbone의 경우 idAttribute는 model에 extend를 통해 바로 넣는다. * Alloy의 경우 adapter에 넣고 adapter가 model에 넣어준다. * 그런데 properties 아답터는 model에 idAttribute를 넣는 코드가 없다. (3.2.0.GA) * */ idAttribute : 'bogoyoLoggedInUser', defaults :{ bogoyoLoggedInUser : 'staticId' }, clearWithoutId : function(options) { this.clear(); return this.set('bogoyoLoggedInUser','staticId'); }, getProfileImageUrl : function(){ return String.format("https://graph.facebook.com/%s/picture?width=%d&height=%d", this.get('external_accounts')[0].external_id, 80, 80); } // extended functions and properties go here }); return Model; }, extendCollection: function(Collection) { _.extend(Collection.prototype, { // extended functions and properties go here }); return Collection; } };
yoda-united/licky
app/models/loggedInUser.js
JavaScript
apache-2.0
1,118
sap.ui.define(['sap/ui/core/UIComponent'], function(UIComponent) { "use strict"; var Component = UIComponent.extend("sap.m.sample.ListDeletion.Component", { metadata : { rootView : { "viewName": "sap.m.sample.ListDeletion.List", "type": "XML", "async": true }, dependencies : { libs : [ "sap.m", "sap.ui.layout" ] }, config : { sample : { files : [ "List.view.xml", "List.controller.js" ] } } } }); return Component; });
SQCLabs/openui5
src/sap.m/test/sap/m/demokit/sample/ListDeletion/Component.js
JavaScript
apache-2.0
513
/** vim: et:ts=4:sw=4:sts=4 * @license RequireJS 2.1.5 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ //Not using strict: uneven strict support in browsers, #392, and causes //problems with requirejs.exec()/transpiler plugins that may not be strict. /*jslint regexp: true, nomen: true, sloppy: true */ /*global window, navigator, document, importScripts, setTimeout, opera */ var requirejs, require, define; (function (global) { var req, s, head, baseElement, dataMain, src, interactiveScript, currentlyAddingScript, mainScript, subPath, version = '2.1.5', commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, jsSuffixRegExp = /\.js$/, currDirRegExp = /^\.\//, op = Object.prototype, ostring = op.toString, hasOwn = op.hasOwnProperty, ap = Array.prototype, apsp = ap.splice, isBrowser = !!(typeof window !== 'undefined' && navigator && document), isWebWorker = !isBrowser && typeof importScripts !== 'undefined', //PS3 indicates loaded and complete, but need to wait for complete //specifically. Sequence is 'loading', 'loaded', execution, // then 'complete'. The UA check is unfortunate, but not sure how //to feature test w/o causing perf issues. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? /^complete$/ : /^(complete|loaded)$/, defContextName = '_', //Oh the tragedy, detecting opera. See the usage of isOpera for reason. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', contexts = {}, cfg = {}, globalDefQueue = [], useInteractive = false; function isFunction(it) { return ostring.call(it) === '[object Function]'; } function isArray(it) { return ostring.call(it) === '[object Array]'; } /** * Helper function for iterating over an array. If the func returns * a true value, it will break out of the loop. */ function each(ary, func) { if (ary) { var i; for (i = 0; i < ary.length; i += 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } } /** * Helper function for iterating over an array backwards. If the func * returns a true value, it will break out of the loop. */ function eachReverse(ary, func) { if (ary) { var i; for (i = ary.length - 1; i > -1; i -= 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } } function hasProp(obj, prop) { return hasOwn.call(obj, prop); } function getOwn(obj, prop) { return hasProp(obj, prop) && obj[prop]; } /** * Cycles over properties in an object and calls a function for each * property value. If the function returns a truthy value, then the * iteration is stopped. */ function eachProp(obj, func) { var prop; for (prop in obj) { if (hasProp(obj, prop)) { if (func(obj[prop], prop)) { break; } } } } /** * Simple function to mix in properties from source into target, * but only if target does not already have a property of the same name. */ function mixin(target, source, force, deepStringMixin) { if (source) { eachProp(source, function (value, prop) { if (force || !hasProp(target, prop)) { if (deepStringMixin && typeof value !== 'string') { if (!target[prop]) { target[prop] = {}; } mixin(target[prop], value, force, deepStringMixin); } else { target[prop] = value; } } }); } return target; } //Similar to Function.prototype.bind, but the 'this' object is specified //first, since it is easier to read/figure out what 'this' will be. function bind(obj, fn) { return function () { return fn.apply(obj, arguments); }; } function scripts() { return document.getElementsByTagName('script'); } //Allow getting a global that expressed in //dot notation, like 'a.b.c'. function getGlobal(value) { if (!value) { return value; } var g = global; each(value.split('.'), function (part) { g = g[part]; }); return g; } /** * Constructs an error with a pointer to an URL with more information. * @param {String} id the error ID that maps to an ID on a web page. * @param {String} message human readable error. * @param {Error} [err] the original error, if there is one. * * @returns {Error} */ function makeError(id, msg, err, requireModules) { var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); e.requireType = id; e.requireModules = requireModules; if (err) { e.originalError = err; } return e; } if (typeof define !== 'undefined') { //If a define is already in play via another AMD loader, //do not overwrite. return; } if (typeof requirejs !== 'undefined') { if (isFunction(requirejs)) { //Do not overwrite and existing requirejs instance. return; } cfg = requirejs; requirejs = undefined; } //Allow for a require config object if (typeof require !== 'undefined' && !isFunction(require)) { //assume it is a config object. cfg = require; require = undefined; } function newContext(contextName) { var inCheckLoaded, Module, context, handlers, checkLoadedTimeoutId, config = { //Defaults. Do not set a default for map //config to speed up normalize(), which //will run faster if there is no default. waitSeconds: 7, baseUrl: './', paths: {}, pkgs: {}, shim: {}, config: {} }, registry = {}, //registry of just enabled modules, to speed //cycle breaking code when lots of modules //are registered, but not activated. enabledRegistry = {}, undefEvents = {}, defQueue = [], defined = {}, urlFetched = {}, requireCounter = 1, unnormalizedCounter = 1; /** * Trims the . and .. from an array of path segments. * It will keep a leading path segment if a .. will become * the first path segment, to help with module name lookups, * which act like paths, but can be remapped. But the end result, * all paths that use this function should look normalized. * NOTE: this method MODIFIES the input array. * @param {Array} ary the array of path segments. */ function trimDots(ary) { var i, part; for (i = 0; ary[i]; i += 1) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @param {Boolean} applyMap apply the map config to the value. Should * only be done if this normalization is for a dependency ID. * @returns {String} normalized name */ function normalize(name, baseName, applyMap) { var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment, foundMap, foundI, foundStarMap, starI, baseParts = baseName && baseName.split('/'), normalizedBaseParts = baseParts, map = config.map, starMap = map && map['*']; //Adjust any relative paths. if (name && name.charAt(0) === '.') { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { if (getOwn(config.pkgs, baseName)) { //If the baseName is a package name, then just treat it as one //name to concat the name with. normalizedBaseParts = baseParts = [baseName]; } else { //Convert baseName to array, and lop off the last part, //so that . matches that 'directory' and not name of the baseName's //module. For instance, baseName of 'one/two/three', maps to //'one/two/three.js', but we want the directory, 'one/two' for //this normalization. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); } name = normalizedBaseParts.concat(name.split('/')); trimDots(name); //Some use of packages may use a . path to reference the //'main' module name, so normalize for that. pkgConfig = getOwn(config.pkgs, (pkgName = name[0])); name = name.join('/'); if (pkgConfig && name === pkgName + '/' + pkgConfig.main) { name = pkgName; } } else if (name.indexOf('./') === 0) { // No baseName, so this is ID is resolved relative // to baseUrl, pull off the leading dot. name = name.substring(2); } } //Apply map config if available. if (applyMap && map && (baseParts || starMap)) { nameParts = name.split('/'); for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join('/'); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = getOwn(map, baseParts.slice(0, j).join('/')); //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = getOwn(mapValue, nameSegment); if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break; } } } } if (foundMap) { break; } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { foundStarMap = getOwn(starMap, nameSegment); starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } return name; } function removeScript(name) { if (isBrowser) { each(scripts(), function (scriptNode) { if (scriptNode.getAttribute('data-requiremodule') === name && scriptNode.getAttribute('data-requirecontext') === context.contextName) { scriptNode.parentNode.removeChild(scriptNode); return true; } }); } } function hasPathFallback(id) { var pathConfig = getOwn(config.paths, id); if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { removeScript(id); //Pop off the first array value, since it failed, and //retry pathConfig.shift(); context.require.undef(id); context.require([id]); return true; } } //Turns a plugin!resource to [plugin, resource] //with the plugin being undefined if the name //did not have a plugin prefix. function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; } /** * Creates a module mapping that includes plugin prefix, module * name, and path. If parentModuleMap is provided it will * also normalize the name via require.normalize() * * @param {String} name the module name * @param {String} [parentModuleMap] parent module map * for the module name, used to resolve relative names. * @param {Boolean} isNormalized: is the ID already normalized. * This is true if this call is done for a define() module ID. * @param {Boolean} applyMap: apply the map config to the ID. * Should only be true if this map is for a dependency. * * @returns {Object} */ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { var url, pluginModule, suffix, nameParts, prefix = null, parentName = parentModuleMap ? parentModuleMap.name : null, originalName = name, isDefine = true, normalizedName = ''; //If no name, then it means it is a require call, generate an //internal name. if (!name) { isDefine = false; name = '_@r' + (requireCounter += 1); } nameParts = splitPrefix(name); prefix = nameParts[0]; name = nameParts[1]; if (prefix) { prefix = normalize(prefix, parentName, applyMap); pluginModule = getOwn(defined, prefix); } //Account for relative paths if there is a base name. if (name) { if (prefix) { if (pluginModule && pluginModule.normalize) { //Plugin is loaded, use its normalize method. normalizedName = pluginModule.normalize(name, function (name) { return normalize(name, parentName, applyMap); }); } else { normalizedName = normalize(name, parentName, applyMap); } } else { //A regular module. normalizedName = normalize(name, parentName, applyMap); //Normalized name may be a plugin ID due to map config //application in normalize. The map config values must //already be normalized, so do not need to redo that part. nameParts = splitPrefix(normalizedName); prefix = nameParts[0]; normalizedName = nameParts[1]; isNormalized = true; url = context.nameToUrl(normalizedName); } } //If the id is a plugin id that cannot be determined if it needs //normalization, stamp it with a unique ID so two matching relative //ids that may conflict can be separate. suffix = prefix && !pluginModule && !isNormalized ? '_unnormalized' + (unnormalizedCounter += 1) : ''; return { prefix: prefix, name: normalizedName, parentMap: parentModuleMap, unnormalized: !!suffix, url: url, originalName: originalName, isDefine: isDefine, id: (prefix ? prefix + '!' + normalizedName : normalizedName) + suffix }; } function getModule(depMap) { var id = depMap.id, mod = getOwn(registry, id); if (!mod) { mod = registry[id] = new context.Module(depMap); } return mod; } function on(depMap, name, fn) { var id = depMap.id, mod = getOwn(registry, id); if (hasProp(defined, id) && (!mod || mod.defineEmitComplete)) { if (name === 'defined') { fn(defined[id]); } } else { getModule(depMap).on(name, fn); } } function onError(err, errback) { var ids = err.requireModules, notified = false; if (errback) { errback(err); } else { each(ids, function (id) { var mod = getOwn(registry, id); if (mod) { //Set error on module, so it skips timeout checks. mod.error = err; if (mod.events.error) { notified = true; mod.emit('error', err); } } }); if (!notified) { req.onError(err); } } } /** * Internal method to transfer globalQueue items to this context's * defQueue. */ function takeGlobalQueue() { //Push all the globalDefQueue items into the context's defQueue if (globalDefQueue.length) { //Array splice in the values since the context code has a //local var ref to defQueue, so cannot just reassign the one //on context. apsp.apply(defQueue, [defQueue.length - 1, 0].concat(globalDefQueue)); globalDefQueue = []; } } handlers = { 'require': function (mod) { if (mod.require) { return mod.require; } else { return (mod.require = context.makeRequire(mod.map)); } }, 'exports': function (mod) { mod.usingExports = true; if (mod.map.isDefine) { if (mod.exports) { return mod.exports; } else { return (mod.exports = defined[mod.map.id] = {}); } } }, 'module': function (mod) { if (mod.module) { return mod.module; } else { return (mod.module = { id: mod.map.id, uri: mod.map.url, config: function () { return (config.config && getOwn(config.config, mod.map.id)) || {}; }, exports: defined[mod.map.id] }); } } }; function cleanRegistry(id) { //Clean up machinery used for waiting modules. delete registry[id]; delete enabledRegistry[id]; } function breakCycle(mod, traced, processed) { var id = mod.map.id; if (mod.error) { mod.emit('error', mod.error); } else { traced[id] = true; each(mod.depMaps, function (depMap, i) { var depId = depMap.id, dep = getOwn(registry, depId); //Only force things that have not completed //being defined, so still in the registry, //and only if it has not been matched up //in the module already. if (dep && !mod.depMatched[i] && !processed[depId]) { if (getOwn(traced, depId)) { mod.defineDep(i, defined[depId]); mod.check(); //pass false? } else { breakCycle(dep, traced, processed); } } }); processed[id] = true; } } function checkLoaded() { var map, modId, err, usingPathFallback, waitInterval = config.waitSeconds * 1000, //It is possible to disable the wait interval by using waitSeconds of 0. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), noLoads = [], reqCalls = [], stillLoading = false, needCycleCheck = true; //Do not bother if this call was a result of a cycle break. if (inCheckLoaded) { return; } inCheckLoaded = true; //Figure out the state of all the modules. eachProp(enabledRegistry, function (mod) { map = mod.map; modId = map.id; //Skip things that are not enabled or in error state. if (!mod.enabled) { return; } if (!map.isDefine) { reqCalls.push(mod); } if (!mod.error) { //If the module should be executed, and it has not //been inited and time is up, remember it. if (!mod.inited && expired) { if (hasPathFallback(modId)) { usingPathFallback = true; stillLoading = true; } else { noLoads.push(modId); removeScript(modId); } } else if (!mod.inited && mod.fetched && map.isDefine) { stillLoading = true; if (!map.prefix) { //No reason to keep looking for unfinished //loading. If the only stillLoading is a //plugin resource though, keep going, //because it may be that a plugin resource //is waiting on a non-plugin cycle. return (needCycleCheck = false); } } } }); if (expired && noLoads.length) { //If wait time expired, throw error of unloaded modules. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); err.contextName = context.contextName; return onError(err); } //Not expired, check for a cycle. if (needCycleCheck) { each(reqCalls, function (mod) { breakCycle(mod, {}, {}); }); } //If still waiting on loads, and the waiting load is something //other than a plugin resource, or there are still outstanding //scripts, then just try back later. if ((!expired || usingPathFallback) && stillLoading) { //Something is still waiting to load. Wait for it, but only //if a timeout is not already in effect. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { checkLoadedTimeoutId = setTimeout(function () { checkLoadedTimeoutId = 0; checkLoaded(); }, 50); } } inCheckLoaded = false; } Module = function (map) { this.events = getOwn(undefEvents, map.id) || {}; this.map = map; this.shim = getOwn(config.shim, map.id); this.depExports = []; this.depMaps = []; this.depMatched = []; this.pluginMaps = {}; this.depCount = 0; /* this.exports this.factory this.depMaps = [], this.enabled, this.fetched */ }; Module.prototype = { init: function (depMaps, factory, errback, options) { options = options || {}; //Do not do more inits if already done. Can happen if there //are multiple define calls for the same module. That is not //a normal, common case, but it is also not unexpected. if (this.inited) { return; } this.factory = factory; if (errback) { //Register for errors on this module. this.on('error', errback); } else if (this.events.error) { //If no errback already, but there are error listeners //on this module, set up an errback to pass to the deps. errback = bind(this, function (err) { this.emit('error', err); }); } //Do a copy of the dependency array, so that //source inputs are not modified. For example //"shim" deps are passed in here directly, and //doing a direct modification of the depMaps array //would affect that config. this.depMaps = depMaps && depMaps.slice(0); this.errback = errback; //Indicate this module has be initialized this.inited = true; this.ignore = options.ignore; //Could have option to init this module in enabled mode, //or could have been previously marked as enabled. However, //the dependencies are not known until init is called. So //if enabled previously, now trigger dependencies as enabled. if (options.enabled || this.enabled) { //Enable this module and dependencies. //Will call this.check() this.enable(); } else { this.check(); } }, defineDep: function (i, depExports) { //Because of cycles, defined callback for a given //export can be called more than once. if (!this.depMatched[i]) { this.depMatched[i] = true; this.depCount -= 1; this.depExports[i] = depExports; } }, fetch: function () { if (this.fetched) { return; } this.fetched = true; context.startTime = (new Date()).getTime(); var map = this.map; //If the manager is for a plugin managed resource, //ask the plugin to load it now. if (this.shim) { context.makeRequire(this.map, { enableBuildCallback: true })(this.shim.deps || [], bind(this, function () { return map.prefix ? this.callPlugin() : this.load(); })); } else { //Regular dependency. return map.prefix ? this.callPlugin() : this.load(); } }, load: function () { var url = this.map.url; //Regular dependency. if (!urlFetched[url]) { urlFetched[url] = true; context.load(this.map.id, url); } }, /** * Checks if the module is ready to define itself, and if so, * define it. */ check: function () { if (!this.enabled || this.enabling) { return; } var err, cjsModule, id = this.map.id, depExports = this.depExports, exports = this.exports, factory = this.factory; if (!this.inited) { this.fetch(); } else if (this.error) { this.emit('error', this.error); } else if (!this.defining) { //The factory could trigger another require call //that would result in checking this module to //define itself again. If already in the process //of doing that, skip this work. this.defining = true; if (this.depCount < 1 && !this.defined) { if (isFunction(factory)) { //If there is an error listener, favor passing //to that instead of throwing an error. if (this.events.error) { try { exports = context.execCb(id, factory, depExports, exports); } catch (e) { err = e; } } else { exports = context.execCb(id, factory, depExports, exports); } if (this.map.isDefine) { //If setting exports via 'module' is in play, //favor that over return value and exports. After that, //favor a non-undefined return value over exports use. cjsModule = this.module; if (cjsModule && cjsModule.exports !== undefined && //Make sure it is not already the exports value cjsModule.exports !== this.exports) { exports = cjsModule.exports; } else if (exports === undefined && this.usingExports) { //exports already set the defined value. exports = this.exports; } } if (err) { err.requireMap = this.map; err.requireModules = [this.map.id]; err.requireType = 'define'; return onError((this.error = err)); } } else { //Just a literal value exports = factory; } this.exports = exports; if (this.map.isDefine && !this.ignore) { defined[id] = exports; if (req.onResourceLoad) { req.onResourceLoad(context, this.map, this.depMaps); } } //Clean up cleanRegistry(id); this.defined = true; } //Finished the define stage. Allow calling check again //to allow define notifications below in the case of a //cycle. this.defining = false; if (this.defined && !this.defineEmitted) { this.defineEmitted = true; this.emit('defined', this.exports); this.defineEmitComplete = true; } } }, callPlugin: function () { var map = this.map, id = map.id, //Map already normalized the prefix. pluginMap = makeModuleMap(map.prefix); //Mark this as a dependency for this plugin, so it //can be traced for cycles. this.depMaps.push(pluginMap); on(pluginMap, 'defined', bind(this, function (plugin) { var load, normalizedMap, normalizedMod, name = this.map.name, parentName = this.map.parentMap ? this.map.parentMap.name : null, localRequire = context.makeRequire(map.parentMap, { enableBuildCallback: true }); //If current map is not normalized, wait for that //normalized name to load instead of continuing. if (this.map.unnormalized) { //Normalize the ID if the plugin allows it. if (plugin.normalize) { name = plugin.normalize(name, function (name) { return normalize(name, parentName, true); }) || ''; } //prefix and name should already be normalized, no need //for applying map config again either. normalizedMap = makeModuleMap(map.prefix + '!' + name, this.map.parentMap); on(normalizedMap, 'defined', bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true, ignore: true }); })); normalizedMod = getOwn(registry, normalizedMap.id); if (normalizedMod) { //Mark this as a dependency for this plugin, so it //can be traced for cycles. this.depMaps.push(normalizedMap); if (this.events.error) { normalizedMod.on('error', bind(this, function (err) { this.emit('error', err); })); } normalizedMod.enable(); } return; } load = bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true }); }); load.error = bind(this, function (err) { this.inited = true; this.error = err; err.requireModules = [id]; //Remove temp unnormalized modules for this module, //since they will never be resolved otherwise now. eachProp(registry, function (mod) { if (mod.map.id.indexOf(id + '_unnormalized') === 0) { cleanRegistry(mod.map.id); } }); onError(err); }); //Allow plugins to load other code without having to know the //context or how to 'complete' the load. load.fromText = bind(this, function (text, textAlt) { /*jslint evil: true */ var moduleName = map.name, moduleMap = makeModuleMap(moduleName), hasInteractive = useInteractive; //As of 2.1.0, support just passing the text, to reinforce //fromText only being called once per resource. Still //support old style of passing moduleName but discard //that moduleName in favor of the internal ref. if (textAlt) { text = textAlt; } //Turn off interactive script matching for IE for any define //calls in the text, then turn it back on at the end. if (hasInteractive) { useInteractive = false; } //Prime the system by creating a module instance for //it. getModule(moduleMap); //Transfer any config to this other module. if (hasProp(config.config, id)) { config.config[moduleName] = config.config[id]; } try { req.exec(text); } catch (e) { return onError(makeError('fromtexteval', 'fromText eval for ' + id + ' failed: ' + e, e, [id])); } if (hasInteractive) { useInteractive = true; } //Mark this as a dependency for the plugin //resource this.depMaps.push(moduleMap); //Support anonymous modules. context.completeLoad(moduleName); //Bind the value of that module to the value for this //resource ID. localRequire([moduleName], load); }); //Use parentName here since the plugin's name is not reliable, //could be some weird string with no path that actually wants to //reference the parentName's path. plugin.load(map.name, localRequire, load, config); })); context.enable(pluginMap, this); this.pluginMaps[pluginMap.id] = pluginMap; }, enable: function () { enabledRegistry[this.map.id] = this; this.enabled = true; //Set flag mentioning that the module is enabling, //so that immediate calls to the defined callbacks //for dependencies do not trigger inadvertent load //with the depCount still being zero. this.enabling = true; //Enable each dependency each(this.depMaps, bind(this, function (depMap, i) { var id, mod, handler; if (typeof depMap === 'string') { //Dependency needs to be converted to a depMap //and wired up to this module. depMap = makeModuleMap(depMap, (this.map.isDefine ? this.map : this.map.parentMap), false, !this.skipMap); this.depMaps[i] = depMap; handler = getOwn(handlers, depMap.id); if (handler) { this.depExports[i] = handler(this); return; } this.depCount += 1; on(depMap, 'defined', bind(this, function (depExports) { this.defineDep(i, depExports); this.check(); })); if (this.errback) { on(depMap, 'error', this.errback); } } id = depMap.id; mod = registry[id]; //Skip special modules like 'require', 'exports', 'module' //Also, don't call enable if it is already enabled, //important in circular dependency cases. if (!hasProp(handlers, id) && mod && !mod.enabled) { context.enable(depMap, this); } })); //Enable each plugin that is used in //a dependency eachProp(this.pluginMaps, bind(this, function (pluginMap) { var mod = getOwn(registry, pluginMap.id); if (mod && !mod.enabled) { context.enable(pluginMap, this); } })); this.enabling = false; this.check(); }, on: function (name, cb) { var cbs = this.events[name]; if (!cbs) { cbs = this.events[name] = []; } cbs.push(cb); }, emit: function (name, evt) { each(this.events[name], function (cb) { cb(evt); }); if (name === 'error') { //Now that the error handler was triggered, remove //the listeners, since this broken Module instance //can stay around for a while in the registry. delete this.events[name]; } } }; function callGetModule(args) { //Skip modules already defined. if (!hasProp(defined, args[0])) { getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); } } function removeListener(node, func, name, ieName) { //Favor detachEvent because of IE9 //issue, see attachEvent/addEventListener comment elsewhere //in this file. if (node.detachEvent && !isOpera) { //Probably IE. If not it will throw an error, which will be //useful to know. if (ieName) { node.detachEvent(ieName, func); } } else { node.removeEventListener(name, func, false); } } /** * Given an event from a script node, get the requirejs info from it, * and then removes the event listeners on the node. * @param {Event} evt * @returns {Object} */ function getScriptData(evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. var node = evt.currentTarget || evt.srcElement; //Remove the listeners once here. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); removeListener(node, context.onScriptError, 'error'); return { node: node, id: node && node.getAttribute('data-requiremodule') }; } function intakeDefines() { var args; //Any defined modules in the global queue, intake them now. takeGlobalQueue(); //Make sure any remaining defQueue items get properly processed. while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); } else { //args are id, deps, factory. Should be normalized by the //define() function. callGetModule(args); } } } context = { config: config, contextName: contextName, registry: registry, defined: defined, urlFetched: urlFetched, defQueue: defQueue, Module: Module, makeModuleMap: makeModuleMap, nextTick: req.nextTick, onError: onError, /** * Set a configuration for the context. * @param {Object} cfg config object to integrate. */ configure: function (cfg) { //Make sure the baseUrl ends in a slash. if (cfg.baseUrl) { if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { cfg.baseUrl += '/'; } } //Save off the paths and packages since they require special processing, //they are additive. var pkgs = config.pkgs, shim = config.shim, objs = { paths: true, config: true, map: true }; eachProp(cfg, function (value, prop) { if (objs[prop]) { if (prop === 'map') { if (!config.map) { config.map = {}; } mixin(config[prop], value, true, true); } else { mixin(config[prop], value, true); } } else { config[prop] = value; } }); //Merge shim if (cfg.shim) { eachProp(cfg.shim, function (value, id) { //Normalize the structure if (isArray(value)) { value = { deps: value }; } if ((value.exports || value.init) && !value.exportsFn) { value.exportsFn = context.makeShimExports(value); } shim[id] = value; }); config.shim = shim; } //Adjust packages if necessary. if (cfg.packages) { each(cfg.packages, function (pkgObj) { var location; pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; location = pkgObj.location; //Create a brand new object on pkgs, since currentPackages can //be passed in again, and config.pkgs is the internal transformed //state for all package configs. pkgs[pkgObj.name] = { name: pkgObj.name, location: location || pkgObj.name, //Remove leading dot in main, so main paths are normalized, //and remove any trailing .js, since different package //envs have different conventions: some use a module name, //some use a file name. main: (pkgObj.main || 'main') .replace(currDirRegExp, '') .replace(jsSuffixRegExp, '') }; }); //Done with modifications, assing packages back to context config config.pkgs = pkgs; } //If there are any "waiting to execute" modules in the registry, //update the maps for them, since their info, like URLs to load, //may have changed. eachProp(registry, function (mod, id) { //If module already has init called, since it is too //late to modify them, and ignore unnormalized ones //since they are transient. if (!mod.inited && !mod.map.unnormalized) { mod.map = makeModuleMap(id); } }); //If a deps array or a config callback is specified, then call //require with those args. This is useful when require is defined as a //config object before require.js is loaded. if (cfg.deps || cfg.callback) { context.require(cfg.deps || [], cfg.callback); } }, makeShimExports: function (value) { function fn() { var ret; if (value.init) { ret = value.init.apply(global, arguments); } return ret || (value.exports && getGlobal(value.exports)); } return fn; }, makeRequire: function (relMap, options) { options = options || {}; function localRequire(deps, callback, errback) { var id, map, requireMod; if (options.enableBuildCallback && callback && isFunction(callback)) { callback.__requireJsBuild = true; } if (typeof deps === 'string') { if (isFunction(callback)) { //Invalid call return onError(makeError('requireargs', 'Invalid require call'), errback); } //If require|exports|module are requested, get the //value for them from the special handlers. Caveat: //this only works while module is being defined. if (relMap && hasProp(handlers, deps)) { return handlers[deps](registry[relMap.id]); } //Synchronous access to one module. If require.get is //available (as in the Node adapter), prefer that. if (req.get) { return req.get(context, deps, relMap, localRequire); } //Normalize module name, if it contains . or .. map = makeModuleMap(deps, relMap, false, true); id = map.id; if (!hasProp(defined, id)) { return onError(makeError('notloaded', 'Module name "' + id + '" has not been loaded yet for context: ' + contextName + (relMap ? '' : '. Use require([])'))); } return defined[id]; } //Grab defines waiting in the global queue. intakeDefines(); //Mark all the dependencies as needing to be loaded. context.nextTick(function () { //Some defines could have been added since the //require call, collect them. intakeDefines(); requireMod = getModule(makeModuleMap(null, relMap)); //Store if map config should be applied to this require //call for dependencies. requireMod.skipMap = options.skipMap; requireMod.init(deps, callback, errback, { enabled: true }); checkLoaded(); }); return localRequire; } mixin(localRequire, { isBrowser: isBrowser, /** * Converts a module name + .extension into an URL path. * *Requires* the use of a module name. It does not support using * plain URLs like nameToUrl. */ toUrl: function (moduleNamePlusExt) { var ext, index = moduleNamePlusExt.lastIndexOf('.'), segment = moduleNamePlusExt.split('/')[0], isRelative = segment === '.' || segment === '..'; //Have a file extension alias, and it is not the //dots from a relative path. if (index !== -1 && (!isRelative || index > 1)) { ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); moduleNamePlusExt = moduleNamePlusExt.substring(0, index); } return context.nameToUrl(normalize(moduleNamePlusExt, relMap && relMap.id, true), ext, true); }, defined: function (id) { return hasProp(defined, makeModuleMap(id, relMap, false, true).id); }, specified: function (id) { id = makeModuleMap(id, relMap, false, true).id; return hasProp(defined, id) || hasProp(registry, id); } }); //Only allow undef on top level require calls if (!relMap) { localRequire.undef = function (id) { //Bind any waiting define() calls to this context, //fix for #408 takeGlobalQueue(); var map = makeModuleMap(id, relMap, true), mod = getOwn(registry, id); delete defined[id]; delete urlFetched[map.url]; delete undefEvents[id]; if (mod) { //Hold on to listeners in case the //module will be attempted to be reloaded //using a different config. if (mod.events.defined) { undefEvents[id] = mod.events; } cleanRegistry(id); } }; } return localRequire; }, /** * Called to enable a module if it is still in the registry * awaiting enablement. A second arg, parent, the parent module, * is passed in for context, when this method is overriden by * the optimizer. Not shown here to keep code compact. */ enable: function (depMap) { var mod = getOwn(registry, depMap.id); if (mod) { getModule(depMap).enable(); } }, /** * Internal method used by environment adapters to complete a load event. * A load event could be a script load or just a load pass from a synchronous * load call. * @param {String} moduleName the name of the module to potentially complete. */ completeLoad: function (moduleName) { var found, args, mod, shim = getOwn(config.shim, moduleName) || {}, shExports = shim.exports; takeGlobalQueue(); while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { args[0] = moduleName; //If already found an anonymous module and bound it //to this name, then this is some other anon module //waiting for its completeLoad to fire. if (found) { break; } found = true; } else if (args[0] === moduleName) { //Found matching define call for this script! found = true; } callGetModule(args); } //Do this after the cycle of callGetModule in case the result //of those calls/init calls changes the registry. mod = getOwn(registry, moduleName); if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { if (hasPathFallback(moduleName)) { return; } else { return onError(makeError('nodefine', 'No define call for ' + moduleName, null, [moduleName])); } } else { //A script that does not call define(), so just simulate //the call for it. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); } } checkLoaded(); }, /** * Converts a module name to a file path. Supports cases where * moduleName may actually be just an URL. * Note that it **does not** call normalize on the moduleName, * it is assumed to have already been normalized. This is an * internal API, not a public one. Use toUrl for the public API. */ nameToUrl: function (moduleName, ext, skipExt) { var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url, parentPath; //If a colon is in the URL, it indicates a protocol is used and it is just //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) //or ends with .js, then assume the user meant to use an url and not a module id. //The slash is important for protocol-less URLs as well as full paths. if (req.jsExtRegExp.test(moduleName)) { //Just a plain path, not module name lookup, so just return it. //Add extension if it is included. This is a bit wonky, only non-.js things pass //an extension, this method probably needs to be reworked. url = moduleName + (ext || ''); } else { //A module that needs to be converted to a path. paths = config.paths; pkgs = config.pkgs; syms = moduleName.split('/'); //For each module name segment, see if there is a path //registered for it. Start with most specific name //and work up from it. for (i = syms.length; i > 0; i -= 1) { parentModule = syms.slice(0, i).join('/'); pkg = getOwn(pkgs, parentModule); parentPath = getOwn(paths, parentModule); if (parentPath) { //If an array, it means there are a few choices, //Choose the one that is desired if (isArray(parentPath)) { parentPath = parentPath[0]; } syms.splice(0, i, parentPath); break; } else if (pkg) { //If module name is just the package name, then looking //for the main module. if (moduleName === pkg.name) { pkgPath = pkg.location + '/' + pkg.main; } else { pkgPath = pkg.location; } syms.splice(0, i, pkgPath); break; } } //Join the path parts together, then figure out if baseUrl is needed. url = syms.join('/'); url += (ext || (/\?/.test(url) || skipExt ? '' : '.js')); url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; } return config.urlArgs ? url + ((url.indexOf('?') === -1 ? '?' : '&') + config.urlArgs) : url; }, //Delegates to req.load. Broken out as a separate function to //allow overriding in the optimizer. load: function (id, url) { req.load(context, id, url); }, /** * Executes a module callack function. Broken out as a separate function * solely to allow the build system to sequence the files in the built * layer in the right sequence. * * @private */ execCb: function (name, callback, args, exports) { return callback.apply(exports, args); }, /** * callback for script loads, used to check status of loading. * * @param {Event} evt the event from the browser for the script * that was loaded. */ onScriptLoad: function (evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. if (evt.type === 'load' || (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { //Reset interactive script so a script node is not held onto for //to long. interactiveScript = null; //Pull out the name of the module and the context. var data = getScriptData(evt); context.completeLoad(data.id); } }, /** * Callback for script errors. */ onScriptError: function (evt) { var data = getScriptData(evt); if (!hasPathFallback(data.id)) { return onError(makeError('scripterror', 'Script error', evt, [data.id])); } } }; context.require = context.makeRequire(); return context; } /** * Main entry point. * * If the only argument to require is a string, then the module that * is represented by that string is fetched for the appropriate context. * * If the first argument is an array, then it will be treated as an array * of dependency string names to fetch. An optional function callback can * be specified to execute when all of those dependencies are available. * * Make a local req variable to help Caja compliance (it assumes things * on a require that are not standardized), and to give a short * name for minification/local scope use. */ req = requirejs = function (deps, callback, errback, optional) { //Find the right context, use default var context, config, contextName = defContextName; // Determine if have config object in the call. if (!isArray(deps) && typeof deps !== 'string') { // deps is a config object config = deps; if (isArray(callback)) { // Adjust args if there are dependencies deps = callback; callback = errback; errback = optional; } else { deps = []; } } if (config && config.context) { contextName = config.context; } context = getOwn(contexts, contextName); if (!context) { context = contexts[contextName] = req.s.newContext(contextName); } if (config) { context.configure(config); } return context.require(deps, callback, errback); }; /** * Support require.config() to make it easier to cooperate with other * AMD loaders on globally agreed names. */ req.config = function (config) { return req(config); }; /** * Execute something after the current tick * of the event loop. Override for other envs * that have a better solution than setTimeout. * @param {Function} fn function to execute later. */ req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { setTimeout(fn, 4); } : function (fn) { fn(); }; /** * Export require as a global, but only if it does not already exist. */ if (!require) { require = req; } req.version = version; //Used to filter out dependencies that are already paths. req.jsExtRegExp = /^\/|:|\?|\.js$/; req.isBrowser = isBrowser; s = req.s = { contexts: contexts, newContext: newContext }; //Create default context. req({}); //Exports some context-sensitive methods on global require. each([ 'toUrl', 'undef', 'defined', 'specified' ], function (prop) { //Reference from contexts instead of early binding to default context, //so that during builds, the latest instance of the default context //with its config gets used. req[prop] = function () { var ctx = contexts[defContextName]; return ctx.require[prop].apply(ctx, arguments); }; }); if (isBrowser) { head = s.head = document.getElementsByTagName('head')[0]; //If BASE tag is in play, using appendChild is a problem for IE6. //When that browser dies, this can be removed. Details in this jQuery bug: //http://dev.jquery.com/ticket/2709 baseElement = document.getElementsByTagName('base')[0]; if (baseElement) { head = s.head = baseElement.parentNode; } } /** * Any errors that require explicitly generates will be passed to this * function. Intercept/override it if you want custom error handling. * @param {Error} err the error object. */ req.onError = function (err) { throw err; }; /** * Does the request to load a module for the browser case. * Make this a separate function to allow other environments * to override it. * * @param {Object} context the require context to find state. * @param {String} moduleName the name of the module. * @param {Object} url the URL to the module. */ req.load = function (context, moduleName, url) { var config = (context && context.config) || {}, node; if (isBrowser) { //In the browser so use a script tag node = config.xhtml ? document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : document.createElement('script'); node.type = config.scriptType || 'text/javascript'; node.charset = 'utf-8'; node.async = true; node.setAttribute('data-requirecontext', context.contextName); node.setAttribute('data-requiremodule', moduleName); //Set up load listener. Test attachEvent first because IE9 has //a subtle issue in its addEventListener and script onload firings //that do not match the behavior of all other browsers with //addEventListener support, which fire the onload event for a //script right after the script execution. See: //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution //UNFORTUNATELY Opera implements attachEvent but does not follow the script //script execution mode. if (node.attachEvent && //Check if node.attachEvent is artificially added by custom script or //natively supported by browser //read https://github.com/jrburke/requirejs/issues/187 //if we can NOT find [native code] then it must NOT natively supported. //in IE8, node.attachEvent does not have toString() //Note the test for "[native code" with no closing brace, see: //https://github.com/jrburke/requirejs/issues/273 !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera) { //Probably IE. IE (at least 6-8) do not fire //script onload right after executing the script, so //we cannot tie the anonymous define call to a name. //However, IE reports the script as being in 'interactive' //readyState at the time of the define call. useInteractive = true; node.attachEvent('onreadystatechange', context.onScriptLoad); //It would be great to add an error handler here to catch //404s in IE9+. However, onreadystatechange will fire before //the error handler, so that does not help. If addEventListener //is used, then IE will fire error before load, but we cannot //use that pathway given the connect.microsoft.com issue //mentioned above about not doing the 'script execute, //then fire the script load event listener before execute //next script' that other browsers do. //Best hope: IE10 fixes the issues, //and then destroys all installs of IE 6-9. //node.attachEvent('onerror', context.onScriptError); } else { node.addEventListener('load', context.onScriptLoad, false); node.addEventListener('error', context.onScriptError, false); } node.src = url; //For some cache cases in IE 6-8, the script executes before the end //of the appendChild execution, so to tie an anonymous define //call to the module name (which is stored on the node), hold on //to a reference to this node, but clear after the DOM insertion. currentlyAddingScript = node; if (baseElement) { head.insertBefore(node, baseElement); } else { head.appendChild(node); } currentlyAddingScript = null; return node; } else if (isWebWorker) { try { //In a web worker, use importScripts. This is not a very //efficient use of importScripts, importScripts will block until //its script is downloaded and evaluated. However, if web workers //are in play, the expectation that a build has been done so that //only one script needs to be loaded anyway. This may need to be //reevaluated if other use cases become common. importScripts(url); //Account for anonymous modules context.completeLoad(moduleName); } catch (e) { context.onError(makeError('importscripts', 'importScripts failed for ' + moduleName + ' at ' + url, e, [moduleName])); } } }; function getInteractiveScript() { if (interactiveScript && interactiveScript.readyState === 'interactive') { return interactiveScript; } eachReverse(scripts(), function (script) { if (script.readyState === 'interactive') { return (interactiveScript = script); } }); return interactiveScript; } //Look for a data-main script attribute, which could also adjust the baseUrl. if (isBrowser) { //Figure out baseUrl. Get it from the script tag with require.js in it. eachReverse(scripts(), function (script) { //Set the 'head' where we can append children by //using the script's parent. if (!head) { head = script.parentNode; } //Look for a data-main attribute to set main script for the page //to load. If it is there, the path to data main becomes the //baseUrl, if it is not already set. dataMain = script.getAttribute('data-main'); if (dataMain) { //Set final baseUrl if there is not already an explicit one. if (!cfg.baseUrl) { //Pull off the directory of data-main for use as the //baseUrl. src = dataMain.split('/'); mainScript = src.pop(); subPath = src.length ? src.join('/') + '/' : './'; cfg.baseUrl = subPath; dataMain = mainScript; } //Strip off any trailing .js since dataMain is now //like a module name. dataMain = dataMain.replace(jsSuffixRegExp, ''); //Put the data-main script in the files to load. cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain]; return true; } }); } /** * The function that handles definitions of modules. Differs from * require() in that a string for the module should be the first argument, * and the function to execute after dependencies are loaded should * return a value to define the module corresponding to the first argument's * name. */ define = function (name, deps, callback) { var node, context; //Allow for anonymous modules if (typeof name !== 'string') { //Adjust args appropriately callback = deps; deps = name; name = null; } //This module may not have dependencies if (!isArray(deps)) { callback = deps; deps = []; } //If no name, and callback is a function, then figure out if it a //CommonJS thing with dependencies. if (!deps.length && isFunction(callback)) { //Remove comments from the callback string, //look for require calls, and pull them into the dependencies, //but only if there are function args. if (callback.length) { callback .toString() .replace(commentRegExp, '') .replace(cjsRequireRegExp, function (match, dep) { deps.push(dep); }); //May be a CommonJS thing even without require calls, but still //could use exports, and module. Avoid doing exports and module //work though if it just needs require. //REQUIRES the function to expect the CommonJS variables in the //order listed below. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); } } //If in IE 6-8 and hit an anonymous define() call, do the interactive //work. if (useInteractive) { node = currentlyAddingScript || getInteractiveScript(); if (node) { if (!name) { name = node.getAttribute('data-requiremodule'); } context = contexts[node.getAttribute('data-requirecontext')]; } } //Always save off evaluating the def call until the script onload handler. //This allows multiple modules to be in a file without prematurely //tracing dependencies, and allows for anonymous module support, //where the module name is not known until the script onload event //occurs. If no context, use the global queue, and get it processed //in the onscript load callback. (context ? context.defQueue : globalDefQueue).push([name, deps, callback]); }; define.amd = { jQuery: true }; /** * Executes the text. Normally just uses eval, but can be modified * to use a better, environment-specific call. Only used for transpiling * loader plugins, not for plain JS modules. * @param {String} text the text to execute/evaluate. */ req.exec = function (text) { /*jslint evil: true */ return eval(text); }; //Set up with config info. req(cfg); }(this));
splendidcode/angular-spring-mvc
src/main/webapp/ui/lib/require.js
JavaScript
apache-2.0
59,237
sap.ui.define([ "jquery.sap.global", "unitTests/utils/loggerInterceptor" ], function ($, loggerInterceptor) { "use strict"; // Opa5 needs to be unloaded because we want to intercept the logger jQuery.sap.unloadResources("sap/ui/test/Opa5.js", false, true, true); // Opa has a config inside remembering state jQuery.sap.unloadResources("sap/ui/test/Opa.js", false, true, true); // all modules that save Opa5 inside their closure and modify it need to be unlaoded too! jQuery.sap.unloadResources("sap/ui/test/opaQunit.js", false, true, true); var oLogger = loggerInterceptor.loadAndIntercept("sap.ui.test.Opa5")[2]; var Opa5 = sap.ui.test.Opa5; var Opa = sap.ui.test.Opa; QUnit.module("Logging", { beforeEach: function () { var sView = [ '<core:View xmlns:core="sap.ui.core" xmlns="sap.ui.commons">', '<Button id="foo">', '</Button>', '<Button id="bar">', '</Button>', '<Button id="baz">', '</Button>', '<Image id="boo"></Image>', '</core:View>' ].join(''); this.oView = sap.ui.xmlview({id: "myViewWithAb", viewContent : sView }); this.oView.setViewName("bar"); this.oView.placeAt("qunit-fixture"); sap.ui.getCore().applyChanges(); var that = this; this.waitForStub = sinon.stub(Opa.prototype, "waitFor", function (oOptions) { that.check = function () { oOptions.check.apply(this, oOptions); }.bind(this); }); this.debugSpy = sinon.spy(oLogger, "debug"); }, afterEach: function () { this.waitForStub.restore(); this.debugSpy.restore(); this.oView.destroy(); } }); QUnit.test("Should log if a control is not found inside a view", function(assert) { // Arrange new Opa5().waitFor({ viewName: "bar", id: "notExistingId" }); // Act this.check(); // Assert sinon.assert.calledWith(this.debugSpy, "Found no control with ID 'notExistingId' in view 'bar'"); }); QUnit.test("Should log if a view is not found", function(assert) { // Arrange new Opa5().waitFor({ viewName: "notExistingView" }); // Act this.check(); // Assert sinon.assert.calledWith(this.debugSpy, "Found no view with the name: 'notExistingView'"); }); });
cschuff/openui5
src/sap.ui.core/test/sap/ui/core/qunit/opa/opa5TestFiles/logging.js
JavaScript
apache-2.0
2,175
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const msRest = require('ms-rest'); const msRestAzure = require('ms-rest-azure'); const WebResource = msRest.WebResource; /** * Result of the request to list REST API operations * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback - The callback. * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link ProviderOperationResult} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ function _list(options, callback) { /* jshint validthis: true */ let client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') { throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.'); } if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL let baseUrl = this.client.baseUri; let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'providers/Microsoft.LabServices/operations'; let queryParameters = []; queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion)); if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects let httpRequest = new WebResource(); httpRequest.method = 'GET'; httpRequest.url = requestUrl; httpRequest.headers = {}; // Set Headers httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(let headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.body = null; // Send Request return client.pipeline(httpRequest, (err, response, responseBody) => { if (err) { return callback(err); } let statusCode = response.statusCode; if (statusCode !== 200) { let error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; let parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { let resultMapper = new client.models['CloudError']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` + `- "${responseBody}" for the default response.`; return callback(error); } return callback(error); } // Create Result let result = null; if (responseBody === '') responseBody = null; // Deserialize Response if (statusCode === 200) { let parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { let resultMapper = new client.models['ProviderOperationResult']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } } return callback(null, result, httpRequest, response); }); } /** * Result of the request to list REST API operations * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback - The callback. * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link ProviderOperationResult} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ function _listNext(nextPageLink, options, callback) { /* jshint validthis: true */ let client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (nextPageLink === null || nextPageLink === undefined || typeof nextPageLink.valueOf() !== 'string') { throw new Error('nextPageLink cannot be null or undefined and it must be of type string.'); } if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL let requestUrl = '{nextLink}'; requestUrl = requestUrl.replace('{nextLink}', nextPageLink); // Create HTTP transport objects let httpRequest = new WebResource(); httpRequest.method = 'GET'; httpRequest.url = requestUrl; httpRequest.headers = {}; // Set Headers httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(let headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.body = null; // Send Request return client.pipeline(httpRequest, (err, response, responseBody) => { if (err) { return callback(err); } let statusCode = response.statusCode; if (statusCode !== 200) { let error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; let parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { let resultMapper = new client.models['CloudError']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` + `- "${responseBody}" for the default response.`; return callback(error); } return callback(error); } // Create Result let result = null; if (responseBody === '') responseBody = null; // Deserialize Response if (statusCode === 200) { let parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { let resultMapper = new client.models['ProviderOperationResult']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } } return callback(null, result, httpRequest, response); }); } /** Class representing a ProviderOperations. */ class ProviderOperations { /** * Create a ProviderOperations. * @param {ManagedLabsClient} client Reference to the service client. */ constructor(client) { this.client = client; this._list = _list; this._listNext = _listNext; } /** * Result of the request to list REST API operations * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProviderOperationResult>} - The deserialized result object. * * @reject {Error} - The error object. */ listWithHttpOperationResponse(options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._list(options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Result of the request to list REST API operations * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {ProviderOperationResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link ProviderOperationResult} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ list(options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._list(options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._list(options, optionalCallback); } } /** * Result of the request to list REST API operations * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProviderOperationResult>} - The deserialized result object. * * @reject {Error} - The error object. */ listNextWithHttpOperationResponse(nextPageLink, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listNext(nextPageLink, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Result of the request to list REST API operations * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {ProviderOperationResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link ProviderOperationResult} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listNext(nextPageLink, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listNext(nextPageLink, options, optionalCallback); } } } module.exports = ProviderOperations;
xingwu1/azure-sdk-for-node
lib/services/labservicesManagement/lib/operations/providerOperations.js
JavaScript
apache-2.0
16,725
define(() => { function postLoad(ipy, editor, savewidget, events) { function navigateAlternate(alt) { var url = document.location.href.replace('/edit', alt); if (url.includes("?")) { url = url.slice(0, url.lastIndexOf("?")); } url = url + '?download=true'; if (!editor.clean) { editor.save().then(function() { window.open(url); }); } else { window.open(url); } } $('#saveButton').click(function() { editor.save(); }) $('#renameButton').click(function() { new savewidget.SaveWidget('span#save_widget', { editor: editor, events: events }).rename(); }) $('#downloadButton').click(function() { navigateAlternate('/files'); }) } return { postLoad: postLoad }; });
googledatalab/datalab
sources/web/datalab/static/edit-app.js
JavaScript
apache-2.0
816
/** * findRoutingRule - find applicable routing rule from bucket metadata * @param {RoutingRule []} routingRules - array of routingRule objects * @param {string} key - object key * @param {number} [errCode] - error code to match if applicable * @return {object | undefined} redirectInfo -- comprised of all of the * keys/values from routingRule.getRedirect() plus * a key of prefixFromRule and a value of routingRule.condition.keyPrefixEquals */ export function findRoutingRule(routingRules, key, errCode) { if (!routingRules || routingRules.length === 0) { return undefined; } // For AWS compat: // 1) use first routing rules whose conditions are satisfied // 2) for matching prefix no need to check closest match. first // match wins // 3) there can be a match for a key condition with and without // error code condition but first one that matches will be the rule // used. So, if prefix foo without error and first rule has error condition, // will fall through to next foo rule. But if first foo rule has // no error condition, will have match on first rule even if later // there is more specific rule with error condition. for (let i = 0; i < routingRules.length; i++) { const prefixFromRule = routingRules[i].getCondition().keyPrefixEquals; const errorCodeFromRule = routingRules[i].getCondition().httpErrorCodeReturnedEquals; if (prefixFromRule !== undefined) { if (!key.startsWith(prefixFromRule)) { // no key match, move on continue; } // add the prefixFromRule to the redirect info // so we can replaceKeyPrefixWith if that is part of redirect // rule const redirectInfo = Object.assign({ prefixFromRule }, routingRules[i].getRedirect()); // have key match so check error code match if (errorCodeFromRule !== undefined) { if (errCode === errorCodeFromRule) { return redirectInfo; } // if don't match on both conditions, this is not the rule // for us continue; } // if no error code condition at all, we have found our match return redirectInfo; } // we have an error code condition but no key condition if (errorCodeFromRule !== undefined) { if (errCode === errorCodeFromRule) { const redirectInfo = Object.assign({}, routingRules[i].getRedirect()); return redirectInfo; } continue; } return undefined; } return undefined; } /** * extractRedirectInfo - convert location saved from x-amz-website header to * same format as redirectInfo saved from a put bucket website configuration * @param {string} location - location to redirect to * @return {object} redirectInfo - select key/values stored in * WebsiteConfiguration for a redirect -- protocol, replaceKeyWith and hostName */ export function extractRedirectInfo(location) { const redirectInfo = { redirectLocationHeader: true }; if (location.startsWith('/')) { // redirect to another object in bucket redirectInfo.replaceKeyWith = location.slice(1); // when redirect info is set by x-amz-website-redirect-location header // to another key in the same bucket // AWS only returns the path in the location response header redirectInfo.justPath = true; } else if (location.startsWith('https')) { // otherwise, redirect to another website redirectInfo.protocol = 'https'; redirectInfo.hostName = location.slice(8); } else { redirectInfo.protocol = 'http'; redirectInfo.hostName = location.slice(7); } return redirectInfo; }
lucisilv/Silviu_S3-Antidote
lib/api/apiUtils/object/websiteServing.js
JavaScript
apache-2.0
3,938
/* * Copyright 2014,2015 Open Networking Laboratory * * 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. */ /* ONOS GUI -- Util -- General Purpose Functions - Unit Tests */ describe('factory: fw/util/fn.js', function() { var $window, fs, someFunction = function () {}, someArray = [1, 2, 3], someObject = { foo: 'bar'}, someNumber = 42, someString = 'xyyzy', someDate = new Date(), stringArray = ['foo', 'bar']; beforeEach(module('onosUtil')); beforeEach(inject(function (_$window_, FnService) { $window = _$window_; fs = FnService; $window.innerWidth = 400; $window.innerHeight = 200; })); // === Tests for isF() it('isF(): null for undefined', function () { expect(fs.isF(undefined)).toBeNull(); }); it('isF(): null for null', function () { expect(fs.isF(null)).toBeNull(); }); it('isF(): the reference for function', function () { expect(fs.isF(someFunction)).toBe(someFunction); }); it('isF(): null for string', function () { expect(fs.isF(someString)).toBeNull(); }); it('isF(): null for number', function () { expect(fs.isF(someNumber)).toBeNull(); }); it('isF(): null for Date', function () { expect(fs.isF(someDate)).toBeNull(); }); it('isF(): null for array', function () { expect(fs.isF(someArray)).toBeNull(); }); it('isF(): null for object', function () { expect(fs.isF(someObject)).toBeNull(); }); // === Tests for isA() it('isA(): null for undefined', function () { expect(fs.isA(undefined)).toBeNull(); }); it('isA(): null for null', function () { expect(fs.isA(null)).toBeNull(); }); it('isA(): null for function', function () { expect(fs.isA(someFunction)).toBeNull(); }); it('isA(): null for string', function () { expect(fs.isA(someString)).toBeNull(); }); it('isA(): null for number', function () { expect(fs.isA(someNumber)).toBeNull(); }); it('isA(): null for Date', function () { expect(fs.isA(someDate)).toBeNull(); }); it('isA(): the reference for array', function () { expect(fs.isA(someArray)).toBe(someArray); }); it('isA(): null for object', function () { expect(fs.isA(someObject)).toBeNull(); }); // === Tests for isS() it('isS(): null for undefined', function () { expect(fs.isS(undefined)).toBeNull(); }); it('isS(): null for null', function () { expect(fs.isS(null)).toBeNull(); }); it('isS(): null for function', function () { expect(fs.isS(someFunction)).toBeNull(); }); it('isS(): the reference for string', function () { expect(fs.isS(someString)).toBe(someString); }); it('isS(): null for number', function () { expect(fs.isS(someNumber)).toBeNull(); }); it('isS(): null for Date', function () { expect(fs.isS(someDate)).toBeNull(); }); it('isS(): null for array', function () { expect(fs.isS(someArray)).toBeNull(); }); it('isS(): null for object', function () { expect(fs.isS(someObject)).toBeNull(); }); // === Tests for isO() it('isO(): null for undefined', function () { expect(fs.isO(undefined)).toBeNull(); }); it('isO(): null for null', function () { expect(fs.isO(null)).toBeNull(); }); it('isO(): null for function', function () { expect(fs.isO(someFunction)).toBeNull(); }); it('isO(): null for string', function () { expect(fs.isO(someString)).toBeNull(); }); it('isO(): null for number', function () { expect(fs.isO(someNumber)).toBeNull(); }); it('isO(): null for Date', function () { expect(fs.isO(someDate)).toBeNull(); }); it('isO(): null for array', function () { expect(fs.isO(someArray)).toBeNull(); }); it('isO(): the reference for object', function () { expect(fs.isO(someObject)).toBe(someObject); }); // === Tests for contains() it('contains(): false for improper args', function () { expect(fs.contains()).toBeFalsy(); }); it('contains(): false for non-array', function () { expect(fs.contains(null, 1)).toBeFalsy(); }); it('contains(): true for contained item', function () { expect(fs.contains(someArray, 1)).toBeTruthy(); expect(fs.contains(stringArray, 'bar')).toBeTruthy(); }); it('contains(): false for non-contained item', function () { expect(fs.contains(someArray, 109)).toBeFalsy(); expect(fs.contains(stringArray, 'zonko')).toBeFalsy(); }); // === Tests for areFunctions() it('areFunctions(): false for non-array', function () { expect(fs.areFunctions({}, 'not-an-array')).toBeFalsy(); }); it('areFunctions(): true for empty-array', function () { expect(fs.areFunctions({}, [])).toBeTruthy(); }); it('areFunctions(): true for some api', function () { expect(fs.areFunctions({ a: function () {}, b: function () {} }, ['b', 'a'])).toBeTruthy(); }); it('areFunctions(): false for some other api', function () { expect(fs.areFunctions({ a: function () {}, b: 'not-a-function' }, ['b', 'a'])).toBeFalsy(); }); it('areFunctions(): extraneous stuff NOT ignored', function () { expect(fs.areFunctions({ a: function () {}, b: function () {}, c: 1, d: 'foo' }, ['a', 'b'])).toBeFalsy(); }); it('areFunctions(): extraneous stuff ignored (alternate fn)', function () { expect(fs.areFunctionsNonStrict({ a: function () {}, b: function () {}, c: 1, d: 'foo' }, ['a', 'b'])).toBeTruthy(); }); // == use the now-tested areFunctions() on our own api: it('should define api functions', function () { expect(fs.areFunctions(fs, [ 'isF', 'isA', 'isS', 'isO', 'contains', 'areFunctions', 'areFunctionsNonStrict', 'windowSize', 'find', 'inArray', 'removeFromArray', 'cap' ])).toBeTruthy(); }); // === Tests for windowSize() it('windowSize(): noargs', function () { var dim = fs.windowSize(); expect(dim.width).toEqual(400); expect(dim.height).toEqual(200); }); it('windowSize(): adjust height', function () { var dim = fs.windowSize(50); expect(dim.width).toEqual(400); expect(dim.height).toEqual(150); }); it('windowSize(): adjust width', function () { var dim = fs.windowSize(0, 50); expect(dim.width).toEqual(350); expect(dim.height).toEqual(200); }); it('windowSize(): adjust width and height', function () { var dim = fs.windowSize(101, 201); expect(dim.width).toEqual(199); expect(dim.height).toEqual(99); }); // === Tests for find() var dataset = [ { id: 'foo', name: 'Furby'}, { id: 'bar', name: 'Barbi'}, { id: 'baz', name: 'Basil'}, { id: 'goo', name: 'Gabby'}, { id: 'zoo', name: 'Zevvv'} ]; it('should not find ooo', function () { expect(fs.find('ooo', dataset)).toEqual(-1); }); it('should find foo', function () { expect(fs.find('foo', dataset)).toEqual(0); }); it('should find zoo', function () { expect(fs.find('zoo', dataset)).toEqual(4); }); it('should not find Simon', function () { expect(fs.find('Simon', dataset, 'name')).toEqual(-1); }); it('should find Furby', function () { expect(fs.find('Furby', dataset, 'name')).toEqual(0); }); it('should find Zevvv', function () { expect(fs.find('Zevvv', dataset, 'name')).toEqual(4); }); // === Tests for inArray() var objRef = { x:1, y:2 }, array = [1, 3.14, 'hey', objRef, 'there', true], array2 = ['b', 'a', 'd', 'a', 's', 's']; it('should return -1 on non-arrays', function () { expect(fs.inArray(1, {x:1})).toEqual(-1); }); it('should not find HOO', function () { expect(fs.inArray('HOO', array)).toEqual(-1); }); it('should find 1', function () { expect(fs.inArray(1, array)).toEqual(0); }); it('should find pi', function () { expect(fs.inArray(3.14, array)).toEqual(1); }); it('should find hey', function () { expect(fs.inArray('hey', array)).toEqual(2); }); it('should find the object', function () { expect(fs.inArray(objRef, array)).toEqual(3); }); it('should find there', function () { expect(fs.inArray('there', array)).toEqual(4); }); it('should find true', function () { expect(fs.inArray(true, array)).toEqual(5); }); it('should find the first occurrence A', function () { expect(fs.inArray('a', array2)).toEqual(1); }); it('should find the first occurrence S', function () { expect(fs.inArray('s', array2)).toEqual(4); }); it('should not find X', function () { expect(fs.inArray('x', array2)).toEqual(-1); }); // === Tests for removeFromArray() it('should ignore non-arrays', function () { expect(fs.removeFromArray(1, {x:1})).toBe(false); }); it('should keep the array the same, for non-match', function () { var array = [1, 2, 3]; expect(fs.removeFromArray(4, array)).toBe(false); expect(array).toEqual([1, 2, 3]); }); it('should remove a value', function () { var array = [1, 2, 3]; expect(fs.removeFromArray(2, array)).toBe(true); expect(array).toEqual([1, 3]); }); it('should remove the first occurrence', function () { var array = ['x', 'y', 'z', 'z', 'y']; expect(fs.removeFromArray('y', array)).toBe(true); expect(array).toEqual(['x', 'z', 'z', 'y']); expect(fs.removeFromArray('x', array)).toBe(true); expect(array).toEqual(['z', 'z', 'y']); }); // === Tests for cap() it('should ignore non-alpha', function () { expect(fs.cap('123')).toEqual('123'); }); it('should capitalize first char', function () { expect(fs.cap('Foo')).toEqual('Foo'); expect(fs.cap('foo')).toEqual('Foo'); expect(fs.cap('foo bar')).toEqual('Foo bar'); }); });
kuangrewawa/onos
web/gui/src/main/webapp/tests/app/fw/util/fn-spec.js
JavaScript
apache-2.0
11,044
import React from 'react'; export default class TabsSkeleton extends React.Component { render() { const tab = ( <li className="wfp--tabs__nav-item"> <div className="wfp--tabs__nav-link">&nbsp;</div> </li> ); return ( <nav className="wfp--tabs wfp--skeleton"> <div className="wfp--tabs-trigger"> <div className="wfp--tabs-trigger-text">&nbsp;</div> <svg width="10" height="5" viewBox="0 0 10 5" fill-rule="evenodd"> <path d="M10 0L5 5 0 0z" /> </svg> </div> <ul className="wfp--tabs__nav wfp--tabs__nav--hidden"> <li className="wfp--tabs__nav-item wfp--tabs__nav-item--selected"> <div className="wfp--tabs__nav-link"> &nbsp;</div> </li> {tab} {tab} {tab} </ul> </nav> ); } }
wfp/ui
src/components/Tabs/Tabs.Skeleton.js
JavaScript
apache-2.0
863
import { nearlyEqual as bigNearlyEqual } from '../../utils/bignumber/nearlyEqual.js' import { nearlyEqual } from '../../utils/number.js' import { factory } from '../../utils/factory.js' import { createAlgorithm03 } from '../../type/matrix/utils/algorithm03.js' import { createAlgorithm12 } from '../../type/matrix/utils/algorithm12.js' import { createAlgorithm14 } from '../../type/matrix/utils/algorithm14.js' import { createAlgorithm13 } from '../../type/matrix/utils/algorithm13.js' import { createAlgorithm05 } from '../../type/matrix/utils/algorithm05.js' const name = 'compare' const dependencies = [ 'typed', 'config', 'matrix', 'equalScalar', 'BigNumber', 'Fraction', 'DenseMatrix' ] export const createCompare = /* #__PURE__ */ factory(name, dependencies, ({ typed, config, equalScalar, matrix, BigNumber, Fraction, DenseMatrix }) => { const algorithm03 = createAlgorithm03({ typed }) const algorithm05 = createAlgorithm05({ typed, equalScalar }) const algorithm12 = createAlgorithm12({ typed, DenseMatrix }) const algorithm13 = createAlgorithm13({ typed }) const algorithm14 = createAlgorithm14({ typed }) /** * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y. * * x and y are considered equal when the relative difference between x and y * is smaller than the configured epsilon. The function cannot be used to * compare values smaller than approximately 2.22e-16. * * For matrices, the function is evaluated element wise. * Strings are compared by their numerical value. * * Syntax: * * math.compare(x, y) * * Examples: * * math.compare(6, 1) // returns 1 * math.compare(2, 3) // returns -1 * math.compare(7, 7) // returns 0 * math.compare('10', '2') // returns 1 * math.compare('1000', '1e3') // returns 0 * * const a = math.unit('5 cm') * const b = math.unit('40 mm') * math.compare(a, b) // returns 1 * * math.compare(2, [1, 2, 3]) // returns [1, 0, -1] * * See also: * * equal, unequal, smaller, smallerEq, larger, largerEq, compareNatural, compareText * * @param {number | BigNumber | Fraction | Unit | string | Array | Matrix} x First value to compare * @param {number | BigNumber | Fraction | Unit | string | Array | Matrix} y Second value to compare * @return {number | BigNumber | Fraction | Array | Matrix} Returns the result of the comparison: * 1 when x > y, -1 when x < y, and 0 when x == y. */ return typed(name, { 'boolean, boolean': function (x, y) { return x === y ? 0 : (x > y ? 1 : -1) }, 'number, number': function (x, y) { return nearlyEqual(x, y, config.epsilon) ? 0 : (x > y ? 1 : -1) }, 'BigNumber, BigNumber': function (x, y) { return bigNearlyEqual(x, y, config.epsilon) ? new BigNumber(0) : new BigNumber(x.cmp(y)) }, 'Fraction, Fraction': function (x, y) { return new Fraction(x.compare(y)) }, 'Complex, Complex': function () { throw new TypeError('No ordering relation is defined for complex numbers') }, 'Unit, Unit': function (x, y) { if (!x.equalBase(y)) { throw new Error('Cannot compare units with different base') } return this(x.value, y.value) }, 'SparseMatrix, SparseMatrix': function (x, y) { return algorithm05(x, y, this) }, 'SparseMatrix, DenseMatrix': function (x, y) { return algorithm03(y, x, this, true) }, 'DenseMatrix, SparseMatrix': function (x, y) { return algorithm03(x, y, this, false) }, 'DenseMatrix, DenseMatrix': function (x, y) { return algorithm13(x, y, this) }, 'Array, Array': function (x, y) { // use matrix implementation return this(matrix(x), matrix(y)).valueOf() }, 'Array, Matrix': function (x, y) { // use matrix implementation return this(matrix(x), y) }, 'Matrix, Array': function (x, y) { // use matrix implementation return this(x, matrix(y)) }, 'SparseMatrix, any': function (x, y) { return algorithm12(x, y, this, false) }, 'DenseMatrix, any': function (x, y) { return algorithm14(x, y, this, false) }, 'any, SparseMatrix': function (x, y) { return algorithm12(y, x, this, true) }, 'any, DenseMatrix': function (x, y) { return algorithm14(y, x, this, true) }, 'Array, any': function (x, y) { // use matrix implementation return algorithm14(matrix(x), y, this, false).valueOf() }, 'any, Array': function (x, y) { // use matrix implementation return algorithm14(matrix(y), x, this, true).valueOf() } }) }) export const createCompareNumber = /* #__PURE__ */ factory(name, ['typed', 'config'], ({ typed, config }) => { return typed(name, { 'number, number': function (x, y) { return nearlyEqual(x, y, config.epsilon) ? 0 : (x > y ? 1 : -1) } }) })
FSMaxB/mathjs
src/function/relational/compare.js
JavaScript
apache-2.0
5,139
// This file has been autogenerated. var profile = require('../../../lib/util/profile'); exports.getMockedProfile = function () { var newProfile = new profile.Profile(); newProfile.addSubscription(new profile.Subscription({ id: '6e0b24a6-2bef-4598-9bd3-f87e9700e24c', name: 'Windows Azure Internal Consumption', user: { name: 'user@domain.example', type: 'user' }, tenantId: '72f988bf-86f1-41af-91ab-2d7cd011db47', state: 'Enabled', registeredProviders: [], _eventsCount: '1', isDefault: true }, newProfile.environments['AzureCloud'])); return newProfile; }; exports.setEnvironment = function() { process.env['AZURE_BATCH_ACCOUNT'] = 'test1'; process.env['AZURE_BATCH_ENDPOINT'] = 'https://test1.westus.batch.azure.com'; }; exports.scopes = [[function (nock) { var result = nock('http://test1.westus.batch.azure.com:443') .get('/pools/xplatTestPool/nodes/tvm-1650185656_1-20160422t053728z?api-version=2016-02-01.3.0&timeout=30') .reply(200, "{\r\n \"odata.metadata\":\"https://test1.westus.batch.azure.com/$metadata#nodes/@Element\",\"id\":\"tvm-1650185656_1-20160422t053728z\",\"url\":\"https://test1.westus.batch.azure.com/pools/xplatTestPool/nodes/tvm-1650185656_1-20160422t053728z\",\"state\":\"idle\",\"schedulingState\":\"enabled\",\"stateTransitionTime\":\"2016-04-22T05:54:18.9370641Z\",\"lastBootTime\":\"2016-04-22T05:54:18.8040259Z\",\"allocationTime\":\"2016-04-22T05:37:28.0108159Z\",\"ipAddress\":\"10.80.34.68\",\"affinityId\":\"TVM:tvm-1650185656_1-20160422t053728z\",\"vmSize\":\"small\",\"totalTasksRun\":0,\"totalTasksSucceeded\":0,\"runningTasksCount\":0\r\n}", { 'transfer-encoding': 'chunked', 'content-type': 'application/json;odata=minimalmetadata', server: 'Microsoft-HTTPAPI/2.0', 'request-id': '5d8be82e-f4c7-448d-8e21-353062f5bbfb', 'strict-transport-security': 'max-age=31536000; includeSubDomains', 'client-request-id': '75a212bb-f572-4f59-a152-89c662806bdd', dataserviceversion: '3.0', date: 'Fri, 22 Apr 2016 06:11:55 GMT', connection: 'close' }); return result; }, function (nock) { var result = nock('https://test1.westus.batch.azure.com:443') .get('/pools/xplatTestPool/nodes/tvm-1650185656_1-20160422t053728z?api-version=2016-02-01.3.0&timeout=30') .reply(200, "{\r\n \"odata.metadata\":\"https://test1.westus.batch.azure.com/$metadata#nodes/@Element\",\"id\":\"tvm-1650185656_1-20160422t053728z\",\"url\":\"https://test1.westus.batch.azure.com/pools/xplatTestPool/nodes/tvm-1650185656_1-20160422t053728z\",\"state\":\"idle\",\"schedulingState\":\"enabled\",\"stateTransitionTime\":\"2016-04-22T05:54:18.9370641Z\",\"lastBootTime\":\"2016-04-22T05:54:18.8040259Z\",\"allocationTime\":\"2016-04-22T05:37:28.0108159Z\",\"ipAddress\":\"10.80.34.68\",\"affinityId\":\"TVM:tvm-1650185656_1-20160422t053728z\",\"vmSize\":\"small\",\"totalTasksRun\":0,\"totalTasksSucceeded\":0,\"runningTasksCount\":0\r\n}", { 'transfer-encoding': 'chunked', 'content-type': 'application/json;odata=minimalmetadata', server: 'Microsoft-HTTPAPI/2.0', 'request-id': '5d8be82e-f4c7-448d-8e21-353062f5bbfb', 'strict-transport-security': 'max-age=31536000; includeSubDomains', 'client-request-id': '75a212bb-f572-4f59-a152-89c662806bdd', dataserviceversion: '3.0', date: 'Fri, 22 Apr 2016 06:11:55 GMT', connection: 'close' }); return result; }, function (nock) { var result = nock('http://test1.westus.batch.azure.com:443') .get('/pools/xplatTestPool/nodes/tvm-1650185656_1-20160422t053728z/rdp?api-version=2016-02-01.3.0&timeout=30') .reply(200, "full address:s:13.91.56.192\r\nLoadBalanceInfo:s:Cookie: mstshash=TVM#TVM_IN_0", { 'transfer-encoding': 'chunked', 'content-type': 'application/octet-stream', server: 'Microsoft-HTTPAPI/2.0', 'request-id': '21112e3a-aaf7-415f-a12d-c31937e8bce2', 'strict-transport-security': 'max-age=31536000; includeSubDomains', 'client-request-id': '61c53a16-d90f-4194-99ff-8be471d4715e', dataserviceversion: '3.0', date: 'Fri, 22 Apr 2016 06:11:56 GMT', connection: 'close' }); return result; }, function (nock) { var result = nock('https://test1.westus.batch.azure.com:443') .get('/pools/xplatTestPool/nodes/tvm-1650185656_1-20160422t053728z/rdp?api-version=2016-02-01.3.0&timeout=30') .reply(200, "full address:s:13.91.56.192\r\nLoadBalanceInfo:s:Cookie: mstshash=TVM#TVM_IN_0", { 'transfer-encoding': 'chunked', 'content-type': 'application/octet-stream', server: 'Microsoft-HTTPAPI/2.0', 'request-id': '21112e3a-aaf7-415f-a12d-c31937e8bce2', 'strict-transport-security': 'max-age=31536000; includeSubDomains', 'client-request-id': '61c53a16-d90f-4194-99ff-8be471d4715e', dataserviceversion: '3.0', date: 'Fri, 22 Apr 2016 06:11:56 GMT', connection: 'close' }); return result; }]];
msfcolombo/azure-xplat-cli
test/recordings/cli-batch-node-tests/cli_batch_node_should_download_the_node_RDP_file.nock.js
JavaScript
apache-2.0
4,788
function GetBehaviorSettings() { return { "name": "Replacer", "id": "Rex_Replacer", "description": "Replace instancne by fade-out itself, and create the target instance then fade-in it.", "author": "Rex.Rainbow", "help url": "https://dl.dropbox.com/u/5779181/C2Repo/rex_replacer.html", "category": "Rex - Movement - opacity", "flags": bf_onlyone }; }; ////////////////////////////////////////////////////////////// // Conditions AddCondition(1, cf_trigger, "On fade-out started", "Fade out", "On {my} fade-out started", "Triggered when fade-out started", "OnFadeOutStart"); AddCondition(2, cf_trigger, "On fade-out finished", "Fade out", "On {my} fade-out finished", "Triggered when fade-out finished", "OnFadeOutFinish"); AddCondition(3, cf_trigger, "On fade-in started", "Fade in", "On {my} fade-in started", "Triggered when fade-out started", "OnFadeInStart"); AddCondition(4, cf_trigger, "On fade-in finished", "Fade in", "On {my} fade-in finished", "Triggered when fade-in finished", "OnFadeInFinish"); AddCondition(5, 0, "Is fade-out", "Fade out", "Is {my} fade-out", "Return true if instance is in fade-out stage", "IsFadeOut"); AddCondition(6, 0, "Is fade-in", "Fade in", "Is {my} fade-in", "Return true if instance is in fade-in stage", "IsFadeIn"); AddCondition(7, 0, "Is idle", "Idle", "Is {my} idle", "Return true if instance is in idle stage", "IsIdle"); ////////////////////////////////////////////////////////////// // Actions AddObjectParam("Target", "Target type of replacing instance."); AddAction(1, 0, "Replace instance", "Replace", "{my} Replace to {0}","Replace instance.", "ReplaceInst"); AddStringParam("Target", "Target type in nickname of replacing instance.", '""'); AddAction(2, 0, "Replace instance to nickname type", "Replace", "Replace {my} to nickname: <i>{0}</i>","Replace instance to nickname type.", "ReplaceInst"); AddNumberParam("Duration", "Duration of fade-out or fade in, in seconds."); AddAction(3, 0, "Set duration", "Configure", "Set {my} fade duration to <i>{0}</i>", "Set the object's fade duration.", "SetDuration"); ////////////////////////////////////////////////////////////// // Expressions AddExpression(1, ef_return_number, "Get UID of replacing instance", "UID", "ReplacingInstUID", "The UID of replacing instanc, return -1 if the replacing does not start."); AddExpression(2, ef_return_number, "Get UID of replacing instance", "UID", "ReplacingInstUID", "The UID of replacing instanc, return -1 if the replacing does not start."); ACESDone(); // Property grid properties for this plugin var property_list = [ new cr.Property(ept_float, "Fade duration", 1, "Duration of fade-out or fade-in, in seconds."), ]; // Called by IDE when a new behavior type is to be created function CreateIDEBehaviorType() { return new IDEBehaviorType(); } // Class representing a behavior type in the IDE function IDEBehaviorType() { assert2(this instanceof arguments.callee, "Constructor called as a function"); } // Called by IDE when a new behavior instance of this type is to be created IDEBehaviorType.prototype.CreateInstance = function(instance) { return new IDEInstance(instance, this); } // Class representing an individual instance of an object in the IDE function IDEInstance(instance, type) { assert2(this instanceof arguments.callee, "Constructor called as a function"); // Save the constructor parameters this.instance = instance; this.type = type; // Set the default property values from the property table this.properties = {}; for (var i = 0; i < property_list.length; i++) this.properties[property_list[i].name] = property_list[i].initial_value; } // Called by the IDE after all initialization on this instance has been completed IDEInstance.prototype.OnCreate = function() { } // Called by the IDE after a property has been changed IDEInstance.prototype.OnPropertyChanged = function(property_name) { // Clamp values if (this.properties["Fade duration"] < 0) this.properties["Fade duration"] = 0; }
jasonshortphd/construct2games
plugins/behaviors/rex_replacer/edittime.js
JavaScript
apache-2.0
4,231
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * 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. */ CLASS({ package: 'foam.u2.md', name: 'CitationView', extends: 'foam.u2.md.DetailView', imports: [ 'dynamic', ], properties: [ { name: 'data', postSet: function(old, nu) { if (old !== nu && nu) this.model = nu.model_; }, }, { name: 'model', postSet: function(old, nu) { if (this.prop && old === nu) return; this.prop = this.pickNameProperty(); }, }, { name: 'prop', documentation: 'The name of the selected property.', }, ], methods: [ function pickNameProperty() { var prop = this.model.getFeature('label') || this.model.getFeature('name'); if (!prop) { var props = this.model.getRuntimeProperties(); var stringProps = []; for (var i = 0; i < props.length; i++) { var p = props[i]; if (! p.hidden && p.name !== 'id' && p.model_.id === 'Property' || p.model_.id === 'StringProperty') { stringProps.push(p); } } for (var i = 0; i < stringProps.length; i++) { var p = stringProps[i]; var pname = p.name.toLowerCase(); if (pname.indexOf('name') > -1 || pname.indexOf('label') > -1) { prop = p; break; } } if (!prop && stringProps.length) prop = stringProps[0]; } return prop ? prop.name : 'id'; } ], templates: [ function CSS() {/* ^ { align-items: center; border-bottom: 1px solid #eee; display: flex; min-height: 48px; padding: 16px; } */}, function initE() {/*#U2 <div class="^"> {{this.dynamic(function(data, prop) { return data ? data.propertyValue(prop) : ''; }, this.data$, this.prop$)}} </div> */}, ] });
jlhughes/foam
js/foam/u2/md/CitationView.js
JavaScript
apache-2.0
2,474
import { factory } from '../../../utils/factory.js' import { createSolveValidation } from './utils/solveValidation.js' const name = 'lsolveAll' const dependencies = [ 'typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtract', 'equalScalar', 'DenseMatrix' ] export const createLsolveAll = /* #__PURE__ */ factory(name, dependencies, ({ typed, matrix, divideScalar, multiplyScalar, subtract, equalScalar, DenseMatrix }) => { const solveValidation = createSolveValidation({ DenseMatrix }) /** * Finds all solutions of a linear equation system by forwards substitution. Matrix must be a lower triangular matrix. * * `L * x = b` * * Syntax: * * math.lsolveAll(L, b) * * Examples: * * const a = [[-2, 3], [2, 1]] * const b = [11, 9] * const x = lsolveAll(a, b) // [ [[-5.5], [20]] ] * * See also: * * lsolve, lup, slu, usolve, lusolve * * @param {Matrix, Array} L A N x N matrix or array (L) * @param {Matrix, Array} b A column vector with the b values * * @return {DenseMatrix[] | Array[]} An array of affine-independent column vectors (x) that solve the linear system */ return typed(name, { 'SparseMatrix, Array | Matrix': function (m, b) { return _sparseForwardSubstitution(m, b) }, 'DenseMatrix, Array | Matrix': function (m, b) { return _denseForwardSubstitution(m, b) }, 'Array, Array | Matrix': function (a, b) { const m = matrix(a) const R = _denseForwardSubstitution(m, b) return R.map(r => r.valueOf()) } }) function _denseForwardSubstitution (m, b_) { // the algorithm is derived from // https://www.overleaf.com/read/csvgqdxggyjv // array of right-hand sides const B = [solveValidation(m, b_, true)._data.map(e => e[0])] const M = m._data const rows = m._size[0] const columns = m._size[1] // loop columns for (let i = 0; i < columns; i++) { let L = B.length // loop right-hand sides for (let k = 0; k < L; k++) { const b = B[k] if (!equalScalar(M[i][i], 0)) { // non-singular row b[i] = divideScalar(b[i], M[i][i]) for (let j = i + 1; j < columns; j++) { // b[j] -= b[i] * M[j,i] b[j] = subtract(b[j], multiplyScalar(b[i], M[j][i])) } } else if (!equalScalar(b[i], 0)) { // singular row, nonzero RHS if (k === 0) { // There is no valid solution return [] } else { // This RHS is invalid but other solutions may still exist B.splice(k, 1) k -= 1 L -= 1 } } else if (k === 0) { // singular row, RHS is zero const bNew = [...b] bNew[i] = 1 for (let j = i + 1; j < columns; j++) { bNew[j] = subtract(bNew[j], M[j][i]) } B.push(bNew) } } } return B.map(x => new DenseMatrix({ data: x.map(e => [e]), size: [rows, 1] })) } function _sparseForwardSubstitution (m, b_) { // array of right-hand sides const B = [solveValidation(m, b_, true)._data.map(e => e[0])] const rows = m._size[0] const columns = m._size[1] const values = m._values const index = m._index const ptr = m._ptr // loop columns for (let i = 0; i < columns; i++) { let L = B.length // loop right-hand sides for (let k = 0; k < L; k++) { const b = B[k] // values & indices (column i) const iValues = [] const iIndices = [] // first & last indeces in column const firstIndex = ptr[i] const lastIndex = ptr[i + 1] // find the value at [i, i] let Mii = 0 for (let j = firstIndex; j < lastIndex; j++) { const J = index[j] // check row if (J === i) { Mii = values[j] } else if (J > i) { // store lower triangular iValues.push(values[j]) iIndices.push(J) } } if (!equalScalar(Mii, 0)) { // non-singular row b[i] = divideScalar(b[i], Mii) for (let j = 0, lastIndex = iIndices.length; j < lastIndex; j++) { const J = iIndices[j] b[J] = subtract(b[J], multiplyScalar(b[i], iValues[j])) } } else if (!equalScalar(b[i], 0)) { // singular row, nonzero RHS if (k === 0) { // There is no valid solution return [] } else { // This RHS is invalid but other solutions may still exist B.splice(k, 1) k -= 1 L -= 1 } } else if (k === 0) { // singular row, RHS is zero const bNew = [...b] bNew[i] = 1 for (let j = 0, lastIndex = iIndices.length; j < lastIndex; j++) { const J = iIndices[j] bNew[J] = subtract(bNew[J], iValues[j]) } B.push(bNew) } } } return B.map(x => new DenseMatrix({ data: x.map(e => [e]), size: [rows, 1] })) } })
FSMaxB/mathjs
src/function/algebra/solver/lsolveAll.js
JavaScript
apache-2.0
5,205
/** * Copyright 2013 Facebook, Inc. * * 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. * * @providesModule ReactTestUtils */ var EventConstants = require('EventConstants'); var React = require('React'); var ReactComponent = require('ReactComponent'); var ReactDOM = require('ReactDOM'); var ReactEventEmitter = require('ReactEventEmitter'); var ReactTextComponent = require('ReactTextComponent'); var ReactMount = require('ReactMount'); var mergeInto = require('mergeInto'); var copyProperties = require('copyProperties'); var topLevelTypes = EventConstants.topLevelTypes; function Event(suffix) {} /** * @class ReactTestUtils */ /** * Todo: Support the entire DOM.scry query syntax. For now, these simple * utilities will suffice for testing purposes. * @lends ReactTestUtils */ var ReactTestUtils = { renderIntoDocument: function(instance) { var div = document.createElement('div'); document.documentElement.appendChild(div); return React.renderComponent(instance, div); }, isComponentOfType: function(inst, type) { return !!( inst && ReactComponent.isValidComponent(inst) && inst.constructor === type.componentConstructor ); }, isDOMComponent: function(inst) { return !!(inst && ReactComponent.isValidComponent(inst) && !!inst.tagName); }, isCompositeComponent: function(inst) { return !!( inst && ReactComponent.isValidComponent(inst) && typeof inst.render === 'function' && typeof inst.setState === 'function' && typeof inst.updateComponent === 'function' ); }, isCompositeComponentWithType: function(inst, type) { return !!(ReactTestUtils.isCompositeComponent(inst) && (inst.constructor === type.componentConstructor || inst.constructor === type)); }, isTextComponent: function(inst) { return inst instanceof ReactTextComponent; }, findAllInRenderedTree: function(inst, test) { if (!inst) { return []; } var ret = test(inst) ? [inst] : []; if (ReactTestUtils.isDOMComponent(inst)) { var renderedChildren = inst._renderedChildren; var key; for (key in renderedChildren) { if (!renderedChildren.hasOwnProperty(key)) { continue; } ret = ret.concat( ReactTestUtils.findAllInRenderedTree(renderedChildren[key], test) ); } } else if (ReactTestUtils.isCompositeComponent(inst)) { ret = ret.concat( ReactTestUtils.findAllInRenderedTree(inst._renderedComponent, test) ); } return ret; }, /** * Finds all instance of components in the rendered tree that are DOM * components with the class name matching `className`. * @return an array of all the matches. */ scryRenderedDOMComponentsWithClass: function(root, className) { return ReactTestUtils.findAllInRenderedTree(root, function(inst) { var instClassName = inst.props.className; return ReactTestUtils.isDOMComponent(inst) && ( instClassName && (' ' + instClassName + ' ').indexOf(' ' + className + ' ') !== -1 ); }); }, /** * Like scryRenderedDOMComponentsWithClass but expects there to be one result, * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactDOMComponent} The one match. */ findRenderedDOMComponentWithClass: function(root, className) { var all = ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className); if (all.length !== 1) { throw new Error('Did not find exactly one match for class:' + className); } return all[0]; }, /** * Finds all instance of components in the rendered tree that are DOM * components with the tag name matching `tagName`. * @return an array of all the matches. */ scryRenderedDOMComponentsWithTag: function(root, tagName) { return ReactTestUtils.findAllInRenderedTree(root, function(inst) { return ReactTestUtils.isDOMComponent(inst) && inst.tagName === tagName.toUpperCase(); }); }, /** * Like scryRenderedDOMComponentsWithTag but expects there to be one result, * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactDOMComponent} The one match. */ findRenderedDOMComponentWithTag: function(root, tagName) { var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName); if (all.length !== 1) { throw new Error('Did not find exactly one match for tag:' + tagName); } return all[0]; }, /** * Finds all instances of components with type equal to `componentType`. * @return an array of all the matches. */ scryRenderedComponentsWithType: function(root, componentType) { return ReactTestUtils.findAllInRenderedTree(root, function(inst) { return ReactTestUtils.isCompositeComponentWithType(inst, componentType); }); }, /** * Same as `scryRenderedComponentsWithType` but expects there to be one result * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactComponent} The one match. */ findRenderedComponentWithType: function(root, componentType) { var all = ReactTestUtils.scryRenderedComponentsWithType( root, componentType ); if (all.length !== 1) { throw new Error( 'Did not find exactly one match for componentType:' + componentType ); } return all[0]; }, /** * Pass a mocked component module to this method to augment it with * useful methods that allow it to be used as a dummy React component. * Instead of rendering as usual, the component will become a simple * <div> containing any provided children. * * @param {object} module the mock function object exported from a * module that defines the component to be mocked * @param {?string} mockTagName optional dummy root tag name to return * from render method (overrides * module.mockTagName if provided) * @return {object} the ReactTestUtils object (for chaining) */ mockComponent: function(module, mockTagName) { var ConvenienceConstructor = React.createClass({ render: function() { var mockTagName = mockTagName || module.mockTagName || "div"; return ReactDOM[mockTagName](null, this.props.children); } }); copyProperties(module, ConvenienceConstructor); module.mockImplementation(ConvenienceConstructor); return this; }, /** * Simulates a top level event being dispatched from a raw event that occured * on and `Element` node. * @param topLevelType {Object} A type from `EventConstants.topLevelTypes` * @param {!Element} node The dom to simulate an event occurring on. * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. */ simulateEventOnNode: function(topLevelType, node, fakeNativeEvent) { var virtualHandler = ReactEventEmitter.TopLevelCallbackCreator.createTopLevelCallback( topLevelType ); fakeNativeEvent.target = node; virtualHandler(fakeNativeEvent); }, /** * Simulates a top level event being dispatched from a raw event that occured * on the `ReactDOMComponent` `comp`. * @param topLevelType {Object} A type from `EventConstants.topLevelTypes`. * @param comp {!ReactDOMComponent} * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. */ simulateEventOnDOMComponent: function(topLevelType, comp, fakeNativeEvent) { var reactRootID = comp._rootNodeID || comp._rootDomId; if (!reactRootID) { throw new Error('Simulating event on non-rendered component'); } var virtualHandler = ReactEventEmitter.TopLevelCallbackCreator.createTopLevelCallback( topLevelType ); var node = ReactMount.getNode(reactRootID); fakeNativeEvent.target = node; /* jsdom is returning nodes without id's - fixing that issue here. */ ReactMount.setID(node, reactRootID); virtualHandler(fakeNativeEvent); }, nativeTouchData: function(x, y) { return { touches: [ {pageX: x, pageY: y} ] }; }, Simulate: null // Will populate }; /** * Exports: * * - `ReactTestUtils.Simulate.click(Element/ReactDOMComponent)` * - `ReactTestUtils.Simulate.mouseMove(Element/ReactDOMComponent)` * - `ReactTestUtils.Simulate.mouseIn/ReactDOMComponent)` * - `ReactTestUtils.Simulate.mouseOut(Element/ReactDOMComponent)` * - ... (All keys from `EventConstants.topLevelTypes`) * * Note: Top level event types are a subset of the entire set of handler types * (which include a broader set of "synthetic" events). For example, onDragDone * is a synthetic event. You certainly may write test cases for these event * types, but it doesn't make sense to simulate them at this low of a level. In * this case, the way you test an `onDragDone` event is by simulating a series * of `mouseMove`/ `mouseDown`/`mouseUp` events - Then, a synthetic event of * type `onDragDone` will be constructed and dispached through your system * automatically. */ function makeSimulator(eventType) { return function(domComponentOrNode, nativeEventData) { var fakeNativeEvent = new Event(eventType); mergeInto(fakeNativeEvent, nativeEventData); if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { ReactTestUtils.simulateEventOnDOMComponent( eventType, domComponentOrNode, fakeNativeEvent ); } else if (!!domComponentOrNode.tagName) { // Will allow on actual dom nodes. ReactTestUtils.simulateEventOnNode( eventType, domComponentOrNode, fakeNativeEvent ); } }; } ReactTestUtils.Simulate = {}; var eventType; for (eventType in topLevelTypes) { // Event type is stored as 'topClick' - we transform that to 'click' var convenienceName = eventType.indexOf('top') === 0 ? eventType.charAt(3).toLowerCase() + eventType.substr(4) : eventType; /** * @param {!Element || ReactDOMComponent} domComponentOrNode * @param {?Event} nativeEventData Fake native event to use in SyntheticEvent. */ ReactTestUtils.Simulate[convenienceName] = makeSimulator(eventType); } module.exports = ReactTestUtils;
rtfeldman/react
src/test/ReactTestUtils.js
JavaScript
apache-2.0
10,971
var component function help() { return component = Qt.createComponent("NearbyDevices.qml"); }
meego-tablet-ux/meego-ux-settings
Bluetooth/helper.js
JavaScript
apache-2.0
96
/** * @license * Copyright 2018 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Zelos theme. */ 'use strict'; /** * Zelos theme. * @namespace Blockly.Themes.Zelos */ goog.module('Blockly.Themes.Zelos'); const {Theme} = goog.require('Blockly.Theme'); const defaultBlockStyles = { 'colour_blocks': { 'colourPrimary': '#CF63CF', 'colourSecondary': '#C94FC9', 'colourTertiary': '#BD42BD', }, 'list_blocks': { 'colourPrimary': '#9966FF', 'colourSecondary': '#855CD6', 'colourTertiary': '#774DCB', }, 'logic_blocks': { 'colourPrimary': '#4C97FF', 'colourSecondary': '#4280D7', 'colourTertiary': '#3373CC', }, 'loop_blocks': { 'colourPrimary': '#0fBD8C', 'colourSecondary': '#0DA57A', 'colourTertiary': '#0B8E69', }, 'math_blocks': { 'colourPrimary': '#59C059', 'colourSecondary': '#46B946', 'colourTertiary': '#389438', }, 'procedure_blocks': { 'colourPrimary': '#FF6680', 'colourSecondary': '#FF4D6A', 'colourTertiary': '#FF3355', }, 'text_blocks': { 'colourPrimary': '#FFBF00', 'colourSecondary': '#E6AC00', 'colourTertiary': '#CC9900', }, 'variable_blocks': { 'colourPrimary': '#FF8C1A', 'colourSecondary': '#FF8000', 'colourTertiary': '#DB6E00', }, 'variable_dynamic_blocks': { 'colourPrimary': '#FF8C1A', 'colourSecondary': '#FF8000', 'colourTertiary': '#DB6E00', }, 'hat_blocks': { 'colourPrimary': '#4C97FF', 'colourSecondary': '#4280D7', 'colourTertiary': '#3373CC', 'hat': 'cap', }, }; const categoryStyles = { 'colour_category': {'colour': '#CF63CF'}, 'list_category': {'colour': '#9966FF'}, 'logic_category': {'colour': '#4C97FF'}, 'loop_category': {'colour': '#0fBD8C'}, 'math_category': {'colour': '#59C059'}, 'procedure_category': {'colour': '#FF6680'}, 'text_category': {'colour': '#FFBF00'}, 'variable_category': {'colour': '#FF8C1A'}, 'variable_dynamic_category': {'colour': '#FF8C1A'}, }; /** * Zelos theme. * @type {Theme} * @alias Blockly.Themes.Zelos */ const Zelos = new Theme('zelos', defaultBlockStyles, categoryStyles); exports.Zelos = Zelos;
rachel-fenichel/blockly
core/theme/zelos.js
JavaScript
apache-2.0
2,189
Controller = undefined;
rm-training/advanced-js
www/discography/js/lib/controller.js
JavaScript
bsd-2-clause
24
/** * @fileoverview Main Espree file that converts Acorn into Esprima output. * * This file contains code from the following MIT-licensed projects: * 1. Acorn * 2. Babylon * 3. Babel-ESLint * * This file also contains code from Esprima, which is BSD licensed. * * Acorn is Copyright 2012-2015 Acorn Contributors (https://github.com/marijnh/acorn/blob/master/AUTHORS) * Babylon is Copyright 2014-2015 various contributors (https://github.com/babel/babel/blob/master/packages/babylon/AUTHORS) * Babel-ESLint is Copyright 2014-2015 Sebastian McKenzie <sebmck@gmail.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Esprima is Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* eslint no-undefined:0, no-use-before-define: 0 */ import * as acorn from "acorn"; import jsx from "acorn-jsx"; import espree from "./lib/espree.js"; import espreeVersion from "./lib/version.js"; import * as visitorKeys from "eslint-visitor-keys"; import { getLatestEcmaVersion, getSupportedEcmaVersions } from "./lib/options.js"; // To initialize lazily. const parsers = { _regular: null, _jsx: null, get regular() { if (this._regular === null) { this._regular = acorn.Parser.extend(espree()); } return this._regular; }, get jsx() { if (this._jsx === null) { this._jsx = acorn.Parser.extend(jsx(), espree()); } return this._jsx; }, get(options) { const useJsx = Boolean( options && options.ecmaFeatures && options.ecmaFeatures.jsx ); return useJsx ? this.jsx : this.regular; } }; //------------------------------------------------------------------------------ // Tokenizer //------------------------------------------------------------------------------ /** * Tokenizes the given code. * @param {string} code The code to tokenize. * @param {Object} options Options defining how to tokenize. * @returns {Token[]} An array of tokens. * @throws {SyntaxError} If the input code is invalid. * @private */ export function tokenize(code, options) { const Parser = parsers.get(options); // Ensure to collect tokens. if (!options || options.tokens !== true) { options = Object.assign({}, options, { tokens: true }); // eslint-disable-line no-param-reassign } return new Parser(options, code).tokenize(); } //------------------------------------------------------------------------------ // Parser //------------------------------------------------------------------------------ /** * Parses the given code. * @param {string} code The code to tokenize. * @param {Object} options Options defining how to tokenize. * @returns {ASTNode} The "Program" AST node. * @throws {SyntaxError} If the input code is invalid. */ export function parse(code, options) { const Parser = parsers.get(options); return new Parser(options, code).parse(); } //------------------------------------------------------------------------------ // Public //------------------------------------------------------------------------------ export const version = espreeVersion; /* istanbul ignore next */ export const VisitorKeys = (function() { return visitorKeys.KEYS; }()); // Derive node types from VisitorKeys /* istanbul ignore next */ export const Syntax = (function() { let name, types = {}; if (typeof Object.create === "function") { types = Object.create(null); } for (name in VisitorKeys) { if (Object.hasOwnProperty.call(VisitorKeys, name)) { types[name] = name; } } if (typeof Object.freeze === "function") { Object.freeze(types); } return types; }()); export const latestEcmaVersion = getLatestEcmaVersion(); export const supportedEcmaVersions = getSupportedEcmaVersions();
eslint/espree
espree.js
JavaScript
bsd-2-clause
6,419
/* */ "use strict"; var Subject_1 = require('../Subject'); var multicast_1 = require('./multicast'); function publish(selector) { return selector ? multicast_1.multicast.call(this, function() { return new Subject_1.Subject(); }, selector) : multicast_1.multicast.call(this, new Subject_1.Subject()); } exports.publish = publish;
poste9/crud
deps/npm/rxjs@5.0.3/operator/publish.js
JavaScript
bsd-2-clause
338
/* * L.Marker is used to display clickable/draggable icons on the map. */ L.Marker = L.Class.extend({ includes: L.Mixin.Events, options: { icon: new L.Icon(), title: '', clickable: true, draggable: false }, initialize: function(latlng, options) { L.Util.setOptions(this, options); this._latlng = latlng; }, onAdd: function(map) { this._map = map; this._initIcon(); map.on('viewreset', this._reset, this); this._reset(); }, onRemove: function(map) { this._removeIcon(); // TODO move to Marker.Popup.js if (this.closePopup) { this.closePopup(); } map.off('viewreset', this._reset, this); }, getLatLng: function() { return this._latlng; }, setLatLng: function(latlng) { this._latlng = latlng; if (this._icon) { this._reset(); } }, setIcon: function(icon) { this._removeIcon(); this._icon = this._shadow = null; this.options.icon = icon; this._initIcon(); this._reset(); }, _initIcon: function() { if (!this._icon) { this._icon = this.options.icon.createIcon(); if (this.options.title) { this._icon.title = this.options.title; } this._initInteraction(); } if (!this._shadow) { this._shadow = this.options.icon.createShadow(); } this._map._panes.markerPane.appendChild(this._icon); if (this._shadow) { this._map._panes.shadowPane.appendChild(this._shadow); } }, _removeIcon: function() { this._map._panes.markerPane.removeChild(this._icon); if (this._shadow) { this._map._panes.shadowPane.removeChild(this._shadow); } }, _reset: function() { var pos = this._map.latLngToLayerPoint(this._latlng).round(); L.DomUtil.setPosition(this._icon, pos); if (this._shadow) { L.DomUtil.setPosition(this._shadow, pos); } this._icon.style.zIndex = pos.y; }, _initInteraction: function() { if (this.options.clickable) { this._icon.className += ' leaflet-clickable'; L.DomEvent.addListener(this._icon, 'click', this._onMouseClick, this); var events = ['dblclick', 'mousedown', 'mouseover', 'mouseout']; for (var i = 0; i < events.length; i++) { L.DomEvent.addListener(this._icon, events[i], this._fireMouseEvent, this); } } if (L.Handler.MarkerDrag) { this.dragging = new L.Handler.MarkerDrag(this); if (this.options.draggable) { this.dragging.enable(); } } }, _onMouseClick: function(e) { L.DomEvent.stopPropagation(e); if (this.dragging && this.dragging.moved()) { return; } this.fire(e.type); }, _fireMouseEvent: function(e) { this.fire(e.type); L.DomEvent.stopPropagation(e); } });
shramov/Leaflet
src/layer/marker/Marker.js
JavaScript
bsd-2-clause
2,762
var stream = require('stream'); var util = require('util'); function combineTarget(){ stream.Writable.call(this); this.file = ''; } util.inherits(combineTarget,stream.Writable); combineTarget.prototype._write = function(chunk,encoding,callback){ this.file += chunk.toString(); callback(); }; module.exports = combineTarget;
SinaMTD-MobileTechnologyDepartment/addjs
src/lib/combineTarget.js
JavaScript
bsd-2-clause
335
/** * @module ol/geom/MultiLineString */ import {extend} from '../array.js'; import {closestSquaredDistanceXY} from '../extent.js'; import GeometryLayout from '../geom/GeometryLayout.js'; import GeometryType from '../geom/GeometryType.js'; import LineString from '../geom/LineString.js'; import SimpleGeometry from '../geom/SimpleGeometry.js'; import {assignClosestArrayPoint, arrayMaxSquaredDelta} from '../geom/flat/closest.js'; import {deflateCoordinatesArray} from '../geom/flat/deflate.js'; import {inflateCoordinatesArray} from '../geom/flat/inflate.js'; import {interpolatePoint, lineStringsCoordinateAtM} from '../geom/flat/interpolate.js'; import {intersectsLineStringArray} from '../geom/flat/intersectsextent.js'; import {douglasPeuckerArray} from '../geom/flat/simplify.js'; /** * @classdesc * Multi-linestring geometry. * * @api */ class MultiLineString extends SimpleGeometry { /** * @param {Array<Array<import("../coordinate.js").Coordinate>|LineString>|Array<number>} coordinates * Coordinates or LineString geometries. (For internal use, flat coordinates in * combination with `opt_layout` and `opt_ends` are also accepted.) * @param {GeometryLayout=} opt_layout Layout. * @param {Array<number>=} opt_ends Flat coordinate ends for internal use. */ constructor(coordinates, opt_layout, opt_ends) { super(); /** * @type {Array<number>} * @private */ this.ends_ = []; /** * @private * @type {number} */ this.maxDelta_ = -1; /** * @private * @type {number} */ this.maxDeltaRevision_ = -1; if (Array.isArray(coordinates[0])) { this.setCoordinates(/** @type {Array<Array<import("../coordinate.js").Coordinate>>} */ (coordinates), opt_layout); } else if (opt_layout !== undefined && opt_ends) { this.setFlatCoordinates(opt_layout, /** @type {Array<number>} */ (coordinates)); this.ends_ = opt_ends; } else { let layout = this.getLayout(); const lineStrings = /** @type {Array<LineString>} */ (coordinates); const flatCoordinates = []; const ends = []; for (let i = 0, ii = lineStrings.length; i < ii; ++i) { const lineString = lineStrings[i]; if (i === 0) { layout = lineString.getLayout(); } extend(flatCoordinates, lineString.getFlatCoordinates()); ends.push(flatCoordinates.length); } this.setFlatCoordinates(layout, flatCoordinates); this.ends_ = ends; } } /** * Append the passed linestring to the multilinestring. * @param {LineString} lineString LineString. * @api */ appendLineString(lineString) { if (!this.flatCoordinates) { this.flatCoordinates = lineString.getFlatCoordinates().slice(); } else { extend(this.flatCoordinates, lineString.getFlatCoordinates().slice()); } this.ends_.push(this.flatCoordinates.length); this.changed(); } /** * Make a complete copy of the geometry. * @return {!MultiLineString} Clone. * @override * @api */ clone() { return new MultiLineString(this.flatCoordinates.slice(), this.layout, this.ends_.slice()); } /** * @inheritDoc */ closestPointXY(x, y, closestPoint, minSquaredDistance) { if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) { return minSquaredDistance; } if (this.maxDeltaRevision_ != this.getRevision()) { this.maxDelta_ = Math.sqrt(arrayMaxSquaredDelta( this.flatCoordinates, 0, this.ends_, this.stride, 0)); this.maxDeltaRevision_ = this.getRevision(); } return assignClosestArrayPoint( this.flatCoordinates, 0, this.ends_, this.stride, this.maxDelta_, false, x, y, closestPoint, minSquaredDistance); } /** * Returns the coordinate at `m` using linear interpolation, or `null` if no * such coordinate exists. * * `opt_extrapolate` controls extrapolation beyond the range of Ms in the * MultiLineString. If `opt_extrapolate` is `true` then Ms less than the first * M will return the first coordinate and Ms greater than the last M will * return the last coordinate. * * `opt_interpolate` controls interpolation between consecutive LineStrings * within the MultiLineString. If `opt_interpolate` is `true` the coordinates * will be linearly interpolated between the last coordinate of one LineString * and the first coordinate of the next LineString. If `opt_interpolate` is * `false` then the function will return `null` for Ms falling between * LineStrings. * * @param {number} m M. * @param {boolean=} opt_extrapolate Extrapolate. Default is `false`. * @param {boolean=} opt_interpolate Interpolate. Default is `false`. * @return {import("../coordinate.js").Coordinate} Coordinate. * @api */ getCoordinateAtM(m, opt_extrapolate, opt_interpolate) { if ((this.layout != GeometryLayout.XYM && this.layout != GeometryLayout.XYZM) || this.flatCoordinates.length === 0) { return null; } const extrapolate = opt_extrapolate !== undefined ? opt_extrapolate : false; const interpolate = opt_interpolate !== undefined ? opt_interpolate : false; return lineStringsCoordinateAtM(this.flatCoordinates, 0, this.ends_, this.stride, m, extrapolate, interpolate); } /** * Return the coordinates of the multilinestring. * @return {Array<Array<import("../coordinate.js").Coordinate>>} Coordinates. * @override * @api */ getCoordinates() { return inflateCoordinatesArray( this.flatCoordinates, 0, this.ends_, this.stride); } /** * @return {Array<number>} Ends. */ getEnds() { return this.ends_; } /** * Return the linestring at the specified index. * @param {number} index Index. * @return {LineString} LineString. * @api */ getLineString(index) { if (index < 0 || this.ends_.length <= index) { return null; } return new LineString(this.flatCoordinates.slice( index === 0 ? 0 : this.ends_[index - 1], this.ends_[index]), this.layout); } /** * Return the linestrings of this multilinestring. * @return {Array<LineString>} LineStrings. * @api */ getLineStrings() { const flatCoordinates = this.flatCoordinates; const ends = this.ends_; const layout = this.layout; /** @type {Array<LineString>} */ const lineStrings = []; let offset = 0; for (let i = 0, ii = ends.length; i < ii; ++i) { const end = ends[i]; const lineString = new LineString(flatCoordinates.slice(offset, end), layout); lineStrings.push(lineString); offset = end; } return lineStrings; } /** * @return {Array<number>} Flat midpoints. */ getFlatMidpoints() { const midpoints = []; const flatCoordinates = this.flatCoordinates; let offset = 0; const ends = this.ends_; const stride = this.stride; for (let i = 0, ii = ends.length; i < ii; ++i) { const end = ends[i]; const midpoint = interpolatePoint( flatCoordinates, offset, end, stride, 0.5); extend(midpoints, midpoint); offset = end; } return midpoints; } /** * @inheritDoc */ getSimplifiedGeometryInternal(squaredTolerance) { const simplifiedFlatCoordinates = []; const simplifiedEnds = []; simplifiedFlatCoordinates.length = douglasPeuckerArray( this.flatCoordinates, 0, this.ends_, this.stride, squaredTolerance, simplifiedFlatCoordinates, 0, simplifiedEnds); return new MultiLineString(simplifiedFlatCoordinates, GeometryLayout.XY, simplifiedEnds); } /** * @inheritDoc * @api */ getType() { return GeometryType.MULTI_LINE_STRING; } /** * @inheritDoc * @api */ intersectsExtent(extent) { return intersectsLineStringArray( this.flatCoordinates, 0, this.ends_, this.stride, extent); } /** * Set the coordinates of the multilinestring. * @param {!Array<Array<import("../coordinate.js").Coordinate>>} coordinates Coordinates. * @param {GeometryLayout=} opt_layout Layout. * @override * @api */ setCoordinates(coordinates, opt_layout) { this.setLayout(opt_layout, coordinates, 2); if (!this.flatCoordinates) { this.flatCoordinates = []; } const ends = deflateCoordinatesArray( this.flatCoordinates, 0, coordinates, this.stride, this.ends_); this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1]; this.changed(); } } export default MultiLineString;
fredj/ol3
src/ol/geom/MultiLineString.js
JavaScript
bsd-2-clause
8,578
// Copyright (C) 2015 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es6id: 23.1.3.6 description: > Throws a TypeError if `this` is a WeakMap object. info: | Map.prototype.get ( key ) ... 3. If M does not have a [[MapData]] internal slot, throw a TypeError exception. ... features: [WeakMap] ---*/ assert.throws(TypeError, function() { Map.prototype.get.call(new WeakMap(), 1); }); assert.throws(TypeError, function() { var m = new Map(); m.get.call(new WeakMap(), 1); });
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Map/prototype/get/does-not-have-mapdata-internal-slot-weakmap.js
JavaScript
bsd-2-clause
569
goog.provide('ol.test.color'); goog.require('ol.color'); describe('ol.color', function() { describe('ol.color.asArray()', function() { it('returns the same for an array', function() { var color = [1, 2, 3, 0.4]; var got = ol.color.asArray(color); expect(got).to.be(color); }); it('returns an array given an rgba string', function() { var color = ol.color.asArray('rgba(1,2,3,0.4)'); expect(color).to.eql([1, 2, 3, 0.4]); }); it('returns an array given an rgb string', function() { var color = ol.color.asArray('rgb(1,2,3)'); expect(color).to.eql([1, 2, 3, 1]); }); it('returns an array given a hex string', function() { var color = ol.color.asArray('#00ccff'); expect(color).to.eql([0, 204, 255, 1]); }); }); describe('ol.color.asString()', function() { it('returns the same for a string', function() { var color = 'rgba(0,1,2,0.3)'; var got = ol.color.asString(color); expect(got).to.be(color); }); it('returns a string given an rgba array', function() { var color = ol.color.asString([1, 2, 3, 0.4]); expect(color).to.eql('rgba(1,2,3,0.4)'); }); it('returns a string given an rgb array', function() { var color = ol.color.asString([1, 2, 3]); expect(color).to.eql('rgba(1,2,3,1)'); }); }); describe('ol.color.fromString', function() { before(function() { sinon.spy(ol.color, 'fromStringInternal_'); }); after(function() { ol.color.fromStringInternal_.restore(); }); if (ol.ENABLE_NAMED_COLORS) { it('can parse named colors', function() { expect(ol.color.fromString('red')).to.eql([255, 0, 0, 1]); }); } it('can parse 3-digit hex colors', function() { expect(ol.color.fromString('#087')).to.eql([0, 136, 119, 1]); }); it('can parse 6-digit hex colors', function() { expect(ol.color.fromString('#56789a')).to.eql([86, 120, 154, 1]); }); it('can parse rgb colors', function() { expect(ol.color.fromString('rgb(0, 0, 255)')).to.eql([0, 0, 255, 1]); }); it('can parse rgba colors', function() { expect(ol.color.fromString('rgba(255, 255, 0, 0.1)')).to.eql( [255, 255, 0, 0.1]); }); it('caches parsed values', function() { var count = ol.color.fromStringInternal_.callCount; ol.color.fromString('aquamarine'); expect(ol.color.fromStringInternal_.callCount).to.be(count + 1); ol.color.fromString('aquamarine'); expect(ol.color.fromStringInternal_.callCount).to.be(count + 1); }); it('throws an error on invalid colors', function() { var invalidColors = ['tuesday', '#1234567', 'rgb(255.0,0,0)']; var i, ii; for (i = 0, ii < invalidColors.length; i < ii; ++i) { expect(function() { ol.color.fromString(invalidColors[i]); }).to.throwException(); } }); }); describe('ol.color.normalize', function() { it('clamps out-of-range channels', function() { expect(ol.color.normalize([-1, 256, 0, 2])).to.eql([0, 255, 0, 1]); }); it('rounds color channels to integers', function() { expect(ol.color.normalize([1.2, 2.5, 3.7, 1])).to.eql([1, 3, 4, 1]); }); }); describe('ol.color.toString', function() { it('converts valid colors', function() { expect(ol.color.toString([1, 2, 3, 0.4])).to.be('rgba(1,2,3,0.4)'); }); it('rounds to integers if needed', function() { expect(ol.color.toString([1.2, 2.5, 3.7, 0.4])).to.be('rgba(1,3,4,0.4)'); }); it('sets default alpha value if undefined', function() { expect(ol.color.toString([0, 0, 0])).to.be('rgba(0,0,0,1)'); }); }); });
tamarmot/ol3
test/spec/ol/color.test.js
JavaScript
bsd-2-clause
3,749
// Copyright 2008 Google Inc. All Rights Reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. var alias = eval; function e(s) { return alias(s); } assertEquals(42, e("42")); assertEquals(Object, e("Object")); assertEquals(e, e("e")); var caught = false; try { e('s'); // should throw exception since aliased eval is global } catch (e) { caught = true; assertTrue(e instanceof ReferenceError); } assertTrue(caught);
dfdeshom/v8onpython
v8-src/test/mjsunit/regress/regress-900055.js
JavaScript
bsd-3-clause
1,916
/** * Copyright 2004-present Facebook. All Rights Reserved. * */ /* eslint-disable sort-keys */ const fs = require('fs'); const os = require('os'); const path = require('path'); const glob = require('glob'); const mkdirp = require('mkdirp'); const toSlug = require('../core/toSlug'); const languages = require('../languages.js'); const feed = require('./feed'); function splitHeader(content) { const lines = content.split(os.EOL); let i = 1; for (; i < lines.length - 1; ++i) { if (lines[i] === '---') { break; } } return { header: lines.slice(1, i + 1).join('\n'), content: lines.slice(i + 1).join('\n'), }; } function backtickify(str) { let escaped = '`' + str.replace(/\\/g, '\\\\').replace(/`/g, '\\`') + '`'; // Replace require( with require\( so node-haste doesn't replace example // require calls in the docs escaped = escaped.replace(/require\(/g, 'require\\('); // Replace ${var} with \${var} so we can use place holders return escaped.replace(/\$\{([\w\s\d\'\:\.\(\)\?]*)\}/g, '\\${$1}'); } // Extract markdown metadata header function extractMetadata(content) { const metadata = {}; const both = splitHeader(content); const lines = both.header.split('\n'); for (let i = 0; i < lines.length - 1; ++i) { const keyvalue = lines[i].split(':'); const key = keyvalue[0].trim(); let value = keyvalue.slice(1).join(':').trim(); // Handle the case where you have "Community #10" try { value = JSON.parse(value); } catch (e) {} metadata[key] = value; } return {metadata, rawContent: both.content}; } const TABLE_OF_CONTENTS_TOKEN = '<AUTOGENERATED_TABLE_OF_CONTENTS>'; const insertTableOfContents = rawContent => { const regexp = /\n###\s+(`.*`.*)\n/g; let match; const headers = []; while ((match = regexp.exec(rawContent))) { headers.push(match[1]); } const tableOfContents = headers .map(header => ` - [${header}](#${toSlug(header)})`) .join('\n'); return rawContent.replace(TABLE_OF_CONTENTS_TOKEN, tableOfContents); }; function buildFile(layout, metadata, rawContent, language) { if (typeof language == 'undefined') { language = 'en'; } if (rawContent && rawContent.indexOf(TABLE_OF_CONTENTS_TOKEN) !== -1) { rawContent = insertTableOfContents(rawContent); } return [ '/**', ' * @generated', ' */', 'var React = require("React");', 'var Layout = require("' + layout + '");', rawContent && 'var content = ' + backtickify(rawContent) + ';', 'var Post = React.createClass({', rawContent && ' statics: { content: content },', ' render: function() {', ' return (', ' <Layout metadata={' + JSON.stringify(metadata) + '} language="' + language + '">', rawContent && ' {content}', ' </Layout>', ' );', ' }', '});', 'module.exports = Post;', ] .filter(e => e) .join('\n'); } function writeFileAndCreateFolder(file, content) { mkdirp.sync(file.replace(new RegExp('/[^/]*$'), '')); fs.writeFileSync(file, content); } function execute() { const DOCS_MD_DIR = '../docs/'; const BLOG_MD_DIR = '../blog/'; // Extracts the Getting started content from GettingStarted.md // and inserts into repo's README const gettingStarted = splitHeader( fs.readFileSync(DOCS_MD_DIR + 'en/GettingStarted.md', 'utf8') ).content.replace(/\(\/jest\//g, '(https://facebook.github.io/jest/'); let readme = fs.readFileSync('../README.md', 'utf8'); const guideStart = '<!-- generated_getting_started_start -->'; const guideEnd = '<!-- generated_getting_started_end -->'; readme = readme.slice(0, readme.indexOf(guideStart) + guideStart.length) + gettingStarted + readme.slice(readme.indexOf(guideEnd)); fs.writeFileSync('../README.md', readme); const regexSubFolder = /..\/docs\/(.*)\/.*/; const enabledLanguages = []; languages.filter(lang => lang.enabled).map(lang => { enabledLanguages.push(lang.tag); }); // for docs glob(DOCS_MD_DIR + '**', (er, files) => { const metadatas = { files: [], }; files.forEach(file => { // extract language let language = 'en'; const match = regexSubFolder.exec(file); if (match) { language = match[1]; } if (enabledLanguages.indexOf(language) === -1) { return; // this language is not enabled, don't process file } const extension = path.extname(file); if (extension === '.md' || extension === '.markdown') { const res = extractMetadata(fs.readFileSync(file, 'utf8')); const metadata = res.metadata; const rawContent = res.rawContent; metadata.source = path.basename(file); // in permalink replace /en/ language with localized folder metadata.permalink = metadata.permalink.replace( /\/en\//g, '/' + language + '/' ); // change ids previous, next metadata.localized_id = metadata.id; metadata.id = language + '-' + metadata.id; if (metadata.previous) { metadata.previous_id = metadata.previous; metadata.previous = language + '-' + metadata.previous; } if (metadata.next) { metadata.next_id = metadata.next; metadata.next = language + '-' + metadata.next; } metadata.language = language; metadatas.files.push(metadata); if (metadata.permalink.match(/^https?:/)) { return; } // Create a dummy .js version that just calls the associated layout const layout = metadata.layout[0].toUpperCase() + metadata.layout.substr(1) + 'Layout'; writeFileAndCreateFolder( 'src/jest/' + metadata.permalink.replace(/\.html$/, '.js'), buildFile(layout, metadata, rawContent, language) ); } if (extension === '.json') { const content = fs.readFileSync(file, 'utf8'); metadatas[path.basename(file, '.json')] = JSON.parse(content); } }); fs.writeFileSync( 'core/metadata.js', '/**\n' + ' * @generated\n' + ' * @providesModule Metadata\n' + ' */\n' + 'module.exports = ' + JSON.stringify(metadatas, null, 2) + ';' ); }); // For the blog glob(BLOG_MD_DIR + '**/*.*', (er, files) => { const metadatas = { files: [], }; files.sort().reverse().forEach(file => { // Transform // 2015-08-13-blog-post-name-0.5.md // into // 2015/08/13/blog-post-name-0-5.html const filePath = path .basename(file) .replace('-', '/') .replace('-', '/') .replace('-', '/') // react-middleware is broken with files that contains multiple . // like react-0.14.js .replace(/\./g, '-') .replace(/\-md$/, '.html'); const res = extractMetadata(fs.readFileSync(file, {encoding: 'utf8'})); const rawContent = res.rawContent; const metadata = Object.assign( {path: filePath, content: rawContent}, res.metadata ); metadata.id = metadata.title; metadatas.files.push(metadata); writeFileAndCreateFolder( 'src/jest/blog/' + filePath.replace(/\.html$/, '.js'), buildFile('BlogPostLayout', metadata, rawContent) ); }); const perPage = 10; for ( let page = 0; page < Math.ceil(metadatas.files.length / perPage); ++page ) { writeFileAndCreateFolder( 'src/jest/blog' + (page > 0 ? '/page' + (page + 1) : '') + '/index.js', buildFile('BlogPageLayout', {page, perPage}) ); } fs.writeFileSync( 'core/metadata-blog.js', '/**\n' + ' * @generated\n' + ' * @providesModule MetadataBlog\n' + ' */\n' + 'module.exports = ' + JSON.stringify(metadatas, null, 2) + ';' ); }); writeFileAndCreateFolder('src/jest/blog/feed.xml', feed('rss')); writeFileAndCreateFolder('src/jest/blog/atom.xml', feed('atom')); } module.exports = execute;
mpontus/jest
website/server/convert.js
JavaScript
bsd-3-clause
8,156
/** * umeditor完整配置项 * 可以在这里配置整个编辑器的特性 */ /**************************提示******************************** * 所有被注释的配置项均为UEditor默认值。 * 修改默认配置请首先确保已经完全明确该参数的真实用途。 * 主要有两种修改方案,一种是取消此处注释,然后修改成对应参数;另一种是在实例化编辑器时传入对应参数。 * 当升级编辑器时,可直接使用旧版配置文件替换新版配置文件,不用担心旧版配置文件中因缺少新功能所需的参数而导致脚本报错。 **************************提示********************************/ (function () { /** * 编辑器资源文件根路径。它所表示的含义是:以编辑器实例化页面为当前路径,指向编辑器资源文件(即dialog等文件夹)的路径。 * 鉴于很多同学在使用编辑器的时候出现的种种路径问题,此处强烈建议大家使用"相对于网站根目录的相对路径"进行配置。 * "相对于网站根目录的相对路径"也就是以斜杠开头的形如"/myProject/umeditor/"这样的路径。 * 如果站点中有多个不在同一层级的页面需要实例化编辑器,且引用了同一UEditor的时候,此处的URL可能不适用于每个页面的编辑器。 * 因此,UEditor提供了针对不同页面的编辑器可单独配置的根路径,具体来说,在需要实例化编辑器的页面最顶部写上如下代码即可。当然,需要令此处的URL等于对应的配置。 * window.UMEDITOR_HOME_URL = "/xxxx/xxxx/"; */ var URL = window.UMEDITOR_HOME_URL || (function(){ function PathStack() { this.documentURL = self.document.URL || self.location.href; this.separator = '/'; this.separatorPattern = /\\|\//g; this.currentDir = './'; this.currentDirPattern = /^[.]\/]/; this.path = this.documentURL; this.stack = []; this.push( this.documentURL ); } PathStack.isParentPath = function( path ){ return path === '..'; }; PathStack.hasProtocol = function( path ){ return !!PathStack.getProtocol( path ); }; PathStack.getProtocol = function( path ){ var protocol = /^[^:]*:\/*/.exec( path ); return protocol ? protocol[0] : null; }; PathStack.prototype = { push: function( path ){ this.path = path; update.call( this ); parse.call( this ); return this; }, getPath: function(){ return this + ""; }, toString: function(){ return this.protocol + ( this.stack.concat( [''] ) ).join( this.separator ); } }; function update() { var protocol = PathStack.getProtocol( this.path || '' ); if( protocol ) { //根协议 this.protocol = protocol; //local this.localSeparator = /\\|\//.exec( this.path.replace( protocol, '' ) )[0]; this.stack = []; } else { protocol = /\\|\//.exec( this.path ); protocol && (this.localSeparator = protocol[0]); } } function parse(){ var parsedStack = this.path.replace( this.currentDirPattern, '' ); if( PathStack.hasProtocol( this.path ) ) { parsedStack = parsedStack.replace( this.protocol , ''); } parsedStack = parsedStack.split( this.localSeparator ); parsedStack.length = parsedStack.length - 1; for(var i= 0,tempPath,l=parsedStack.length,root = this.stack;i<l;i++){ tempPath = parsedStack[i]; if(tempPath){ if( PathStack.isParentPath( tempPath ) ) { root.pop(); } else { root.push( tempPath ); } } } } var currentPath = document.getElementsByTagName('script'); currentPath = currentPath[ currentPath.length -1 ].src; return new PathStack().push( currentPath ) + ""; })(); /** * 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。 */ window.UMEDITOR_CONFIG = { //为编辑器实例添加一个路径,这个不能被注释 UMEDITOR_HOME_URL : URL //图片上传配置区 ,imageUrl:"/Advice/imgUpload" //图片上传提交地址 ,imagePath:'http://www.test.com/' //图片修正地址,引用了fixedImagePath,如有特殊需求,可自行配置 ,imageFieldName:"upfile" //图片数据的key,若此处修改,需要在后台对应文件修改对应参数 //工具栏上的所有的功能按钮和下拉框,可以在new编辑器的实例时选择自己需要的从新定义 ,toolbar:[ 'source | undo redo | bold italic underline strikethrough | superscript subscript | forecolor backcolor | removeformat |', 'insertorderedlist insertunorderedlist | selectall cleardoc paragraph | fontfamily fontsize' , '| justifyleft justifycenter justifyright justifyjustify |', 'link unlink | emotion image video | map', '| horizontal print preview fullscreen', 'drafts', 'formula' ] //语言配置项,默认是zh-cn。有需要的话也可以使用如下这样的方式来自动多语言切换,当然,前提条件是lang文件夹下存在对应的语言文件: //lang值也可以通过自动获取 (navigator.language||navigator.browserLanguage ||navigator.userLanguage).toLowerCase() //,lang:"zh-cn" //,langPath:URL +"lang/" //ie下的链接自动监测 //,autourldetectinie:false //主题配置项,默认是default。有需要的话也可以使用如下这样的方式来自动多主题切换,当然,前提条件是themes文件夹下存在对应的主题文件: //现有如下皮肤:default //,theme:'default' //,themePath:URL +"themes/" //针对getAllHtml方法,会在对应的head标签中增加该编码设置。 //,charset:"utf-8" //常用配置项目 //,isShow : true //默认显示编辑器 //,initialContent:'欢迎使用UMEDITOR!' //初始化编辑器的内容,也可以通过textarea/script给值,看官网例子 //,initialFrameWidth:500 //初始化编辑器宽度,默认500 //,initialFrameHeight:500 //初始化编辑器高度,默认500 //,autoClearinitialContent:true //是否自动清除编辑器初始内容,注意:如果focus属性设置为true,这个也为真,那么编辑器一上来就会触发导致初始化的内容看不到了 //,textarea:'editorValue' // 提交表单时,服务器获取编辑器提交内容的所用的参数,多实例时可以给容器name属性,会将name给定的值最为每个实例的键值,不用每次实例化的时候都设置这个值 //,focus:false //初始化时,是否让编辑器获得焦点true或false //,autoClearEmptyNode : true //getContent时,是否删除空的inlineElement节点(包括嵌套的情况) //,fullscreen : false //是否开启初始化时即全屏,默认关闭 //,readonly : false //编辑器初始化结束后,编辑区域是否是只读的,默认是false //,zIndex : 900 //编辑器层级的基数,默认是900 //如果自定义,最好给p标签如下的行高,要不输入中文时,会有跳动感 //注意这里添加的样式,最好放在.edui-editor-body .edui-body-container这两个的下边,防止跟页面上css冲突 //,initialStyle:'.edui-editor-body .edui-body-container p{line-height:1em}' //,autoSyncData:true //自动同步编辑器要提交的数据 //,emotionLocalization:false //是否开启表情本地化,默认关闭。若要开启请确保emotion文件夹下包含官网提供的images表情文件夹 //,allHtmlEnabled:false //提交到后台的数据是否包含整个html字符串 //fontfamily //字体设置 // ,'fontfamily':[ // { name: 'songti', val: '宋体,SimSun'}, // ] //fontsize //字号 //,'fontsize':[10, 11, 12, 14, 16, 18, 20, 24, 36] //paragraph //段落格式 值留空时支持多语言自动识别,若配置,则以配置值为准 //,'paragraph':{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''} //undo //可以最多回退的次数,默认20 //,maxUndoCount:20 //当输入的字符数超过该值时,保存一次现场 //,maxInputCount:1 //imageScaleEnabled // 是否允许点击文件拖拽改变大小,默认true //,imageScaleEnabled:true //dropFileEnabled // 是否允许拖放图片到编辑区域,上传并插入,默认true //,dropFileEnabled:true //pasteImageEnabled // 是否允许粘贴QQ截屏,上传并插入,默认true //,pasteImageEnabled:true //autoHeightEnabled // 是否自动长高,默认true //,autoHeightEnabled:true //autoFloatEnabled //是否保持toolbar的位置不动,默认true //,autoFloatEnabled:true //浮动时工具栏距离浏览器顶部的高度,用于某些具有固定头部的页面 //,topOffset:30 //填写过滤规则 //,filterRules: {} }; })();
airect/part-time-job
Tpl/bootstrap/public/um/umeditor.config.js
JavaScript
bsd-3-clause
9,939
window.jQuery = window.$ = require('jquery'); require('bootstrap'); require('bootstrap/dist/js/bootstrap.js'); require('bootstrap/dist/css/bootstrap.css'); require('file?name=[name].[ext]!bootstrap/dist/css/bootstrap.css.map'); require('yii2-pjax'); require('yii'); require('yii.validation'); require('yii.activeForm'); require('yii.gridView'); require('yii.captcha');
kllakk/yii2base
web/js/site/vendor.js
JavaScript
bsd-3-clause
370
/* Language: Tagger Script Author: Philipp Wolfer <ph.wolfer@gmail.com> Description: Syntax Highlighting for the Tagger Script as used by MusicBrainz Picard. Website: https://picard.musicbrainz.org */ function(hljs) { var COMMENT = { className: 'comment', begin: /\$noop\(/, end: /\)/, contains: [{ begin: /\(/, end: /\)/, contains: ['self', { begin: /\\./ }] }], relevance: 10 }; var FUNCTION = { className: 'keyword', begin: /\$(?!noop)[a-zA-Z][_a-zA-Z0-9]*/, end: /\(/, excludeEnd: true }; var VARIABLE = { className: 'variable', begin: /%[_a-zA-Z0-9:]*/, end: '%' }; var ESCAPE_SEQUENCE = { className: 'symbol', begin: /\\./ }; return { contains: [ COMMENT, FUNCTION, VARIABLE, ESCAPE_SEQUENCE ] }; }
MakeNowJust/highlight.js
src/languages/taggerscript.js
JavaScript
bsd-3-clause
855
#!/usr/bin/env node // var fs = require('fs'), path = require('path'), http = require('http'), BufferStream = require('bufferstream'), // http://www.ksu.ru/eng/departments/ktk/test/perl/lib/unicode/UCDFF301.html keys = ['value', 'name', 'category', 'class', 'bidirectional_category', 'mapping', 'decimal_digit_value', 'digit_value', 'numeric_value', 'mirrored', 'unicode_name', 'comment', 'uppercase_mapping', 'lowercase_mapping', 'titlecase_mapping'], systemfiles = [ "UnicodeData.txt" ], refs = 0; // based on https://github.com/mathiasbynens/jsesc function escape(charValue) { var hexadecimal = charValue.replace(/^0*/, ''); // is already in hexadecimal var longhand = hexadecimal.length > 2; return '\\' + (longhand ? 'u' : 'x') + ('0000' + hexadecimal).slice(longhand ? -4 : -2); } function stringify(key, value) { return key + ":" + JSON.stringify(value).replace(/\\\\(u|x)/, "\\$1"); } function newFile(name, callback) { var filename = path.join(__dirname, "category", name + ".js"), file = fs.createWriteStream(filename, {encoding:'utf8'}); file.once('close', function () { if (!--refs) { console.log("done."); callback(); } }); refs++; return file; } function parser(callback) { var data = {}, buffer = new BufferStream({encoding:'utf8', size:'flexible'}), resume = buffer.resume.bind(buffer); buffer.split('\n', function (line) { var v, c, char = {}, values = line.toString().split(';'); for(var i = 0 ; i < 15 ; i++) char[keys[i]] = values[i]; v = parseInt(char.value, 16); char.symbol = escape(char.value); c = char.category; if (!data[c]) { data[c] = newFile(c, callback) .on('drain', resume) .once('open', function () { console.log("saving data as %s.js …", c); if (this.write('module.exports={' + stringify(v, char))) buffer.resume(); }); buffer.pause(); } else if (!data[c].write("," + stringify(v, char))) { buffer.pause(); } }); buffer.on('end', function () { var cat, categories = Object.keys(data), len = categories.length; for(var i = 0 ; i < len ; i++) { cat = categories[i]; data[cat].end("};"); } }); buffer.on('error', function (err) { if (typeof err === 'string') err = new Error(err); throw err; }); return buffer; } function read_file(success_cb, error_cb) { var systemfile, sysfiles = systemfiles.slice(), try_reading = function (success, error) { systemfile = sysfiles.shift(); if (!systemfile) return error_cb(); console.log("try to read file %s …", systemfile); fs.exists(systemfile, function (exists) { if (!exists) { console.error("%s not found.", systemfile); return try_reading(success_cb, error_cb); } console.log("parsing …"); fs.createReadStream(systemfile, {encoding:'utf8'}).pipe(parser(success_cb)); }); }; try_reading(success_cb, error_cb); } // run if (!module.parent) { // not required read_file(process.exit, process.exit); } else { module.exports = { escape:escape, stringify:stringify, newFile:newFile, parser:parser, read_file:read_file }; }
feup-infolab/dendro-install
scripts/Programs/node_modules/unicode/generate.js
JavaScript
bsd-3-clause
3,600
module.exports = function (grunt) { var packageVersion = require('../../package.json').version; /* ------------- RELEASE ------------- */ grunt.registerTask('notes', 'Run a ruby gem that will request from Github unreleased pull requests', ['prompt:generatelogsmanually']); grunt.registerTask('updateRelease', '', function () { packageVersion = require('../../package.json').version; }); // Maintainers: Run prior to a release. Includes SauceLabs VM tests. grunt.registerTask('release', 'Release a new version, push it and publish it', function () { grunt.log.write('Welcome to the FUEL UX Release process.\n'); grunt.log.write('\n'); grunt.log.write('Please review and complete prerequisites in RELEASE.md.\n'); grunt.log.write('\n'); grunt.log.write('Please make sure you are not on VPN.\n'); grunt.log.write('\n'); // default variables for release task var releaseDefaults = { release: { files: ['dist', 'README.md', 'CONTRIBUTING.md', 'bower.json', 'package.json', 'reference/dist'], localBranch: 'release', remoteBaseBranch: 'master', remoteDestinationBranch: '3.x', remoteRepository: 'upstream' } }; // add releaseDefaults grunt.config.merge(releaseDefaults); if (!grunt.file.exists('SAUCE_API_KEY.yml')) { grunt.log.write('The file SAUCE_API_KEY.yml is needed in order to run tests in SauceLabs.'.red.bold + ' Please contact another maintainer to obtain this file.'); } if (typeof grunt.config('cdnLoginFile') === 'undefined') { grunt.log.write('The file FUEL_CDN.yml is needed in order to upload the release files to the CDN.'.red.bold + ' Please contact another maintainer to obtain this file.'); } // update local variable to make sure build prompt is using temp branch's package version grunt.task.run( [ 'prompt:logoffvpn', 'prompt:rannpminstall', 'prompt:rangrunttest', 'prompt:ransauce', 'prompt:createmilestone', 'prompt:bumpmilestones', 'prompt:closemilestone', 'prompt:startrelease', 'prompt:tempbranch', 'shell:checkoutRemoteReleaseBranch', 'updateRelease', 'prompt:build', 'dorelease' ] ); }); grunt.registerTask('dorelease', '', function () { grunt.log.writeln(''); if (!grunt.option('no-tests')) { grunt.task.run(['releasetest']); // If phantom timeouts happening because of long-running qunit tests, look into setting `resourceTimeout` in phantom: http://phantomjs.org/api/webpage/property/settings.html // Delete any screenshots that may have happened if it got this far. This isn't foolproof // because it relies on the phantomjs server/page timeout, which can take longer than this // grunt task depending on how long saucelabs takes to run... grunt.task.run('clean:screenshots'); } grunt.config('banner', '<%= bannerRelease %>'); // Run dist again to grab the latest version numbers. Yeah, we're running it twice... ¯\_(ツ)_/¯ grunt.task.run([ 'bump-only:' + grunt.config('release.buildSemVerType'), 'replace:readme', 'replace:packageJs', 'dist', 'shell:addReleaseFiles', 'shell:copyToReference', 'prompt:commit', 'prompt:tag', 'prompt:pushLocalBranchToUpstream', 'prompt:pushTagToUpstream', 'prompt:uploadToCDN', 'prompt:pushLocalBranchToUpstreamMaster', 'shell:publishToNPM', 'prompt:generatelogs' ]); }); };
cormacmccarthy/fuelux
grunt/tasks/release.js
JavaScript
bsd-3-clause
3,374
/** * openircd, a lightweight ircd written in javascript v8 with nodejs. * http://www.openbrasil.org/ - rede do conhecimento livre. * * $Id$ */ exports.listen = { port: 6667, host: '0.0.0.0' }; exports.server = { name: "experimental.openbrasil.org", description: "servidor experimental openbrasil", }; exports.network = { name: "openbrasil" }; exports.general = { ping_timeout: 1 };
ArmandoAce/openircd
config.js
JavaScript
bsd-3-clause
399
import { Handlers } from '@sentry/node'; import { sentry } from '../../../../config/secrets'; export default function sentryRequestHandler() { return sentry.dns === 'dsn_from_sentry_dashboard' ? (req, res, next) => next() : Handlers.requestHandler(); }
FreeCodeCamp/FreeCodeCamp
api-server/src/server/middlewares/sentry-request-handler.js
JavaScript
bsd-3-clause
264
// These tests require the client to be built and served with additional // redirect configuration. The Cypress action in .github/workflows/cypress.yml // contains the necessary commands to do this. describe('Legacy redirects', () => { it('should redirect from front-end-libraries to front-end-development-libraries', () => { cy.visit('learn/front-end-libraries'); cy.url().should('include', 'learn/front-end-development-libraries'); cy.visit('learn/front-end-libraries/bootstrap'); cy.location().should(loc => { expect(loc.pathname).to.eq( '/learn/front-end-development-libraries/bootstrap/' ); }); cy.visit('learn/front-end-libraries/front-end-libraries-projects'); cy.location().should(loc => { expect(loc.pathname).to.eq( '/learn/front-end-development-libraries/front-end-development-libraries-projects/' ); }); cy.visit( 'learn/front-end-libraries/front-end-libraries-projects/build-a-random-quote-machine' ); cy.location().should(loc => { expect(loc.pathname).to.eq( '/learn/front-end-development-libraries/front-end-development-libraries-projects/build-a-random-quote-machine' ); }); cy.visit('certification/certifieduser/front-end-libraries'); cy.location().should(loc => { expect(loc.pathname).to.eq( '/certification/certifieduser/front-end-development-libraries' ); }); cy.visit( 'learn/front-end-libraries/bootstrap/use-responsive-design-with-bootstrap-fluid-containers' ); cy.location().should(loc => { expect(loc.pathname).to.eq( '/learn/front-end-development-libraries/bootstrap/use-responsive-design-with-bootstrap-fluid-containers' ); }); // Bit of hack: but we need to make sure the page is fully loaded before // moving on. cy.get('.react-monaco-editor-container').should('be.visible'); }); it('should redirect from /apis-and-microservices to /back-end-development-and-apis', () => { cy.visit('learn/apis-and-microservices'); cy.location().should(loc => { expect(loc.pathname).to.eq('/learn/back-end-development-and-apis/'); }); cy.visit('learn/apis-and-microservices/managing-packages-with-npm'); cy.location().should(loc => { expect(loc.pathname).to.eq( '/learn/back-end-development-and-apis/managing-packages-with-npm/' ); }); cy.visit( 'learn/apis-and-microservices/managing-packages-with-npm/how-to-use-package-json-the-core-of-any-node-js-project-or-npm-package' ); cy.location().should(loc => { expect(loc.pathname).to.eq( '/learn/back-end-development-and-apis/managing-packages-with-npm/how-to-use-package-json-the-core-of-any-node-js-project-or-npm-package' ); }); cy.visit('learn/apis-and-microservices/apis-and-microservices-projects'); cy.location().should(loc => { expect(loc.pathname).to.eq( '/learn/back-end-development-and-apis/back-end-development-and-apis-projects/' ); }); cy.visit( 'learn/apis-and-microservices/apis-and-microservices-projects/timestamp-microservice' ); cy.location().should(loc => { expect(loc.pathname).to.eq( '/learn/back-end-development-and-apis/back-end-development-and-apis-projects/timestamp-microservice' ); }); cy.visit('certification/certifieduser/apis-and-microservices'); cy.location().should(loc => { expect(loc.pathname).to.eq( '/certification/certifieduser/back-end-development-and-apis' ); }); }); });
FreeCodeCamp/FreeCodeCamp
cypress/integration/legacy/redirects/adding-development.js
JavaScript
bsd-3-clause
3,591
foo.bar()
mck89/peast
test/Peast/Syntax/ES2015/files/CallExpression/Simple.js
JavaScript
bsd-3-clause
9
var structarm__dct4__instance__q31 = [ [ "N", "structarm__dct4__instance__q31.html#a46a9f136457350676e2bfd3768ff9d6d", null ], [ "Nby2", "structarm__dct4__instance__q31.html#a32d3268ba4629908dba056599f0a904d", null ], [ "normalize", "structarm__dct4__instance__q31.html#ac80ff7b28fca36aeef74dea12e8312dd", null ], [ "pCfft", "structarm__dct4__instance__q31.html#ac96579cfb28d08bb11dd2fe4c6303833", null ], [ "pCosFactor", "structarm__dct4__instance__q31.html#af97204d1838925621fc82021a0c2d6c1", null ], [ "pRfft", "structarm__dct4__instance__q31.html#af1487dab5e7963b85dc0fdc6bf492542", null ], [ "pTwiddle", "structarm__dct4__instance__q31.html#a7db236e22673146bb1d2c962f0713f08", null ] ];
lpodkalicki/blog
stm32/STM32Cube_FW_F0_V1.9.0/Drivers/CMSIS/Documentation/DSP/html/structarm__dct4__instance__q31.js
JavaScript
bsd-3-clause
728
var _ = require('underscore-cdb-v3'); var cdb = require('cartodb.js-v3'); var pluralizeString = require('../../../view_helpers/pluralize_string') module.exports = cdb.core.View.extend({ initialize: function() { _.each(['permission', 'isUsingVis'], function(name) { if (_.isUndefined(this.options[name])) throw new Error(name + ' is required'); }, this); }, render: function() { this.$el.html( this.getTemplate('common/dialogs/change_privacy/share/details')({ willRevokeAccess: this._willRevokeAccess(), avatarUrl: this.model.get('avatar_url'), title: this.model.get('display_name'), desc: this._desc(), roleLabel: false }) ); return this; }, _desc: function() { var usersCount = this.model.users.length; var xMembers = pluralizeString.prefixWithCount('member', 'members', usersCount); if (this._willRevokeAccess()) { return xMembers + '. ' + pluralizeString("Member's", "Members'", usersCount) + ' maps will be affected'; } else if (this.options.isUsingVis) { return xMembers + '. ' + pluralizeString('Member is', 'Members are', usersCount) + ' using this dataset'; } else { return xMembers; } }, _willRevokeAccess: function() { return this.options.isUsingVis && !this.options.permission.hasReadAccess(this.model); } });
splashblot/dronedb
lib/assets/javascripts/cartodb/common/dialogs/change_privacy/share/group_details_view.js
JavaScript
bsd-3-clause
1,368
module.exports = { selector: '.lift-status', parse: { name: '1/0', status: { child: 0, attribute: 'class', fn: s => s.split(' ').pop() } } };
pirxpilot/liftie
lib/resorts/snowbasin/index.js
JavaScript
bsd-3-clause
178
/* * Copyright (c) 2019-2021 Renata Hodovan, Akos Kiss. * * Licensed under the BSD 3-Clause License * <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. * This file may not be copied, modified, or distributed except * according to those terms. */ /* global fz */ $(document).ready(function () { 'use strict'; var jobAdded = function (data) { var job = $(`#${data.type}-job-template`).prop('content').cloneNode(true); $(job).find('.card').attr('id', `job-${data.job_id}`); $(job).find('.card').addClass(data.status === 'active' ? 'bg-success' : 'bg-secondary'); $(job).find('.close').attr('onclick', `fz.api.cancelJob('${data.job_id}')`); $(job).find('.job-id').text(data.job_id); if ('fuzzer' in data) { $(job).find('.job-fuzzer').text(data.fuzzer); } if ('sut' in data) { $(job).find('.job-sut').text(data.sut); } if ('issue_id' in data) { $(job).find('.job-issue').text(data.issue_id); } if ('issue_oid' in data) { $(job).find('.job-issue').attr('href', `/issues/${data.issue_oid}`); } var maxValue = data.batch || data.size || 0; var progress = $(job).find('.progress-bar'); progress.attr('data-maxvalue', maxValue); if (maxValue == Infinity) { $(job).find('.progress-text').text('0'); } $('#jobs').append(document.importNode(job, true)); if ('progress' in data) { jobProgressed(data); } }; fz.notifications.onmessage['job_added'] = jobAdded; var jobProgressed = function (data) { var jobCard = $(`#job-${data.job_id}`); if (jobCard.length !== 0) { var progress = jobCard.find('.progress-bar'); if ($(progress).data('maxvalue') < Infinity) { var percent = Math.round(data.progress / $(progress).data('maxvalue') * 100); progress.css('width', `${percent}%`); progress.attr('aria-valuenow', percent); jobCard.find('.progress-text').text(`${percent}%`); } else { jobCard.find('.progress-text').text(new Intl.NumberFormat({ notation: "scientific" }).format(data.progress)); if (!progress.hasClass('progress-bar-striped')) { progress.attr('style', 'width: 100%'); progress.addClass('progress-bar-striped'); } } } }; fz.notifications.onmessage['job_progressed'] = jobProgressed; fz.notifications.onmessage['job_activated'] = function (data) { var jobCard = $(`#job-${data.job_id}`); if (jobCard.length !== 0 && jobCard.hasClass('bg-secondary')) { jobCard.removeClass('bg-secondary').addClass('bg-success'); } if ($(jobCard).data('job-type') == 'fuzz') { var progress = $(jobCard).find('.progress-bar'); if ($(progress).data('maxvalue') == Infinity) { progress.attr('style', 'width: 100%'); progress.addClass('progress-bar-striped'); } } }; fz.notifications.onmessage['job_removed'] = function (data) { $(`#job-${data.job_id}`).remove(); }; fz.api.getJobs(function (data) { for (var job of data) { jobAdded(job); } }); });
akosthekiss/fuzzinator
fuzzinator/ui/wui/resources/static/scripts/jobs.js
JavaScript
bsd-3-clause
3,086
var searchData= [ ['node',['node',['../structconnectivity.html#af0fc7c1443c916dce333bee34787cd20',1,'connectivity']]] ];
pushkarjain1991/Poisson_FEM
html/search/variables_0.js
JavaScript
bsd-3-clause
123
$(document).ready(function () { //$('#pageListDt').DataTable(); /* $("#publish").click(function () { NccPageMask.ShowLoadingMask(); $.ajax({ type: "post", url: form.action, data: form.serialize(), contentType: "application/x-www-form-urlencoded", success: function (rsp, textStatus, jqXHR) { NccPageMask.HideLoadingMask(); if (rsp.isSuccess) { NccAlert.ShowSuccess(rsp.message); ClearForm(); } else { NccAlert.ShowError("Error: " + rsp.message); } }, error: function (jqXHR, textStatus, errorThrown) { NccPageMask.HideLoadingMask(); NccAlert.ShowError("Error. Please try again."); } }) }); */ });
OnnoRokomSoftware/NetCoreCMS
NetCoreCMS.Web/Core/Core.Cms/wwwroot/js/managePage.js
JavaScript
bsd-3-clause
965
( function( exports ) { /** * @class * @param params * @constructor */ function BulkLoader( params ) { this.params = params; this._ids = []; this.results = {}; this._objects = []; // GC対策 this.cache = {}; var self = this; this._handler = function( e ) { self._onLoadHandler( e ); }; for ( var id in this.params ) { this._ids.push( id ); var param = this.params[id]; var object = null; switch ( param.type ) { case "image": object = new Image(); object.src = param.url; break; case "audio": case "music": object = new Audio( param.url, Audio.MUSIC ); break; case "se": object = new Audio( param.url, Audio.SE ); break; } object.id = id; object.onload = this._handler; this._objects.push( object ); } } BulkLoader.prototype = {}; BulkLoader.prototype._onLoadHandler = function( e ) { var id = e.target.id; e.target.onload = null; this.results[id] = e.target; this._ids.splice( this._ids.indexOf( id ), 1 ); if ( this._ids.length > 0 ) { return; } // complete this._handler = null; if ( this.onload !== null ) this.onload(); }; BulkLoader.prototype.getBitmapData = function( id ) { if(typeof this.cache[id] === "undefined" && typeof this.results[id] !== "undefined") { this.cache[id] = new BitmapData(this.results[id]); this.results[id] = null; } return this.cache[id]; }; BulkLoader.prototype.get = function( id ) { return this.results[id]; }; BulkLoader.prototype.onload = null; exports.BulkLoader = BulkLoader; } )( this ); ( function( exports ) { var Observer = function () { this.listeners = {}; }; Observer.prototype = { addEventListener: function( type, listener ) { var listeners = this.listeners; if (!listeners[type]) { listeners[type] = []; } listeners[type].push(listener); }, removeEventListener:function (type, listener) { var listeners = this.listeners; if (listeners[type]) { var i; var len = listeners[type].length; for (i = len - 1; i >= 0; i--) { var arr = listeners[type][i]; if (arr[0] === listener) { listeners[type].splice(i, 1); } } } }, dispatchEvent: function(event) { var listeners = this.listeners; var newEvent = {}; newEvent.type = event.type; newEvent.target = this; if (listeners[newEvent.type]) { var i; var len = listeners[newEvent.type].length; for (i = 0; i < len; i++) { var listener = listeners[newEvent.type][i]; listener.call(this, newEvent); } } } }; exports.Observer = Observer; } )( this );
sonicmoov/herlock-samples
nekoana/libs/common.js
JavaScript
bsd-3-clause
3,586
module.exports = function(gatewayd) { // ADD PLUGINS HERE, SUCH AS SETUP WIZARD const WizardPlugin = require('gatewayd-setup-wizard-plugin'); var wizardPlugin = new WizardPlugin({ gatewayd: gatewayd }); gatewayd.server.use('/', wizardPlugin.router); }
crazyquark/gatewayd
Gatewaydfile.js
JavaScript
isc
270