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
|
---|---|---|---|---|---|
Drupal.behaviors.scholarlayout = function() {
Drupal.CTools.AJAX.commands.updateLayoutForm = function(data) {
scholarlayout_update_moved_elements(data.warning);
}
var layoutRegions = [ "#scholarlayout-header-left", "#scholarlayout-header-main", "#scholarlayout-header-right", "#scholarlayout-navbar", "#scholarlayout-left", "#scholarlayout-right", "#scholarlayout-footer" ];
if( $("#edit-page-type").val() == "front"){
layoutRegions.push("#scholarlayout-content-top");
layoutRegions.push("#scholarlayout-content-bottom");
layoutRegions.push("#scholarlayout-content-left");
layoutRegions.push("#scholarlayout-content-right");
}
scholarlayout_add_sortable(layoutRegions);
if (!scholarlayout_change_bound) {
scholarlayout_change_bound = true;
$('#vsite-layout-ui-settings-form').submit(function() {
scholarlayout_update_moved_elements(false);
return true;
});
$("#edit-page-type").bind('change', function(e) {
if (scholarlayout_catchchanges()) {
$('#edit-secret-hidden-ahah').val($("#edit-page-type").val());
$('#edit-secret-hidden-ahah').trigger('go_ahah');
$("#edit-page-type").trigger('go_ahah');
$("#scholarforms_save_warning").remove();
scholarlayout_add_sortable(layoutRegions);
} else {
// revert
$('#edit-page-type').val($("#edit-secret-hidden-ahah").val());
}
});
}
scholarlayout_add_removal_hooks();
//Add scroller that shows what exceptions exist
vsite_layout_setExceptionScroller();
//init scroller on topbox
vsite_layout_init_horz_scroller();
//Add tabbed event for catigorized widgets
vsite_layout_add_category_select();
//remove or prevent ctools modal handling from modalframe links
vsite_layout_modalframe_links();
//compress widgets widths to fit in the space provided
vsite_layout_set_widget_width(false);
//Create the wobble func
$(document).bind('CToolsDetachBehaviors',function(element) {
//Shake new widgets when they are created
vsite_layout_wobble_new();
});
};
function scholarlayout_add_removal_hooks() {
$(".ui-sortable .close-this:not(.close-this-processed)").addClass('close-this-processed')
.click(function(e) {
var parent = $(this).parent("dd");
$("body").append("<div class='poof'></div>");
// set the x and y offset of the poof animation <div> from cursor
// position (in pixels)
var xOffset = 24;
var yOffset = 24;
$('.poof').css({
left : e.pageX - xOffset + 'px',
top : e.pageY - yOffset + 'px'
}).show(); // display the poof <div>
animatePoof(); // run the sprite animation
parent.appendTo("#scholarlayout-top-widgets");
scholarlayout_update_moved_elements(true);
parent.fadeIn('fast');
vsite_layout_init_categories();
vsite_layout_update_scroller_width();
});
}
var scholarlayout_change_bound = false;
var scholarlayout_oScrollbar = false;
//Executed after a block is dragged
function scholarlayout_afterdrag(event, ui) {
scholarlayout_update_moved_elements(true);
vsite_layout_update_scroller_width();
//compress widgets widths to fit in the space provided
vsite_layout_set_widget_width(ui.item);
};
/**
* Update the form with the correct values after elemens have been moved.
* @param warning
* @return
*/
function scholarlayout_update_moved_elements(warning){
var regions = $("#scholarlayout-container > .scholarlayout-widgets-list");
$.each(regions.filter(":visible"), function(i, region) {
var items = $("#" + region.id + " > .scholarlayout-item");
var ids = "";
$.each(items, function(i, value) {
if (ids.length) {
ids += "|";
}
ids += value.id;
});
$('#edit-' + region.id).val(ids);
});
$.each(regions.filter(":hidden"), function(i, region) {
$('#edit-' + region.id).val("");
});
if (!$("#scholarforms_save_warning").length && warning) {
$("#cp-settings-layout").before(
$('<div id="scholarforms_save_warning" class="warning"><span class="warning tabledrag-changed">*</span> Your changes have not yet been saved. Click "Save Settings" for your changes to take effect</div>')
);
}
}
function scholarlayout_catchchanges() {
if (!$("#scholarforms_save_warning").length
|| confirm("Your changes have not been saved. Continue and lose your changes?")) {
return true;
}
return false;
};
function scholarlayout_add_sortable(layoutRegions) {
var allRegions = layoutRegions.slice();
allRegions[allRegions.length] = "#scholarlayout-top-widgets";
$.each(allRegions, function(i, value) {
$(value).sortable('destroy');
$(value).sortable({
appendTo: '#vsite-layout-ui-settings-form',
helper: 'clone',
cursorAt: {top: 25, left: 38},
connectWith : allRegions,
stop : scholarlayout_afterdrag,
tolerance : 'pointer',
start: function (event, ui) {ui.helper.width('75px'); },
over : function(event, ui) {$(event.target).addClass('active');},
out : function(event, ui) {$(event.target).removeClass('active');}
});
});
}
// The jQuery Poof Effect was developed by Kreg Wallace at The Kombine Group,
// Inc. http://www.kombine.net/
function animatePoof() {
var bgTop = 0; // initial background-position for the poof sprit is '0 0'
var frames = 5; // number of frames in the sprite animation
var frameSize = 32; // size of poof <div> in pixels (32 x 32 px in this example)
var frameRate = 80; // set length of time each frame in the animation will
// display (in milliseconds)
// loop through amination frames
// and display each frame by resetting the background-position of the poof
// <div>
for (i = 1; i < frames; i++) {
$('.poof').animate({backgroundPosition : '0 ' + (bgTop - frameSize) + 'px'}, frameRate);
bgTop -= frameSize; // update bgPosition to reflect the new
// background-position of our poof <div>
}
// wait until the animation completes and then hide the poof <div>
setTimeout("$('.poof').remove()", frames * frameRate);
}
// Horizontal Sliding Exceptions
function vsite_layout_setExceptionScroller() {
$('span.toggle-exceptions').click(function() {
$(this).siblings('div.layout-exceptions').stop().animate({
right : '-20px'
}, {
queue : false,
duration : 300
});
});
$('div.layout-exceptions').click(function() {
$(this).stop().animate({
right : '-101%'
}, {
queue : false,
duration : 300
});
});
}
//attaches event listeners to category select widget
//when its changed, show only widgets that match the category
function vsite_layout_add_category_select() {
$('#widget-categories li').click(function() {
$('#widget-categories li').removeClass('active');
$(this).addClass('active');
vsite_layout_init_categories();
vsite_layout_update_scroller_width();
return false;
});
// behaviors gets run after an ajax call
// prevent this from selecting multiple tabs
if (!$('#widget-categories li.active').length) {
$('#widget-categories li:first').addClass('active');
}
vsite_layout_init_categories();
}
function vsite_layout_init_categories(){
var cat = $('#widget-categories li.active a').attr('href').substring(1);
vsite_layout_swap_categories(cat);
}
function vsite_layout_swap_categories(cat) {
if (cat == 'all') {
$('#scholarlayout-top-widgets dd').not('.disabled').show();
}
else {
$('#scholarlayout-top-widgets').children('dd:not(.' + cat + ')').hide();
$('#scholarlayout-top-widgets').children("."+cat + ':not(.disabled)').show();
}
vsite_layout_update_scroller_width();
}
//remove or prevent ctools modal handling from modalframe links
function vsite_layout_modalframe_links(){
function modalFrameSubmitHandler(args, messages) {
Drupal.CTools.AJAX.respond(args);
}
$('a.ctools-use-modal').each(function(i, elem) {
if (elem.href && elem.href.indexOf('/modal/') != -1) {
var $this = $(this);
$this.removeClass('ctools-use-modal');
if ($this.hasClass('ctools-use-modal-processed')) {
$this.unbind('click', Drupal.CTools.Modal.clickAjaxLink);
}
$this.click(function (e) {
var url = $(this).attr('href'),
modal_start = url.indexOf('/modal/'),
params = url.slice(modal_start);
url = url.replace(params, '');
params = params.split('/');
url = url+'?modal&box='+params[3]+'&source='+params[5];
var modalOptions = {
url: url,
autoFit: true,
width: 980,
height: 150,
onSubmit: modalFrameSubmitHandler
};
Drupal.modalFrame.open(modalOptions);
e.preventDefault();
});
}
});
}
//init scroller on topbox
function vsite_layout_init_horz_scroller(){
//Top Scroller
$('#scholarlayout-top-widgets-wrapper').addClass('scroll-wrapper').append('<div class="scrollbar"><div class="track"><div class="thumb"><div class="end"></div></div></div></div>');
$('.scroll-wrapper .tagged-list').addClass('scroll-viewport');
$('.scroll-wrapper .tagged-list #scholarlayout-top-widgets').addClass('scroll-content');
scholarlayout_oScrollbar = $('.scroll-wrapper').tinyscrollbar({ axis: 'x'});
if ($('#scholarlayout-top-widgets-wrapper').hasClass('scroll-wrapper')) {
vsite_layout_update_scroller_width();
}
}
/*
* Update the width of divs and re-init to scrollbar object
*/
function vsite_layout_update_scroller_width(){
var vp_width = $('.scroll-wrapper .scroll-viewport').width();
//arb large
$('.scroll-wrapper .scroll-viewport').width(5000);
$('.scroll-wrapper .scroll-content').css('width','auto');
var ct_width = Math.max($('.scroll-wrapper .scroll-content').width(),vp_width);
$('.scroll-wrapper .scroll-content').width(ct_width);
$('.scroll-wrapper .scroll-viewport').width(vp_width);
if(scholarlayout_oScrollbar) scholarlayout_oScrollbar.tinyscrollbar_update();
}
/**
* Only does something when a widget has been added dynamically.
*/
Drupal.behaviors.widgetBeenAdded = function (ctx) {
// ctx is a jQuery object with our element inside
// do nothing if our ctx doesnt have the widget class!
if (!('hasClass' in ctx) || !ctx.hasClass('scholarlayout-item')) return;
$('#widget-categories li a').each(function () {
var cat = $(this).attr('href').substring(1);
if (ctx.hasClass(cat)) {
$(this).click();
return false;
}
});
};
/*
* adjusts the width of a single widget to fit the container
* takes either an element or a jQuery object
*/
function vsite_layout_set_widget_width(widget){
var nHeight = 36; //Height of one widget
var regions;
if(widget){
regions = widget.parent();
}else{
regions = $("#scholarlayout-container > .scholarlayout-widgets-list");
}
$.each(regions, function(i, region){
var rgn = $("#"+region.id);
if(region.id == 'scholarlayout-top-widgets' && widget){
//top widgets should go back to default size
$(widget).removeAttr( "style" );
}else if(rgn.height() < nHeight *2){
//If this is a skinny container
var items = $("#"+region.id+" > .scholarlayout-item");
var nWidth = (rgn.width()) / items.length;
items.width(nWidth - 51);
}else if(rgn.hasClass('scholarlayout-widgets-list') && widget){
var nWidth = rgn.width();
$(widget).width(nWidth-51);
}
});
}
/**
* AHAH leaves an unmarked div inbetween our wrapper and content elements
* This fixes it
*/
function vsite_layout_fix_top_ahah() {
var $top = $('#scholarlayout-top-widgets'),
top = $top[0];
if (typeof top.parentNode.id == 'undefined' && top.parentNode.className == '') {
// we have an unmarked div
var rem = $(top.parentNode),
targ = $(top.parentNode.parentNode);
$top.detach();
rem.remove();
targ.after($top);
}
}
////////wobble///////////
function vsite_layout_wobble_new(){
$('dd.changed').each(function(){
var i = 0;
while(i < 8) {
$(this).animate({marginTop:'-'+3+'px'}, 90);
$(this).animate({marginTop:3}, 90);
i++;
}
$(this).removeClass('changed');
});
}
|
Mukeysh/alf_git
|
sites/all/modules/openscholar_vsite/vsite_layout/vsite_layout_ui/theme/vsite_layout_ui.js
|
JavaScript
|
gpl-2.0
| 12,083 |
var ShellTask = require('../../src/tasks/shell.js');
describe("ShellTask", function() {
var fail = this.fail;
it("returns stdout and stderr", function(done) {
var task = new ShellTask('echo "hi"; echo "ho" >&2');
task.start();
task.then(function(result) {
expect(result).toEqual({stdout: "hi\n", stderr: "ho\n"});
}).catch(function(e) { fail(e); }).then(done);
});
it("specifies command in its name", function() {
var task = new ShellTask("ls");
expect(task.name).toBe("exec ls");
});
it("logs the command, stdout and stderr", function(done) {
var task = new ShellTask('echo "bad" >&2 ; echo "good"');
task.start();
task.then(function() {
expect(task.plainLog).toEqual("good\nbad\n");
}).catch(function(e) { fail(e); }).then(done);
});
it("rejects if exit code is not zero", function(done) {
var task = new ShellTask('exit 13');
task.start();
task.catch(function(error) {
expect(error.code).toEqual(13);
done();
});
});
it("logs stdout and stderr when exit code is not zero", function(done) {
var task = new ShellTask('echo "bad" >&2 ; echo "good"; exit 13');
task.start();
task.catch(function() {
expect(task.plainLog).toContain("good\nbad\n");
done();
});
});
it("respects cwd parameter", function(done) {
var task = new ShellTask('pwd', '/usr/bin');
task.start();
task.then(function(result) {
expect(result.stdout.trim()).toEqual("/usr/bin");
}).catch(function(e) { fail(e); }).then(done);
});
});
|
Yogu/site-manager
|
test/server-unit/shellTaskSpec.js
|
JavaScript
|
gpl-2.0
| 1,497 |
createBinding({
name: "kendoListView",
defaultOption: DATA,
watch: {
data: function(value, options) {
ko.kendo.setDataSource(this, value, options);
}
},
templates: ["template"]
});
|
RUBi-ZA/JMS
|
static/lib/knockout-kendo-master/src/knockout-kendoListView.js
|
JavaScript
|
gpl-2.0
| 228 |
showWord(["v. "," Mache dapre sèten prensip. Se pou ou konfòme ou. 2. Obeyi, obsève prensip."
])
|
georgejhunt/HaitiDictionary.activity
|
data/words/konf~ome.js
|
JavaScript
|
gpl-2.0
| 99 |
/**
* A socket connection to some devopsd daemon. A {DevopsdConnection} is an instanceof {EventEmitter}.
*
* Periodically pings devopsd daemons, and emits events when they respond with data.
*/
var _ = require('lodash'),
util = require('util'),
events = require('events'),
nssocket = require('nssocket');
function DevopsdConnection(options) {
options = _.defaults(options || {}, {
port: 8320
});
var self = this,
socket = this.socket = new nssocket.NsSocket({
// Don't use nssocket reconnect -- exponential backoff, so it will never reconnect if connection goes down for
// a little bit.
// reconnect: true DON'T USE!
});
socket.on('error', function(error) {
self.emit('error', error);
});
function pollForStatus() {
console.log("Polling " + options.port + " for status update");
socket.send('webServer.isProcessUp');
socket.send('webServer.isAcceptingRequests');
}
// Every 5 sec, either try to reconnect or request latest server status
setInterval(function tryReconnect() {
if (!self.isConnected())
return socket.connect(options.port);
pollForStatus();
}, 5000);
socket.on('start', function() {
// On initial connection or subsequent re-connect, send off first few requests
pollForStatus();
});
socket.on('close', function() {
self.isProcessUp = false;
self.isAcceptingRequests = false;
});
// Now register handlers for all devopsd reponses
socket.data('webServer.isProcessUp', function(data) {
if (!data || !data.success) {
return self.emit('error', new Error('Error checking isProcessUp: ' + (data && data.error)));
}
self.isProcessUp = !!data.results;
self.emit('isProcessUp', !!data.results);
});
socket.data('webServer.isAcceptingRequests', function(data) {
if (!data || !data.success) {
return self.emit('error', new Error('Error checking isAcceptingRequests: ' + (data && data.error)));
}
self.isAcceptingRequests = !!data.results;
self.emit('isAcceptingRequests', !!data.results);
});
socket.data('broadcast.webServer.activity', function(data) {
// log activity. data will be 'info', 'warn', or 'error'
self.emit('activity', data);
});
socket.connect(options.port);
}
util.inherits(DevopsdConnection, events.EventEmitter);
DevopsdConnection.prototype.isConnected = function() {
return this.socket.socket && this.socket.connected;
};
module.exports = DevopsdConnection;
|
dlopuch/glow-ops
|
lib/controllers/DevopsdConnection.js
|
JavaScript
|
gpl-2.0
| 2,495 |
showWord(["np. "," 1772-1802. Bòfrè Napoleyon Bonapat. Li te alatèt 45 mil nan sòlda lame franse. Men a tout sa, li pat rive genyen kontwòl koloni an. Nèg yo kraze lame mouche."
])
|
georgejhunt/HaitiDictionary.activity
|
data/words/Lekl~e.js
|
JavaScript
|
gpl-2.0
| 186 |
var searchData=
[
['check',['check',['../classWHtree.html#a668db7c1368f273ef462e44bff2fc91d',1,'WHtree']]],
['cleanup',['cleanup',['../classlistedCache.html#a92febe1b16ddb282d0f5e2ca9eb1c462',1,'listedCache']]],
['clear',['clear',['../classlistedCache.html#add33fbae1be6a7f3aaa6b052587f1619',1,'listedCache']]],
['clearcontainedleaves',['clearContainedLeaves',['../classWHtree.html#a9ba656617bb3102c20f0771afa42bf04',1,'WHtree']]],
['clearnbhood',['clearNbhood',['../classprotoNode.html#ac5c5eaa32ec60fc7564c8c1955c50e1e',1,'protoNode']]],
['clearpartcolors',['clearPartColors',['../classWHtree.html#a788d7d3be48109af762b2fba429a171b',1,'WHtree']]],
['clearpartitions',['clearPartitions',['../classWHtree.html#a764ababf846cb18b5039d35b3dd02051',1,'WHtree']]],
['cnbtreebuilder',['CnbTreeBuilder',['../classCnbTreeBuilder.html#a0ef0e3aef78372fe59c00b449302b174',1,'CnbTreeBuilder']]],
['coarsetree',['coarseTree',['../classWHtreeProcesser.html#a8a2c9af01167829a700c7636cb49c233',1,'WHtreeProcesser']]],
['collapsebranch',['collapseBranch',['../classWHtreeProcesser.html#a800173738287bbb762db126db97a1abd',1,'WHtreeProcesser']]],
['collapsetree',['collapseTree',['../classWHtreeProcesser.html#a87d26ceede0ff0e7c02aa728c735a89c',1,'WHtreeProcesser']]],
['collapsetreelinear',['collapseTreeLinear',['../classWHtreeProcesser.html#a6a8740c021ff7e5c184d4de295022775',1,'WHtreeProcesser']]],
['collapsetreesquare',['collapseTreeSquare',['../classWHtreeProcesser.html#a6e4315fbfb2b28890035d4d4f2176bc0',1,'WHtreeProcesser']]],
['compact2full',['compact2full',['../classfileManager.html#aee236bd074126896cc5dc4e1d5c5a2ee',1,'fileManager']]],
['compacttract',['compactTract',['../classcompactTract.html#a768f98790c79a32ec890c2f8a860b868',1,'compactTract::compactTract()'],['../classcompactTract.html#a0df1b9bb6f933f77cb2a55b549944dec',1,'compactTract::compactTract(std::vector< float > tractInit)'],['../classcompactTract.html#ab370799e5b1892c20e774ece5aae1988',1,'compactTract::compactTract(const compactTract &object)'],['../classcompactTract.html#ae6dd8d553eecc27217c63338eafa155f',1,'compactTract::compactTract(const compactTractChar &charTract)'],['../classcompactTract.html#a62d9323e06f379909a198409b07b4fb3',1,'compactTract::compactTract(const compactTract &tract1, const compactTract &tract2, const size_t size1, const size_t size2)']]],
['compacttractchar',['compactTractChar',['../classcompactTractChar.html#a6c70cebeac0797ccda21fac0ff532d10',1,'compactTractChar::compactTractChar()'],['../classcompactTractChar.html#ab1d7cd1687ea942ff791ec3a8583d87d',1,'compactTractChar::compactTractChar(std::vector< unsigned char > tractInit)'],['../classcompactTractChar.html#a4ad4dd87b23e608f36ce9265d8e0ea67',1,'compactTractChar::compactTractChar(const compactTractChar &object)']]],
['computenorm',['computeNorm',['../classcompactTract.html#a5292a6afd40d42e3686e9beb9d621fd5',1,'compactTract::computeNorm()'],['../classcompactTractChar.html#aef4eb7d55252ec902fae6768d72b133c',1,'compactTractChar::computeNorm()']]],
['convert2grid',['convert2grid',['../classWHtree.html#adbb0438fc5e1f0093a123a0e5c702888',1,'WHtree']]]
];
|
dmordom/hClustering
|
doc/html/search/functions_63.js
|
JavaScript
|
gpl-2.0
| 3,180 |
angular.module('civics.downloader', [])
.service('Downloader', function(){
/**
* Download XLS with filtered initiatives
*/
this.get = function(format, section, selected_categories){
// Check section and build base URL for the query
var base_url = "/api/initiatives_" + format + "?topics=";
if(section == 'events')
base_url = "/api/events_" + format + "?topics=";
// Build url
for(var i in selected_categories.topics){
var topic = selected_categories.topics[i]
if(topic)
base_url += topic.toUpperCase() + ",";
}
if(section == 'initiatives'){
base_url += "&spaces=";
for(var i in selected_categories.spaces){
var space = selected_categories.spaces[i];
if(space)
base_url += space.toUpperCase() + ",";
}
} else {
base_url += "&activities=";
for(var i in selected_categories.activities){
activity = selected_categories.activities[i];
if(activity)
base_url += activity.toUpperCase() + ",";
}
}
base_url += "&agents=";
for(var i in selected_categories.agents){
agent = selected_categories.agents[i];
if(agent)
base_url += agent.toUpperCase() + ",";
}
base_url += "&cities=";
for(var i in selected_categories.cities){
city = selected_categories.cities[i];
if(city)
base_url += city + ",";
}
// Get items in new window
window.open(base_url);
};
return this;
})
|
Ale-/civics
|
static/civics/angular/services/Downloader.js
|
JavaScript
|
gpl-3.0
| 1,711 |
/*
surveys.js
Copyright © 2012 - 2013 WOT Services Oy <info@mywot.com>
This file is part of WOT.
WOT is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
WOT is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with WOT. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
const WOT_PREFIX_ASKED = "wot_asked";
const WOT_FBL_ASKED_RE = new RegExp(WOT_PREFIX_ASKED + "\:(.+)\:(.+)\:status");
const WOT_FBL_ASKED_LOADED = "wot_asked_loaded";
var wot_surveys = {
fbl_form_schema: "//",
storage_file: "storage.json",
// fbl_form_uri: "fbl.local/feedback/1/surveys.html", // for dev only. don't forget to change version!
fbl_form_uri: "api.mywot.com/feedback/1/surveys.html", // don't forget to change version!
re_fbl_uri: null,
wrapper_id: "wot_surveys_wrapper",
pheight: 400,
pwidth: 392,
px: 10,
py: 10,
script_base: "resource://wot-base-dir/",
scripts: [ "libs/jquery.js", "libs/jquery-ui-1.9.2.custom.js",
"injections/wot_proxy.js", "injections/ga_configure.js",
"injections/surveys.widgets.js", "injections/ga_init.js"],
global_calm_period: 3 * 24 * 3600, // Time in seconds after asking a question before we can ask next question
site_calm_period: 10 * 24 * 3600, // delay between asking for the particular website if user hasn't given the feedback yet
site_max_reask_tries: 3, // How many times we can ask a user for the feedback about the website
newuser_period: 14 * 24 * 3600, // Don't ask new users (<14 days)
always_ask: ['api.mywot.com', 'fb.mywot.com'],
always_ask_passwd: "#surveymewot", // this string must be present to show survey in forced way
reset_passwd: "#wotresetsurveysettings", // this string must be present to reset timers and optout
FLAGS: {
none: 0, // a user didn't make any input yet
submited: 1, // a user has given the answer
closed: 2, // a user has closed the survey dialog without givin the answer
optedout: 3 // a user has clicked "Hide forever"
},
survey_url: function()
{
return this.fbl_form_schema + this.fbl_form_uri;
},
load_delayed: function ()
{
this.re_fbl_uri = new RegExp("^" + wot_surveys.fbl_form_uri, "i"); // prepare RegExp once to use often
// Load the JSON stored data about asked websites
if (!wot_surveys.asked.is_loaded()) {
wot_surveys.asked.load_from_file();
}
},
domcontentloaded: function(event)
{
try {
if (!event || !wot_util.isenabled()) {
return;
}
try { // Workaround to resolve "TypeError: can't access dead object" at start of the browser
if (!event.originalTarget) { return; }
} catch (e) { return; }
var content = event.originalTarget,
location = (content && content.location) ? content.location : {};
var is_framed = (content.defaultView && content.defaultView != content.defaultView.top);
// Process framed documents differently than normal ones
if (is_framed) {
if (location) {
// skip all frames except of our own FBL form
if (wot_surveys.re_fbl_uri.test(location.host + location.pathname)) {
// here we found WOT FBL form loaded into a frame. Next step - to inject JS into it.
wot_surveys.inject_javascript(content);
}
}
} else {
// same code as for warning screen
if (!content || !location || !location.href ||
wot_url.isprivate(location.href) || !(/^https?:$/.test(location.protocol))) {
return;
}
var hostname = wot_url.gethostname(location.href);
var warning_type = wot_warning.isdangerous(hostname, false);
// ask only if no big Warning is going to be shown
if (warning_type == WOT_WARNING_NONE|| warning_type == WOT_WARNING_NOTIFICATION) {
wot_surveys.try_show(content, hostname);
}
}
} catch (e) {
dump("wot_surveys.domcontentloaded: failed with " + e + "\n");
}
},
unload: function (event)
{
// dumping global hash table on unloading doesn't work here since wot_hashtable is already unloaded
// wot_surveys.asked.dump_to_file(); // save state to the file
},
get_or_create_sandbox: function(content)
{
var sandbox = content.wotsandbox;
if (!sandbox) {
var wnd = new XPCNativeWrapper(content.defaultView);
sandbox = new Components.utils.Sandbox(wnd);
sandbox.window = wnd;
sandbox.document = sandbox.window.document;
sandbox.__proto__ = sandbox.window;
sandbox.wot_post = wot_search.getsandboxfunc(sandbox, "wot_post", wot_surveys.sandboxapi);
content.wotsandbox = sandbox;
}
return sandbox;
},
load_file: function(file)
{
var str = "";
try {
var ioService = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var scriptableStream = Components
.classes["@mozilla.org/scriptableinputstream;1"]
.getService(Components.interfaces.nsIScriptableInputStream);
var channel = ioService.newChannel(file, null, null);
var input = channel.open();
scriptableStream.init(input);
str = scriptableStream.read(input.available());
scriptableStream.close();
input.close();
} catch (e) {
dump("wot_surveys.load_file(): failed with " + e + "\n");
}
return str;
},
inject_javascript: function (content)
{
var sandbox = wot_surveys.get_or_create_sandbox(content);
var contents = "",
url = "";
// load all scripts and join to one text
for(var i=0; i < wot_surveys.scripts.length; i++) {
url = wot_surveys.script_base + wot_surveys.scripts[i];
contents = wot_surveys.load_file(url);
// run scripts in fbl form-page
try {
Components.utils.evalInSandbox(contents, sandbox);
} catch (e) {
dump("wot_surveys.load_script(): evalInSandbox " +
"failed with " + e + "\n");
}
}
},
inject: function (doc, question)
{
var ws = wot_surveys;
var location = doc.defaultView.location;
// skip params and hash in the URL
question.url = location.protocol + "//" + location.host + location.pathname;
var wrapper = doc.getElementById(ws.wrapper_id);
if(wrapper) {
return;
}
wrapper = doc.createElement("iframe");
wrapper.setAttribute("id", ws.wrapper_id);
if (!wrapper) {
dump("can't add element to DOM / wot.surveys.inject_placeholder()");
return;
}
wrapper.setAttribute("scrolling", "no");
wrapper.setAttribute("style",
"position: fixed; " +
"top: " + ws.py + "px; " +
"left: "+ ws.px +"px;" +
"width: "+ ws.pwidth +"px; " +
"height: "+ ws.pheight +"px; " +
"z-index: 2147483647; " +
"border: none; visibility: hidden;");
wrapper.setAttribute("src", this.survey_url());
var encoded_data = btoa(JSON.stringify(question));
// Probably in FF we should transfer data to the frame by injecting it as JS (json) object instead of
// relying to "name" property
wrapper.setAttribute("name", encoded_data); // transfer question's data via "name" property of iframe
wot_browser.attach_element(wrapper, doc.defaultView); // attach iframe wrapper to DOM
},
try_show: function (doc, hostname)
{
try {
var url = doc.defaultView.location.href;
// test url for RESET command
if (wot_surveys.always_ask.indexOf(hostname) >= 0 && url && url.indexOf(wot_surveys.reset_passwd) >= 0) {
wot_surveys.reset_settings(hostname);
return;
}
var question = wot_surveys.get_question(hostname);
if (this.is_tts(hostname, url, question.question)) {
this.inject(doc, question);
}
} catch (e) {
dump("wot_surveys.try_show() failed with " + e + "\n");
}
},
reset_settings: function (hostname)
{
var ws = wot_surveys;
ws.asked.set_loaded();
ws.opt_out(false); // reset opt-out
// reset the list of websites asked about
ws.asked.enumerate(function(hostname, question_id) {
ws.asked.remove(hostname, question_id, "time");
ws.asked.remove(hostname, question_id, "count");
ws.asked.remove(hostname, question_id, "status");
});
ws.asked.dump_to_file();
ws.set_lasttime_asked(false); // reset last time to empty
},
remove_form: function (sandbox, timeout)
{
try {
timeout = timeout || 100;
window.setTimeout(function () {
var wrapper = wot_surveys.get_wrapper(sandbox);
if (wrapper) {
wrapper.parentNode.removeChild(wrapper);
}
}, timeout);
} catch (e) {
dump("wot_surveys.remove_form() failed with " + e + "\n");
}
},
get_question: function (hostname)
{
try {
var question_id = wot_cache.get(hostname, "question_id");
var question_text = wot_cache.get(hostname, "question_text");
var dismiss_text = wot_cache.get(hostname, "dismiss_text");
var choices_number = wot_cache.get(hostname, "choices_number");
if (choices_number > 0) {
var question = {
target: hostname,
decodedtarget: wot_idn.idntoutf(hostname),
question: {
id: question_id,
text: question_text,
dismiss_text: dismiss_text,
choices: []
}
};
for(var i= 0, v, t; i < choices_number; i++) {
v = wot_cache.get(hostname, "choice_value_" + i);
t = wot_cache.get(hostname, "choice_text_" + i);
question.question.choices.push({ value: v, text: t });
}
return question;
} else {
return {};
}
} catch (e) {
return {};
}
},
is_tts: function (hostname, url, question)
{
var ws = wot_surveys;
try {
if(!wot_surveys.asked.is_loaded()) return false; // data isn't ready for process
// dump("if(!wot_surveys.asked.is_loaded()) passed.\n");
if(!(question && question.id !== undefined && question.text && question.choices)) {
// no question was given for the current website - do nothing
// dump("is_tts: empty or no question test NOT PASSED\n");
return false;
}
// dump("is_tts: question test passed.\n");
// on special domains we should always show the survey if there is a special password given (for testing purposes)
// e.g. try this url http://api.mywot.com/test.html#surveymewot
if (ws.always_ask.indexOf(hostname) >= 0 && url && url.indexOf(ws.always_ask_passwd) >= 0) {
// dump("is_tts: Magic 'always show' test PASSED\n");
return true;
}
if (ws.is_optedout() || !wot_prefs.getBool("feedback_enabled", true)) {
// dump("is_tts: Opted-out test NOT PASSED\n");
return false;
}
// check if have asked the user more than X days ago or never before
var lasttime = ws.get_lasttime_asked();
if (lasttime && wot_util.time_since(lasttime) < ws.global_calm_period) {
// dump("is_tts: Last time test NOT PASSED\n");
return false;
}
var firstrun_time = wot_util.time_sincefirstrun();
if (firstrun_time && firstrun_time < ws.newuser_period) {
// dump("is_tts: old user test NOT PASSED\n");
return false;
}
// check whether we already have asked the user about current website
var asked_status = ws.asked.get(hostname, question.id, "status");
var asked_time = ws.asked.get(hostname, question.id, "time");
var asked_count = ws.asked.get(hostname, question.id, "count");
if (asked_status === ws.FLAGS.submited) {
// dump("is_tts: 'Already gave feedback for the website' test NOT PASSED\n");
return false;
}
// all other statuses ("closed" and "none") are subject to show FBL again after delay
if (asked_count >= ws.site_max_reask_tries) {
// dump("is_tts: Max asked times NOT PASSED\n");
return false;
}
// If we have never showed the FBL for this site before, or more than "delay"
if (!(asked_time === null || wot_util.time_since(asked_time) >= ws.site_calm_period)) {
// dump("is_tts: 'Calm delay for the website' test NOT PASSED\n");
return false;
}
// dump("is_tts: already asked test passed -> show it!\n");
return true;
} catch (e) {
dump("wot_surveys.is_tts() failed with " + e + "\n");
return false;
}
},
is_optedout: function()
{
return wot_prefs.getBool("feedback_optedout", false);
},
opt_out: function(value)
{
value = (value === undefined) ? true : value;
wot_prefs.setBool("feedback_optedout", value);
},
remember_asked: function(target, question_id, status) {
var ws = wot_surveys;
try {
status = status === undefined ? ws.FLAGS.none : status;
var count = ws.asked.get(target, question_id, "count") || 0;
ws.asked.set(target, question_id, "status", status);
ws.asked.set(target, question_id, "time", new Date());
ws.asked.set(target, question_id, "count", count + 1); // increase counter of times FBL has been shown
ws.asked.dump_to_file();
} catch (e) {
console.error("remember_asked() failed with", e);
}
},
save_asked_status: function (data, status) {
var ws = wot_surveys;
try {
if (data && data.target && data.question_id) {
ws.remember_asked(data.target, data.question_id, status);
// we remember the last time of user's interaction with FBL
ws.set_lasttime_asked();
}
} catch (e) {
dump("wot_surveys.save_asked_status() failed with " + e + "\n");
}
},
get_lasttime_asked: function () {
try {
var lasttime = wot_prefs.getChar("feedback_lasttimeasked", null);
if(lasttime) {
return new Date(lasttime);
}
} catch (e) {
dump("wot_surveys.get_lasttime_asked() failed with " + e + "\n");
}
return null;
},
set_lasttime_asked: function (time) {
if (time === undefined) {
time = new Date();
}
if (time === false) {
time = "";
}
wot_prefs.setChar("feedback_lasttimeasked", String(time));
},
get_top_content: function (sandbox)
{
var top = null;
if(sandbox && sandbox.window && sandbox.window.top) {
top = sandbox.window.top; // look into top content window document
}
return top;
},
get_wrapper: function (sandbox)
{
var wrapper = null;
try {
var top = wot_surveys.get_top_content(sandbox);
if(top && top.document) {
wrapper = top.document.getElementById(wot_surveys.wrapper_id);
if(!wrapper) {
dump("wot_surveys.get_wrapper(): can't find FBL wrapper in the document\n");
}
}
} catch (e) {
dump("wot_surveys.get_wrapper() failed with " + e + "\n");
}
return wrapper;
},
reveal_form: function (sandbox)
{
var wrapper = wot_surveys.get_wrapper(sandbox);
if (wrapper) {
var style = wrapper.getAttribute("style") || "";
if (style) {
style = style.replace(/^(.*visibility: )(hidden;)(.*)$/, "$1visible;$3"); // replace hidden -> visible
wrapper.setAttribute("style", style);
}
}
},
dispatch: function (message, data, sandbox)
{
switch(message) {
case "shown": // FBL form was shown
wot_surveys.reveal_form(sandbox); // make iframe visible
wot_surveys.save_asked_status(data, wot_surveys.FLAGS.none);
break;
case "close": // FBL is asking to close it
// data.target
wot_surveys.save_asked_status(data, wot_surveys.FLAGS.closed);
wot_surveys.remove_form(sandbox);
break;
case "optout": // FBL says the user wants to opt-out from the feedback loop.
// data.target
wot_surveys.opt_out(); // store setting
wot_surveys.save_asked_status(data, wot_surveys.FLAGS.optedout);
wot_surveys.remove_form(sandbox);
break;
case "submit":
// data.target, .url, .question_id, .answer
wot_api_feedback.send(data.url, data.question_id, data.answer);
wot_surveys.save_asked_status(data, wot_surveys.FLAGS.submited);
wot_surveys.remove_form(sandbox, 1500); // wait a bit to show "thank you!"
break;
}
},
// This is a wrapper around functions that might be called from the injected JS
sandboxapi: {
wot_post: function (sandbox, data_json) {
// this func is called from /content/injections/wot_proxy.js : wot.post()
try {
// try un-json data (DON'T call any methods of data_json since it is unsafe!)
var data = JSON.parse(data_json);
// dump("wot_surveys.sandpoxapi.wot_post(): " + JSON.stringify(data) + "\n");
if (data && data.message && data.data) {
wot_surveys.dispatch(data.message, data.data, sandbox);
}
} catch (e) {
dump("wot_surveys.sandboxapi.wot_post(): failed with " + e + "\n");
}
}
},
asked: {
is_loaded: function () {
var res = wot_hashtable.get(WOT_FBL_ASKED_LOADED);
return !!res;
},
set_loaded: function () {
wot_hashtable.set(WOT_FBL_ASKED_LOADED, true);
},
get: function (hostname, question_id, prop) {
var name = wot_surveys.asked._get_name(hostname, question_id, prop),
res = null;
if (name) {
res = wot_hashtable.get(name);
} else {
// dump("wot_survey.asked._get_name() returned NULL\n");
}
return res;
},
set: function (hostname, question_id, prop, value) {
var name = wot_surveys.asked._get_name(hostname, question_id, prop);
if (name) {
wot_hashtable.set(name, value);
// dump("HashT_set: " + name + " == " + value + "\n");
} else {
// dump("wot_survey.asked._get_name() returned NULL\n");
}
},
remove: function (hostname, question_id, prop) {
var name = wot_surveys.asked._get_name(hostname, question_id, prop);
wot_hashtable.remove(name);
},
_get_name: function (hostname, question_id, prop) {
// makes a string indentifier like "mywot.com:12345:status"
var cn = wot_idn.utftoidn(hostname);
if (!cn) {
return null;
}
return WOT_PREFIX_ASKED + ":" + cn + ":" + String(question_id) + ":" + prop;
},
_extract_name: function (element) {
try {
if (!element || !element.QueryInterface) {
return null;
}
var property =
element.QueryInterface(Components.interfaces.nsIProperty);
if (!property) {
return null;
}
// enumerate only records with property 'status'
if (property.name.lastIndexOf(":status") < 0) {
return null;
}
var match = property.name.match(WOT_FBL_ASKED_RE);
if (!match || !match[1] || !match[2]) {
return null;
}
return {
name: match[1],
question_id: match[2]
};
} catch (e) {
dump("wot_cache.get_name_from_element: failed with " + e + "\n");
}
return null;
},
enumerate: function (func) {
var ws = wot_surveys,
hash = wot_hashtable.get_enumerator();
while (hash.hasMoreElements()) {
var name_question = ws.asked._extract_name(hash.getNext());
if (name_question) {
var name = name_question.name,
question_id = name_question.question_id;
if (name) {
func(name, question_id);
}
}
}
},
load_from_file: function () {
wot_file.read_json(wot_surveys.storage_file, function (data, status) {
try {
if (data && data.asked) {
for (var hostname in data.asked) {
var questions = data.asked[hostname];
for (var question_id in questions) {
var qd = questions[question_id];
if (qd) {
var time = qd['time'];
var status = qd['status'];
var count = qd['count'] || 0;
if (time && status !== null) {
wot_surveys.asked.set(hostname, question_id, "status", status);
wot_surveys.asked.set(hostname, question_id, "time", time);
wot_surveys.asked.set(hostname, question_id, "count", count);
}
}
}
}
} else {
// dump("FBL: no data in file storage found\n");
}
} catch (e) {
dump("wot_surveys.load_from_file() failed with " + e + "\n");
}
wot_surveys.asked.set_loaded(); // set this flag anyway to indicate that loading finished
});
},
dump_to_file: function () {
var ws = wot_surveys, _asked = {};
try {
ws.asked.enumerate(function (name, question_id) {
if (!_asked[name]) {
_asked[name] = {};
}
_asked[name][question_id] = {
status: ws.asked.get(name, question_id, "status"),
time: ws.asked.get(name, question_id, "time"),
count: (ws.asked.get(name, question_id, "count") || 0)
};
});
var storage = {
asked: _asked
};
wot_file.save_json(wot_surveys.storage_file, storage); // and dump to file
} catch (e) {
dump("wot_surveys.asked.dump_to_file() failed with " + e + "\n");
}
}
}
};
wot_modules.push({ name: "wot_surveys", obj: wot_surveys });
|
mywot/firefox-xul
|
content/surveys.js
|
JavaScript
|
gpl-3.0
| 20,641 |
var INFO_MESSAGE = "[INFO] ";
var ERROR_MESSAGE = "[ERROR] ";
var WARNING_MESSAGE = "[WARN] ";
var SUCCESS_MESSAGE = "[SUCCESS] ";
var UNDEFINED_MESSAGE = "[???] ";
function getInfoMessage(type, message){
console.log(checkTypeMessage(type) + message);
}
function checkTypeMessage(type){
switch(type){
case "error" :return ERROR_MESSAGE;
case "info" :return INFO_MESSAGE;
case "warn" :return WARNING_MESSAGE;
case "success" :return SUCCESS_MESSAGE;
default :return UNDEFINED_MESSAGE;
}
}
|
MatheusMFranco/ALREADYHAS-Elysium
|
Implementation/Elysium-Web/src/main/webapp/assets/js/logMessage.js
|
JavaScript
|
gpl-3.0
| 513 |
/**
* Play JavaScript routing as an AngularJS module.
* Wraps Play's routes to use Angular's $http.
* Example:
* {{{
* // For `POST /login controller.Application.login()` Play generates:
* jsRoutes.controllers.Application.login()
* // With playRoutes, this can be used like this:
* playRoutes.controllers.Application.login().post({user:"username", password:"secret"}).then(function(response) {
* ...
* )};
* }}}
* @author Marius Soutier, 2013
*/
define(["angular", "require", "jsRoutes"], function(angular, require, jsRoutes) {
"use strict";
// The service - will be used by controllers or other services, filters, etc.
var mod = angular.module("common.playRoutes", []);
mod.service("playRoutes", ["$http", function($http) {
/**
* Wrap a Play JS function with a new function that adds the appropriate $http method.
* Note that the url has been already applied to the $http method so you only have to pass in
* the data (if any).
* Note: This is not only easier on the eyes, but must be called in a separate function with its own
* set of arguments, because otherwise JavaScript's function scope will bite us.
* @param playFunction The function from Play's jsRouter to be wrapped
*/
var wrapHttp = function(playFunction) {
return function(/*arguments*/) {
var routeObject = playFunction.apply(this, arguments);
var httpMethod = routeObject.method.toLowerCase();
var url = routeObject.url;
var res = {
method: httpMethod,
url: url,
absoluteUrl: routeObject.absoluteURL,
webSocketUrl: routeObject.webSocketURL
};
res[httpMethod] = function(obj) {
return $http[httpMethod](url, obj);
};
return res;
};
};
// Add package object, in most cases "controllers"
var addPackageObject = function(packageName, service) {
if (!(packageName in service)) {
service[packageName] = {};
}
};
// Add controller object, e.g. Application
var addControllerObject = function(packageName, controllerKey, service) {
if (!(controllerKey in service[packageName])) {
service[packageName][controllerKey] = {};
}
};
var playRoutes = {};
// Loop over all items in the jsRoutes generated by Play, wrap and add them to playRoutes
for (var packageKey in jsRoutes) {
var packageObject = jsRoutes[packageKey];
addPackageObject(packageKey, playRoutes);
for (var controllerKey in packageObject) {
var controller = packageObject[controllerKey];
addControllerObject(packageKey, controllerKey, playRoutes);
for (var controllerMethodKey in controller) {
playRoutes[packageKey][controllerKey][controllerMethodKey] =
wrapHttp(controller[controllerMethodKey]);
}
}
}
return playRoutes;
}]);
return mod;
});
|
myclabs/CarbonDB-UI
|
app/assets/javascripts/common/services/playRoutes.js
|
JavaScript
|
gpl-3.0
| 2,930 |
import path from 'node:path';
import { promises as fsP } from 'node:fs';
import { promisify } from 'node:util';
import glob from 'glob';
import { metaHelper, moduleExists } from '@sweet-milktea/utils';
import parser from './parser.js';
import lessCode from './lessCode.js';
const globPromise = promisify(glob);
const { __dirname } = metaHelper(import.meta.url);
/* 提取antd的less路径并生成css文件 */
async function main() {
// 获取所有的tsx文件
const cwd48tools = path.join(__dirname, '../../48tools/src');
const files = await globPromise('**/*.tsx', { cwd: cwd48tools });
// 查找antd组件
const antdComponents = await parser(cwd48tools, files);
// 生成less文件
const css = await lessCode(antdComponents);
const distDir = path.join(__dirname, '../dist');
// 代码高亮的暗黑主题样式
const hljsPath = path.join(moduleExists('highlight.js'), '../..', 'styles/atom-one-dark.css');
const hljsCss = await fsP.readFile(hljsPath, { encoding: 'utf8' });
await fsP.mkdir(distDir);
await fsP.writeFile(path.join(distDir, 'dark-theme.css'), `/*! @48tools 暗黑模式css文件 !*/\n${ css }\n${ hljsCss }`);
}
main();
|
duan602728596/48tools
|
packages/darkTheme/src/index.js
|
JavaScript
|
gpl-3.0
| 1,172 |
var path = require('path');
module.exports = {
GetFileName: function (filepath) {
var base_fl_name = path.basename(filepath);
var filename = base_fl_name.substr(0, base_fl_name.lastIndexOf('.')) || base_fl_name;
return filename;
},
GetExtension: function (filename) {
var ext = path.extname(filename||'').split('.');
return ext[ext.length - 1];
}
};
|
gmontalvoriv/mailock
|
lib/file_modules/file_info.js
|
JavaScript
|
gpl-3.0
| 379 |
'use strict';
module.exports = {
url: function(){
return this.api.launchUrl + '/#signin';
},
sections: {
menu: require( './menu' ),
content: {
selector: "#core-signin-view",
elements: {
"signinBtn": ".login-btn",
"passwordForgottenBtn": ".password-forgotten-btn",
"emailInput": "input#email",
"passwordInput": "input#password",
"tutorialBtn": "a[href='#tutorial']",
"uploadsBtn": "a[href='#uploads']",
"assessBtn": "a[href='#assess']",
"resultsBtn": "a[href='#results']"
}
}
},
commands: [
{
signinUser: function( user ){
return this.section.content
.setValue( '@emailInput', user.email )
.setValue( '@passwordInput', user.password )
.click( '@signinBtn' )
.waitForElementNotPresent( '@signinBtn', 20000 )
;
}
}
]
};
|
d-pac/d-pac.client
|
tests/e2e/pages/signin.js
|
JavaScript
|
gpl-3.0
| 1,095 |
var searchData=
[
['timer_2ec',['timer.c',['../timer_8c.html',1,'']]],
['timer_2ed',['timer.d',['../timer_8d.html',1,'']]],
['timer_2eh',['timer.h',['../timer_8h.html',1,'']]],
['timer_5fcommon_5fall_2ec',['timer_common_all.c',['../timer__common__all_8c.html',1,'']]],
['timer_5fcommon_5fall_2ed',['timer_common_all.d',['../timer__common__all_8d.html',1,'']]],
['timer_5fcommon_5fall_2eh',['timer_common_all.h',['../timer__common__all_8h.html',1,'']]]
];
|
Aghosh993/TARS_codebase
|
libopencm3/doc/stm32f1/html/search/files_e.js
|
JavaScript
|
gpl-3.0
| 467 |
/**
* @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function (config) {
config.extraPlugins = 'cms-imagemanager,cms-filemanager,cms-dynamicregion,cms-togglelinewrap,cms-modelvalues,aceeditor,cms-widget,cms-option';
config.toolbar = [
['Undo', 'Redo'],
['Link', 'Unlink'],
['Bold', 'Italic', 'Underline'],
['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
['BulletedList', 'NumberedList'],
['CmsModelValues'],
['CmsImageManager', 'CmsFileManager', 'Image'],
['CmsDynamicRegion', 'CmsWidget', 'CmsOption'],
['Source', 'Maximize', 'CmsToggleLineWrap'],
'/',
['Styles'],
['Format'],
['Font'],
['FontSize'],
['Copy', 'Cut', 'Paste', 'PasteFromWord'],
['Strike', 'SpecialChar', 'Table']
];
config.skin = 'bettercms';
config.removePlugins = 'tabletools';
config.disableNativeSpellChecker = false;
config.allowedContent = true;
config.extraAllowedContent = 'div[class]';
config.autoParagraph = false;
config.toolbarCanCollapse = true;
config.forcePasteAsPlainText = true;
};
|
devbridge/BetterCMS
|
Modules/BetterCms.Module.Root/Scripts/ckeditor/config.js
|
JavaScript
|
gpl-3.0
| 1,293 |
/**
* Copyright 2015 Sky Wickenden
*
* This file is part of StreamBed.
* An implementation of the Babbling Brook Protocol.
*
* StreamBed is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* at your option any later version.
*
* StreamBed is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with StreamBed. If not, see <http://www.gnu.org/licenses/>
*
* @fileOverview Used to create the CodeMirror editor for displaying the Rhythms.
* @author Sky Wickenden
*/
/**
* @namespace Used to create the CodeMirror editor for displaying the Rhythms.
* @package JS_Client
*/
BabblingBrook.Client.Component.CodeMirror = (function () {
'use strict';
var j_code_mirror;
return {
create : function () {
// If the code is shown straight away it sometimes errors when loaded through ajaxurl.
// Not worked out what causes this.
// As a stop gap the code is shown in a fake loading element and displayed after 1 second.
setTimeout(function () {
if (typeof CodeMirror.defineOption !== 'function') {
BabblingBrook.Client.Component.CodeMirror.construct();
return;
}
var read_only = false;
var theme = 'default';
var is_private = jQuery.trim(jQuery('#rhythm_status').text()) === "Private";
var is_view_page = jQuery('#view_details').length > 0;
var is_create_page = jQuery('#create_rhythm_form').val() === 'true';
if ((is_private === false || is_view_page === true) && is_create_page === false) {
read_only = true;
theme = 'disabled';
}
var dom_editor;
dom_editor = jQuery('#rhythm_javascript').get(0);
CodeMirror.keyMap.tabSpace = {
Tab: function(cm) {
cm.replaceSelection(" ", "end", "+input");
},
fallthrough: ['default']
};
var config = {
value : "function myScript(){return 100;}\n",
lineNumbers : true,
matchBrackets : true,
tabSize : 4,
indentWithTabs : false,
readOnly : read_only,
theme : theme,
mode : 'javascript',
indentUnit : 4,
keyMap: 'tabSpace',
viewportMargin : Infinity
}
jQuery('#rhythm_javascript').removeClass('hidden').parent().removeClass('block-loading');
j_code_mirror = CodeMirror.fromTextArea(dom_editor, config);
/* This is necessary so that the real textbox is repopulated before ajaxurl serializes the form */
jQuery('#save_rhythm').click(function() {
j_code_mirror.save();
});
}, 30);
},
/*
* Exposed publicly so that selenium can edit it for testing.
*
* @return void
*/
setValue : function(text) {
j_code_mirror.setValue(text);
},
/*
* Exposed publicly so that selenium can get it for testing.
*
* @return string
*/
getValue : function() {
return j_code_mirror.getValue();
}
};
}());
|
babbling-brook/streambed
|
js/Client/Component/CodeMirror.js
|
JavaScript
|
gpl-3.0
| 3,894 |
var searchData=
[
['welcome',['Welcome',['../classUi__Widget.html#acd80be5365bb876d562abced34124d16',1,'Ui_Widget']]],
['widget_5f8cpp',['widget_8cpp',['../widget__8cpp_8js.html#a1bc5bc969cbc93541cf2ea73705bc3a9',1,'widget_8cpp.js']]],
['widget_5f8h',['widget_8h',['../widget__8h_8js.html#ae9cebfd6f1dcbcaae1bcf80cd007313b',1,'widget_8h.js']]]
];
|
shinshipower/pd2-Taiko
|
html/search/variables_10.js
|
JavaScript
|
gpl-3.0
| 353 |
// PngMagic minimal server script (server will be active on port 83)
// Waits for CarSentry to send a request, then pokes CarSentry.js to time the next WebSocket open at the optimum time
localPort = 83
Http.Close()
Http.Server(localPort)
function OnCall( msg, cl, path )
{
switch(msg)
{
case 'HTTPREQ':
Pm.Echo('Remote IP: ' + Http.IP + ' URL: ' + path)
if(path == '/')
{
for(i = 0; i < Http.ParamCount; i++)
{
Pm.Echo('Param ' + i + ': ' + Http.Params(i, 0) + ' = ' + Http.Params(i, 1) )
}
sendPage('Server Stuff')
}
else if(path == '/car')
Pm.CarSentry('CHECK', Http.IP, Http.Params(0,1), Http.Params(1,1) )
else Http.Send( "HTTP/1.1 404 Not Found\r\n\r\n" )
break
case 'HTTPDATA':
Pm.Echo('Data from ' + cl + ' : ' + path)
break
case 'HTTPSENT':
Pm.Echo('Sent ' + cl + ' ' + path)
break
case 'HTTPSTATUS':
Pm.Echo('HTTP Server Status ' + cl)
break
}
}
function sendPage(title)
{
s = 'HTTP/1.1 200 OK\r\n\r\n'
s += '<!DOCTYPE html><html lang="en"><head><meta name="viewport" content="width=device-width, initial-scale=1"/><title>' +
title + '</title>'
s += "<style>div,input {margin-bottom: 5px;}body{width:250px;display:block;margin-left:auto;margin-right:auto;text-align:right;}</style>"
s += '<body>'
s += 'Logged IP: ' + Http.IP + '<br>'
s += '</body></html>'
Http.Send(s)
}
|
CuriousTech/WiFi-Car-Sentry
|
Server.js
|
JavaScript
|
gpl-3.0
| 1,367 |
var ViewModule = require( './view-module' );
module.exports = ViewModule.extend( {
getDefaultSettings: function() {
return {
container: null,
items: null,
columnsCount: 3,
verticalSpaceBetween: 30,
};
},
getDefaultElements: function() {
return {
$container: jQuery( this.getSettings( 'container' ) ),
$items: jQuery( this.getSettings( 'items' ) ),
};
},
run: function() {
var heights = [],
distanceFromTop = this.elements.$container.position().top,
settings = this.getSettings(),
columnsCount = settings.columnsCount;
distanceFromTop += parseInt( this.elements.$container.css( 'margin-top' ), 10 );
this.elements.$items.each( function( index ) {
var row = Math.floor( index / columnsCount ),
$item = jQuery( this ),
itemHeight = $item[ 0 ].getBoundingClientRect().height + settings.verticalSpaceBetween;
if ( row ) {
var itemPosition = $item.position(),
indexAtRow = index % columnsCount,
pullHeight = itemPosition.top - distanceFromTop - heights[ indexAtRow ];
pullHeight -= parseInt( $item.css( 'margin-top' ), 10 );
pullHeight *= -1;
$item.css( 'margin-top', pullHeight + 'px' );
heights[ indexAtRow ] += itemHeight;
} else {
heights.push( itemHeight );
}
} );
},
} );
|
FrankM1/qazana
|
assets/dev/js/utils/masonry.js
|
JavaScript
|
gpl-3.0
| 1,328 |
var interrupt = {
step:function(){
memory.mapper.irqStep();
},
};
|
dgibb/MOES
|
Emulators/src/NES/interrupt.js
|
JavaScript
|
gpl-3.0
| 74 |
var isnew1=false;//判定newPwd是否符合规范
var isnew2=false;//判定newPwd2是否和newPwd一致
var oldpwds=$("#pwdhid").html();
$(function(){
var newPwd=$("#newPwd");
var newPwd2=$("#newPwd2");
var btn=$("#pwdBtn");
newPwd.blur(function(){ //新密码框的失焦事件
var pwd=newPwd.val();
if((pwd.length<6 || pwd.length>20) && pwd.length>0){
$("#newp1").text("密码长度不符合规则!!!").css("color","red");
newPwd.val("");
isnew1=false;
} else if(pwd=="" || pwd==null){
$("#newp1").text("");
isnew1=false;
} else{
$("#newp1").text("密码符合!!!").css("color","green");
isnew1=true;
}
});
newPwd2.blur(function(){ //新密码确认框的失焦事件
var pwd=newPwd.val();
var pwd2=newPwd2.val();
if(pwd2!=pwd){
$("#newp2").text("密码不相同,请重新输入!!!").css("color","red");
newPwd2.val("");
btn.attr("disabled",true);
isnew2=false;
} else if(pwd2=="" || pwd2==null){
$("#newp2").text("");
isnew2=false;
} else{
$("#newp2").text("密码符合!!!").css("color","green");
btn.attr("disabled",false);
isnew2=true;
}
});
});
function updateAdminPwd(){
var yuanPwd=$("#yuanPwd").val();
if(yuanPwd!=oldpwds){
$("#oldp").text("原密码错误,请重新输入!!!").css("color","red");
}else if(isnew1&&isnew2){
$.messager.confirm('信息确认','您确定要修改密码吗 ?',function(r){
if(r){
var nePwd=$("#newPwd").val();
var adNo=$("#aidhid").html();
$.post("admin_updatepwd",{aPwd:nePwd,aId:adNo},function(data){
data=parseInt($.trim(data));
if(data>0){
$.messager.show({
title:'修改提示',
msg:'管理员密码修改成功....',
timeout:2000,
showType:'slide'
});
/*location.href="index.jsp";*/
location.reload(true);
}else{
$.messager.alert('失败提示','管理员密码修改失败....','error');
}
});
}
});
}
}
|
dreampeople123/muke
|
MuKe/src/main/webapp/easyui/js/password.js
|
JavaScript
|
gpl-3.0
| 2,025 |
jQuery(document).ready(function (){
if (needToCheckCookie()){
show_cookie_bar();
var cookie_bar = jQuery('#cg_cookie_bar');
var cfTimeout = cookie_bar.data('timeout');
var cfScrollout = cookie_bar.data('scrollout');
cookie_bar.find('.close').click(function (){
cookies_accepted();
return false;
});
jQuery('a').not('.no-cookie-accept').click(cookies_accepted);
var isException = cookie_bar.hasClass('exception');
if (!isException){
setTimeout(function (){
cookies_accepted();
},cfTimeout*1000);
jQuery(window).scroll(function (){
if (jQuery(window).scrollTop()>cfScrollout){
cookies_accepted();
}
});
}
insertTemplatesDenied();
} else {
cookies_accepted();
}
});
function cookies_accepted(){
if (typeof(accepted)=='undefined' || !accepted){
accepted = true;
accept_cookies();
hide_cookie_bar();
jQuery('a').unbind('click',cookies_accepted);
insertTemplatesAccepted();
}
}
function show_cookie_bar(){
jQuery('html').css({
'margin-top': jQuery('#cg_cookie_bar').outerHeight()
});
jQuery('#cg_cookie_bar').show();
}
function hide_cookie_bar(){
jQuery('html').animate({
'margin-top': 0
});
//~ jQuery('#cg_cookie_bar').slideUp();
jQuery('#cg_cookie_bar').fadeOut();
}
function accept_cookies(){
setCookie('cg_cookie_accepted','1',365);
}
function setCookie(c_name,value,exdays){
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function needToCheckCookie(){
var userDate = new Date();
var timezone = -(userDate.getTimezoneOffset()/60);
var cookie_preset = document.cookie.indexOf('cg_cookie_accepted=1') >= 0;
var result = timezone>=0 && timezone<=3 && !cookie_preset;
return result;
}
function insertTemplatesAccepted(){
insertTemplates('accepted');
}
function insertTemplatesDenied(){
insertTemplates('denied');
}
function insertTemplates(sufix){
jQuery('head').append(parseTemplate('cg_cf_head_template_' + sufix));
jQuery('body').append(parseTemplate('cg_cf_foot_template_' + sufix));
}
function parseTemplate(template){
var code = jQuery('#'+template).html().replace('/*!*','').replace('*!*/','').replace('/!*','/*').replace('*!/','*/').replace('<!/script','</script');
return code;
}
|
cartograf/cartograf-cookie-filter
|
script.js
|
JavaScript
|
gpl-3.0
| 2,643 |
const EventEmitter = require('events').EventEmitter;
const request = require('request');
const WebSocketClient = require('websocket').client;
export const SLACK_API = 'https://slack.com/api/';
export default class SlackAPI extends EventEmitter {
constructor(token, screen) {
super();
this.screen = screen; // used only for logging here
this.token = token;
this.users = {};
this.channels = {};
this.messages = [];
this.rtm = null;
this.init();
}
init() {
this.fetchUsers();
this.connectRTM();
}
connectRTM() {
this.rtm = new WebSocketClient();
this.get('rtm.connect', {}, (err, resp, body) => {
if (err || !body.ok) {
this.screen.log("API: rtm.connect failed");
this.screen.log(err);
this.screen.log(body);
console.log("Failed connecting to slack. See log for details.");
process.exit(1);
return;
}
this.rtm.on('connect', (connection) => {
connection.on('error', function(error) {
console.log("Connection Error: " + error.toString());
});
connection.on('message', (message) => {
const data = message.utf8Data;
const obj = JSON.parse(data);
this.messages.push(obj);
this.emit('message', obj);
// Used only for MessagesList, so that we can removeALlListeners('receive message')
// without interfering with other listeners that need messages
this.emit('receive message', obj);
if (this.channels[obj.channel]) {
if (typeof this.channels[obj.channel].history === 'undefined') {
this.channels[obj.channel].history = {messages: []};
}
if (typeof this.channels[obj.channel].history.messages === 'undefined') {
this.channels[obj.channel].history.messages = [];
}
this.channels[obj.channel].history.messages.unshift(obj);
this.screen.log("API: Added message to channel history, now " + this.channels[obj.channel].history.messages.length + " messages in " + obj.channel);
} else {
this.screen.log("API: couldn't add message to channel history, channel does not exist " + obj.channel);
this.screen.log(obj);
}
});
});
this.rtm.on('connectFailed', function(error) {
console.log('Connect Error: ' + error.toString());
});
this.rtm.connect(body.url);
});
}
getChannelDisplayName(channel) {
let display_name = channel.name || '';
if (channel.is_im) {
display_name = '@' + this.getUserName(channel.user);
} else if (channel.is_mpim) {
display_name = '@' + display_name
.replace('mpdm-', '')
.replace('-1', '')
.replace(/--/g, ', ');
} else if (channel.is_channel || channel.is_private) {
display_name = '#' + display_name;
}
return display_name;
}
markChannelRead(channel, callback) {
let endpoint = 'channels.mark';
if (channel.is_im) endpoint = 'im.mark';
else if (channel.is_private) endpoint = 'groups.mark';
else if (channel.is_mpim) endpoint = 'mpim.mark';
if (this.channels[channel.id] && this.channels[channel.id].history && this.channels[channel.id].history.messages && this.channels[channel.id].history.messages.some(m => typeof m.ts !== 'undefined')) {
let mostRecentMessages = this.channels[channel.id].history.messages.filter(m => typeof m.ts !== 'undefined').sort((a, b) => {
let ats = 0;
let bts = 0;
if (a.ts) ats = parseFloat(a.ts);
if (b.ts) bts = parseFloat(b.ts);
return ats < bts ? 1 : -1;
});
let mostRecentMessage = mostRecentMessages[0];
const payload = {channel: channel.id, ts: mostRecentMessage.ts};
this.screen.log("API: Marking channel as read");
this.screen.log(mostRecentMessage);
this.screen.log(JSON.stringify(payload));
this.post(endpoint, payload, (err, resp, body) => {
this.screen.log("API: Marking channel as read got response");
this.screen.log(JSON.stringify(body));
if (typeof callback === 'function') callback(body);
});
} else {
this.screen.log("API: Couldn't mark channel " + channel.id + " as read");
this.screen.log(JSON.stringify(this.channels[channel.id]));
this.screen.log(JSON.stringify(Object.keys(this.channels)));
}
}
fetchChannelHistory(channel, callback) {
this.screen.log("API: Fetching channel history for " + channel.id);
return this.get(
'conversations.history',
{channel: channel.id},
(err, resp, body) => {
if (err) {
this.screen.log("Error fetching history");
this.screen.log(err);
}
this.channels[channel.id].history = body;
if (typeof callback === 'function') callback(body);
}
);
}
getUser(id) {
return this.users[id] || {id, name: id};
}
getUserName(id) {
return this.getUser(id).name;
}
postMessage(channel, text, callback) {
this.post('chat.postMessage', {channel: channel.id, text, as_user: true, link_names: true, parse: 'full'}, callback);
}
fetchChannels(callback) {
return this.get(
'conversations.list',
{exclude_archived: true, types: 'public_channel,private_channel,mpim,im', limit: 500},
(err, resp, body) => {
let out = {};
for (const channel of body.channels) {
out[channel.id] = channel;
}
this.channels = out;
if (typeof callback === 'function') callback(out);
}
);
}
fetchUsers(callback) {
return this.get('users.list', {}, (err, resp, body) => {
let out = {};
body.members.forEach(member => {
out[member.id] = member;
});
this.users = out;
if (typeof callback === 'function') callback(out);
});
}
get(methodName, args = null, callback) {
const url = SLACK_API+methodName;
if (args === null) {
args = {};
}
args['token'] = this.token;
return request({
method: 'GET',
url,
json: true,
qs: args
}, callback);
}
post(methodName, args = null, callback) {
const url = SLACK_API+methodName;
if (args === null) {
args = {};
}
args['token'] = this.token;
return request({
method: 'POST',
url,
form: args
}, callback);
}
}
module.exports = SlackAPI;
|
bkanber/Slackadaisical
|
src/SlackAPI.js
|
JavaScript
|
gpl-3.0
| 7,511 |
var HeaderModel = Backbone.Model.extend({
isEdit: false,
url: '/assets/calendarDetail.json'
});
headerModel = new HeaderModel();
headerModel.fetch();
|
BiteKollektiv/webcal
|
app/assets/javascripts/backbone/models/HeaderModel.js
|
JavaScript
|
gpl-3.0
| 152 |
/*
Splat! Flying Slime JavaScript Script
Copyright (C) 2015 GeckoGames
All Rights Reserved
And, we hope you have fun!
This file is part of Splat!.
Splat! is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Splat! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Splat!. If not, see <http://www.gnu.org/licenses/>.
*/
var SlimeFlying = function (x, y) {
this.name = "FLYING_SLIME_OBJECT"
this.x = x
this.y = y
this.truex = x
this.image = "flying_slime";
this.w = 128
this.h = 128
this.SPEED = 5
this.current_path_index = 5;
this.health = 1;
this.path_distance = 300;
this.update = function () {
slimelogic.path_movement(this);
slimelogic.pi_handler(this);
}
}
|
geckogames/splat
|
src/js/obj/flyingslime.js
|
JavaScript
|
gpl-3.0
| 1,217 |
/**
* Created by yurik on 12.08.16.
*/
function getUrl() {
// run in heroku
return "https://team1-test-prof.herokuapp.com/";
// run in local host
// return "http://127.0.0.1:5000/"
}
|
YurikAbdulayev/test_prof
|
static/js/url.js
|
JavaScript
|
gpl-3.0
| 219 |
/*
* Copyright (C) 2016-2022 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Handles the main things for the Discord modules. This is like the core if you would like to call it that.
*
* Command permissions for the registerCommand function:
* - 1 means only administrators can access the command.
* - 0 means everyone can access the command.
*
* Guidelines for merging thing on our repo for this module:
* - Please try not to call the $.discordAPI function out of this script, move all the main functions here and export the function to the $.discord API.
* - To register command to our command list please add a comment starting with @discordcommandpath before the command info.
* - Make sure to comment on every function what their name is and the parameters they require and if they return something.
*/
(function() {
var embedReg = new RegExp(/\(embed\s([\s\d\w]+),\s([\w\W]+)\)/),
fileRegMsg = new RegExp(/\(file\s([\w\W]+),\s?([\r\n\w\W]*)\)/),
fileReg = new RegExp(/\(file\s([\w\W]+)\)/),
messageDeleteArray = [];
/**
* @function userPrefix
*
* @export $.discord
* @param {string} username
* @return {String}
*/
function userPrefix(username) {
return (username + ', ');
}
/**
* @function isConnected
*
* @return {boolean}
*/
function isConnected() {
return $.discordAPI.isLoggedIn() &&
$.discordAPI.checkConnectionStatus() == Packages.tv.phantombot.discord.DiscordAPI.ConnectionState.CONNECTED
}
/**
* @function getUserMention
*
* @export $.discord.username
* @param {string} username
* @return {string}
*/
function getUserMention(username) {
return ($.discordAPI.getUser(username) != null ? $.discordAPI.getUser(username).getMention() : username);
}
/**
* @function getUserMentionOrChannel
*
* @export $.discord.resolve
* @param {string} argument
* @return {string}
*/
function getUserMentionOrChannel(argument) {
if ($.discordAPI.getUser(username) != null) {
return $.discordAPI.getUser(argument).getMention();
} else if ($.discordAPI.getChannel(argument) != null) {
return $.discordAPI.getChannel(argument).getMention();
} else {
return argument;
}
}
/**
* @function getRandomUser
*
* @export $.discord.username
* @return {string}
*/
function getRandomUser() {
return ($.discordAPI.getUsers().get($.randRange(0, $.discordAPI.getUsers().size() - 1)).getMention()());
}
/**
* @function say
*
* @export $.discord
* @param {string} channel
* @param {string} message
*/
function say(channel, message) {
if (embedReg.test(message)) {
return $.discordAPI.sendMessageEmbed(channel, message.match(embedReg)[1], message.match(embedReg)[2]);
} else if (fileRegMsg.test(message)) {
return $.discordAPI.sendFile(channel, message.match(fileRegMsg)[2], message.match(fileRegMsg)[1]);
} else if (fileReg.test(message)) {
return $.discordAPI.sendFile(channel, message.match(fileReg)[1]);
} else {
return $.discordAPI.sendMessage(channel, message);
}
}
/**
* @function setGame
*
* @export $.discord
* @param {string} game
*/
function setGame(game) {
$.discordAPI.setGame(game);
}
/**
* @function setGame
*
* @export $.discord
* @param {string} game
* @param {string} url
*/
function setStream(game, url) {
$.discordAPI.setStream(game, url);
}
/**
* @function removeGame
*
* @export $.discord
*/
function removeGame() {
$.discordAPI.removeGame();
}
/**
* @function setRole
*
* @param {string} role
* @param {string} username
* @export $.discord
*/
function setRole(role, username) {
return $.discordAPI.addRole(role, username);
}
function sanitizeChannelName(channel) {
channel = channel.trim();
if (channel.startsWith('<')) {
channel = channel.slice(1);
}
if (channel.startsWith('#')) {
channel = channel.slice(1);
}
if (channel.endsWith('>')) {
channel = channel.slice(0, channel.length - 1);
}
return channel;
}
/**
* @function handleDeleteReaction
*
* @param {object} user
* @param {object} message
* @param {object} commandMessage
* @export $.discord
*/
function handleDeleteReaction(user, message, commandMessage) {
var xEmoji = Packages.discord4j.core.object.reaction.ReactionEmoji.unicode('❌');
message.addReaction(xEmoji);
messageDeleteArray[message.getId().asString()] = {
lastMessage: message,
lastCommandMessage: commandMessage,
lastUser: user,
timeout: setTimeout(function() {
messageDeleteArray[message.getId().asString()].lastMessage.delete().subscribe();
messageDeleteArray[message.getId().asString()].lastCommandMessage.delete().subscribe();
delete messageDeleteArray[message.getId().asString()];
}, 3e4)
};
}
/**
* @event discordChannelCommand
*/
$.bind('discordChannelCommand', function(event) {
var sender = event.getSender(),
channel = event.getDiscordChannel(),
command = event.getCommand(),
mention = event.getMention(),
args = event.getArgs(),
action = args[0],
subAction = args[1];
/**
* @discordcommandpath module enable [path] - Enables any modules in the bot, it should only be used to enable discord modules though.
*/
if (command.equalsIgnoreCase('module')) {
if (action === undefined || (subAction === undefined && !action.equalsIgnoreCase('list'))) {
say(channel, userPrefix(mention) + $.lang.get('discord.misc.module.usage'));
return;
}
if (action.equalsIgnoreCase('enable')) {
var module = $.bot.getModule(subAction);
if (module !== undefined) {
$.setIniDbBoolean('modules', module.scriptName, true);
$.bot.loadScript(module.scriptName);
$.bot.modules[module.scriptName].isEnabled = true;
var hookIndex = $.bot.getHookIndex(module.scriptName, 'initReady');
try {
if (hookIndex !== -1) {
$.bot.getHook(module.scriptName, 'initReady').handler();
}
say(channel, userPrefix(mention) + $.lang.get('discord.misc.module.enabled', module.getModuleName()));
} catch (ex) {
$.log.error('[DISCORD] Unable to call initReady for enabled module (' + module.scriptName + '): ' + ex.message);
$.consoleLn("Sending stack trace to error log...");
Packages.com.gmt2001.Console.err.printStackTrace(ex.javaException);
}
} else {
say(channel, userPrefix(mention) + $.lang.get('discord.misc.module.404', subAction));
}
}
/**
* @discordcommandpath module disable [path] - Disables any modules in the bot, it should only be used to enable discord modules though.
*/
if (action.equalsIgnoreCase('disable')) {
var module = $.bot.getModule(subAction);
if (module !== undefined) {
$.setIniDbBoolean('modules', module.scriptName, false);
$.bot.modules[module.scriptName].isEnabled = false;
say(channel, userPrefix(mention) + $.lang.get('discord.misc.module.disabled', module.getModuleName()));
} else {
say(channel, userPrefix(mention) + $.lang.get('discord.misc.module.404', subAction));
}
}
/**
* @discordcommandpath module list - Lists all of the discord modules.
*/
if (action.equalsIgnoreCase('list')) {
var keys = Object.keys($.bot.modules),
modules = $.bot.modules,
list = [],
i;
for (i in keys) {
if (!modules[keys[i]].scriptName.startsWith('./discord/core/') && modules[keys[i]].scriptName.startsWith('./discord/')) {
list.push(modules[keys[i]].scriptName + ' [' + (modules[keys[i]].isEnabled === true ? $.lang.get('common.enabled') : $.lang.get('common.disabled')) + ']');
}
}
say(channel, userPrefix(mention) + $.lang.get('discord.misc.module.list', list.join('\r\n')));
}
}
/**
* @discordcommandpath setgame [game name] - Sets the bot game.
*/
if (command.equalsIgnoreCase('setgame')) {
if (action === undefined) {
say(channel, userPrefix(mention) + $.lang.get('discord.misc.game.set.usage'));
return;
}
setGame(args.join(' '));
say(channel, userPrefix(mention) + $.lang.get('discord.misc.game.set', args.join(' ')));
}
/**
* @discordcommandpath setstream [twitch url] [game name] - Sets the bot game and marks it as streaming.
*/
if (command.equalsIgnoreCase('setstream')) {
if (action === undefined) {
say(channel, userPrefix(mention) + $.lang.get('discord.misc.game.stream.set.usage'));
return;
}
setStream(args.slice(1).join(' '), action);
say(channel, userPrefix(mention) + $.lang.get('discord.misc.game.stream.set', action, args.slice(1).join(' ')));
}
/**
* @discordcommandpath removegame - Removes the bot's game and streaming status if set.
*/
if (command.equalsIgnoreCase('removegame')) {
removeGame();
say(channel, userPrefix(mention) + $.lang.get('discord.misc.game.removed'));
}
});
/**
* @event discordRoleCreated
*/
$.bind('discordRoleCreated', function(event) {
var permObj = JSON.parse($.inidb.get('discordPermsObj', 'obj'));
permObj.roles.push({
'name': event.getDiscordRole().getName() + '',
'_id': event.getRoleID() + '',
'selected': 'false'
});
$.inidb.set('discordPermsObj', 'obj', JSON.stringify(permObj));
});
/**
* @event discordRoleUpdated
*/
$.bind('discordRoleUpdated', function(event) {
var permObj = JSON.parse($.inidb.get('discordPermsObj', 'obj'));
for (var i = 0; i < permObj.roles.length; i++) {
if (permObj.roles[i]._id.equals(event.getRoleID() + '')) {
permObj.roles[i].name = event.getDiscordRole().getName() + '';
break;
}
}
$.inidb.set('discordPermsObj', 'obj', JSON.stringify(permObj));
});
/**
* @event discordRoleDeleted
*/
$.bind('discordRoleDeleted', function(event) {
var permObj = JSON.parse($.inidb.get('discordPermsObj', 'obj'));
var commands = $.inidb.GetKeyList('discordPermcom', '');
for (var i = 0; i < permObj.roles.length; i++) {
if (permObj.roles[i]._id.equals(event.getRoleID() + '')) {
permObj.roles.splice(i, 1);
break;
}
}
for (var i = 0; i < commands.length; i++) {
var perms = JSON.parse($.inidb.get('discordPermcom', commands[i]));
if (perms.roles.indexOf((event.getRoleID() + '')) > -1) {
perms.roles.splice(perms.roles.indexOf((event.getRoleID() + '')), 1);
$.discord.setCommandPermission(commands[i], perms);
$.inidb.set('discordPermcom', commands[i], JSON.stringify(perms));
break;
}
}
$.inidb.set('discordPermsObj', 'obj', JSON.stringify(permObj));
});
/**
* @event discordMessageReaction
*/
$.bind('discordMessageReaction', function (event) {
var reactionEvent = event.getEvent(),
reactionUser = event.getSenderId();
if (event.getReactionEmoji().asUnicodeEmoji().equals(Packages.discord4j.core.object.reaction.ReactionEmoji.unicode('❌'))) {
var messageID = reactionEvent.getMessage().block().getId().asString(),
messageInArray = messageDeleteArray[messageID];
if (messageInArray !== undefined) {
if (messageInArray.lastUser.getId().asString().equals(reactionUser) &&
messageInArray.lastMessage.getId().asString().equals(messageID)) {
reactionEvent.getMessage().block().delete().subscribe();
messageInArray.lastCommandMessage.delete().subscribe();
clearTimeout(messageInArray.timeout);
delete messageDeleteArray[messageID];
}
}
}
});
/**
* @event initReady
*/
$.bind('initReady', function() {
$.discord.registerCommand('./discord/core/misc.js', 'module', 1);
$.discord.registerCommand('./discord/core/misc.js', 'setgame', 1);
$.discord.registerCommand('./discord/core/misc.js', 'setstream', 1);
$.discord.registerCommand('./discord/core/misc.js', 'removegame', 1);
$.discord.registerSubCommand('module', 'list', 1);
$.discord.registerSubCommand('module', 'enable', 1);
$.discord.registerSubCommand('module', 'disable', 1);
});
/* Export the function to the $.discord api. */
/* There are the same functions twice in here - that's normal and wanted. */
$.discord = {
isConnected: isConnected,
getUserMention: getUserMention,
userMention: getUserMention,
removeGame: removeGame,
userPrefix: userPrefix,
setStream: setStream,
setGame: setGame,
setRole: setRole,
say: say,
handleDeleteReaction: handleDeleteReaction,
sanitizeChannelName: sanitizeChannelName,
resolve: {
global: getUserMentionOrChannel,
getUserMentionOrChannel: getUserMentionOrChannel
},
username: {
resolve: getUserMention,
random: getRandomUser,
getUserMention: getUserMention,
getRandomUser: getRandomUser
}
};
})();
|
PhantomBot/PhantomBot
|
javascript-source/discord/core/misc.js
|
JavaScript
|
gpl-3.0
| 15,576 |
function photoSearchService() {
var f = {};
f.findPhotos = function(keyword) {
var matches = [];
if (keyword.toLowerCase() == 'water') {
matches = [
{
title: 'A Perfect Morning',
thumbUrl: 'http://googledrive.com/host/0Bz6MIjSA3u5MSDNwcmNDYWVOdms/images/water1.jpg'
},
{
title: 'Footprints',
thumbUrl: 'http://googledrive.com/host/0Bz6MIjSA3u5MSDNwcmNDYWVOdms/images/water2.jpg'
},
{
title: 'Rush (II)',
thumbUrl: 'http://googledrive.com/host/0Bz6MIjSA3u5MSDNwcmNDYWVOdms/images/water3.jpg'
},
{
title: 'El Matador State Beach',
thumbUrl: 'http://googledrive.com/host/0Bz6MIjSA3u5MSDNwcmNDYWVOdms/images/water4.jpg'
},
{
title: 'El Matador State Beach',
thumbUrl: 'http://googledrive.com/host/0Bz6MIjSA3u5MSDNwcmNDYWVOdms/images/water5.jpg'
},
{
title: 'Big Sur',
thumbUrl: 'http://googledrive.com/host/0Bz6MIjSA3u5MSDNwcmNDYWVOdms/images/water6.jpg'
}];
}
else if (keyword.toLowerCase() == 'mountains') {
matches = [
{
title: 'Difficult Roads',
thumbUrl: 'http://googledrive.com/host/0Bz6MIjSA3u5MSDNwcmNDYWVOdms/images/mountains1.jpg'
},
{
title: 'Klondike Highway - Mountain',
thumbUrl: 'http://googledrive.com/host/0Bz6MIjSA3u5MSDNwcmNDYWVOdms/images/mountains2.jpg'
},
{
title: 'Mount Ossa and Cathedral Mountain',
thumbUrl: 'http://googledrive.com/host/0Bz6MIjSA3u5MSDNwcmNDYWVOdms/images/mountains3.jpg'
},
{
title: 'Heading Down the Mountain',
thumbUrl: 'http://googledrive.com/host/0Bz6MIjSA3u5MSDNwcmNDYWVOdms/images/mountains4.jpg'
},
{
title: 'Stone Bridge',
thumbUrl: 'http://googledrive.com/host/0Bz6MIjSA3u5MSDNwcmNDYWVOdms/images/mountains5.jpg'
}
];
}
return matches;
};
return f;
}
|
jorgeas80/curso-angularjs
|
apps_completas/photo-app/resuelto/js/services.js
|
JavaScript
|
gpl-3.0
| 2,565 |
/* Minimalistic IndexedDB Wrapper with Bullet Proof Transactions
=============================================================
By David Fahlander, david.fahlander@gmail.com
Version 1.0.2 - December 9, 2014.
Tested successfully on Chrome, IE, Firefox and Opera.
Official Website: https://github.com/dfahlander/Dexie.js/wiki/Dexie.js
Licensed under the Apache License Version 2.0, January 2004, http://www.apache.org/licenses/
*/
(function (window, publish, isBrowser, undefined) {
"use strict";
function extend(obj, extension) {
if (typeof extension !== 'object') extension = extension(); // Allow to supply a function returning the extension. Useful for simplifying private scopes.
Object.keys(extension).forEach(function (key) {
obj[key] = extension[key];
});
return obj;
}
function derive(Child) {
return {
from: function (Parent) {
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
return {
extend: function (extension) {
extend(Child.prototype, typeof extension !== 'object' ? extension(Parent.prototype) : extension);
}
};
}
};
}
function override(origFunc, overridedFactory) {
return overridedFactory(origFunc);
}
function Dexie(dbName) {
// Resolve all external dependencies:
var deps = Dexie.dependencies;
var indexedDB = deps.indexedDB,
IDBKeyRange = deps.IDBKeyRange,
IDBTransaction = deps.IDBTransaction;
var DOMError = deps.DOMError,
TypeError = deps.TypeError,
Error = deps.Error;
var globalSchema = this._dbSchema = {};
var versions = [];
var dbStoreNames = [];
var allTables = {};
var notInTransFallbackTables = {};
///<var type="IDBDatabase" />
var idbdb = null; // Instance of IDBDatabase
var db_is_blocked = true;
var dbOpenError = null;
var isBeingOpened = false;
var READONLY = "readonly", READWRITE = "readwrite";
var db = this;
var pausedResumeables = [];
var autoSchema = false;
function init() {
// If browser (not node.js or other), subscribe to versionchange event and reload page
if (isBrowser) db.on("versionchange", function (ev) {
// Let's not block the other window from making it's delete() or open() call.
db.close();
if (ev.newVersion) { // Only reload page if versionchange event isnt a deletion of db.
// Default behavior for versionchange event is to reload the page.
// Caller can override this behavior by doing db.on("versionchange", function(){ return false; });
window.location.reload(true);
/* The logic behind this default handler is:
1. Since this event means that the db is upgraded in another IDBDatabase instance (in tab or window that has a newer version of the code),
it makes sense to reload our page and force reload from cache. When reloaded, we get the newest version of the code - making app in synch with db.
2. There wont be an infinite loop here even if our page still get the old version, becuase the next time onerror will be triggered and not versionchange.
3. If not solving this by default, the API user would be obligated to handle versionchange, and would have to be on place in every example of Dexie code.
*/
};
});
}
//
//
//
// ------------------------- Versioning Framework---------------------------
//
//
//
this.version = function (versionNumber) {
/// <param name="versionNumber" type="Number"></param>
/// <returns type="Version"></returns>
if (idbdb) throw new Error("Cannot add version when database is open");
this.verno = Math.max(this.verno, versionNumber);
var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0];
if (versionInstance) return versionInstance;
versionInstance = new Version(versionNumber);
versions.push(versionInstance);
versions.sort(lowerVersionFirst);
return versionInstance;
};
function Version(versionNumber) {
this._cfg = {
version: versionNumber,
storesSource: null,
dbschema: {},
tables: {},
contentUpgrade: null
};
this.stores({}); // Derive earlier schemas by default.
}
extend(Version.prototype, {
stores: function (stores) {
/// <summary>
/// Defines the schema for a particular version
/// </summary>
/// <param name="stores" type="Object">
/// Example: <br/>
/// {users: "id++,first,last,&username,*email", <br/>
/// passwords: "id++,&username"}<br/>
/// <br/>
/// Syntax: {Table: "[primaryKey][++],[&][*]index1,[&][*]index2,..."}<br/><br/>
/// Special characters:<br/>
/// "&" means unique key, <br/>
/// "*" means value is multiEntry, <br/>
/// "++" means auto-increment and only applicable for primary key <br/>
/// </param>
this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores;
// Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.
var storesSpec = {};
versions.forEach(function (version) { // 'versions' is always sorted by lowest version first.
extend(storesSpec, version._cfg.storesSource);
});
var dbschema = (this._cfg.dbschema = {});
this._parseStoresSpec(storesSpec, dbschema);
// Update the latest schema to this version
// Update API
globalSchema = db._dbSchema = dbschema;
removeTablesApi([allTables, db, notInTransFallbackTables]);
setApiOnPlace([notInTransFallbackTables], tableNotInTransaction, Object.keys(dbschema), READWRITE, dbschema);
setApiOnPlace([allTables, db, this._cfg.tables], db._transPromiseFactory, Object.keys(dbschema), READWRITE, dbschema, true);
dbStoreNames = Object.keys(dbschema);
return this;
},
upgrade: function (upgradeFunction) {
/// <param name="upgradeFunction" optional="true">Function that performs upgrading actions.</param>
var self = this;
fakeAutoComplete(function () {
upgradeFunction(db._createTransaction(READWRITE, Object.keys(self._cfg.dbschema), self._cfg.dbschema));// BUGBUG: No code completion for prev version's tables wont appear.
});
this._cfg.contentUpgrade = upgradeFunction;
return this;
},
_parseStoresSpec: function (stores, outSchema) {
Object.keys(stores).forEach(function (tableName) {
if (stores[tableName] !== null) {
var instanceTemplate = {};
var indexes = parseIndexSyntax(stores[tableName]);
var primKey = indexes.shift();
if (primKey.multi) throw new Error("Primary key cannot be multi-valued");
if (primKey.keyPath && primKey.auto) setByKeyPath(instanceTemplate, primKey.keyPath, 0);
indexes.forEach(function (idx) {
if (idx.auto) throw new Error("Only primary key can be marked as autoIncrement (++)");
if (!idx.keyPath) throw new Error("Index must have a name and cannot be an empty string");
setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () { return ""; }) : "");
});
outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate);
}
});
}
});
function runUpgraders(oldVersion, idbtrans, reject, openReq) {
if (oldVersion === 0) {
//globalSchema = versions[versions.length - 1]._cfg.dbschema;
// Create tables:
Object.keys(globalSchema).forEach(function (tableName) {
createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);
});
// Populate data
var t = db._createTransaction(READWRITE, dbStoreNames, globalSchema);
t.idbtrans = idbtrans;
t.idbtrans.onerror = eventRejectHandler(reject, ["populating database"]);
t.on('error').subscribe(reject);
Promise.newPSD(function () {
Promise.PSD.trans = t;
try {
db.on("populate").fire(t);
} catch (err) {
openReq.onerror = idbtrans.onerror = function (ev) { ev.preventDefault(); }; // Prohibit AbortError fire on db.on("error") in Firefox.
try { idbtrans.abort(); } catch (e) { }
idbtrans.db.close();
reject(err);
}
});
} else {
// Upgrade version to version, step-by-step from oldest to newest version.
// Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version)
var queue = [];
var oldVersionStruct = versions.filter(function (version) { return version._cfg.version === oldVersion; })[0];
if (!oldVersionStruct) throw new Error("Dexie specification of currently installed DB version is missing");
globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema;
var anyContentUpgraderHasRun = false;
var versToRun = versions.filter(function (v) { return v._cfg.version > oldVersion; });
versToRun.forEach(function (version) {
/// <param name="version" type="Version"></param>
var oldSchema = globalSchema;
var newSchema = version._cfg.dbschema;
adjustToExistingIndexNames(oldSchema, idbtrans);
adjustToExistingIndexNames(newSchema, idbtrans);
globalSchema = db._dbSchema = newSchema;
{
var diff = getSchemaDiff(oldSchema, newSchema);
diff.add.forEach(function (tuple) {
queue.push(function (idbtrans, cb) {
createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes);
cb();
});
});
diff.change.forEach(function (change) {
if (change.recreate) {
throw new Error("Not yet support for changing primary key");
} else {
queue.push(function (idbtrans, cb) {
var store = idbtrans.objectStore(change.name);
change.add.forEach(function (idx) {
addIndex(store, idx);
});
change.change.forEach(function (idx) {
store.deleteIndex(idx.name);
addIndex(store, idx);
});
change.del.forEach(function (idxName) {
store.deleteIndex(idxName);
});
cb();
});
}
});
if (version._cfg.contentUpgrade) {
queue.push(function (idbtrans, cb) {
anyContentUpgraderHasRun = true;
var t = db._createTransaction(READWRITE, [].slice.call(idbtrans.db.objectStoreNames, 0), newSchema);
t.idbtrans = idbtrans;
var uncompletedRequests = 0;
t._promise = override(t._promise, function (orig_promise) {
return function (mode, fn, writeLock) {
++uncompletedRequests;
function proxy(fn) {
return function () {
fn.apply(this, arguments);
if (--uncompletedRequests === 0) cb(); // A called db operation has completed without starting a new operation. The flow is finished, now run next upgrader.
};
}
return orig_promise.call(this, mode, function (resolve, reject, trans) {
arguments[0] = proxy(resolve);
arguments[1] = proxy(reject);
fn.apply(this, arguments);
}, writeLock);
};
});
idbtrans.onerror = eventRejectHandler(reject, ["running upgrader function for version", version._cfg.version]);
t.on('error').subscribe(reject);
version._cfg.contentUpgrade(t);
if (uncompletedRequests === 0) cb(); // contentUpgrade() didnt call any db operations at all.
});
}
if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug()) { // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of.
queue.push(function (idbtrans, cb) {
// Delete old tables
deleteRemovedTables(newSchema, idbtrans);
cb();
});
}
}
});
// Now, create a queue execution engine
var runNextQueuedFunction = function () {
try {
if (queue.length)
queue.shift()(idbtrans, runNextQueuedFunction);
else
createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)
} catch (err) {
openReq.onerror = idbtrans.onerror = function (ev) { ev.preventDefault(); }; // Prohibit AbortError fire on db.on("error") in Firefox.
idbtrans.abort();
idbtrans.db.close();
reject(err);
}
};
runNextQueuedFunction();
}
}
function getSchemaDiff(oldSchema, newSchema) {
var diff = {
del: [], // Array of table names
add: [], // Array of [tableName, newDefinition]
change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}
};
for (var table in oldSchema) {
if (!newSchema[table]) diff.del.push(table);
}
for (var table in newSchema) {
var oldDef = oldSchema[table],
newDef = newSchema[table];
if (!oldDef) diff.add.push([table, newDef]);
else {
var change = {
name: table,
def: newSchema[table],
recreate: false,
del: [],
add: [],
change: []
};
if (oldDef.primKey.src !== newDef.primKey.src) {
// Primary key has changed. Remove and re-add table.
change.recreate = true;
diff.change.push(change);
} else {
var oldIndexes = oldDef.indexes.reduce(function (prev, current) { prev[current.name] = current; return prev; }, {});
var newIndexes = newDef.indexes.reduce(function (prev, current) { prev[current.name] = current; return prev; }, {});
for (var idxName in oldIndexes) {
if (!newIndexes[idxName]) change.del.push(idxName);
}
for (var idxName in newIndexes) {
var oldIdx = oldIndexes[idxName],
newIdx = newIndexes[idxName];
if (!oldIdx) change.add.push(newIdx);
else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);
}
if (change.recreate || change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {
diff.change.push(change);
}
}
}
}
return diff;
}
function createTable(idbtrans, tableName, primKey, indexes) {
/// <param name="idbtrans" type="IDBTransaction"></param>
var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto });
indexes.forEach(function (idx) { addIndex(store, idx); });
return store;
}
function createMissingTables(newSchema, idbtrans) {
Object.keys(newSchema).forEach(function (tableName) {
if (!idbtrans.db.objectStoreNames.contains(tableName)) {
createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);
}
});
}
function deleteRemovedTables(newSchema, idbtrans) {
for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) {
var storeName = idbtrans.db.objectStoreNames[i];
if (newSchema[storeName] === null || newSchema[storeName] === undefined) {
idbtrans.db.deleteObjectStore(storeName);
}
}
}
function addIndex(store, idx) {
console.log(idx, idx.keyPath);
store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });
}
//
//
// Dexie Protected API
//
//
this._allTables = allTables;
this._tableFactory = function createTable(mode, tableSchema, transactionPromiseFactory) {
/// <param name="tableSchema" type="TableSchema"></param>
if (mode === READONLY)
return new Table(tableSchema.name, transactionPromiseFactory, tableSchema, Collection);
else
return new WriteableTable(tableSchema.name, transactionPromiseFactory, tableSchema);
};
this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) {
return new Transaction(mode, storeNames, dbschema, parentTransaction);
};
function tableNotInTransaction(mode, storeNames) {
throw new Error("Table " + storeNames[0] + " not part of transaction. Original Scope Function Source: " + Dexie.Promise.PSD.trans.scopeFunc.toString());
}
this._transPromiseFactory = function transactionPromiseFactory(mode, storeNames, fn) { // Last argument is "writeLocked". But this doesnt apply to oneshot direct db operations, so we ignore it.
if (db_is_blocked && (!Promise.PSD || !Promise.PSD.letThrough)) {
// Database is paused. Wait til resumed.
var blockedPromise = new Promise(function (resolve, reject) {
pausedResumeables.push({
resume: function () {
var p = db._transPromiseFactory(mode, storeNames, fn);
blockedPromise.onuncatched = p.onuncatched;
p.then(resolve, reject);
}
});
});
return blockedPromise;
} else {
var trans = db._createTransaction(mode, storeNames, globalSchema);
return trans._promise(mode, function (resolve, reject) {
// An uncatched operation will bubble to this anonymous transaction. Make sure
// to continue bubbling it up to db.on('error'):
trans.error(function (err) {
db.on('error').fire(err);
});
fn(function (value) {
// Instead of resolving value directly, wait with resolving it until transaction has completed.
// Otherwise the data would not be in the DB if requesting it in the then() operation.
// Specifically, to ensure that the following expression will work:
//
// db.friends.put({name: "Arne"}).then(function () {
// db.friends.where("name").equals("Arne").count(function(count) {
// assert (count === 1);
// });
// });
//
trans.complete(function () {
resolve(value);
});
}, reject, trans);
});
}
};
this._whenReady = function (fn) {
if (db_is_blocked && (!Promise.PSD || !Promise.PSD.letThrough)) {
return new Promise(function (resolve, reject) {
fakeAutoComplete(function () { new Promise(function () { fn(resolve, reject); }); });
pausedResumeables.push({
resume: function () {
fn(resolve, reject);
}
});
});
}
return new Promise(fn);
};
//
//
//
//
// Dexie API
//
//
//
this.verno = 0;
this.open = function () {
return new Promise(function (resolve, reject) {
if (idbdb || isBeingOpened) throw new Error("Database already opened or being opened");
function openError(err) {
isBeingOpened = false;
dbOpenError = err;
db_is_blocked = false;
reject(dbOpenError);
pausedResumeables.forEach(function (resumable) {
// Resume all stalled operations. They will fail once they wake up.
resumable.resume();
});
pausedResumeables = [];
}
try {
dbOpenError = null;
isBeingOpened = true;
// Make sure caller has specified at least one version
if (versions.length === 0) {
autoSchema = true;
}
// Multiply db.verno with 10 will be needed to workaround upgrading bug in IE:
// IE fails when deleting objectStore after reading from it.
// A future version of Dexie.js will stopover an intermediate version to workaround this.
// At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number.
if (!indexedDB) throw new Error("indexedDB API not found. If using IE10+, make sure to run your code on a server URL (not locally). If using Safari, make sure to include indexedDB polyfill.");
var dbWasCreated = false; // TODO: Remove this line. Never used.
var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10));
req.onerror = eventRejectHandler(openError, ["opening database", dbName]);
req.onblocked = function (ev) {
db.on("blocked").fire(ev);
};
req.onupgradeneeded = trycatch (function (e) {
if (autoSchema && !db._allowEmptyDB) { // Unless an addon has specified db._allowEmptyDB, lets make the call fail.
// Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.
// If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we
// do not create a new database by accident here.
req.onerror = function (event) { event.preventDefault(); }; // Prohibit onabort error from firing before we're done!
req.transaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)
// Close database and delete it.
req.result.close();
var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here!
delreq.onsuccess = delreq.onerror = function () {
openError(new Error("Database '" + dbName + "' doesnt exist"));
};
} else {
if (e.oldVersion === 0) dbWasCreated = true; // TODO: Remove this line. Never used.
req.transaction.onerror = eventRejectHandler(openError);
var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.
runUpgraders(oldVer / 10, req.transaction, openError, req);
}
}, openError);
req.onsuccess = trycatch(function (e) {
isBeingOpened = false;
idbdb = req.result;
if (autoSchema) readGlobalSchema();
else if (idbdb.objectStoreNames.length > 0)
adjustToExistingIndexNames(globalSchema, idbdb.transaction(idbdb.objectStoreNames, READONLY));
idbdb.onversionchange = db.on("versionchange").fire; // Not firing it here, just setting the function callback to any registered subscriber.
globalDatabaseList(function (databaseNames) {
if (databaseNames.indexOf(dbName) === -1) return databaseNames.push(dbName);
});
// Now, let any subscribers to the on("ready") fire BEFORE any other db operations resume!
// If an the on("ready") subscriber returns a Promise, we will wait til promise completes or rejects before
Promise.newPSD(function () {
Promise.PSD.letThrough = true; // Set a Promise-Specific Data property informing that onready is firing. This will make db._whenReady() let the subscribers use the DB but block all others (!). Quite cool ha?
try {
var res = db.on.ready.fire();
if (res && typeof res.then === 'function') {
// If on('ready') returns a promise, wait for it to complete and then resume any pending operations.
res.then(resume, function (err) {
idbdb.close();
idbdb = null;
openError(err);
});
} else {
asap(resume); // Cannot call resume directly because then the pauseResumables would inherit from our PSD scope.
}
} catch (e) {
openError(e);
}
function resume() {
db_is_blocked = false;
pausedResumeables.forEach(function (resumable) {
// If anyone has made operations on a table instance before the db was opened, the operations will start executing now.
resumable.resume();
});
pausedResumeables = [];
resolve();
}
});
}, openError);
} catch (err) {
openError(err);
}
});
};
this.close = function () {
if (idbdb) {
idbdb.close();
idbdb = null;
db_is_blocked = true;
dbOpenError = null;
}
};
this.delete = function () {
var args = arguments;
return new Promise(function (resolve, reject) {
if (args.length > 0) throw new Error("Arguments not allowed in db.delete()");
function doDelete() {
db.close();
var req = indexedDB.deleteDatabase(dbName);
req.onsuccess = function () {
globalDatabaseList(function (databaseNames) {
var pos = databaseNames.indexOf(dbName);
if (pos >= 0) return databaseNames.splice(pos, 1);
});
resolve();
};
req.onerror = eventRejectHandler(reject, ["deleting", dbName]);
req.onblocked = function () {
db.on("blocked").fire();
};
}
if (isBeingOpened) {
pausedResumeables.push({ resume: doDelete });
} else {
doDelete();
}
});
};
this.backendDB = function () {
return idbdb;
};
this.isOpen = function () {
return idbdb !== null;
};
this.hasFailed = function () {
return dbOpenError !== null;
};
/*this.dbg = function (collection, counter) {
if (!this._dbgResult || !this._dbgResult[counter]) {
if (typeof collection === 'string') collection = this.table(collection).toCollection().limit(100);
if (!this._dbgResult) this._dbgResult = [];
var db = this;
new Promise(function () {
Promise.PSD.letThrough = true;
db._dbgResult[counter] = collection.toArray();
});
}
return this._dbgResult[counter]._value;
}*/
//
// Properties
//
this.name = dbName;
// db.tables - an array of all Table instances.
// TODO: Change so that tables is a simple member and make sure to update it whenever allTables changes.
Object.defineProperty(this, "tables", {
get: function () {
/// <returns type="Array" elementType="WriteableTable" />
return Object.keys(allTables).map(function (name) { return allTables[name]; });
}
});
//
// Events
//
this.on = events(this, "error", "populate", "blocked", { "ready": [promisableChain, nop], "versionchange": [reverseStoppableEventChain, nop] });
// Handle on('ready') specifically: If DB is already open, trigger the event immediately. Also, default to unsubscribe immediately after being triggered.
this.on.ready.subscribe = override(this.on.ready.subscribe, function (origSubscribe) {
return function (subscriber, bSticky) {
function proxy () {
if (!bSticky) db.on.ready.unsubscribe(proxy);
return subscriber.apply(this, arguments);
}
origSubscribe.call(this, proxy);
if (db.isOpen()) {
if (db_is_blocked) {
pausedResumeables.push({ resume: proxy });
} else {
proxy();
}
}
};
});
fakeAutoComplete(function () {
db.on("populate").fire(db._createTransaction(READWRITE, dbStoreNames, globalSchema));
db.on("error").fire(new Error());
});
this.transaction = function (mode, tableInstances, scopeFunc) {
/// <summary>
///
/// </summary>
/// <param name="mode" type="String">"r" for readonly, or "rw" for readwrite</param>
/// <param name="tableInstances">Table instance, Array of Table instances, String or String Array of object stores to include in the transaction</param>
/// <param name="scopeFunc" type="Function">Function to execute with transaction</param>
// Let table arguments be all arguments between mode and last argument.
tableInstances = [].slice.call(arguments, 1, arguments.length - 1);
// Let scopeFunc be the last argument
scopeFunc = arguments[arguments.length - 1];
var parentTransaction = Promise.PSD && Promise.PSD.trans;
if (mode.indexOf('!') !== -1) parentTransaction = null; // Caller dont want to reuse existing transaction
var onlyIfCompatible = mode.indexOf('?') !== -1;
mode = mode.replace('!', '').replace('?', '');
//
// Get storeNames from arguments. Either through given table instances, or through given table names.
//
var tables = Array.isArray(tableInstances[0]) ? tableInstances.reduce(function (a, b) { return a.concat(b); }) : tableInstances;
var error = null;
var storeNames = tables.map(function (tableInstance) {
if (typeof tableInstance === "string") {
return tableInstance;
} else {
if (!(tableInstance instanceof Table)) error = error || new TypeError("Invalid type. Arguments following mode must be instances of Table or String");
return tableInstance.name;
}
});
//
// Resolve mode. Allow shortcuts "r" and "rw".
//
if (mode === "r" || mode === READONLY)
mode = READONLY;
else if (mode === "rw" || mode === READWRITE)
mode = READWRITE;
else
error = new Error("Invalid transaction mode: " + mode);
if (parentTransaction) {
// Basic checks
if (!error) {
if (parentTransaction.db !== db) {
if (onlyIfCompatible) parentTransaction = null; // Spawn new transaction instead.
else error = new Error("Current transaction bound to different database instance");
}
if (parentTransaction && parentTransaction.mode === READONLY && mode === READWRITE) {
if (onlyIfCompatible) parentTransaction = null; // Spawn new transaction instead.
else error = error || new Error("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");
}
if (parentTransaction) {
storeNames.forEach(function (storeName) {
if (!parentTransaction.tables.hasOwnProperty(storeName)) {
if (onlyIfCompatible) parentTransaction = null; // Spawn new transaction instead.
else error = error || new Error("Table " + storeName + " not included in parent transaction. Parent Transaction function: " + parentTransaction.scopeFunc.toString());
}
});
}
}
}
if (parentTransaction) {
// If this is a sub-transaction, lock the parent and then launch the sub-transaction.
return parentTransaction._promise(mode, enterTransactionScope, "lock");
} else {
// If this is a root-level transaction, wait til database is ready and then launch the transaction.
return db._whenReady(enterTransactionScope);
}
function enterTransactionScope(resolve, reject) {
// Our transaction. To be set later.
var trans = null;
try {
// Throw any error if any of the above checks failed.
// Real error defined some lines up. We throw it here from within a Promise to reject Promise
// rather than make caller need to both use try..catch and promise catching. The reason we still
// throw here rather than do Promise.reject(error) is that we like to have the stack attached to the
// error. Also because there is a catch() clause bound to this try() that will bubble the error
// to the parent transaction.
if (error) throw error;
//
// Create Transaction instance
//
trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction);
// Provide arguments to the scope function (for backward compatibility)
var tableArgs = storeNames.map(function (name) { return trans.tables[name]; });
tableArgs.push(trans);
// If transaction completes, resolve the Promise with the return value of scopeFunc.
var returnValue;
var uncompletedRequests = 0;
// Create a new PSD frame to hold Promise.PSD.trans. Must not be bound to the current PSD frame since we want
// it to pop before then() callback is called of our returned Promise.
Promise.newPSD(function () {
// Let the transaction instance be part of a Promise-specific data (PSD) value.
Promise.PSD.trans = trans;
trans.scopeFunc = scopeFunc; // For Error ("Table " + storeNames[0] + " not part of transaction") when it happens. This may help localizing the code that started a transaction used on another place.
if (parentTransaction) {
// Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)
trans.idbtrans = parentTransaction.idbtrans;
trans._promise = override(trans._promise, function (orig) {
return function (mode, fn, writeLock) {
++uncompletedRequests;
function proxy(fn2) {
return function (val) {
var retval = fn2(val);
if (--uncompletedRequests === 0 && trans.active) {
trans.active = false;
trans.on.complete.fire(); // A called db operation has completed without starting a new operation. The flow is finished
}
return retval;
};
}
return orig.call(this, mode, function (resolve2, reject2, trans) {
return fn(proxy(resolve2), proxy(reject2), trans);
}, writeLock);
};
});
}
trans.complete(function () {
resolve(returnValue);
});
// If transaction fails, reject the Promise and bubble to db if noone catched this rejection.
trans.error(function (e) {
trans.idbtrans.onerror = preventDefault; // Prohibit AbortError from firing.
trans.abort();
if (parentTransaction) {
parentTransaction.active = false;
parentTransaction.on.error.fire(e); // Bubble to parent transaction
}
var catched = reject(e);
if (!parentTransaction && !catched) {
db.on.error.fire(e);// If not catched, bubble error to db.on("error").
}
});
// Finally, call the scope function with our table and transaction arguments.
returnValue = scopeFunc.apply(trans, tableArgs); // NOTE: returnValue is used in trans.on.complete() not as a returnValue to this func.
});
if (!trans.idbtrans || parentTransaction && uncompletedRequests === 0) {
trans._nop(); // Make sure transaction is being used so that it will resolve.
}
} catch (e) {
// If exception occur, abort the transaction and reject Promise.
if (trans && trans.idbtrans) trans.idbtrans.onerror = preventDefault; // Prohibit AbortError from firing.
if (trans) trans.abort();
if (parentTransaction) parentTransaction.on.error.fire(e);
asap(function () {
// Need to use asap(=setImmediate/setTimeout) before calling reject because we are in the Promise constructor and reject() will always return false if so.
if (!reject(e)) db.on("error").fire(e); // If not catched, bubble exception to db.on("error");
});
}
}
};
this.table = function (tableName) {
/// <returns type="WriteableTable"></returns>
if (!autoSchema && !allTables.hasOwnProperty(tableName)) { throw new Error("Table does not exist"); return { AN_UNKNOWN_TABLE_NAME_WAS_SPECIFIED: 1 }; }
return allTables[tableName];
};
//
//
//
// Table Class
//
//
//
function Table(name, transactionPromiseFactory, tableSchema, collClass) {
/// <param name="name" type="String"></param>
this.name = name;
this.schema = tableSchema;
this.hook = allTables[name] ? allTables[name].hook : events(null, {
"creating": [hookCreatingChain, nop],
"reading": [pureFunctionChain, mirror],
"updating": [hookUpdatingChain, nop],
"deleting": [nonStoppableEventChain, nop]
});
this._tpf = transactionPromiseFactory;
this._collClass = collClass || Collection;
}
extend(Table.prototype, function () {
function failReadonly() {
throw new Error("Current Transaction is READONLY");
}
return {
//
// Table Protected Methods
//
_trans: function getTransaction(mode, fn, writeLocked) {
return this._tpf(mode, [this.name], fn, writeLocked);
},
_idbstore: function getIDBObjectStore(mode, fn, writeLocked) {
var self = this;
return this._tpf(mode, [this.name], function (resolve, reject, trans) {
fn(resolve, reject, trans.idbtrans.objectStore(self.name), trans);
}, writeLocked);
},
//
// Table Public Methods
//
get: function (key, cb) {
var self = this;
fakeAutoComplete(function () { cb(self.schema.instanceTemplate); });
return this._idbstore(READONLY, function (resolve, reject, idbstore) {
var req = idbstore.get(key);
req.onerror = eventRejectHandler(reject, ["getting", key, "from", self.name]);
req.onsuccess = function () {
resolve(self.hook.reading.fire(req.result));
};
}).then(cb);
},
where: function (indexName) {
return new WhereClause(this, indexName);
},
count: function (cb) {
return this.toCollection().count(cb);
},
offset: function (offset) {
return this.toCollection().offset(offset);
},
limit: function (numRows) {
return this.toCollection().limit(numRows);
},
reverse: function () {
return this.toCollection().reverse();
},
filter: function (filterFunction) {
return this.toCollection().and(filterFunction);
},
each: function (fn) {
var self = this;
fakeAutoComplete(function () { fn(self.schema.instanceTemplate); });
return this._idbstore(READONLY, function (resolve, reject, idbstore) {
var req = idbstore.openCursor();
req.onerror = eventRejectHandler(reject, ["calling", "Table.each()", "on", self.name]);
iterate(req, null, fn, resolve, reject, self.hook.reading.fire);
});
},
toArray: function (cb) {
var self = this;
fakeAutoComplete(function () { cb([self.schema.instanceTemplate]); });
return this._idbstore(READONLY, function (resolve, reject, idbstore) {
var a = [];
var req = idbstore.openCursor();
req.onerror = eventRejectHandler(reject, ["calling", "Table.toArray()", "on", self.name]);
iterate(req, null, function (item) { a.push(item); }, function () { resolve(a); }, reject, self.hook.reading.fire);
}).then(cb);
},
orderBy: function (index) {
return new this._collClass(new WhereClause(this, index));
},
toCollection: function () {
return new this._collClass(new WhereClause(this));
},
mapToClass: function (constructor, structure) {
/// <summary>
/// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making
/// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}.
/// </summary>
/// <param name="constructor">Constructor function representing the class.</param>
/// <param name="structure" optional="true">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also
/// know what type each member has. Example: {name: String, emailAddresses: [String], password}</param>
this.schema.mappedClass = constructor;
var instanceTemplate = Object.create(constructor.prototype);
if (this.schema.primKey.keyPath) {
// Make sure primary key is not part of prototype because add() and put() fails on Chrome if primKey template lies on prototype due to a bug in its implementation
// of getByKeyPath(), that it accepts getting from prototype chain.
setByKeyPath(instanceTemplate, this.schema.primKey.keyPath, this.schema.primKey.auto ? 0 : "");
delByKeyPath(constructor.prototype, this.schema.primKey.keyPath);
}
if (structure) {
// structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance.
applyStructure(instanceTemplate, structure);
}
this.schema.instanceTemplate = instanceTemplate;
// Now, subscribe to the when("reading") event to make all objects that come out from this table inherit from given class
// no matter which method to use for reading (Table.get() or Table.where(...)... )
var readHook = Object.setPrototypeOf ?
function makeInherited(obj) {
if (!obj) return obj; // No valid object. (Value is null). Return as is.
// Object.setPrototypeOf() supported. Just change that pointer on the existing object. A little more efficient way.
Object.setPrototypeOf(obj, constructor.prototype);
return obj;
} : function makeInherited(obj) {
if (!obj) return obj; // No valid object. (Value is null). Return as is.
// Object.setPrototypeOf not supported (IE10)- return a new object and clone the members from the old one.
var res = Object.create(constructor.prototype);
for (var m in obj) if (obj.hasOwnProperty(m)) res[m] = obj[m];
return res;
};
if (this.schema.readHook) {
this.hook.reading.unsubscribe(this.schema.readHook);
}
this.schema.readHook = readHook;
this.hook("reading", readHook);
return constructor;
},
defineClass: function (structure) {
/// <summary>
/// Define all members of the class that represents the table. This will help code completion of when objects are read from the database
/// as well as making it possible to extend the prototype of the returned constructor function.
/// </summary>
/// <param name="structure">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also
/// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}</param>
return this.mapToClass(Dexie.defineClass(structure), structure);
},
add: failReadonly,
put: failReadonly,
'delete': failReadonly,
clear: failReadonly,
update: failReadonly
};
});
//
//
//
// WriteableTable Class (extends Table)
//
//
//
function WriteableTable(name, transactionPromiseFactory, tableSchema, collClass) {
Table.call(this, name, transactionPromiseFactory, tableSchema, collClass || WriteableCollection);
}
derive(WriteableTable).from(Table).extend(function () {
return {
add: function (obj, key) {
/// <summary>
/// Add an object to the database. In case an object with same primary key already exists, the object will not be added.
/// </summary>
/// <param name="obj" type="Object">A javascript object to insert</param>
/// <param name="key" optional="true">Primary key</param>
var self = this,
creatingHook = this.hook.creating.fire;
return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {
var thisCtx = {};
if (creatingHook !== nop) {
var effectiveKey = key || (idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined);
var keyToUse = creatingHook.call(thisCtx, effectiveKey, obj, trans); // Allow subscribers to when("creating") to generate the key.
if (effectiveKey === undefined && keyToUse !== undefined) {
if (idbstore.keyPath)
setByKeyPath(obj, idbstore.keyPath, keyToUse);
else
key = keyToUse;
}
}
//try {
var req = key ? idbstore.add(obj, key) : idbstore.add(obj);
req.onerror = eventRejectHandler(function (e) {
if (thisCtx.onerror) thisCtx.onerror(e);
return reject(e);
}, ["adding", obj, "into", self.name]);
req.onsuccess = function (ev) {
var keyPath = idbstore.keyPath;
if (keyPath) setByKeyPath(obj, keyPath, ev.target.result);
if (thisCtx.onsuccess) thisCtx.onsuccess(ev.target.result);
resolve(req.result);
};
/*} catch (e) {
trans.on("error").fire(e);
trans.abort();
reject(e);
}*/
});
},
put: function (obj, key) {
/// <summary>
/// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated.
/// </summary>
/// <param name="obj" type="Object">A javascript object to insert or update</param>
/// <param name="key" optional="true">Primary key</param>
var self = this,
creatingHook = this.hook.creating.fire,
updatingHook = this.hook.updating.fire;
if (creatingHook !== nop || updatingHook !== nop) {
//
// People listens to when("creating") or when("updating") events!
// We must know whether the put operation results in an CREATE or UPDATE.
//
return this._trans(READWRITE, function (resolve, reject, trans) {
// Since key is optional, make sure we get it from obj if not provided
var effectiveKey = key || (self.schema.primKey.keyPath && getByKeyPath(obj, self.schema.primKey.keyPath));
if (effectiveKey === undefined) {
// No primary key. Must use add().
trans.tables[self.name].add(obj).then(resolve, reject);
} else {
// Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add().
trans._lock(); // Needed because operation is splitted into modify() and add().
// clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation.
obj = deepClone(obj);
trans.tables[self.name].where(":id").equals(effectiveKey).modify(function (value) {
// Replace extisting value with our object
// CRUD event firing handled in WriteableCollection.modify()
this.value = obj;
}).then(function (count) {
if (count === 0) {
// Object's key was not found. Add the object instead.
// CRUD event firing will be done in add()
return trans.tables[self.name].add(obj, key); // Resolving with another Promise. Returned Promise will then resolve with the new key.
} else {
return effectiveKey; // Resolve with the provided key.
}
}).finally(function () {
trans._unlock();
}).then(resolve, reject);
}
});
} else {
// Use the standard IDB put() method.
return this._idbstore(READWRITE, function (resolve, reject, idbstore) {
var req = key ? idbstore.put(obj, key) : idbstore.put(obj);
req.onerror = eventRejectHandler(reject, ["putting", obj, "into", self.name]);
req.onsuccess = function (ev) {
var keyPath = idbstore.keyPath;
if (keyPath) setByKeyPath(obj, keyPath, ev.target.result);
resolve(req.result);
};
});
}
},
'delete': function (key) {
/// <param name="key">Primary key of the object to delete</param>
if (this.hook.deleting.subscribers.length) {
// People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will
// call the CRUD event. Only WriteableCollection.delete() will know whether an object was actually deleted.
return this.where(":id").equals(key).delete();
} else {
// No one listens. Use standard IDB delete() method.
return this._idbstore(READWRITE, function (resolve, reject, idbstore) {
var req = idbstore.delete(key);
req.onerror = eventRejectHandler(reject, ["deleting", key, "from", idbstore.name]);
req.onsuccess = function (ev) {
resolve(req.result);
};
});
}
},
clear: function () {
if (this.hook.deleting.subscribers.length) {
// People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will
// call the CRUD event. Only WriteableCollection.delete() will knows which objects that are actually deleted.
return this.toCollection().delete();
} else {
return this._idbstore(READWRITE, function (resolve, reject, idbstore) {
var req = idbstore.clear();
req.onerror = eventRejectHandler(reject, ["clearing", idbstore.name]);
req.onsuccess = function (ev) {
resolve(req.result);
};
});
}
},
update: function (keyOrObject, modifications) {
if (typeof modifications !== 'object' || Array.isArray(modifications)) throw new Error("db.update(keyOrObject, modifications). modifications must be an object.");
if (typeof keyOrObject === 'object' && !Array.isArray(keyOrObject)) {
// object to modify. Also modify given object with the modifications:
Object.keys(modifications).forEach(function (keyPath) {
setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);
});
var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);
if (key === undefined) Promise.reject(new Error("Object does not contain its primary key"));
return this.where(":id").equals(key).modify(modifications);
} else {
// key to modify
return this.where(":id").equals(keyOrObject).modify(modifications);
}
}
};
});
//
//
//
// Transaction Class
//
//
//
function Transaction(mode, storeNames, dbschema, parent) {
/// <summary>
/// Transaction class. Represents a database transaction. All operations on db goes through a Transaction.
/// </summary>
/// <param name="mode" type="String">Any of "readwrite" or "readonly"</param>
/// <param name="storeNames" type="Array">Array of table names to operate on</param>
var self = this;
this.db = db;
this.mode = mode;
this.storeNames = storeNames;
this.idbtrans = null;
this.on = events(this, ["complete", "error"], "abort");
this._reculock = 0;
this._blockedFuncs = [];
this._psd = null;
this.active = true;
this._dbschema = dbschema;
if (parent) this.parent = parent;
this._tpf = transactionPromiseFactory;
this.tables = Object.create(notInTransFallbackTables); // ...so that all non-included tables exists as instances (possible to call table.name for example) but will fail as soon as trying to execute a query on it.
function transactionPromiseFactory(mode, storeNames, fn, writeLocked) {
// Creates a Promise instance and calls fn (resolve, reject, trans) where trans is the instance of this transaction object.
// Support for write-locking the transaction during the promise life time from creation to success/failure.
// This is actually not needed when just using single operations on IDB, since IDB implements this internally.
// However, when implementing a write operation as a series of operations on top of IDB(collection.delete() and collection.modify() for example),
// lock is indeed needed if Dexie APIshould behave in a consistent manner for the API user.
// Another example of this is if we want to support create/update/delete events,
// we need to implement put() using a series of other IDB operations but still need to lock the transaction all the way.
return self._promise(mode, fn, writeLocked);
}
for (var i = storeNames.length - 1; i !== -1; --i) {
var name = storeNames[i];
var table = db._tableFactory(mode, dbschema[name], transactionPromiseFactory);
this.tables[name] = table;
if (!this[name]) this[name] = table;
}
}
extend(Transaction.prototype, {
//
// Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions)
//
_lock: function () {
// Temporary set all requests into a pending queue if they are called before database is ready.
++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)
if (this._reculock === 1 && Promise.PSD) Promise.PSD.lockOwnerFor = this;
return this;
},
_unlock: function () {
if (--this._reculock === 0) {
if (Promise.PSD) Promise.PSD.lockOwnerFor = null;
while (this._blockedFuncs.length > 0 && !this._locked()) {
var fn = this._blockedFuncs.shift();
try { fn(); } catch (e) { }
}
}
return this;
},
_locked: function () {
// Checks if any write-lock is applied on this transaction.
// To simplify the Dexie API for extension implementations, we support recursive locks.
// This is accomplished by using "Promise Specific Data" (PSD).
// PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).
// Promise.PSD is local to code executing on top of the call stacks of any of any code executed by Promise():
// * callback given to the Promise() constructor (function (resolve, reject){...})
// * callbacks given to then()/catch()/finally() methods (function (value){...})
// If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise.
// Derivation is done so that the inner PSD __proto__ points to the outer PSD.
// Promise.PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.
return this._reculock && (!Promise.PSD || Promise.PSD.lockOwnerFor !== this);
},
_nop: function (cb) {
// An asyncronic no-operation that may call given callback when done doing nothing. An alternative to asap() if we must not lose the transaction.
this.tables[this.storeNames[0]].get(0).then(cb);
},
_promise: function (mode, fn, bWriteLock) {
var self = this;
return Promise.newPSD(function() {
var p;
// Read lock always
if (!self._locked()) {
p = self.active ? new Promise(function (resolve, reject) {
if (!self.idbtrans && mode) {
if (!idbdb) throw dbOpenError ? new Error("Database not open. Following error in populate, ready or upgrade function made Dexie.open() fail: " + dbOpenError) : new Error("Database not open");
var idbtrans = self.idbtrans = idbdb.transaction(self.storeNames, self.mode);
idbtrans.onerror = function (e) {
self.on("error").fire(e && e.target.error);
e.preventDefault(); // Prohibit default bubbling to window.error
self.abort(); // Make sure transaction is aborted since we preventDefault.
};
idbtrans.onabort = function (e) {
self.active = false;
self.on("abort").fire(e);
};
idbtrans.oncomplete = function (e) {
self.active = false;
self.on("complete").fire(e);
};
}
if (bWriteLock) self._lock(); // Write lock if write operation is requested
try {
fn(resolve, reject, self);
} catch (e) {
// Direct exception happened when doin operation.
// We must immediately fire the error and abort the transaction.
// When this happens we are still constructing the Promise so we don't yet know
// whether the caller is about to catch() the error or not. Have to make
// transaction fail. Catching such an error wont stop transaction from failing.
// This is a limitation we have to live with.
Dexie.spawn(function () { self.on('error').fire(e); });
self.abort();
reject(e);
}
}) : Promise.reject(stack(new Error("Transaction is inactive. Original Scope Function Source: " + self.scopeFunc.toString())));
if (self.active && bWriteLock) p.finally(function () {
self._unlock();
});
} else {
// Transaction is write-locked. Wait for mutex.
p = new Promise(function (resolve, reject) {
self._blockedFuncs.push(function () {
self._promise(mode, fn, bWriteLock).then(resolve, reject);
});
});
}
p.onuncatched = function (e) {
// Bubble to transaction. Even though IDB does this internally, it would just do it for error events and not for caught exceptions.
Dexie.spawn(function () { self.on("error").fire(e); });
self.abort();
};
return p;
});
},
//
// Transaction Public Methods
//
complete: function (cb) {
return this.on("complete", cb);
},
error: function (cb) {
return this.on("error", cb);
},
abort: function () {
if (this.idbtrans && this.active) try { // TODO: if !this.idbtrans, enqueue an abort() operation.
this.active = false;
this.idbtrans.abort();
this.on.error.fire(new Error("Transaction Aborted"));
} catch (e) { }
},
table: function (name) {
if (!this.tables.hasOwnProperty(name)) { throw new Error("Table " + name + " not in transaction"); return { AN_UNKNOWN_TABLE_NAME_WAS_SPECIFIED: 1 }; }
return this.tables[name];
}
});
//
//
//
// WhereClause
//
//
//
function WhereClause(table, index, orCollection) {
/// <param name="table" type="Table"></param>
/// <param name="index" type="String" optional="true"></param>
/// <param name="orCollection" type="Collection" optional="true"></param>
this._ctx = {
table: table,
index: index === ":id" ? null : index,
collClass: table._collClass,
or: orCollection
};
}
extend(WhereClause.prototype, function () {
// WhereClause private methods
function fail(collection, err) {
try { throw err; } catch (e) {
collection._ctx.error = e;
}
return collection;
}
function getSetArgs(args) {
return Array.prototype.slice.call(args.length === 1 && Array.isArray(args[0]) ? args[0] : args);
}
function upperFactory(dir) {
return dir === "next" ? function (s) { return s.toUpperCase(); } : function (s) { return s.toLowerCase(); };
}
function lowerFactory(dir) {
return dir === "next" ? function (s) { return s.toLowerCase(); } : function (s) { return s.toUpperCase(); };
}
function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {
var length = Math.min(key.length, lowerNeedle.length);
var llp = -1;
for (var i = 0; i < length; ++i) {
var lwrKeyChar = lowerKey[i];
if (lwrKeyChar !== lowerNeedle[i]) {
if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);
if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);
if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);
return null;
}
if (cmp(key[i], lwrKeyChar) < 0) llp = i;
}
if (length < lowerNeedle.length && dir === "next") return key + upperNeedle.substr(key.length);
if (length < key.length && dir === "prev") return key.substr(0, upperNeedle.length);
return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1));
}
function addIgnoreCaseAlgorithm(c, match, needle) {
/// <param name="needle" type="String"></param>
var upper, lower, compare, upperNeedle, lowerNeedle, direction;
function initDirection(dir) {
upper = upperFactory(dir);
lower = lowerFactory(dir);
compare = (dir === "next" ? ascending : descending);
upperNeedle = upper(needle);
lowerNeedle = lower(needle);
direction = dir;
}
initDirection("next");
c._ondirectionchange = function (direction) {
// This event onlys occur before filter is called the first time.
initDirection(direction);
};
c._addAlgorithm(function (cursor, advance, resolve) {
/// <param name="cursor" type="IDBCursor"></param>
/// <param name="advance" type="Function"></param>
/// <param name="resolve" type="Function"></param>
var key = cursor.key;
if (typeof key !== 'string') return false;
var lowerKey = lower(key);
if (match(lowerKey, lowerNeedle)) {
advance(function () { cursor.continue(); });
return true;
} else {
var nextNeedle = nextCasing(key, lowerKey, upperNeedle, lowerNeedle, compare, direction);
if (nextNeedle) {
advance(function () { cursor.continue(nextNeedle); });
} else {
advance(resolve);
}
return false;
}
});
}
//
// WhereClause public methods
//
return {
between: function (lower, upper, includeLower, includeUpper) {
/// <summary>
/// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates.
/// </summary>
/// <param name="lower"></param>
/// <param name="upper"></param>
/// <param name="includeLower" optional="true">Whether items that equals lower should be included. Default true.</param>
/// <param name="includeUpper" optional="true">Whether items that equals upper should be included. Default false.</param>
/// <returns type="Collection"></returns>
includeLower = includeLower !== false; // Default to true
includeUpper = includeUpper === true; // Default to false
if ((lower > upper) ||
(lower === upper && (includeLower || includeUpper) && !(includeLower && includeUpper)))
return new this._ctx.collClass(this, IDBKeyRange.only(lower)).limit(0); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection.
return new this._ctx.collClass(this, IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper));
},
equals: function (value) {
return new this._ctx.collClass(this, IDBKeyRange.only(value));
},
above: function (value) {
return new this._ctx.collClass(this, IDBKeyRange.lowerBound(value, true));
},
aboveOrEqual: function (value) {
return new this._ctx.collClass(this, IDBKeyRange.lowerBound(value));
},
below: function (value) {
return new this._ctx.collClass(this, IDBKeyRange.upperBound(value, true));
},
belowOrEqual: function (value) {
return new this._ctx.collClass(this, IDBKeyRange.upperBound(value));
},
startsWith: function (str) {
/// <param name="str" type="String"></param>
if (typeof str !== 'string') return fail(new this._ctx.collClass(this), new TypeError("String expected"));
return this.between(str, str + String.fromCharCode(65535), true, true);
},
startsWithIgnoreCase: function (str) {
/// <param name="str" type="String"></param>
if (typeof str !== 'string') return fail(new this._ctx.collClass(this), new TypeError("String expected"));
if (str === "") return this.startsWith(str);
var c = new this._ctx.collClass(this, IDBKeyRange.bound(str.toUpperCase(), str.toLowerCase() + String.fromCharCode(65535)));
addIgnoreCaseAlgorithm(c, function (a, b) { return a.indexOf(b) === 0; }, str);
c._ondirectionchange = function () { fail(c, new Error("reverse() not supported with WhereClause.startsWithIgnoreCase()")); };
return c;
},
equalsIgnoreCase: function (str) {
/// <param name="str" type="String"></param>
if (typeof str !== 'string') return fail(new this._ctx.collClass(this), new TypeError("String expected"));
var c = new this._ctx.collClass(this, IDBKeyRange.bound(str.toUpperCase(), str.toLowerCase()));
addIgnoreCaseAlgorithm(c, function (a, b) { return a === b; }, str);
return c;
},
anyOf: function (valueArray) {
var ctx = this._ctx,
schema = ctx.table.schema;
var idxSpec = ctx.index ? schema.idxByName[ctx.index] : schema.primKey;
var isCompound = idxSpec && idxSpec.compound;
var set = getSetArgs(arguments);
var compare = isCompound ? compoundCompare(ascending) : ascending;
set.sort(compare);
if (set.length === 0) return new this._ctx.collClass(this, IDBKeyRange.only("")).limit(0); // Return an empty collection.
var c = new this._ctx.collClass(this, IDBKeyRange.bound(set[0], set[set.length - 1]));
c._ondirectionchange = function (direction) {
compare = (direction === "next" ? ascending : descending);
if (isCompound) compare = compoundCompare(compare);
set.sort(compare);
};
var i = 0;
c._addAlgorithm(function (cursor, advance, resolve) {
var key = cursor.key;
while (compare(key, set[i]) > 0) {
// The cursor has passed beyond this key. Check next.
++i;
if (i === set.length) {
// There is no next. Stop searching.
advance(resolve);
return false;
}
}
if (compare(key, set[i]) === 0) {
// The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.
advance(function () { cursor.continue(); });
return true;
} else {
// cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.
advance(function () { cursor.continue(set[i]); });
return false;
}
});
return c;
}
};
});
//
//
//
// Collection Class
//
//
//
function Collection(whereClause, keyRange) {
/// <summary>
///
/// </summary>
/// <param name="whereClause" type="WhereClause">Where clause instance</param>
/// <param name="keyRange" type="IDBKeyRange" optional="true"></param>
var whereCtx = whereClause._ctx;
this._ctx = {
table: whereCtx.table,
index: whereCtx.index,
isPrimKey: (!whereCtx.index || (whereCtx.table.schema.primKey.keyPath && whereCtx.index === whereCtx.table.schema.primKey.name)),
range: keyRange,
op: "openCursor",
dir: "next",
unique: "",
algorithm: null,
filter: null,
isMatch: null,
offset: 0,
limit: Infinity,
error: null, // If set, any promise must be rejected with this error
or: whereCtx.or
};
}
extend(Collection.prototype, function () {
//
// Collection Private Functions
//
function addFilter(ctx, fn) {
ctx.filter = combine(ctx.filter, fn);
}
function addMatchFilter(ctx, fn) {
ctx.isMatch = combine(ctx.isMatch, fn);
}
function getIndexOrStore(ctx, store) {
if (ctx.isPrimKey) return store;
var indexSpec = ctx.table.schema.idxByName[ctx.index];
if (!indexSpec) throw new Error("KeyPath " + ctx.index + " on object store " + store.name + " is not indexed");
return ctx.isPrimKey ? store : store.index(indexSpec.name);
}
function openCursor(ctx, store) {
return getIndexOrStore(ctx, store)[ctx.op](ctx.range || null, ctx.dir + ctx.unique);
}
function iter(ctx, fn, resolve, reject, idbstore) {
if (!ctx.or) {
iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, ctx.filter), fn, resolve, reject, ctx.table.hook.reading.fire);
} else {
(function () {
var filter = ctx.filter;
var set = {};
var primKey = ctx.table.schema.primKey.keyPath;
var resolved = 0;
function resolveboth() {
if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion.
}
function union(item, cursor, advance) {
if (!filter || filter(cursor, advance, resolveboth, reject)) {
var key = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string
if (!set.hasOwnProperty(key)) {
set[key] = true;
fn(item, cursor, advance);
}
}
}
ctx.or._iterate(union, resolveboth, reject, idbstore);
iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, ctx.table.hook.reading.fire);
})();
}
}
function getInstanceTemplate(ctx) {
return ctx.table.schema.instanceTemplate;
}
return {
//
// Collection Protected Functions
//
_read: function (fn, cb) {
var ctx = this._ctx;
if (ctx.error)
return ctx.table._trans(null, function rejector(resolve, reject) { reject(ctx.error); });
else
return ctx.table._idbstore(READONLY, fn).then(cb);
},
_write: function (fn) {
var ctx = this._ctx;
if (ctx.error)
return ctx.table._trans(null, function rejector(resolve, reject) { reject(ctx.error); });
else
return ctx.table._idbstore(READWRITE, fn, "locked"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.
},
_addAlgorithm: function (fn) {
var ctx = this._ctx;
ctx.algorithm = combine(ctx.algorithm, fn);
},
_iterate: function (fn, resolve, reject, idbstore) {
return iter(this._ctx, fn, resolve, reject, idbstore);
},
//
// Collection Public methods
//
each: function (fn) {
var ctx = this._ctx;
fakeAutoComplete(function () { fn(getInstanceTemplate(ctx)); });
return this._read(function (resolve, reject, idbstore) {
iter(ctx, fn, resolve, reject, idbstore);
});
},
count: function (cb) {
fakeAutoComplete(function () { cb(0); });
var self = this,
ctx = this._ctx;
if (ctx.filter || ctx.algorithm || ctx.or) {
// When filters are applied or 'ored' collections are used, we must count manually
var count = 0;
return this._read(function (resolve, reject, idbstore) {
iter(ctx, function () { ++count; return false; }, function () { resolve(count); }, reject, idbstore);
}, cb);
} else {
// Otherwise, we can use the count() method if the index.
return this._read(function (resolve, reject, idbstore) {
var idx = getIndexOrStore(ctx, idbstore);
var req = (ctx.range ? idx.count(ctx.range) : idx.count());
req.onerror = eventRejectHandler(reject, ["calling", "count()", "on", self.name]);
req.onsuccess = function (e) {
resolve(Math.min(e.target.result, Math.max(0, ctx.limit - ctx.offset)));
};
}, cb);
}
},
sortBy: function (keyPath, cb) {
/// <param name="keyPath" type="String"></param>
var ctx = this._ctx;
fakeAutoComplete(function () { cb([getInstanceTemplate(ctx)]); });
var parts = keyPath.split('.').reverse(),
lastPart = parts[0],
lastIndex = parts.length - 1;
function getval(obj, i) {
if (i) return getval(obj[parts[i]], i - 1);
return obj[lastPart];
}
var order = this._ctx.dir === "next" ? 1 : -1;
function sorter(a, b) {
var aVal = getval(a, lastIndex),
bVal = getval(b, lastIndex);
return aVal < bVal ? -order : aVal > bVal ? order : 0;
}
return this.toArray(function (a) {
return a.sort(sorter);
}).then(cb);
},
toArray: function (cb) {
var ctx = this._ctx;
fakeAutoComplete(function () { cb([getInstanceTemplate(ctx)]); });
return this._read(function (resolve, reject, idbstore) {
var a = [];
iter(ctx, function (item) { a.push(item); }, function arrayComplete() {
resolve(a);
}, reject, idbstore);
}, cb);
},
offset: function (offset) {
var ctx = this._ctx;
if (offset <= 0) return this;
ctx.offset += offset; // For count()
if (!ctx.or && !ctx.algorithm && !ctx.filter) {
addFilter(ctx, function offsetFilter(cursor, advance, resolve) {
if (offset === 0) return true;
if (offset === 1) { --offset; return false; }
advance(function () { cursor.advance(offset); offset = 0; });
return false;
});
} else {
addFilter(ctx, function offsetFilter(cursor, advance, resolve) {
return (--offset < 0);
});
}
return this;
},
limit: function (numRows) {
this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()
addFilter(this._ctx, function (cursor, advance, resolve) {
if (--numRows <= 0) advance(resolve); // Stop after this item has been included
return numRows >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here.
});
return this;
},
until: function (filterFunction, bIncludeStopEntry) {
var ctx = this._ctx;
fakeAutoComplete(function () { filterFunction(getInstanceTemplate(ctx)); });
addFilter(this._ctx, function (cursor, advance, resolve) {
if (filterFunction(cursor.value)) {
advance(resolve);
return bIncludeStopEntry;
} else {
return true;
}
});
return this;
},
first: function (cb) {
var self = this;
fakeAutoComplete(function () { cb(getInstanceTemplate(self._ctx)); });
return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);
},
last: function (cb) {
return this.reverse().first(cb);
},
and: function (filterFunction) {
/// <param name="jsFunctionFilter" type="Function">function(val){return true/false}</param>
var self = this;
fakeAutoComplete(function () { filterFunction(getInstanceTemplate(self._ctx)); });
addFilter(this._ctx, function (cursor) {
return filterFunction(cursor.value);
});
addMatchFilter(this._ctx, filterFunction); // match filters not used in Dexie.js but can be used by 3rd part libraries to test a collection for a match without querying DB. Used by Dexie.Observable.
return this;
},
or: function (indexName) {
return new WhereClause(this._ctx.table, indexName, this);
},
reverse: function () {
this._ctx.dir = (this._ctx.dir === "prev" ? "next" : "prev");
if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);
return this;
},
desc: function () {
return this.reverse();
},
eachKey: function (cb) {
var self = this, ctx = this._ctx;
fakeAutoComplete(function () { cb(getInstanceTemplate(self._ctx)[self._ctx.index]); });
if (!ctx.isPrimKey) ctx.op = "openKeyCursor"; // Need the check because IDBObjectStore does not have "openKeyCursor()" while IDBIndex has.
return this.each(function (val, cursor) { cb(cursor.key, cursor); });
},
eachUniqueKey: function (cb) {
this._ctx.unique = "unique";
return this.eachKey(cb);
},
keys: function (cb) {
fakeAutoComplete(function () { cb([getInstanceTemplate(ctx)[self._ctx.index]]); });
var self = this,
ctx = this._ctx;
if (!ctx.isPrimKey) ctx.op = "openKeyCursor"; // Need the check because IDBObjectStore does not have "openKeyCursor()" while IDBIndex has.
var a = [];
return this.each(function (item, cursor) {
a.push(cursor.key);
}).then(function () {
return a;
}).then(cb);
},
uniqueKeys: function (cb) {
this._ctx.unique = "unique";
return this.keys(cb);
},
firstKey: function (cb) {
var self = this;
//fakeAutoComplete(function () { cb(getInstanceTemplate(self._ctx)[self._ctx.index]); });
//debugger;
return this.limit(1).keys(function (a) { return a[0]; }).then(cb);
},
lastKey: function (cb) {
return this.reverse().firstKey(cb);
},
distinct: function () {
var set = {};
addFilter(this._ctx, function (cursor) {
var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string
var found = set.hasOwnProperty(strKey);
set[strKey] = true;
return !found;
});
return this;
}
};
});
//
//
// WriteableCollection Class
//
//
function WriteableCollection() {
Collection.apply(this, arguments);
}
derive(WriteableCollection).from(Collection).extend({
//
// WriteableCollection Public Methods
//
modify: function (changes) {
var self = this,
ctx = this._ctx,
hook = ctx.table.hook,
updatingHook = hook.updating.fire,
deletingHook = hook.deleting.fire;
fakeAutoComplete(function () {
if (typeof changes === 'function') {
changes.call({ value: ctx.table.schema.instanceTemplate }, ctx.table.schema.instanceTemplate);
}
});
return this._write(function (resolve, reject, idbstore, trans) {
var modifyer;
if (typeof changes === 'function') {
// Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)
if (updatingHook === nop && deletingHook === nop) {
// Noone cares about what is being changed. Just let the modifier function be the given argument as is.
modifyer = changes;
} else {
// People want to know exactly what is being modified or deleted.
// Let modifyer be a proxy function that finds out what changes the caller is actually doing
// and call the hooks accordingly!
modifyer = function (item) {
var origItem = deepClone(item); // Clone the item first so we can compare laters.
if (changes.call(this, item) === false) return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object)
if (!this.hasOwnProperty("value")) {
// The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place.
deletingHook.call(this, this.primKey, item, trans);
} else {
// No deletion. Check what was changed
var objectDiff = getObjectDiff(origItem, this.value);
var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans);
if (additionalChanges) {
// Hook want to apply additional modifications. Make sure to fullfill the will of the hook.
item = this.value;
Object.keys(additionalChanges).forEach(function (keyPath) {
setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath
});
}
}
};
}
} else if (updatingHook === nop) {
// changes is a set of {keyPath: value} and no one is listening to the updating hook.
var keyPaths = Object.keys(changes);
var numKeys = keyPaths.length;
modifyer = function (item) {
var anythingModified = false;
for (var i = 0; i < numKeys; ++i) {
var keyPath = keyPaths[i], val = changes[keyPath];
if (getByKeyPath(item, keyPath) !== val) {
setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath
anythingModified = true;
}
}
return anythingModified;
};
} else {
// changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and
// allow it to add additional modifications to make.
var origChanges = changes;
changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it.
modifyer = function (item) {
var anythingModified = false;
var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans);
if (additionalChanges) extend(changes, additionalChanges);
Object.keys(changes).forEach(function (keyPath) {
var val = changes[keyPath];
if (getByKeyPath(item, keyPath) !== val) {
setByKeyPath(item, keyPath, changes[keyPath]);
anythingModified = true;
}
});
if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes.
return anythingModified;
};
}
var count = 0;
var successCount = 0;
var iterationComplete = false;
var failures = [];
var failKeys = [];
var currentKey = null;
function modifyItem(item, cursor, advance) {
currentKey = cursor.primaryKey;
var thisContext = { primKey: cursor.primaryKey, value: item };
if (modifyer.call(thisContext, item) !== false) { // If a callback explicitely returns false, do not perform the update!
var bDelete = !thisContext.hasOwnProperty("value");
var req = (bDelete ? cursor.delete() : cursor.update(thisContext.value));
++count;
req.onerror = eventRejectHandler(function (e) {
failures.push(e);
failKeys.push(thisContext.primKey);
if (thisContext.onerror) thisContext.onerror(e);
return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction
}, bDelete ? ["deleting", item, "from", ctx.table.name] : ["modifying", item, "on", ctx.table.name]);
req.onsuccess = function (ev) {
if (thisContext.onsuccess) thisContext.onsuccess(thisContext.value);
++successCount;
checkFinished();
};
}
}
function doReject(e) {
if (e) {
failures.push(e);
failKeys.push(currentKey);
}
return reject(new ModifyError("Error modifying one or more objects", failures, successCount, failKeys));
}
function checkFinished() {
if (iterationComplete && successCount + failures.length === count) {
if (failures.length > 0)
doReject();
else
resolve(successCount);
}
}
self._iterate(modifyItem, function () {
iterationComplete = true;
checkFinished();
}, doReject, idbstore);
});
},
'delete': function () {
return this.modify(function () { delete this.value; });
}
});
//
//
//
// ------------------------- Help functions ---------------------------
//
//
//
function lowerVersionFirst(a, b) {
return a._cfg.version - b._cfg.version;
}
function setApiOnPlace(objs, transactionPromiseFactory, tableNames, mode, dbschema, enableProhibitedDB) {
tableNames.forEach(function (tableName) {
var tableInstance = db._tableFactory(mode, dbschema[tableName], transactionPromiseFactory);
objs.forEach(function (obj) {
if (!obj[tableName]) {
if (enableProhibitedDB) {
Object.defineProperty(obj, tableName, {
configurable: true,
enumerable: true,
get: function () {
if (Promise.PSD && Promise.PSD.trans) {
return Promise.PSD.trans.tables[tableName];
}
return tableInstance;
}
});
} else {
obj[tableName] = tableInstance;
}
}
});
});
}
function removeTablesApi(objs) {
objs.forEach(function (obj) {
for (var key in obj) {
if (obj[key] instanceof Table) delete obj[key];
}
});
}
function iterate(req, filter, fn, resolve, reject, readingHook) {
var psd = Promise.PSD;
readingHook = readingHook || mirror;
if (!req.onerror) req.onerror = eventRejectHandler(reject);
if (filter) {
req.onsuccess = trycatch(function filter_record(e) {
var cursor = req.result;
if (cursor) {
var c = function () { cursor.continue(); };
if (filter(cursor, function (advancer) { c = advancer; }, resolve, reject))
fn(readingHook(cursor.value), cursor, function (advancer) { c = advancer; });
c();
} else {
resolve();
}
}, reject, psd);
} else {
req.onsuccess = trycatch(function filter_record(e) {
var cursor = req.result;
if (cursor) {
var c = function () { cursor.continue(); };
fn(readingHook(cursor.value), cursor, function (advancer) { c = advancer; });
c();
} else {
resolve();
}
}, reject, psd);
}
}
function parseIndexSyntax(indexes) {
/// <param name="indexes" type="String"></param>
/// <returns type="Array" elementType="IndexSpec"></returns>
var rv = [];
indexes.split(',').forEach(function (index) {
index = index.trim();
var name = index.replace("&", "").replace("++", "").replace("*", "");
var keyPath = (name.indexOf('[') !== 0 ? name : index.substring(index.indexOf('[') + 1, index.indexOf(']')).split('+'));
rv.push(new IndexSpec(
name,
keyPath || null,
index.indexOf('&') !== -1,
index.indexOf('*') !== -1,
index.indexOf("++") !== -1,
Array.isArray(keyPath),
keyPath.indexOf('.') !== -1
));
});
return rv;
}
function ascending(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
}
function descending(a, b) {
return a < b ? 1 : a > b ? -1 : 0;
}
function compoundCompare(itemCompare) {
return function (a, b) {
var i = 0;
while (true) {
var result = itemCompare(a[i], b[i]);
if (result !== 0) return result;
++i;
if (i === a.length || i === b.length)
return itemCompare(a.length, b.length);
}
};
}
function combine(filter1, filter2) {
return filter1 ? filter2 ? function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : filter1 : filter2;
}
function hasIEDeleteObjectStoreBug() {
// Assume bug is present in IE10 and IE11 but dont expect it in next version of IE (IE12)
return navigator.userAgent.indexOf("Trident") >= 0 || navigator.userAgent.indexOf("MSIE") >= 0;
}
function readGlobalSchema() {
db.verno = idbdb.version / 10;
db._dbSchema = globalSchema = {};
dbStoreNames = [].slice.call(idbdb.objectStoreNames, 0);
if (dbStoreNames.length === 0) return; // Database contains no stores.
var trans = idbdb.transaction(dbStoreNames, 'readonly');
dbStoreNames.forEach(function (storeName) {
var store = trans.objectStore(storeName),
keyPath = store.keyPath,
dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;
var primKey = new IndexSpec(keyPath, keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted);
var indexes = [];
for (var j = 0; j < store.indexNames.length; ++j) {
var idbindex = store.index(store.indexNames[j]);
keyPath = idbindex.keyPath;
dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;
var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted);
indexes.push(index);
}
globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {});
});
setApiOnPlace([allTables], db._transPromiseFactory, Object.keys(globalSchema), READWRITE, globalSchema);
}
function adjustToExistingIndexNames(schema, idbtrans) {
/// <summary>
/// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db
/// </summary>
/// <param name="schema" type="Object">Map between name and TableSchema</param>
/// <param name="idbtrans" type="IDBTransaction"></param>
var storeNames = idbtrans.db.objectStoreNames;
for (var i = 0; i < storeNames.length; ++i) {
var storeName = storeNames[i];
var store = idbtrans.objectStore(storeName);
for (var j = 0; j < store.indexNames.length; ++j) {
var indexName = store.indexNames[j];
var keyPath = store.index(indexName).keyPath;
var dexieName = typeof keyPath === 'string' ? keyPath : "[" + [].slice.call(keyPath).join('+') + "]";
if (schema[storeName]) {
var indexSpec = schema[storeName].idxByName[dexieName];
if (indexSpec) indexSpec.name = indexName;
}
}
}
}
extend(this, {
Collection: Collection,
Table: Table,
Transaction: Transaction,
Version: Version,
WhereClause: WhereClause,
WriteableCollection: WriteableCollection,
WriteableTable: WriteableTable
});
init();
Dexie.addons.forEach(function (fn) {
fn(db);
});
}
//
// Promise Class
//
// A variant of promise-light (https://github.com/taylorhakes/promise-light) by https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.
//
// Modified by David Fahlander to be indexedDB compliant (See discussion: https://github.com/promises-aplus/promises-spec/issues/45) .
// This implementation will not use setTimeout or setImmediate when it's not needed. The behavior is 100% Promise/A+ compliant since
// the caller of new Promise() can be certain that the promise wont be triggered the lines after constructing the promise. We fix this by using the member variable constructing to check
// whether the object is being constructed when reject or resolve is called. If so, the use setTimeout/setImmediate to fulfill the promise, otherwise, we know that it's not needed.
//
// This topic was also discussed in the following thread: https://github.com/promises-aplus/promises-spec/issues/45 and this implementation solves that issue.
//
// Another feature with this Promise implementation is that reject will return false in case no one catched the reject call. This is used
// to stopPropagation() on the IDBRequest error event in case it was catched but not otherwise.
//
// Also, the event new Promise().onuncatched is called in case no one catches a reject call. This is used for us to manually bubble any request
// errors to the transaction. We must not rely on IndexedDB implementation to do this, because it only does so when the source of the rejection
// is an error event on a request, not in case an ordinary exception is thrown.
var Promise = (function () {
// The use of asap in handle() is remarked because we must NOT use setTimeout(fn,0) because it causes premature commit of indexedDB transactions - which is according to indexedDB specification.
var _slice = [].slice;
var _asap = typeof (setImmediate) === 'undefined' ? function(fn, arg1, arg2, argN) {
var args = arguments;
setTimeout(function() { fn.apply(window, _slice.call(args, 1)); }, 0); // If not FF13 and earlier failed, we could use this call here instead: setTimeout.call(this, [fn, 0].concat(arguments));
} : setImmediate; // IE10+ and node.
var asap = _asap,
isRootExecution = true;
var operationsQueue = [];
function enqueueImmediate(fn, args) {
operationsQueue.push([fn, _slice.call(arguments, 1)]);
}
function executeOperationsQueue() {
var queue = operationsQueue;
operationsQueue = [];
for (var i = 0, l = queue.length; i < l; ++i) {
var item = queue[i];
item[0].apply(window, item[1]);
}
}
//var PromiseID = 0;
function Promise(fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
if (typeof fn !== 'function') throw new TypeError('not a function');
this._state = null; // null (=pending), false (=rejected) or true (=resolved)
this._value = null; // error or result
this._deferreds = [];
this._catched = false; // for onuncatched
//this._id = ++PromiseID;
var self = this;
var constructing = true;
this._PSD = Promise.PSD;
try {
doResolve(this, fn, function (data) {
if (constructing)
asap(resolve, self, data);
else
resolve(self, data);
}, function (reason) {
if (constructing) {
asap(reject, self, reason);
return false;
} else {
return reject(self, reason);
}
});
} finally {
constructing = false;
}
}
function handle(self, deferred) {
if (self._state === null) {
self._deferreds.push(deferred);
return;
}
var cb = self._state ? deferred.onFulfilled : deferred.onRejected;
if (cb === null) {
// This Deferred doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch()
return (self._state ? deferred.resolve : deferred.reject)(self._value);
}
var ret, isRootExec = isRootExecution;
isRootExecution = false;
asap = enqueueImmediate;
try {
ret = cb(self._value);
if (!self._state && (!ret || typeof ret.then !== 'function' || ret._state !== false)) setCatched(self); // Caller did 'return Promise.reject(err);' - don't regard it as catched!
} catch (e) {
var catched = deferred.reject(e);
if (!catched && self.onuncatched) {
try { self.onuncatched(e); } catch (e) { }
}
return;
}
deferred.resolve(ret);
if (isRootExec) {
while(operationsQueue.length > 0) executeOperationsQueue();
asap = _asap;
isRootExecution = true;
}
}
function setCatched(promise) {
promise._catched = true;
if (promise._parent) setCatched(promise._parent);
}
function resolve(promise, newValue) {
var outerPSD = Promise.PSD;
Promise.PSD = promise._PSD;
try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === promise) throw new TypeError('A promise cannot be resolved with itself.');
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
if (typeof newValue.then === 'function') {
doResolve(promise, function (resolve, reject) {
newValue.then(resolve, reject);
}, function (data) {
resolve(promise, data);
}, function (reason) {
reject(promise, reason);
});
return;
}
}
promise._state = true;
promise._value = newValue;
finale.call(promise);
} catch (e) { reject(e); } finally {
Promise.PSD = outerPSD;
}
}
function reject(promise, newValue) {
var outerPSD = Promise.PSD;
Promise.PSD = promise._PSD;
promise._state = false;
promise._value = newValue;
finale.call(promise);
if (!promise._catched && promise.onuncatched) {
try { promise.onuncatched(promise._value); } catch (e) { }
}
Promise.PSD = outerPSD;
return promise._catched;
}
function finale() {
for (var i = 0, len = this._deferreds.length; i < len; i++) {
handle(this, this._deferreds[i]);
}
this._deferreds = [];
}
function Deferred(onFulfilled, onRejected, resolve, reject) {
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
this.onRejected = typeof onRejected === 'function' ? onRejected : null;
this.resolve = resolve;
this.reject = reject;
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(promise, fn, onFulfilled, onRejected) {
var done = false;
try {
fn(function Promise_resolve(value) {
if (done) return;
done = true;
onFulfilled(value);
}, function Promise_reject(reason) {
if (done) return promise._catched;
done = true;
return onRejected(reason);
});
} catch (ex) {
if (done) return;
return onRejected(ex);
}
}
Promise.all = function () {
var args = Array.prototype.slice.call(arguments.length === 1 && Array.isArray(arguments[0]) ? arguments[0] : arguments);
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([]);
var remaining = args.length;
function res(i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then;
if (typeof then === 'function') {
then.call(val, function (val) { res(i, val); }, reject);
return;
}
}
args[i] = val;
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex);
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i]);
}
});
};
/* Prototype Methods */
Promise.prototype.then = function (onFulfilled, onRejected) {
var self = this;
var p = new Promise(function (resolve, reject) {
if (self._state === null)
handle(self, new Deferred(onFulfilled, onRejected, resolve, reject));
else
asap(handle, self, new Deferred(onFulfilled, onRejected, resolve, reject));
});
p._PSD = this._PSD;
p.onuncatched = this.onuncatched; // Needed when exception occurs in a then() clause of a successful parent promise. Want onuncatched to be called even in callbacks of callbacks of the original promise.
p._parent = this; // Used for recursively calling onuncatched event on self and all parents.
return p;
};
Promise.prototype['catch'] = function (onRejected) {
if (arguments.length === 1) return this.then(null, onRejected);
// First argument is the Error type to catch
var type = arguments[0], callback = arguments[1];
if (typeof type === 'function') return this.then(null, function (e) {
// Catching errors by its constructor type (similar to java / c++ / c#)
// Sample: promise.catch(TypeError, function (e) { ... });
if (e instanceof type) return callback(e); else return Promise.reject(e);
});
else return this.then(null, function (e) {
// Catching errors by the error.name property. Makes sense for indexedDB where error type
// is always DOMError but where e.name tells the actual error type.
// Sample: promise.catch('ConstraintError', function (e) { ... });
if (e && e.name === type) return callback(e); else return Promise.reject(e);
});
};
Promise.prototype['finally'] = function (onFinally) {
return this.then(function (value) {
onFinally();
return value;
}, function (err) {
onFinally();
return Promise.reject(err);
});
};
Promise.prototype.onuncatched = null; // Optional event triggered if promise is rejected but no one listened.
Promise.resolve = function (value) {
var p = new Promise(function () { });
p._state = true;
p._value = value;
return p;
};
Promise.reject = function (value) {
var p = new Promise(function () { });
p._state = false;
p._value = value;
return p;
};
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
values.map(function (value) {
value.then(resolve, reject);
});
});
};
Promise.PSD = null; // Promise Specific Data - a TLS Pattern (Thread Local Storage) for Promises. TODO: Rename Promise.PSD to Promise.data
Promise.newPSD = function (fn) {
// Create new PSD scope (Promise Specific Data)
var outerScope = Promise.PSD;
Promise.PSD = outerScope ? Object.create(outerScope) : {};
try {
return fn();
} finally {
Promise.PSD = outerScope;
}
};
return Promise;
})();
//
//
// ------ Exportable Help Functions -------
//
//
function nop() { }
function mirror(val) { return val; }
function pureFunctionChain(f1, f2) {
// Enables chained events that takes ONE argument and returns it to the next function in chain.
// This pattern is used in the hook("reading") event.
if (f1 === mirror) return f2;
return function (val) {
return f2(f1(val));
};
}
function callBoth(on1, on2) {
return function () {
on1.apply(this, arguments);
on2.apply(this, arguments);
};
}
function hookCreatingChain(f1, f2) {
// Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.
// This pattern is used in the hook("creating") event.
if (f1 === nop) return f2;
return function () {
var res = f1.apply(this, arguments);
if (res !== undefined) arguments[0] = res;
var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess
onerror = this.onerror; // In case event listener has set this.onerror
delete this.onsuccess;
delete this.onerror;
var res2 = f2.apply(this, arguments);
if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;
if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;
return res2 !== undefined ? res2 : res;
};
}
function hookUpdatingChain(f1, f2) {
if (f1 === nop) return f2;
return function () {
var res = f1.apply(this, arguments);
if (res !== undefined) extend(arguments[0], res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.
var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess
onerror = this.onerror; // In case event listener has set this.onerror
delete this.onsuccess;
delete this.onerror;
var res2 = f2.apply(this, arguments);
if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;
if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;
return res === undefined ?
(res2 === undefined ? undefined : res2) :
(res2 === undefined ? res : extend(res, res2));
};
}
function stoppableEventChain(f1, f2) {
// Enables chained events that may return false to stop the event chain.
if (f1 === nop) return f2;
return function () {
if (f1.apply(this, arguments) === false) return false;
return f2.apply(this, arguments);
};
}
function reverseStoppableEventChain(f1, f2) {
if (f1 === nop) return f2;
return function () {
if (f2.apply(this, arguments) === false) return false;
return f1.apply(this, arguments);
};
}
function nonStoppableEventChain(f1, f2) {
if (f1 === nop) return f2;
return function () {
f1.apply(this, arguments);
f2.apply(this, arguments);
};
}
function promisableChain(f1, f2) {
if (f1 === nop) return f2;
return function () {
var res = f1.apply(this, arguments);
if (res && typeof res.then === 'function') {
var thiz = this, args = arguments;
return res.then(function () {
return f2.apply(thiz, args);
});
}
return f2.apply(this, arguments);
};
}
function events(ctx, eventNames) {
var args = arguments;
var evs = {};
var rv = function (eventName, subscriber) {
if (subscriber) {
// Subscribe
var args = [].slice.call(arguments, 1);
var ev = evs[eventName];
ev.subscribe.apply(ev, args);
return ctx;
} else if (typeof (eventName) === 'string') {
// Return interface allowing to fire or unsubscribe from event
return evs[eventName];
}
};
rv.addEventType = add;
function add(eventName, chainFunction, defaultFunction) {
if (Array.isArray(eventName)) return addEventGroup(eventName);
if (typeof eventName === 'object') return addConfiguredEvents(eventName);
if (!chainFunction) chainFunction = stoppableEventChain;
if (!defaultFunction) defaultFunction = nop;
var context = {
subscribers: [],
fire: defaultFunction,
subscribe: function (cb) {
context.subscribers.push(cb);
context.fire = chainFunction(context.fire, cb);
},
unsubscribe: function (cb) {
context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; });
context.fire = context.subscribers.reduce(chainFunction, defaultFunction);
}
};
evs[eventName] = rv[eventName] = context;
return context;
}
function addConfiguredEvents(cfg) {
// events(this, {reading: [functionChain, nop]});
Object.keys(cfg).forEach(function (eventName) {
var args = cfg[eventName];
if (Array.isArray(args)) {
add(eventName, cfg[eventName][0], cfg[eventName][1]);
} else if (args === 'asap') {
// Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack
// enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.
var context = add(eventName, null, function fire() {
var args = arguments;
context.subscribers.forEach(function (fn) {
asap(function fireEvent() {
fn.apply(window, args);
});
});
});
context.subscribe = function (fn) {
// Change how subscribe works to not replace the fire function but to just add the subscriber to subscribers
if (context.subscribers.indexOf(fn) === -1)
context.subscribers.push(fn);
};
context.unsubscribe = function (fn) {
// Change how unsubscribe works for the same reason as above.
var idxOfFn = context.subscribers.indexOf(fn);
if (idxOfFn !== -1) context.subscribers.splice(idxOfFn, 1);
};
} else throw new Error("Invalid event config");
});
}
function addEventGroup(eventGroup) {
// promise-based event group (i.e. we promise to call one and only one of the events in the pair, and to only call it once.
var done = false;
eventGroup.forEach(function (name) {
add(name).subscribe(checkDone);
});
function checkDone() {
if (done) return false;
done = true;
}
}
for (var i = 1, l = args.length; i < l; ++i) {
add(args[i]);
}
return rv;
}
function assert(b) {
if (!b) throw new Error("Assertion failed");
}
function asap(fn) {
if (window.setImmediate) setImmediate(fn); else setTimeout(fn, 0);
}
function fakeAutoComplete(fn) {
var to = setTimeout(fn, 1000);
clearTimeout(to);
}
function trycatch(fn, reject, psd) {
return function () {
var outerPSD = Promise.PSD; // Support Promise-specific data (PSD) in callback calls
Promise.PSD = psd;
try {
fn.apply(this, arguments);
} catch (e) {
reject(e);
} finally {
Promise.PSD = outerPSD;
}
};
}
function getByKeyPath(obj, keyPath) {
// http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path
if (obj.hasOwnProperty(keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.
if (!keyPath) return obj;
if (typeof keyPath !== 'string') {
var rv = [];
for (var i = 0, l = keyPath.length; i < l; ++i) {
var val = getByKeyPath(obj, keyPath[i]);
rv.push(val);
}
return rv;
}
var period = keyPath.indexOf('.');
if (period !== -1) {
var innerObj = obj[keyPath.substr(0, period)];
return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));
}
return undefined;
}
function setByKeyPath(obj, keyPath, value) {
if (!obj || keyPath === undefined) return;
if (typeof keyPath !== 'string' && 'length' in keyPath) {
assert(typeof value !== 'string' && 'length' in value);
for (var i = 0, l = keyPath.length; i < l; ++i) {
setByKeyPath(obj, keyPath[i], value[i]);
}
} else {
var period = keyPath.indexOf('.');
if (period !== -1) {
var currentKeyPath = keyPath.substr(0, period);
var remainingKeyPath = keyPath.substr(period + 1);
if (remainingKeyPath === "")
if (value === undefined) delete obj[currentKeyPath]; else obj[currentKeyPath] = value;
else {
var innerObj = obj[currentKeyPath];
if (!innerObj) innerObj = (obj[currentKeyPath] = {});
setByKeyPath(innerObj, remainingKeyPath, value);
}
} else {
if (value === undefined) delete obj[keyPath]; else obj[keyPath] = value;
}
}
}
function delByKeyPath(obj, keyPath) {
setByKeyPath(obj, keyPath, undefined);
}
function shallowClone(obj) {
var rv = {};
for (var m in obj) {
if (obj.hasOwnProperty(m)) rv[m] = obj[m];
}
return rv;
}
function deepClone(any) {
if (!any || typeof any !== 'object') return any;
var rv;
if (Array.isArray(any)) {
rv = [];
for (var i = 0, l = any.length; i < l; ++i) {
rv.push(deepClone(any[i]));
}
} else if (any instanceof Date) {
rv = new Date();
rv.setTime(any.getTime());
} else {
rv = any.constructor ? Object.create(any.constructor.prototype) : {};
for (var prop in any) {
if (any.hasOwnProperty(prop)) {
rv[prop] = deepClone(any[prop]);
}
}
}
return rv;
}
function getObjectDiff(a, b) {
// This is a simplified version that will always return keypaths on the root level.
// If for example a and b differs by: (a.somePropsObject.x != b.somePropsObject.x), we will return that "somePropsObject" is changed
// and not "somePropsObject.x". This is acceptable and true but could be optimized to support nestled changes if that would give a
// big optimization benefit.
var rv = {};
for (var prop in a) if (a.hasOwnProperty(prop)) {
if (!b.hasOwnProperty(prop))
rv[prop] = undefined; // Property removed
else if (a[prop] !== b[prop] && JSON.stringify(a[prop]) !== JSON.stringify(b[prop]))
rv[prop] = b[prop]; // Property changed
}
for (var prop in b) if (b.hasOwnProperty(prop) && !a.hasOwnProperty(prop)) {
rv[prop] = b[prop]; // Property added
}
return rv;
}
function parseType(type) {
if (typeof type === 'function') {
return new type();
} else if (Array.isArray(type)) {
return [parseType(type[0])];
} else if (type && typeof type === 'object') {
var rv = {};
applyStructure(rv, type);
return rv;
} else {
return type;
}
}
function applyStructure(obj, structure) {
Object.keys(structure).forEach(function (member) {
var value = parseType(structure[member]);
obj[member] = value;
});
}
function eventRejectHandler(reject, sentance) {
return function (event) {
var errObj = (event && event.target.error) || new Error();
if (sentance) {
var occurredWhen = " occured when " + sentance.map(function (word) {
switch (typeof (word)) {
case 'function': return word();
case 'string': return word;
default: return JSON.stringify(word);
}
}).join(" ");
if (errObj.name) {
errObj.toString = function toString() {
return errObj.name + occurredWhen + (errObj.message ? ". " + errObj.message : "");
// Code below works for stacked exceptions, BUT! stack is never present in event errors (not in any of the browsers). So it's no use to include it!
/*delete this.toString; // Prohibiting endless recursiveness in IE.
if (errObj.stack) rv += (errObj.stack ? ". Stack: " + errObj.stack : "");
this.toString = toString;
return rv;*/
};
} else {
errObj = errObj + occurredWhen;
}
};
reject(errObj);
// Stop error from propagating to IDBTransaction. Let us handle that manually instead.
event.stopPropagation();
event.preventDefault();
return false;
};
}
function stack(error) {
try {
throw error;
} catch (e) {
return e;
}
}
function preventDefault(e) {
e.preventDefault();
}
function globalDatabaseList(cb) {
var val;
try {
val = JSON.parse(localStorage.getItem('Dexie.DatabaseNames') || "[]");
} catch (e) {
val = [];
}
if (cb(val)) {
localStorage.setItem('Dexie.DatabaseNames', JSON.stringify(val));
}
}
//
// IndexSpec struct
//
function IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) {
/// <param name="name" type="String"></param>
/// <param name="keyPath" type="String"></param>
/// <param name="unique" type="Boolean"></param>
/// <param name="multi" type="Boolean"></param>
/// <param name="auto" type="Boolean"></param>
/// <param name="compound" type="Boolean"></param>
/// <param name="dotted" type="Boolean"></param>
this.name = name;
this.keyPath = keyPath;
this.unique = unique;
this.multi = multi;
this.auto = auto;
this.compound = compound;
this.dotted = dotted;
var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && ('[' + [].join.call(keyPath, '+') + ']');
this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + keyPathSrc;
}
//
// TableSchema struct
//
function TableSchema(name, primKey, indexes, instanceTemplate) {
/// <param name="name" type="String"></param>
/// <param name="primKey" type="IndexSpec"></param>
/// <param name="indexes" type="Array" elementType="IndexSpec"></param>
/// <param name="instanceTemplate" type="Object"></param>
this.name = name;
this.primKey = primKey || new IndexSpec();
this.indexes = indexes || [new IndexSpec()];
this.instanceTemplate = instanceTemplate;
this.mappedClass = null;
this.idxByName = indexes.reduce(function (hashSet, index) {
hashSet[index.name] = index;
return hashSet;
}, {});
}
//
// ModifyError Class (extends Error)
//
function ModifyError(msg, failures, successCount, failedKeys) {
this.name = "ModifyError";
this.failures = failures;
this.failedKeys = failedKeys;
this.successCount = successCount;
this.message = failures.join('\n');
}
derive(ModifyError).from(Error);
//
// Static delete() method.
//
Dexie.delete = function (databaseName) {
var db = new Dexie(databaseName),
promise = db.delete();
promise.onblocked = function (fn) {
db.on("blocked", fn);
return this;
};
return promise;
};
//
// Static method for retrieving a list of all existing databases at current host.
//
Dexie.getDatabaseNames = function (cb) {
return new Promise(function (resolve, reject) {
if ('webkitGetDatabaseNames' in indexedDB || 'getDatabaseNames' in indexedDB) { // In case getDatabaseNames() becomes standard, let's prepare to support it:
var req = ('getDatabaseNames' in indexedDB ? indexedDB.getDatabaseNames() : indexedDB.webkitGetDatabaseNames());
req.onsuccess = function (event) {
resolve([].slice.call(event.target.result, 0)); // Converst DOMStringList to Array<String>
};
req.onerror = eventRejectHandler(reject);
} else {
globalDatabaseList(function (val) {
resolve(val);
return false;
});
}
}).then(cb);
};
Dexie.defineClass = function (structure) {
/// <summary>
/// Create a javascript constructor based on given template for which properties to expect in the class.
/// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}.
/// </summary>
/// <param name="structure">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also
/// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}</param>
// Default constructor able to copy given properties into this object.
function Class(properties) {
/// <param name="properties" type="Object" optional="true">Properties to initialize object with.
/// </param>
if (properties) extend(this, properties);
}
applyStructure(Class.prototype, structure);
return Class;
};
Dexie.spawn = function (scopeFunc) {
// In case caller is within a transaction but needs to create a separate transaction.
// Example of usage:
//
// Let's say we have a logger function in our app. Other application-logic should be unaware of the
// logger function and not need to include the 'logentries' table in all transaction it performs.
// The logging should always be done in a separate transaction and not be dependant on the current
// running transaction context. Then you could use Dexie.spawn() to run code that starts a new transaction.
//
// Dexie.spawn(function() {
// db.logentries.add(newLogEntry);
// });
//
// Unless using Dexie.spawn(), the above example would try to reuse the current transaction
// in current Promise-scope.
//
// An alternative to Dexie.spawn() would be setImmediate() or setTimeout(). The reason we still provide an
// API for this because
// 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().
// 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().
// 3) setImmediate() is not supported in the ES standard.
return Promise.newPSD(function () {
Promise.PSD.trans = null;
return scopeFunc();
});
};
Dexie.vip = function (fn) {
// To be used by subscribers to the on('ready') event.
// This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.
// This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD
// from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since
// the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.
// Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()
// the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by
// the caller will not resolve until database is opened.
return Promise.newPSD(function () {
Promise.PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.
return fn();
});
};
// Dexie.currentTransaction property. Only applicable for transactions entered using the new "transact()" method.
Object.defineProperty(Dexie, "currentTransaction", {
get: function () {
/// <returns type="Transaction"></returns>
return Promise.PSD && Promise.PSD.trans || null;
}
});
// Export our Promise implementation since it can be handy as a standalone Promise implementation
Dexie.Promise = Promise;
// Export our derive/extend/override methodology
Dexie.derive = derive;
Dexie.extend = extend;
Dexie.override = override;
// Export our events() function - can be handy as a toolkit
Dexie.events = events;
Dexie.getByKeyPath = getByKeyPath;
Dexie.setByKeyPath = setByKeyPath;
Dexie.delByKeyPath = delByKeyPath;
Dexie.shallowClone = shallowClone;
Dexie.deepClone = deepClone;
Dexie.addons = [];
Dexie.fakeAutoComplete = fakeAutoComplete;
Dexie.asap = asap;
// Export our static classes
Dexie.ModifyError = ModifyError;
Dexie.MultiModifyError = ModifyError; // Backward compatibility pre 0.9.8
Dexie.IndexSpec = IndexSpec;
Dexie.TableSchema = TableSchema;
//
// Dependencies
//
// These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.
//
// In node.js, however, these properties must be set "manually" before instansiating a new Dexie(). For node.js, you need to require indexeddb-js or similar and then set these deps.
//
Dexie.dependencies = {
// Required:
indexedDB: window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB,
IDBKeyRange: window.IDBKeyRange || window.webkitIDBKeyRange,
IDBTransaction: window.IDBTransaction || window.webkitIDBTransaction,
// Optional:
Error: window.Error || String,
SyntaxError: window.SyntaxError || String,
TypeError: window.TypeError || String,
DOMError: window.DOMError || String
};
// API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc.
Dexie.version = 1.02;
// Publish the Dexie to browser or NodeJS environment.
publish("Dexie", Dexie);
}).apply(this, typeof module === 'undefined' || (typeof window !== 'undefined' && this === window)
? [window, function (name, value) { window[name] = value; }, true] // Adapt to browser environment
: [global, function (name, value) { module.exports = value; }, false]); // Adapt to Node.js environment
|
KaySchneider/istart-ntp
|
app/backendScript/eventADexie.js
|
JavaScript
|
gpl-3.0
| 154,068 |
'use strict';
const program = require('commander');
const debug = require('debug')('kcm:make_program');
const pkg = require('../package.json');
module.exports = function makeProgram(hasY) {
debug('Start to make a commander instance...');
let tmp = program
.version(pkg.version)
.option('-H, --host [value]', 'host of admin APIs of kong instance')
.option(
'-f, --file [path]',
'path of config file for this CLI tool, default to `./kcm-config.json`',
'./kcm-config.json'
)
.option(
'-i, --instance [name]',
'when you have many kong instances to manage, specify a name, default to `main`. NOTE: this requires `--file` option rather than `--host`',
'main'
)
.option(
'-a, --all',
'whether to operate on all kong instances listed in CLI config file. NOTE: this requires `--file` option rather than `--host`'
)
.option(
'-k, --no-ssl',
'whether ignore ssl certificates errors, default to `false`',
false
)
.option('--no-git', 'use this tool without the help of git');
if (hasY) {
tmp = tmp.option(
'-y, --yes',
'whether go on directly while asking for yes or no'
);
}
debug('Finished!');
return tmp.parse(process.argv);
};
|
Maples7/kong-config-manager
|
utils/make_program.js
|
JavaScript
|
gpl-3.0
| 1,262 |
'use strict'
const test = require('tape')
const SparseArray = require('../')
const max = 100
let arr
test('allows creation', (t) => {
arr = new SparseArray()
t.end()
})
test('allows pushing', (t) => {
for(let i = 0; i < max; i++) {
const pos = arr.push(i.toString())
t.equal(pos, i + 1)
}
t.end()
})
test('find foundable', (t) => {
const min = Math.floor(max / 2)
t.equal(arr.find(elem => Number(elem) >= min), min.toString())
t.end()
})
test('does not find unfoundable', (t) => {
t.equal(arr.find(elem => Number(elem) > max), undefined)
t.end()
})
|
js0p/sprouts
|
node_modules/sparse-array/tests/test-find.js
|
JavaScript
|
gpl-3.0
| 583 |
var test = require("test");
test.setup();
var coroutine = require('coroutine');
describe('lock', () => {
it("Lock", () => {
var l = new coroutine.Lock();
assert.throws(() => {
l.release();
});
var v = 100;
function f() {
l.acquire();
v = 200;
coroutine.sleep(1);
v = 300;
l.release();
}
coroutine.start(f);
coroutine.sleep(1);
l.acquire();
assert.equal(300, v);
l.release();
});
it("Semaphore", () => {
var sem = new coroutine.Semaphore();
assert.equal(true, sem.trywait());
assert.equal(false, sem.trywait());
var v = 100;
var run = true;
function f1() {
while (run) {
sem.wait();
v++;
}
}
coroutine.start(f1);
coroutine.sleep(1);
assert.equal(100, v);
sem.post();
coroutine.sleep(1);
assert.equal(101, v);
for (var i = 0; i < 10; i++)
sem.post();
coroutine.sleep(1);
assert.equal(111, v);
run = false;
sem.post();
});
it("Condition", () => {
var v = 0;
var cond = new coroutine.Condition();
assert.throws(() => {
cond.wait();
});
function f3() {
cond.acquire();
while (v <= 0)
cond.wait();
assert.equal(100, v);
v += 100;
cond.release();
}
coroutine.start(f3);
cond.acquire();
coroutine.sleep(1);
cond.notify();
coroutine.sleep(1);
assert.equal(0, v);
cond.acquire();
v = 100;
cond.notify();
coroutine.sleep(1);
assert.equal(200, v);
});
});
repl && test.run(console.DEBUG);
|
onceyoung/fibjs
|
test/lock_test.js
|
JavaScript
|
gpl-3.0
| 1,916 |
/**
* Events list
*/
jQuery( document ).on( 'widget-updated widget-added ready', initWidgetCategoriesTiles );
/**
* Renumber list
* @returns {undefined}
*/
function reNumberCategoriesTiles( categories ) {
categories.find( '.category-area' ).each( function( index ) {
jQuery( this ).find( 'h3 span' ).html( index + 1 );
});
}
/**
* ReInit widget
* @returns {undefined}
*/
function reInitWidgetCategoriesTiles() {
jQuery( '.tm-categories-tiles-form-widget select, .tm-categories-tiles-form-widget input[type=text]' ).off( 'change' );
jQuery( '.tm-categories-tiles-form-widget div.upload-image img' ).off( 'click' );
jQuery( '.tm-categories-tiles-form-widget .upload-image .delete-image-url' ).off( 'click' );
jQuery( '.tm-categories-tiles-form-widget .category-area .delete-category' ).off( 'click' );
jQuery( '.tm-categories-tiles-form-widget .categories .add-category' ).off( 'click' );
initWidgetCategoriesTiles();
}
/**
* Initialization widget js
*
* @returns {undefined}
*/
function initWidgetCategoriesTiles() {
jQuery( '.tm-categories-tiles-form-widget select, .tm-categories-tiles-form-widget input[type=text]' ).change( function() {
jQuery( document ).trigger( 'widget-change' );
});
// Upload image
jQuery( '.tm-categories-tiles-form-widget div.upload-image img' ).click( function( e ) {
var _this = jQuery( this );
var inputImage = _this.parents( '.category-area' ).find( '.custom-image-url' );
var inputAvatar = _this.parents( '.category-area' ).find( '.upload-image img' );
var customUploader = wp.media( {
title: 'Upload a Image',
button: {
text: 'Select'
},
multiple: false
} );
customUploader.on( 'select', function() {
var imgurl = customUploader.state().get( 'selection' ).first().attributes.url;
inputImage.val( imgurl ).trigger( 'change' );
inputAvatar.attr( 'src', imgurl );
});
customUploader.open();
e.preventDefault();
});
// Delete image
jQuery( '.tm-categories-tiles-form-widget .upload-image .delete-image-url' ).click( function() {
var _this = jQuery( this );
var inputImage = _this.parents( '.category-area' ).find( '.custom-image-url' );
var inputAvatar = _this.parents( '.category-area' ).find( '.upload-image img' );
var defaultAvatar = inputAvatar.attr( 'default_image' );
inputAvatar.attr( 'src', defaultAvatar );
inputImage.val( '' ).trigger( 'change' );
return false;
});
// Delete category
jQuery( '.tm-categories-tiles-form-widget .category-area .delete-category' ).click( function() {
var _this = jQuery( this );
var category = _this.parents( '.category-area' );
var categories = _this.parents( '.tm-categories-tiles-form-widget' ).find( '.categories' );
var categoriesCount = parseInt( categories.attr( 'count' ), 10 ) - 1;
categories.attr( 'count', categoriesCount );
category.find( 'input' ).trigger( 'change' );
category.remove();
reNumberCategoriesTiles( categories );
reInitWidgetCategoriesTiles();
});
// Add category
jQuery( '.tm-categories-tiles-form-widget .categories .add-category' ).click( function() {
var _this = jQuery( this );
var categories = _this.parents( '.tm-categories-tiles-form-widget' ).find( '.categories' );
var categoriesCount = parseInt( categories.attr( 'count' ), 10 ) + 1;
var category = _this.parents( '.tm-categories-tiles-form-widget' ).find( '.category-new' );
var categoryNew = category.clone();
var inputImage = categoryNew.find( '.custom-image-url' );
var inputAvatar = categoryNew.find( '.upload-image img' );
var defaultAvatar = inputAvatar.attr( 'default_image' );
var selectCategory = categoryNew.find( 'select' );
category.before( categoryNew );
inputAvatar.attr( 'src', defaultAvatar );
selectCategory.val( '1' );
inputImage.val( '' );
categories.attr( 'count', categoriesCount );
categoryNew.toggleClass( 'category-area category-new' );
categoryNew.find( 'input' ).each( function() {
var _inputItem = jQuery( this );
var name = _inputItem.attr( 'name' );
name = name.replace( '_new', '' );
_inputItem.attr( 'name', name );
});
categoryNew.find( 'select' ).each( function() {
var _inputItem = jQuery( this );
var name = _inputItem.attr( 'name' );
name = name.replace( '_new', '' );
_inputItem.attr( 'name', name );
});
categoryNew.find( 'h3 span' ).html( categoriesCount );
categoryNew.find( 'input' ).trigger( 'change' );
jQuery( document ).trigger( 'widget-change' );
reNumberCategoriesTiles( categories );
reInitWidgetCategoriesTiles();
});
}
|
gcofficial/basetheme
|
app/assets/js/categories-tiles-widget-admin.js
|
JavaScript
|
gpl-3.0
| 4,525 |
/*
* Copyright (C) 2010-2016 Structr GmbH
*
* This file is part of Structr <http://structr.org>.
*
* Structr is free software: you can redistribute it and/or modify
* it under the terms of 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.
*
* Structr is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Structr. If not, see <http://www.gnu.org/licenses/>.
*/
var s = require('../setup'),
login = require('../templates/login'),
createPage = require('../templates/createPage');
var testName = '004_create_page';
var heading = "Create Page", sections = [];
var desc = "This animation shows how an empty page is created."
var numberOfTests = 3;
s.startRecording(window, casper, testName);
casper.test.begin(testName, numberOfTests, function (test) {
casper.start(s.url);
login.init(test, 'admin', 'admin');
createPage.init(test, 'test-page');
casper.then(function () {
test.assertEval(function () {
return $('#previewTabs li.page.active .name_').text() === 'test-page';
});
});
sections.push('If it is not already active, click on the "Pages" menu entry.');
sections.push('Click on the icon with the green plus on the rightmost tab above the preview frame.');
sections.push('A new page with a random name has been created. The page is automatically loaded into the preview window.');
casper.then(function () {
s.animateHtml(testName, heading, sections);
this.exit();
});
casper.run();
});
|
MarcelStructr/structr
|
structr-ui/src/test/javascript/004_create_page.js
|
JavaScript
|
gpl-3.0
| 1,908 |
import format from 'date-fns/format';
import { map, tap, catchError } from 'rxjs/operators';
import { of, pipe } from 'rxjs';
import { ofType } from 'redux-observable';
import { PACKAGE_GROUPS } from 'constants/AppConstants';
import { readPackageJson } from 'commons/utils';
import {
mapPackages,
mapOutdatedPackages,
setPackagesSuccess,
setPackagesSearchSuccess,
setOutdatedSuccess,
mapSearchPackages,
} from '../actions';
const setSearchPackages = (payload) => ({
type: setPackagesSearchSuccess.type,
payload,
});
const setPackages = (payload) => ({
type: setPackagesSuccess.type,
payload,
});
const setOutdatedPackages = (payload) => ({
type: setOutdatedSuccess.type,
payload,
});
const mapSearchPackagesEpic = (action$) =>
action$.pipe(
ofType(mapSearchPackages.type),
map(({ payload: { data, fromSearch } }) => {
const enhancedDependencies = data.map(({ name, version }) => ({
name,
latest: version,
version: null,
}));
return setSearchPackages({
dependencies: enhancedDependencies,
fromSearch,
lastUpdatedAt: format(new Date(), 'dd/MM/yyyy h:mm'),
});
}),
catchError((error) =>
of({
type: '@@LUNA/ERROR/SEARCH_PACKAGES',
error: error.toString(),
})
)
);
const mapPackagesEpic = (action$, state$) =>
action$.pipe(
ofType(mapPackages.type),
map(
({
payload: {
data,
fromSearch,
fromSort,
projectName,
projectDescription,
projectVersion,
},
}) => {
const {
common: { mode, directory },
packages: {
packagesOutdated,
project: { name, version, description },
},
} = state$.value;
const enhancedDependencies = data.reduce(
(alldependencies, dependency) => {
const [pkgName, details] = fromSearch
? [
dependency.name,
{
version: dependency.version,
description: dependency.description,
},
]
: dependency;
const { extraneous, invalid, missing, peerMissing, problems } =
details || {};
const isOutdated = packagesOutdated.some((o) => o.name === pkgName);
const outdatedPkg = packagesOutdated.find(
(o) => o.name === pkgName
);
// side effect
const packageJSON = readPackageJson(directory);
const group =
mode === 'local'
? Object.keys(PACKAGE_GROUPS).find(
(groupName) =>
packageJSON[groupName] && packageJSON[groupName][pkgName]
)
: null;
return [
...alldependencies,
{
name: pkgName,
isOutdated,
latest:
isOutdated && outdatedPkg
? outdatedPkg.latest
: details.version,
__invalid: invalid,
__hasError: extraneous,
__missing: missing,
__peerMissing: peerMissing,
__fromSearch: fromSearch,
__group: group,
...details,
},
];
},
[]
);
const dependencies = enhancedDependencies.filter(
(dependency) =>
!dependency.__invalid &&
!dependency.__hasError &&
!dependency.__peerMissing &&
!dependency.__missing
);
return setPackages({
dependencies,
projectName: fromSearch ? name : projectName,
projectDescription: fromSearch ? description : projectDescription,
projectVersion: fromSearch ? version : projectVersion,
fromSearch,
fromSort,
lastUpdatedAt: format(new Date(), 'dd/MM/yyyy h:mm'),
});
}
),
catchError((error) =>
of({
type: '@@LUNA/ERROR/MAP_PACKAGES',
error: error.toString(),
})
)
);
const mapOutdatedPackagesEpic = pipe(
ofType(mapOutdatedPackages.type),
map(({ payload: { data } }) =>
data.reduce((alldependencies, dependency) => {
const [name, details] = dependency;
return [
...alldependencies,
{
name,
isOutdated: true,
...details,
},
];
}, [])
),
map((alldependencies) => setOutdatedPackages({ outdated: alldependencies })),
catchError((error) =>
of({
type: '@@LUNA/ERROR/MAP_OUTDATED_PACKAGES',
error: error.toString(),
})
)
);
export { mapPackagesEpic, mapOutdatedPackagesEpic, mapSearchPackagesEpic };
|
rvpanoz/luna
|
app/models/packages/epics/transformEpics.js
|
JavaScript
|
gpl-3.0
| 4,862 |
"use strict";
module.exports = Object.freeze({
// App-ID. TODO: set to your own Skill App ID from the developer portal.
appId : 'amzn1.ask.skill.5def441f-b36d-4f44-a8d7-f3c1a4837e17',
// DynamoDB Table name
dynamoDBTableName : 'stampSkill'
});
|
jpecore/AlexaStampSkill
|
src/constants.js
|
JavaScript
|
gpl-3.0
| 292 |
Joomla 3.4.1 = 68f807052420e16a2697b4cc1da56970
|
gohdan/DFC
|
known_files/hashes/media/editors/codemirror/mode/markdown/test.js
|
JavaScript
|
gpl-3.0
| 48 |
var searchData=
[
['rawinput',['RawInput',['../moves_8h.html#struct_raw_input',1,'']]]
];
|
sherman5/MeleeModdingLibrary
|
docs/search/classes_8.js
|
JavaScript
|
gpl-3.0
| 92 |
/* GENERATED */
initParams = { forceErrorCorrection:1, reverseAnswers:1, interQuestionDelay:250, stimuliShowCount:0, leftKeyChar:"D", rightKeyChar:"K", tooSlowMessageMS:2000, tooSlowMessageShowTimeMS:600, practiceMode:1, practiceSuccessThreasholdCorrect:0.80, practiceSuccessThreasholdMedianMS:2000, showPracticeStats:1 };
|
michalkouril/irapgen
|
inst/codefiles/codePARAMS_practice_neg.js
|
JavaScript
|
gpl-3.0
| 324 |
/*
Find the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by all sequential numbers in the range between these parameters.
The range will be an array of two numbers that will not necessarily be in numerical order.
e.g. for 1 and 3 - find the smallest common multiple of both 1 and 3 that is evenly divisible by all numbers between 1 and 3.
*/
function smallestCommons(arr) {
// rearrange the array with min and max value
var min = Math.min.apply(null, arr);
var max = Math.max.apply(null, arr);
// new array with numbers in range
var new_arr = [];
// loop through all numbers in range and push it to new array
for (max; max >= min; max--) {
new_arr.push(max);
}
// Note: I couldn't solve this from here and I copied this solution.
// Variables needed declared outside the loops.
var quot = 0;
var loop = 1;
var n;
// run code while n is not the same as the array lenght.
do {
quot = new_arr[0] * loop * new_arr[1];
for (n = 2; n < new_arr.length; n++) {
if (quot % new_arr[n] !== 0) {
break;
}
}
loop++;
} while (n !== new_arr.length); {
return quot;
}
}
smallestCommons([1, 5]);
|
yavuzovski/playground
|
web development/frontend/freecodecamp/smallest_common_multiple.js
|
JavaScript
|
gpl-3.0
| 1,216 |
/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
* Copyright (C) 2011 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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 APPLE INC. ``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 APPLE INC. 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.
*/
/**
* @implements {UI.ContextMenu.Provider}
* @implements {SDK.TargetManager.Observer}
* @implements {UI.ViewLocationResolver}
* @unrestricted
*/
Sources.SourcesPanel = class extends UI.Panel {
constructor() {
super('sources');
Sources.SourcesPanel._instance = this;
this.registerRequiredCSS('sources/sourcesPanel.css');
new UI.DropTarget(
this.element, [UI.DropTarget.Types.Files], Common.UIString('Drop workspace folder here'),
this._handleDrop.bind(this));
this._workspace = Workspace.workspace;
this._togglePauseAction =
/** @type {!UI.Action }*/ (UI.actionRegistry.action('debugger.toggle-pause'));
this._stepOverAction =
/** @type {!UI.Action }*/ (UI.actionRegistry.action('debugger.step-over'));
this._stepIntoAction =
/** @type {!UI.Action }*/ (UI.actionRegistry.action('debugger.step-into'));
this._stepOutAction = /** @type {!UI.Action }*/ (UI.actionRegistry.action('debugger.step-out'));
this._toggleBreakpointsActiveAction =
/** @type {!UI.Action }*/ (UI.actionRegistry.action('debugger.toggle-breakpoints-active'));
this._debugToolbar = this._createDebugToolbar();
this._debugToolbarDrawer = this._createDebugToolbarDrawer();
this._debuggerPausedMessage = new Sources.DebuggerPausedMessage();
const initialDebugSidebarWidth = 225;
this._splitWidget = new UI.SplitWidget(true, true, 'sourcesPanelSplitViewState', initialDebugSidebarWidth);
this._splitWidget.enableShowModeSaving();
this._splitWidget.show(this.element);
// Create scripts navigator
const initialNavigatorWidth = 225;
this.editorView = new UI.SplitWidget(true, false, 'sourcesPanelNavigatorSplitViewState', initialNavigatorWidth);
this.editorView.enableShowModeSaving();
this.editorView.element.tabIndex = 0;
this._splitWidget.setMainWidget(this.editorView);
// Create navigator tabbed pane with toolbar.
this._navigatorTabbedLocation =
UI.viewManager.createTabbedLocation(this._revealNavigatorSidebar.bind(this), 'navigator-view', true);
var tabbedPane = this._navigatorTabbedLocation.tabbedPane();
tabbedPane.setMinimumSize(100, 25);
tabbedPane.element.classList.add('navigator-tabbed-pane');
var navigatorMenuButton = new UI.ToolbarMenuButton(this._populateNavigatorMenu.bind(this), true);
navigatorMenuButton.setTitle(Common.UIString('More options'));
tabbedPane.rightToolbar().appendToolbarItem(navigatorMenuButton);
this.editorView.setSidebarWidget(tabbedPane);
this._sourcesView = new Sources.SourcesView();
this._sourcesView.addEventListener(Sources.SourcesView.Events.EditorSelected, this._editorSelected.bind(this));
this._sourcesView.registerShortcuts(this.registerShortcuts.bind(this));
this._toggleNavigatorSidebarButton = this.editorView.createShowHideSidebarButton('navigator');
this._toggleDebuggerSidebarButton = this._splitWidget.createShowHideSidebarButton('debugger');
this.editorView.setMainWidget(this._sourcesView);
this._threadsSidebarPane = null;
this._watchSidebarPane = /** @type {!UI.View} */ (UI.viewManager.view('sources.watch'));
// TODO: Force installing listeners from the model, not the UI.
self.runtime.sharedInstance(Sources.XHRBreakpointsSidebarPane);
this._callstackPane = self.runtime.sharedInstance(Sources.CallStackSidebarPane);
this._callstackPane.registerShortcuts(this.registerShortcuts.bind(this));
Common.moduleSetting('sidebarPosition').addChangeListener(this._updateSidebarPosition.bind(this));
this._updateSidebarPosition();
this._updateDebuggerButtonsAndStatus();
this._pauseOnExceptionEnabledChanged();
Common.moduleSetting('pauseOnExceptionEnabled').addChangeListener(this._pauseOnExceptionEnabledChanged, this);
this._liveLocationPool = new Bindings.LiveLocationPool();
this._setTarget(UI.context.flavor(SDK.Target));
Bindings.breakpointManager.addEventListener(
Bindings.BreakpointManager.Events.BreakpointsActiveStateChanged, this._breakpointsActiveStateChanged, this);
UI.context.addFlavorChangeListener(SDK.Target, this._onCurrentTargetChanged, this);
UI.context.addFlavorChangeListener(SDK.DebuggerModel.CallFrame, this._callFrameChanged, this);
SDK.targetManager.addModelListener(
SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerWasEnabled, this._debuggerWasEnabled, this);
SDK.targetManager.addModelListener(
SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerPaused, this._debuggerPaused, this);
SDK.targetManager.addModelListener(
SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerResumed, this._debuggerResumed, this);
SDK.targetManager.addModelListener(
SDK.DebuggerModel, SDK.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this);
SDK.targetManager.addModelListener(
SDK.SubTargetsManager, SDK.SubTargetsManager.Events.PendingTargetAdded, this._pendingTargetAdded, this);
new Sources.WorkspaceMappingTip(this, this._workspace);
Extensions.extensionServer.addEventListener(
Extensions.ExtensionServer.Events.SidebarPaneAdded, this._extensionSidebarPaneAdded, this);
Components.DataSaverInfobar.maybeShowInPanel(this);
SDK.targetManager.observeTargets(this);
}
/**
* @return {!Sources.SourcesPanel}
*/
static instance() {
if (Sources.SourcesPanel._instance)
return Sources.SourcesPanel._instance;
return /** @type {!Sources.SourcesPanel} */ (self.runtime.sharedInstance(Sources.SourcesPanel));
}
/**
* @param {!Sources.SourcesPanel} panel
*/
static updateResizerAndSidebarButtons(panel) {
panel._sourcesView.leftToolbar().removeToolbarItems();
panel._sourcesView.rightToolbar().removeToolbarItems();
panel._sourcesView.bottomToolbar().removeToolbarItems();
var isInWrapper = Sources.SourcesPanel.WrapperView.isShowing() && !UI.inspectorView.isDrawerMinimized();
if (panel._splitWidget.isVertical() || isInWrapper)
panel._splitWidget.uninstallResizer(panel._sourcesView.toolbarContainerElement());
else
panel._splitWidget.installResizer(panel._sourcesView.toolbarContainerElement());
if (!isInWrapper) {
panel._sourcesView.leftToolbar().appendToolbarItem(panel._toggleNavigatorSidebarButton);
if (panel._splitWidget.isVertical())
panel._sourcesView.rightToolbar().appendToolbarItem(panel._toggleDebuggerSidebarButton);
else
panel._sourcesView.bottomToolbar().appendToolbarItem(panel._toggleDebuggerSidebarButton);
}
}
/**
* @override
* @param {!SDK.Target} target
*/
targetAdded(target) {
this._showThreadsIfNeeded();
}
/**
* @override
* @param {!SDK.Target} target
*/
targetRemoved(target) {
}
_pendingTargetAdded() {
this._showThreadsIfNeeded();
}
_showThreadsIfNeeded() {
if (Sources.ThreadsSidebarPane.shouldBeShown() && !this._threadsSidebarPane) {
this._threadsSidebarPane = /** @type {!UI.View} */ (UI.viewManager.view('sources.threads'));
if (this._sidebarPaneStack) {
this._sidebarPaneStack.showView(
this._threadsSidebarPane, this._splitWidget.isVertical() ? this._watchSidebarPane : this._callstackPane);
}
}
}
/**
* @param {?SDK.Target} target
*/
_setTarget(target) {
if (!target)
return;
var debuggerModel = SDK.DebuggerModel.fromTarget(target);
if (!debuggerModel)
return;
if (debuggerModel.isPaused()) {
this._showDebuggerPausedDetails(
/** @type {!SDK.DebuggerPausedDetails} */ (debuggerModel.debuggerPausedDetails()));
} else {
this._paused = false;
this._clearInterface();
this._toggleDebuggerSidebarButton.setEnabled(true);
}
}
/**
* @param {!Common.Event} event
*/
_onCurrentTargetChanged(event) {
var target = /** @type {?SDK.Target} */ (event.data);
this._setTarget(target);
}
/**
* @return {boolean}
*/
paused() {
return this._paused;
}
/**
* @override
*/
wasShown() {
UI.context.setFlavor(Sources.SourcesPanel, this);
super.wasShown();
var wrapper = Sources.SourcesPanel.WrapperView._instance;
if (wrapper && wrapper.isShowing()) {
UI.inspectorView.setDrawerMinimized(true);
Sources.SourcesPanel.updateResizerAndSidebarButtons(this);
}
this.editorView.setMainWidget(this._sourcesView);
}
/**
* @override
*/
willHide() {
super.willHide();
UI.context.setFlavor(Sources.SourcesPanel, null);
if (Sources.SourcesPanel.WrapperView.isShowing()) {
Sources.SourcesPanel.WrapperView._instance._showViewInWrapper();
UI.inspectorView.setDrawerMinimized(false);
Sources.SourcesPanel.updateResizerAndSidebarButtons(this);
}
}
/**
* @override
* @param {string} locationName
* @return {?UI.ViewLocation}
*/
resolveLocation(locationName) {
if (locationName === 'sources-sidebar')
return this._sidebarPaneStack;
else
return this._navigatorTabbedLocation;
}
/**
* @return {boolean}
*/
_ensureSourcesViewVisible() {
if (Sources.SourcesPanel.WrapperView.isShowing())
return true;
if (!UI.inspectorView.canSelectPanel('sources'))
return false;
UI.viewManager.showView('sources');
return true;
}
/**
* @override
*/
onResize() {
if (Common.moduleSetting('sidebarPosition').get() === 'auto')
this.element.window().requestAnimationFrame(this._updateSidebarPosition.bind(this)); // Do not force layout.
}
/**
* @override
* @return {!UI.SearchableView}
*/
searchableView() {
return this._sourcesView.searchableView();
}
/**
* @param {!Common.Event} event
*/
_debuggerPaused(event) {
var details = /** @type {!SDK.DebuggerPausedDetails} */ (event.data);
if (!this._paused)
this._setAsCurrentPanel();
if (UI.context.flavor(SDK.Target) === details.target())
this._showDebuggerPausedDetails(details);
else if (!this._paused)
UI.context.setFlavor(SDK.Target, details.target());
}
/**
* @param {!SDK.DebuggerPausedDetails} details
*/
_showDebuggerPausedDetails(details) {
this._paused = true;
this._updateDebuggerButtonsAndStatus();
UI.context.setFlavor(SDK.DebuggerPausedDetails, details);
this._toggleDebuggerSidebarButton.setEnabled(false);
this._revealDebuggerSidebar();
window.focus();
InspectorFrontendHost.bringToFront();
}
/**
* @param {!Common.Event} event
*/
_debuggerResumed(event) {
var debuggerModel = /** @type {!SDK.DebuggerModel} */ (event.target);
var target = debuggerModel.target();
if (UI.context.flavor(SDK.Target) !== target)
return;
this._paused = false;
this._clearInterface();
this._toggleDebuggerSidebarButton.setEnabled(true);
this._switchToPausedTargetTimeout = setTimeout(this._switchToPausedTarget.bind(this, debuggerModel), 500);
}
/**
* @param {!Common.Event} event
*/
_debuggerWasEnabled(event) {
var target = /** @type {!SDK.Target} */ (event.target.target());
if (UI.context.flavor(SDK.Target) !== target)
return;
this._updateDebuggerButtonsAndStatus();
}
/**
* @param {!Common.Event} event
*/
_debuggerReset(event) {
this._debuggerResumed(event);
}
/**
* @return {?UI.Widget}
*/
get visibleView() {
return this._sourcesView.visibleView();
}
/**
* @param {!Workspace.UISourceCode} uiSourceCode
* @param {number=} lineNumber 0-based
* @param {number=} columnNumber
* @param {boolean=} omitFocus
*/
showUISourceCode(uiSourceCode, lineNumber, columnNumber, omitFocus) {
if (omitFocus) {
var wrapperShowing =
Sources.SourcesPanel.WrapperView._instance && Sources.SourcesPanel.WrapperView._instance.isShowing();
if (!this.isShowing() && !wrapperShowing)
return;
} else {
this._showEditor();
}
this._sourcesView.showSourceLocation(uiSourceCode, lineNumber, columnNumber, omitFocus);
}
_showEditor() {
if (Sources.SourcesPanel.WrapperView._instance && Sources.SourcesPanel.WrapperView._instance.isShowing())
return;
this._setAsCurrentPanel();
}
/**
* @param {!Workspace.UILocation} uiLocation
* @param {boolean=} omitFocus
*/
showUILocation(uiLocation, omitFocus) {
this.showUISourceCode(uiLocation.uiSourceCode, uiLocation.lineNumber, uiLocation.columnNumber, omitFocus);
}
/**
* @param {!Workspace.UISourceCode} uiSourceCode
* @param {boolean=} skipReveal
*/
_revealInNavigator(uiSourceCode, skipReveal) {
var binding = Persistence.persistence.binding(uiSourceCode);
if (binding && binding.network === uiSourceCode)
uiSourceCode = binding.fileSystem;
var extensions = self.runtime.extensions(Sources.NavigatorView);
Promise.all(extensions.map(extension => extension.instance())).then(filterNavigators.bind(this));
/**
* @this {Sources.SourcesPanel}
* @param {!Array.<!Object>} objects
*/
function filterNavigators(objects) {
for (var i = 0; i < objects.length; ++i) {
var navigatorView = /** @type {!Sources.NavigatorView} */ (objects[i]);
var viewId = extensions[i].descriptor()['viewId'];
if (navigatorView.accept(uiSourceCode)) {
navigatorView.revealUISourceCode(uiSourceCode, true);
if (skipReveal)
this._navigatorTabbedLocation.tabbedPane().selectTab(viewId);
else
UI.viewManager.showView(viewId);
}
}
}
}
/**
* @param {!UI.ContextMenu} contextMenu
*/
_populateNavigatorMenu(contextMenu) {
var groupByFolderSetting = Common.moduleSetting('navigatorGroupByFolder');
contextMenu.appendItemsAtLocation('navigatorMenu');
contextMenu.appendSeparator();
contextMenu.appendCheckboxItem(
Common.UIString('Group by folder'), () => groupByFolderSetting.set(!groupByFolderSetting.get()),
groupByFolderSetting.get());
}
/**
* @param {boolean} ignoreExecutionLineEvents
*/
setIgnoreExecutionLineEvents(ignoreExecutionLineEvents) {
this._ignoreExecutionLineEvents = ignoreExecutionLineEvents;
}
updateLastModificationTime() {
this._lastModificationTime = window.performance.now();
}
/**
* @param {!Bindings.LiveLocation} liveLocation
*/
_executionLineChanged(liveLocation) {
var uiLocation = liveLocation.uiLocation();
if (!uiLocation)
return;
this._sourcesView.clearCurrentExecutionLine();
this._sourcesView.setExecutionLocation(uiLocation);
if (window.performance.now() - this._lastModificationTime < Sources.SourcesPanel._lastModificationTimeout)
return;
this._sourcesView.showSourceLocation(
uiLocation.uiSourceCode, uiLocation.lineNumber, uiLocation.columnNumber, undefined, true);
}
_lastModificationTimeoutPassedForTest() {
Sources.SourcesPanel._lastModificationTimeout = Number.MIN_VALUE;
}
_updateLastModificationTimeForTest() {
Sources.SourcesPanel._lastModificationTimeout = Number.MAX_VALUE;
}
_callFrameChanged() {
var callFrame = UI.context.flavor(SDK.DebuggerModel.CallFrame);
if (!callFrame)
return;
if (this._executionLineLocation)
this._executionLineLocation.dispose();
this._executionLineLocation = Bindings.debuggerWorkspaceBinding.createCallFrameLiveLocation(
callFrame.location(), this._executionLineChanged.bind(this), this._liveLocationPool);
}
_pauseOnExceptionEnabledChanged() {
var enabled = Common.moduleSetting('pauseOnExceptionEnabled').get();
this._pauseOnExceptionButton.setToggled(enabled);
this._pauseOnExceptionButton.setTitle(
Common.UIString(enabled ? 'Don\'t pause on exceptions' : 'Pause on exceptions'));
this._debugToolbarDrawer.classList.toggle('expanded', enabled);
}
_updateDebuggerButtonsAndStatus() {
var currentTarget = UI.context.flavor(SDK.Target);
var currentDebuggerModel = SDK.DebuggerModel.fromTarget(currentTarget);
if (!currentDebuggerModel) {
this._togglePauseAction.setEnabled(false);
this._stepOverAction.setEnabled(false);
this._stepIntoAction.setEnabled(false);
this._stepOutAction.setEnabled(false);
} else if (this._paused) {
this._togglePauseAction.setToggled(true);
this._togglePauseAction.setEnabled(true);
this._stepOverAction.setEnabled(true);
this._stepIntoAction.setEnabled(true);
this._stepOutAction.setEnabled(true);
} else {
this._togglePauseAction.setToggled(false);
this._togglePauseAction.setEnabled(!currentDebuggerModel.isPausing());
this._stepOverAction.setEnabled(false);
this._stepIntoAction.setEnabled(false);
this._stepOutAction.setEnabled(false);
}
var details = currentDebuggerModel ? currentDebuggerModel.debuggerPausedDetails() : null;
this._debuggerPausedMessage.render(details, Bindings.debuggerWorkspaceBinding, Bindings.breakpointManager);
}
_clearInterface() {
this._sourcesView.clearCurrentExecutionLine();
this._updateDebuggerButtonsAndStatus();
UI.context.setFlavor(SDK.DebuggerPausedDetails, null);
if (this._switchToPausedTargetTimeout)
clearTimeout(this._switchToPausedTargetTimeout);
this._liveLocationPool.disposeAll();
}
/**
* @param {!SDK.DebuggerModel} debuggerModel
*/
_switchToPausedTarget(debuggerModel) {
delete this._switchToPausedTargetTimeout;
if (this._paused)
return;
var target = UI.context.flavor(SDK.Target);
if (debuggerModel.isPaused())
return;
var debuggerModels = SDK.DebuggerModel.instances();
for (var i = 0; i < debuggerModels.length; ++i) {
if (debuggerModels[i].isPaused()) {
UI.context.setFlavor(SDK.Target, debuggerModels[i].target());
break;
}
}
}
_togglePauseOnExceptions() {
Common.moduleSetting('pauseOnExceptionEnabled').set(!this._pauseOnExceptionButton.toggled());
}
/**
* @return {boolean}
*/
_runSnippet() {
var uiSourceCode = this._sourcesView.currentUISourceCode();
if (uiSourceCode.project().type() !== Workspace.projectTypes.Snippets)
return false;
var currentExecutionContext = UI.context.flavor(SDK.ExecutionContext);
if (!currentExecutionContext)
return false;
Snippets.scriptSnippetModel.evaluateScriptSnippet(currentExecutionContext, uiSourceCode);
return true;
}
/**
* @param {!Common.Event} event
*/
_editorSelected(event) {
var uiSourceCode = /** @type {!Workspace.UISourceCode} */ (event.data);
if (this.editorView.mainWidget() && Common.moduleSetting('autoRevealInNavigator').get())
this._revealInNavigator(uiSourceCode, true);
}
/**
* @return {boolean}
*/
_togglePause() {
var target = UI.context.flavor(SDK.Target);
if (!target)
return true;
var debuggerModel = SDK.DebuggerModel.fromTarget(target);
if (!debuggerModel)
return true;
if (this._paused) {
this._paused = false;
debuggerModel.resume();
} else {
// Make sure pauses didn't stick skipped.
debuggerModel.pause();
}
this._clearInterface();
return true;
}
/**
* @return {?SDK.DebuggerModel}
*/
_prepareToResume() {
if (!this._paused)
return null;
this._paused = false;
this._clearInterface();
var target = UI.context.flavor(SDK.Target);
return target ? SDK.DebuggerModel.fromTarget(target) : null;
}
/**
* @return {boolean}
*/
_longResume() {
var debuggerModel = this._prepareToResume();
if (!debuggerModel)
return true;
debuggerModel.skipAllPausesUntilReloadOrTimeout(500);
debuggerModel.resume();
return true;
}
/**
* @return {boolean}
*/
_stepOver() {
var debuggerModel = this._prepareToResume();
if (!debuggerModel)
return true;
debuggerModel.stepOver();
return true;
}
/**
* @return {boolean}
*/
_stepInto() {
var debuggerModel = this._prepareToResume();
if (!debuggerModel)
return true;
debuggerModel.stepInto();
return true;
}
/**
* @return {boolean}
*/
_stepOut() {
var debuggerModel = this._prepareToResume();
if (!debuggerModel)
return true;
debuggerModel.stepOut();
return true;
}
/**
* @param {!Workspace.UILocation} uiLocation
*/
_continueToLocation(uiLocation) {
var executionContext = UI.context.flavor(SDK.ExecutionContext);
if (!executionContext)
return;
// Always use 0 column.
var rawLocation = Bindings.debuggerWorkspaceBinding.uiLocationToRawLocation(
executionContext.target(), uiLocation.uiSourceCode, uiLocation.lineNumber, 0);
if (!rawLocation)
return;
if (!this._prepareToResume())
return;
rawLocation.continueToLocation();
}
_toggleBreakpointsActive() {
Bindings.breakpointManager.setBreakpointsActive(!Bindings.breakpointManager.breakpointsActive());
}
_breakpointsActiveStateChanged(event) {
var active = event.data;
this._toggleBreakpointsActiveAction.setToggled(!active);
this._sourcesView.toggleBreakpointsActiveState(active);
}
/**
* @return {!UI.Toolbar}
*/
_createDebugToolbar() {
var debugToolbar = new UI.Toolbar('scripts-debug-toolbar');
var longResumeButton =
new UI.ToolbarButton(Common.UIString('Resume with all pauses blocked for 500 ms'), 'largeicon-play');
longResumeButton.addEventListener('click', this._longResume.bind(this), this);
debugToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._togglePauseAction, [longResumeButton], []));
debugToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._stepOverAction));
debugToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._stepIntoAction));
debugToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._stepOutAction));
debugToolbar.appendSeparator();
debugToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._toggleBreakpointsActiveAction));
this._pauseOnExceptionButton = new UI.ToolbarToggle('', 'largeicon-pause-on-exceptions');
this._pauseOnExceptionButton.addEventListener('click', this._togglePauseOnExceptions, this);
debugToolbar.appendToolbarItem(this._pauseOnExceptionButton);
debugToolbar.appendSeparator();
debugToolbar.appendToolbarItem(new UI.ToolbarCheckbox(
Common.UIString('Async'), Common.UIString('Capture async stack traces'),
Common.moduleSetting('enableAsyncStackTraces')));
return debugToolbar;
}
_createDebugToolbarDrawer() {
var debugToolbarDrawer = createElementWithClass('div', 'scripts-debug-toolbar-drawer');
var label = Common.UIString('Pause On Caught Exceptions');
var setting = Common.moduleSetting('pauseOnCaughtException');
debugToolbarDrawer.appendChild(UI.SettingsUI.createSettingCheckbox(label, setting, true));
return debugToolbarDrawer;
}
/**
* @param {!Workspace.UISourceCode} uiSourceCode
*/
_showLocalHistory(uiSourceCode) {
Sources.RevisionHistoryView.showHistory(uiSourceCode);
}
/**
* @override
* @param {!Event} event
* @param {!UI.ContextMenu} contextMenu
* @param {!Object} target
*/
appendApplicableItems(event, contextMenu, target) {
this._appendUISourceCodeItems(event, contextMenu, target);
this._appendUISourceCodeFrameItems(event, contextMenu, target);
this.appendUILocationItems(contextMenu, target);
this._appendRemoteObjectItems(contextMenu, target);
this._appendNetworkRequestItems(contextMenu, target);
}
/**
* @param {!Workspace.UISourceCode} uiSourceCode
*/
mapFileSystemToNetwork(uiSourceCode) {
Sources.SelectUISourceCodeForProjectTypesDialog.show(
uiSourceCode.name(), [Workspace.projectTypes.Network, Workspace.projectTypes.ContentScripts],
mapFileSystemToNetwork);
/**
* @param {?Workspace.UISourceCode} networkUISourceCode
*/
function mapFileSystemToNetwork(networkUISourceCode) {
if (!networkUISourceCode)
return;
var fileSystemPath = Bindings.FileSystemWorkspaceBinding.fileSystemPath(uiSourceCode.project().id());
Workspace.fileSystemMapping.addMappingForResource(networkUISourceCode.url(), fileSystemPath, uiSourceCode.url());
}
}
/**
* @param {!Workspace.UISourceCode} networkUISourceCode
*/
mapNetworkToFileSystem(networkUISourceCode) {
Sources.SelectUISourceCodeForProjectTypesDialog.show(
networkUISourceCode.name(), [Workspace.projectTypes.FileSystem], mapNetworkToFileSystem);
/**
* @param {?Workspace.UISourceCode} uiSourceCode
*/
function mapNetworkToFileSystem(uiSourceCode) {
if (!uiSourceCode)
return;
var fileSystemPath = Bindings.FileSystemWorkspaceBinding.fileSystemPath(uiSourceCode.project().id());
Workspace.fileSystemMapping.addMappingForResource(networkUISourceCode.url(), fileSystemPath, uiSourceCode.url());
}
}
/**
* @param {!Workspace.UISourceCode} uiSourceCode
*/
_removeNetworkMapping(uiSourceCode) {
Workspace.fileSystemMapping.removeMappingForURL(uiSourceCode.url());
}
/**
* @param {!UI.ContextMenu} contextMenu
* @param {!Workspace.UISourceCode} uiSourceCode
*/
_appendUISourceCodeMappingItems(contextMenu, uiSourceCode) {
Sources.NavigatorView.appendAddFolderItem(contextMenu);
if (Runtime.experiments.isEnabled('persistence2'))
return;
if (uiSourceCode.project().type() === Workspace.projectTypes.FileSystem) {
var binding = Persistence.persistence.binding(uiSourceCode);
if (!binding) {
contextMenu.appendItem(
Common.UIString.capitalize('Map to ^network ^resource\u2026'),
this.mapFileSystemToNetwork.bind(this, uiSourceCode));
} else {
contextMenu.appendItem(
Common.UIString.capitalize('Remove ^network ^mapping'),
this._removeNetworkMapping.bind(this, binding.network));
}
}
/**
* @param {!Workspace.Project} project
*/
function filterProject(project) {
return project.type() === Workspace.projectTypes.FileSystem;
}
if (uiSourceCode.project().type() === Workspace.projectTypes.Network ||
uiSourceCode.project().type() === Workspace.projectTypes.ContentScripts) {
if (!this._workspace.projects().filter(filterProject).length)
return;
if (this._workspace.uiSourceCodeForURL(uiSourceCode.url()) === uiSourceCode) {
contextMenu.appendItem(
Common.UIString.capitalize('Map to ^file ^system ^resource\u2026'),
this.mapNetworkToFileSystem.bind(this, uiSourceCode));
}
}
}
/**
* @param {!Event} event
* @param {!UI.ContextMenu} contextMenu
* @param {!Object} target
*/
_appendUISourceCodeItems(event, contextMenu, target) {
if (!(target instanceof Workspace.UISourceCode))
return;
var uiSourceCode = /** @type {!Workspace.UISourceCode} */ (target);
var projectType = uiSourceCode.project().type();
if (projectType !== Workspace.projectTypes.Debugger &&
!event.target.isSelfOrDescendant(this._navigatorTabbedLocation.widget().element)) {
contextMenu.appendItem(
Common.UIString.capitalize('Reveal in ^navigator'), this._handleContextMenuReveal.bind(this, uiSourceCode));
contextMenu.appendSeparator();
}
this._appendUISourceCodeMappingItems(contextMenu, uiSourceCode);
if (projectType !== Workspace.projectTypes.FileSystem) {
contextMenu.appendItem(
Common.UIString.capitalize('Local ^modifications\u2026'), this._showLocalHistory.bind(this, uiSourceCode));
}
}
/**
* @param {!Event} event
* @param {!UI.ContextMenu} contextMenu
* @param {!Object} target
*/
_appendUISourceCodeFrameItems(event, contextMenu, target) {
if (!(target instanceof Sources.UISourceCodeFrame))
return;
contextMenu.appendAction('debugger.evaluate-selection');
}
/**
* @param {!UI.ContextMenu} contextMenu
* @param {!Object} object
*/
appendUILocationItems(contextMenu, object) {
if (!(object instanceof Workspace.UILocation))
return;
var uiLocation = /** @type {!Workspace.UILocation} */ (object);
var uiSourceCode = uiLocation.uiSourceCode;
var projectType = uiSourceCode.project().type();
var contentType = uiSourceCode.contentType();
if (contentType.hasScripts()) {
var target = UI.context.flavor(SDK.Target);
var debuggerModel = SDK.DebuggerModel.fromTarget(target);
if (debuggerModel && debuggerModel.isPaused()) {
contextMenu.appendItem(
Common.UIString.capitalize('Continue to ^here'), this._continueToLocation.bind(this, uiLocation));
}
}
if (contentType.hasScripts() && projectType !== Workspace.projectTypes.Snippets)
this._callstackPane.appendBlackboxURLContextMenuItems(contextMenu, uiSourceCode);
}
/**
* @param {!Workspace.UISourceCode} uiSourceCode
*/
_handleContextMenuReveal(uiSourceCode) {
this.editorView.showBoth();
this._revealInNavigator(uiSourceCode);
}
/**
* @param {!UI.ContextMenu} contextMenu
* @param {!Object} target
*/
_appendRemoteObjectItems(contextMenu, target) {
if (!(target instanceof SDK.RemoteObject))
return;
var remoteObject = /** @type {!SDK.RemoteObject} */ (target);
contextMenu.appendItem(
Common.UIString.capitalize('Store as ^global ^variable'), this._saveToTempVariable.bind(this, remoteObject));
if (remoteObject.type === 'function') {
contextMenu.appendItem(
Common.UIString.capitalize('Show ^function ^definition'),
this._showFunctionDefinition.bind(this, remoteObject));
}
}
/**
* @param {!UI.ContextMenu} contextMenu
* @param {!Object} target
*/
_appendNetworkRequestItems(contextMenu, target) {
if (!(target instanceof SDK.NetworkRequest))
return;
var request = /** @type {!SDK.NetworkRequest} */ (target);
var uiSourceCode = this._workspace.uiSourceCodeForURL(request.url);
if (!uiSourceCode)
return;
var openText = Common.UIString.capitalize('Open in Sources ^panel');
contextMenu.appendItem(openText, this.showUILocation.bind(this, uiSourceCode.uiLocation(0, 0)));
}
/**
* @param {!SDK.RemoteObject} remoteObject
*/
_saveToTempVariable(remoteObject) {
var currentExecutionContext = UI.context.flavor(SDK.ExecutionContext);
if (!currentExecutionContext)
return;
currentExecutionContext.globalObject('', false, didGetGlobalObject);
/**
* @param {?SDK.RemoteObject} global
* @param {!Protocol.Runtime.ExceptionDetails=} exceptionDetails
*/
function didGetGlobalObject(global, exceptionDetails) {
/**
* @suppressReceiverCheck
* @this {Window}
*/
function remoteFunction(value) {
var prefix = 'temp';
var index = 1;
while ((prefix + index) in this)
++index;
var name = prefix + index;
this[name] = value;
return name;
}
if (!!exceptionDetails || !global) {
failedToSave(global);
} else {
global.callFunction(
remoteFunction, [SDK.RemoteObject.toCallArgument(remoteObject)], didSave.bind(null, global));
}
}
/**
* @param {!SDK.RemoteObject} global
* @param {?SDK.RemoteObject} result
* @param {boolean=} wasThrown
*/
function didSave(global, result, wasThrown) {
global.release();
if (wasThrown || !result || result.type !== 'string') {
failedToSave(result);
} else {
SDK.ConsoleModel.evaluateCommandInConsole(
/** @type {!SDK.ExecutionContext} */ (currentExecutionContext), result.value);
}
}
/**
* @param {?SDK.RemoteObject} result
*/
function failedToSave(result) {
var message = Common.UIString('Failed to save to temp variable.');
if (result) {
message += ' ' + result.description;
result.release();
}
Common.console.error(message);
}
}
/**
* @param {!SDK.RemoteObject} remoteObject
*/
_showFunctionDefinition(remoteObject) {
remoteObject.debuggerModel().functionDetailsPromise(remoteObject).then(this._didGetFunctionDetails.bind(this));
}
/**
* @param {?{location: ?SDK.DebuggerModel.Location}} response
*/
_didGetFunctionDetails(response) {
if (!response || !response.location)
return;
var location = response.location;
if (!location)
return;
var uiLocation = Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(location);
if (uiLocation)
this.showUILocation(uiLocation);
}
showGoToSourceDialog() {
this._sourcesView.showOpenResourceDialog();
}
_revealNavigatorSidebar() {
this._setAsCurrentPanel();
this.editorView.showBoth(true);
}
_revealDebuggerSidebar() {
this._setAsCurrentPanel();
this._splitWidget.showBoth(true);
}
_updateSidebarPosition() {
var vertically;
var position = Common.moduleSetting('sidebarPosition').get();
if (position === 'right')
vertically = false;
else if (position === 'bottom')
vertically = true;
else
vertically = UI.inspectorView.element.offsetWidth < 680;
if (this.sidebarPaneView && vertically === !this._splitWidget.isVertical())
return;
if (this.sidebarPaneView && this.sidebarPaneView.shouldHideOnDetach())
return; // We can't reparent extension iframes.
if (this.sidebarPaneView)
this.sidebarPaneView.detach();
this._splitWidget.setVertical(!vertically);
this._splitWidget.element.classList.toggle('sources-split-view-vertical', vertically);
Sources.SourcesPanel.updateResizerAndSidebarButtons(this);
// Create vertical box with stack.
var vbox = new UI.VBox();
vbox.element.appendChild(this._debugToolbarDrawer);
vbox.setMinimumAndPreferredSizes(25, 25, Sources.SourcesPanel.minToolbarWidth, 100);
this._sidebarPaneStack = UI.viewManager.createStackLocation(this._revealDebuggerSidebar.bind(this));
this._sidebarPaneStack.widget().element.classList.add('overflow-auto');
this._sidebarPaneStack.widget().show(vbox.element);
this._sidebarPaneStack.widget().element.appendChild(this._debuggerPausedMessage.element());
vbox.element.appendChild(this._debugToolbar.element);
if (this._threadsSidebarPane)
this._sidebarPaneStack.showView(this._threadsSidebarPane);
if (!vertically)
this._sidebarPaneStack.appendView(this._watchSidebarPane);
this._sidebarPaneStack.showView(this._callstackPane);
var jsBreakpoints = /** @type {!UI.View} */ (UI.viewManager.view('sources.jsBreakpoints'));
var scopeChainView = /** @type {!UI.View} */ (UI.viewManager.view('sources.scopeChain'));
if (!vertically) {
// Populate the rest of the stack.
this._sidebarPaneStack.showView(scopeChainView);
this._sidebarPaneStack.showView(jsBreakpoints);
this._extensionSidebarPanesContainer = this._sidebarPaneStack;
this.sidebarPaneView = vbox;
} else {
var splitWidget = new UI.SplitWidget(true, true, 'sourcesPanelDebuggerSidebarSplitViewState', 0.5);
splitWidget.setMainWidget(vbox);
// Populate the left stack.
this._sidebarPaneStack.showView(jsBreakpoints);
var tabbedLocation = UI.viewManager.createTabbedLocation(this._revealDebuggerSidebar.bind(this));
splitWidget.setSidebarWidget(tabbedLocation.tabbedPane());
tabbedLocation.appendView(scopeChainView);
tabbedLocation.appendView(this._watchSidebarPane);
this._extensionSidebarPanesContainer = tabbedLocation;
this.sidebarPaneView = splitWidget;
}
this._sidebarPaneStack.appendApplicableItems('sources-sidebar');
var extensionSidebarPanes = Extensions.extensionServer.sidebarPanes();
for (var i = 0; i < extensionSidebarPanes.length; ++i)
this._addExtensionSidebarPane(extensionSidebarPanes[i]);
this._splitWidget.setSidebarWidget(this.sidebarPaneView);
}
/**
* @return {!Promise}
*/
_setAsCurrentPanel() {
return UI.viewManager.showView('sources');
}
/**
* @param {!Common.Event} event
*/
_extensionSidebarPaneAdded(event) {
var pane = /** @type {!Extensions.ExtensionSidebarPane} */ (event.data);
this._addExtensionSidebarPane(pane);
}
/**
* @param {!Extensions.ExtensionSidebarPane} pane
*/
_addExtensionSidebarPane(pane) {
if (pane.panelName() === this.name)
this._extensionSidebarPanesContainer.appendView(pane);
}
/**
* @return {!Sources.SourcesView}
*/
sourcesView() {
return this._sourcesView;
}
/**
* @param {!DataTransfer} dataTransfer
*/
_handleDrop(dataTransfer) {
var items = dataTransfer.items;
if (!items.length)
return;
var entry = items[0].webkitGetAsEntry();
if (!entry.isDirectory)
return;
InspectorFrontendHost.upgradeDraggedFileSystemPermissions(entry.filesystem);
}
};
Sources.SourcesPanel._lastModificationTimeout = 200;
Sources.SourcesPanel.minToolbarWidth = 215;
/**
* @implements {Common.Revealer}
* @unrestricted
*/
Sources.SourcesPanel.UILocationRevealer = class {
/**
* @override
* @param {!Object} uiLocation
* @param {boolean=} omitFocus
* @return {!Promise}
*/
reveal(uiLocation, omitFocus) {
if (!(uiLocation instanceof Workspace.UILocation))
return Promise.reject(new Error('Internal error: not a ui location'));
Sources.SourcesPanel.instance().showUILocation(uiLocation, omitFocus);
return Promise.resolve();
}
};
/**
* @implements {Common.Revealer}
* @unrestricted
*/
Sources.SourcesPanel.DebuggerLocationRevealer = class {
/**
* @override
* @param {!Object} rawLocation
* @param {boolean=} omitFocus
* @return {!Promise}
*/
reveal(rawLocation, omitFocus) {
if (!(rawLocation instanceof SDK.DebuggerModel.Location))
return Promise.reject(new Error('Internal error: not a debugger location'));
Sources.SourcesPanel.instance().showUILocation(
Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(rawLocation), omitFocus);
return Promise.resolve();
}
};
/**
* @implements {Common.Revealer}
* @unrestricted
*/
Sources.SourcesPanel.UISourceCodeRevealer = class {
/**
* @override
* @param {!Object} uiSourceCode
* @param {boolean=} omitFocus
* @return {!Promise}
*/
reveal(uiSourceCode, omitFocus) {
if (!(uiSourceCode instanceof Workspace.UISourceCode))
return Promise.reject(new Error('Internal error: not a ui source code'));
Sources.SourcesPanel.instance().showUISourceCode(uiSourceCode, undefined, undefined, omitFocus);
return Promise.resolve();
}
};
/**
* @implements {Common.Revealer}
* @unrestricted
*/
Sources.SourcesPanel.DebuggerPausedDetailsRevealer = class {
/**
* @override
* @param {!Object} object
* @return {!Promise}
*/
reveal(object) {
return Sources.SourcesPanel.instance()._setAsCurrentPanel();
}
};
/**
* @implements {UI.ActionDelegate}
* @unrestricted
*/
Sources.SourcesPanel.RevealingActionDelegate = class {
/**
* @override
* @param {!UI.Context} context
* @param {string} actionId
* @return {boolean}
*/
handleAction(context, actionId) {
var panel = Sources.SourcesPanel.instance();
if (!panel._ensureSourcesViewVisible())
return false;
switch (actionId) {
case 'debugger.toggle-pause':
panel._togglePause();
return true;
case 'sources.go-to-source':
panel.showGoToSourceDialog();
return true;
}
return false;
}
};
/**
* @implements {UI.ActionDelegate}
* @unrestricted
*/
Sources.SourcesPanel.DebuggingActionDelegate = class {
/**
* @override
* @param {!UI.Context} context
* @param {string} actionId
* @return {boolean}
*/
handleAction(context, actionId) {
var panel = Sources.SourcesPanel.instance();
switch (actionId) {
case 'debugger.step-over':
panel._stepOver();
return true;
case 'debugger.step-into':
panel._stepInto();
return true;
case 'debugger.step-out':
panel._stepOut();
return true;
case 'debugger.run-snippet':
panel._runSnippet();
return true;
case 'debugger.toggle-breakpoints-active':
panel._toggleBreakpointsActive();
return true;
case 'debugger.evaluate-selection':
var frame = UI.context.flavor(Sources.UISourceCodeFrame);
if (frame) {
var text = frame.textEditor.text(frame.textEditor.selection());
var executionContext = UI.context.flavor(SDK.ExecutionContext);
if (executionContext)
SDK.ConsoleModel.evaluateCommandInConsole(executionContext, text);
}
return true;
}
return false;
}
};
/**
* @unrestricted
*/
Sources.SourcesPanel.WrapperView = class extends UI.VBox {
constructor() {
super();
this.element.classList.add('sources-view-wrapper');
Sources.SourcesPanel.WrapperView._instance = this;
this._view = Sources.SourcesPanel.instance()._sourcesView;
}
/**
* @return {boolean}
*/
static isShowing() {
return !!Sources.SourcesPanel.WrapperView._instance && Sources.SourcesPanel.WrapperView._instance.isShowing();
}
/**
* @override
*/
wasShown() {
if (!Sources.SourcesPanel.instance().isShowing())
this._showViewInWrapper();
else
UI.inspectorView.setDrawerMinimized(true);
Sources.SourcesPanel.updateResizerAndSidebarButtons(Sources.SourcesPanel.instance());
}
/**
* @override
*/
willHide() {
UI.inspectorView.setDrawerMinimized(false);
setImmediate(() => Sources.SourcesPanel.updateResizerAndSidebarButtons(Sources.SourcesPanel.instance()));
}
_showViewInWrapper() {
this._view.show(this.element);
}
};
|
geminy/aidear
|
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/WebKit/Source/devtools/front_end/sources/SourcesPanel.js
|
JavaScript
|
gpl-3.0
| 43,485 |
/*
* editor_plugin.js
*
* Copyright 2014 Ed Hynan <edhynan@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; specifically version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
/**
* WP visual editor presentation of SWFPut video.
*
* With v 2.9 (3.0) a new pretty dialog based simplified
* UI is implemented based on (literally) the wp.media w/
* Backbone and _'s that WP comments suggest was started
* ~ v 3.5 -- this implementation is conditional on v >= 4.3.
*
* See, in WP installation, wp-includes/js/{mce-view,media*}.js
*/
//
// A utitlity for this code, i.e. stuff in one place
//
var SWFPut_video_utility_obj_def = function() {
// start new serial based on page load time --
// not critical, meant to help avoid clashes,
// but not under perverse conditions like rapid
// multiple use incremenenting to values that might
// be greater than initial value on next page load --
// under such conditions, games over anyway.
this.loadtime_serial = this.unixtime() & 0x0FFFFFFFFF;
};
SWFPut_video_utility_obj_def.prototype = {
defprops : {
url: "",
cssurl: "",
iimage: "",
width: "240",
height: "180",
mobiwidth: "0",
audio: "false",
aspectautoadj: "false",
displayaspect: "0",
pixelaspect: "0",
volume: "50",
play: "false",
hidebar: "true",
disablebar: "false",
iimgbg: "true",
barheight: "36",
quality: "high",
allowfull: "true",
allowxdom: "false",
loop: "false",
mtype: "application/x-shockwave-flash",
playpath: "",
altvideo: "",
classid: "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000",
codebase: "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0",
align: "center",
preload: "image"
},
mk_shortcode : function(sc, atts, cap) {
var c = cap || '', s = '[' + sc,
defs = SWFPut_video_utility_obj_def.prototype.defprops;
for ( var t in atts ) {
if ( defs[ t ] === undefined ) {
continue;
}
s += ' ' + t + '="' + atts[t] + '"';
}
return s + ']' + c + '[/' + sc + ']'
},
atts_filter : function(atts) {
var defs = SWFPut_video_utility_obj_def.prototype.defprops,
outp = {};
for ( var t in atts ) {
if ( defs[ t ] !== undefined ) {
outp[t] = atts[ t ];
}
}
return outp;
},
// Like JS Date.now
date_now: function() {
return Date.now ? Date.now() : new Date().getTime();
},
// w/ 1 sec reso. like unix epoch time (JS funcs start at epoch)
unixtime: function() {
return (this.date_now() / 1000);
},
// set in ctor to epoch time in seconds
loadtime_serial: 0,
// get an empty shortcode for new insertion,
// adding caption reminder with timestamp --
// timestamp serves to make string unique for
// wp.media use in a data-* attribute
get_new_putswf_shortcode: function() {
var d = new Date(),
s = '[putswf_video url="" iimage="" altvideo=""]',
e = '[/putswf_video]',
c = 'Edit me please! '
+ d.toString() + ', '
+ d.getTime() + 'ms';
return s + c + e;
},
// the WP media root object, 'wp'
_wp: wp || false,
// use wp ajax to fetch attachment data from attachment id integer
// -- result_cb is a function to call with results, arg 1 is id
// arg 2 is object status: true == ok + response,
// null == ok w/o response,
// or false on fail, and response
// this returns status object w/ status == 0 for pending;
// if saved test again for res.status !== 0
attachment_data_by_id: function(id, result_cb) {
var pid = id,
res = { status: 0, response: null };
if ( this._wp ) { // 'wp_ajax_get_attachment'
this._wp.ajax.send( 'get-attachment', {
data: {
id: pid
}
} )
.done( function( response ) {
res.status = response ? true : null;
res.response = response;
if ( result_cb && typeof result_cb === 'function' ) {
result_cb(id, res);
}
} )
.fail( function( response ) {
res.status = false;
res.response = response;
if ( result_cb && typeof result_cb === 'function' ) {
result_cb(id, res);
}
} );
}
},
// object to hold attachements keyed by attachment id
attachments: {},
// get an attachment obj from attachments, or by ajax if needed
// -- 1st arg is id, 2nd is existing obj to (re)place in table and
// is optional, 3rd is an optional callback taking the 2 args
// described for 'attachment_data_by_id' plus a 3rd convenience
// arg -- the cache object
//
// -- returns attachment object if possible, false on error, and
// null on ajax call with result pending
get_attachment_by_id: function(id, attach_put, result_cb) {
if ( this.attachments.id === undefined ) {
if ( attach_put !== undefined && attach_put ) {
this.attachments.id = attach_put;
return attach_put;
} else {
var obj = this.attachments, cb = result_cb || false;
this.attachment_data_by_id(id, function (_id, _res) {
if ( _res.status === true ) {
obj[_id] = _res.response;
} else {
obj[_id] = false;
}
if ( typeof cb === 'function' ) {
cb(_id, _res, obj);
}
} );
return null;
}
} else {
if ( attach_put !== undefined && attach_put ) {
this.attachments.id = attach_put;
}
return this.attachments.id;
}
return false;
}
};
var SWFPut_video_utility_obj =
new SWFPut_video_utility_obj_def(wp || false);
//
// Experimental wp.media based presentation in/of editor thing
//
// Our button (next to "Add Media") calls this
var SWFPut_add_button_func = function(btn) {
var ivl, ivlmax = 100, tid = btn.id, ed,
sc = SWFPut_video_utility_obj.get_new_putswf_shortcode(),
dat = SWFPut_putswf_video_inst.get_mce_dat(),
enc = window.encodeURIComponent( sc ),
div = false;
if ( ! (dat && dat.ed) ) {
alert('Failed to get visual editor');
return false;
}
ed = dat.ed;
ed.selection.setContent( sc + ' ', {format : 'text'} );
ivl = setInterval( function() {
var divel, // raw browser dom element vs. mce object
got = false,
$ = ed.$;
if ( div === false ) {
var w = $( '.wpview-wrap' );
w.each( function(cur) {
var at;
// wacky: mce.dom.query.each passing number, not obj
cur = w[cur];
at = cur.getAttribute( 'data-wpview-text' );
if ( at && at.indexOf( enc ) >= 0 ) {
divel = cur; // keep raw . . .
div = $( cur ); // . . . and mce obj
return false;
}
} );
}
if ( div !== false ) {
var f = div.find( 'iframe' );
if ( f ) {
ed.selection.select( divel, true );
ed.selection.scrollIntoView( divel );
div.trigger( 'click' );
got = true;
}
}
if ( (--ivlmax <= 0) || got ) {
clearInterval( ivl );
}
}, 1500);
return false;
};
// get an attachment obj from attachments, or by ajax if needed
// -- 1st arg is id, 2nd is existing obj to (re)place in table and
// is optional
var SWFPut_get_attachment_by_id = function(id, attach_put, result_cb) {
return SWFPut_video_utility_obj
? SWFPut_video_utility_obj.get_attachment_by_id(id, attach_put, result_cb || false)
: false;
};
// specific to putswf shortcode attr url and altvideo.
// and iimage -- these might have a URL or WP
// attachment ID -- in the latter case get the
// wp "attachment" object w/ ajax and cache the
// objs for later use
var SWFPut_cache_shortcode_ids = function(sc, cb) {
var aatt = [
sc.get( 'url' ),
sc.get( 'altvideo' ),
sc.get( 'iimage' )
], _cb = (cb && typeof cb === 'function') ? cb : false;
_.each(aatt, function(s) {
if ( s != undefined ) {
_.each(s.split('|'), function(t) {
var m = t.match(/^[ \t]*([0-9]+)[ \t]*$/);
if ( m && m[1] ) {
var res = SWFPut_get_attachment_by_id(m[1], false, _cb);
if ( res !== null && _cb !== false ) {
var o = SWFPut_video_utility_obj.attachments;
cb(m[1], o[m[1]], o);
}
}
} );
}
} );
};
// get html document for iframe: head and body params
// are fetched by wp_ajax, returned by SWFPut plugin php;
// styles and bodcls (bodyClasses) are WP hosekeeping.
// this was pulled from within WP method
var SWFPut_get_iframe_document = function(head, styles, bodcls, body) {
head = head || '';
styles = styles || '';
bodcls = bodcls || '';
body = body || '';
return (
'<!DOCTYPE html>' +
'<html>' +
'<head>' +
'<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
head +
styles +
'<style>' +
'html {' +
'background: transparent;' +
'padding: 0;' +
'margin: 0;' +
'}' +
'body#wpview-iframe-sandbox {' +
'background: transparent;' +
'padding: 1px 0 !important;' +
'margin: -1px 0 0 !important;' +
'}' +
'body#wpview-iframe-sandbox:before,' +
'body#wpview-iframe-sandbox:after {' +
'display: none;' +
'content: "";' +
'}' +
'.fix-alignleft {' +
'display: block;' +
'min-height: 32px;' +
'margin-top: 0;' +
'margin-bottom: 0;' +
'margin-left: 0px;' +
'margin-right: auto; }' +
'' +
'.fix-alignright {' +
'display: block;' +
'min-height: 32px;' +
'margin-top: 0;' +
'margin-bottom: 0;' +
'margin-right: 0px;' +
'margin-left: auto; }' +
'' +
'.fix-aligncenter {' +
'clear: both;' +
'display: block;' +
'margin: 0 auto; }' +
'' +
'.alignright .caption {' +
'padding-bottom: 0;' +
'margin-bottom: 0.1rem; }' +
'' +
'.alignleft .caption {' +
'padding-bottom: 0;' +
'margin-bottom: 0.1rem; }' +
'' +
'.aligncenter .caption {' +
'padding-bottom: 0;' +
'margin-bottom: 0.1rem; }' +
'' +
'</style>' +
'</head>' +
'<script type="text/javascript">' +
'var evhh5v_sizer_maxheight_off = true;' +
'</script>' +
'<body id="wpview-iframe-sandbox" class="' + bodcls + '">' +
body +
'</body>' +
'<script type="text/javascript">' +
'( function() {' +
'["alignright", "aligncenter", "alignleft"].forEach( function( c, ix, ar ) {' +
'var nc = "fix-" + c, mxi = 100,' +
'cur = document.getElementsByClassName( c ) || [];' +
'for ( var i = 0; i < cur.length; i++ ) {' +
'var e = cur[i],' +
'mx = 0 + mxi,' +
'iv = setInterval( function() {' +
'var h = e.height || e.offsetHeight;' +
'if ( h && h > 0 ) {' +
'var cl = e.getAttribute( "class" );' +
'cl = cl.replace( c, nc );' +
'e.setAttribute( "class", cl );' +
'h += 2; e.setAttribute( "height", h );' +
'setTimeout( function() {' +
'h -= 2; e.setAttribute( "height", h );' +
'}, 250 );' +
'clearInterval( iv );' +
'} else {' +
'if ( --mx < 1 ) {' +
'clearInterval( iv );' +
'}' +
'}' +
'}, 50 );' +
'}' +
'} );' +
'}() );' +
'</script>' +
'</html>');
};
// Get / help the 'Add SWFPut Video' button
(function() {
var btn = document.getElementById('evhvid-putvid-input-0');
if ( btn != undefined ) {
btn.onclick = 'return false;';
btn.addEventListener(
'click',
function (e) {
// must stop event due to way WP/jquery is handling
// it propagated to ancestor element selected on
// class .insert-media, which our button must use
// for CSS snazziness
e.stopPropagation();
e.preventDefault();
btn.blur();
SWFPut_add_button_func(btn);
},
false
);
}
}());
// MVC
(function(wp, $, _, Backbone) {
var media = wp.media,
baseSettings = SWFPut_video_utility_obj.defprops,
l10n = typeof _wpMediaViewsL10n === 'undefined' ? {} : _wpMediaViewsL10n,
mce = wp.mce,
dbg = true;
var M = { // ...edia
state: [],
// setIframes copied from mce-view.js for broken call
// to MutationObserver.observe() --
// arg 1 was iframeDoc.body but body lacks interface Node
// and more importantly we need to control the markup
// written into the iframe document
setIframes: function ( head, body, callback, rendered ) {
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
self = this;
this.getNodes( function( editor, node, contentNode ) {
var dom = editor.dom,
styles = '',
bodyClasses = editor.getBody().className || '',
editorHead = editor.getDoc().getElementsByTagName( 'head' )[0];
tinymce.each( dom.$( 'link[rel="stylesheet"]', editorHead ), function( link ) {
if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
styles += dom.getOuterHTML( link );
}
} );
// Seems the browsers need a bit of time to insert/set the view nodes,
// or the iframe will fail especially when switching Text => Visual.
setTimeout( function() {
var iframe, iframeDoc, observer, i;
contentNode.innerHTML = '';
iframe = dom.add( contentNode, 'iframe', {
/* jshint scripturl: true */
src: tinymce.Env.ie ? 'javascript:""' : '',
frameBorder: '0',
allowTransparency: 'true',
scrolling: 'no',
'class': 'wpview-sandbox',
style: {
width: '100%',
display: 'block'
}
} );
dom.add( contentNode, 'div', { 'class': 'wpview-overlay' } );
iframeDoc = iframe.contentWindow.document;
iframeDoc.open();
iframeDoc.write(
SWFPut_get_iframe_document( head, styles, bodyClasses, body )
);
iframeDoc.close();
function resize() {
var $iframe, iframeDocHeight;
// Make sure the iframe still exists.
if ( iframe.contentWindow ) {
$iframe = $( iframe );
iframeDocHeight = $( iframeDoc.body ).height();
if ( $iframe.height() !== iframeDocHeight ) {
$iframe.height( iframeDocHeight );
editor.nodeChanged();
}
}
}
$( iframe.contentWindow ).on( 'load', resize );
if ( MutationObserver ) {
var n = iframeDoc; // iframeDoc.body // WP core bug -- had body
observer = new MutationObserver( _.debounce( resize, 100 ) );
observer.observe( n, {
attributes: true,
childList: true,
subtree: true
} );
$( node ).one( 'wp-mce-view-unbind', function() {
observer.disconnect();
} );
} else {
for ( i = 1; i < 6; i++ ) {
setTimeout( resize, i * 700 );
}
}
function classChange() {
iframeDoc.body.className = editor.getBody().className;
}
editor.on( 'wp-body-class-change', classChange );
$( node ).one( 'wp-mce-view-unbind', function() {
editor.off( 'wp-body-class-change', classChange );
} );
callback && callback.call( self, editor, node, contentNode );
}, 50 );
}, rendered );
},
// Sad hack: the replaceMarkers in wp.mce.view is overriden
// because it fails when our captions have markup elements,
// but in addition whitespace differs, so naive comps will
// fail, and additionally in addition tinymce cannot refrain
// from diddling with the elements and adds attributes that
// cause comp fail; therefore, this string prep. function
marker_comp_prepare: function(str) {
var ostr,
rx1 = /[ \t]*data-mce[^=]*="[^"]*"/g,
rx2 = /[ \t]{2,}/g;
ostr = str.substr(0).replace(rx1, '');
if ( ostr ) {
ostr = ostr.replace(rx2, ' ');
}
return ostr || str;
},
/**
* Replaces all marker nodes tied to this view instance.
*
* EH: override here due to naive comparision that fails
* when captions have markup
*/
replaceMarkers: function() {
this.getMarkers( function( editor, node ) {
var c1 = M.marker_comp_prepare( $( node ).html() ),
c2 = M.marker_comp_prepare( this.text );
if ( ! this.loader && c1 !== c2 ) {
editor.dom.setAttrib( node, 'data-wpview-marker', null );
return;
}
editor.dom.replace(
editor.dom.createFragment(
'<div class="wpview-wrap" data-wpview-text="' + this.encodedText + '" data-wpview-type="' + this.type + '">' +
'<p class="wpview-selection-before">\u00a0</p>' +
'<div class="wpview-body" contenteditable="false">' +
'<div class="wpview-content wpview-type-' + this.type + '"></div>' +
'</div>' +
'<p class="wpview-selection-after">\u00a0</p>' +
'</div>'
),
node
);
} );
},
/**
* Tries to find a text match in a given string.
*
* @param {String} content The string to scan.
*
* @return {Object}
*
* EH: originally overridden for debugging, now
* kept in place to add capencoded= to attrs
*/
match: function( content ) {
//var match = wp.shortcode.next( this.type, content );
var rx = /\[(\[?)(putswf_video)(?![\w-])([^\]\/]*(?:\/(?!\])[^\]\/]*)*?)(?:(\/)\]|\](?:([^\[]*(?:\[(?!\/\2\])[^\[]*)*)(\[\/\2\]))?)(\]?)/g,
match = rx.exec( content );
if ( match ) {
var c1, c2;
c1 = ' capencoded="' + encodeURIComponent(match[5]) + '"';
c2 = match[3].indexOf(' capencoded=');
if ( c2 < 0 ) {
c2 = match[3] + c1;
} else {
c2 = match[3].replace(/ capencoded="[^"]*"/g, c1);
}
return {
index: match.index,
content: match[0],
options: {
shortcode: new wp.shortcode({
tag: match[2],
attrs: c2,
type: match[6] ? 'closed' : 'single',
content: match[5]
})
}
};
}
},
edit: function( text, update ) {
var media = wp.media[ this.type ],
frame = media.edit( text );
this.pausePlayers && this.pausePlayers();
_.each( this.state, function( state ) {
frame.state( state ).on( 'update', function( selection ) {
var s = media.shortcode( selection ).string()
update( s );
} );
} );
frame.on( 'close', function() {
frame.detach();
} );
frame.open();
}
};
var V = _.extend( {}, M, { // ...ideo
action: 'parse_putswf_video_shortcode',
initialize: function() {
var self = this;
this.fetch();
this.getEditors( function( editor ) {
editor.on( 'wpview-selected', function() {
self.pausePlayers();
} );
} );
},
fetch: function () {
var self = this,
atts = SWFPut_video_utility_obj.atts_filter(
this.shortcode.attrs.named),
sc =
SWFPut_video_utility_obj.mk_shortcode(
this.shortcode.tag,
atts,
this.shortcode.content),
ng = this.shortcode.string();
wp.ajax.send( this.action, {
data: {
post_ID: $( '#post_ID' ).val() || 0,
type: this.shortcode.tag,
shortcode: sc
}
} )
.done( function( response ) {
self.render( response );
} )
.fail( function( response ) {
if ( self.url ) {
self.removeMarkers();
} else {
self.setError( response.message || response.statusText, 'admin-media' );
}
} );
},
stopPlayers: function( event_arg ) {
var rem = event_arg; // might be Event or string
this.getNodes( function( editor, node, content ) {
var p, win,
iframe = $( 'iframe.wpview-sandbox', content ).get(0);
if ( iframe && ( win = iframe.contentWindow ) && win.evhh5v_sizer_instances ) {
try {
for ( p in win.evhh5v_sizer_instances ) {
var vi = win.evhh5v_sizer_instances[p],
v = vi.va_o || false, // H5V
f = vi.o || false, // flash
act = (event_arg === 'pause')
? 'pause' : 'stop';
// use 'stop()' or 'pause()'
// the latter is gentler
if ( v && (typeof v[act] === 'function') ) {
v[act]();
}
if ( f && (typeof f[act] === 'function') ) {
f[act]();
}
}
} catch( err ) {
var e = err.message;
}
if ( rem === 'remove' ) {
iframe.contentWindow = null;
iframe = null;
}
}
});
},
pausePlayers: function() {
this.stopPlayers && this.stopPlayers( 'pause' );
},
} );
mce.views.register( 'putswf_video', _.extend( {}, V, {
state: [ 'putswf_video-details' ]
} ) );
// NOTE: several of the objects below have a 'media' object
// usually assigned in initialize() -- but these are not necessarily
// the same type, much less same obj.
// MODEL: available as 'data.model' within frame content template
media.model.putswf_postMedia = Backbone.Model.extend({
SWFPut_cltag: 'media.model.putswf_postMedia',
// called with shortcode attributes including shortcode object
initialize: function(o) {
this.attachment = this.initial_attrs = false;
if ( o !== undefined && o.shortcode !== undefined ) {
var that = this, sc = o.shortcode,
pat = /^[ \t]*([^ \t]*(.*[^ \t])?)[ \t]*$/;
this.initial_attrs = o;
this.poster = '';
this.flv = '';
this.html5s = [];
if ( sc.iimage ) {
var m = pat.exec(sc.iimage);
this.poster = (m && m[1]) ? m[1] : sc.iimage;
}
if ( sc.url ) {
var m = pat.exec(sc.url);
this.flv = (m && m[1]) ? m[1] : sc.url;
}
if ( sc.altvideo ) {
var t = sc.altvideo, a = t.split('|');
for ( var i = 0; i < a.length; i++ ) {
var m = pat.exec(a[i]);
if ( m && m[1] ) {
this.html5s.push(m[1]);
}
}
}
SWFPut_cache_shortcode_ids( sc, function(id, r, c) {
var sid = '' + id;
that.initial_attrs.id_cache = c;
if ( that.initial_attrs.id_array === undefined ) {
that.initial_attrs.id_array = [];
}
that.initial_attrs.id_array.push(id);
if ( that.poster === sid ) {
that.poster = c[id];
} else if ( that.flv === sid ) {
that.flv = c[id];
} else if ( that.html5s !== null ) {
for ( var i = 0; i < that.html5s.length; i++ ) {
if ( that.html5s[i] === sid ) {
that.html5s[i] = c[id];
}
}
}
} );
}
},
poster : null,
flv : null,
html5s : null,
setSource: function( attachment ) {
this.attachment = attachment;
this.extension = attachment.get( 'filename' ).split('.').pop();
if ( this.get( 'src' ) && this.extension === this.get( 'src' ).split('.').pop() ) {
this.unset( 'src' );
}
if ( _.contains( wp.media.view.settings.embedExts, this.extension ) ) {
this.set( this.extension, this.attachment.get( 'url' ) );
} else {
this.unset( this.extension );
}
try {
var am, multi = attachment.get( 'putswf_attach_all' );
if ( multi && multi.toArray().length < 1 ) {
delete this.attachment.putswf_attach_all;
}
} catch ( e ) {
}
},
changeAttachment: function( attachment ) {
var self = this;
this.setSource( attachment );
this.unset( 'src' );
_.each( _.without( wp.media.view.settings.embedExts, this.extension ), function( ext ) {
self.unset( ext );
} );
}
,
// methods specific to SWFPut
cleanup_media: function() {
var a = [],
mp4 = false, ogg = false, webm = false;
for ( var i = 0; i < this.html5s.length; i++ ) {
var m = this.html5s[i];
if ( typeof m === 'object' ) {
var t = m.subtype
? (m.subtype.split('-').pop())
: (m.filename
? m.filename.split('.').pop()
: false
);
// last wins
switch ( t ) {
case 'mp4':
case 'm4v':
case 'mv4':
mp4 = m;
break;
case 'ogg':
case 'ogv':
case 'vorbis':
ogg = m;
break;
case 'webm':
case 'wbm':
case 'vp8':
case 'vp9':
webm = m;
break;
}
} else {
a.push(m);
}
}
if ( mp4 ) {
a.push(mp4);
}
if ( ogg ) {
a.push(ogg);
}
if ( webm ) {
a.push(webm);
}
this.html5s = a;
},
// get uri related strings -- if display is true
// get URL if available as it's informative;
// else use id integers if available
get_poster: function( display ) {
display = display || false;
if ( display && this.poster !== null ) {
return ( typeof this.poster === 'object' )
? this.poster.url
: this.poster;
}
if ( this.poster !== null ) {
return ( typeof this.poster === 'object' )
? ('' + this.poster.id)
: this.poster;
}
return '';
},
get_flv: function( display ) {
display = display || false;
if ( display && this.flv !== null ) {
return ( typeof this.flv === 'object' )
? this.flv.url
: this.flv;
}
if ( this.flv !== null ) {
return ( typeof this.flv === 'object' )
? ('' + this.flv.id)
: this.flv;
}
return '';
},
get_html5s: function( display ) {
var s ='';
display = display || false;
if ( this.html5s === null ) {
return s;
}
for ( var i = 0; i < this.html5s.length; i++ ) {
var cur = this.html5s[i], addl = '';
if ( s !== '' ) {
addl += ' | ';
}
addl += ( typeof cur === 'object' )
? (display ? cur.url : ('' + cur.id))
: cur;
s += addl;
}
return s;
},
putswf_postex: function() {
},
}); // media.model.putswf_postMedia = Backbone.Model.extend({
// media.view.MediaFrame.Select -> media.view.MediaFrame.MediaDetails
media.view.MediaFrame.Putswf_mediaDetails = media.view.MediaFrame.Select.extend({ //media.view.MediaFrame.MediaDetails.extend({ //
defaults: {
id: 'putswf_media',
//id: 'media',
url: '',
menu: 'media-details',
content: 'media-details',
toolbar: 'media-details',
type: 'link',
priority: 121 // 120
},
SWFPut_cltag: 'media.view.MediaFrame.Putswf_mediaDetails',
initialize: function( options ) {
//var controller = options.controller || false,
// model = options.model || false,
// attachment = options.attachment || false;
this.DetailsView = options.DetailsView;
this.cancelText = options.cancelText;
this.addText = options.addText;
this.media = new media.model.putswf_postMedia( options.metadata ); //PostMedia( options.metadata );
this.options.selection = new media.model.Selection( this.media.attachment, { multiple: true } );// { multiple: false } ); //
media.view.MediaFrame.Select.prototype.initialize.apply( this, arguments );
//media.view.MediaFrame.MediaDetails.prototype.initialize.apply( this, arguments );
}
,
bindHandlers: function() {
var menu = this.defaults.menu;
media.view.MediaFrame.Select.prototype.bindHandlers.apply( this, arguments );
//media.view.MediaFrame.MediaDetails.prototype.bindHandlers.apply( this, arguments );
this.on( 'menu:create:' + menu, this.createMenu, this );
this.on( 'content:render:' + menu, this.renderDetailsContent, this );
this.on( 'menu:render:' + menu, this.renderMenu, this );
this.on( 'toolbar:render:' + menu, this.renderDetailsToolbar, this );
},
// lots of following code copied right from
// wp-includes/js/media-audiovideo.js
renderDetailsContent: function() {
var attach = this.state().media.attachment;
var view = new this.DetailsView({
controller: this,
model: this.state().media,
attachment: attach //this.state().media.attachment //
}).render();
this.content.set( view );
}
,
renderMenu: function( view ) {
var lastState = this.lastState(),
previous = lastState && lastState.id,
frame = this;
view.set({
cancel: {
text: this.cancelText,
priority: 20,
click: function() {
if ( previous ) {
frame.setState( previous );
} else {
frame.close();
}
}
},
separateCancel: new media.View({
className: 'separator',
priority: 40
})
});
},
setPrimaryButton: function(text, handler) {
this.toolbar.set( new media.view.Toolbar({
controller: this,
items: {
button: {
style: 'primary',
text: text,
priority: 80,
click: function() {
var controller = this.controller;
handler.call( this, controller, controller.state() );
// Restore and reset the default state.
controller.setState( controller.options.state );
controller.reset();
}
}
}
}) );
},
renderDetailsToolbar: function() {
this.setPrimaryButton( l10n.update, function( controller, state ) {
controller.close();
state.trigger( 'update', controller.media.toJSON() );
} );
},
renderReplaceToolbar: function() {
this.setPrimaryButton( l10n.replace, function( controller, state ) {
var attachment = state.get( 'selection' ).single();
controller.media.changeAttachment( attachment );
state.trigger( 'replace', controller.media.toJSON() );
} );
},
renderAddSourceToolbar: function() {
this.setPrimaryButton( this.addText, function( controller, state ) {
var attachment = state.get( 'selection' ).single();
controller.media.setSource( attachment );
state.trigger( 'add-source', controller.media.toJSON() );
} );
}
}); // media.view.MediaFrame.Putswf_mediaDetails = media.view.MediaFrame.MediaDetails.extend({ // = media.view.MediaFrame.Select.extend({
media.view.SWFPutDetails = media.view.Settings.AttachmentDisplay.extend({
SWFPut_cltag: 'media.view.SWFPutDetails',
initialize: function() {
_.bindAll(this, 'success');
this.players = [];
this.listenTo( this.controller, 'close', media.putswf_mixin.unsetPlayers );
this.on( 'ready', this.setPlayer );
this.on( 'media:setting:remove', media.putswf_mixin.unsetPlayers, this );
this.on( 'media:setting:remove', this.render );
this.on( 'media:setting:remove', this.setPlayer );
this.events = _.extend( this.events, {
'click .remove-setting' : 'removeSetting',
//'change .content-track' : 'setTracks',
//'click .remove-track' : 'setTracks',
'click .add-media-source' : 'addSource'
} );
media.view.Settings.AttachmentDisplay.prototype.initialize.apply( this, arguments );
},
prepare: function() {
var model = this.model;
return _.defaults({
model: model //model: this.model.toJSON()
}, this.options );
},
/**
* Remove a setting's UI when the model unsets it
*
* @fires wp.media.view.MediaDetails#media:setting:remove
*
* @param {Event} e
*/
removeSetting : function(e) {
var wrap = $( e.currentTarget ).parent(), setting;
setting = wrap.find( 'input' ).data( 'setting' );
if ( setting ) {
this.model.unset( setting );
this.trigger( 'media:setting:remove', this );
}
wrap.remove();
},
/**
*
* @fires wp.media.view.MediaDetails#media:setting:remove
*/
setTracks : function() {
//var tracks = '';
//
//_.each( this.$('.content-track'), function(track) {
// tracks += $( track ).val();
//} );
//
//this.model.set( 'content', tracks );
//this.trigger( 'media:setting:remove', this );
},
addSource : function( e ) {
this.controller.lastMime = $( e.currentTarget ).data( 'mime' );
this.controller.setState( 'add-' + this.controller.defaults.id + '-source' );
},
/**
* @global MediaElementPlayer
*/
setPlayer : function() {
//if ( ! this.players.length && this.media ) {
// this.players.push( new MediaElementPlayer( this.media, this.settings ) );
//}
},
/**
* @abstract
*/
setMedia : function() {
return this;
},
success : function(mejs) {
//var autoplay = mejs.attributes.autoplay && 'false' !== mejs.attributes.autoplay;
//
//if ( 'flash' === mejs.pluginType && autoplay ) {
// mejs.addEventListener( 'canplay', function() {
// mejs.play();
// }, false );
//}
//
//this.mejs = mejs;
},
/**
* @returns {media.view.MediaDetails} Returns itself to allow chaining
*/
render: function() {
var self = this;
media.view.Settings.AttachmentDisplay.prototype.render.apply( this, arguments );
setTimeout( function() { self.resetFocus(); }, 10 );
this.settings = _.defaults( {
success : this.success
}, baseSettings );
return this.setMedia();
},
resetFocus: function() {
this.$( '.putswf_video-details-iframe' ).scrollTop( 0 );
}
}, {
instances : 0,
/**
* When multiple players in the DOM contain the same src, things get weird.
*
* @param {HTMLElement} elem
* @returns {HTMLElement}
*/
// EH: above is orig comment from WP core
prepareSrc : function( elem ) {
var i = media.view.SWFPutDetails.instances++;
// EH: in SWFPut the following loop will only be effactive
// if sources were set in the metabox along with
// types -- otherwise harmless
_.each( $( elem ).find( 'source' ), function( source ) {
source.src = [
source.src,
source.src.indexOf('?') > -1 ? '&' : '?',
'_=',
i
].join('');
} );
return elem;
}
});
//media.view.Putswf_videoDetails = media.view.MediaFrame.Putswf_mediaDetails.extend({
media.view.Putswf_videoDetails = media.view.SWFPutDetails.extend({
//className: 'putswf_video-details',
className: 'putswf_video-mediaframe-details',
template: media.template('putswf_video-details'),
SWFPut_cltag: 'media.view.Putswf_videoDetails',
initialize: function() {
_.bindAll(this, 'success');
this.players = [];
this.listenTo( this.controller, 'close', wp.media.putswf_mixin.unsetPlayers );
this.on( 'ready', this.setPlayer );
this.on( 'media:setting:remove', wp.media.putswf_mixin.unsetPlayers, this );
this.on( 'media:setting:remove', this.render );
this.on( 'media:setting:remove', this.setPlayer );
this.events = _.extend( this.events, {
// 'click .remove-setting' : 'removeSetting',
// 'change .content-track' : 'setTracks',
// 'click .remove-track' : 'setTracks',
'click .add-media-source' : 'addSource'
} );
this.init_data = (arguments && arguments[0])
? arguments[0] : false;
media.view.SWFPutDetails.prototype.initialize.apply( this, arguments );
},
setMedia: function() {
var v1 = this.$('.evhh5v_vidobjdiv'),
v2 = this.$('.wp-caption'),
video = v1 || v2,
found = video.find( 'video' )
|| video.find( 'canvas' )
|| video.find( 'object' );
if ( found ) {
video.show();
this.media = media.view.SWFPutDetails.prepareSrc( video.get(0) );
} else {
video.hide();
this.media = false;
}
return this;
}
});
// TITLE
media.controller.Putswf_videoDetails = media.controller.State.extend({
defaults: {
id: 'putswf_video-details', //'putswf_video', //
toolbar: 'putswf_video-details',
title: 'SWFPut Video Details', //l10n.putswf_videoDetailsTitle,
content: 'putswf_video-details',
menu: 'putswf_video-details',
router: false,
priority: 60
},
SWFPut_cltag: 'media.controller.Putswf_videoDetails',
initialize: function( options ) {
// media should be a media.model.putswf_postMedia
this.media = options.media;
media.controller.State.prototype.initialize.apply( this, arguments );
}
,
setSource: function( attachment ) {
this.attachment = attachment;
this.extension = attachment.get( 'filename' ).split('.').pop();
//if ( this.get( 'src' ) && this.extension === this.get( 'src' ).split('.').pop() ) {
// this.unset( 'src' );
//}
//
//if ( _.contains( wp.media.view.settings.embedExts, this.extension ) ) {
// this.set( this.extension, this.attachment.get( 'url' ) );
//} else {
// this.unset( this.extension );
//}
}
});
// media.view.MediaFrame.Putswf_mediaDetails
media.view.MediaFrame.Putswf_videoDetails = media.view.MediaFrame.Putswf_mediaDetails.extend({ // media.view.MediaFrame.MediaDetails.extend({
defaults: {
id: 'putswf_video',
url: '',
menu: 'putswf_video-details',
content: 'putswf_video-details',
toolbar: 'putswf_video-details',
type: 'link',
title: 'SWFPut Video -- Media', //l10n.putswf_videoDetailsTitle,
priority: 120
},
SWFPut_cltag: 'media.view.MediaFrame.Putswf_videoDetails',
initialize: function( options ) {
this.media = options.media;
options.DetailsView = media.view.Putswf_videoDetails;
options.cancelText = 'Cancel Edit'; //l10n.putswf_videoDetailsCancel;
options.addText = 'Add Video'; //l10n.putswf_videoAddSourceTitle;
media.view.MediaFrame.Putswf_mediaDetails.prototype.initialize.call( this, options );
},
bindHandlers: function() {
media.view.MediaFrame.Putswf_mediaDetails.prototype.bindHandlers.apply( this, arguments );
this.on( 'toolbar:render:replace-putswf_video', this.renderReplaceToolbar, this );
this.on( 'toolbar:render:add-putswf_video-source', this.renderAddSourceToolbar, this );
this.on( 'toolbar:render:putswf_poster-image', this.renderSelectPosterImageToolbar, this );
//this.on( 'toolbar:render:add-track', this.renderAddTrackToolbar, this );
},
createStates: function() {
this.states.add([
new media.controller.Putswf_videoDetails( {
media: this.media
} ),
new media.controller.MediaLibrary( {
type: 'video',
id: 'replace-putswf_video',
title: 'Replace Media', //l10n.putswf_videoReplaceTitle,
toolbar: 'replace-putswf_video',
media: this.media,
menu: 'putswf_video-details'
} ),
new media.controller.MediaLibrary( {
type: 'video',
id: 'add-putswf_video-source',
title: 'Add Media', //l10n.putswf_videoAddSourceTitle,
toolbar: 'add-putswf_video-source',
media: this.media,
multiple: true,
//syncSelection: true,
menu: 'putswf_video-details'
//menu: false
} ),
new media.controller.MediaLibrary( {
type: 'image',
id: 'select-poster-image',
title: l10n.SelectPosterImageTitle
? l10n.SelectPosterImageTitle
: 'Set Initial (poster) Image',
toolbar: 'putswf_poster-image',
media: this.media,
menu: 'putswf_video-details'
} ),
]);
},
renderSelectPosterImageToolbar: function() {
this.setPrimaryButton( 'Select Poster Image', function( controller, state ) {
var attachment = state.get( 'selection' ).single();
attachment.attributes.putswf_action = 'poster';
controller.media.changeAttachment( attachment );
state.trigger( 'replace', controller.media.toJSON() );
} );
},
renderReplaceToolbar: function() {
this.setPrimaryButton( 'Replace Video', function( controller, state ) {
var attachment = state.get( 'selection' ).single();
attachment.attributes.putswf_action = 'replace_video';
controller.media.changeAttachment( attachment );
state.trigger( 'replace', controller.media.toJSON() );
} );
},
renderAddSourceToolbar: function() {
this.setPrimaryButton( this.addText, function( controller, state ) {
var attachment = state.get( 'selection' ).single(); //; //
var attach_all = state.get( 'selection' ) || false;
attachment.attributes.putswf_action = 'add_video';
// w/ multiple add the full del monte --
// dirty hack unto blech -- but there are errors w/
// the multiple selection I haven't figured out yet
if ( attach_all && attach_all.multiple ) {
attachment.attributes.putswf_attach_all = attach_all;
}
controller.media.setSource( attachment );
state.trigger( 'add-source', controller.media.toJSON() );
} );
},
});
wp.media.putswf_mixin = {
putswfSettings: baseSettings,
SWFPut_cltag: 'wp.media.putswf_mixin',
removeAllPlayers: function() {
},
/**
* Override the MediaElement method for removing a player.
* MediaElement tries to pull the audio/video tag out of
* its container and re-add it to the DOM.
*/
removePlayer: function(t) {
},
/**
* Allows any class that has set 'player' to a MediaElementPlayer
* instance to remove the player when listening to events.
*
* Examples: modal closes, shortcode properties are removed, etc.
*/
unsetPlayers : function() {
}
}; // wp.media.putswf_mixin = {
// Sort of basic media type object: the MCE view object gets
// one of the from wp.media[ this.type ] in its edit method
// then calls edit on this
wp.media.putswf_video = {
//coerce : wp.media.coerce,
defaults : baseSettings,
SWFPut_cltag: 'wp.media.putswf_video',
_mk_shortcode : SWFPut_video_utility_obj.mk_shortcode,
_atts_filter : SWFPut_video_utility_obj.atts_filter,
// called by MCE view::edit -- the arg is
// an unmolested shortcode string
edit : function( data ) {
var frame,
shortcode = wp.shortcode.next( 'putswf_video', data ).shortcode,
attrs, aext,
MediaFrame = media.view.MediaFrame;
attrs = shortcode.attrs.named;
attrs.content = shortcode.content;
attrs.shortcode = shortcode;
aext = {
frame: 'putswf_video',
state: 'putswf_video-details',
metadata: _.defaults( attrs, this.defaults )
};
frame = new media.view.MediaFrame.Putswf_videoDetails( aext );
media.frame = frame;
return frame;
},
// the MCE view object update callback calls this (statically,
// dont't use this) as in:
// var shortcode = wp.media[ self.type ].shortcode( selection ).string();
shortcode : function( model_atts ) { // arg is "selection"
var content, sc, atts;
sc = model_atts.shortcode.tag;
content = model_atts.content; //.substr(0);
atts = wp.media.putswf_video._atts_filter(model_atts);
// code elsewhere adds props to selection, so the use of
// _atts_filter() is required to make a working
// shortcode
//return wp.media.putswf_video._mk_shortcode( sc, atts, content );
return new wp.shortcode({
tag: sc,
attrs: atts,
content: content
});
}
};
}(wp, jQuery, _, Backbone));
|
ehy/swfput-wp
|
js/editor_plugin45.js
|
JavaScript
|
gpl-3.0
| 42,346 |
"use strict";
// Handle Right Button events
function OnRightButtonPressed()
{
$.Msg("OnRightButtonPressed")
var iPlayerID = Players.GetLocalPlayer();
var mainSelected = Players.GetLocalPlayerPortraitUnit();
var mainSelectedName = Entities.GetUnitName( mainSelected )
var cursor = GameUI.GetCursorPosition();
var mouseEntities = GameUI.FindScreenEntities( cursor );
mouseEntities = mouseEntities.filter( function(e) { return e.entityIndex != mainSelected; } )
var pressedShift = GameUI.IsShiftDown();
// Builder Right Click
if ( IsBuilder(mainSelectedName) )
{
// Cancel BH
SendCancelCommand();
// If it's mousing over entities
if (mouseEntities.length > 0)
{
for ( var e of mouseEntities )
{
var entityName = Entities.GetUnitName(e.entityIndex)
// Gold mine rightclick
if (entityName == "gold_mine"){
$.Msg("Player "+iPlayerID+" Clicked on a gold mine")
GameEvents.SendCustomGameEventToServer( "gold_gather_order", { pID: iPlayerID, mainSelected: mainSelected, targetIndex: e.entityIndex, queue: pressedShift})
return true;
}
// Entangled gold mine rightclick
else if (mainSelectedName == "nightelf_wisp" && entityName == "nightelf_entangled_gold_mine" && Entities.IsControllableByPlayer( e.entityIndex, iPlayerID )){
$.Msg("Player "+iPlayerID+" Clicked on a entangled gold mine")
GameEvents.SendCustomGameEventToServer( "gold_gather_order", { pID: iPlayerID, mainSelected: mainSelected, targetIndex: e.entityIndex, queue: pressedShift })
return true;
}
// Haunted gold mine rightclick
else if (mainSelectedName == "undead_acolyte" && entityName == "undead_haunted_gold_mine" && Entities.IsControllableByPlayer( e.entityIndex, iPlayerID )){
$.Msg("Player "+iPlayerID+" Clicked on a haunted gold mine")
GameEvents.SendCustomGameEventToServer( "gold_gather_order", { pID: iPlayerID, mainSelected: mainSelected, targetIndex: e.entityIndex, queue: pressedShift })
return true;
}
// Repair rightclick
else if ( (IsCustomBuilding(e.entityIndex) || IsMechanical(e.entityIndex)) && Entities.GetHealthPercent(e.entityIndex) < 100 && Entities.IsControllableByPlayer( e.entityIndex, iPlayerID ) ){
$.Msg("Player "+iPlayerID+" Clicked on a building or mechanical unit with health missing")
GameEvents.SendCustomGameEventToServer( "repair_order", { pID: iPlayerID, mainSelected: mainSelected, targetIndex: e.entityIndex, queue: pressedShift })
return true;
}
return false;
}
}
}
// Building Right Click
else if (IsCustomBuilding(mainSelected))
{
$.Msg("Building Right Click")
// Click on a target entity
if (mouseEntities.length > 0)
{
for ( var e of mouseEntities )
{
var entityName = Entities.GetUnitName(e.entityIndex)
if ( entityName == "gold_mine" || ( Entities.IsControllableByPlayer( e.entityIndex, iPlayerID ) && (entityName == "nightelf_entangled_gold_mine" || entityName == "undead_haunted_gold_mine")))
{
$.Msg(" Targeted gold mine")
GameEvents.SendCustomGameEventToServer( "building_rally_order", { pID: iPlayerID, mainSelected: mainSelected, rally_type: "mine", targetIndex: e.entityIndex })
}
else{
$.Msg(" Targeted a building")
GameEvents.SendCustomGameEventToServer( "building_rally_order", { pID: iPlayerID, mainSelected: mainSelected, rally_type: "target", targetIndex: e.entityIndex })
}
return true;
}
}
// Click on a position
else
{
$.Msg(" Targeted position")
var GamePos = Game.ScreenXYToWorld(cursor[0], cursor[1]);
GameEvents.SendCustomGameEventToServer( "building_rally_order", { pID: iPlayerID, mainSelected: mainSelected, rally_type: "position", position: GamePos})
return true;
}
}
// Unit rightclick
if (mouseEntities.length > 0)
{
for ( var e of mouseEntities )
{
// Moonwell rightclick
if (IsCustomBuilding(e.entityIndex) && Entities.GetUnitName(e.entityIndex) == "nightelf_moon_well" && Entities.IsControllableByPlayer( e.entityIndex, iPlayerID ) )
{
$.Msg("Player "+iPlayerID+" Clicked on moon well to replenish")
GameEvents.SendCustomGameEventToServer( "moonwell_order", { pID: iPlayerID, mainSelected: mainSelected, targetIndex: e.entityIndex })
return false; //Keep the unit order
}
else
{
GameEvents.SendCustomGameEventToServer( "right_click_order", { pID: iPlayerID })
}
}
}
return false;
}
function IsBuilder(name) {
return (name == "human_peasant" || name == "nightelf_wisp" || name == "orc_peon" || name == "undead_acolyte")
}
// Main mouse event callback
GameUI.SetMouseCallback( function( eventName, arg ) {
var CONSUME_EVENT = true;
var CONTINUE_PROCESSING_EVENT = false;
if ( GameUI.GetClickBehaviors() !== CLICK_BEHAVIORS.DOTA_CLICK_BEHAVIOR_NONE )
return CONTINUE_PROCESSING_EVENT;
var mainSelectedName = Entities.GetUnitName( Players.GetLocalPlayerPortraitUnit())
if ( eventName === "pressed" && IsBuilder(mainSelectedName))
{
// Left-click with a builder while BH is active
if ( arg === 0 && state == "active")
{
return SendBuildCommand();
}
// Right-click (Cancel & Repair)
if ( arg === 1 )
{
return OnRightButtonPressed();
}
}
else if ( eventName === "pressed" || eventName === "doublepressed")
{
// Left-click
if ( arg === 0 )
{
//OnLeftButtonPressed();
return CONTINUE_PROCESSING_EVENT;
}
// Right-click
if ( arg === 1 )
{
return OnRightButtonPressed();
}
}
return CONTINUE_PROCESSING_EVENT;
} );
|
TideSofDarK/DotaCraft
|
content/dota_addons/dotacraft/panorama/scripts/clicks.js
|
JavaScript
|
gpl-3.0
| 5,690 |
var searchData=
[
['distance',['distance',['../struct_settings_values.html#ad1a3f2b400302307e0a5d6bb7efcbb15',1,'SettingsValues']]]
];
|
eucall-software/targeter
|
docs/search/variables_1.js
|
JavaScript
|
gpl-3.0
| 137 |
var mbFilter = {
dateFormat:function(date,format)
{
date = new Date(date);
var o = {
"M+" : date.getMonth()+1, //month
"d+" : date.getDate(), //day
"h+" : date.getHours(), //hour
"m+" : date.getMinutes(), //minute
"s+" : date.getSeconds(), //second
"q+" : Math.floor((date.getMonth()+3)/3), //quarter
"S" : date.getMilliseconds() //millisecond
}
if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
(date.getFullYear()+"").substr(4- RegExp.$1.length));
for(var k in o)if(new RegExp("("+ k +")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length==1? o[k] :
("00"+ o[k]).substr((""+ o[k]).length));
return format;
},
dgmdate:function (date) {
date = date*1000;
var o = Date.now() - date;
if (o > 259200000) {
return this.dateFormat(date,'yyyy-MM-dd hh:mm');
} else if (o > 86400000) {
return Math.floor(o / 86400000) + '天前';
} else if (o > 3600000) {
return Math.floor(o / 3600000) + '小时前';
} else if (o > 60000) {
return Math.floor(o / 60000) + '分钟前';
} else {
return "刚刚";
}
}
}
|
ckken/vco-riot-mobile
|
app/mod/filter.js
|
JavaScript
|
gpl-3.0
| 1,368 |
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
ccs.SliderEventType = {percent_changed: 0};
/**
* Base class for ccs.UISlider
* @class
* @extends ccs.UIWidget
*/
ccs.UISlider = ccs.UIWidget.extend({
_barRenderer: null,
_progressBarRenderer: null,
_progressBarTextureSize: null,
_slidBallNormalRenderer: null,
_slidBallPressedRenderer: null,
_slidBallDisabledRenderer: null,
_slidBallRenderer: null,
_barLength: 0,
_percent: 0,
_scale9Enabled: false,
_prevIgnoreSize: true,
_textureFile: "",
_progressBarTextureFile: "",
_slidBallNormalTextureFile: "",
_slidBallPressedTextureFile: "",
_slidBallDisabledTextureFile: "",
_capInsetsBarRenderer: null,
_capInsetsProgressBarRenderer: null,
_sliderEventListener: null,
_sliderEventSelector: null,
_barTexType: null,
_progressBarTexType: null,
_ballNTexType: null,
_ballPTexType: null,
_ballDTexType: null,
ctor: function () {
ccs.UIWidget.prototype.ctor.call(this);
this._barRenderer = null;
this._progressBarRenderer = null;
this._progressBarTextureSize = cc.size(0, 0);
this._slidBallNormalRenderer = null;
this._slidBallPressedRenderer = null;
this._slidBallDisabledRenderer = null;
this._slidBallRenderer = null;
this._barLength = 0;
this._percent = 0;
this._scale9Enabled = false;
this._prevIgnoreSize = true;
this._textureFile = "";
this._progressBarTextureFile = "";
this._slidBallNormalTextureFile = "";
this._slidBallPressedTextureFile = "";
this._slidBallDisabledTextureFile = "";
this._capInsetsBarRenderer = cc.RectZero();
this._capInsetsProgressBarRenderer = cc.RectZero();
this._sliderEventListener = null;
this._sliderEventSelector = null;
this._barTexType = ccs.TextureResType.local;
this._progressBarTexType = ccs.TextureResType.local;
this._ballNTexType = ccs.TextureResType.local;
this._ballPTexType = ccs.TextureResType.local;
this._ballDTexType = ccs.TextureResType.local;
},
initRenderer: function () {
ccs.UIWidget.prototype.initRenderer.call(this);
this._barRenderer = cc.Sprite.create();
this._progressBarRenderer = cc.Sprite.create();
this._progressBarRenderer.setAnchorPoint(cc.p(0.0, 0.5));
this._renderer.addChild(this._barRenderer, -1);
this._renderer.addChild(this._progressBarRenderer, -1);
this._slidBallNormalRenderer = cc.Sprite.create();
this._slidBallPressedRenderer = cc.Sprite.create();
this._slidBallPressedRenderer.setVisible(false);
this._slidBallDisabledRenderer = cc.Sprite.create();
this._slidBallDisabledRenderer.setVisible(false);
this._slidBallRenderer = cc.Node.create();
this._slidBallRenderer.addChild(this._slidBallNormalRenderer);
this._slidBallRenderer.addChild(this._slidBallPressedRenderer);
this._slidBallRenderer.addChild(this._slidBallDisabledRenderer);
this._renderer.addChild(this._slidBallRenderer);
},
/**
* Load texture for slider bar.
* @param {String} fileName
* @param {ccs.TextureResType} texType
*/
loadBarTexture: function (fileName, texType) {
if (!fileName) {
return;
}
texType = texType || ccs.TextureResType.local;
this._textureFile = fileName;
this._barTexType = texType;
switch (this._barTexType) {
case ccs.TextureResType.local:
this._barRenderer.initWithFile(fileName);
break;
case ccs.TextureResType.plist:
this._barRenderer.initWithSpriteFrameName(fileName);
break;
default:
break;
}
if (this._scale9Enabled) {
this._barRenderer.setColor(this.getColor());
this._barRenderer.setOpacity(this.getOpacity());
}
else {
this._barRenderer.setColor(this.getColor());
this._barRenderer.setOpacity(this.getOpacity());
}
this.barRendererScaleChangedWithSize();
},
/**
* Load dark state texture for slider progress bar.
* @param {String} fileName
* @param {ccs.TextureResType} texType
*/
loadProgressBarTexture: function (fileName, texType) {
if (!fileName) {
return;
}
texType = texType || ccs.TextureResType.local;
this._progressBarTextureFile = fileName;
this._progressBarTexType = texType;
switch (this._progressBarTexType) {
case ccs.TextureResType.local:
this._progressBarRenderer.initWithFile(fileName);
break;
case ccs.TextureResType.plist:
this._progressBarRenderer.initWithSpriteFrameName(fileName);
break;
default:
break;
}
if (this._scale9Enabled) {
this._progressBarRenderer.setColor(this.getColor());
this._progressBarRenderer.setOpacity(this.getOpacity());
}
else {
this._progressBarRenderer.setColor(this.getColor());
this._progressBarRenderer.setOpacity(this.getOpacity());
}
this._progressBarRenderer.setAnchorPoint(cc.p(0.0, 0.5));
var locSize = this._progressBarRenderer.getContentSize();
this._progressBarTextureSize.width = locSize.width;
this._progressBarTextureSize.height = locSize.height;
this.progressBarRendererScaleChangedWithSize();
},
/**
* Sets if slider is using scale9 renderer.
* @param {Boolean} able
*/
setScale9Enabled: function (able) {
if (this._scale9Enabled == able) {
return;
}
this._scale9Enabled = able;
this._renderer.removeChild(this._barRenderer, true);
this._renderer.removeChild(this._progressBarRenderer, true);
this._barRenderer = null;
this._progressBarRenderer = null;
if (this._scale9Enabled) {
this._barRenderer = cc.Scale9Sprite.create();
this._progressBarRenderer = cc.Scale9Sprite.create();
}
else {
this._barRenderer = cc.Sprite.create();
this._progressBarRenderer = cc.Sprite.create();
}
this.loadBarTexture(this._textureFile, this._barTexType);
this.loadProgressBarTexture(this._progressBarTextureFile, this._progressBarTexType);
this._renderer.addChild(this._barRenderer, -1);
this._renderer.addChild(this._progressBarRenderer, -1);
if (this._scale9Enabled) {
var ignoreBefore = this._ignoreSize;
this.ignoreContentAdaptWithSize(false);
this._prevIgnoreSize = ignoreBefore;
}
else {
this.ignoreContentAdaptWithSize(this._prevIgnoreSize);
}
this.setCapInsetsBarRenderer(this._capInsetsBarRenderer);
this.setCapInsetProgressBarRebderer(this._capInsetsProgressBarRenderer);
},
/**
* override "ignoreContentAdaptWithSize" method of widget.
* @param {Boolean} ignore
*/
ignoreContentAdaptWithSize: function (ignore) {
if (!this._scale9Enabled || (this._scale9Enabled && !ignore)) {
ccs.UIWidget.prototype.ignoreContentAdaptWithSize.call(this, ignore);
this._prevIgnoreSize = ignore;
}
},
/**
* Sets capinsets for slider, if slider is using scale9 renderer.
* @param {cc.Rect} capInsets
*/
setCapInsets: function (capInsets) {
this.setCapInsetsBarRenderer(capInsets);
this.setCapInsetProgressBarRebderer(capInsets);
},
/**
* Sets capinsets for slider, if slider is using scale9 renderer.
* @param {cc.Rect} capInsets
*/
setCapInsetsBarRenderer: function (capInsets) {
this._capInsetsBarRenderer = capInsets;
if (!this._scale9Enabled) {
return;
}
this._barRenderer.setCapInsets(capInsets);
},
/**
* Sets capinsets for slider, if slider is using scale9 renderer.
* @param {cc.Rect} capInsets
*/
setCapInsetProgressBarRebderer: function (capInsets) {
this._capInsetsProgressBarRenderer = capInsets;
if (!this._scale9Enabled) {
return;
}
this._progressBarRenderer.setCapInsets(capInsets);
},
/**
* Load textures for slider ball.
* @param {String} normal
* @param {String} pressed
* @param {String} disabled
* @param {ccs.TextureResType} texType
*/
loadSlidBallTextures: function (normal, pressed, disabled, texType) {
this.loadSlidBallTextureNormal(normal, texType);
this.loadSlidBallTexturePressed(pressed, texType);
this.loadSlidBallTextureDisabled(disabled, texType);
},
/**
* Load normal state texture for slider ball.
* @param {String} normal
* @param {ccs.TextureResType} texType
*/
loadSlidBallTextureNormal: function (normal, texType) {
if (!normal) {
return;
}
texType = texType || ccs.TextureResType.local;
this._slidBallNormalTextureFile = normal;
this._ballNTexType = texType;
switch (this._ballNTexType) {
case ccs.TextureResType.local:
this._slidBallNormalRenderer.initWithFile(normal);
break;
case ccs.TextureResType.plist:
this._slidBallNormalRenderer.initWithSpriteFrameName(normal);
break;
default:
break;
}
this._slidBallNormalRenderer.setColor(this.getColor());
this._slidBallNormalRenderer.setOpacity(this.getOpacity());
},
/**
* Load selected state texture for slider ball.
* @param {String} pressed
* @param {ccs.TextureResType} texType
*/
loadSlidBallTexturePressed: function (pressed, texType) {
if (!pressed) {
return;
}
texType = texType || ccs.TextureResType.local;
this._slidBallPressedTextureFile = pressed;
this._ballPTexType = texType;
switch (this._ballPTexType) {
case ccs.TextureResType.local:
this._slidBallPressedRenderer.initWithFile(pressed);
break;
case ccs.TextureResType.plist:
this._slidBallPressedRenderer.initWithSpriteFrameName(pressed);
break;
default:
break;
}
this._slidBallPressedRenderer.setColor(this.getColor());
this._slidBallPressedRenderer.setOpacity(this.getOpacity());
},
/**
* Load dark state texture for slider ball.
* @param {String} disabled
* @param {ccs.TextureResType} texType
*/
loadSlidBallTextureDisabled: function (disabled, texType) {
if (!disabled) {
return;
}
texType = texType || ccs.TextureResType.local;
this._slidBallDisabledTextureFile = disabled;
this._ballDTexType = texType;
switch (this._ballDTexType) {
case ccs.TextureResType.local:
this._slidBallDisabledRenderer.initWithFile(disabled);
break;
case ccs.TextureResType.plist:
this._slidBallDisabledRenderer.initWithSpriteFrameName(disabled);
break;
default:
break;
}
this._slidBallDisabledRenderer.setColor(this.getColor());
this._slidBallDisabledRenderer.setOpacity(this.getOpacity());
},
/**
* Changes the progress direction of slider.
* @param {number} percent
*/
setPercent: function (percent) {
if (percent > 100) {
percent = 100;
}
if (percent < 0) {
percent = 0;
}
this._percent = percent;
var dis = this._barLength * (percent / 100.0);
this._slidBallRenderer.setPosition(cc.p(-this._barLength / 2.0 + dis, 0.0));
if (this._scale9Enabled) {
this._progressBarRenderer.setPreferredSize(cc.size(dis, this._progressBarTextureSize.height));
}
else {
var x = 0, y = 0;
switch (this._progressBarTexType) {
case ccs.TextureResType.plist:
var barNode = this._progressBarRenderer;
if (barNode) {
var to = barNode.getTextureRect().origin;
x = to.x;
y = to.y;
}
break;
default:
break;
}
this._progressBarRenderer.setTextureRect(cc.rect(x, y, this._progressBarTextureSize.width * (percent / 100.0), this._progressBarTextureSize.height));
}
},
onTouchBegan: function (touchPoint) {
var pass = ccs.UIWidget.prototype.onTouchBegan.call(this,touchPoint);
var nsp = this._renderer.convertToNodeSpace(touchPoint);
this.setPercent(this.getPercentWithBallPos(nsp.x));
this.percentChangedEvent();
return pass;
},
onTouchMoved: function (touchPoint) {
var nsp = this._renderer.convertToNodeSpace(touchPoint);
this._slidBallRenderer.setPosition(cc.p(nsp.x, 0));
this.setPercent(this.getPercentWithBallPos(nsp.x));
this.percentChangedEvent();
},
onTouchEnded: function (touchPoint) {
ccs.UIWidget.prototype.onTouchEnded.call(this, touchPoint);
},
onTouchCancelled: function (touchPoint) {
ccs.UIWidget.prototype.onTouchCancelled.call(this, touchPoint);
},
/**
* get percent with ballPos
* @param {cc.Point} px
* @returns {number}
*/
getPercentWithBallPos: function (px) {
return (((px - (-this._barLength / 2.0)) / this._barLength) * 100.0);
},
/**
* add event listener
* @param {Function} selector
* @param {Object} target
*/
addEventListenerSlider: function (selector, target) {
this._sliderEventSelector = selector;
this._sliderEventListener = target;
},
percentChangedEvent: function () {
if (this._sliderEventListener && this._sliderEventSelector) {
this._sliderEventSelector.call(this._sliderEventListener, this, ccs.SliderEventType.percent_changed);
}
},
/**
* Gets the progress direction of slider.
* @returns {number}
*/
getPercent: function () {
return this._percent;
},
onSizeChanged: function () {
this.barRendererScaleChangedWithSize();
this.progressBarRendererScaleChangedWithSize();
},
/**
* override "getContentSize" method of widget.
* @returns {cc.Size}
*/
getContentSize: function () {
var locContentSize = this._barRenderer.getContentSize();
return cc.size(locContentSize.width,locContentSize.height);
},
/**
* override "getContentSize" method of widget.
* @returns {cc.Node}
*/
getVirtualRenderer: function () {
return this._barRenderer;
},
barRendererScaleChangedWithSize: function () {
if (this._ignoreSize) {
this._barRenderer.setScale(1.0);
var locSize = this._barRenderer.getContentSize();
this._size.width = locSize.width;
this._size.height = locSize.height;
this._barLength = locSize.width;
}
else {
this._barLength = this._size.width;
if (this._scale9Enabled) {
this._barRenderer.setPreferredSize(cc.size(this._size.width,this._size.height));
}
else {
var btextureSize = this._barRenderer.getContentSize();
if (btextureSize.width <= 0.0 || btextureSize.height <= 0.0) {
this._barRenderer.setScale(1.0);
return;
}
var bscaleX = this._size.width / btextureSize.width;
var bscaleY = this._size.height / btextureSize.height;
this._barRenderer.setScaleX(bscaleX);
this._barRenderer.setScaleY(bscaleY);
}
}
this.setPercent(this._percent);
},
progressBarRendererScaleChangedWithSize: function () {
if (this._ignoreSize) {
if (!this._scale9Enabled) {
var ptextureSize = this._progressBarTextureSize;
var pscaleX = this._size.width / ptextureSize.width;
var pscaleY = this._size.height / ptextureSize.height;
this._progressBarRenderer.setScaleX(pscaleX);
this._progressBarRenderer.setScaleY(pscaleY);
}
}
else {
if (this._scale9Enabled) {
this._progressBarRenderer.setPreferredSize(cc.size(this._size.width,this._size.height));
}
else {
var ptextureSize = this._progressBarTextureSize;
if (ptextureSize.width <= 0.0 || ptextureSize.height <= 0.0) {
this._progressBarRenderer.setScale(1.0);
return;
}
var pscaleX = this._size.width / ptextureSize.width;
var pscaleY = this._size.height / ptextureSize.height;
this._progressBarRenderer.setScaleX(pscaleX);
this._progressBarRenderer.setScaleY(pscaleY);
}
}
this._progressBarRenderer.setPosition(cc.p(-this._barLength * 0.5, 0.0));
this.setPercent(this._percent);
},
onPressStateChangedToNormal: function () {
this._slidBallNormalRenderer.setVisible(true);
this._slidBallPressedRenderer.setVisible(false);
this._slidBallDisabledRenderer.setVisible(false);
},
onPressStateChangedToPressed: function () {
this._slidBallNormalRenderer.setVisible(false);
this._slidBallPressedRenderer.setVisible(true);
this._slidBallDisabledRenderer.setVisible(false);
},
onPressStateChangedToDisabled: function () {
this._slidBallNormalRenderer.setVisible(false);
this._slidBallPressedRenderer.setVisible(false);
this._slidBallDisabledRenderer.setVisible(true);
},
getDescription: function () {
return "Slider";
},
createCloneInstance: function () {
return ccs.UISlider.create();
},
copySpecialProperties: function (slider) {
this._prevIgnoreSize = slider._prevIgnoreSize;
this.setScale9Enabled(slider._scale9Enabled);
this.loadBarTexture(slider._textureFile, slider._barTexType);
this.loadProgressBarTexture(slider._progressBarTextureFile, slider._progressBarTexType);
this.loadSlidBallTextureNormal(slider._slidBallNormalTextureFile, slider._ballNTexType);
this.loadSlidBallTexturePressed(slider._slidBallPressedTextureFile, slider._ballPTexType);
this.loadSlidBallTextureDisabled(slider._slidBallDisabledTextureFile, slider._ballDTexType);
this.setPercent(slider.getPercent());
}
});
ccs.UISlider.create = function () {
var uiSlider = new ccs.UISlider();
if (uiSlider && uiSlider.init()) {
return uiSlider;
}
return null;
};
|
kaikai2/ShadowWalker
|
Cocos2d-html5-v2.2.1/extensions/CocoStudio/GUI/UIWidgets/UISlider.js
|
JavaScript
|
gpl-3.0
| 20,636 |
/**
* Use the elem given as a parameter to display the range. Does not change the elem, only its content
* calling destroy() will give the elem as it was at the begining
* @param elem the elem in which the input will be inserted
* @param an array of nodes [{value: "...", id: n, ?children: []}]
*/
function Tree(elem, tree) {
var parent = document.createElement('ul');
parent.classList.add('tree-root');
var that = this;
var treeBackup = tree;
tree = tree.children;
var onChangeEvent = function() {};
this.init = function() {
for(var i = 0; i < tree.length; ++i) {
parent.appendChild(that.createSubTree(tree[i]));
}
elem.appendChild(parent);
};
this.destroy = function() {
parent.parentNode.removeChild(parent);
};
/**
* takes a node and gen an element that contains it
*/
this.createSubTree = function(node) {
return (function() {
var elem = document.createElement('li');
var name = document.createElement('div');
node.open = false;
elem.classList.add('tree-node');
name.classList.add('tree-value');
name.innerHTML = node.value;
elem.appendChild(name);
if(node.children) {
var children = document.createElement('ul');
children.classList.add('tree-children');
for(var i = 0; i < node.children.length; ++i) {
children.appendChild(that.createSubTree(node.children[i]));
}
elem.appendChild(children);
}
node.select = function() {
$(name).css('background', 'hsl(180, 60%, 30%)');
$(name).css('color', 'hsl(0, 0%, 90%)');
$(children).slideDown(200);
node.open = true;
};
node.unselect = function() {
$(children).slideUp(200);
$(name).css('color', 'hsl(0, 0%, 0%)');
$(name).css('background', 'hsl(180, 10%, 80%)');
node.open = false;
};
$(children).slideUp(0);
name.addEventListener('click', function() {
if(node.open) {
node.unselect();
}
else {
node.select();
}
onChangeEvent(that.getTree());
});
name.addEventListener("mouseover", function() {
if(!node.open) {
$(name).css('background', 'hsl(180, 10%, 80%)');
}
//$(elem).find('.tree-children > .tree-node > .tree-value').css('background', 'hsl(180, 60%, 15%)');
});
name.addEventListener('mouseout', function() {
if(!node.open) {
$(name).css('background', 'hsl(180, 10%, 85%)');
}
//$(elem).find('.tree-children > .tree-node > .tree-value').css('background', 'hsl(180, 60%, 30%)');
});
return elem;
})();
};
this.getTree = function() {
var nodes = [];
var oneSelected = false;
for(var i = 0; i < tree.length; ++i) {
if(tree[i].open) {
oneSelected = true;
break;
}
}
for(var i = 0; i < tree.length; ++i) {
if(tree[i].open || !oneSelected) {
nodes.push(that.getNode(tree[i], !oneSelected));
}
}
return {
id: treeBackup.id,
children: nodes
};
};
this.getNode = function(node, force) {
if(!node.children) {
return {
id: node.id
};
}
if(force) { // add the node no matter what
var nodes = [];
for(var i = 0; i < node.children.length; ++i) {
nodes.push(that.getNode(node.children[i], true));
}
return {
id: node.id,
children: nodes
};
}
else {
var nodes = [];
var oneSelected = false;
for(var i = 0; i < node.children.length; ++i) {
if(node.children[i].open) {
oneSelected = true;
break;
}
}
for(var i = 0; i < node.children.length; ++i) {
if(node.children[i].open || !oneSelected) {
nodes.push(that.getNode(node.children[i], !oneSelected));
}
}
return {
id: node.id,
children: nodes
};
}
};
this.selectTree = function(t, equivalentNode) {
if(!equivalentNode) {
equivalentNode = treeBackup;
}
if(!t.children) {
equivalentNode.select();
}
else {
// check if all the children are selected. If yes, do not print it
if(t.children.length === equivalentNode.children.length) {
return;
}
var j = 0;
for(var i = 0; i < t.children.length; ++i) {
while(t.children[i].id !== equivalentNode.children[j].id && j < equivalentNode.children.length) {
++j;
}
if(t.children[i].id === equivalentNode.children[j].id) {
equivalentNode.children[j].select();
that.selectTree(t.children[i], equivalentNode.children[j]);
}
}
}
};
this.onChange = function(callback) {
onChangeEvent = callback;
callback(that.getTree());
};
}
|
gaelfoppolo/locomotor
|
resources/scripts/types/tree.js
|
JavaScript
|
gpl-3.0
| 4,437 |
var searchData=
[
['bedtargettemp',['bedTargetTemp',['../class_temperature_private.html#a7efbf4904d5577226627803e7d12cb9e',1,'TemperaturePrivate']]],
['bedtargettemperature',['bedTargetTemperature',['../class_temperature.html#ab9bee6e2f30f262336122cc6b9f9437e',1,'Temperature::bedTargetTemperature()'],['../class_temperature.html#a5abe728615cc1f4a5e6e71b4d2ce5bfb',1,'Temperature::bedTargetTemperature() const']]],
['bedtargettemperaturechanged',['bedTargetTemperatureChanged',['../class_temperature.html#a4de0d105369f43f95a9c03320e26c270',1,'Temperature']]],
['bedtemp',['bedTemp',['../class_temperature_private.html#a8b4f1869aba07203fa5df329e32b8545',1,'TemperaturePrivate']]],
['bedtemperature',['bedTemperature',['../class_temperature.html#a6a57de8fa997f4abc0d954c26b991112',1,'Temperature::bedTemperature()'],['../class_temperature.html#a25180adef1c3265e512e29b43e910d47',1,'Temperature::bedTemperature() const']]],
['bedtemperaturechanged',['bedTemperatureChanged',['../class_temperature.html#a8bf9b247e9ff8423b391e04f1824dcdd',1,'Temperature']]],
['busy',['BUSY',['../class_at_core.html#a20cf87d39ee4ab339964f2a20a0bb326a14f4e23946a6fe036bae108aca395738',1,'AtCore']]]
];
|
lays147/WebAtelier
|
atelier/static/atcore_doc/search/all_2.js
|
JavaScript
|
gpl-3.0
| 1,193 |
const mc4wp = window.mc4wp || {}
const forms = require('./forms/forms.js')
require('./forms/conditional-elements.js')
function trigger (event, args) {
forms.trigger(args[0].id + '.' + event, args)
forms.trigger(event, args)
}
function bind (evtName, cb) {
document.addEventListener(evtName, evt => {
if (!evt.target) {
return
}
const el = evt.target
let fireEvent = false
if (typeof el.className === 'string') {
fireEvent = el.className.indexOf('mc4wp-form') > -1
}
if (!fireEvent && typeof el.matches === 'function') {
fireEvent = el.matches('.mc4wp-form *')
}
if (fireEvent) {
cb.call(evt, evt)
}
}, true)
}
bind('submit', (event) => {
const form = forms.getByElement(event.target)
if (!event.defaultPrevented) {
forms.trigger(form.id + '.submit', [form, event])
}
if (!event.defaultPrevented) {
forms.trigger('submit', [form, event])
}
})
bind('focus', (event) => {
const form = forms.getByElement(event.target)
if (!form.started) {
trigger('started', [form, event])
form.started = true
}
})
bind('change', (event) => {
const form = forms.getByElement(event.target)
trigger('change', [form, event])
})
// register early listeners
if (mc4wp.listeners) {
const listeners = mc4wp.listeners
for (let i = 0; i < listeners.length; i++) {
forms.on(listeners[i].event, listeners[i].callback)
}
// delete temp listeners array, so we don't bind twice
delete mc4wp.listeners
}
// expose forms object
mc4wp.forms = forms
// expose mc4wp object globally
window.mc4wp = mc4wp
|
ibericode/mailchimp-for-wordpress
|
assets/src/js/forms.js
|
JavaScript
|
gpl-3.0
| 1,600 |
// Animation
jQuery('#prenom').animate({opacity: 1},{duration: 300}).animate({top: "-=15px"},{duration: 800});
jQuery('#nom').animate({opacity: 1},{duration: 300}).animate({top: "+=15px"},{duration: 800});
jQuery('#two-colors').delay(1300).animate({opacity: 1},{duration: 800});
|
Uncanny-Nantes/accueil
|
js/accueil.js
|
JavaScript
|
gpl-3.0
| 280 |
'use strict';
(function(){
angular.module('factories.side-menu', [])
.factory('sideMenuFactory', function(
$mdSidenav,
$timeout,
path
){
var scope = null;
var componentId = 'side-menu';
var paths = path.getPaths();
var sideMenuItems = [];
var getSideMenuItems = function(){
return sideMenuItems;
};
var setSideMenuItems = function(){
Object.keys(paths).map(function(key){
if(paths[key].sideMenu){
sideMenuItems.push(paths[key]);
}
});
};
/**
* Supplies a function that will continue to operate until the
* time is up.
*/
var debounce = function(func, wait){
var timer;
return function debounced() {
var context = scope,
args = Array.prototype.slice.call(arguments);
$timeout.cancel(timer);
timer = $timeout(function() {
timer = undefined;
func.apply(context, args);
}, wait || 10);
};
};
/**
* Build handler to open/close a SideNav; when animation finishes
* report completion in console
*/
var buildDelayedToggler = function(navID){
return debounce(function(){
$mdSidenav(navID)
.toggle()
.then(function () {
console.log('toggle ' + navID + ' is done');
});
}, 200);
};
var toggle = buildDelayedToggler(componentId);
var getId = function(){
return componentId;
};
var setScope = function(sideMenuScope){
scope = sideMenuScope;
};
var factory = {
setScope: setScope,
toggle: toggle,
getId: getId,
getSideMenuItems: getSideMenuItems
};
setSideMenuItems();
return factory;
});
})();
|
betorobson/angular-material-app
|
src/directives/side-menu/side-menu-factory.js
|
JavaScript
|
gpl-3.0
| 1,584 |
/*******************************************************************************
uBlock Origin - a browser extension to block requests.
Copyright (C) 2014-2106 The uBlock Origin authors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see {http://www.gnu.org/licenses/}.
Home: https://github.com/gorhill/uBlock
*/
/* jshint esnext: true, bitwise: false */
/* global punycode */
// For background page
/******************************************************************************/
(function() {
'use strict';
/******************************************************************************/
const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
const {Services} = Cu.import('resource://gre/modules/Services.jsm', null);
/******************************************************************************/
var vAPI = self.vAPI = self.vAPI || {};
vAPI.firefox = true;
vAPI.fennec = Services.appinfo.ID === '{aa3c5121-dab2-40e2-81ca-7ea25febc110}';
vAPI.thunderbird = Services.appinfo.ID === '{3550f703-e582-4d05-9a08-453d09bdfdc6}';
/******************************************************************************/
var deferUntil = function(testFn, mainFn, details) {
if ( typeof details !== 'object' ) {
details = {};
}
var now = 0;
var next = details.next || 200;
var until = details.until || 2000;
var check = function() {
if ( testFn() === true || now >= until ) {
mainFn();
return;
}
now += next;
vAPI.setTimeout(check, next);
};
if ( 'sync' in details && details.sync === true ) {
check();
} else {
vAPI.setTimeout(check, 1);
}
};
/******************************************************************************/
vAPI.app = {
name: 'uBlock Origin',
version: location.hash.slice(1)
};
/******************************************************************************/
vAPI.app.restart = function() {
// Listening in bootstrap.js
Cc['@mozilla.org/childprocessmessagemanager;1']
.getService(Ci.nsIMessageSender)
.sendAsyncMessage(location.host + '-restart');
};
/******************************************************************************/
// Set default preferences for user to find in about:config
vAPI.localStorage.setDefaultBool('forceLegacyToolbarButton', false);
/******************************************************************************/
// List of things that needs to be destroyed when disabling the extension
// Only functions should be added to it
var cleanupTasks = [];
// This must be updated manually, every time a new task is added/removed
var expectedNumberOfCleanups = 9;
window.addEventListener('unload', function() {
if ( typeof vAPI.app.onShutdown === 'function' ) {
vAPI.app.onShutdown();
}
// IMPORTANT: cleanup tasks must be executed using LIFO order.
var i = cleanupTasks.length;
while ( i-- ) {
cleanupTasks[i]();
}
if ( cleanupTasks.length < expectedNumberOfCleanups ) {
console.error(
'uBlock> Cleanup tasks performed: %s (out of %s)',
cleanupTasks.length,
expectedNumberOfCleanups
);
}
// frameModule needs to be cleared too
var frameModuleURL = vAPI.getURL('frameModule.js');
var frameModule = {};
// https://github.com/gorhill/uBlock/issues/1004
// For whatever reason, `Cu.import` can throw -- at least this was
// reported as happening for Pale Moon 25.8.
try {
Cu.import(frameModuleURL, frameModule);
frameModule.contentObserver.unregister();
Cu.unload(frameModuleURL);
} catch (ex) {
}
});
/******************************************************************************/
// For now, only booleans.
vAPI.browserSettings = {
originalValues: {},
rememberOriginalValue: function(path, setting) {
var key = path + '.' + setting;
if ( this.originalValues.hasOwnProperty(key) ) {
return;
}
var hasUserValue;
var branch = Services.prefs.getBranch(path + '.');
try {
hasUserValue = branch.prefHasUserValue(setting);
} catch (ex) {
}
if ( hasUserValue !== undefined ) {
this.originalValues[key] = hasUserValue ? this.getValue(path, setting) : undefined;
}
},
clear: function(path, setting) {
var key = path + '.' + setting;
// Value was not overriden -- nothing to restore
if ( this.originalValues.hasOwnProperty(key) === false ) {
return;
}
var value = this.originalValues[key];
// https://github.com/gorhill/uBlock/issues/292#issuecomment-109621979
// Forget the value immediately, it may change outside of
// uBlock control.
delete this.originalValues[key];
// Original value was a default one
if ( value === undefined ) {
try {
Services.prefs.getBranch(path + '.').clearUserPref(setting);
} catch (ex) {
}
return;
}
// Reset to original value
this.setValue(path, setting, value);
},
getValue: function(path, setting) {
var branch = Services.prefs.getBranch(path + '.');
var getMethod;
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIPrefBranch#getPrefType%28%29
switch ( branch.getPrefType(setting) ) {
case 64: // PREF_INT
getMethod = 'getIntPref';
break;
case 128: // PREF_BOOL
getMethod = 'getBoolPref';
break;
default: // not supported
return;
}
try {
return branch[getMethod](setting);
} catch (ex) {
}
},
setValue: function(path, setting, value) {
var setMethod;
switch ( typeof value ) {
case 'number':
setMethod = 'setIntPref';
break;
case 'boolean':
setMethod = 'setBoolPref';
break;
default: // not supported
return;
}
try {
Services.prefs.getBranch(path + '.')[setMethod](setting, value);
} catch (ex) {
}
},
set: function(details) {
var settingVal;
var prefName, prefVal;
for ( var setting in details ) {
if ( details.hasOwnProperty(setting) === false ) {
continue;
}
settingVal = !!details[setting];
switch ( setting ) {
case 'prefetching':
this.rememberOriginalValue('network', 'prefetch-next');
// http://betanews.com/2015/08/15/firefox-stealthily-loads-webpages-when-you-hover-over-links-heres-how-to-stop-it/
// https://bugzilla.mozilla.org/show_bug.cgi?id=814169
// Sigh.
this.rememberOriginalValue('network.http', 'speculative-parallel-limit');
// https://github.com/gorhill/uBlock/issues/292
// "true" means "do not disable", i.e. leave entry alone
if ( settingVal ) {
this.clear('network', 'prefetch-next');
this.clear('network.http', 'speculative-parallel-limit');
} else {
this.setValue('network', 'prefetch-next', false);
this.setValue('network.http', 'speculative-parallel-limit', 0);
}
break;
case 'hyperlinkAuditing':
this.rememberOriginalValue('browser', 'send_pings');
this.rememberOriginalValue('beacon', 'enabled');
// https://github.com/gorhill/uBlock/issues/292
// "true" means "do not disable", i.e. leave entry alone
if ( settingVal ) {
this.clear('browser', 'send_pings');
this.clear('beacon', 'enabled');
} else {
this.setValue('browser', 'send_pings', false);
this.setValue('beacon', 'enabled', false);
}
break;
// https://github.com/gorhill/uBlock/issues/894
// Do not disable completely WebRTC if it can be avoided. FF42+
// has a `media.peerconnection.ice.default_address_only` pref which
// purpose is to prevent local IP address leakage.
case 'webrtcIPAddress':
if ( this.getValue('media.peerconnection', 'ice.default_address_only') !== undefined ) {
prefName = 'ice.default_address_only';
prefVal = true;
} else {
prefName = 'enabled';
prefVal = false;
}
this.rememberOriginalValue('media.peerconnection', prefName);
if ( settingVal ) {
this.clear('media.peerconnection', prefName);
} else {
this.setValue('media.peerconnection', prefName, prefVal);
}
break;
default:
break;
}
}
},
restoreAll: function() {
var pos;
for ( var key in this.originalValues ) {
if ( this.originalValues.hasOwnProperty(key) === false ) {
continue;
}
pos = key.lastIndexOf('.');
this.clear(key.slice(0, pos), key.slice(pos + 1));
}
}
};
cleanupTasks.push(vAPI.browserSettings.restoreAll.bind(vAPI.browserSettings));
/******************************************************************************/
// API matches that of chrome.storage.local:
// https://developer.chrome.com/extensions/storage
vAPI.storage = (function() {
var db = null;
var vacuumTimer = null;
var close = function() {
if ( vacuumTimer !== null ) {
clearTimeout(vacuumTimer);
vacuumTimer = null;
}
if ( db === null ) {
return;
}
db.asyncClose();
db = null;
};
var open = function() {
if ( db !== null ) {
return db;
}
// Create path
var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
path.append('extension-data');
if ( !path.exists() ) {
path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
}
if ( !path.isDirectory() ) {
throw Error('Should be a directory...');
}
path.append(location.host + '.sqlite');
// Open database
try {
db = Services.storage.openDatabase(path);
if ( db.connectionReady === false ) {
db.asyncClose();
db = null;
}
} catch (ex) {
}
if ( db === null ) {
return null;
}
// Database was opened, register cleanup task
cleanupTasks.push(close);
// Setup database
db.createAsyncStatement('CREATE TABLE IF NOT EXISTS "settings" ("name" TEXT PRIMARY KEY NOT NULL, "value" TEXT);')
.executeAsync();
if ( vacuum !== null ) {
vacuumTimer = vAPI.setTimeout(vacuum, 60000);
}
return db;
};
// https://developer.mozilla.org/en-US/docs/Storage/Performance#Vacuuming_and_zero-fill
// Vacuum only once, and only while idle
var vacuum = function() {
vacuumTimer = null;
if ( db === null ) {
return;
}
var idleSvc = Cc['@mozilla.org/widget/idleservice;1']
.getService(Ci.nsIIdleService);
if ( idleSvc.idleTime < 60000 ) {
vacuumTimer = vAPI.setTimeout(vacuum, 60000);
return;
}
db.createAsyncStatement('VACUUM').executeAsync();
vacuum = null;
};
// Execute a query
var runStatement = function(stmt, callback) {
var result = {};
stmt.executeAsync({
handleResult: function(rows) {
if ( !rows || typeof callback !== 'function' ) {
return;
}
var row;
while ( (row = rows.getNextRow()) ) {
// we assume that there will be two columns, since we're
// using it only for preferences
result[row.getResultByIndex(0)] = row.getResultByIndex(1);
}
},
handleCompletion: function(reason) {
if ( typeof callback === 'function' && reason === 0 ) {
callback(result);
}
result = null;
},
handleError: function(error) {
console.error('SQLite error ', error.result, error.message);
// Caller expects an answer regardless of failure.
if ( typeof callback === 'function' ) {
callback(null);
}
result = null;
}
});
};
var bindNames = function(stmt, names) {
if ( Array.isArray(names) === false || names.length === 0 ) {
return;
}
var params = stmt.newBindingParamsArray();
var i = names.length, bp;
while ( i-- ) {
bp = params.newBindingParams();
bp.bindByName('name', names[i]);
params.addParams(bp);
}
stmt.bindParameters(params);
};
var clear = function(callback) {
if ( open() === null ) {
if ( typeof callback === 'function' ) {
callback();
}
return;
}
runStatement(db.createAsyncStatement('DELETE FROM "settings";'), callback);
};
var getBytesInUse = function(keys, callback) {
if ( typeof callback !== 'function' ) {
return;
}
if ( open() === null ) {
callback(0);
return;
}
var stmt;
if ( Array.isArray(keys) ) {
stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings" WHERE "name" = :name');
bindNames(keys);
} else {
stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings"');
}
runStatement(stmt, function(result) {
callback(result.size);
});
};
var read = function(details, callback) {
if ( typeof callback !== 'function' ) {
return;
}
var prepareResult = function(result) {
var key;
for ( key in result ) {
if ( result.hasOwnProperty(key) === false ) {
continue;
}
result[key] = JSON.parse(result[key]);
}
if ( typeof details === 'object' && details !== null ) {
for ( key in details ) {
if ( result.hasOwnProperty(key) === false ) {
result[key] = details[key];
}
}
}
callback(result);
};
if ( open() === null ) {
prepareResult({});
return;
}
var names = [];
if ( details !== null ) {
if ( Array.isArray(details) ) {
names = details;
} else if ( typeof details === 'object' ) {
names = Object.keys(details);
} else {
names = [details.toString()];
}
}
var stmt;
if ( names.length === 0 ) {
stmt = db.createAsyncStatement('SELECT * FROM "settings"');
} else {
stmt = db.createAsyncStatement('SELECT * FROM "settings" WHERE "name" = :name');
bindNames(stmt, names);
}
runStatement(stmt, prepareResult);
};
var remove = function(keys, callback) {
if ( open() === null ) {
if ( typeof callback === 'function' ) {
callback();
}
return;
}
var stmt = db.createAsyncStatement('DELETE FROM "settings" WHERE "name" = :name');
bindNames(stmt, typeof keys === 'string' ? [keys] : keys);
runStatement(stmt, callback);
};
var write = function(details, callback) {
if ( open() === null ) {
if ( typeof callback === 'function' ) {
callback();
}
return;
}
var stmt = db.createAsyncStatement('INSERT OR REPLACE INTO "settings" ("name", "value") VALUES(:name, :value)');
var params = stmt.newBindingParamsArray(), bp;
for ( var key in details ) {
if ( details.hasOwnProperty(key) === false ) {
continue;
}
bp = params.newBindingParams();
bp.bindByName('name', key);
bp.bindByName('value', JSON.stringify(details[key]));
params.addParams(bp);
}
if ( params.length === 0 ) {
return;
}
stmt.bindParameters(params);
runStatement(stmt, callback);
};
// Export API
var api = {
QUOTA_BYTES: 100 * 1024 * 1024,
clear: clear,
get: read,
getBytesInUse: getBytesInUse,
remove: remove,
set: write
};
return api;
})();
/******************************************************************************/
// This must be executed/setup early.
var winWatcher = (function() {
var chromeWindowType = vAPI.thunderbird ? 'mail:3pane' : 'navigator:browser';
var windowToIdMap = new Map();
var windowIdGenerator = 1;
var api = {
onOpenWindow: null,
onCloseWindow: null
};
api.getWindows = function() {
return windowToIdMap.keys();
};
api.idFromWindow = function(win) {
return windowToIdMap.get(win) || 0;
};
api.getCurrentWindow = function() {
return Services.wm.getMostRecentWindow(chromeWindowType) || null;
};
var addWindow = function(win) {
if ( !win || windowToIdMap.has(win) ) {
return;
}
windowToIdMap.set(win, windowIdGenerator++);
if ( typeof api.onOpenWindow === 'function' ) {
api.onOpenWindow(win);
}
};
var removeWindow = function(win) {
if ( !win || windowToIdMap.delete(win) !== true ) {
return;
}
if ( typeof api.onCloseWindow === 'function' ) {
api.onCloseWindow(win);
}
};
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowMediator
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowWatcher
// https://github.com/gorhill/uMatrix/issues/357
// Use nsIWindowMediator for being notified of opened/closed windows.
var listeners = {
onOpenWindow: function(aWindow) {
var win;
try {
win = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
} catch (ex) {
}
addWindow(win);
},
onCloseWindow: function(aWindow) {
var win;
try {
win = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
} catch (ex) {
}
removeWindow(win);
},
observe: function(aSubject, topic) {
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowWatcher#registerNotification%28%29
// "aSubject - the window being opened or closed, sent as an
// "nsISupports which can be ... QueryInterfaced to an
// "nsIDOMWindow."
var win;
try {
win = aSubject.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
} catch (ex) {
}
if ( !win ) { return; }
if ( topic === 'domwindowopened' ) {
addWindow(win);
return;
}
if ( topic === 'domwindowclosed' ) {
removeWindow(win);
return;
}
}
};
(function() {
var winumerator, win;
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowMediator#getEnumerator%28%29
winumerator = Services.wm.getEnumerator(null);
while ( winumerator.hasMoreElements() ) {
win = winumerator.getNext();
if ( !win.closed ) {
windowToIdMap.set(win, windowIdGenerator++);
}
}
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowWatcher#getWindowEnumerator%28%29
winumerator = Services.ww.getWindowEnumerator();
while ( winumerator.hasMoreElements() ) {
win = winumerator.getNext()
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
if ( !win.closed ) {
windowToIdMap.set(win, windowIdGenerator++);
}
}
Services.wm.addListener(listeners);
Services.ww.registerNotification(listeners);
})();
cleanupTasks.push(function() {
Services.wm.removeListener(listeners);
Services.ww.unregisterNotification(listeners);
windowToIdMap.clear();
});
return api;
})();
/******************************************************************************/
var getTabBrowser = (function() {
if ( vAPI.fennec ) {
return function(win) {
return win.BrowserApp || null;
};
}
if ( vAPI.thunderbird ) {
return function(win) {
return win.document.getElementById('tabmail') || null;
};
}
// https://github.com/gorhill/uBlock/issues/1004
// Merely READING the `gBrowser` property causes the issue -- no
// need to even use its returned value... This really should be fixed
// in the browser.
// Meanwhile, the workaround is to check whether the document is
// ready. This is hacky, as the code below has to make assumption
// about the browser's inner working -- specifically that the `gBrowser`
// property should NOT be accessed before the document of the window is
// in its ready state.
return function(win) {
if ( win ) {
var doc = win.document;
if ( doc && doc.readyState === 'complete' ) {
return win.gBrowser || null;
}
}
return null;
};
})();
/******************************************************************************/
var getOwnerWindow = function(target) {
if ( target.ownerDocument ) {
return target.ownerDocument.defaultView;
}
// Fennec
for ( var win of winWatcher.getWindows() ) {
for ( var tab of win.BrowserApp.tabs) {
if ( tab === target || tab.window === target ) {
return win;
}
}
}
return null;
};
/******************************************************************************/
vAPI.isBehindTheSceneTabId = function(tabId) {
return tabId.toString() === '-1';
};
vAPI.noTabId = '-1';
/******************************************************************************/
vAPI.tabs = {};
/******************************************************************************/
vAPI.tabs.registerListeners = function() {
tabWatcher.start();
};
/******************************************************************************/
// Firefox:
// https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Tabbed_browser
//
// browser --> ownerDocument --> defaultView --> gBrowser --> browsers --+
// ^ |
// | |
// +-------------------------------------------------------------------
//
// browser (browser)
// contentTitle
// currentURI
// ownerDocument (XULDocument)
// defaultView (ChromeWindow)
// gBrowser (tabbrowser OR browser)
// browsers (browser)
// selectedBrowser
// selectedTab
// tabs (tab.tabbrowser-tab)
//
// Fennec: (what I figured so far)
//
// tab --> browser windows --> window --> BrowserApp --> tabs --+
// ^ window |
// | |
// +---------------------------------------------------------------+
//
// tab
// browser
// [manual search to go back to tab from list of windows]
vAPI.tabs.get = function(tabId, callback) {
var browser;
if ( tabId === null ) {
browser = tabWatcher.currentBrowser();
tabId = tabWatcher.tabIdFromTarget(browser);
} else {
browser = tabWatcher.browserFromTabId(tabId);
}
// For internal use
if ( typeof callback !== 'function' ) {
return browser;
}
if ( !browser ) {
callback();
return;
}
var win = getOwnerWindow(browser);
var tabBrowser = getTabBrowser(win);
callback({
id: tabId,
index: tabWatcher.indexFromTarget(browser),
windowId: winWatcher.idFromWindow(win),
active: tabBrowser !== null && browser === tabBrowser.selectedBrowser,
url: browser.currentURI.asciiSpec,
title: browser.contentTitle
});
};
/******************************************************************************/
vAPI.tabs.getAll = function(window) {
var win, tab;
var tabs = [];
for ( win of winWatcher.getWindows() ) {
if ( window && window !== win ) {
continue;
}
var tabBrowser = getTabBrowser(win);
if ( tabBrowser === null ) {
continue;
}
// This can happens if a tab-less window is currently opened.
// Example of a tab-less window: one opened from clicking
// "View Page Source".
if ( !tabBrowser.tabs ) {
continue;
}
for ( tab of tabBrowser.tabs ) {
tabs.push(tab);
}
}
return tabs;
};
/******************************************************************************/
// properties of the details object:
// url: 'URL', // the address that will be opened
// tabId: 1, // the tab is used if set, instead of creating a new one
// index: -1, // undefined: end of the list, -1: following tab, or after index
// active: false, // opens the tab in background - true and undefined: foreground
// select: true // if a tab is already opened with that url, then select it instead of opening a new one
vAPI.tabs.open = function(details) {
if ( !details.url ) {
return null;
}
// extension pages
if ( /^[\w-]{2,}:/.test(details.url) === false ) {
details.url = vAPI.getURL(details.url);
}
var tab;
if ( details.select ) {
var URI = Services.io.newURI(details.url, null, null);
for ( tab of this.getAll() ) {
var browser = tabWatcher.browserFromTarget(tab);
// Or simply .equals if we care about the fragment
if ( URI.equalsExceptRef(browser.currentURI) === false ) {
continue;
}
this.select(tab);
// Update URL if fragment is different
if ( URI.equals(browser.currentURI) === false ) {
browser.loadURI(URI.asciiSpec);
}
return;
}
}
if ( details.active === undefined ) {
details.active = true;
}
if ( details.tabId ) {
tab = tabWatcher.browserFromTabId(details.tabId);
if ( tab ) {
tabWatcher.browserFromTarget(tab).loadURI(details.url);
return;
}
}
var win = winWatcher.getCurrentWindow();
var tabBrowser = getTabBrowser(win);
if ( tabBrowser === null ) {
return;
}
if ( vAPI.fennec ) {
tabBrowser.addTab(details.url, {
selected: details.active !== false
});
// Note that it's impossible to move tabs on Fennec, so don't bother
return;
}
// Open in a standalone window
if ( details.popup === true ) {
Services.ww.openWindow(
self,
details.url,
null,
'location=1,menubar=1,personalbar=1,resizable=1,toolbar=1',
null
);
return;
}
if ( vAPI.thunderbird ) {
tabBrowser.openTab('contentTab', {
contentPage: details.url,
background: !details.active
});
// TODO: Should be possible to move tabs on Thunderbird
return;
}
if ( details.index === -1 ) {
details.index = tabBrowser.browsers.indexOf(tabBrowser.selectedBrowser) + 1;
}
tab = tabBrowser.loadOneTab(details.url, { inBackground: !details.active });
if ( details.index !== undefined ) {
tabBrowser.moveTabTo(tab, details.index);
}
};
/******************************************************************************/
// Replace the URL of a tab. Noop if the tab does not exist.
vAPI.tabs.replace = function(tabId, url) {
var targetURL = url;
// extension pages
if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
targetURL = vAPI.getURL(targetURL);
}
var browser = tabWatcher.browserFromTabId(tabId);
if ( browser ) {
browser.loadURI(targetURL);
}
};
/******************************************************************************/
vAPI.tabs._remove = (function() {
if ( vAPI.fennec || vAPI.thunderbird ) {
return function(tab, tabBrowser) {
tabBrowser.closeTab(tab);
};
}
return function(tab, tabBrowser, nuke) {
if ( !tabBrowser ) {
return;
}
if ( tabBrowser.tabs.length === 1 && nuke ) {
getOwnerWindow(tab).close();
} else {
tabBrowser.removeTab(tab);
}
};
})();
/******************************************************************************/
vAPI.tabs.remove = (function() {
var remove = function(tabId, nuke) {
var browser = tabWatcher.browserFromTabId(tabId);
if ( !browser ) {
return;
}
var tab = tabWatcher.tabFromBrowser(browser);
if ( !tab ) {
return;
}
this._remove(tab, getTabBrowser(getOwnerWindow(browser)), nuke);
};
// Do this asynchronously
return function(tabId, nuke) {
vAPI.setTimeout(remove.bind(this, tabId, nuke), 1);
};
})();
/******************************************************************************/
vAPI.tabs.reload = function(tabId) {
var browser = tabWatcher.browserFromTabId(tabId);
if ( !browser ) {
return;
}
browser.webNavigation.reload(Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE);
};
/******************************************************************************/
vAPI.tabs.select = function(tab) {
if ( typeof tab !== 'object' ) {
tab = tabWatcher.tabFromBrowser(tabWatcher.browserFromTabId(tab));
}
if ( !tab ) {
return;
}
var win = getOwnerWindow(tab);
var tabBrowser = getTabBrowser(win);
if ( tabBrowser === null ) {
return;
}
// https://github.com/gorhill/uBlock/issues/470
win.focus();
if ( vAPI.fennec ) {
tabBrowser.selectTab(tab);
} else {
tabBrowser.selectedTab = tab;
}
};
/******************************************************************************/
vAPI.tabs.injectScript = function(tabId, details, callback) {
var browser = tabWatcher.browserFromTabId(tabId);
if ( !browser ) {
return;
}
if ( typeof details.file !== 'string' ) {
return;
}
details.file = vAPI.getURL(details.file);
browser.messageManager.sendAsyncMessage(
location.host + ':broadcast',
JSON.stringify({
broadcast: true,
channelName: 'vAPI',
msg: {
cmd: 'injectScript',
details: details
}
})
);
if ( typeof callback === 'function' ) {
vAPI.setTimeout(callback, 13);
}
};
/******************************************************************************/
var tabWatcher = (function() {
// TODO: find out whether we need a janitor to take care of stale entries.
var browserToTabIdMap = new Map();
var tabIdToBrowserMap = new Map();
var tabIdGenerator = 1;
var indexFromBrowser = function(browser) {
// TODO: Add support for this
if ( vAPI.thunderbird ) {
return -1;
}
var win = getOwnerWindow(browser);
if ( !win ) {
return -1;
}
var tabbrowser = getTabBrowser(win);
if ( tabbrowser === null ) {
return -1;
}
// This can happen, for example, the `view-source:` window, there is
// no tabbrowser object, the browser object sits directly in the
// window.
if ( tabbrowser === browser ) {
return 0;
}
// Fennec
// https://developer.mozilla.org/en-US/Add-ons/Firefox_for_Android/API/BrowserApp
if ( vAPI.fennec ) {
return tabbrowser.tabs.indexOf(tabbrowser.getTabForBrowser(browser));
}
return tabbrowser.browsers.indexOf(browser);
};
var indexFromTarget = function(target) {
return indexFromBrowser(browserFromTarget(target));
};
var tabFromBrowser = function(browser) {
var i = indexFromBrowser(browser);
if ( i === -1 ) {
return null;
}
var win = getOwnerWindow(browser);
if ( !win ) {
return null;
}
var tabbrowser = getTabBrowser(win);
if ( tabbrowser === null ) {
return null;
}
if ( !tabbrowser.tabs || i >= tabbrowser.tabs.length ) {
return null;
}
return tabbrowser.tabs[i];
};
var browserFromTarget = (function() {
if ( vAPI.fennec ) {
return function(target) {
if ( !target ) { return null; }
if ( target.browser ) { // target is a tab
target = target.browser;
}
return target.localName === 'browser' ? target : null;
};
}
if ( vAPI.thunderbird ) {
return function(target) {
if ( !target ) { return null; }
if ( target.mode ) { // target is object with tab info
var browserFunc = target.mode.getBrowser || target.mode.tabType.getBrowser;
if ( browserFunc ) {
return browserFunc.call(target.mode.tabType, target);
}
}
return target.localName === 'browser' ? target : null;
};
}
return function(target) {
if ( !target ) { return null; }
if ( target.linkedPanel ) { // target is a tab
target = target.linkedBrowser;
}
return target.localName === 'browser' ? target : null;
};
})();
var tabIdFromTarget = function(target) {
var browser = browserFromTarget(target);
if ( browser === null ) {
return vAPI.noTabId;
}
var tabId = browserToTabIdMap.get(browser);
if ( tabId === undefined ) {
tabId = '' + tabIdGenerator++;
browserToTabIdMap.set(browser, tabId);
tabIdToBrowserMap.set(tabId, browser);
}
return tabId;
};
var browserFromTabId = function(tabId) {
var browser = tabIdToBrowserMap.get(tabId);
if ( browser === undefined ) {
return null;
}
// Verify that the browser is still live
if ( indexFromBrowser(browser) !== -1 ) {
return browser;
}
removeBrowserEntry(tabId, browser);
return null;
};
var currentBrowser = function() {
var win = winWatcher.getCurrentWindow();
// https://github.com/gorhill/uBlock/issues/399
// getTabBrowser() can return null at browser launch time.
var tabBrowser = getTabBrowser(win);
if ( tabBrowser === null ) {
return null;
}
if ( vAPI.thunderbird ) {
// Directly at startup the first tab may not be initialized
if ( tabBrowser.tabInfo.length === 0 ) {
return null;
}
return tabBrowser.getBrowserForSelectedTab() || null;
}
return browserFromTarget(tabBrowser.selectedTab);
};
var removeBrowserEntry = function(tabId, browser) {
if ( tabId && tabId !== vAPI.noTabId ) {
vAPI.tabs.onClosed(tabId);
delete vAPI.toolbarButton.tabs[tabId];
tabIdToBrowserMap.delete(tabId);
}
if ( browser ) {
browserToTabIdMap.delete(browser);
}
};
var removeTarget = function(target) {
onClose({ target: target });
};
// https://developer.mozilla.org/en-US/docs/Web/Events/TabShow
var onShow = function({target}) {
tabIdFromTarget(target);
};
// https://developer.mozilla.org/en-US/docs/Web/Events/TabClose
var onClose = function({target}) {
// target is tab in Firefox, browser in Fennec
var browser = browserFromTarget(target);
var tabId = browserToTabIdMap.get(browser);
removeBrowserEntry(tabId, browser);
};
// https://developer.mozilla.org/en-US/docs/Web/Events/TabSelect
var onSelect = function({target}) {
vAPI.setIcon(tabIdFromTarget(target), getOwnerWindow(target));
};
var attachToTabBrowser = function(window) {
if ( typeof vAPI.toolbarButton.attachToNewWindow === 'function' ) {
vAPI.toolbarButton.attachToNewWindow(window);
}
var tabBrowser = getTabBrowser(window);
if ( tabBrowser === null ) {
return;
}
var tabContainer;
if ( tabBrowser.deck ) { // Fennec
tabContainer = tabBrowser.deck;
} else if ( tabBrowser.tabContainer ) { // Firefox
tabContainer = tabBrowser.tabContainer;
vAPI.contextMenu.register(window);
}
// https://github.com/gorhill/uBlock/issues/697
// Ignore `TabShow` events: unfortunately the `pending` attribute is
// not set when a tab is opened as a result of session restore -- it is
// set *after* the event is fired in such case.
if ( tabContainer ) {
tabContainer.addEventListener('TabShow', onShow);
tabContainer.addEventListener('TabClose', onClose);
// when new window is opened TabSelect doesn't run on the selected tab?
tabContainer.addEventListener('TabSelect', onSelect);
}
};
// https://github.com/gorhill/uBlock/issues/906
// Ensure the environment is ready before trying to attaching.
var canAttachToTabBrowser = function(window) {
var document = window && window.document;
if ( !document || document.readyState !== 'complete' ) {
return false;
}
// On some platforms, the tab browser isn't immediately available,
// try waiting a bit if this happens.
// https://github.com/gorhill/uBlock/issues/763
// Not getting a tab browser should not prevent from attaching ourself
// to the window.
var tabBrowser = getTabBrowser(window);
if ( tabBrowser === null ) {
return false;
}
var docElement = document.documentElement;
return docElement && docElement.getAttribute('windowtype') === 'navigator:browser';
};
var onWindowLoad = function(win) {
deferUntil(
canAttachToTabBrowser.bind(null, win),
attachToTabBrowser.bind(null, win)
);
};
var onWindowUnload = function(win) {
vAPI.contextMenu.unregister(win);
var tabBrowser = getTabBrowser(win);
if ( tabBrowser === null ) {
return;
}
var tabContainer;
if ( tabBrowser.deck ) { // Fennec
tabContainer = tabBrowser.deck;
} else if ( tabBrowser.tabContainer ) { // Firefox
tabContainer = tabBrowser.tabContainer;
}
if ( tabContainer ) {
tabContainer.removeEventListener('TabShow', onShow);
tabContainer.removeEventListener('TabClose', onClose);
tabContainer.removeEventListener('TabSelect', onSelect);
}
// https://github.com/gorhill/uBlock/issues/574
// To keep in mind: not all windows are tab containers,
// sometimes the window IS the tab.
var tabs;
if ( vAPI.thunderbird ) {
tabs = tabBrowser.tabInfo;
} else if ( tabBrowser.tabs ) {
tabs = tabBrowser.tabs;
} else if ( tabBrowser.localName === 'browser' ) {
tabs = [tabBrowser];
} else {
tabs = [];
}
var browser, tabId;
var tabindex = tabs.length, tab;
while ( tabindex-- ) {
tab = tabs[tabindex];
browser = browserFromTarget(tab);
if ( browser === null ) {
continue;
}
tabId = browserToTabIdMap.get(browser);
if ( tabId !== undefined ) {
removeBrowserEntry(tabId, browser);
tabIdToBrowserMap.delete(tabId);
}
browserToTabIdMap.delete(browser);
}
};
// Initialize map with existing active tabs
var start = function() {
var tabBrowser, tabs, tab;
for ( var win of winWatcher.getWindows() ) {
onWindowLoad(win);
tabBrowser = getTabBrowser(win);
if ( tabBrowser === null ) {
continue;
}
// `tabBrowser.tabs` may not exist (Thunderbird).
tabs = tabBrowser.tabs;
if ( !tabs ) {
continue;
}
for ( tab of tabs ) {
if ( vAPI.fennec || !tab.hasAttribute('pending') ) {
tabIdFromTarget(tab);
}
}
}
winWatcher.onOpenWindow = onWindowLoad;
winWatcher.onCloseWindow = onWindowUnload;
};
var stop = function() {
winWatcher.onOpenWindow = null;
winWatcher.onCloseWindow = null;
for ( var win of winWatcher.getWindows() ) {
onWindowUnload(win);
}
browserToTabIdMap.clear();
tabIdToBrowserMap.clear();
};
cleanupTasks.push(stop);
return {
browsers: function() { return browserToTabIdMap.keys(); },
browserFromTabId: browserFromTabId,
browserFromTarget: browserFromTarget,
currentBrowser: currentBrowser,
indexFromTarget: indexFromTarget,
removeTarget: removeTarget,
start: start,
tabFromBrowser: tabFromBrowser,
tabIdFromTarget: tabIdFromTarget
};
})();
/******************************************************************************/
vAPI.setIcon = function(tabId, iconStatus, badge) {
// If badge is undefined, then setIcon was called from the TabSelect event
var win = badge === undefined
? iconStatus
: winWatcher.getCurrentWindow();
var curTabId;
var tabBrowser = getTabBrowser(win);
if ( tabBrowser !== null ) {
curTabId = tabWatcher.tabIdFromTarget(tabBrowser.selectedTab);
}
var tb = vAPI.toolbarButton;
// from 'TabSelect' event
if ( tabId === undefined ) {
tabId = curTabId;
} else if ( badge !== undefined ) {
tb.tabs[tabId] = { badge: badge, img: iconStatus === 'on' };
}
if ( curTabId && tabId === curTabId ) {
tb.updateState(win, tabId);
vAPI.contextMenu.onMustUpdate(tabId);
}
};
/******************************************************************************/
vAPI.messaging = {
get globalMessageManager() {
return Cc['@mozilla.org/globalmessagemanager;1']
.getService(Ci.nsIMessageListenerManager);
},
frameScriptURL: vAPI.getURL('frameScript.js'),
listeners: {},
defaultHandler: null,
NOOPFUNC: function(){},
UNHANDLED: 'vAPI.messaging.notHandled'
};
/******************************************************************************/
vAPI.messaging.listen = function(listenerName, callback) {
this.listeners[listenerName] = callback;
};
/******************************************************************************/
vAPI.messaging.onMessage = (function() {
var messaging = vAPI.messaging;
var toAuxPending = {};
// Use a wrapper to avoid closure and to allow reuse.
var CallbackWrapper = function(messageManager, listenerId, channelName, auxProcessId, timeout) {
this.callback = this.proxy.bind(this); // bind once
this.init(messageManager, listenerId, channelName, auxProcessId, timeout);
};
CallbackWrapper.prototype.init = function(messageManager, listenerId, channelName, auxProcessId, timeout) {
this.messageManager = messageManager;
this.listenerId = listenerId;
this.channelName = channelName;
this.auxProcessId = auxProcessId;
this.timerId = timeout !== undefined ?
vAPI.setTimeout(this.callback, timeout) :
null;
return this;
};
CallbackWrapper.prototype.proxy = function(response) {
if ( this.timerId !== null ) {
clearTimeout(this.timerId);
delete toAuxPending[this.timerId];
this.timerId = null;
}
var message = JSON.stringify({
auxProcessId: this.auxProcessId,
channelName: this.channelName,
msg: response !== undefined ? response : null
});
if ( this.messageManager.sendAsyncMessage ) {
this.messageManager.sendAsyncMessage(this.listenerId, message);
} else {
this.messageManager.broadcastAsyncMessage(this.listenerId, message);
}
// Mark for reuse
this.messageManager =
this.listenerId =
this.channelName =
this.auxProcessId = null;
callbackWrapperJunkyard.push(this);
};
var callbackWrapperJunkyard = [];
var callbackWrapperFactory = function(messageManager, listenerId, channelName, auxProcessId, timeout) {
var wrapper = callbackWrapperJunkyard.pop();
if ( wrapper ) {
return wrapper.init(messageManager, listenerId, channelName, auxProcessId, timeout);
}
return new CallbackWrapper(messageManager, listenerId, channelName, auxProcessId, timeout);
};
// "Auxiliary process": any process other than main process.
var toAux = function(target, details) {
var messageManagerFrom = target.messageManager;
// Message came from a popup, and its message manager is not usable.
// So instead we broadcast to the parent window.
if ( !messageManagerFrom ) {
messageManagerFrom = getOwnerWindow(
target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
).messageManager;
}
var wrapper;
if ( details.auxProcessId !== undefined ) {
var channelNameRaw = details.channelName;
var pos = channelNameRaw.indexOf('|');
wrapper = callbackWrapperFactory(
messageManagerFrom,
channelNameRaw.slice(0, pos),
channelNameRaw.slice(pos + 1),
details.auxProcessId,
1023
);
}
var messageManagerTo = null;
var browser = tabWatcher.browserFromTabId(details.toTabId);
if ( browser !== null && browser.messageManager ) {
messageManagerTo = browser.messageManager;
}
if ( messageManagerTo === null ) {
if ( wrapper !== undefined ) {
wrapper.callback();
}
return;
}
// As per HTML5, timer id is always an integer, thus suitable to be used
// as a key, and which value is safe to use across process boundaries.
if ( wrapper !== undefined ) {
toAuxPending[wrapper.timerId] = wrapper;
}
var targetId = location.host + ':broadcast';
var payload = JSON.stringify({
mainProcessId: wrapper && wrapper.timerId,
channelName: details.toChannel,
msg: details.msg
});
if ( messageManagerTo.sendAsyncMessage ) {
messageManagerTo.sendAsyncMessage(targetId, payload);
} else {
messageManagerTo.broadcastAsyncMessage(targetId, payload);
}
};
var toAuxResponse = function(details) {
var mainProcessId = details.mainProcessId;
if ( mainProcessId === undefined ) {
return;
}
if ( toAuxPending.hasOwnProperty(mainProcessId) === false ) {
return;
}
var wrapper = toAuxPending[mainProcessId];
delete toAuxPending[mainProcessId];
wrapper.callback(details.msg);
};
return function({target, data}) {
// Auxiliary process to auxiliary process
if ( data.toTabId !== undefined ) {
toAux(target, data);
return;
}
// Auxiliary process to auxiliary process: response
if ( data.mainProcessId !== undefined ) {
toAuxResponse(data);
return;
}
// Auxiliary process to main process
var messageManager = target.messageManager;
// Message came from a popup, and its message manager is not usable.
// So instead we broadcast to the parent window.
if ( !messageManager ) {
messageManager = getOwnerWindow(
target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
).messageManager;
}
var channelNameRaw = data.channelName;
var pos = channelNameRaw.indexOf('|');
var channelName = channelNameRaw.slice(pos + 1);
// Auxiliary process to main process: prepare response
var callback = messaging.NOOPFUNC;
if ( data.auxProcessId !== undefined ) {
callback = callbackWrapperFactory(
messageManager,
channelNameRaw.slice(0, pos),
channelName,
data.auxProcessId
).callback;
}
var sender = {
tab: {
id: tabWatcher.tabIdFromTarget(target)
}
};
// Auxiliary process to main process: specific handler
var r = messaging.UNHANDLED;
var listener = messaging.listeners[channelName];
if ( typeof listener === 'function' ) {
r = listener(data.msg, sender, callback);
}
if ( r !== messaging.UNHANDLED ) {
return;
}
// Auxiliary process to main process: default handler
r = messaging.defaultHandler(data.msg, sender, callback);
if ( r !== messaging.UNHANDLED ) {
return;
}
// Auxiliary process to main process: no handler
console.error('uBlock> messaging > unknown request: %o', data);
// Need to callback anyways in case caller expected an answer, or
// else there is a memory leak on caller's side
callback();
};
})();
/******************************************************************************/
vAPI.messaging.setup = function(defaultHandler) {
// Already setup?
if ( this.defaultHandler !== null ) {
return;
}
if ( typeof defaultHandler !== 'function' ) {
defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
}
this.defaultHandler = defaultHandler;
this.globalMessageManager.addMessageListener(
location.host + ':background',
this.onMessage
);
this.globalMessageManager.loadFrameScript(this.frameScriptURL, true);
cleanupTasks.push(function() {
var gmm = vAPI.messaging.globalMessageManager;
gmm.broadcastAsyncMessage(
location.host + ':broadcast',
JSON.stringify({
broadcast: true,
channelName: 'vAPI',
msg: { cmd: 'shutdownSandbox' }
})
);
gmm.removeDelayedFrameScript(vAPI.messaging.frameScriptURL);
gmm.removeMessageListener(
location.host + ':background',
vAPI.messaging.onMessage
);
vAPI.messaging.defaultHandler = null;
});
};
/******************************************************************************/
vAPI.messaging.broadcast = function(message) {
this.globalMessageManager.broadcastAsyncMessage(
location.host + ':broadcast',
JSON.stringify({broadcast: true, msg: message})
);
};
/******************************************************************************/
/******************************************************************************/
// Synchronous messaging: Firefox allows this. Chromium does not allow this.
// Sometimes there is no way around synchronous messaging, as long as:
// - the code at the other end execute fast and return quickly.
// - it's not abused.
// Original rationale is <https://github.com/gorhill/uBlock/issues/756>.
// Synchronous messaging is a good solution for this case because:
// - It's done only *once* per page load. (Keep in mind there is already a
// sync message sent for each single network request on a page and it's not
// an issue, because the code executed is trivial, which is the key -- see
// shouldLoadListener below).
// - The code at the other end is fast.
// Though vAPI.rpcReceiver was brought forth because of this one case, I
// generalized the concept for whatever future need for synchronous messaging
// which might arise.
// https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox/Message_Manager/Message_manager_overview#Content_frame_message_manager
vAPI.rpcReceiver = (function() {
var calls = Object.create(null);
var childProcessMessageName = location.host + ':child-process-message';
var onChildProcessMessage = function(ev) {
var msg = ev.data;
if ( !msg ) { return; }
var fn = calls[msg.fnName];
if ( typeof fn === 'function' ) {
return fn(msg);
}
};
var ppmm = Services.ppmm;
if ( !ppmm ) {
ppmm = Cc['@mozilla.org/parentprocessmessagemanager;1'];
if ( ppmm ) {
ppmm = ppmm.getService(Ci.nsIMessageListenerManager);
}
}
if ( ppmm ) {
ppmm.addMessageListener(
childProcessMessageName,
onChildProcessMessage
);
}
cleanupTasks.push(function() {
if ( ppmm ) {
ppmm.removeMessageListener(
childProcessMessageName,
onChildProcessMessage
);
}
});
return calls;
})();
/******************************************************************************/
/******************************************************************************/
var httpObserver = {
classDescription: 'net-channel-event-sinks for ' + location.host,
classID: Components.ID('{dc8d6319-5f6e-4438-999e-53722db99e84}'),
contractID: '@' + location.host + '/net-channel-event-sinks;1',
REQDATAKEY: location.host + 'reqdata',
ABORT: Components.results.NS_BINDING_ABORTED,
ACCEPT: Components.results.NS_SUCCEEDED,
// Request types:
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants
typeMap: {
1: 'other',
2: 'script',
3: 'image',
4: 'stylesheet',
5: 'object',
6: 'main_frame',
7: 'sub_frame',
10: 'ping',
11: 'xmlhttprequest',
12: 'object',
14: 'font',
15: 'media',
16: 'websocket',
19: 'beacon',
21: 'image'
},
onBeforeRequest: function(){},
onBeforeRequestTypes: null,
onHeadersReceived: function(){},
onHeadersReceivedTypes: null,
get componentRegistrar() {
return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
},
get categoryManager() {
return Cc['@mozilla.org/categorymanager;1']
.getService(Ci.nsICategoryManager);
},
QueryInterface: (function() {
var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
return XPCOMUtils.generateQI([
Ci.nsIFactory,
Ci.nsIObserver,
Ci.nsIChannelEventSink,
Ci.nsISupportsWeakReference
]);
})(),
createInstance: function(outer, iid) {
if ( outer ) {
throw Components.results.NS_ERROR_NO_AGGREGATION;
}
return this.QueryInterface(iid);
},
register: function() {
this.pendingRingBufferInit();
Services.obs.addObserver(this, 'http-on-modify-request', true);
Services.obs.addObserver(this, 'http-on-examine-response', true);
// Guard against stale instances not having been unregistered
if ( this.componentRegistrar.isCIDRegistered(this.classID) ) {
try {
this.componentRegistrar.unregisterFactory(this.classID, Components.manager.getClassObject(this.classID, Ci.nsIFactory));
} catch (ex) {
console.error('uBlock> httpObserver > unable to unregister stale instance: ', ex);
}
}
this.componentRegistrar.registerFactory(
this.classID,
this.classDescription,
this.contractID,
this
);
this.categoryManager.addCategoryEntry(
'net-channel-event-sinks',
this.contractID,
this.contractID,
false,
true
);
},
unregister: function() {
Services.obs.removeObserver(this, 'http-on-modify-request');
Services.obs.removeObserver(this, 'http-on-examine-response');
this.componentRegistrar.unregisterFactory(this.classID, this);
this.categoryManager.deleteCategoryEntry(
'net-channel-event-sinks',
this.contractID,
false
);
},
PendingRequest: function() {
this.frameId = 0;
this.parentFrameId = 0;
this.rawtype = 0;
this.tabId = 0;
this._key = ''; // key is url, from URI.spec
},
// If all work fine, this map should not grow indefinitely. It can have
// stale items in it, but these will be taken care of when entries in
// the ring buffer are overwritten.
pendingURLToIndex: new Map(),
pendingWritePointer: 0,
pendingRingBuffer: new Array(32),
pendingRingBufferInit: function() {
// Use and reuse pre-allocated PendingRequest objects = less memory
// churning.
var i = this.pendingRingBuffer.length;
while ( i-- ) {
this.pendingRingBuffer[i] = new this.PendingRequest();
}
},
// Pending request ring buffer:
// +-------+-------+-------+-------+-------+-------+-------
// |0 |1 |2 |3 |4 |5 |...
// +-------+-------+-------+-------+-------+-------+-------
//
// URL to ring buffer index map:
// { k = URL, s = ring buffer indices }
//
// s is a string which character codes map to ring buffer indices -- for
// when the same URL is received multiple times by shouldLoadListener()
// before the existing one is serviced by the network request observer.
// I believe the use of a string in lieu of an array reduces memory
// churning.
createPendingRequest: function(url) {
var bucket;
var i = this.pendingWritePointer;
this.pendingWritePointer = i + 1 & 31;
var preq = this.pendingRingBuffer[i];
var si = String.fromCharCode(i);
// Cleanup unserviced pending request
if ( preq._key !== '' ) {
bucket = this.pendingURLToIndex.get(preq._key);
if ( bucket.length === 1 ) {
this.pendingURLToIndex.delete(preq._key);
} else {
var pos = bucket.indexOf(si);
this.pendingURLToIndex.set(preq._key, bucket.slice(0, pos) + bucket.slice(pos + 1));
}
}
bucket = this.pendingURLToIndex.get(url);
this.pendingURLToIndex.set(url, bucket === undefined ? si : bucket + si);
preq._key = url;
return preq;
},
lookupPendingRequest: function(url) {
var bucket = this.pendingURLToIndex.get(url);
if ( bucket === undefined ) {
return null;
}
var i = bucket.charCodeAt(0);
if ( bucket.length === 1 ) {
this.pendingURLToIndex.delete(url);
} else {
this.pendingURLToIndex.set(url, bucket.slice(1));
}
var preq = this.pendingRingBuffer[i];
preq._key = ''; // mark as "serviced"
return preq;
},
// https://github.com/gorhill/uMatrix/issues/165
// https://developer.mozilla.org/en-US/Firefox/Releases/3.5/Updating_extensions#Getting_a_load_context_from_a_request
// Not sure `umatrix:shouldLoad` is still needed, uMatrix does not
// care about embedded frames topography.
// Also:
// https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox/Limitations_of_chrome_scripts
tabIdFromChannel: function(channel) {
var lc;
try {
lc = channel.notificationCallbacks.getInterface(Ci.nsILoadContext);
} catch(ex) {
}
if ( !lc ) {
try {
lc = channel.loadGroup.notificationCallbacks.getInterface(Ci.nsILoadContext);
} catch(ex) {
}
if ( !lc ) {
return vAPI.noTabId;
}
}
if ( lc.topFrameElement ) {
return tabWatcher.tabIdFromTarget(lc.topFrameElement);
}
var win;
try {
win = lc.associatedWindow;
} catch (ex) { }
if ( !win ) {
return vAPI.noTabId;
}
if ( win.top ) {
win = win.top;
}
var tabBrowser;
try {
tabBrowser = getTabBrowser(
win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShell).rootTreeItem
.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow)
);
} catch (ex) { }
if ( !tabBrowser ) {
return vAPI.noTabId;
}
if ( tabBrowser.getBrowserForContentWindow ) {
return tabWatcher.tabIdFromTarget(tabBrowser.getBrowserForContentWindow(win));
}
// Falling back onto _getTabForContentWindow to ensure older versions
// of Firefox work well.
return tabBrowser._getTabForContentWindow ?
tabWatcher.tabIdFromTarget(tabBrowser._getTabForContentWindow(win)) :
vAPI.noTabId;
},
// https://github.com/gorhill/uBlock/issues/959
// Try to synthesize a pending request from a behind-the-scene request.
synthesizePendingRequest: function(channel, rawtype) {
var tabId = this.tabIdFromChannel(channel);
if ( tabId === vAPI.noTabId ) {
return null;
}
return {
frameId: 0,
parentFrameId: -1,
tabId: tabId,
rawtype: rawtype
};
},
handleRequest: function(channel, URI, details) {
var type = this.typeMap[details.rawtype] || 'other';
if ( this.onBeforeRequestTypes && this.onBeforeRequestTypes.has(type) === false ) {
return false;
}
var result = this.onBeforeRequest({
frameId: details.frameId,
parentFrameId: details.parentFrameId,
tabId: details.tabId,
type: type,
url: URI.asciiSpec
});
if ( !result || typeof result !== 'object' ) {
return false;
}
if ( 'cancel' in result && result.cancel === true ) {
channel.cancel(this.ABORT);
return true;
}
if ( 'redirectUrl' in result ) {
channel.redirectionLimit = 1;
channel.redirectTo(Services.io.newURI(result.redirectUrl, null, null));
return true;
}
return false;
},
getResponseHeader: function(channel, name) {
var value;
try {
value = channel.getResponseHeader(name);
} catch (ex) {
}
return value;
},
handleResponseHeaders: function(channel, URI, channelData) {
var requestType = this.typeMap[channelData[3]] || 'other';
if ( this.onHeadersReceivedTypes && this.onHeadersReceivedTypes.has(requestType) === false ) {
return;
}
// 'Content-Security-Policy' MUST come last in the array. Need to
// revised this eventually.
var responseHeaders = [];
var value = channel.contentLength;
if ( value !== -1 ) {
responseHeaders.push({ name: 'Content-Length', value: value });
}
if ( requestType.endsWith('_frame') ) {
value = this.getResponseHeader(channel, 'Content-Security-Policy');
if ( value !== undefined ) {
responseHeaders.push({ name: 'Content-Security-Policy', value: value });
}
}
var result = this.onHeadersReceived({
parentFrameId: channelData[1],
responseHeaders: responseHeaders,
tabId: channelData[2],
type: requestType,
url: URI.asciiSpec
});
if ( !result ) {
return;
}
if ( result.cancel ) {
channel.cancel(this.ABORT);
return;
}
if ( result.responseHeaders ) {
channel.setResponseHeader(
'Content-Security-Policy',
result.responseHeaders.pop().value,
true
);
return;
}
},
observe: function(channel, topic) {
if ( channel instanceof Ci.nsIHttpChannel === false ) {
return;
}
var URI = channel.URI;
if ( topic === 'http-on-examine-response' ) {
if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
return;
}
var channelData;
try {
channelData = channel.getProperty(this.REQDATAKEY);
} catch (ex) {
}
if ( !channelData ) {
return;
}
this.handleResponseHeaders(channel, URI, channelData);
return;
}
// http-on-modify-request
var pendingRequest = this.lookupPendingRequest(URI.spec);
// https://github.com/gorhill/uMatrix/issues/390#issuecomment-155759004
var rawtype = 1;
var loadInfo = channel.loadInfo;
if ( loadInfo ) {
rawtype = loadInfo.externalContentPolicyType !== undefined ?
loadInfo.externalContentPolicyType :
loadInfo.contentPolicyType;
if ( !rawtype ) {
rawtype = 1;
}
}
// IMPORTANT:
// If this is a main frame, ensure that the proper tab id is being
// used: it can happen that the wrong tab id was looked up at
// `shouldLoadListener` time. Without this, the popup blocker may
// not work properly, and also a tab opened from a link may end up
// being wrongly reported as an embedded element.
if ( pendingRequest !== null && pendingRequest.rawtype === 6 ) {
var tabId = this.tabIdFromChannel(channel);
if ( tabId !== vAPI.noTabId ) {
pendingRequest.tabId = tabId;
}
}
// Behind-the-scene request... Really?
if ( pendingRequest === null ) {
pendingRequest = this.synthesizePendingRequest(channel, rawtype);
}
// Behind-the-scene request... Yes, really.
if ( pendingRequest === null ) {
if ( this.handleRequest(channel, URI, { tabId: vAPI.noTabId, rawtype: rawtype }) ) {
return;
}
// Carry data for behind-the-scene redirects
if ( channel instanceof Ci.nsIWritablePropertyBag ) {
channel.setProperty(this.REQDATAKEY, [0, -1, vAPI.noTabId, rawtype]);
}
return;
}
// https://github.com/gorhill/uBlock/issues/654
// Use the request type from the HTTP observer point of view.
if ( rawtype !== 1 ) {
pendingRequest.rawtype = rawtype;
}
if ( this.handleRequest(channel, URI, pendingRequest) ) {
return;
}
// If request is not handled we may use the data in on-modify-request
if ( channel instanceof Ci.nsIWritablePropertyBag ) {
channel.setProperty(this.REQDATAKEY, [
pendingRequest.frameId,
pendingRequest.parentFrameId,
pendingRequest.tabId,
pendingRequest.rawtype
]);
}
},
// contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
// If error thrown, the redirect will fail
try {
var URI = newChannel.URI;
if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
return;
}
if (
oldChannel instanceof Ci.nsIWritablePropertyBag === false ||
newChannel instanceof Ci.nsIWritablePropertyBag === false
) {
return;
}
// Carry the data on in case of multiple redirects
newChannel.setProperty(
this.REQDATAKEY,
oldChannel.getProperty(this.REQDATAKEY)
);
} catch (ex) {
// console.error(ex);
} finally {
callback.onRedirectVerifyCallback(this.ACCEPT);
}
}
};
/******************************************************************************/
/******************************************************************************/
vAPI.net = {};
/******************************************************************************/
vAPI.net.registerListeners = function() {
// Since it's not used
this.onBeforeSendHeaders = null;
if ( typeof this.onBeforeRequest.callback === 'function' ) {
httpObserver.onBeforeRequest = this.onBeforeRequest.callback;
httpObserver.onBeforeRequestTypes = this.onBeforeRequest.types ?
new Set(this.onBeforeRequest.types) :
null;
}
if ( typeof this.onHeadersReceived.callback === 'function' ) {
httpObserver.onHeadersReceived = this.onHeadersReceived.callback;
httpObserver.onHeadersReceivedTypes = this.onHeadersReceived.types ?
new Set(this.onHeadersReceived.types) :
null;
}
var shouldLoadPopupListenerMessageName = location.host + ':shouldLoadPopup';
var shouldLoadPopupListener = function(e) {
if ( typeof vAPI.tabs.onPopupCreated !== 'function' ) {
return;
}
var openerURL = e.data;
var popupTabId = tabWatcher.tabIdFromTarget(e.target);
var uri, openerTabId;
for ( var browser of tabWatcher.browsers() ) {
uri = browser.currentURI;
// Probably isn't the best method to identify the source tab.
// https://github.com/gorhill/uBlock/issues/450
// Skip entry if no valid URI available.
// Apparently URI can be undefined under some circumstances: I
// believe this may have to do with those very temporary
// browser objects created when opening a new tab, i.e. related
// to https://github.com/gorhill/uBlock/issues/212
if ( !uri || uri.spec !== openerURL ) {
continue;
}
openerTabId = tabWatcher.tabIdFromTarget(browser);
if ( openerTabId !== popupTabId ) {
vAPI.tabs.onPopupCreated(popupTabId, openerTabId);
break;
}
}
};
vAPI.messaging.globalMessageManager.addMessageListener(
shouldLoadPopupListenerMessageName,
shouldLoadPopupListener
);
var shouldLoadListenerMessageName = location.host + ':shouldLoad';
var shouldLoadListener = function(e) {
// Non blocking: it is assumed that the http observer is fired after
// shouldLoad recorded the pending requests. If this is not the case,
// a request would end up being categorized as a behind-the-scene
// requests.
var details = e.data;
// We are being called synchronously from the content process, so we
// must return ASAP. The code below merely record the details of the
// request into a ring buffer for later retrieval by the HTTP observer.
var pendingReq = httpObserver.createPendingRequest(details.url);
pendingReq.frameId = details.frameId;
pendingReq.parentFrameId = details.parentFrameId;
pendingReq.rawtype = details.rawtype;
pendingReq.tabId = tabWatcher.tabIdFromTarget(e.target);
};
vAPI.messaging.globalMessageManager.addMessageListener(
shouldLoadListenerMessageName,
shouldLoadListener
);
var locationChangedListenerMessageName = location.host + ':locationChanged';
var locationChangedListener = function(e) {
var browser = e.target;
// I have seen this happens (at startup time)
if ( !browser.currentURI ) {
return;
}
// https://github.com/gorhill/uBlock/issues/697
// Dismiss event if the associated tab is pending.
var tab = tabWatcher.tabFromBrowser(browser);
if ( !vAPI.fennec && tab && tab.hasAttribute('pending') ) {
// https://github.com/gorhill/uBlock/issues/820
// Firefox quirk: it happens the `pending` attribute was not
// present for certain tabs at startup -- and this can cause
// unwanted [browser <--> tab id] associations internally.
// Dispose of these if it is found the `pending` attribute is
// set.
tabWatcher.removeTarget(tab);
return;
}
var details = e.data;
var tabId = tabWatcher.tabIdFromTarget(browser);
// Ignore notifications related to our popup
if ( details.url.startsWith(vAPI.getURL('popup.html')) ) {
return;
}
// LOCATION_CHANGE_SAME_DOCUMENT = "did not load a new document"
if ( details.flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT ) {
vAPI.tabs.onUpdated(tabId, {url: details.url}, {
frameId: 0,
tabId: tabId,
url: browser.currentURI.asciiSpec
});
return;
}
// https://github.com/chrisaljoudi/uBlock/issues/105
// Allow any kind of pages
vAPI.tabs.onNavigation({
frameId: 0,
tabId: tabId,
url: details.url
});
};
vAPI.messaging.globalMessageManager.addMessageListener(
locationChangedListenerMessageName,
locationChangedListener
);
httpObserver.register();
cleanupTasks.push(function() {
vAPI.messaging.globalMessageManager.removeMessageListener(
shouldLoadPopupListenerMessageName,
shouldLoadPopupListener
);
vAPI.messaging.globalMessageManager.removeMessageListener(
shouldLoadListenerMessageName,
shouldLoadListener
);
vAPI.messaging.globalMessageManager.removeMessageListener(
locationChangedListenerMessageName,
locationChangedListener
);
httpObserver.unregister();
});
};
/******************************************************************************/
/******************************************************************************/
vAPI.toolbarButton = {
id: location.host + '-button',
type: 'view',
viewId: location.host + '-panel',
label: vAPI.app.name,
tooltiptext: vAPI.app.name,
tabs: {/*tabId: {badge: 0, img: boolean}*/},
init: null,
codePath: ''
};
/******************************************************************************/
// Fennec
(function() {
if ( !vAPI.fennec ) {
return;
}
var tbb = vAPI.toolbarButton;
tbb.codePath = 'fennec';
var menuItemIds = new WeakMap();
var shutdown = function() {
for ( var win of winWatcher.getWindows() ) {
var id = menuItemIds.get(win);
if ( !id ) {
continue;
}
win.NativeWindow.menu.remove(id);
menuItemIds.delete(win);
}
};
tbb.getMenuItemLabel = function(tabId) {
var label = this.label;
if ( tabId === undefined ) {
return label;
}
var tabDetails = this.tabs[tabId];
if ( !tabDetails ) {
return label;
}
if ( !tabDetails.img ) {
label += ' (' + vAPI.i18n('fennecMenuItemBlockingOff') + ')';
} else if ( tabDetails.badge ) {
label += ' (' + tabDetails.badge + ')';
}
return label;
};
tbb.onClick = function() {
var win = winWatcher.getCurrentWindow();
var curTabId = tabWatcher.tabIdFromTarget(getTabBrowser(win).selectedTab);
vAPI.tabs.open({
url: 'popup.html?tabId=' + curTabId,
index: -1,
select: true
});
};
tbb.updateState = function(win, tabId) {
var id = menuItemIds.get(win);
if ( !id ) {
return;
}
win.NativeWindow.menu.update(id, {
name: this.getMenuItemLabel(tabId)
});
};
// https://github.com/gorhill/uBlock/issues/955
// Defer until `NativeWindow` is available.
tbb.initOne = function(win) {
if ( !win.NativeWindow ) {
return;
}
var label = this.getMenuItemLabel();
var id = win.NativeWindow.menu.add({
name: label,
callback: this.onClick
});
menuItemIds.set(win, id);
};
tbb.canInit = function(win) {
return !!win.NativeWindow;
};
tbb.init = function() {
// Only actually expecting one window under Fennec (note, not tabs, windows)
for ( var win of winWatcher.getWindows() ) {
deferUntil(
this.canInit.bind(this, win),
this.initOne.bind(this, win)
);
}
cleanupTasks.push(shutdown);
};
})();
/******************************************************************************/
// Non-Fennec: common code paths.
(function() {
if ( vAPI.fennec ) {
return;
}
var tbb = vAPI.toolbarButton;
tbb.onViewShowing = function({target}) {
target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
};
tbb.onViewHiding = function({target}) {
target.parentNode.style.maxWidth = '';
target.firstChild.setAttribute('src', 'about:blank');
};
tbb.updateState = function(win, tabId) {
var button = win.document.getElementById(this.id);
if ( !button ) {
return;
}
var icon = this.tabs[tabId];
button.setAttribute('badge', icon && icon.badge || '');
button.classList.toggle('off', !icon || !icon.img);
};
tbb.populatePanel = function(doc, panel) {
panel.setAttribute('id', this.viewId);
var iframe = doc.createElement('iframe');
iframe.setAttribute('type', 'content');
panel.appendChild(iframe);
var toPx = function(pixels) {
return pixels.toString() + 'px';
};
var resizeTimer = null;
var resizePopupDelayed = function(attempts) {
if ( resizeTimer !== null ) {
return;
}
// Sanity check
attempts = (attempts || 0) + 1;
if ( attempts > 1/*000*/ ) {
console.error('Unsuckifier> resizePopupDelayed: giving up after too many attempts');
return;
}
resizeTimer = vAPI.setTimeout(resizePopup, 10, attempts);
};
var resizePopup = function(attempts) {
resizeTimer = null;
var body = iframe.contentDocument.body;
panel.parentNode.style.maxWidth = 'none';
// https://github.com/gorhill/uMatrix/issues/362
panel.parentNode.style.opacity = '1';
// https://github.com/chrisaljoudi/uBlock/issues/730
// Voodoo programming: this recipe works
var clientHeight = body.clientHeight;
iframe.style.height = toPx(clientHeight);
panel.style.height = toPx(clientHeight + panel.boxObject.height - panel.clientHeight);
var clientWidth = body.clientWidth;
iframe.style.width = toPx(clientWidth);
panel.style.width = toPx(clientWidth + panel.boxObject.width - panel.clientWidth);
if ( iframe.clientHeight !== body.clientHeight || iframe.clientWidth !== body.clientWidth ) {
resizePopupDelayed(attempts);
}
};
var onPopupReady = function() {
var win = this.contentWindow;
if ( !win || win.location.host !== location.host ) {
return;
}
if ( typeof tbb.onBeforePopupReady === 'function' ) {
tbb.onBeforePopupReady.call(this);
}
new win.MutationObserver(resizePopupDelayed).observe(win.document.body, {
attributes: true,
characterData: true,
subtree: true
});
resizePopupDelayed();
};
iframe.addEventListener('load', onPopupReady, true);
};
})();
/******************************************************************************/
// Firefox 35 and less: use legacy toolbar button.
(function() {
var tbb = vAPI.toolbarButton;
if ( tbb.init !== null ) {
return;
}
var CustomizableUI = null;
var forceLegacyToolbarButton = vAPI.localStorage.getBool('forceLegacyToolbarButton');
if ( !forceLegacyToolbarButton ) {
try {
CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
} catch (ex) {
}
}
if (
CustomizableUI !== null &&
Services.vc.compare(Services.appinfo.platformVersion, '36.0') >= 0
) {
return;
}
tbb.codePath = 'legacy';
tbb.id = 'Unsuckifier-legacy-button'; // NOTE: must match legacy-toolbar-button.css
tbb.viewId = tbb.id + '-panel';
var styleSheetUri = null;
var createToolbarButton = function(window) {
var document = window.document;
var toolbarButton = document.createElement('toolbarbutton');
toolbarButton.setAttribute('id', tbb.id);
// type = panel would be more accurate, but doesn't look as good
toolbarButton.setAttribute('type', 'menu');
toolbarButton.setAttribute('removable', 'true');
toolbarButton.setAttribute('class', 'toolbarbutton-1 chromeclass-toolbar-additional');
toolbarButton.setAttribute('label', tbb.label);
toolbarButton.setAttribute('tooltiptext', tbb.label);
var toolbarButtonPanel = document.createElement('panel');
// NOTE: Setting level to parent breaks the popup for PaleMoon under
// linux (mouse pointer misaligned with content). For some reason.
// toolbarButtonPanel.setAttribute('level', 'parent');
tbb.populatePanel(document, toolbarButtonPanel);
toolbarButtonPanel.addEventListener('popupshowing', tbb.onViewShowing);
toolbarButtonPanel.addEventListener('popuphiding', tbb.onViewHiding);
toolbarButton.appendChild(toolbarButtonPanel);
return toolbarButton;
};
var addLegacyToolbarButton = function(window) {
// uBO's stylesheet lazily added.
if ( styleSheetUri === null ) {
var sss = Cc['@mozilla.org/content/style-sheet-service;1']
.getService(Ci.nsIStyleSheetService);
styleSheetUri = Services.io.newURI(vAPI.getURL('css/legacy-toolbar-button.css'), null, null);
// Register global so it works in all windows, including palette
if ( !sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
sss.loadAndRegisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
}
}
var document = window.document;
// https://github.com/gorhill/uMatrix/issues/357
// Already installed?
if ( document.getElementById(tbb.id) !== null ) {
return;
}
var toolbox = document.getElementById('navigator-toolbox') ||
document.getElementById('mail-toolbox');
if ( toolbox === null ) {
return;
}
var toolbarButton = createToolbarButton(window);
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/toolbarpalette
var palette = toolbox.palette;
if ( palette && palette.querySelector('#' + tbb.id) === null ) {
palette.appendChild(toolbarButton);
}
// Find the place to put the button.
// Pale Moon: `toolbox.externalToolbars` can be undefined. Seen while
// testing popup test number 3:
// http://raymondhill.net/ublock/popup.html
var toolbars = toolbox.externalToolbars ? toolbox.externalToolbars.slice() : [];
for ( var child of toolbox.children ) {
if ( child.localName === 'toolbar' ) {
toolbars.push(child);
}
}
for ( var toolbar of toolbars ) {
var currentsetString = toolbar.getAttribute('currentset');
if ( !currentsetString ) {
continue;
}
var currentset = currentsetString.split(/\s*,\s*/);
var index = currentset.indexOf(tbb.id);
if ( index === -1 ) {
continue;
}
// This can occur with Pale Moon:
// "TypeError: toolbar.insertItem is not a function"
if ( typeof toolbar.insertItem !== 'function' ) {
continue;
}
// Found our button on this toolbar - but where on it?
var before = null;
for ( var i = index + 1; i < currentset.length; i++ ) {
before = toolbar.querySelector('[id="' + currentset[i] + '"]');
if ( before !== null ) {
break;
}
}
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Method/insertItem
toolbar.insertItem(tbb.id, before);
break;
}
// https://github.com/gorhill/uBlock/issues/763
// We are done if our toolbar button is already installed in one of the
// toolbar.
if ( palette !== null && toolbarButton.parentElement !== palette ) {
return;
}
// No button yet so give it a default location. If forcing the button,
// just put in in the palette rather than on any specific toolbar (who
// knows what toolbars will be available or visible!)
var navbar = document.getElementById('nav-bar');
if ( navbar !== null && !vAPI.localStorage.getBool('legacyToolbarButtonAdded') ) {
// https://github.com/gorhill/uBlock/issues/264
// Find a child customizable palette, if any.
navbar = navbar.querySelector('.customization-target') || navbar;
navbar.appendChild(toolbarButton);
navbar.setAttribute('currentset', navbar.currentSet);
document.persist(navbar.id, 'currentset');
vAPI.localStorage.setBool('legacyToolbarButtonAdded', 'true');
}
};
var canAddLegacyToolbarButton = function(window) {
var document = window.document;
if (
!document ||
document.readyState !== 'complete' ||
document.getElementById('nav-bar') === null
) {
return false;
}
var toolbox = document.getElementById('navigator-toolbox') ||
document.getElementById('mail-toolbox');
return toolbox !== null && !!toolbox.palette;
};
var onPopupCloseRequested = function({target}) {
var document = target.ownerDocument;
if ( !document ) {
return;
}
var toolbarButtonPanel = document.getElementById(tbb.viewId);
if ( toolbarButtonPanel === null ) {
return;
}
// `hidePopup` reported as not existing while testing legacy button
// on FF 41.0.2.
// https://bugzilla.mozilla.org/show_bug.cgi?id=1151796
if ( typeof toolbarButtonPanel.hidePopup === 'function' ) {
toolbarButtonPanel.hidePopup();
}
};
var shutdown = function() {
for ( var win of winWatcher.getWindows() ) {
var toolbarButton = win.document.getElementById(tbb.id);
if ( toolbarButton ) {
toolbarButton.parentNode.removeChild(toolbarButton);
}
}
vAPI.messaging.globalMessageManager.removeMessageListener(
location.host + ':closePopup',
onPopupCloseRequested
);
if ( styleSheetUri !== null ) {
var sss = Cc['@mozilla.org/content/style-sheet-service;1']
.getService(Ci.nsIStyleSheetService);
if ( sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
sss.unregisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
}
styleSheetUri = null;
}
};
tbb.attachToNewWindow = function(win) {
deferUntil(
canAddLegacyToolbarButton.bind(null, win),
addLegacyToolbarButton.bind(null, win)
);
};
tbb.init = function() {
vAPI.messaging.globalMessageManager.addMessageListener(
location.host + ':closePopup',
onPopupCloseRequested
);
cleanupTasks.push(shutdown);
};
})();
/******************************************************************************/
// Firefox Australis >= 36.
(function() {
var tbb = vAPI.toolbarButton;
if ( tbb.init !== null ) {
return;
}
if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') < 0 ) {
return null;
}
if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
return null;
}
var CustomizableUI = null;
try {
CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
} catch (ex) {
}
if ( CustomizableUI === null ) {
return null;
}
tbb.codePath = 'australis';
tbb.CustomizableUI = CustomizableUI;
tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
var CUIEvents = {};
var badgeCSSRules = [
'background: #666',
'color: #fff'
].join(';');
var updateBadgeStyle = function() {
for ( var win of winWatcher.getWindows() ) {
var button = win.document.getElementById(tbb.id);
if ( button === null ) {
continue;
}
var badge = button.ownerDocument.getAnonymousElementByAttribute(
button,
'class',
'toolbarbutton-badge'
);
if ( !badge ) {
continue;
}
badge.style.cssText = badgeCSSRules;
}
};
var updateBadge = function() {
var wId = tbb.id;
var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
for ( var win of winWatcher.getWindows() ) {
var button = win.document.getElementById(wId);
if ( button === null ) {
continue;
}
if ( buttonInPanel ) {
button.classList.remove('badged-button');
continue;
}
button.classList.add('badged-button');
}
if ( buttonInPanel ) {
return;
}
// Anonymous elements need some time to be reachable
vAPI.setTimeout(updateBadgeStyle, 250);
}.bind(CUIEvents);
// https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/CustomizableUI.jsm#Listeners
CUIEvents.onCustomizeEnd = updateBadge;
CUIEvents.onWidgetAdded = updateBadge;
CUIEvents.onWidgetUnderflow = updateBadge;
var onPopupCloseRequested = function({target}) {
if ( typeof tbb.closePopup === 'function' ) {
tbb.closePopup(target);
}
};
var shutdown = function() {
for ( var win of winWatcher.getWindows() ) {
var panel = win.document.getElementById(tbb.viewId);
if ( panel !== null && panel.parentNode !== null ) {
panel.parentNode.removeChild(panel);
}
win.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils)
.removeSheet(styleURI, 1);
}
CustomizableUI.removeListener(CUIEvents);
CustomizableUI.destroyWidget(tbb.id);
vAPI.messaging.globalMessageManager.removeMessageListener(
location.host + ':closePopup',
onPopupCloseRequested
);
};
var styleURI = null;
tbb.onBeforeCreated = function(doc) {
var panel = doc.createElement('panelview');
this.populatePanel(doc, panel);
doc.getElementById('PanelUI-multiView').appendChild(panel);
doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils)
.loadSheet(styleURI, 1);
};
tbb.onCreated = function(button) {
button.setAttribute('badge', '');
vAPI.setTimeout(updateBadge, 250);
};
tbb.onBeforePopupReady = function() {
// https://github.com/gorhill/uBlock/issues/83
// Add `portrait` class if width is constrained.
try {
this.contentDocument.body.classList.toggle(
'portrait',
CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
);
} catch (ex) {
/* noop */
}
};
tbb.closePopup = function(tabBrowser) {
CustomizableUI.hidePanelForNode(
tabBrowser.ownerDocument.getElementById(tbb.viewId)
);
};
tbb.init = function() {
vAPI.messaging.globalMessageManager.addMessageListener(
location.host + ':closePopup',
onPopupCloseRequested
);
CustomizableUI.addListener(CUIEvents);
var style = [
'#' + this.id + '.off {',
'list-style-image: url(',
vAPI.getURL('img/browsericons/icon16-off.svg'),
');',
'}',
'#' + this.id + ' {',
'list-style-image: url(',
vAPI.getURL('img/browsericons/icon16.svg'),
');',
'}',
'#' + this.viewId + ',',
'#' + this.viewId + ' > iframe {',
'width: 160px;',
'height: 290px;',
'overflow: hidden !important;',
'}'
];
styleURI = Services.io.newURI(
'data:text/css,' + encodeURIComponent(style.join('')),
null,
null
);
CustomizableUI.createWidget(this);
cleanupTasks.push(shutdown);
};
})();
/******************************************************************************/
// No toolbar button.
(function() {
// Just to ensure the number of cleanup tasks is as expected: toolbar
// button code is one single cleanup task regardless of platform.
if ( vAPI.toolbarButton.init === null ) {
cleanupTasks.push(function(){});
}
})();
/******************************************************************************/
if ( vAPI.toolbarButton.init !== null ) {
vAPI.toolbarButton.init();
}
/******************************************************************************/
/******************************************************************************/
vAPI.contextMenu = (function() {
var clientCallback = null;
var clientEntries = [];
var contextMap = {
frame: 'inFrame',
link: 'onLink',
image: 'onImage',
audio: 'onAudio',
video: 'onVideo',
editable: 'onEditableArea'
};
var onCommand = function() {
var gContextMenu = getOwnerWindow(this).gContextMenu;
var details = {
menuItemId: this.id
};
if ( gContextMenu.inFrame ) {
details.tagName = 'iframe';
// Probably won't work with e10s
details.frameUrl = gContextMenu.focusedWindow && gContextMenu.focusedWindow.location.href || '';
} else if ( gContextMenu.onImage ) {
details.tagName = 'img';
details.srcUrl = gContextMenu.mediaURL;
} else if ( gContextMenu.onAudio ) {
details.tagName = 'audio';
details.srcUrl = gContextMenu.mediaURL;
} else if ( gContextMenu.onVideo ) {
details.tagName = 'video';
details.srcUrl = gContextMenu.mediaURL;
} else if ( gContextMenu.onLink ) {
details.tagName = 'a';
details.linkUrl = gContextMenu.linkURL;
}
clientCallback(details, {
id: tabWatcher.tabIdFromTarget(gContextMenu.browser),
url: gContextMenu.browser.currentURI.asciiSpec
});
};
var menuItemMatchesContext = function(contextMenu, clientEntry) {
if ( !clientEntry.contexts ) {
return false;
}
for ( var context of clientEntry.contexts ) {
if ( context === 'all' ) {
return true;
}
if (
contextMap.hasOwnProperty(context) &&
contextMenu[contextMap[context]]
) {
return true;
}
}
return false;
};
var onMenuShowing = function({target}) {
var doc = target.ownerDocument;
var gContextMenu = doc.defaultView.gContextMenu;
if ( !gContextMenu.browser ) {
return;
}
// https://github.com/chrisaljoudi/uBlock/issues/105
// TODO: Should the element picker works on any kind of pages?
var currentURI = gContextMenu.browser.currentURI,
isHTTP = currentURI.schemeIs('http') || currentURI.schemeIs('https'),
layoutChanged = false,
contextMenu = doc.getElementById('contentAreaContextMenu'),
newEntries = clientEntries,
oldMenuitems = contextMenu.querySelectorAll('[data-Unsuckifier="menuitem"]'),
newMenuitems = [],
n = Math.max(clientEntries.length, oldMenuitems.length),
menuitem, newEntry;
for ( var i = 0; i < n; i++ ) {
menuitem = oldMenuitems[i];
newEntry = newEntries[i];
if ( menuitem && !newEntry ) {
menuitem.parentNode.removeChild(menuitem);
menuitem.removeEventListener('command', onCommand);
menuitem = null;
layoutChanged = true;
} else if ( !menuitem && newEntry ) {
menuitem = doc.createElement('menuitem');
menuitem.setAttribute('data-Unsuckifier', 'menuitem');
menuitem.addEventListener('command', onCommand);
}
if ( !menuitem ) {
continue;
}
if ( menuitem.id !== newEntry.id ) {
menuitem.setAttribute('id', newEntry.id);
menuitem.setAttribute('label', newEntry.title);
layoutChanged = true;
}
menuitem.setAttribute('hidden', !isHTTP || !menuItemMatchesContext(gContextMenu, newEntry));
newMenuitems.push(menuitem);
}
// No changes?
if ( layoutChanged === false ) {
return;
}
// No entry: remove submenu if present.
var menu = contextMenu.querySelector('[data-Unsuckifier="menu"]');
if ( newMenuitems.length === 0 ) {
if ( menu !== null ) {
menu.parentNode.removeChild(menuitem);
}
return;
}
// Only one entry: no need for a submenu.
if ( newMenuitems.length === 1 ) {
if ( menu !== null ) {
menu.parentNode.removeChild(menu);
}
menuitem = newMenuitems[0];
menuitem.setAttribute('class', 'menuitem-iconic');
menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
return;
}
// More than one entry: we need a submenu.
if ( menu === null ) {
menu = doc.createElement('menu');
menu.setAttribute('label', vAPI.app.name);
menu.setAttribute('data-Unsuckifier', 'menu');
menu.setAttribute('class', 'menu-iconic');
menu.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
contextMenu.insertBefore(menu, doc.getElementById('inspect-separator'));
}
var menupopup = contextMenu.querySelector('[data-Unsuckifier="menupopup"]');
if ( menupopup === null ) {
menupopup = doc.createElement('menupopup');
menupopup.setAttribute('data-Unsuckifier', 'menupopup');
menu.appendChild(menupopup);
}
for ( i = 0; i < newMenuitems.length; i++ ) {
menuitem = newMenuitems[i];
menuitem.setAttribute('class', 'menuitem-non-iconic');
menuitem.removeAttribute('image');
menupopup.appendChild(menuitem);
}
};
// https://github.com/gorhill/uBlock/issues/906
// Be sure document.readyState is 'complete': it could happen at launch
// time that we are called by vAPI.contextMenu.create() directly before
// the environment is properly initialized.
var canRegister = function(win) {
return win && win.document.readyState === 'complete';
};
var register = function(window) {
if ( canRegister(window) !== true ) {
return;
}
var contextMenu = window.document.getElementById('contentAreaContextMenu');
if ( contextMenu === null ) {
return;
}
contextMenu.addEventListener('popupshowing', onMenuShowing);
};
var registerAsync = function(win) {
// TODO https://developer.mozilla.org/en-US/Add-ons/Firefox_for_Android/API/NativeWindow/contextmenus/add
// var nativeWindow = doc.defaultView.NativeWindow;
// contextId = nativeWindow.contextmenus.add(
// this.menuLabel,
// nativeWindow.contextmenus.linkOpenableContext,
// this.onCommand
// );
if ( vAPI.fennec ) {
return;
}
deferUntil(
canRegister.bind(null, win),
register.bind(null, win)
);
};
var unregister = function(win) {
// TODO
if ( vAPI.fennec ) {
return;
}
var contextMenu = win.document.getElementById('contentAreaContextMenu');
if ( contextMenu !== null ) {
contextMenu.removeEventListener('popupshowing', onMenuShowing);
}
var menuitems = win.document.querySelectorAll('[data-Unsuckifier]'),
menuitem;
for ( var i = 0; i < menuitems.length; i++ ) {
menuitem = menuitems[i];
menuitem.parentNode.removeChild(menuitem);
menuitem.removeEventListener('command', onCommand);
}
};
var setEntries = function(entries, callback) {
clientEntries = entries || [];
clientCallback = callback || null;
};
return {
onMustUpdate: function() {},
register: registerAsync,
unregister: unregister,
setEntries: setEntries
};
})();
/******************************************************************************/
/******************************************************************************/
var optionsObserver = (function() {
var addonId = 'Unsuckifier@raymondhill.net';
var commandHandler = function() {
switch ( this.id ) {
case 'showDashboardButton':
vAPI.tabs.open({ url: 'dashboard.html', index: -1 });
break;
case 'showNetworkLogButton':
vAPI.tabs.open({ url: 'logger-ui.html', index: -1 });
break;
default:
break;
}
};
var setupOptionsButton = function(doc, id) {
var button = doc.getElementById(id);
if ( button === null ) {
return;
}
button.addEventListener('command', commandHandler);
button.label = vAPI.i18n(id);
};
var setupOptionsButtons = function(doc) {
setupOptionsButton(doc, 'showDashboardButton');
setupOptionsButton(doc, 'showNetworkLogButton');
};
var observer = {
observe: function(doc, topic, id) {
if ( id !== addonId ) {
return;
}
setupOptionsButtons(doc);
}
};
// https://github.com/gorhill/uBlock/issues/948
// Older versions of Firefox can throw here when looking up `currentURI`.
var canInit = function() {
try {
var tabBrowser = tabWatcher.currentBrowser();
return tabBrowser &&
tabBrowser.currentURI &&
tabBrowser.currentURI.spec === 'about:addons' &&
tabBrowser.contentDocument &&
tabBrowser.contentDocument.readyState === 'complete';
} catch (ex) {
}
};
// Manually add the buttons if the `about:addons` page is already opened.
var init = function() {
if ( canInit() ) {
setupOptionsButtons(tabWatcher.currentBrowser().contentDocument);
}
};
var unregister = function() {
Services.obs.removeObserver(observer, 'addon-options-displayed');
};
var register = function() {
Services.obs.addObserver(observer, 'addon-options-displayed', false);
cleanupTasks.push(unregister);
deferUntil(canInit, init, { next: 463 });
};
return {
register: register,
unregister: unregister
};
})();
optionsObserver.register();
/******************************************************************************/
/******************************************************************************/
vAPI.lastError = function() {
return null;
};
/******************************************************************************/
// This is called only once, when everything has been loaded in memory after
// the extension was launched. It can be used to inject content scripts
// in already opened web pages, to remove whatever nuisance could make it to
// the web pages before uBlock was ready.
vAPI.onLoadAllCompleted = function() {
// TODO: vAPI shouldn't know about uBlock. Just like in uMatrix, uBlock
// should collect on its side all the opened tabs whenever it is ready.
var µb = µBlock;
var tabId;
for ( var browser of tabWatcher.browsers() ) {
tabId = tabWatcher.tabIdFromTarget(browser);
µb.tabContextManager.commit(tabId, browser.currentURI.asciiSpec);
µb.bindTabToPageStats(tabId);
}
// Inject special frame script, which sole purpose is to inject
// content scripts into *already* opened tabs. This allows to unclutter
// the main frame script.
vAPI.messaging
.globalMessageManager
.loadFrameScript(vAPI.getURL('frameScript0.js'), false);
};
/******************************************************************************/
/******************************************************************************/
// Likelihood is that we do not have to punycode: given punycode overhead,
// it's faster to check and skip than do it unconditionally all the time.
var punycodeHostname = punycode.toASCII;
var isNotASCII = /[^\x21-\x7F]/;
vAPI.punycodeHostname = function(hostname) {
return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
};
vAPI.punycodeURL = function(url) {
if ( isNotASCII.test(url) ) {
return Services.io.newURI(url, null, null).asciiSpec;
}
return url;
};
/******************************************************************************/
/******************************************************************************/
// https://github.com/gorhill/uBlock/issues/531
// Storage area dedicated to admin settings. Read-only.
vAPI.adminStorage = {
getItem: function(key, callback) {
if ( typeof callback !== 'function' ) {
return;
}
callback(vAPI.localStorage.getItem(key));
}
};
/******************************************************************************/
/******************************************************************************/
vAPI.cloud = (function() {
var extensionBranchPath = 'extensions.' + location.host;
var cloudBranchPath = extensionBranchPath + '.cloudStorage';
// https://github.com/gorhill/uBlock/issues/80#issuecomment-132081658
// We must use get/setComplexValue in order to properly handle strings
// with unicode characters.
var iss = Ci.nsISupportsString;
var argstr = Components.classes['@mozilla.org/supports-string;1']
.createInstance(iss);
var options = {
defaultDeviceName: '',
deviceName: ''
};
// User-supplied device name.
try {
options.deviceName = Services.prefs
.getBranch(extensionBranchPath + '.')
.getComplexValue('deviceName', iss)
.data;
} catch(ex) {
}
var getDefaultDeviceName = function() {
var name = '';
try {
name = Services.prefs
.getBranch('services.sync.client.')
.getComplexValue('name', iss)
.data;
} catch(ex) {
}
return name || window.navigator.platform || window.navigator.oscpu;
};
var start = function(dataKeys) {
var extensionBranch = Services.prefs.getBranch(extensionBranchPath + '.');
var syncBranch = Services.prefs.getBranch('services.sync.prefs.sync.');
// Mark config entries as syncable
argstr.data = '';
var dataKey;
for ( var i = 0; i < dataKeys.length; i++ ) {
dataKey = dataKeys[i];
if ( extensionBranch.prefHasUserValue('cloudStorage.' + dataKey) === false ) {
extensionBranch.setComplexValue('cloudStorage.' + dataKey, iss, argstr);
}
syncBranch.setBoolPref(cloudBranchPath + '.' + dataKey, true);
}
};
var push = function(datakey, data, callback) {
var branch = Services.prefs.getBranch(cloudBranchPath + '.');
var bin = {
'source': options.deviceName || getDefaultDeviceName(),
'tstamp': Date.now(),
'data': data,
'size': 0
};
bin.size = JSON.stringify(bin).length;
argstr.data = JSON.stringify(bin);
branch.setComplexValue(datakey, iss, argstr);
if ( typeof callback === 'function' ) {
callback();
}
};
var pull = function(datakey, callback) {
var result = null;
var branch = Services.prefs.getBranch(cloudBranchPath + '.');
try {
var json = branch.getComplexValue(datakey, iss).data;
if ( typeof json === 'string' ) {
result = JSON.parse(json);
}
} catch(ex) {
}
callback(result);
};
var getOptions = function(callback) {
if ( typeof callback !== 'function' ) {
return;
}
options.defaultDeviceName = getDefaultDeviceName();
callback(options);
};
var setOptions = function(details, callback) {
if ( typeof details !== 'object' || details === null ) {
return;
}
var branch = Services.prefs.getBranch(extensionBranchPath + '.');
if ( typeof details.deviceName === 'string' ) {
argstr.data = details.deviceName;
branch.setComplexValue('deviceName', iss, argstr);
options.deviceName = details.deviceName;
}
getOptions(callback);
};
return {
start: start,
push: push,
pull: pull,
getOptions: getOptions,
setOptions: setOptions
};
})();
/******************************************************************************/
/******************************************************************************/
})();
/******************************************************************************/
|
dcposch/unsuckifier
|
platform/firefox/vapi-background.js
|
JavaScript
|
gpl-3.0
| 115,608 |
CKEDITOR.plugins.setLang('ajaxSave', 'no',
{
ajaxSave :
{
toolbar_button : 'Spare'
}
});
|
stephaneeybert/learnintouch
|
system/editor/ckeditor/plugins/ajaxSave/lang/no.js
|
JavaScript
|
gpl-3.0
| 109 |
import { remove_compose_box } from './composeBoxActions';
import mailer from './../../../modules/mailerService';
import { showNotification, hideNotification } from './notificationsActions';
export const send_request = () => {
return {
type: 'SEND_REQUEST',
isSending: true
}
};
export const send_success = () => {
return {
type: 'SEND_SUCCESS',
isSending: false
}
};
export const send_error = (message) => {
return {
type: 'SEND_ERROR',
isSending: false,
message
}
};
export const get_public_key = (publicKey) => {
return {
type: 'PUBLIC_KEY',
publicKey
}
};
export const showSpinner = () => {
return dispatch => {
dispatch(send_request());
}
};
export const sendMail = (data, composeBoxIndex) => {
return dispatch => {
mailer.sendEmail(data, (error, result) => {
if(error) {
dispatch(send_error());
return;
}
// Dispatch the success action
dispatch(send_success());
dispatch(remove_compose_box(composeBoxIndex));
dispatch(showNotification('sentOk'));
setTimeout(() => {
dispatch(hideNotification('sentOk'));
}, 5000);
});
}
};
|
DevanaLabs/lemon.email-dApp
|
assets/react/actions/sendMailActions.js
|
JavaScript
|
gpl-3.0
| 1,184 |
// MITHRAS: Javascript configuration management tool for AWS.
// Copyright (C) 2016, Colin Steele
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// @public
//
// # Instance
//
// Instance is resource handler for managing AWS caches.
//
// This module exports:
//
// > * `init` Initialization function, registers itself as a resource
// > handler with `mithras.modules.handlers` for resources with a
// > module value of `"instance"`
//
// Usage:
//
// `var instance = require("instance").init();`
//
// ## Example Resource
//
// ```javascript
// var webserverTagName: "my-web-server";
// var keyname: "test-key";
// var webServer = {
// name: "webserver"
// module: "instance"
// dependsOn: [resource.name]
// params: {
// region: "us-east-1"
// ensure: "present"
// on_find: function(catalog) {
// var matches = _.filter(catalog.instances, function (i) {
// if (i.State.Name != "running") {
// return false;
// }
// return (_.where(i.Tags, {"Key": "Name",
// "Value": webserverTagName}).length > 0);
// });
// return matches;
// }
// tags: {
// Name: webserverTagName
// }
// instance: {
// ImageId: "ami-60b6c60a"
// MaxCount: 1
// MinCount: 1
// DisableApiTermination: false
// EbsOptimized: false
// IamInstanceProfile: {
// Name: iamProfileName
// }
// InstanceInitiatedShutdownBehavior: "terminate"
// InstanceType: "t2.small"
// KeyName: keyName
// Monitoring: {
// Enabled: true
// }
// NetworkInterfaces: [
// {
// AssociatePublicIpAddress: true
// DeleteOnTermination: true
// DeviceIndex: 0
// Groups: [ "sg-abc" ]
// SubnetId: "subnet-123"
// }
// ]
// } // instance
// } // params
// };
// ```
//
// ## Parameter Properties
//
// ### `ensure`
//
// * Required: true
// * Allowed Values: "present" or "absent"
//
// If `"present"`, the db specified by `db` will be created, and
// if `"absent"`, it will be removed using the `delete` property.
//
// ### `region`
//
// * Required: true
// * Allowed Values: string, any valid AWS region; eg "us-east-1"
//
// The region for calls to the AWS API.
//
// ### `instance`
//
// * Required: true
// * Allowed Values: JSON corresponding to the structure found [here](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2.html#type-RunInstancesInput)
//
// Parameters for resource creation.
//
// ### `on_find`
//
// * Required: true
// * Allowed Values: A function taking two parameters: `catalog` and `resource`
//
// If defined in the resource's `params` object, the `on_find`
// function provides a way for a matching resource to be identified
// using a user-defined way. The function is called with the current
// `catalog`, as well as the `resource` object itself. The function
// can look through the catalog, find a matching object using whatever
// logic you want, and return it. If the function returns `undefined`
// or a n empty Javascript array, (`[]`), the function is indicating
// that no matching resource was found in the `catalog`.
//
// ### `tags`
//
// * Required: false
// * Allowed Values: A map of tags to be applied to created instances
//
// A map of tags to be applied to created instances
//
(function (root, factory){
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory();
}
})(this, function() {
var sprintf = require("sprintf.js").sprintf;
var handler = {
moduleNames: ["instance"]
findInCatalog: function(catalog, resources, resource) {
if (!typeof(resource.params.on_find) === 'function') {
console.log(sprintf("Instance resource '%s' has no 'on_find' param.",
resource.name));
os.exit(3);
}
result = resource.params.on_find(catalog, resources);
if (Array.isArray(result) && result.length == 0) {
return;
}
return result;
}
handle: function(catalog, resources, resource) {
if (!_.find(handler.moduleNames, function(m) { return resource.module === m; })) {
return [null, false];
}
var ensure = resource.params.ensure;
var params = resource.params;
if (!resource.params.instance) {
console.log("Invalid instance params")
os.exit(3);
}
var found = resource._target || [];
var matchingCount = found.length;
if (mithras.verbose) {
log(sprintf("Found %d matching instances, max %d, min %d",
matchingCount,
params.instance.MaxCount,
params.instance.MinCount));
}
switch(ensure) {
case "absent":
if (found.length == 0 && mithras.verbose) {
log(sprintf("No action taken."));
break;
}
if (mithras.verbose) {
log(sprintf("Deleting %d instances", found.length));
}
for (var idx in found) {
var inst = found[idx];
aws.instances.delete(params.region,
inst.InstanceId);
catalog.instances =
_.reject(catalog.instances,
function(i) {
return i.InstanceId == inst.InstanceId;
});
}
break;
case "present":
// Too many?
if (matchingCount > params.instance.MaxCount) {
var numToDelete = matchingCount - params.instance.MaxCount;
if (mithras.verbose) {
log(sprintf("Deleting %d instances", numToDelete));
}
for (var idx in _.range(numToDelete)) {
var inst = found[idx];
aws.instances.delete(params.region,
inst.InstanceId);
catalog.instances =
_.reject(catalog.instances,
function(i) {
return i.InstanceId == inst.InstanceId;
});
}
} else if (matchingCount < params.instance.MinCount) {
var numToAdd = params.instance.MaxCount - matchingCount;
// create
params.instance.MaxCount = numToAdd;
if (mithras.verbose) {
log(sprintf("Launching %d instances", numToAdd));
}
created = aws.instances.create(params.region, params.instance);
// Set tags
for (var idx in created) {
aws.tags.create(params.region,
created[idx].InstanceId,
params.tags);
}
// describe 'em (to get tags) and add to catalog
for (var idx in created) {
var inst = aws.instances.describe(params.region,
created[idx].InstanceId);
catalog.instances.push(inst);
}
} else {
if (mithras.verbose) {
log(sprintf("No action taken."));
}
}
// return 'em
return [handler.findInCatalog(catalog, resources, resource), true];
break;
}
return [null, true];
}
preflight: function(catalog, resources, resource) {
if (!_.find(handler.moduleNames, function(m) {
return resource.module === m;
})) {
return [null, false];
}
var params = resource.params;
var found = handler.findInCatalog(catalog, resources, resource);
if (found) {
return [found, true];
}
return [null, true];
}
};
handler.init = function () {
_.each(handler.moduleNames, function(name) {
mithras.modules.preflight.register(name, handler.preflight);
mithras.modules.handlers.register(name, handler.handle);
});
return handler;
};
return handler;
});
|
cvillecsteele/mithras
|
js/instance.js
|
JavaScript
|
gpl-3.0
| 10,118 |
var struct_appointment =
[
[ "callee_id", "struct_appointment.html#a1c758224d618992d6bcda246e68384c3", null ],
[ "caller_id", "struct_appointment.html#a677c4126148ba11b303127cd76cf9e35", null ],
[ "end", "struct_appointment.html#a13455ba845bf5d4dba37be491bc6a036", null ],
[ "id", "struct_appointment.html#a7441ef0865bcb3db9b8064dd7375c1ea", null ],
[ "is_accepted", "struct_appointment.html#a30449d2de0bda7cca32135a283b0162b", null ],
[ "next", "struct_appointment.html#a7a0b65c736183dbc90fdeb836add2a10", null ],
[ "prev", "struct_appointment.html#a76cac42b207c5cf8c9175afad72b7bd2", null ],
[ "reason", "struct_appointment.html#a578cf64f7f41b31eeda6f51fdd99b971", null ],
[ "rescheduled", "struct_appointment.html#a7d53dc414f2d787dc031b868da72e703", null ],
[ "start", "struct_appointment.html#ada310e7f72b38fadd4b24d80ed3438ee", null ],
[ "type", "struct_appointment.html#ae7b6c9fdabaf04275e5799e5daf7eecd", null ]
];
|
oneonestar/AppointmentManager
|
doc/html/struct_appointment.js
|
JavaScript
|
gpl-3.0
| 965 |
/*global describe, it*/
'use strict';
var assert = require('chai').assert;
var scorer = require('../scorer.js');
describe('scorer.js', function () {
describe('scorer:getScore', function () {
it('should return 0 when the user answers incorrectly', function () {
var anyTime, correctAnswers, userWrongAnswers, score;
anyTime = 9;
correctAnswers = ["correctAnswerA", "correctAnswerB"];
userWrongAnswers = ["wrongAnswerA", "wrongAnswerB"];
score = scorer.getScore(anyTime, anyTime, userWrongAnswers, correctAnswers);
assert(score === 0);
});
it('should return 0 when the number of selected doesn\'t equal the number of answers', function () {
var anyTime, correctAnswers, userWrongAnswers, score;
anyTime = 9;
correctAnswers = ["correctAnswerA", "correctAnswerB", "correctAnswerC"];
userWrongAnswers = ["wrongAnswerA", "wrongAnswerB"];
score = scorer.getScore(anyTime, anyTime, userWrongAnswers, correctAnswers);
assert(score === 0);
});
it('should return the ceil of 1000 * (reactionTime/roundTime)', function () {
var reactionTime, roundTime, correctAnswers, userCorrectAnswers, score;
reactionTime = 5;
roundTime = 10;
correctAnswers = ["correctAnswerA", "correctAnswerB"];
userCorrectAnswers = ["correctAnswerA", "correctAnswerB"];
score = scorer.getScore(reactionTime, roundTime, userCorrectAnswers, correctAnswers);
assert(score === 500);
});
});
});
|
mevorah/Oh-Strike-a-match
|
Game/test/scorer-test.js
|
JavaScript
|
gpl-3.0
| 1,722 |
/**
* @module db
* @description Creates new MongoDB connection to the mud database, so the connection can be included
* as a module where needed, using a single connection pool
*
* @author cemckinley <cemckinley@gmail.com>
* @copyright Copyright (c) 2013 Author, contributors
* @license GPL v3
*/
var mongoClient = require('mongodb').MongoClient,
config = require('../config/env');
var db = {
/**
* MongoDB connection instance will be stored here
* @type {Object}
*/
data: null,
connect: function(callback){
var self = this;
mongoClient.connect(config.db.location, function(err, database){
if(err) { return console.dir(err); }
self.data = database;
if( typeof callback === 'function' ) callback();
});
}
};
module.exports = db;
|
cemckinley/node-mud
|
server/controllers/db.js
|
JavaScript
|
gpl-3.0
| 791 |
var searchData=
[
['literal_5fpiece',['literal_piece',['../format_8h.html#acfe25efb8bb971dd9e124d9ba58dda49a4576cd306de90b968e9df7b467e9a08b',1,'format.h']]],
['long_5farg',['long_arg',['../format_8h.html#acfe25efb8bb971dd9e124d9ba58dda49a10fa003dddb41328dec4ac49dd276b08',1,'format.h']]],
['long_5fdouble_5farg',['long_double_arg',['../format_8h.html#acfe25efb8bb971dd9e124d9ba58dda49a7c832d62fac8f4277dad867cff4d0f6c',1,'format.h']]],
['long_5flong_5farg',['long_long_arg',['../format_8h.html#acfe25efb8bb971dd9e124d9ba58dda49a941086167c41858f6006e5f4a30e9441',1,'format.h']]]
];
|
StanShebs/gdb-doxy-test
|
gdbserver/search/enumvalues_6c.js
|
JavaScript
|
gpl-3.0
| 590 |
function ControladorHabitaciones() {
this.lista = Modelo.Habitaciones.lista;
this.cantidad = function() {
return Modelo.Habitaciones.lista.length;
}
this.delHabitacion = function(numero) {
Modelo.Habitaciones.quitar(numero);
}
}
function ControladorHabitacion() {
this.numero = 1;
this.doble = false;
this.addHabitacion = function() {
Modelo.Habitaciones.agregar({
numero: this.numero,
doble: this.doble
});
this.numero++;
}
}
var moduloAplicacion = angular.module("habitaciones", []);
moduloAplicacion.controller("HabitacionesController", ControladorHabitaciones);
moduloAplicacion.controller("HabitacionController", ControladorHabitacion);
|
lubicanDev/cursoMEANstack
|
_App_Node_Hoteles/webapp_angularjs_1/js/habitaciones.js
|
JavaScript
|
gpl-3.0
| 744 |
/*
* GET preguntas_respuestas listing.
*/
exports.list = function(req, res){
var id = req.params.id;
req.getConnection(function(err,connection){
connection.query('SELECT * FROM respuesta WHERE id_pregunta = ?',[id],function(err,rows) {
if(err)
console.log("Error Selecting : %s ",err );
res.send(rows);
});
});
};
/*
* ADD Respuesta
*/
exports.add = function(req, res){
var id_pregunta = req.params.id;
req.getConnection(function (err, connection) {
var data = {
texto : "Respuesta",
correcta: false,
id_pregunta:id_pregunta
};
var query = connection.query("INSERT INTO respuesta set ? ",data, function(err, rows)
{
if (err)
console.log("Error inserting : %s", err);
});
});
res.redirect('/preguntas/edit/'+id_pregunta);
};
/*
* Editando Respuesta
*/
exports.edit = function(req, res){
var id = req.params.id;
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM respuesta WHERE id = ?',[id],function(err,rows)
{
if(err)
console.log("Error Selecting : %s ",err );
res.render('edit_respuesta',{page_title:"Edita respuesta",data:rows});
});
//console.log(query.sql);
});
};
exports.delete = function(req, res){
var id = req.params.id;
req.getConnection(function(err,connection){
var query = connection.query('DELETE FROM respuesta WHERE id = ?',[id],function(err,rows)
{
if(err)
console.log("Error Selecting : %s ",err );
res.redirect('/preguntas');
});
//console.log(query.sql);
});
}
/**
* Guardando la respuesta
*/
exports.save_edit = function(req,res){
var input = JSON.parse(JSON.stringify(req.body));
var id = req.params.id;
var correcta = input.correcta;
if (correcta=="true"){
input.correcta = 1;
}else{
input.correcta = 0;
}
req.getConnection(function (err, connection) {
var data = {
id : req.params.id,
texto: input.texto,
correcta : input.correcta
};
var query = connection.query("UPDATE respuesta set ? WHERE id = ? ",[data,id], function(err, rows)
{
if (err)
console.log("Error Updating : %s ",err );
//res.redirect('/preguntas/');
});
});
// Volvemos al menu de la pregunta
req.getConnection(function (err, connection) {
var data = {
id : req.params.id,
};
var query = connection.query("SELECT id_pregunta FROM respuesta WHERE id = ? ",id, function(err, rows)
{
if (err)
console.log("Error Updating : %s ",err );
var pregunta=JSON.parse(JSON.stringify((rows)));
;
res.redirect('/preguntas/edit/'+pregunta[0].id_pregunta);
});
});
};
/**
* Obtenemos las respuestas para una pregunta
*/
exports.get_respuestas = function(req, res){
var id = req.params.id;
req.getConnection(function(err,connection){
connection.query('SELECT id, id_pregunta, texto FROM respuesta WHERE id_pregunta = ?',[id],function(err,rows) {
if(err)
console.log("Error Selecting : %s ",err );
res.send(rows);
});
});
};
/**
* Obtenemos las respuestas para una pregunta
*/
exports.get_respuesta_correcta = function(req, res){
var id = req.params.id;
req.getConnection(function(err,connection){
connection.query('SELECT id, correcta FROM respuesta WHERE correcta=1 and id_pregunta = ?',[id],function(err,rows) {
if(err)
console.log("Error Selecting : %s ",err );
res.send(rows);
});
});
};
/**
* Obtenemos si una respuesta es correcta
*/
exports.get_es_respuesta_correcta = function(req, res){
var id = req.params.id;
console.log(id);
req.getConnection(function(err,connection){
connection.query('SELECT correcta FROM respuesta WHERE id = ?',[id],function(err,rows) {
if(err)
console.log("Error Selecting : %s ",err );
res.send(rows);
});
});
};
exports.cierto_o_no = function(req, res){
var json = req.body.json;
//console.log(req.body.json[0]['pregunta']);
//console.log(JSON.parse(req.body));
for (var i = 0; i < json.length; i++) {
var id_respuesta = json[i].respuesta;
console.log(json[i]['respuesta']);
busca(req, id_respuesta);// ejecuta y no pierde el valor de id_respuesta
if (i==3) {texto="hola";}
}
}
function busca(req, id_respuesta){
req.getConnection(function(err,connection){
connection.query('SELECT correcta FROM respuesta WHERE id = ?',[id_respuesta],function(err,rows) {
if(err){
console.log("Error Selecting : %s ",err );
}
//res.send(rows);
}
);
});
}
|
aberlanas/TFG-Enigmas-Pursuit
|
enigma/routes/respuestas.js
|
JavaScript
|
gpl-3.0
| 5,430 |
var context;
context = Context();
var ride;
loadSample('../audio_samples/RIDEDA.wav', function(buffer) {
ride = buffer;
});
var ride_sequence = [1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0];
var step = 0;
setInterval(function() {
if (ride_sequence[step % ride_sequence.length] == 1) {
// playride();
}
step++;
}, 300);
function playride() {
var player = context.createBufferSource();
player.buffer = ride;
player.start();
player.loop = false;
player.connect(context.destination);
}
function loadSample(url, callback) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function() {
var audioData = request.response;
context.decodeAudioData(audioData, function(buffer) {
console.log(buffer);
callback(buffer);
});
}
request.send();
}
|
ruckert/web_audio_experiments
|
synth013/synth.js
|
JavaScript
|
gpl-3.0
| 832 |
import Lexx, { NodeTypes, NodeTypeKeys } from "xml-zero-lexer";
import XMLZeroElement from "./element";
import { seekByNodeType, getSiblings } from "./utils";
import type { Token, Tokens } from "./types";
export default class XMLZeroDOM {
// I was think about extending XMLZeroElement but that
// should have a distinct open/close element pair whereas
// this doesn't (it can have multiple root nodes) so it felt
// easier to just have a DOM class
constructor(xml: string) {
this.xml = xml;
this.tokens = Lexx(xml);
this.cache = {}; // use a weakmap?
const bindAll = fn => {
this[fn.name] = fn.bind(this);
};
}
get documentElementToken() {
this.cache.documentElementToken =
this.cache.documentElementToken ||
seekByNodeType(NodeTypes.ELEMENT_NODE, this.tokens);
// maybe i should store the index of the token so that,
// rather than erasing all cache, I can just invalidate
// caches of tokens further along this.tokens.
return this.cache.documentElementToken;
}
get documentElement() {
this.documentElementToken._element =
this.documentElementToken._element ||
new XMLZeroElement(this.xml, this.tokens, this.documentElementToken);
return this.documentElementToken._element;
}
get documentElements() {
console.log("dEs");
this.cache.documentElements =
this.cache.documentElements ||
getSiblings(this.documentElementToken, this.tokens, this.xml);
console.log("dEs after");
return this.cache.documentElements;
}
}
|
holloway/xml-zero.js
|
packages/xml-zero-dom/src/index.js
|
JavaScript
|
gpl-3.0
| 1,548 |
const expect = require('chai').expect;
const _ = require('underscore');
const Rx = require('rx');
const Game = require('../../src/game').Game;
const newPlayer = require('../../src/player').newPlayer;
const gameStarted = require('./unit-test-utils').gameStarted;
const gameStartedAnswered = require('./unit-test-utils').gameStartedAnswered;
const gameStartedAnsweredChosen = require('./unit-test-utils').gameStartedAnsweredChosen;
const gameStartedAnsweredChosenWithTwoResults = require('./unit-test-utils').gameStartedAnsweredChosenWithTwoResults;
const gameStartedAnsweredChosenWithTruthOnly = require('./unit-test-utils').gameStartedAnsweredChosenWithTruthOnly;
const gameCompleted = require('./unit-test-utils').gameCompleted;
const contains = require('./unit-test-utils').contains;
const assertResultsDoNotContainChoice = require('./unit-test-utils').assertResultsDoNotContainChoice;
const QUESTIONS = require('./unit-test-utils').QUESTIONS;
const createConfig = require('./unit-test-utils').createConfig;
const TOLERANCE_MILLIS = 3;
describe('A game', () => {
it('can be created', () => {
Game.create(createConfig());
});
describe('adding a player', () => {
it('sends the player list with that player in it', done => {
const game = Game.create(createConfig());
game.players().take(1).subscribe(players => {
expect(_.contains(players, 'bob'));
done();
});
game.addPlayer(newPlayer('bob'));
});
it('throws an error if a player already has that name', () => {
const game = Game.create(createConfig());
game.addPlayer(newPlayer('bob'));
expect(() => {
game.addPlayer(newPlayer('bob'));
}).to.throw(/EXISTING/);
});
it('throws an error if game is already started', () => {
const game = Game.create(createConfig());
game.addPlayer(newPlayer('bob'));
game.start();
expect(() => {
game.addPlayer(newPlayer('alice'));
}).to.throw(/ALREADY_STARTED/);
});
});
describe('removing a player', () => {
it('removes it from the game', done => {
const game = Game.create(createConfig());
const player = newPlayer('bob');
game.players().skip(1).take(1).subscribe(players => {
expect(players).to.eql([]);
done();
});
game.addPlayer(player);
game.removePlayer(player.socketId);
});
it('sends a player quit event', done => {
const game = Game.create(createConfig());
const player = newPlayer('bob');
game.playerQuit().take(1).subscribe(playerName => {
expect(playerName).to.eql(player.name);
done();
});
game.addPlayer(player);
game.removePlayer(player.socketId);
});
});
describe('starting a game', () => {
it('throws an error if game is already started', done => {
gameStarted(game => {
expect(() => {
game.start();
}).to.throw(/ALREADY_STARTED/);
done();
});
});
it('send one starting event per second to start, then send the first question with the number of players', done => {
const game = Game.create(createConfig());
game.starting().take(5).toArray().subscribe(seconds => {
expect(seconds).to.eql([5,4,3,2,1]);
game.questions().take(1).timeout(createConfig().millisecondsPerSecond + TOLERANCE_MILLIS).subscribe(({index, question, playerCount}) => {
expect(index).to.eql(0);
expect(question).to.eql(QUESTIONS[0].question);
expect(playerCount).to.eql(0);
done();
});
});
game.start();
});
describe('when game is cancelled before countdown reaches zero', () => {
it('stops sending starting events', done => {
const game = Game.create(createConfig());
game.starting().take(1).subscribe(() => {
done(new Error('should never be called'));
});
game.start();
game.cancel();
done();
});
it('sends the player list', done => {
const game = Game.create(createConfig());
game.players().take(1).subscribe(players => {
done();
});
game.start();
game.cancel();
});
});
// TODO : game is cancelled automatically if player quits during countdown
// Works live, but somehow unit test fails
it.skip('should cancel start if player quits suddenly', done => {
const game = Game.create(createConfig());
const player = newPlayer('bob');
game.addPlayer(player);
game.starting().take(5).toArray().subscribe(() => {
done(new Error('should never be called'));
});
game.start();
game.removePlayer(player.socketId);
});
});
describe('answering a question', () => {
it('throws an error if answer is the truth', () => {
gameStarted((game, player1, player2) => {
expect(() => {
game.answer(player1.socketId, QUESTIONS[0].answer);
}).to.throw(/TRUTH/);
});
});
it('does not send choices when everybody has not answered', () => {
gameStarted((game, player1, player2) => {
game.choices().subscribe(choices => {
fail();
});
game.answer(player1.socketId, QUESTIONS[0].answer + '1');
});
});
it('sends an answer state event with number of answers received and total expected', done => {
gameStarted((game, player1, player2) => {
game.answerState().take(1).subscribe(answerState => {
expect(_.isEqual(answerState, { count: 1, total: 2 })).to.eql(true);
done();
});
game.answer(player1.socketId, QUESTIONS[0].answer + '1');
});
});
});
describe('when every player has answered, sends a choice array', () => {
const TRUTH = QUESTIONS[0].answer;
const ANSWERS = { player1: TRUTH + '1', player2: TRUTH + '1' };
it('along with the number of players', done => {
gameStartedAnswered(ANSWERS, (game, player1, player2, { choices, playerCount }) => {
expect(playerCount).to.eql(2);
done();
});
});
it('containing the truth', done => {
gameStartedAnswered(ANSWERS, (game, player1, player2, { choices, playerCount }) => {
expect(choices).to.contain(TRUTH);
done();
});
});
it('containing unique choices', done => {
gameStartedAnswered(ANSWERS, (game, player1, player2, { choices, playerCount }) => {
expect(choices.length).to.eql(_.uniq(choices).length);
done();
});
});
it('containing the answer of each player', done => {
gameStartedAnswered(ANSWERS, (game, player1, player2, { choices, playerCount }) => {
expect(choices).to.contain(player1.lastAnswer);
expect(choices).to.contain(player2.lastAnswer);
done();
});
});
describe('choosing', () => {
it('sends a choice state event with number of choices received and total expected', done => {
gameStartedAnswered(ANSWERS, (game, player1, player2) => {
game.choiceState().take(1).subscribe(choiceState => {
expect(_.isEqual(choiceState, { count: 1, total: 2 })).to.eql(true);
done();
});
game.choose(player1.socketId, QUESTIONS[0].answer + '1');
});
});
});
});
describe('when every player has chosen, sends the results', () => {
const TRUTH = QUESTIONS[0].answer;
it('one by one', done => {
const TRUTH = QUESTIONS[0].answer;
const ANSWERS = { player1: TRUTH + '1', player2: TRUTH + '2' };
const CHOICES = { player1: TRUTH + '2', player2: TRUTH + '1' };
gameStartedAnsweredChosen(ANSWERS, CHOICES, (game, player1, player2, results) => {
expect(_.isEqual(results[0], { choice: ANSWERS.player1, authors: [player1.name], choosedBy: [player2.name] })).to.eql(true);
expect(_.isEqual(results[1], { choice: ANSWERS.player2, authors: [player2.name], choosedBy: [player1.name] })).to.eql(true);
done();
});
});
it('giving 1000 points to each player who found the truth', done => {
const ANSWERS = { player1: TRUTH + '1', player2: TRUTH + '2' };
const CHOICES = { player1: TRUTH, player2: TRUTH + '2' };
gameStartedAnsweredChosenWithTwoResults(ANSWERS, CHOICES, (game, player1, player2) => {
expect(player1.score).to.eql(1000);
expect(player2.score).to.eql(0);
done();
});
});
it('giving 500 points to each player who authored a choice picked by others', done => {
const ANSWERS = { player1: TRUTH + '1', player2: TRUTH + '2' };
const CHOICES = { player1: TRUTH + '1', player2: TRUTH + '1' };
gameStartedAnsweredChosenWithTwoResults(ANSWERS, CHOICES, (game, player1, player2) => {
expect(player1.score).to.eql(500);
expect(player2.score).to.eql(0);
done();
});
});
it('giving 0 points to each player who picked his own choice', done => {
const ANSWERS = { player1: TRUTH + '1', player2: TRUTH + '2' };
const CHOICES = { player1: TRUTH + '1', player2: TRUTH + '2' };
gameStartedAnsweredChosen(ANSWERS, CHOICES, (game, player1, player2) => {
expect(player1.score).to.eql(0);
expect(player2.score).to.eql(0);
done();
});
});
it('containing a result for the truth and who chose it', done => {
const ANSWERS = { player1: TRUTH + '1', player2: TRUTH + '2' };
const CHOICES = { player1: TRUTH, player2: TRUTH };
gameStartedAnsweredChosenWithTruthOnly(ANSWERS, CHOICES, (game, player1, player2, results) => {
expect(contains(results, { choice: TRUTH, authors: ['TRUTH'], choosedBy: [player1.name, player2.name] })).to.eql(true);
done();
});
});
it('containing a result for each player answer chosen by at least one person', done => {
const ANSWERS = { player1: TRUTH + '1', player2: TRUTH + '2' };
const CHOICES = { player1: TRUTH + '2', player2: TRUTH + '1' };
gameStartedAnsweredChosen(ANSWERS, CHOICES, (game, player1, player2, results) => {
expect(contains(results, { choice: ANSWERS.player1, authors: [player1.name], choosedBy: [player2.name] })).to.eql(true);
expect(contains(results, { choice: ANSWERS.player2, authors: [player2.name], choosedBy: [player1.name] })).to.eql(true);
done();
});
});
it('not containing a result for player answers chosen by nobody', done => {
const ANSWERS = { player1: TRUTH + '1', player2: TRUTH + '2' };
const CHOICES = { player1: TRUTH + '2', player2: TRUTH + '2' };
gameStartedAnsweredChosenWithTwoResults(ANSWERS, CHOICES, (game, player1, player2, results) => {
assertResultsDoNotContainChoice(ANSWERS.player1, results);
done();
});
});
it('containing result with multiple authors if answer was authored by more than one player', done => {
const ANSWERS = { player1: TRUTH + '1', player2: TRUTH + '1' };
const CHOICES = { player1: TRUTH + '1', player2: TRUTH };
gameStartedAnsweredChosenWithTwoResults(ANSWERS, CHOICES, (game, player1, player2, results) => {
expect(contains(results, { choice: CHOICES.player1, authors: [player1.name, player2.name], choosedBy: [player1.name] })).to.eql(true);
done();
});
});
});
describe('after results are sent', () => {
it('send scores, in order, with an entry for every player', done => {
const TRUTH = QUESTIONS[0].answer;
const ANSWERS = { player1: TRUTH + '1', player2: TRUTH + '2' };
const CHOICES = { player1: TRUTH + '2', player2: TRUTH };
gameStartedAnsweredChosenWithTwoResults(ANSWERS, CHOICES, (game, player1, player2, results, scores) => {
expect(_.isEqual(scores.array, [
{ name: 'alice', score: 1500 },
{ name: 'bob', score: 0 }
])).to.eql(true);
expect(scores.final).to.eql(false);
done();
});
});
it('after sending scores, should wait for specified time before sending new question', done => {
const TRUTH = QUESTIONS[0].answer;
const ANSWERS = { player1: TRUTH + '1', player2: TRUTH + '1' };
const CHOICES = { player1: TRUTH + '1', player2: TRUTH };
gameStartedAnswered(ANSWERS, (game, player1, player2) => {
game.questions().take(1).subscribe(() => {
done();
});
game.choose(player1.socketId, CHOICES.player1);
game.choose(player2.socketId, CHOICES.player2);
});
});
});
describe('after scores are sent, when there are still more questions', () => {
describe('when there are more questions', () => {
it('sends the next question', done => {
const TRUTH = QUESTIONS[0].answer;
const ANSWERS = { player1: TRUTH + '1', player2: TRUTH + '1' };
const CHOICES = { player1: TRUTH + '1', player2: TRUTH };
gameStartedAnswered(ANSWERS, (game, player1, player2) => {
game.scores().take(1).delay(1).subscribe(() => {
game.questions().take(1).subscribe(({question, index, playerCount}) => {
expect(index).to.eql(1);
expect(question).to.eql(QUESTIONS[1].question);
expect(playerCount).to.eql(2);
done();
});
});
game.choose(player1.socketId, CHOICES.player1);
game.choose(player2.socketId, CHOICES.player2);
});
});
});
describe('when there are no more questions', () => {
it('scores are marked as final', done => {
const TRUTH = QUESTIONS[0].answer;
const ANSWERS = { player1: TRUTH + '1', player2: TRUTH + '2' };
const CHOICES = { player1: TRUTH + '2', player2: TRUTH + '1' };
gameCompleted(ANSWERS, CHOICES, (game, player1, player2, scores) => {
expect(scores.final).to.eql(true);
done();
});
});
});
})
});
|
francois-roseberry/question-game-websocket
|
server/test/unit/game.test.js
|
JavaScript
|
gpl-3.0
| 13,946 |
import Style from './converter'
export default class Section extends Style.Properties{
size(x){
this.set("page-width",`${x.width}pt`)
this.set("page-height", `${x.height}pt`)
}
margin(x){
this.set("margin-left",x.left+'pt')
this.set("margin-right",x.right+'pt')
this.set("margin-top",x.top+'pt')
this.set("margin-bottom",x.bottom+'pt')
if(x.gutter){
let gutter='padding'+(x.gutterAtRight ? 'Right' : 'Left')
this.set(gutter,x[(x.gutterAtRight ? 'right' : 'left')]+x.gutter+'pt')
}
}
cols(x){
}
}
|
lalalic/docx2xsl
|
src/style/section.js
|
JavaScript
|
gpl-3.0
| 528 |
$.getScript('https://sandbox.advantage-apps.com/fhstp-bewerbungstool-up3v/responsive.js', function()
{
// script should now be loaded an executed.
// put your dependent JS here.
});
|
FH-Complete/FHC-AddOn-Aufnahme
|
cis/themes/fhstp/global.js
|
JavaScript
|
gpl-3.0
| 184 |
(function(){
'use strict';
angular.module('musicHub')
.factory('ArtistService', artistService);
artistService.$inject = ['$resource', 'API_URL'];
function artistService($resource, API_URL) {
return $resource(
API_URL + '/artists/:id',
{},
{}
);
}
})();
|
manufarfaro/musichub-app
|
app/js/services/artist-service.js
|
JavaScript
|
gpl-3.0
| 298 |
import { Promise as EmberPromise, resolve } from 'rsvp';
import { computed } from '@ember/object';
import { isEmpty } from '@ember/utils';
import { alias } from '@ember/object/computed';
import { inject as controller } from '@ember/controller';
import AbstractEditController from 'hospitalrun/controllers/abstract-edit-controller';
import AddNewPatient from 'hospitalrun/mixins/add-new-patient';
import FulfillRequest from 'hospitalrun/mixins/fulfill-request';
import InventoryLocations from 'hospitalrun/mixins/inventory-locations'; // inventory-locations mixin is needed for fulfill-request mixin!
import PatientSubmodule from 'hospitalrun/mixins/patient-submodule';
import UserSession from 'hospitalrun/mixins/user-session';
export default AbstractEditController.extend(AddNewPatient, FulfillRequest, InventoryLocations, PatientSubmodule, UserSession, {
medicationController: controller('medication'),
expenseAccountList: alias('medicationController.expenseAccountList'),
canFulfill: computed(function() {
return this.currentUserCan('fulfill_medication');
}),
isFulfilled: computed('model.status', function() {
let status = this.get('model.status');
return (status === 'Fulfilled');
}),
isFulfilling: computed('canFulfill', 'model.isRequested', 'model.shouldFulfillRequest', function() {
let canFulfill = this.get('canFulfill');
let isRequested = this.get('model.isRequested');
let fulfillRequest = this.get('model.shouldFulfillRequest');
let isFulfilling = canFulfill && (isRequested || fulfillRequest);
this.get('model').set('isFulfilling', isFulfilling);
return isFulfilling;
}),
isFulfilledOrRequested: computed('isFulfilled', 'model.isRequested', function() {
return (this.get('isFulfilled') || this.get('model.isRequested'));
}),
prescriptionClass: computed('model.quantity', function() {
let quantity = this.get('model.quantity');
if (isEmpty(quantity)) {
return 'required test-medication-prescription';
}
}),
quantityClass: computed('isFulfilling', 'model.prescription', function() {
let prescription = this.get('model.prescription');
let returnClass = 'col-xs-3';
let isFulfilling = this.get('isFulfilling');
if (isFulfilling || isEmpty(prescription)) {
returnClass += ' required';
}
return `${returnClass} test-quantity-input`;
}),
quantityLabel: computed('isFulfilled', function() {
let intl = this.get('intl');
let returnLabel = intl.t('medication.labels.quantityRequested');
let isFulfilled = this.get('isFulfilled');
let isFulfilling = this.get('isFulfilling');
if (isFulfilling) {
returnLabel = intl.t('medication.labels.quantityDispensed');
} else if (isFulfilled) {
returnLabel = intl.t('medication.labels.quantityDistributed');
}
return returnLabel;
}),
medicationList: [],
updateCapability: 'add_medication',
afterUpdate() {
let intl = this.get('intl');
let alertTitle, alertMessage;
let isFulfilled = this.get('isFulfilled');
if (isFulfilled) {
alertTitle = intl.t('medication.alerts.fulfilledTitle');
alertMessage = 'The medication request has been fulfilled.';
this.set('model.selectPatient', false);
} else {
alertTitle = intl.t('medication.alerts.savedTitle');
alertMessage = intl.t('medication.alerts.savedMessage');
}
this.saveVisitIfNeeded(alertTitle, alertMessage);
},
beforeUpdate() {
let isFulfilling = this.get('isFulfilling');
let isNew = this.get('model.isNew');
if (isNew || isFulfilling) {
return new EmberPromise(function(resolve, reject) {
let newMedication = this.get('model');
newMedication.validate().then(function() {
if (newMedication.get('isValid')) {
if (isNew) {
if (isEmpty(newMedication.get('patient'))) {
this.addNewPatient();
reject({
ignore: true,
message: 'creating new patient first'
});
} else {
newMedication.set('medicationTitle', newMedication.get('inventoryItem.name'));
newMedication.set('priceOfMedication', newMedication.get('inventoryItem.price'));
newMedication.set('status', 'Requested');
newMedication.set('requestedBy', newMedication.getUserName());
newMedication.set('requestedDate', new Date());
this.addChildToVisit(newMedication, 'medication', 'Pharmacy').then(function() {
this.finishBeforeUpdate(isFulfilling, resolve);
}.bind(this), reject);
}
} else {
this.finishBeforeUpdate(isFulfilling, resolve);
}
} else {
this.send('showDisabledDialog');
reject('invalid model');
}
}.bind(this)).catch(function() {
this.send('showDisabledDialog');
reject('invalid model');
}.bind(this));
}.bind(this));
} else {
return resolve();
}
},
finishBeforeUpdate(isFulfilling, resolve) {
if (isFulfilling) {
let inventoryLocations = this.get('model.inventoryLocations');
let inventoryRequest = this.get('store').createRecord('inv-request', {
expenseAccount: this.get('model.expenseAccount'),
dateCompleted: new Date(),
inventoryItem: this.get('model.inventoryItem'),
inventoryLocations,
quantity: this.get('model.quantity'),
transactionType: 'Fulfillment',
patient: this.get('model.patient'),
markAsConsumed: true
});
this.performFulfillRequest(inventoryRequest, false, false, true).then(function() {
this.set('model.status', 'Fulfilled');
resolve();
}.bind(this));
} else {
resolve();
}
},
showUpdateButton: computed('updateCapability', 'isFulfilled', function() {
let isFulfilled = this.get('isFulfilled');
if (isFulfilled) {
return false;
} else {
return this._super();
}
}),
updateButtonText: computed('model.isNew', 'isFulfilling', 'model.hideFulfillRequest', function() {
let intl = this.get('intl');
if (this.get('model.hideFulfillRequest')) {
return intl.t('buttons.dispense');
} else if (this.get('isFulfilling')) {
return intl.t('labels.fulfill');
}
return this._super();
})
});
|
HospitalRun/frontend
|
app/medication/edit/controller.js
|
JavaScript
|
gpl-3.0
| 6,445 |
/*
Copyright (C) 2013 Tony Mobily
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
[ ] Write tests
*/
const CircularJSON = require('circular-json')
const SimpleSchema = class {
constructor (structure, options) {
this.structure = structure
this.options = options || {}
}
// Built-in types
// definition, value, fieldName, options, failedCasts
noneType (p) {
return p.value
}
stringType (p) {
if (typeof p.value === 'undefined' || p.value === null) return ''
// No toString() available: failing to cast
if (typeof (p.value.toString) === 'undefined') {
throw this._typeError(p.fieldName)
}
// Return cast value, trimmed by default (unless noTrim is passed to the definition)
const r = p.value.toString()
return p.definition.noTrim ? r : r.trim()
}
blobType (p) {
return p.value
}
numberType (p) {
if (typeof (p.value) === 'undefined') return 0
// If Number() returns NaN, fail
const r = Number(p.value)
if (isNaN(r)) {
throw this._typeError(p.fieldName)
}
// Return cast value
return r
}
// This is like "number", but it will set timestamp as NULL for empty strings
timestampType (p) {
// If Number() returns NaN, fail
const r = Number(p.value)
if (isNaN(r)) {
throw this._typeError(p.fieldName)
}
// Return cast value
return r
}
dateType (p) {
// Undefined: return a new date object
if (typeof (p.value) === 'undefined') {
return new Date()
}
// If new Date() returns NaN, date was not corect, fail
const r = new Date(p.value)
if (isNaN(r)) {
throw this._typeError(p.fieldName)
}
// return cast value
return r
}
arrayType (p) {
return Array.isArray(p.value) ? p.value : [p.value]
}
serializeType (p) {
let r
if (p.options.deserialize) {
if (typeof (p.value) !== 'string') {
throw this._typeError(p.fieldName)
}
try {
// Attempt to stringify
r = CircularJSON.parse(p.value)
// It worked: return r
return r
} catch (e) {
throw this._typeError(p.fieldName)
}
} else {
try {
r = CircularJSON.stringify(p.value)
// It worked: return r
return r
} catch (e) {
throw this._typeError(p.fieldName)
}
//
}
}
booleanType (p) {
if (typeof (p.value) === 'string') {
if (p.value === (p.definition.stringFalseWhen || 'false')) return false
else if ((p.value === (p.definition.stringTrueWhen || 'true')) || (p.value === (p.definition.stringTrueWhen || 'on'))) return true
else return false
} else {
return !!p.value
}
}
// Cast an ID for this particular engine. If the object is in invalid format, it won't
// get cast, and as a result check will fail
idType (p) {
const n = parseInt(p.value)
if (isNaN(n)) {
throw this._typeError(p.fieldName)
} else {
return n
}
}
// Built-in parameters
minParam (p) {
if (typeof p.value === 'undefined') return
if (p.definition.type === 'number' && typeof p.value === 'number' && Number(p.value) < p.parameterValue) {
throw this._paramError(p.fieldName, "Field's value is too low")
}
if (p.definition.type === 'string' && p.value.toString && p.value.toString().length < p.parameterValue) {
throw this._paramError(p.fieldName, 'Field is too short')
}
}
maxParam (p) {
if (typeof p.value === 'undefined') return
if (p.definition.type === 'number' && typeof p.value === 'number' && Number(p.value) > p.parameterValue) {
throw this._paramError(p.fieldName, "Field's value is too high")
}
if (p.definition.type === 'string' && p.value.toString && p.value.toString().length > p.parameterValue) {
throw this._paramError(p.fieldName, 'Field is too long')
}
}
validatorParam (p) {
if (typeof (p.parameterValue) !== 'function') {
throw (new Error('Validator function needs to be a function, found: ' + typeof (p.parameterValue)))
}
const r = p.parameterValue(p.object[p.fieldName], p.object, { schema: this, fieldName: p.fieldName})
if (typeof (r) === 'string') throw this._paramError(p.fieldName, r)
}
uppercaseParam (p) {
if (p.definition.type !== 'string' || typeof p.value !== 'string') return
return p.value.toUpperCase()
}
lowercaseParam (p) {
if (p.definition.type !== 'string' || typeof p.value !== 'string') return
return p.value.toLowerCase()
}
trimParam (p) {
// For strings, trim works as intended: it will trim the cast string
if (p.definition.type === 'string' && typeof p.value === 'string') {
return p.value.substr(0, p.parameterValue)
// For non-string values, it will however check the original value. If it's longer than it should, it will puke
} else {
if (Number.isInteger(Number(p.valueBeforeCast)) && String(Number(p.valueBeforeCast)).length > p.parameterValue) throw this._paramError(p.fieldName, 'Value out of range')
}
}
defaultParam (p) {
let v
if (typeof (p.valueBeforeCast) === 'undefined') {
if (typeof (p.parameterValue) === 'function') {
v = p.parameterValue(p)
} else {
v = p.parameterValue
}
return v
}
}
notEmptyParam (p) {
const bc = p.valueBeforeCast
const bcs = (typeof bc !== 'undefined' && bc !== null && bc.toString ? bc.toString() : '')
if (p.parameterValue && !Array.isArray(p.value) && typeof (bc) !== 'undefined' && bcs === '') {
throw this._paramError(p.fieldName, 'Field cannot be empty')
}
}
_typeError (field) {
const e = new Error('Error with field: ' + field)
e.errorObject = { field, message: 'Error during casting' }
return e
}
_paramError (field, message) {
const e = new Error(message)
e.errorObject = { field, message }
return e
}
// Options:
//
// * options.onlyObjectValues -- Will apply cast for existing object's keys rather than the schema itself
// * options.skipFields -- To know what casts need to be skipped
// * options.skipParams -- Won't apply specific params for specific fields
// * options.emptyAsNull -- Empty string values will be cast to null (also as a per-field option)
// * options.canBeNull -- All values can be null (also as a per-field option)
//
// * Common parameters for every type
// * required -- the field is required
// * canBeNull -- the "null" value is always accepted
// * emptyAsNull -- an empty string will be stored as null
//
// This will run _cast and _param
async validate (object, options) {
const errors = []
let skipBoth
let skipCast
let targetObject
let fieldName
let result
function emptyString (s) {
return String(s) === ''
}
// Copy object over
const validatedObject = Object.assign({}, object)
options = options || {}
// Check for spurious fields not in the schema
for (fieldName in object) {
if (typeof this.structure[fieldName] === 'undefined') {
errors.push({ field: fieldName, message: 'Field not allowed' })
}
}
// Set the targetObject. If the target is the object itself,
// then missing fields won't be a problem
if (options.onlyObjectValues) targetObject = object
else targetObject = this.structure
for (fieldName in targetObject) {
const definition = this.structure[fieldName]
if (!definition) continue
// The checking logic will check if cast -- or both cast and params --
// should be skipped
skipCast = false
skipBoth = false
let canBeNull
if (definition.default === null) canBeNull = true
else if (typeof definition.canBeNull !== 'undefined') canBeNull = definition.canBeNull
else if (typeof options.canBeNull !== 'undefined') canBeNull = !!options.canBeNull
else canBeNull = false
let emptyAsNull
if (typeof definition.emptyAsNull !== 'undefined') emptyAsNull = definition.emptyAsNull
else if (typeof options.emptyAsNull !== 'undefined') emptyAsNull= !!options.emptyAsNull
else emptyAsNull = false
// If emptyAsNull is set, then canBeNull is implicitly set
if (emptyAsNull) {
canBeNull = true
}
// Skip cast/param if so required by the skipFields array
if (Array.isArray(options.skipFields) && options.skipFields.indexOf(fieldName) !== -1) {
skipBoth = true
}
// Skip castParam if value is `undefined` AND it IS required (enriching error)
// NOTE: this won't happen if 'required' is in the list of parameters to be skipped
if (definition.required && typeof (object[fieldName]) === 'undefined') {
if (!this._paramToBeSkipped('required', options.skipParams, fieldName)) {
skipBoth = true
errors.push({ field: fieldName, message: 'Field required' })
}
}
// Skip casting if value is `undefined` AND it's not required
if (!definition.required && typeof (object[fieldName]) === 'undefined') {
skipCast = true
}
// Empty string: check if it should be forced to null
if (emptyString(object[fieldName])) {
if (emptyAsNull) {
validatedObject[fieldName] = null
skipBoth = true
}
}
// If it's null, then really check: either canBeNull is true, or return with a message
if (object[fieldName] === null) {
skipBoth = true
if (!canBeNull) {
errors.push({ field: fieldName, message: 'Field cannot be null' })
}
}
// If cast is skipped for whatever reason, params will never go through either
if (skipBoth) continue
if (!skipCast) {
// Run the xxxType function for a specific type
if (typeof (this[definition.type + 'Type']) === 'function') {
try {
result = await this[definition.type + 'Type']({
definition,
value: object[fieldName],
fieldName,
object: validatedObject,
objectBeforeCast: object,
valueBeforeCast: object[fieldName],
definitionName: definition.type,
options,
computedOptions: {
emptyAsNull,
canBeNull
}
})
} catch (e) {
if (!e.errorObject) throw e
errors.push(e.errorObject)
}
if (typeof result !== 'undefined') validatedObject[fieldName] = result
} else {
throw (new Error('No casting function found, type probably wrong: ' + definition.type))
}
}
for (const parameterName in this.structure[fieldName]) {
//
// If it's to be skipped, we shall skip -- e.g. `options.skipParams == { tabId: ['required'] }` to
// skip `required` parameter for `tabId` field
if (this._paramToBeSkipped(parameterName, options.skipParams, fieldName)) continue
if (parameterName !== 'type' && typeof (this[parameterName + 'Param']) === 'function') {
try {
result = await this[parameterName + 'Param']({
definition,
value: validatedObject[fieldName],
fieldName,
object: validatedObject,
objectBeforeCast: object,
valueBeforeCast: object[fieldName],
parameterName,
parameterValue: definition[parameterName],
options: options,
computedOptions: {
emptyAsNull,
canBeNull
}
})
} catch (e) {
if (!e.errorObject) throw e
errors.push(e.errorObject)
}
if (typeof (result) !== 'undefined') validatedObject[fieldName] = result
}
}
}
return { validatedObject, errors }
}
_paramToBeSkipped (parameterName, skipParams, fieldName) {
if (typeof (skipParams) !== 'object' || skipParams === null) return false
if (Array.isArray(skipParams[fieldName]) && skipParams.indexOf(parameterName) !== -1) return true
return false
}
cleanup (object, parameterName) {
const newObject = {}
for (const k in object) {
if (!this.structure[k]) continue
if (this.structure[k][parameterName]) {
delete object[k]
newObject[k] = object[k]
}
}
return newObject
}
}
exports = module.exports = SimpleSchema
/*
let s = new SimpleSchema({
level: { type: 'number', default: 10 },
name: { type: 'string', trim: 50 },
surname: { type: 'string', required: true, trim: 10 },
age: { type: 'number', min: 10, max: 20 }
})
let { validatedObject, errors } = s.validate({ name: 'Tony', surname: 'Mobily1234567890' }, { __onlyObjectValues: true })
console.log('RESULT:', validatedObject, errors)
*/
|
mercmobily/SimpleSchema
|
simpleschema.js
|
JavaScript
|
gpl-3.0
| 14,014 |
/**
* Admin/CategoryController
*/
module.exports = {
index: function(req, res, next) {
res.locals.config = {};
res.locals.headers = {
'breadcrumb': [{
name: "后台首页",
link: "/admin/main"
}],
'title': '栏目管理',
'description': "目前暂时支持2级栏目",
'parent_purview': "content",
'purview': "category"
};
res.locals.data = [];
Category.getTree({}).then(function(data) {
res.locals.data = data;
return res.view();
});
},
add: function(req, res, next) {
res.locals.headers = {
'breadcrumb': [{
name: "后台首页",
link: "/admin/main"
}, {
name: "栏目管理",
link: "/admin/category"
}],
'title': '添加栏目',
'description': "",
'parent_purview': "content",
'purview': "category"
};
res.locals.category = {};
// 获取模型列表
Models
.find({status: 1})
.sort("listorder ASC")
.then(function(data) {
res.locals.models = data;
return Category.getTree({});
})
.then(function(categorys) {
res.locals.categorys = categorys;
if(req.method == "POST"){
req.body.lang = "zh_cn";
Category.create(req.body).then(function(records){
console.log(records)
req.session.flash = {
succ: "添加成功!"
};
return res.redirect("/admin/category/index");
},function(err){
console.log(err)
res.locals.flash = {
error: "添加失败!"
};
res.locals.category = req.body;
return res.view();
});
}else{
return res.view();
}
}, function(err) {
return next(err);
});
},
update:function(req,res,next){
res.locals.headers = {
'breadcrumb': [{
name: "后台首页",
link: "/admin/main"
}, {
name: "栏目管理",
link: "/admin/category"
}],
'title': '编辑栏目',
'description': "",
'parent_purview': "content",
'purview': "category"
};
var id = req.param("id");
if(!id){
req.session.flash = {
error: "资源未找到"
};
return res.redirect("back");
}
Category.findOne({id:id}).then(function(category){
res.locals.category = category;
return Models.find({status: 1}).sort("listorder ASC");
})
.then(function(models){
res.locals.models = models;
return Category.getTree({id:{"!":id}});
})
.then(function(categorys){
res.locals.categorys = categorys;
if(req.method == "POST"){
req.body.lang = "zh_cn";
Category.update({id:id},req.body).then(function(records){
req.session.flash = {
succ: "修改成功!"
};
return res.redirect("/admin/category/index");
},function(err){
res.locals.flash = {
error: "修改失败!"
};
res.locals.category = req.body;
return res.view();
});
}else{
return res.view();
}
},function(err){
return next(err);
});
},
delete: function(req, res, next) {
var id = req.param("id");
if (!id) {
req.session.flash = {
error: "资源未找到"
};
return res.redirect("back");
}
Category.destroy({
id: id
}).then(function(data) {
if (data) {
req.session.flash = {
succ: "删除成功"
};
} else {
req.session.flash = {
error: "删除错误"
};
}
return res.redirect("back");
});
}
};
|
SJTUYale/GPS
|
api/controllers/Admin/CategoryController.js
|
JavaScript
|
gpl-3.0
| 3,460 |
/*
* This file is part of the AuScope Virtual Rock Lab (VRL) project.
* Copyright (c) 2010 The University of Queensland, ESSCC
*
* Licensed under the terms of the GNU Lesser General Public License.
*/
Ext.namespace('VRL.SeriesBrowser');
VRL.SeriesBrowser = {
// a template for the description html area
descTpl: new Ext.Template(
'<p class="jobdesc-title">{name}</p>',
'<p class="jobdesc-key">Description:</p><br/><p>{description}</p>',
{
compiled: true,
disableFormats: true
}
),
updateDetails: function(node) {
if (node.leaf) {
node.attributes.name = node.parentNode.attributes.name
+' (Revision '+node.attributes.revision+')';
}
var descEl = Ext.getCmp('sb-details-panel').body;
this.descTpl.overwrite(descEl, node.attributes);
},
show: function(callback, doExamples) {
var detailsPanel = new Ext.Panel({
id: 'sb-details-panel',
title: 'Details',
bodyStyle: 'padding:10px',
region: 'west',
width: '220',
collapsible: false,
split: true
});
function dateRenderer(value, cell, record) {
return Ext.util.Format.date(new Date(value), 'd M Y, g:i:s a');
}
function dateSorter(node) {
return parseInt(node.attributes.date, 10);
}
var seriesTree = new Ext.ux.tree.TreeGrid({
title: 'Series',
id: 'sb-tree',
region: 'center',
split: true,
enableSort: true,
singleExpand: true,
columns: [
{ header: 'Name/Revision', width: 160, dataIndex: 'name' },
{ header: 'Date Created', width: 160, dataIndex: 'date',
sortType: dateSorter, renderer: dateRenderer }
],
loader: new Ext.tree.TreeLoader({
baseParams: {
'action': 'listSeries',
'demo': doExamples || false
},
dataUrl: VRL.controllerURL
}),
root: new Ext.tree.AsyncTreeNode({id:'series-root'}),
listeners: {
scope: this,
'click': function(node, e) {
if (!node.isSelected()) {
node.select();
Ext.getCmp('sb-open-btn').enable();
this.updateDetails(node);
}
},
'load': function(loader, node, response) {
seriesTree.treeLoadMask.hide();
},
'loadexception': function(loader, node, response) {
seriesTree.treeLoadMask.hide();
VRL.onLoadException(
loader, 'remote', null, null, response);
}
}
});
seriesTree.getLoader().on('beforeload',
function(loader, node, callback) {
if (!seriesTree.treeLoadMask) {
seriesTree.treeLoadMask = new Ext.LoadMask('sb-tree', {
msg: 'Loading data, please wait...'
});
}
seriesTree.treeLoadMask.show();
},
this,
{ delay: 1 }
);
var w = new Ext.Window({
title: 'VRL Series Browser',
modal: true,
layout: 'border',
closable: false,
constrain: true,
constrainHeader: true,
initHidden: false,
width: 600,
height: 400,
buttons: [{
text: 'Cancel',
handler: function() {
w.on({'close': callback.createCallback()});
w.close();
}
}, {
text: 'Open',
id: 'sb-open-btn',
disabled: true,
handler: function() {
w.on({'close': callback.createCallback(
seriesTree.getSelectionModel().
getSelectedNode().attributes)});
w.close();
}
}],
items: [
detailsPanel,
seriesTree
]
});
}
}
|
AuScope/VirtualRockLab
|
src/main/webapp/js/SeriesBrowser.js
|
JavaScript
|
gpl-3.0
| 3,954 |
import { App } from '../components/app/app';
import { IonicApp } from '../components/app/app-root';
import { Config } from '../config/config';
import { DeepLinker } from '../navigation/deep-linker';
import { Form } from './form';
import { GestureController } from '../gestures/gesture-controller';
import { Keyboard } from './keyboard';
import { Menu } from '../components/menu/menu';
import { ViewState } from '../navigation/nav-util';
import { OverlayPortal } from '../components/nav/overlay-portal';
import { PageTransition } from '../transitions/page-transition';
import { Platform } from '../platform/platform';
import { QueryParams } from '../platform/query-params';
import { Tab } from '../components/tabs/tab';
import { Tabs } from '../components/tabs/tabs';
import { TransitionController } from '../transitions/transition-controller';
import { UrlSerializer } from '../navigation/url-serializer';
import { ViewController } from '../navigation/view-controller';
import { NavControllerBase } from '../navigation/nav-controller-base';
export const mockConfig = function (config, url = '/', platform) {
const c = new Config();
const q = mockQueryParams();
const p = platform || mockPlatform();
c.init(config, q, p);
return c;
};
export const mockQueryParams = function (url = '/') {
return new QueryParams(url);
};
export const mockPlatform = function () {
return new Platform();
};
export const mockApp = function (config, platform) {
platform = platform || mockPlatform();
config = config || mockConfig(null, '/', platform);
let app = new App(config, platform);
mockIonicApp(app, config, platform);
return app;
};
export const mockIonicApp = function (app, config, platform) {
let appRoot = new IonicApp(null, null, mockElementRef(), mockRenderer(), config, platform, app);
appRoot._loadingPortal = mockOverlayPortal(app, config, platform);
appRoot._toastPortal = mockOverlayPortal(app, config, platform);
appRoot._overlayPortal = mockOverlayPortal(app, config, platform);
return appRoot;
};
export const mockTrasitionController = function (config) {
let trnsCtrl = new TransitionController(config);
trnsCtrl.get = (trnsId, enteringView, leavingView, opts) => {
let trns = new PageTransition(enteringView, leavingView, opts, (callback) => {
callback();
});
trns.trnsId = trnsId;
return trns;
};
return trnsCtrl;
};
export const mockZone = function () {
let zone = {
run: function (cb) {
cb();
},
runOutsideAngular: function (cb) {
cb();
}
};
return zone;
};
export const mockChangeDetectorRef = function () {
let cd = {
reattach: () => { },
detach: () => { },
detectChanges: () => { }
};
return cd;
};
export class MockElementRef {
constructor() {
this.nativeElement = new MockElement();
}
}
export class MockElement {
constructor() {
this.children = [];
this.classList = new ClassList();
this.attributes = {};
this.style = {};
this.clientWidth = 0;
this.clientHeight = 0;
this.clientTop = 0;
this.clientLeft = 0;
this.offsetWidth = 0;
this.offsetHeight = 0;
this.offsetTop = 0;
this.offsetLeft = 0;
this.scrollTop = 0;
this.scrollHeight = 0;
}
get className() {
return this.classList.classes.join(' ');
}
set className(val) {
this.classList.classes = val.split(' ');
}
hasAttribute(name) {
return !!this.attributes[name];
}
getAttribute(name) {
return this.attributes[name];
}
setAttribute(name, val) {
this.attributes[name] = val;
}
removeAttribute(name) {
delete this.attributes[name];
}
}
export class ClassList {
constructor() {
this.classes = [];
}
add(className) {
if (!this.contains(className)) {
this.classes.push(className);
}
}
remove(className) {
const index = this.classes.indexOf(className);
if (index > -1) {
this.classes.splice(index, 1);
}
}
toggle(className) {
if (this.contains(className)) {
this.remove(className);
}
else {
this.add(className);
}
}
contains(className) {
return this.classes.indexOf(className) > -1;
}
}
export const mockElementRef = function () {
return new MockElementRef();
};
export class MockRenderer {
setElementAttribute(renderElement, name, val) {
if (name === null) {
renderElement.removeAttribute(name);
}
else {
renderElement.setAttribute(name, val);
}
}
setElementClass(renderElement, className, isAdd) {
if (isAdd) {
renderElement.classList.add(className);
}
else {
renderElement.classList.remove(className);
}
}
setElementStyle(renderElement, styleName, styleValue) {
renderElement.style[styleName] = styleValue;
}
}
export const mockRenderer = function () {
const renderer = new MockRenderer();
return renderer;
};
export const mockLocation = function () {
let location = {
path: () => { return ''; },
subscribe: () => { },
go: () => { },
back: () => { }
};
return location;
};
export const mockView = function (component, data) {
if (!component) {
component = MockView;
}
let view = new ViewController(component, data);
view.init(mockComponentRef());
return view;
};
export const mockViews = function (nav, views) {
nav._views = views;
views.forEach(v => v._setNav(nav));
};
export const mockComponentRef = function () {
let componentRef = {
location: mockElementRef(),
changeDetectorRef: mockChangeDetectorRef(),
destroy: () => { }
};
return componentRef;
};
export const mockDeepLinker = function (linkConfig = null, app) {
let serializer = new UrlSerializer(linkConfig);
let location = mockLocation();
return new DeepLinker(app || mockApp(), serializer, location);
};
export const mockNavController = function () {
let platform = mockPlatform();
let config = mockConfig(null, '/', platform);
let app = mockApp(config, platform);
let form = new Form();
let zone = mockZone();
let keyboard = new Keyboard(config, form, zone);
let elementRef = mockElementRef();
let renderer = mockRenderer();
let componentFactoryResolver = null;
let gestureCtrl = new GestureController(app);
let linker = mockDeepLinker(null, app);
let trnsCtrl = mockTrasitionController(config);
let nav = new NavControllerBase(null, app, config, keyboard, elementRef, zone, renderer, componentFactoryResolver, gestureCtrl, trnsCtrl, linker);
nav._viewInit = function (enteringView) {
enteringView.init(mockComponentRef());
enteringView._state = ViewState.INITIALIZED;
};
nav._orgViewInsert = nav._viewInsert;
nav._viewInsert = function (view, componentRef, viewport) {
let mockedViewport = {
insert: () => { }
};
nav._orgViewInsert(view, componentRef, mockedViewport);
};
return nav;
};
export const mockOverlayPortal = function (app, config, platform) {
let form = new Form();
let zone = mockZone();
let keyboard = new Keyboard(config, form, zone);
let elementRef = mockElementRef();
let renderer = mockRenderer();
let componentFactoryResolver = null;
let gestureCtrl = new GestureController(app);
let serializer = new UrlSerializer(null);
let location = mockLocation();
let deepLinker = new DeepLinker(app, serializer, location);
return new OverlayPortal(app, config, keyboard, elementRef, zone, renderer, componentFactoryResolver, gestureCtrl, null, deepLinker, null);
};
export const mockTab = function (parentTabs) {
let platform = mockPlatform();
let config = mockConfig(null, '/', platform);
let app = parentTabs._app || mockApp(config, platform);
let form = new Form();
let zone = mockZone();
let keyboard = new Keyboard(config, form, zone);
let elementRef = mockElementRef();
let renderer = mockRenderer();
let changeDetectorRef = mockChangeDetectorRef();
let compiler = null;
let gestureCtrl = new GestureController(app);
let linker = mockDeepLinker(null, app);
let tab = new Tab(parentTabs, app, config, keyboard, elementRef, zone, renderer, compiler, changeDetectorRef, gestureCtrl, null, linker);
tab.load = (opts, cb) => {
cb();
};
return tab;
};
export const mockTabs = function (app) {
let platform = mockPlatform();
let config = mockConfig(null, '/', platform);
app = app || mockApp(config, platform);
let elementRef = mockElementRef();
let renderer = mockRenderer();
let linker = mockDeepLinker();
return new Tabs(null, null, app, config, elementRef, platform, renderer, linker);
};
export const mockMenu = function () {
return new Menu(null, null, null, null, null, null, null, null);
};
export const mockDeepLinkConfig = function (links) {
return {
links: links || [
{ component: MockView1, name: 'viewone' },
{ component: MockView2, name: 'viewtwo' },
{ component: MockView3, name: 'viewthree' },
{ component: MockView4, name: 'viewfour' },
{ component: MockView5, name: 'viewfive' }
]
};
};
export class MockView {
}
export class MockView1 {
}
export class MockView2 {
}
export class MockView3 {
}
export class MockView4 {
}
export class MockView5 {
}
export function noop() { return 'noop'; }
;
|
shdevops/JAF-Dice-Roller
|
node_modules/ionic-angular/es2015/util/mock-providers.js
|
JavaScript
|
gpl-3.0
| 9,830 |
const {
JSDOM
} = require("jsdom")
async function checkInvite(url) {
try {
let page = await JSDOM.fromURL(url)
let title = page.window.document.querySelector('.tgme_page_title').textContent.trim()
if (title == 'Join group chat on Telegram') {
return false
} else {
return title
}
} catch (e) {
console.error(e.message)
return false
}
}
async function getMemberCount(url) {
try {
let page = await JSDOM.fromURL(url)
let extra = page.window.document.querySelector('.tgme_page_extra')
if (extra) {
if (extra.textContent.trim().match(/[0-9 ]*[0-9]/)) {
let count = parseInt(extra.textContent.trim().match(/[0-9 ]*[0-9]/)[0].replace(/\s/, ''))
console.log('t.me getMemberCount: ', url + ' - ' + count)
return count
}
return false
} else {
return false
}
} catch (e) {
console.error(e.message)
return false
}
}
module.exports = {
checkInvite,
getMemberCount
}
|
wfjsw/osiris-groupindexer
|
lib/t_me_assistant.js
|
JavaScript
|
gpl-3.0
| 1,126 |
'use strict';
const logger = require('../../server/logger');
module.exports = function(app){
app.date = {
formatUnixTimestamp: (timestamp) => {
var dateObj = new Date(timestamp*1000);
return dateObj.toUTCString();
// return dateObj.getHours()+':'
// +(dateObj.getMinutes() < 10?'0'+dateObj.getMinutes():dateObj.getMinutes())
// +' '+dateObj.getDate() + ' '
// + app.date.monthName(dateObj) + ' '
// + dateObj.getFullYear();
//+'. UTC Offset: '+(dateObj.getTimezoneOffset()/60)+' hours';
},
formatUnixMilliseconds: (timestamp) => {
//console.log(timestamp);
var dateObj = new Date(timestamp);
//console.log('dateObj: '+JSON.stringify(dateObj));
return dateObj.getHours()+':'+(dateObj.getMinutes() < 10?'0'+dateObj.getMinutes():dateObj.getMinutes())+' '+dateObj.getDate() + ' ' + app.date.monthName(dateObj) + ' ' + dateObj.getFullYear();
//+'. UTC Offset: '+(dateObj.getTimezoneOffset()/60)+' hours';
},
printServerUtcOffset: () => {
var utcOffset = new Date().getTimezoneOffset();
console.log('the iECHO server is minutes offset from UTC: '+utcOffset);
},
monthName: (dateTime,lang) => {
lang = lang || "en";
var monthList =
{
"en":
["January", "February","March","April","May","June","July","August","September","October","November","December"]
};
return monthList[lang][dateTime.getMonth()];
}
}
}
|
wardance-ferret/es
|
localtime/server/boot/date.js
|
JavaScript
|
gpl-3.0
| 1,456 |
// socket_io_transport client
var LABPROJECT_BASE = process.cwd();
var LABPROJECT_LIB = process.cwd() + "/lib";
var common_crypto = require(LABPROJECT_LIB + "/common/crypto");
function create_socket(location, callback) {
var socket = require('socket.io-client')(location, {forceNew: true});
socket.on('connect', function(){
callback(null, socket);
});
}
module.exports = {
connect_clients: function(logger, hosts_config, callback) {
add_clients(logger, 0, hosts_config, {}, function(error, client_map) {
callback(null, new vm_server_client(client_map));
});
}
}
function add_clients(logger, location, hosts_config, client_map, callback) {
if (location >= Object.keys(hosts_config).length) {
callback(null, client_map);
} else {
var current_key = Object.keys(hosts_config)[location];
var current = hosts_config[current_key];
client_map[current.name] = new socket_io_client(current.clientkey, logger);
client_map[current.name].connect('http://' + current.host + ':' + current.port, function(error, status) {
add_clients(logger, location+1, hosts_config, client_map, callback);
});
}
}
function vm_server_client(client_map) {
var self = this;
var client_map = client_map;
self.call = function(server_id, method, params, callback) {
if (client_map.hasOwnProperty(server_id)) {
var call_data = {
'get': method
}
for (var item in params) {
call_data[item] = params[item];
}
client_map[server_id].send(call_data, function(error, result) {
if (error) {
callback(error, null);
} else if (result.error !== null) {
callback(result.error, null);
} else {
callback(null, result.data);
}
});
} else {
callback(new Error("Invalid server id"), null);
}
}
self.destroy = function() {
for (var server_id in client_map) {
client_map[server_id].disconnect();
}
}
self.on_event = function(event_name, callback) {
var event_callback = function(error, data) {
callback(error, data);
};
for (var server_id in client_map) {
client_map[server_id].on_event(event_name, event_callback);
}
}
}
function socket_io_client(clientkey, logger) {
var self = this;
var connected = false;
var client_socket = null;
var client_logger = logger;
var response_map = {};
self.connect = function(location, callback) {
create_socket(location, function(error, socket) {
client_logger.log("notice", "Connected to VM server at " + location);
client_socket = socket;
connected = true;
// socket.on("server_response", function(data, response) {
// });
socket.on('disconnect', function() {
client_logger.log("warning", "Disconnected from server");
connected = false;
});
socket.on('reconnect_attempt', function() {
client_logger.log("notice", "Attempting to reconnect to server");
});
socket.on('reconnect', function(){
client_logger.log("notice", "Successfully reconnected to server");
connected = true;
});
callback(null, true);
});
};
self.is_connected = function() {
return (connected === true);
}
self.disconnect = function() {
if (connected) {
client_socket.disconnect();
}
}
// Send data to server
self.send = function(payload, callback) {
if (connected) {
var request_data = {
clientkey: clientkey,
payload: payload
}
client_socket.emit("server_request", request_data, function(resp) {
if (!resp.error) {
callback(null, resp.payload);
} else {
callback(new Error(resp.error), null);
}
});
} else {
callback(new Error("SOCKET_IO_TRANSPORT_NOT_CONNECTED"), null);
}
};
self.on_event = function(event_name, callback) {
client_socket.on(event_name, callback);
};
}
|
j2h2-labproject/labproject-frontend-servers
|
lib/transports/socket_io_transport.js
|
JavaScript
|
gpl-3.0
| 4,516 |
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var ObjectId = mongoose.Types.ObjectId;
var User = require('../models/User');
var bcrypt = require('bcryptjs');
var moment = require('moment');
var jwt = require('jwt-simple');
var config = require('config');
// POST /auth/login
router.post('/login', function(req, res) {
User.findOne({ username: req.body.username }, '+password', function(err, user) {
if (!user) {
return res.status(401).send({ message: { username: 'Incorrect username' } });
}
bcrypt.compare(req.body.password, user.password, function(err, isMatch) {
if (!isMatch) {
return res.status(401).send({ message: { password: 'Incorrect password' } });
}
user = user.toObject();
delete user.password;
var token = createToken(user);
res.send({ token: token, user: user });
});
});
});
// POST /auth/signup
router.post('/auth/signup', function(req, res) {
User.findOne({ email: req.body.email }, function(err, existingEmail) {
if (existingEmail) {
return res.status(409).send({ message: 'Email is already taken.' });
}
User.findOne({ username: req.body.username }, function(err, existingUser) {
if (existingUser) {
return res.status(409).send({ message: 'Email is already taken.' });
}
var user = new User({
email: req.body.email,
username: req.body.username,
password: req.body.password
});
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
user.password = hash;
user.save(function() {
var token = createToken(user);
res.send({ token: token, user: user });
});
});
});
});
});
});
module.exports = router;
function createToken(user) {
var payload = {
exp: moment().add(14, 'days').unix(),
iat: moment().unix(),
sub: user._id
};
return jwt.encode(payload, config.tokenSecret);
}
|
UTAlan/SenatorTracker
|
server/routes/users.js
|
JavaScript
|
gpl-3.0
| 2,346 |
/*!
* VisualEditor DataModel ClassAttribute class.
*
* @copyright 2011-2016 VisualEditor Team and others; see http://ve.mit-license.org
*/
/**
* DataModel class-attribute node.
*
* Used for nodes which use classes to store attributes.
*
* @class
* @abstract
*
* @constructor
*/
ve.dm.ClassAttributeNode = function VeDmClassAttributeNode() {};
/* Inheritance */
OO.initClass( ve.dm.ClassAttributeNode );
/* Static methods */
/**
* Mapping from class names to attributes
*
* e.g. { alignLeft: { align: 'left' } } sets the align attribute to 'left'
* if the element has the class 'alignLeft'
*
* @type {Object}
*/
ve.dm.ClassAttributeNode.static.classAttributes = {};
/**
* Set attributes from a class attribute
*
* Unrecognized classes are also preserved.
*
* @param {Object} attributes Attributes object to modify
* @param {string|null} classAttr Class attribute from an element
*/
ve.dm.ClassAttributeNode.static.setClassAttributes = function ( attributes, classAttr ) {
var className, i, l,
unrecognizedClasses = [],
classNames = classAttr ? classAttr.trim().split( /\s+/ ) : [];
if ( !classNames.length ) {
return;
}
for ( i = 0, l = classNames.length; i < l; i++ ) {
className = classNames[ i ];
if ( Object.prototype.hasOwnProperty.call( this.classAttributes, className ) ) {
attributes = ve.extendObject( attributes, this.classAttributes[ className ] );
} else {
unrecognizedClasses.push( className );
}
}
attributes.originalClasses = classAttr;
attributes.unrecognizedClasses = unrecognizedClasses;
};
/**
* Get class attribute from element attributes
*
* @param {Object|undefined} attributes Element attributes
* @return {string|null} Class name, or null if no classes to set
*/
ve.dm.ClassAttributeNode.static.getClassAttrFromAttributes = function ( attributes ) {
var className, key, classAttributeSet, hasClass,
classNames = [];
attributes = attributes || {};
for ( className in this.classAttributes ) {
classAttributeSet = this.classAttributes[ className ];
hasClass = true;
for ( key in classAttributeSet ) {
if ( attributes[ key ] !== classAttributeSet[ key ] ) {
hasClass = false;
break;
}
}
if ( hasClass ) {
classNames.push( className );
}
}
if ( attributes.unrecognizedClasses ) {
classNames = OO.simpleArrayUnion( classNames, attributes.unrecognizedClasses );
}
// If no meaningful change in classes, preserve order
if (
attributes.originalClasses &&
ve.compareClassLists( attributes.originalClasses, classNames )
) {
return attributes.originalClasses;
} else if ( classNames.length > 0 ) {
return classNames.join( ' ' );
}
return null;
};
/**
* @inheritdoc ve.dm.Node
*/
ve.dm.ClassAttributeNode.static.sanitize = function ( dataElement ) {
if ( dataElement.attributes ) {
delete dataElement.attributes.unrecognizedClasses;
}
};
|
Facerafter/starcitizen-tools
|
extensions/VisualEditor/lib/ve/src/dm/ve.dm.ClassAttributeNode.js
|
JavaScript
|
gpl-3.0
| 2,882 |
define(["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.when = n;
/**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
function n(n, o, r) {
return n ? o() : null == r ? void 0 : r();
}
});
|
elmsln/elmsln
|
core/dslmcode/cores/haxcms-1/build/es5-amd/node_modules/lit-html/directives/when.js
|
JavaScript
|
gpl-3.0
| 331 |
/* -*- Mode: JavaScript; coding: utf-8; tab-width: 3; indent-tabs-mode: tab; c-basic-offset: 3 -*-
*******************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright create3000, Scheffelstraße 31a, Leipzig, Germany 2011.
*
* All rights reserved. Holger Seelig <holger.seelig@yahoo.de>.
*
* The copyright notice above does not evidence any actual of intended
* publication of such source code, and is an unpublished work by create3000.
* This material contains CONFIDENTIAL INFORMATION that is the property of
* create3000.
*
* No permission is granted to copy, distribute, or create derivative works from
* the contents of this software, in whole or in part, without the prior written
* permission of create3000.
*
* NON-MILITARY USE ONLY
*
* All create3000 software are effectively free software with a non-military use
* restriction. It is free. Well commented source is provided. You may reuse the
* source in any way you please with the exception anything that uses it must be
* marked to indicate is contains 'non-military use only' components.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2015, 2016 Holger Seelig <holger.seelig@yahoo.de>.
*
* This file is part of the Cobweb Project.
*
* Cobweb is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 3 only, as published by the
* Free Software Foundation.
*
* Cobweb is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License version 3 for more
* details (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU General Public License version 3
* along with Cobweb. If not, see <http://www.gnu.org/licenses/gpl.html> for a
* copy of the GPLv3 License.
*
* For Silvio, Joy and Adi.
*
******************************************************************************/
define ([
"jquery",
"cobweb/Fields",
"cobweb/Basic/X3DFieldDefinition",
"cobweb/Basic/FieldDefinitionArray",
"cobweb/Execution/X3DExecutionContext",
"cobweb/Prototype/X3DProtoDeclarationNode",
"cobweb/Bits/X3DConstants",
"cobweb/InputOutput/Generator",
],
function ($,
Fields,
X3DFieldDefinition,
FieldDefinitionArray,
X3DExecutionContext,
X3DProtoDeclarationNode,
X3DConstants,
Generator)
{
"use strict";
function X3DProtoDeclaration (executionContext)
{
X3DProtoDeclarationNode .call (this, executionContext);
X3DExecutionContext .call (this, executionContext);
this .addType (X3DConstants .X3DProtoDeclaration);
this .addChildObjects ("loadState", new Fields .SFInt32 (X3DConstants .NOT_STARTED_STATE));
}
X3DProtoDeclaration .prototype = $.extend (Object .create (X3DExecutionContext .prototype),
X3DProtoDeclarationNode .prototype,
{
constructor: X3DProtoDeclaration,
fieldDefinitions: new FieldDefinitionArray ([
new X3DFieldDefinition (X3DConstants .inputOutput, "metadata", new Fields .SFNode ()),
]),
getTypeName: function ()
{
return "PROTO";
},
getComponentName: function ()
{
return "Cobweb";
},
getContainerField: function ()
{
return "protos";
},
initialize: function ()
{
X3DProtoDeclarationNode .prototype .initialize .call (this);
this .loadState_ = X3DConstants .COMPLETE_STATE;
},
hasUserDefinedFields: function ()
{
return true;
},
getURL: function ()
{
return this .getExecutionContext () .getURL ();
},
getProtoDeclaration: function ()
{
return this;
},
checkLoadState: function ()
{
return this .loadState_ .getValue ();
},
toXMLStream: function (stream)
{
stream .string += Generator .Indent ();
stream .string += "<ProtoDeclare";
stream .string += " ";
stream .string += "name='";
stream .string += Generator .XMLEncode (this .getName ());
stream .string += "'";
stream .string += ">";
stream .string += "\n";
// <ProtoInterface>
Generator .EnterScope ();
var userDefinedFields = this .getUserDefinedFields ();
if (! $.isEmptyObject (userDefinedFields))
{
Generator .IncIndent ();
stream .string += Generator .Indent ();
stream .string += "<ProtoInterface>\n";
Generator .IncIndent ();
for (var name in userDefinedFields)
{
var field = userDefinedFields [name];
stream .string += Generator .Indent ();
stream .string += "<field";
stream .string += " ";
stream .string += "accessType='";
stream .string += Generator .AccessType (field .getAccessType ());
stream .string += "'";
stream .string += " ";
stream .string += "type='";
stream .string += field .getTypeName ();
stream .string += "'";
stream .string += " ";
stream .string += "name='";
stream .string += Generator .XMLEncode (field .getName ());
stream .string += "'";
if (field .isDefaultValue ())
{
stream .string += "/>\n";
}
else
{
switch (field .getType ())
{
case X3DConstants .SFNode:
case X3DConstants .MFNode:
{
Generator .PushContainerField (null);
stream .string += ">\n";
Generator .IncIndent ();
field .toXMLStream (stream);
stream .string += "\n";
Generator .DecIndent ();
stream .string += Generator .Indent ();
stream .string += "</field>\n";
Generator .PopContainerField ();
break;
}
default:
{
stream .string += " ";
stream .string += "value='";
field .toXMLStream (stream);
stream .string += "'";
stream .string += "/>\n";
break;
}
}
}
}
Generator .DecIndent ();
stream .string += Generator .Indent ();
stream .string += "</ProtoInterface>\n";
Generator .DecIndent ();
}
Generator .LeaveScope ();
// </ProtoInterface>
// <ProtoBody>
Generator .IncIndent ();
stream .string += Generator .Indent ();
stream .string += "<ProtoBody>\n";
Generator .IncIndent ();
X3DExecutionContext .prototype .toXMLStream .call (this, stream);
Generator .DecIndent ();
stream .string += Generator .Indent ();
stream .string += "</ProtoBody>\n";
Generator .DecIndent ();
// </ProtoBody>
stream .string += Generator .Indent ();
stream .string += "</ProtoDeclare>";
},
});
Object .defineProperty (X3DProtoDeclaration .prototype, "name",
{
get: function () { return this .getName (); },
enumerable: true,
configurable: false
});
Object .defineProperty (X3DProtoDeclaration .prototype, "fields",
{
get: function () { return this .getFieldDefinitions (); },
enumerable: true,
configurable: false
});
Object .defineProperty (X3DProtoDeclaration .prototype, "isExternProto",
{
get: function () { return false; },
enumerable: true,
configurable: false
});
return X3DProtoDeclaration;
});
|
create3000/cobweb
|
src/cobweb/Prototype/X3DProtoDeclaration.js
|
JavaScript
|
gpl-3.0
| 7,241 |
/* global ajaxurl */
jQuery(function($){
$( 'body' ).bind( 'click.mn-gallery', function(e){
var target = $( e.target ), id, img_size;
if ( target.hasClass( 'mn-set-header' ) ) {
( window.dialogArguments || opener || parent || top ).location.href = target.data( 'location' );
e.preventDefault();
} else if ( target.hasClass( 'mn-set-background' ) ) {
id = target.data( 'attachment-id' );
img_size = $( 'input[name="attachments[' + id + '][image-size]"]:checked').val();
jQuery.post(ajaxurl, {
action: 'set-background-image',
attachment_id: id,
size: img_size
}, function(){
var win = window.dialogArguments || opener || parent || top;
win.tb_remove();
win.location.reload();
});
e.preventDefault();
}
});
});
|
mtaandao/Framework
|
admin/js/media-gallery.js
|
JavaScript
|
gpl-3.0
| 769 |
#!/usr/bin/env node
/*
* Copyright (c) 2016 The Ontario Institute for Cancer Research. All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the GNU Public License v3.0.
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* 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 HOLDER 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.
*
* Based on work from iobio: https://github.com/iobio
*
* This file incorporates work covered by the following copyright and permission notice:
*
* The MIT License (MIT)
*
* Copyright (c) <2014>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
var port = 8002,
minion = require('../index.js')(port);
// define tool
tool = {
apiVersion : "0.1",
name : 'vcfstatsAlive',
path : 'vcfstatsAliveWrapper.sh',
inputOption: '-fake',
// instructional data used in /help
description : 'utility for vcf files',
exampleUrl : "fill in"
};
// start minion socket
minion.listen(tool);
console.log('iobio server started on port ' + port);
|
icgc-dcc/dcc-iobio
|
dcc-iobio-vcf/services/vcfstatsalive.js
|
JavaScript
|
gpl-3.0
| 3,441 |
"use strict";
var SHOW_DATA = {
"venue_name": "Uptown Theatre, Chicago, Illinois",
"venue_id": 24,
"show_date": "20th of Aug, 1980",
"sets": [
{"set_title": "1st set",
"encore": false,
"songs": [
{"name": "Jack Straw", "length":"5:54", "trans":"/"},
{"name": "Loser", "length":"7:26", "trans":"/"},
{"name": "Beat It On Down The Line", "length":"3:14", "trans":"/"},
{"name": "Ramble On Rose", "length":"7:30", "trans":">"},
{"name": "El Paso", "length":"4:40", "trans":"/"},
{"name": "Big Railroad Blues", "length":"4:07", "trans":"/"},
{"name": "Looks Like Rain", "length":"8:37", "trans":"/"},
{"name": "Far From Me", "length":"3:52", "trans":"/"},
{"name": "Let It Grow", "length":"10:17", "trans":">"},
{"name": "Deal", "length":"4:25", "trans":"/"},
]},
{"set_title": "2nd set",
"encore": false,
"songs": [
{"name": "Greatest Story Ever Told", "length":"4:15", "trans":"/"},
{"name": "Althea", "length":"8:14", "trans":"/"},
{"name": "Lost Sailor", "length":"6:33", "trans":">"},
{"name": "Saint Of Circumstance", "length":"6:17", "trans":"/"},
{"name": "Terrapin Station", "length":"12:58", "trans":">"},
{"name": "Drums", "length":"12:49", "trans":"/"},
{"name": "Space", "length":"4:07", "trans":">"},
{"name": "Not Fade Away", "length":"6:41", "trans":">"},
{"name": "Morning Dew", "length":"11:30", "trans":"/"},
{"name": "Good Lovin'", "length":"7:44", "trans":"/"},
]},
{"set_title": "3rd set",
"encore": false,
"songs": [
{"name": "U.S. Blues", "length":"5:10", "trans":"/"},
]},
],
};
|
maximinus/grateful-dead-songs
|
gdsongs/static/data/shows/66.js
|
JavaScript
|
gpl-3.0
| 1,599 |
import * as types from './Types';
export const dummy = () => ({ type: types.dummy });
export const startup = () => ({ type: types.startup });
export const setDate = (date) => ({ type: types.setDate, date});
// DayView
export const goToNextDay = () => ({ type: types.goToNextDay });
export const goToPreviousDay = () => ({ type: types.goToPreviousDay });
export const fetchItems = () => ({ type: types.fetchItems });
export const itemsFetched = (items) => ({ type: types.itemsFetched, items });
export const itemAdded = (item) => ({ type: types.dayViewAddItem, item });
// Goals
export const goalsViewLoaded = () => ({type: types.goalsViewLoaded});
export const goalsChanged = (goals) => ({type: types.goalsChanged, goals});
export const goalsLoaded = (goals) => ({type: types.goalsLoaded, goals});
export const goalReached = (goalNum) => ({type: types.goalReached, goalNum});
|
BALEHOK/motodo
|
App/Actions/AppActionCreators.js
|
JavaScript
|
gpl-3.0
| 881 |
"use strict";
var http = require('http');
var https = require('https');
http.globalAgent.maxSockets = 1000000000;
const requestHandler = (request, response) => {
response.end('Hello Node.js Server!')
}
var server = http.Server(requestHandler);
var env = process.env;
var url = require('url');
var fs = require('fs');
const configUrl = env.CONFIG_URL
const parsedUrl = url.parse(configUrl);
const requestOptions = {
hostname: parsedUrl.hostname,
path: parsedUrl.path,
port: parsedUrl.port,
headers: {
Accept: 'text/plain, application/xml , application/ld+json',
'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0',
}
};
https.get(requestOptions, function(res) {
var responseBody = '';
if (res.statusCode == 200) {
}
res.on('data', chunk => {
responseBody += chunk.toString();
});
res.on('end', () => {
// console.log("http end", responseBody)
let content = 'module.exports = ' + responseBody;
fs.writeFile("configuration.js", content, 'utf8', function(err) {
server.listen(8080, function () {
console.log('~~ server started ')
require('../core/timerScheduler').run(true);
})
});
});
}.bind(this)).on('error', (e) => {
console.error('timer APP config error', e);
throw new Error(e)
});
|
assemblee-virtuelle/Semantic-Bus
|
timer/app.js
|
JavaScript
|
gpl-3.0
| 1,315 |
'use strict';
var config = require('../config/environment');
exports.index = function(req, res) {
res.json({
currentYear: new Date().getFullYear(),
apiUrl: '/api',
tokenName: 'lypo.token',
environment: config.env,
showAds: config.showAds
});
};
|
vivanov1410/lypo
|
server/settings/settings.controller.js
|
JavaScript
|
gpl-3.0
| 270 |
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
(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", '../../animations/animation', '../../transitions/page-transition', '../../util/dom'], factory);
}
})(function (require, exports) {
"use strict";
var animation_1 = require('../../animations/animation');
var page_transition_1 = require('../../transitions/page-transition');
var dom_1 = require('../../util/dom');
var ModalSlideIn = (function (_super) {
__extends(ModalSlideIn, _super);
function ModalSlideIn() {
_super.apply(this, arguments);
}
ModalSlideIn.prototype.init = function () {
_super.prototype.init.call(this);
var ele = this.enteringView.pageRef().nativeElement;
var backdropEle = ele.querySelector('ion-backdrop');
var backdrop = new animation_1.Animation(backdropEle);
var wrapper = new animation_1.Animation(ele.querySelector('.modal-wrapper'));
backdrop.fromTo('opacity', 0.01, 0.4);
wrapper.fromTo('translateY', '100%', '0%');
this
.element(this.enteringView.pageRef())
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(400)
.add(backdrop)
.add(wrapper);
};
return ModalSlideIn;
}(page_transition_1.PageTransition));
exports.ModalSlideIn = ModalSlideIn;
var ModalSlideOut = (function (_super) {
__extends(ModalSlideOut, _super);
function ModalSlideOut() {
_super.apply(this, arguments);
}
ModalSlideOut.prototype.init = function () {
_super.prototype.init.call(this);
var ele = this.leavingView.pageRef().nativeElement;
var backdrop = new animation_1.Animation(ele.querySelector('ion-backdrop'));
var wrapperEle = ele.querySelector('.modal-wrapper');
var wrapperEleRect = wrapperEle.getBoundingClientRect();
var wrapper = new animation_1.Animation(wrapperEle);
var screenDimensions = dom_1.windowDimensions();
wrapper.fromTo('translateY', '0px', (screenDimensions.height - wrapperEleRect.top) + "px");
backdrop.fromTo('opacity', 0.4, 0.0);
this
.element(this.leavingView.pageRef())
.easing('ease-out')
.duration(250)
.add(backdrop)
.add(wrapper);
};
return ModalSlideOut;
}(page_transition_1.PageTransition));
exports.ModalSlideOut = ModalSlideOut;
var ModalMDSlideIn = (function (_super) {
__extends(ModalMDSlideIn, _super);
function ModalMDSlideIn() {
_super.apply(this, arguments);
}
ModalMDSlideIn.prototype.init = function () {
_super.prototype.init.call(this);
var ele = this.enteringView.pageRef().nativeElement;
var backdrop = new animation_1.Animation(ele.querySelector('ion-backdrop'));
var wrapper = new animation_1.Animation(ele.querySelector('.modal-wrapper'));
backdrop.fromTo('opacity', 0.01, 0.4);
wrapper.fromTo('translateY', '40px', '0px');
wrapper.fromTo('opacity', 0.01, 1);
var DURATION = 280;
var EASING = 'cubic-bezier(0.36,0.66,0.04,1)';
this.element(this.enteringView.pageRef()).easing(EASING).duration(DURATION)
.add(backdrop)
.add(wrapper);
};
return ModalMDSlideIn;
}(page_transition_1.PageTransition));
exports.ModalMDSlideIn = ModalMDSlideIn;
var ModalMDSlideOut = (function (_super) {
__extends(ModalMDSlideOut, _super);
function ModalMDSlideOut() {
_super.apply(this, arguments);
}
ModalMDSlideOut.prototype.init = function () {
_super.prototype.init.call(this);
var ele = this.leavingView.pageRef().nativeElement;
var backdrop = new animation_1.Animation(ele.querySelector('ion-backdrop'));
var wrapper = new animation_1.Animation(ele.querySelector('.modal-wrapper'));
backdrop.fromTo('opacity', 0.4, 0.0);
wrapper.fromTo('translateY', '0px', '40px');
wrapper.fromTo('opacity', 0.99, 0);
this
.element(this.leavingView.pageRef())
.duration(200)
.easing('cubic-bezier(0.47,0,0.745,0.715)')
.add(wrapper)
.add(backdrop);
};
return ModalMDSlideOut;
}(page_transition_1.PageTransition));
exports.ModalMDSlideOut = ModalMDSlideOut;
});
|
shdevops/JAF-Dice-Roller
|
node_modules/ionic-angular/umd/components/modal/modal-transitions.js
|
JavaScript
|
gpl-3.0
| 5,137 |
Ext.define('Hrproject.hrproject.shared.demo.model.backgroundcheck.UniversityTypeModel', {
"extend": "Ext.data.Model",
"fields": [{
"name": "primaryKey",
"type": "string",
"defaultValue": ""
}, {
"name": "unvCode",
"type": "string",
"defaultValue": ""
}, {
"name": "unvDesc",
"type": "string",
"defaultValue": ""
}, {
"name": "unvHelp",
"type": "string",
"defaultValue": ""
}, {
"name": "unvIcon",
"type": "string",
"defaultValue": ""
}, {
"name": "versionId",
"type": "int",
"defaultValue": ""
}, {
"name": "entityAudit",
"reference": "EntityAudit"
}, {
"name": "primaryDisplay",
"type": "string",
"defaultValue": ""
}]
});
|
applifireAlgo/HR
|
hrproject/src/main/webapp/app/hrproject/shared/demo/model/backgroundcheck/UniversityTypeModel.js
|
JavaScript
|
gpl-3.0
| 903 |
/* Scripts loaded specifically for peoplegroups post type pages in the admin */
jQuery(document).ready(function () {
"use strict";
//changes the 'add new' link to the custom page.
jQuery('.page-title-action').attr('href', 'edit.php?post_type=peoplegroups&page=disciple_tools_people_groups');
//removes the edit slug box.
jQuery('#edit-slug-box').hide();
});
|
ChasmSolutions/disciple-tools
|
dt-core/admin/js/dt-peoplegroups.js
|
JavaScript
|
gpl-3.0
| 371 |
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2015 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko
* Website: http://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
Espo.define('views/settings/fields/quick-create-list', 'views/fields/array', function (Dep) {
return Dep.extend({
setup: function () {
this.params.options = Object.keys(this.getMetadata().get('scopes')).filter(function (scope) {
return this.getMetadata().get('scopes.' + scope + '.entity') && this.getMetadata().get('scopes.' + scope + '.tab');
}, this).sort(function (v1, v2) {
return this.translate(v1, 'scopeNamesPlural').localeCompare(this.translate(v2, 'scopeNamesPlural'));
}.bind(this));
Dep.prototype.setup.call(this);
},
});
});
|
sanduhrs/espocrm
|
frontend/client/src/views/settings/fields/quick-create-list.js
|
JavaScript
|
gpl-3.0
| 1,621 |
Creep.prototype.roleDemolisher = function() {
var demolishFlag = _.filter(Game.flags,{ memory: { function: 'demolish', spawn: this.memory.spawn}});
demolishFlag = _.filter(Game.flags,{ memory: { function: 'demolish', spawn: this.memory.spawn}});
if (demolishFlag.length > 0) {
demolishFlag = demolishFlag[0];
}
// if creep is bringing energy to a structure but has no energy left
if (this.room.memory.hostiles.length > 0) {
var homespawn = Game.getObjectById(this.memory.spawn);
if (this.room.name != this.memory.homeroom) {
this.moveTo(homespawn), {reusePath: moveReusePath()};
}
else if (this.pos.getRangeTo(homespawn) > 5) {
this.moveTo(homespawn), {reusePath: moveReusePath()};
}
this.memory.fleeing = true;
return;
}
if (this.carry.energy == 0) {
// switch state to demolishing
this.memory.working = false;
}
else if (this.carry.energy == this.carryCapacity) {
// if creep is demolishing but is full
demolishFlag = _.filter(Game.flags,{ memory: { function: 'demolish', spawn: this.memory.spawn}});
if (demolishFlag.length > 0) {
demolishFlag = demolishFlag[0];
if (demolishFlag.memory.dropEnergy == true) {
this.drop(RESOURCE_ENERGY);
this.memory.dropEnergy = true;
}
else {
this.memory.working = true;
delete this.memory.path;
}
}
}
// if creep is supposed to transfer energy to a structure
if (this.memory.working == true) {
// Find exit to spawn room
var spawn = Game.getObjectById(this.memory.spawn);
if (this.room.name != this.memory.homeroom) {
//still in new room, go out
if(!this.memory.path) {
this.memory.path = this.pos.findPathTo(spawn);
}
if(this.moveByPath(this.memory.path) == ERR_NOT_FOUND) {
this.memory.path = this.pos.findPathTo(spawn);
this.moveByPath(this.memory.path);
}
} //TODO: Check demolishFlag.pos
else if (demolishFlag.pos != undefined) {
// back in spawn room
let structure;
if (demolishFlag.pos.roomName == this.memory.homeroom) {
//Demolisher flag is in creep's home room -> energy will only be stored in containers and in the storage
structure = this.pos.findClosestByPath(FIND_STRUCTURES, {filter: (s) => (s.structureType == STRUCTURE_CONTAINER || s.structureType == STRUCTURE_STORAGE) && s.storeCapacity > _.sum(s.store) && s.pos.isEqualTo(demolishFlag.pos) == false});
}
else {
structure = this.findResource(RESOURCE_SPACE, STRUCTURE_CONTAINER, STRUCTURE_LINK, STRUCTURE_TOWER, STRUCTURE_STORAGE, STRUCTURE_SPAWN);
}
if (structure != null) {
// try to transfer energy, if it is not in range
if (this.transfer(structure, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
// move towards it
this.moveTo(structure, {reusePath: moveReusePath()});
}
}
}
else {
this.roleUpgrader();
}
}
// if creep is supposed to demolish
else {
//TODO Several demolishers per spawn; use creep.findMyFlag()
//Find something to demolish
demolishFlag = _.filter(Game.flags,{ memory: { function: 'demolish', spawn: this.memory.spawn}});
if (demolishFlag.length > 0) {
// Find exit to target room
demolishFlag = demolishFlag[0];
if (this.room.name != demolishFlag.pos.roomName) {
//still in old room, go out
if (this.moveTo(demolishFlag, {reusePath: moveReusePath()}) == ERR_NO_PATH) {
delete this.memory._move;
delete this.memory.path;
}
this.memory.oldRoom = true;
}
if (this.room.name == demolishFlag.pos.roomName) {
if (this.room.memory.hostiles.length == 0 || demolishFlag.memory.ignoreHostiles) {
let foreignConstructionSites = this.room.find(FIND_HOSTILE_CONSTRUCTION_SITES);
if (foreignConstructionSites.length > 0) {
this.moveTo(foreignConstructionSites[0], {reusePath: moveReusePath(), ignoreCreeps: false});
}
else if (this.memory.statusDemolishing == undefined) {
//new room reached, start demolishing
if (this.memory.oldRoom == true) {
delete this.memory.targetBuffer;
delete this.memory.oldRoom;
delete this.memory._move;
delete this.memory.path;
}
var targetlist;
if (demolishFlag.memory.target == "object") {
//demolish flag position structures
targetlist = demolishFlag.pos.lookFor(LOOK_STRUCTURES);
// Go through target list
for (var i in targetlist) {
if (targetlist[i].structureType != undefined) {
if ((targetlist[i].store != undefined && targetlist[i].store[RESOURCE_ENERGY] > 0) || (targetlist[i].energy != undefined && targetlist[i].energy > 0)) {
//empty structure of energy first
if (this.withdraw(targetlist[i], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
this.moveTo(targetlist[i], {reusePath: moveReusePath()});
}
}
else if (this.dismantle(targetlist[i]) == ERR_NOT_IN_RANGE) {
this.moveTo(targetlist[i], {reusePath: moveReusePath()});
}
break;
}
}
if (targetlist.length == 0) {
console.log("Demolition flag in room " + demolishFlag.pos.roomName + " is placed in empty square!")
}
}
else if (demolishFlag.memory.target == "room") {
//demolish all structures in room
// find structures with energy
var target = this.findResource(RESOURCE_ENERGY, STRUCTURE_SPAWN, STRUCTURE_EXTENSION, STRUCTURE_TERMINAL, STRUCTURE_STORAGE, STRUCTURE_TOWER, STRUCTURE_LINK, STRUCTURE_LAB);
if (target == null) {
target = this.pos.findClosestByPath(FIND_STRUCTURES, {filter: (s) => s.structureType != STRUCTURE_ROAD && s.structureType != STRUCTURE_WALL && s.structureType != STRUCTURE_CONTAINER && s.structureType != STRUCTURE_CONTROLLER});
}
if (target == null) {
target = this.pos.findClosestByPath(FIND_STRUCTURES, {filter: (s) => s.structureType != STRUCTURE_ROAD && s.structureType != STRUCTURE_CONTAINER && s.structureType != STRUCTURE_CONTROLLER});
}
if (target != null) {
if ((target.store != undefined && target.store[RESOURCE_ENERGY] > 0) || target.energy != undefined && target.energy > 20) {
//empty structure of energy first
if (this.withdraw(target, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
this.moveTo(target, {reusePath: moveReusePath()});
}
}
else {
var result = this.dismantle(target);
if (result == ERR_NOT_IN_RANGE) {
this.moveTo(target, {reusePath: moveReusePath()});
}
else if (result == OK) {
this.memory.statusDemolishing = target.id;
}
}
}
}
}
else {
if (this.dismantle(Game.getObjectById(this.memory.statusDemolishing)) != OK) {
delete this.memory.statusDemolishing;
delete this.memory.path;
delete this.memory._move;
delete this.memory.targetBuffer;
}
}
}
else {
//Hostiles creeps in new room
this.memory.fleeing = true;
this.goToHomeRoom();
}
}
}
else {
this.roleHarvester();
}
}
};
|
lispeaking/Screeps-Noob-Code
|
role.demolisher.js
|
JavaScript
|
gpl-3.0
| 9,494 |
Monocle.Controls.Contents = function (reader) {
var API = { constructor: Monocle.Controls.Contents }
var k = API.constants = API.constructor;
var p = API.properties = {
reader: reader
}
function createControlElements() {
var div = reader.dom.make('div', 'controls_contents_container');
contentsForBook(div, reader.getBook());
return div;
}
function contentsForBook(div, book) {
while (div.hasChildNodes()) {
div.removeChild(div.firstChild);
}
var list = div.dom.append('ol', 'controls_contents_list');
var contents = book.properties.contents;
for (var i = 0; i < contents.length; ++i) {
chapterBuilder(list, contents[i], 0);
}
}
function chapterBuilder(list, chp, padLvl) {
var index = list.childNodes.length;
var li = list.dom.append('li', 'controls_contents_chapter', index);
var span = li.dom.append(
'span',
'controls_contents_chapterTitle',
index,
{ html: chp.title }
);
span.style.paddingLeft = padLvl + "em";
var invoked = function () {
p.reader.skipToChapter(chp.src);
p.reader.hideControl(API);
}
Monocle.Events.listenForTap(li, invoked, 'controls_contents_chapter_active');
if (chp.children) {
for (var i = 0; i < chp.children.length; ++i) {
chapterBuilder(list, chp.children[i], padLvl + 1);
}
}
}
API.createControlElements = createControlElements;
return API;
}
;
Monocle.Controls.Magnifier = function (reader) {
var API = { constructor: Monocle.Controls.Magnifier }
var k = API.constants = API.constructor;
var p = API.properties = {
buttons: [],
magnified: false
}
function initialize() {
p.reader = reader;
}
function createControlElements(holder) {
var btn = holder.dom.make('div', 'controls_magnifier_button');
btn.smallA = btn.dom.append('span', 'controls_magnifier_a', { text: 'A' });
btn.largeA = btn.dom.append('span', 'controls_magnifier_A', { text: 'A' });
p.buttons.push(btn);
Monocle.Events.listenForTap(btn, toggleMagnification);
return btn;
}
function toggleMagnification(evt) {
var opacities;
p.magnified = !p.magnified;
if (p.magnified) {
opacities = [0.3, 1];
p.reader.formatting.setFontScale(k.MAGNIFICATION, true);
} else {
opacities = [1, 0.3];
p.reader.formatting.setFontScale(null, true);
}
for (var i = 0; i < p.buttons.length; i++) {
p.buttons[i].smallA.style.opacity = opacities[0];
p.buttons[i].largeA.style.opacity = opacities[1];
}
}
API.createControlElements = createControlElements;
initialize();
return API;
}
Monocle.Controls.Magnifier.MAGNIFICATION = 1.2;
// A panel is an invisible column of interactivity. When contact occurs
// (mousedown, touchstart), the panel expands to the full width of its
// container, to catch all interaction events and prevent them from hitting
// other things.
//
// Panels are used primarily to provide hit zones for page flipping
// interactions, but you can do whatever you like with them.
//
// After instantiating a panel and adding it to the reader as a control,
// you can call listenTo() with a hash of methods for any of 'start', 'move'
// 'end' and 'cancel'.
//
Monocle.Controls.Panel = function () {
var API = { constructor: Monocle.Controls.Panel }
var k = API.constants = API.constructor;
var p = API.properties = {
evtCallbacks: {}
}
function createControlElements(cntr) {
p.div = cntr.dom.make('div', k.CLS.panel);
p.div.dom.setStyles(k.DEFAULT_STYLES);
Monocle.Events.listenForContact(
p.div,
{
'start': start,
'move': move,
'end': end,
'cancel': cancel
},
{ useCapture: false }
);
return p.div;
}
function setDirection(dir) {
p.direction = dir;
}
function listenTo(evtCallbacks) {
p.evtCallbacks = evtCallbacks;
}
function deafen() {
p.evtCallbacks = {}
}
function start(evt) {
p.contact = true;
evt.m.offsetX += p.div.offsetLeft;
evt.m.offsetY += p.div.offsetTop;
expand();
invoke('start', evt);
}
function move(evt) {
if (!p.contact) {
return;
}
invoke('move', evt);
}
function end(evt) {
if (!p.contact) {
return;
}
Monocle.Events.deafenForContact(p.div, p.listeners);
contract();
p.contact = false;
invoke('end', evt);
}
function cancel(evt) {
if (!p.contact) {
return;
}
Monocle.Events.deafenForContact(p.div, p.listeners);
contract();
p.contact = false;
invoke('cancel', evt);
}
function invoke(evtType, evt) {
if (p.evtCallbacks[evtType]) {
p.evtCallbacks[evtType](p.direction, evt.m.offsetX, evt.m.offsetY, API);
}
evt.preventDefault();
}
function expand() {
if (p.expanded) {
return;
}
p.div.dom.addClass(k.CLS.expanded);
p.expanded = true;
}
function contract(evt) {
if (!p.expanded) {
return;
}
p.div.dom.removeClass(k.CLS.expanded);
p.expanded = false;
}
API.createControlElements = createControlElements;
API.listenTo = listenTo;
API.deafen = deafen;
API.expand = expand;
API.contract = contract;
API.setDirection = setDirection;
return API;
}
Monocle.Controls.Panel.CLS = {
panel: 'panel',
expanded: 'controls_panel_expanded'
}
Monocle.Controls.Panel.DEFAULT_STYLES = {
position: 'absolute',
height: '100%'
}
;
Monocle.Controls.PlaceSaver = function (bookId) {
var API = { constructor: Monocle.Controls.PlaceSaver }
var k = API.constants = API.constructor;
var p = API.properties = {}
function initialize() {
applyToBook(bookId);
}
function assignToReader(reader) {
p.reader = reader;
p.reader.listen('monocle:turn', savePlaceToCookie);
}
function applyToBook(bookId) {
p.bkTitle = bookId.toLowerCase().replace(/[^a-z0-9]/g, '');
p.prefix = k.COOKIE_NAMESPACE + p.bkTitle + ".";
}
function setCookie(key, value, days) {
var expires = "";
if (days) {
var d = new Date();
d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires="+d.toGMTString();
}
var path = "; path=/";
document.cookie = p.prefix + key + "=" + value + expires + path;
return value;
}
function getCookie(key) {
if (!document.cookie) {
return null;
}
var regex = new RegExp(p.prefix + key + "=(.+?)(;|$)");
var matches = document.cookie.match(regex);
if (matches) {
return matches[1];
} else {
return null;
}
}
function savePlaceToCookie() {
var place = p.reader.getPlace();
setCookie(
"component",
encodeURIComponent(place.componentId()),
k.COOKIE_EXPIRES_IN_DAYS
);
setCookie(
"percent",
place.percentageThrough(),
k.COOKIE_EXPIRES_IN_DAYS
);
}
function savedPlace() {
var locus = {
componentId: getCookie('component'),
percent: getCookie('percent')
}
if (locus.componentId && locus.percent) {
locus.componentId = decodeURIComponent(locus.componentId);
locus.percent = parseFloat(locus.percent);
return locus;
} else {
return null;
}
}
function restorePlace() {
var locus = savedPlace();
if (locus) {
p.reader.moveTo(locus);
}
}
API.assignToReader = assignToReader;
API.savedPlace = savedPlace;
API.restorePlace = restorePlace;
initialize();
return API;
}
Monocle.Controls.PlaceSaver.COOKIE_NAMESPACE = "monocle.controls.placesaver.";
Monocle.Controls.PlaceSaver.COOKIE_EXPIRES_IN_DAYS = 7; // Set to 0 for session-based expiry.
;
Monocle.Controls.Scrubber = function (reader) {
var API = { constructor: Monocle.Controls.Scrubber }
var k = API.constants = API.constructor;
var p = API.properties = {}
function initialize() {
p.reader = reader;
p.reader.listen('monocle:turn', updateNeedles);
updateNeedles();
}
function pixelToPlace(x, cntr) {
if (!p.componentIds) {
p.componentIds = p.reader.getBook().properties.componentIds;
p.componentWidth = 100 / p.componentIds.length;
}
var pc = (x / cntr.offsetWidth) * 100;
var cmpt = p.componentIds[Math.floor(pc / p.componentWidth)];
var cmptPc = ((pc % p.componentWidth) / p.componentWidth);
return { componentId: cmpt, percentageThrough: cmptPc };
}
function placeToPixel(place, cntr) {
if (!p.componentIds) {
p.componentIds = p.reader.getBook().properties.componentIds;
p.componentWidth = 100 / p.componentIds.length;
}
var componentIndex = p.componentIds.indexOf(place.componentId());
var pc = p.componentWidth * componentIndex;
pc += place.percentageThrough() * p.componentWidth;
return Math.round((pc / 100) * cntr.offsetWidth);
}
function updateNeedles() {
if (p.hidden || !p.reader.dom.find(k.CLS.container)) {
return;
}
var place = p.reader.getPlace();
var x = placeToPixel(place, p.reader.dom.find(k.CLS.container));
for (var i = 0, needle; needle = p.reader.dom.find(k.CLS.needle, i); ++i) {
setX(needle, x - needle.offsetWidth / 2);
p.reader.dom.find(k.CLS.trail, i).style.width = x + "px";
}
}
function setX(node, x) {
var cntr = p.reader.dom.find(k.CLS.container);
x = Math.min(cntr.offsetWidth - node.offsetWidth, x);
x = Math.max(x, 0);
Monocle.Styles.setX(node, x);
}
function createControlElements(holder) {
var cntr = holder.dom.make('div', k.CLS.container);
var track = cntr.dom.append('div', k.CLS.track);
var needleTrail = cntr.dom.append('div', k.CLS.trail);
var needle = cntr.dom.append('div', k.CLS.needle);
var bubble = cntr.dom.append('div', k.CLS.bubble);
var cntrListeners, bodyListeners;
var moveEvt = function (evt, x) {
evt.preventDefault();
x = (typeof x == "number") ? x : evt.m.registrantX;
var place = pixelToPlace(x, cntr);
setX(needle, x - needle.offsetWidth / 2);
var book = p.reader.getBook();
var chps = book.chaptersForComponent(place.componentId);
var cmptIndex = p.componentIds.indexOf(place.componentId);
var chp = chps[Math.floor(chps.length * place.percentageThrough)];
if (cmptIndex > -1 && book.properties.components[cmptIndex]) {
var actualPlace = Monocle.Place.FromPercentageThrough(
book.properties.components[cmptIndex],
place.percentageThrough
);
chp = actualPlace.chapterInfo() || chp;
}
if (chp) {
bubble.innerHTML = chp.title;
}
setX(bubble, x - bubble.offsetWidth / 2);
p.lastX = x;
return place;
}
var endEvt = function (evt) {
var place = moveEvt(evt, p.lastX);
p.reader.moveTo({
percent: place.percentageThrough,
componentId: place.componentId
});
Monocle.Events.deafenForContact(cntr, cntrListeners);
Monocle.Events.deafenForContact(document.body, bodyListeners);
bubble.style.display = "none";
}
var startFn = function (evt) {
evt.stopPropagation();
bubble.style.display = "block";
moveEvt(evt);
cntrListeners = Monocle.Events.listenForContact(
cntr,
{ move: moveEvt }
);
bodyListeners = Monocle.Events.listenForContact(
document.body,
{ end: endEvt }
);
}
Monocle.Events.listenForContact(cntr, { start: startFn });
return cntr;
}
API.createControlElements = createControlElements;
API.updateNeedles = updateNeedles;
initialize();
return API;
}
Monocle.Controls.Scrubber.CLS = {
container: 'controls_scrubber_container',
track: 'controls_scrubber_track',
needle: 'controls_scrubber_needle',
trail: 'controls_scrubber_trail',
bubble: 'controls_scrubber_bubble'
}
;
Monocle.Controls.Spinner = function (reader) {
var API = { constructor: Monocle.Controls.Spinner }
var k = API.constants = API.constructor;
var p = API.properties = {
reader: reader,
divs: [],
repeaters: {},
showForPages: []
}
function createControlElements(cntr) {
var anim = cntr.dom.make('div', 'controls_spinner_anim');
anim.dom.append('div', 'controls_spinner_inner');
p.divs.push(anim);
return anim;
}
function registerSpinEvent(startEvtType, stopEvtType) {
var label = startEvtType;
p.reader.listen(startEvtType, function (evt) { spin(label, evt) });
p.reader.listen(stopEvtType, function (evt) { spun(label, evt) });
}
// Registers spin/spun event handlers for certain time-consuming events.
//
function listenForUsualDelays() {
registerSpinEvent('monocle:componentloading', 'monocle:componentloaded');
registerSpinEvent('monocle:componentchanging', 'monocle:componentchange');
registerSpinEvent('monocle:resizing', 'monocle:resize');
registerSpinEvent('monocle:jumping', 'monocle:jump');
registerSpinEvent('monocle:recalculating', 'monocle:recalculated');
p.reader.listen('monocle:notfound', forceSpun);
p.reader.listen('monocle:componentfailed', forceSpun);
}
// Displays the spinner. Both arguments are optional.
//
function spin(label, evt) {
label = label || k.GENERIC_LABEL;
p.repeaters[label] = true;
p.reader.showControl(API);
// If the delay is on a page other than the page we've been assigned to,
// don't show the animation. p.global ensures that if an event affects
// all pages, the animation is always shown, even if other events in this
// spin cycle are page-specific.
var page = (evt && evt.m && evt.m.page) ? evt.m.page : null;
if (page && p.divs.length > 1) {
p.showForPages[page.m.pageIndex] = true;
} else {
p.global = true;
p.reader.dispatchEvent('monocle:modal:on');
}
for (var i = 0; i < p.divs.length; ++i) {
var show = (p.global || p.showForPages[i]) ? true : false;
p.divs[i].dom[show ? 'removeClass' : 'addClass']('dormant');
}
}
// Stops displaying the spinner. Both arguments are optional.
//
function spun(label, evt) {
label = label || k.GENERIC_LABEL;
p.repeaters[label] = false;
for (var l in p.repeaters) {
if (p.repeaters[l]) { return; }
}
forceSpun();
}
function forceSpun() {
if (p.global) { p.reader.dispatchEvent('monocle:modal:off'); }
p.global = false;
p.repeaters = {};
p.showForPages = [];
for (var i = 0; i < p.divs.length; ++i) {
p.divs[i].dom.addClass('dormant');
}
}
API.createControlElements = createControlElements;
API.registerSpinEvent = registerSpinEvent;
API.listenForUsualDelays = listenForUsualDelays;
API.spin = spin;
API.spun = spun;
API.forceSpun = forceSpun;
return API;
}
Monocle.Controls.Spinner.GENERIC_LABEL = "generic";
Monocle.Controls.Stencil = function (reader, behaviorClasses) {
var API = { constructor: Monocle.Controls.Stencil }
var k = API.constants = API.constructor;
var p = API.properties = {
reader: reader,
behaviors: [],
components: {},
masks: []
}
// Create the stencil container and listen for draw/update events.
//
function createControlElements(holder) {
behaviorClasses = behaviorClasses || k.DEFAULT_BEHAVIORS;
for (var i = 0, ii = behaviorClasses.length; i < ii; ++i) {
addBehavior(behaviorClasses[i]);
}
p.container = holder.dom.make('div', k.CLS.container);
p.reader.listen('monocle:turning', hide);
p.reader.listen('monocle:turn:cancel', show);
p.reader.listen('monocle:turn', update);
p.reader.listen('monocle:stylesheetchange', update);
p.reader.listen('monocle:resize', update);
update();
return p.container;
}
// Pass this method an object that responds to 'findElements(doc)' with
// an array of DOM elements for that document, and to 'fitMask(elem, mask)'.
//
// After you have added all your behaviors this way, you would typically
// call update() to make them take effect immediately.
//
function addBehavior(bhvrClass) {
var bhvr = new bhvrClass(API);
if (typeof bhvr.findElements != 'function') {
console.warn('Missing "findElements" method for behavior: %o', bhvr);
}
if (typeof bhvr.fitMask != 'function') {
console.warn('Missing "fitMask" method for behavior: %o', bhvr);
}
p.behaviors.push(bhvr);
}
// Resets any pre-calculated rectangles for the active component,
// recalculates them, and forces masks to be "drawn" (moved into the new
// rectangular locations).
//
function update() {
var visPages = p.reader.visiblePages();
if (!visPages || !visPages.length) { return; }
var pageDiv = visPages[0];
var cmptId = pageComponentId(pageDiv);
if (!cmptId) { return; }
p.components[cmptId] = null;
calculateRectangles(pageDiv);
draw();
}
function hide() {
p.container.style.display = 'none';
}
function show() {
p.container.style.display = 'block';
}
// Removes any existing masks.
function clear() {
while (p.container.childNodes.length) {
p.container.removeChild(p.container.lastChild);
}
}
// Aligns the stencil container to the shape of the page, then moves the
// masks to sit above any currently visible rectangles.
//
function draw() {
var pageDiv = p.reader.visiblePages()[0];
var cmptId = pageComponentId(pageDiv);
if (!p.components[cmptId]) {
return;
}
// Position the container.
alignToComponent(pageDiv);
// Clear old masks.
clear();
// Layout the masks.
if (!p.disabled) {
show();
var rects = p.components[cmptId];
if (rects && rects.length) {
layoutRectangles(pageDiv, rects);
}
}
}
// Iterate over all the <a> elements in the active component, and
// create an array of rectangular points corresponding to their positions.
//
function calculateRectangles(pageDiv) {
var cmptId = pageComponentId(pageDiv);
if (!p.components[cmptId]) {
p.components[cmptId] = [];
} else {
return;
}
var doc = pageDiv.m.activeFrame.contentDocument;
var offset = getOffset(pageDiv);
for (var b = 0, bb = p.behaviors.length; b < bb; ++b) {
var bhvr = p.behaviors[b];
var elems = bhvr.findElements(doc);
for (var i = 0; i < elems.length; ++i) {
var elem = elems[i];
if (elem.getClientRects) {
var r = elem.getClientRects();
for (var j = 0; j < r.length; j++) {
p.components[cmptId].push({
element: elem,
behavior: bhvr,
left: Math.ceil(r[j].left + offset.l),
top: Math.ceil(r[j].top),
width: Math.floor(r[j].width),
height: Math.floor(r[j].height)
});
}
}
}
}
return p.components[cmptId];
}
// Update location of visible rectangles - creating as required.
//
function layoutRectangles(pageDiv, rects) {
var offset = getOffset(pageDiv);
var visRects = [];
for (var i = 0; i < rects.length; ++i) {
if (rectVisible(rects[i], offset.l, offset.l + offset.w)) {
visRects.push(rects[i]);
}
}
for (i = 0; i < visRects.length; ++i) {
var r = visRects[i];
var cr = {
left: r.left - offset.l,
top: r.top,
width: r.width,
height: r.height
};
var mask = createMask(r.element, r.behavior);
mask.dom.setStyles({
display: 'block',
left: cr.left+"px",
top: cr.top+"px",
width: cr.width+"px",
height: cr.height+"px",
position: 'absolute'
});
mask.stencilRect = cr;
}
}
// Find the offset position in pixels from the left of the current page.
//
function getOffset(pageDiv) {
return {
l: pageDiv.m.offset || 0,
w: pageDiv.m.dimensions.properties.width
};
}
// Is this area presently on the screen?
//
function rectVisible(rect, l, r) {
return rect.left >= l && rect.left < r;
}
// Returns the active component id for the given page, or the current
// page if no argument passed in.
//
function pageComponentId(pageDiv) {
pageDiv = pageDiv || p.reader.visiblePages()[0];
if (!pageDiv.m.activeFrame.m.component) { return; }
return pageDiv.m.activeFrame.m.component.properties.id;
}
// Positions the stencil container over the active frame.
//
function alignToComponent(pageDiv) {
var cmpt = pageDiv.m.activeFrame.parentNode;
p.container.dom.setStyles({
left: cmpt.offsetLeft+"px",
top: cmpt.offsetTop+"px"
});
}
function createMask(element, bhvr) {
var mask = p.container.dom.append(bhvr.maskTagName || 'div', k.CLS.mask);
Monocle.Events.listenForContact(mask, {
start: function () { p.reader.dispatchEvent('monocle:magic:halt'); },
move: function (evt) { evt.preventDefault(); },
end: function () { p.reader.dispatchEvent('monocle:magic:init'); }
});
bhvr.fitMask(element, mask);
return mask;
}
// Make the active masks visible (by giving them a class -- override style
// in monoctrl.css).
//
function toggleHighlights() {
var cls = k.CLS.highlights;
if (p.container.dom.hasClass(cls)) {
p.container.dom.removeClass(cls);
} else {
p.container.dom.addClass(cls);
}
}
function disable() {
p.disabled = true;
draw();
}
function enable() {
p.disabled = false;
draw();
}
function filterElement(elem, behavior) {
if (typeof behavior.filterElement == 'function') {
return behavior.filterElement(elem);
}
return elem;
}
function maskAssigned(elem, mask, behavior) {
if (typeof behavior.maskAssigned == 'function') {
return behavior.maskAssigned(elem, mask);
}
return false;
}
API.createControlElements = createControlElements;
API.addBehavior = addBehavior;
API.draw = draw;
API.update = update;
API.toggleHighlights = toggleHighlights;
return API;
}
Monocle.Controls.Stencil.CLS = {
container: 'controls_stencil_container',
mask: 'controls_stencil_mask',
highlights: 'controls_stencil_highlighted'
}
Monocle.Controls.Stencil.Links = function (stencil) {
var API = { constructor: Monocle.Controls.Stencil.Links }
// Optionally specify the HTML tagname of the mask.
API.maskTagName = 'a';
// Returns an array of all the elements in the given doc that should
// be covered with a stencil mask for interactivity.
//
// (Hint: doc.querySelectorAll() is your friend.)
//
API.findElements = function (doc) {
return doc.querySelectorAll('a[href]');
}
// Return an element. It should usually be a child of the container element,
// with a className of the given maskClass. You set up the interactivity of
// the mask element here.
//
API.fitMask = function (link, mask) {
var hrefObject = deconstructHref(link);
var rdr = stencil.properties.reader;
var evtData = { href: hrefObject, link: link, mask: mask }
if (hrefObject.pass) {
mask.onclick = function (evt) { return link.click(); }
} else {
link.onclick = function (evt) {
evt.preventDefault();
return false;
}
if (hrefObject.internal) {
mask.setAttribute('href', 'javascript:"Skip to chapter"');
mask.onclick = function (evt) {
if (rdr.dispatchEvent('monocle:link:internal', evtData, true)) {
rdr.skipToChapter(hrefObject.internal);
}
evt.preventDefault();
return false;
}
} else {
mask.setAttribute('href', hrefObject.external);
mask.setAttribute('target', '_blank');
mask.onclick = function (evt) {
return rdr.dispatchEvent('monocle:link:external', evtData, true);
}
}
}
}
// Returns an object with either:
//
// - an 'external' property -- an absolute URL with a protocol,
// host & etc, which should be treated as an external resource (eg,
// open in new window)
//
// OR
//
// - an 'internal' property -- a relative URL (with optional hash anchor),
// that is treated as a link to component in the book
//
// A weird but useful property of <a> tags is that while
// link.getAttribute('href') will return the actual string value of the
// attribute (eg, 'foo.html'), link.href will return the absolute URL (eg,
// 'http://example.com/monocles/foo.html').
//
function deconstructHref(elem) {
var loc = document.location;
var origin = loc.protocol+'//'+loc.host;
var href = elem.href;
var path = href.substring(origin.length);
var ext = { external: href };
if (href.toLowerCase().match(/^javascript:/)) {
return { pass: true };
}
// Anchor tags with 'target' attributes are always external URLs.
if (elem.getAttribute('target')) {
return ext;
}
// URLs with a different protocol or domain are always external.
//console.log("Domain test: %s <=> %s", origin, href);
if (href.indexOf(origin) !== 0) {
return ext;
}
// If it is in a sub-path of the current path, it's internal.
var topPath = loc.pathname.replace(/[^\/]*\.[^\/]+$/,'');
if (topPath[topPath.length - 1] != '/') {
topPath += '/';
}
//console.log("Sub-path test: %s <=> %s", topPath, path);
if (path.indexOf(topPath) === 0) {
return { internal: path.substring(topPath.length) }
}
// If it's a root-relative URL and it's in our list of component ids,
// it's internal.
var cmptIds = stencil.properties.reader.getBook().properties.componentIds;
for (var i = 0, ii = cmptIds.length; i < ii; ++i) {
//console.log("Component test: %s <=> %s", cmptIds[i], path);
if (path.indexOf(cmptIds[i]) === 0) {
return { internal: path }
}
}
// Otherwise it's external.
return ext;
}
return API;
}
Monocle.Controls.Stencil.DEFAULT_BEHAVIORS = [Monocle.Controls.Stencil.Links];
|
rschroll/beru
|
html/monocle/scripts/monoctrl.js
|
JavaScript
|
gpl-3.0
| 26,117 |
/**
* Created by cgeek on 22/08/15.
*/
var AbstractDAL = require('./AbstractDAL');
var Q = require('q');
var _ = require('underscore');
module.exports = CoresDAL;
function CoresDAL(dal) {
"use strict";
AbstractDAL.call(this, dal);
var logger = require('../../../lib/logger')(dal.profile);
var that = this;
var treeMade;
this.initTree = function() {
return Q.all([
that.makeTree('cores/')
]);
};
this.addCore = function(core) {
return that.initTree()
.then(function(){
return that.write('cores/' + getCoreID(core) + '.json', core, that.DEEP_WRITE);
});
};
this.getCore = function(core) {
return that.initTree()
.then(function(){
return that.read('cores/' + getCoreID(core) + '.json');
});
};
this.removeCore = function(core) {
return that.initTree()
.then(function(){
return that.remove('cores/' + getCoreID(core) + '.json', that.RECURSIVE)
.catch(function(){
});
});
};
this.getCores = function() {
var cores = [];
return that.initTree()
.then(function(){
return that.list('cores/')
.then(function(files){
return _.pluck(files, 'file');
})
.then(that.reduceTo('cores/', cores))
.thenResolve(cores);
});
};
function getCoreID(core) {
return [core.forkPointNumber, core.forkPointHash].join('-');
}
}
|
okiwi/ucoin
|
app/lib/dal/fileDALs/CoresDAL.js
|
JavaScript
|
gpl-3.0
| 1,434 |
var class_w3_c_validator_1_1_markup_1_1_warnings_list =
[
[ "WarningsList", "class_w3_c_validator_1_1_markup_1_1_warnings_list.html#ad018cf0d41988ac5d0befee141c6ad09", null ],
[ "Count", "class_w3_c_validator_1_1_markup_1_1_warnings_list.html#ac41f64f0609ef2ebe688d8403b0f5c79", null ],
[ "Warnings", "class_w3_c_validator_1_1_markup_1_1_warnings_list.html#a453be7800f2e0e3ca12297670603f143", null ],
[ "WarningsCollection", "class_w3_c_validator_1_1_markup_1_1_warnings_list.html#a17590a371db17384b0ccb8d929016662", null ]
];
|
prokhor-ozornin/W3CValidator.NET
|
doc/html/class_w3_c_validator_1_1_markup_1_1_warnings_list.js
|
JavaScript
|
gpl-3.0
| 542 |
GO.billing.ImportSettingsPanel = Ext.extend(Ext.Panel,{
title:GO.billing.lang['payments'],
labelWidth:200,
layout:'form',
cls:'go-form-panel',
initComponent : function(){
this.items=[
this.importStatusId = new GO.form.ComboBox({
hiddenName: 'import_status_id',
fieldLabel: GO.billing.lang.paidStatus,
store:new GO.data.JsonStore({
url: GO.url('billing/status/store'),
baseParams: {
book_id: 0
},
fields: ['id','name'],
remoteSort: true
}),
valueField:'id',
displayField:'name',
mode: 'remote',
triggerAction: 'all',
anchor: '-20',
editable: false
}),{
xtype:'xcheckbox',
boxLabel: GO.billing.lang.notifyCustomer,
labelSeparator: '',
name: 'import_notify_customer',
// allowBlank: true,
hideLabel:true
},this.newBookField = new GO.form.ComboBoxReset({
hiddenName: 'import_duplicate_to_book',
fieldLabel: GO.billing.lang.copyToBook,
store: GO.billing.writableBooksStore,
emptyText:GO.lang.strNA,
valueField:'id',
displayField:'name',
typeAhead: true,
mode: 'local',
triggerAction: 'all',
editable: false,
anchor: '-20'
})
,
this.duplicateStatusId = new GO.form.ComboBox({
hiddenName: 'import_duplicate_status_id',
fieldLabel: GO.billing.lang.copyStatus,
store:new GO.data.JsonStore({
url: GO.url('billing/status/store'),
baseParams: {
book_id: 0
},
fields: ['id','name'],
remoteSort: true
}),
valueField:'id',
displayField:'name',
mode: 'remote',
triggerAction: 'all',
anchor: '-20',
editable: false
}),
this.autoPaidStatus = {
xtype:'xcheckbox',
boxLabel: GO.billing.lang['autoPaidStatus'],
labelSeparator: '',
name: 'auto_paid_status',
// allowBlank: true,
hideLabel:true
}
];
this.newBookField.on('select', function(combo, record, index){
this.duplicateStatusId.store.baseParams.book_id=record.data.id;
this.duplicateStatusId.store.removeAll();
this.duplicateStatusId.clearLastSearch();
}, this);
GO.billing.ImportSettingsPanel.superclass.initComponent.call(this);
},
setBookId : function(book_id){
this.importStatusId.store.baseParams.book_id=book_id;
this.importStatusId.store.removeAll();
this.importStatusId.clearLastSearch();
this.setDisabled(book_id==0);
}
});
|
deependhulla/powermail-debian9
|
files/rootdir/usr/local/src/groupoffice-6.2/groupoffice-6.2-setup-www/modules/billing/ImportSettingsPanel.js
|
JavaScript
|
gpl-3.0
| 2,328 |
function debug() {
var script = document.createElement('script'); script.src = "http://netcell.github.io/phaser-inspector/build/phaser-inspector.js"; document.getElementsByTagName('head')[0].appendChild(script); function phaserInspectorInject(){ if (Phaser.Plugin.Inspector) Phaser.GAMES[0].plugins.add(Phaser.Plugin.Inspector); else setTimeout(phaserInspectorInject); } setTimeout(phaserInspectorInject);
};
|
bdaenen/Mad-Science-Bro
|
src/debug.js
|
JavaScript
|
gpl-3.0
| 411 |
var _ = require('lodash');
var parseVerbLineData = require('../util/parse-verb-line-data');
function readSurface(data){
var vertices = [];
var uvs = [];
var halfEdges = [];
var faces = [];
var handlers = {
'v': function(x, y, z, firstHalfEdge){
vertices.push({
x: parseFloat(x),
y: parseFloat(y),
z: parseFloat(z),
firstHalfEdge: parseInt(firstHalfEdge)
});
},
'vt': function(u, v){
uvs.push({
u: parseFloat(u),
v: parseFloat(v)
});
},
'h': function(vertex, nextHalfEdge, face, twin){
halfEdges.push({
vertex: parseInt(vertex),
nextHalfEdge: parseInt(nextHalfEdge),
face: parseInt(face),
twin: twin !== undefined ? parseInt(twin) : null
});
},
'f': function(firstHalfEdge){
faces.push({
firstHalfEdge: parseInt(firstHalfEdge)
});
}
};
parseVerbLineData(data, handlers);
_.forEach(halfEdges, function(halfEdge, halfEdgeIndex){
halfEdges[halfEdge.nextHalfEdge].prevHalfEdge = halfEdgeIndex;
});
return {
vertices: vertices,
halfEdges: halfEdges,
faces: faces
};
}
module.exports = readSurface;
|
mjleehh/paper-model
|
lib/surface/read-surface.js
|
JavaScript
|
gpl-3.0
| 1,411 |
/* GCompris - explore_world_animals.js
*
* Copyright (C) 2015 Johnny Jazeix <jazeix@gmail.com>
*
* Authors:
* Beth Hadley <bethmhadley@gmail.com> (GTK+ version)
* Johnny Jazeix <jazeix@gmail.com> (Qt Quick port)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
var tab = [
{
"image": "qrc:/gcompris/src/activities/explore_world_animals/resource/tux.svg",
"title": qsTr("Jaguar"),
"text": qsTr("Jaguars are named after the Native American word meaning 'he who kills with one leap' because they like to climb trees to attack their prey."),
"image2": "qrc:/gcompris/src/activities/explore_world_animals/resource/jaggy.jpg",
"text2": qsTr("Jaguar"),
"x": 0.36,
"y": 0.56,
"width": 0.0785,
"height": 0.1005
},
{
"image": "qrc:/gcompris/src/activities/explore_world_animals/resource/tux.svg",
"title": qsTr("Hedgehog"),
"text": qsTr("Hedgehogs eat small animals, like frogs and insects, so many people keep them as useful pets. When in danger, they will curl up into a ball and stick up their coat of sharp spines."),
"image2": "qrc:/gcompris/src/activities/explore_world_animals/resource/hedgy.jpg",
"text2": qsTr("Hedgehog"),
"x": 0.53,
"y": 0.24,
"width": 0.0785,
"height": 0.1005
},
{
"image": "qrc:/gcompris/src/activities/explore_world_animals/resource/tux.svg",
"title": qsTr("Giraffe"),
"text": qsTr("The giraffe lives in Africa and is the tallest mammal in the world. Just their legs, which are usually 1.8 meters long, are taller than most humans!"),
"image2": "qrc:/gcompris/src/activities/explore_world_animals/resource/giraffe.jpg",
"text2": qsTr("Giraffe"),
"x": 0.58,
"y": 0.48,
"width": 0.0785,
"height": 0.1005
},
{
"image": "qrc:/gcompris/src/activities/explore_world_animals/resource/tux.svg",
"title": qsTr("Bison"),
"text": qsTr("Bison live on the plains of North America and were hunted by the Native Americans for food."),
"image2": "qrc:/gcompris/src/activities/explore_world_animals/resource/bison.jpg",
"text2": qsTr("Bison"),
"x": 0.27,
"y": 0.29,
"width": 0.0785,
"height": 0.1005
},
{
"image": "qrc:/gcompris/src/activities/explore_world_animals/resource/tux.svg",
"title": qsTr("Narwhal"),
"text": qsTr("Narwhals are whales that live in the Arctic Ocean and have long tusks. These tusks remind many people of the mythical unicorn's horn."),
"image2": "qrc:/gcompris/src/activities/explore_world_animals/resource/narwhal.jpg",
"text2": qsTr("Narwhal"),
"x": 0.50,
"y": 0.06,
"width": 0.0785,
"height": 0.1005
}
]
var instruction = [
{
"text": qsTr("Explore exotic animals from around the world.")
},
{
"text": qsTr("Click on location where the given animal lives.")
}
]
|
jamesthechamp/gcompris-recyclebin
|
src/activities/explore_world_animals/explore_world_animals.js
|
JavaScript
|
gpl-3.0
| 3,641 |
/*
Part of the Shuttr app by @aureljared.
Licensed under GPLv3.
http://github.com/aureljared/shuttr
*/
// Logging
const l = require('./logger').log;
var log = function(msg) { l('ui-buttons', msg) };
const hb = require('./heartbeat');
const fn = require('./shuttr');
const ants = require('./constants');
const query = require('./stethoscope').query;
const populateList = require('./ui-populate');
var prefs = {
grid: 0, // disabled
video: {
res: 0, // 4k
fps: 8, // 4k 24fps
fov: 3, // 4k 24fps superview
pro: 1, // on
pt: {
color: 0, // GoPro
wb: 0, // auto
iso: 9, // auto (SEPARATE KEY IN CONSTANTS)
shut: 8, // 1/60s
ev: 4, // off
shrp: 0, // hi
rawaud: 3 // off
},
lolt: 0, // off
stab: 0, // off
aud: 2, // auto
},
photo: {
pro: 0, // off
pt: {
color: 0, // GoPro
wb: 0, // auto
isomin: 3, // 100
isomax: 0, // 800
ev: 4, // off
shrp: 0, // hi
},
raw: 0, // off
wdr: 0 // off
}
};
// Flip boolean values and convert to 1/0
var flip = function(val) {
return !val ? 1 : 0;
}
// On button click
var bindToButton = function(id, fn) { $('#' + id).click(fn) }
var init = function() {
// Controls switcher
$("#modeselect li:first-child").hover(function(){
$("#modeselect .triangle").css("border-bottom-color", "#dab12e");
}, function(){
$("#modeselect .triangle").removeAttr("style");
});
// Power
$('#pwr').click(function(){
hb.test(function(){
// Switch off
$('.message').each(function(){ $(this).hide() });
$('#msg_off').show();
$('#msg_off .title').text("Turning camera off");
$('#messages').fadeIn();
fn.controls.vf_close();
hb.stop();
fn.power.off();
$('#msg_off .title').text("Camera is off");
}, function(){
// Switch on
$('#msg_off .title').text("Turning camera on");
fn.power.on(function(){
$('#messages').fadeOut();
});
});
})
// Start/stop recording
bindToButton('shutter', function(){
var busy = query.status('IS_BUSY');
if (busy == 1) {
fn.controls.stoprec();
$('.shutter').removeClass("rolling");
} else {
fn.controls.trigger();
if (query.status("CURRENT_MODE") == 0)
$('.shutter').addClass("rolling");
}
});
// Switch modes
bindToButton('mode_video_normal', fn.mode.video);
bindToButton('mode_video_timelapse', fn.mode.tl_video);
bindToButton('mode_video_vphoto', fn.mode.vphoto);
bindToButton('mode_video_looping', fn.mode.looping);
bindToButton('mode_photo_normal', fn.mode.photo);
bindToButton('mode_photo_cont', fn.mode.continuous);
bindToButton('mode_photo_night', fn.mode.night);
bindToButton('mode_multi_burst', fn.mode.burst);
bindToButton('mode_multi_timelapse', fn.mode.timelapse);
bindToButton('mode_multi_nightlapse', fn.mode.nightlapse);
$("#modeselect li").click(function(){
var mode = $(this).text();
$('#stat_mode').text(mode);
})
/**********************
Footage settings
**********************/
$('select[name=res]').on('change', function(){
var val = parseInt($(this).val());
fn.set(2, val);
prefs.video.res = val;
// Update available fps
populateList(val);
})
$('select[name=fps]').on('change', function(){
var val = parseInt($(this).val());
prefs.video.fps = val;
fn.set(3, val);
// Update available FOVs
populateList(null, val);
})
$('select[name=fov]').on('change', function(){
var val = parseInt($(this).val());
prefs.video.fov = val;
fn.set(4, val);
})
/***************
Controls
***************/
// Protune master toggle
$('#set_pro').click(function(){
prefs[mode].pro = flip(prefs[mode].pro);
var ptKey = ants[model].settings[mode].PROTUNE;
fn.set(ptKey, prefs[mode].pro);
if (prefs[mode].pro) {
$(this).addClass("on");
$("td.pt").each(function(){ $(this).removeClass("disabled") });
} else {
$(this).removeClass("on");
$("td.pt").each(function(){ $(this).addClass("disabled") });
}
})
// Stabilizer
$("#set_stab").click(function(){
prefs.video.stab = flip(prefs.video.stab);
fn.set(ants[model].settings.video.STABILIZER, prefs.video.stab);
if (prefs.video.stab)
$(this).addClass("on")
else
$(this).removeClass("on");
})
// Auto low light
$("#set_lolt").click(function(){
prefs.video.lolt = flip(prefs.video.lolt);
fn.set(ants[model].settings.video.LOWLIGHT, prefs.video.lolt);
if (prefs.video.lolt)
$(this).addClass("on")
else
$(this).removeClass("on");
})
// Grid
$('#set_grid').click(function(){
prefs.grid++;
if (prefs.grid == 3)
prefs.grid = 0;
switch (prefs.grid) {
case 0:
$(this).text("off");
$('#overlays > div').each(function(){ $(this).addClass("hidden") });
break;
case 1:
$(this).text("thirds");
$("#overlays .quadgrid").addClass("hidden");
$("#overlays .thirdgrid").removeClass("hidden");
break;
case 2:
$(this).text("quads");
$("#overlays .thirdgrid").addClass("hidden");
$("#overlays .quadgrid").removeClass("hidden");
break;
}
})
};
module.exports.init = init;
|
aureljared/shuttr
|
js/ui-buttons.js
|
JavaScript
|
gpl-3.0
| 6,028 |
exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('action_user').del()
.then(function () {
return Promise.all([
// Inserts seed entries
// knex('action_user').insert({action_user_id:1, action_id: 1, user_id: 1, points: 5}),
knex('action_user').insert({action_user_id:2, action_id: 2, user_id: 1, points: 5, skip:true})
]);
});
};
|
ITsolution-git/actodo
|
src/db/seeds/action_user.js
|
JavaScript
|
gpl-3.0
| 414 |