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 |
|---|---|---|---|---|---|
// Inspiration : https://atom.io/packages/ide-haskell
// and https://atom.io/packages/ide-flow
// https://atom.io/packages/atom-typescript
var rx_1 = require("rx");
var Omni = require('../../omni-sharp-server/omni');
var TooltipView = require('../views/tooltip-view');
var $ = require('jquery');
var escape = require("escape-html");
var TypeLookup = (function () {
function TypeLookup() {
}
TypeLookup.prototype.activate = function () {
var _this = this;
this.disposable = new rx_1.CompositeDisposable();
this.disposable.add(Omni.activeEditor.where(function (z) { return !!z; }).subscribe(function (editor) {
var cd = new rx_1.CompositeDisposable();
// subscribe for tooltips
// inspiration : https://github.com/chaika2013/ide-haskell
var editorView = $(atom.views.getView(editor));
var tooltip = editor['__omniTooltip'] = new Tooltip(editorView, editor);
cd.add(tooltip);
editor.onDidDestroy(function () {
editor['__omniTooltip'] = null;
cd.dispose();
});
cd.add(Omni.activeEditor.where(function (active) { return active !== editor; }).subscribe(function () {
cd.dispose();
_this.disposable.remove(cd);
}));
}));
this.disposable.add(Omni.addTextEditorCommand("omnisharp-atom:type-lookup", function () {
Omni.activeEditor.first().subscribe(function (editor) {
var tooltip = editor['__omniTooltip'];
tooltip.showExpressionTypeOnCommand();
});
}));
};
TypeLookup.prototype.dispose = function () {
this.disposable.dispose();
};
return TypeLookup;
})();
var Tooltip = (function () {
function Tooltip(editorView, editor) {
var _this = this;
this.editorView = editorView;
this.editor = editor;
this.exprTypeTimeout = null;
this.exprTypeTooltip = null;
this.rawView = editorView[0];
var scroll = this.getFromShadowDom(editorView, '.scroll-view');
// to debounce mousemove event's firing for some reason on some machines
var lastExprTypeBufferPt;
var mousemove = rx_1.Observable.fromEvent(scroll[0], 'mousemove');
var mouseout = rx_1.Observable.fromEvent(scroll[0], 'mouseout');
this.keydown = rx_1.Observable.fromEvent(scroll[0], 'keydown');
var cd = this.disposable = new rx_1.CompositeDisposable();
cd.add(mousemove.map(function (event) {
var pixelPt = _this.pixelPositionFromMouseEvent(editorView, event);
var screenPt = editor.screenPositionForPixelPosition(pixelPt);
var bufferPt = editor.bufferPositionForScreenPosition(screenPt);
if (lastExprTypeBufferPt && lastExprTypeBufferPt.isEqual(bufferPt) && _this.exprTypeTooltip)
return null;
lastExprTypeBufferPt = bufferPt;
return { bufferPt: bufferPt, event: event };
})
.where(function (z) { return !!z; })
.tapOnNext(function () { return _this.hideExpressionType(); })
.debounce(200)
.where(function (x) { return _this.checkPosition(x.bufferPt); })
.tapOnNext(function () { return _this.subcribeKeyDown(); })
.subscribe(function (_a) {
var bufferPt = _a.bufferPt, event = _a.event;
_this.showExpressionTypeOnMouseOver(event, bufferPt);
}));
cd.add(mouseout.subscribe(function (e) { return _this.hideExpressionType(); }));
cd.add(Omni.activeEditor.subscribe(function (activeItem) {
_this.hideExpressionType();
}));
}
Tooltip.prototype.subcribeKeyDown = function () {
var _this = this;
this.keydownSubscription = this.keydown.subscribe(function (e) { return _this.hideExpressionType(); });
this.disposable.add(this.keydownSubscription);
};
Tooltip.prototype.showExpressionTypeOnCommand = function () {
if (this.editor.cursors.length < 1)
return;
var buffer = this.editor.getBuffer();
var bufferPt = this.editor.getCursorBufferPosition();
if (!this.checkPosition(bufferPt))
return;
// find out show position
var offset = (this.rawView.component.getFontSize() * bufferPt.column) * 0.7;
var rect = this.getFromShadowDom(this.editorView, '.cursor-line')[0].getBoundingClientRect();
var tooltipRect = {
left: rect.left - offset,
right: rect.left + offset,
top: rect.bottom,
bottom: rect.bottom
};
this.hideExpressionType();
this.subcribeKeyDown();
this.showToolTip(bufferPt, tooltipRect);
};
Tooltip.prototype.showExpressionTypeOnMouseOver = function (e, bufferPt) {
if (!Omni.isOn) {
return;
}
// If we are already showing we should wait for that to clear
if (this.exprTypeTooltip)
return;
// find out show position
var offset = this.editor.getLineHeightInPixels() * 0.7;
var tooltipRect = {
left: e.clientX,
right: e.clientX,
top: e.clientY - offset,
bottom: e.clientY + offset
};
this.showToolTip(bufferPt, tooltipRect);
};
Tooltip.prototype.checkPosition = function (bufferPt) {
var curCharPixelPt = this.rawView.pixelPositionForBufferPosition([bufferPt.row, bufferPt.column]);
var nextCharPixelPt = this.rawView.pixelPositionForBufferPosition([bufferPt.row, bufferPt.column + 1]);
if (curCharPixelPt.left >= nextCharPixelPt.left) {
return false;
}
else {
return true;
}
;
};
Tooltip.prototype.showToolTip = function (bufferPt, tooltipRect) {
var _this = this;
this.exprTypeTooltip = new TooltipView(tooltipRect);
var buffer = this.editor.getBuffer();
// TODO: Fix typings
// characterIndexForPosition should return a number
//var position = buffer.characterIndexForPosition(bufferPt);
// Actually make the program manager query
Omni.request(function (client) { return client.typelookup({
IncludeDocumentation: true,
Line: bufferPt.row,
Column: bufferPt.column,
FileName: _this.editor.getURI()
}); }).subscribe(function (response) {
if (response.Type === null) {
return;
}
var message = "<b>" + escape(response.Type) + "</b>";
if (response.Documentation) {
message = message + ("<br/><i>" + escape(response.Documentation) + "</i>");
}
// Sorry about this "if". It's in the code I copied so I guess its there for a reason
if (_this.exprTypeTooltip) {
_this.exprTypeTooltip.updateText(message);
}
});
};
Tooltip.prototype.dispose = function () {
this.disposable.dispose();
};
Tooltip.prototype.hideExpressionType = function () {
if (!this.exprTypeTooltip)
return;
this.exprTypeTooltip.remove();
this.exprTypeTooltip = null;
if (this.keydownSubscription) {
this.disposable.remove(this.keydownSubscription);
this.keydownSubscription.dispose();
this.keydownSubscription = null;
}
};
Tooltip.prototype.getFromShadowDom = function (element, selector) {
var el = element[0];
var found = el.rootElement.querySelectorAll(selector);
return $(found[0]);
};
Tooltip.prototype.pixelPositionFromMouseEvent = function (editorView, event) {
var clientX = event.clientX, clientY = event.clientY;
var linesClientRect = this.getFromShadowDom(editorView, '.lines')[0].getBoundingClientRect();
var top = clientY - linesClientRect.top;
var left = clientX - linesClientRect.left;
top += this.editor.displayBuffer.getScrollTop();
left += this.editor.displayBuffer.getScrollLeft();
return { top: top, left: left };
};
Tooltip.prototype.screenPositionFromMouseEvent = function (editorView, event) {
return editorView.getModel().screenPositionForPixelPosition(this.pixelPositionFromMouseEvent(editorView, event));
};
return Tooltip;
})();
exports.typeLookup = new TypeLookup;
| joerter/atom-config | .atom/packages/omnisharp-atom/lib/omnisharp-atom/features/lookup.js | JavaScript | mit | 8,529 |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define({about:"\u0646\u0628\u0630\u0629 \u0639\u0646",add:"\u0625\u0636\u0627\u0641\u0629",all:"\u062c\u0645\u064a\u0639",apply:"\u062a\u0637\u0628\u064a\u0642",auth:{logOut:"\u062a\u0633\u062c\u064a\u0644 \u0627\u0644\u062e\u0631\u0648\u062c",signIn:"\u062a\u0633\u062c\u064a\u0644 \u0627\u0644\u062f\u062e\u0648\u0644"},back:"\u0627\u0644\u0633\u0627\u0628\u0642",cancel:"\u0625\u0644\u063a\u0627\u0621",change:"\u062a\u063a\u064a\u064a\u0631",clear:"\u0645\u0633\u062d",close:"\u0625\u063a\u0644\u0627\u0642",
collapse:"\u0637\u064a",configure:"\u062a\u0643\u0648\u064a\u0646",control:{pause:"\u0625\u064a\u0642\u0627\u0641 \u0645\u0624\u0642\u062a",play:"\u062a\u0634\u063a\u064a\u0644",resume:"\u064a\u062a\u0627\u0628\u0639",stop:"\u0625\u064a\u0642\u0627\u0641"},copy:"\u0646\u0633\u062e",create:"\u0625\u0646\u0634\u0627\u0621",cut:"\u0642\u0635","delete":"\u062d\u0630\u0641",details:"\u0627\u0644\u062a\u0641\u0627\u0635\u064a\u0644",done:"\u062a\u0645",dragHandleTitle:"\u0633\u062d\u0628/\u0625\u0639\u0627\u062f\u0629 \u0627\u0644\u062a\u0631\u062a\u064a\u0628",
dragHandleLabel:"\u0642\u0645 \u0628\u062a\u0641\u0639\u064a\u0644 \u0632\u0631 \u0625\u0639\u0627\u062f\u0629 \u0627\u0644\u062a\u0631\u062a\u064a\u0628 \u0648\u0627\u0633\u062a\u062e\u062f\u0645 \u0645\u0641\u0627\u062a\u064a\u062d \u0627\u0644\u0623\u0633\u0647\u0645 \u0644\u0625\u0639\u0627\u062f\u0629 \u062a\u0631\u062a\u064a\u0628 \u0627\u0644\u0642\u0627\u0626\u0645\u0629 \u0623\u0648 \u0627\u0633\u062a\u062e\u062f\u0627\u0645 \u0627\u0644\u0641\u0623\u0631\u0629 \u0644\u0644\u0633\u062d\u0628/\u0625\u0639\u0627\u062f\u0629 \u0627\u0644\u062a\u0631\u062a\u064a\u0628. \u0627\u0636\u063a\u0637 \u0639\u0644\u0649 escape \u0644\u0625\u0644\u063a\u0627\u0621 \u0627\u0644\u062a\u0631\u062a\u064a\u0628.",
edit:"\u062a\u062d\u0631\u064a\u0631",error:"\u062e\u0637\u0623",esri:"Esri",exit:"\u062e\u0631\u0648\u062c",expand:"\u062a\u0648\u0633\u064a\u0639",fieldsSummary:"\u0642\u0627\u0626\u0645\u0629 \u0627\u0644\u0628\u064a\u0627\u0646\u0627\u062a \u0627\u0644\u062c\u062f\u0648\u0644\u064a\u0629 \u0648\u0627\u0644\u0642\u064a\u0645",find:"\u0628\u062d\u062b",form:{no:"\u0644\u0627",ok:"\u0645\u0648\u0627\u0641\u0642",password:"\u0643\u0644\u0645\u0629 \u0627\u0644\u0645\u0631\u0648\u0631",submit:"\u0625\u0631\u0633\u0627\u0644",
username:"\u0627\u0633\u0645 \u0627\u0644\u0645\u0633\u062a\u062e\u062f\u0645",yes:"\u0646\u0639\u0645"},help:"\u062a\u0639\u0644\u064a\u0645\u0627\u062a",home:"\u0627\u0644\u0635\u0641\u062d\u0629 \u0627\u0644\u0631\u0626\u064a\u0633\u064a\u0629",info:"\u0645\u0639\u0644\u0648\u0645\u0627\u062a",information:"\u0645\u0639\u0644\u0648\u0645\u0627\u062a",layer:"\u0627\u0644\u0637\u0628\u0642\u0629",loading:"\u062a\u062d\u0645\u064a\u0644",maximize:"\u062a\u0643\u0628\u064a\u0631",menu:"\u0627\u0644\u0642\u0627\u0626\u0645\u0629",
more:"\u0627\u0644\u0645\u0632\u064a\u062f",none:"\u0644\u0627 \u0634\u064a\u0621",open:"\u0641\u062a\u062d",pagination:{first:"\u0627\u0644\u0623\u0648\u0644",last:"\u0623\u062e\u064a\u0631",next:"\u0627\u0644\u062a\u0627\u0644\u064a",page:"\u0635\u0641\u062d\u0629",pageText:"{index} \u0645\u0646 {total}",previous:"\u0627\u0644\u0633\u0627\u0628\u0642"},paste:"\u0644\u0635\u0642",preview:"\u0645\u0639\u0627\u064a\u0646\u0629",print:"\u0637\u0628\u0627\u0639\u0629",publish:"\u0646\u0634\u0631",redo:"\u0625\u0639\u0627\u062f\u0629",
refresh:"\u062a\u062d\u062f\u064a\u062b",remove:"\u0625\u0632\u0627\u0644\u0629",rename:"\u0625\u0639\u0627\u062f\u0629 \u062a\u0633\u0645\u064a\u0629",reset:"\u0625\u0639\u0627\u062f\u0629 \u062a\u0639\u064a\u064a\u0646",restore:"\u0627\u0633\u062a\u0639\u0627\u062f\u0629",save:"\u062d\u0641\u0638",search:"\u0628\u062d\u062b",searching:"\u062c\u0627\u0631\u0650 \u0627\u0644\u0628\u062d\u062b",select:"\u062a\u062d\u062f\u064a\u062f",settings:"\u0627\u0644\u0625\u0639\u062f\u0627\u062f\u0627\u062a",
sort:"\u0641\u0631\u0632",share:"\u0645\u0634\u0627\u0631\u0643\u0629",title:"\u0627\u0644\u0639\u0646\u0648\u0627\u0646",untitled:"\u0628\u0644\u0627 \u0639\u0646\u0648\u0627\u0646",unnamed:"\u063a\u064a\u0631 \u0645\u0633\u0645\u0649",update:"\u062a\u062d\u062f\u064a\u062b",upload:"\u062a\u062d\u0645\u064a\u0644",undo:"\u062a\u0631\u0627\u062c\u0639",view:"\u0639\u0631\u0636",visibility:{hide:"\u0625\u062e\u0641\u0627\u0621",show:"\u0625\u0638\u0647\u0627\u0631",toggle:"\u062a\u0628\u062f\u064a\u0644"},
warning:"\u062a\u062d\u0630\u064a\u0631"}); | ycabon/presentations | 2020-devsummit/arcgis-js-api-road-ahead/js-api/esri/nls/ar/common.js | JavaScript | mit | 4,609 |
/* -*- mode: javascript; js-indent-level: 2; -*- */
(function() {
var accordion = document.querySelector(".accordion");
if (!accordion) {
return;
}
var header = accordion.firstElementChild;
if (!header) {
return;
}
function addTopNav(container) {
var topnav = document.createElement('div');
topnav.setAttribute('class', 'tutorialNavigationHeader');
container.appendChild(topnav);
container.setAttribute('class', 'tutorialContainer');
}
function addBottomNav(container) {
var button = document.createElement('button');
button.textContent = "Next Step";
button.setAttribute('class', 'btn btn-success btn-lg tutorialNextButton');
var bottomnav = document.createElement('div');
bottomnav.setAttribute('class', 'tutorialNextButtonContainer');
bottomnav.appendChild(button);
container.appendChild(bottomnav);
}
var headerTag = header.tagName;
var secondaryTag = 'H' + (parseInt(headerTag[1]) + 1);
var container = document.createElement('div');
var sibling = header.nextElementSibling;
var firstNav = true;
var isTutorialBody = false;
var sawNav = false;
var shouldAddNav = false;
var subcontainer;
while (sibling) {
var next = sibling.nextElementSibling;
if (sibling.tagName == 'NAV') {
sibling.remove();
if (firstNav) {
addTopNav(container);
isTutorialBody = true;
firstNav = false;
sawNav = true;
} else {
if (isTutorialBody) {
container.appendChild(subcontainer);
subcontainer = null;
isTutorialBody = false;
}
addBottomNav(container);
}
/*
} else if (sibling.tagName == 'HINT') {
sibling.remove();
var hint = document.createElement('div');
hint.setAttribute('class', 'hintContainer');
var button = document.createElement('button'),
content = document.createElement('div');
content.setAttribute('class', 'hint hideHint');
hint.appendChild(button);
hint.appendChild(content);
button.textContent = sibling.getAttribute('title');
content.innerHTML = sibling.innerHTML;
if (isTutorialBody) {
subcontainer.appendChild(hint);
} else {
container.appendChild(hint);
}*/
} else if (sibling.tagName != header.tagName) {
if (isTutorialBody || sibling.tagName == secondaryTag) {
if (sibling.tagName != secondaryTag) {
subcontainer.appendChild(sibling);
} else {
if (subcontainer) {
container.appendChild(subcontainer);
} else {
// First subdivison, add nav header
if (!sawNav) {
addTopNav(container);
isTutorialBody = true;
firstNav = false;
shouldAddNav = true;
}
}
subcontainer = document.createElement('div');
subcontainer.setAttribute('class', 'tutorialContentPage');
subcontainer.appendChild(sibling); // move subheading
}
} else {
container.appendChild(sibling);
}
} else {
if (isTutorialBody) {
container.appendChild(subcontainer);
}
if (shouldAddNav && !sawNav) {
addBottomNav(container);
}
accordion.insertBefore(container, sibling);
container = document.createElement('div');
isTutorialBody = false;
subcontainer = null;
firstNav = true;
sawNav = false;
shouldAddNav = false;
}
sibling = next;
}
if (isTutorialBody) {
container.appendChild(subcontainer);
}
if (shouldAddNav) {
addBottomNav(container);
}
accordion.appendChild(container);
$( ".accordion" ).accordion({heightStyle: "content"});
var howtos = document.querySelectorAll('howto');
for (var i = 0; i < howtos.length; i++ ) {
var howto = howtos[i];
var div = document.createElement('div');
div.setAttribute('class', 'setup');
div.setAttribute('id', howto.getAttribute('id'));
howto.replaceWith(div);
}
// Convert HINT elements
var hints = document.querySelectorAll('hint');
for (var i = hints.length - 1; i >= 0; i--) {
var hint = document.createElement('div');
hint.setAttribute('class', 'hintContainer');
var button = document.createElement('button'),
content = document.createElement('div');
content.setAttribute('class', 'hint hideHint');
hint.appendChild(button);
hint.appendChild(content);
button.textContent = hints[i].getAttribute('title');
content.innerHTML = hints[i].innerHTML;
hints[i].replaceWith(hint);
}
// Convert NOTE elements
var notes = document.querySelectorAll('note');
for (var i = 0; i < notes.length; i++) {
var note = notes[i];
var table = document.createElement('table');
table.setAttribute('class', 'note');
var tbody = document.createElement('tbody');
var tr = document.createElement('tr');
var td = document.createElement('td');
var noteImage = document.createElement('img');
noteImage.setAttribute('src', '/punya-tutorials/images/note.png');
noteImage.setAttribute('alt', 'Note:');
td.appendChild(noteImage);
tr.appendChild(td);
td = document.createElement('td');
td.innerHTML = note.innerHTML;
tr.appendChild(td);
tbody.appendChild(tr);
table.appendChild(tbody);
note.replaceWith(table);
}
// Open external lnks in a new tab/window
var links = accordion.querySelectorAll('a');
for (var i = 0; i < links.length; i++) {
if (links[i].href.indexOf('http:') == 0 || links[i].href.indexOf('https:') == 0) {
links[i].setAttribute('target', '_blank');
}
}
})();
| mit-dig/punya-tutorials | scripts/markdown.js | JavaScript | mit | 5,687 |
// server.js
const express = require('express');
const app = express();
const path = require('path');
// If an incoming request uses a protocol other than HTTPS,
// redirect that request to the same url but with HTTPS
const forceSSL = function() {
return function (req, res, next) {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(
['https://', req.get('Host'), req.url].join('')
);
}
next();
}
}
// Instruct the app to use the forceSSL middleware
app.use(forceSSL());
// Run the app by serving the static files in the dist directory
app.use(express.static(__dirname + '/dist'));
// Start the app by listening on the default Heroku port
app.listen(process.env.PORT || 8080);
// For all GET requests, send back index.html so that PathLocationStrategy can be used
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/index.html'));
});
console.log('finish')
| jdflaugergues/salati | server.js | JavaScript | mit | 946 |
'use strict';
Connector.playerSelector = '.controls';
Connector.artistTrackSelector = '.scroll-title';
Connector.isPlaying = () => $('.controls .fa-pause').length > 0;
| Paszt/web-scrobbler | connectors/monstercat.js | JavaScript | mit | 171 |
'use strict';
var $ = {
util: require('gulp-util')
};
module.exports = {
appName: 'vbudWebsite',
errorHandler: function (title) {
return function (err) {
$.util.log($.util.colors.red('[' + title + ']'), err.toString());
this.emit('end');
};
},
wiredep: {
directory: 'bower_components'
},
paths: {
// src directories
src: 'src',
styles: 'src/styles',
fonts: 'src/fonts',
posts: 'src/blog/posts',
// dependencies directories
bower: 'bower_components',
// tmp directories
tmp: '.tmp',
tmpTemplates: '.tmp/templates',
tmpServe: '.tmp/serve',
tmpPosts: '.tmp/serve/blog/posts',
tmpDist: '.tmp/dist',
dist: 'dist',
e2e: 'e2e',
// generator templates
templates: 'templates'
}
};
| vbud/vbud.github.io | gulp/config.js | JavaScript | mit | 729 |
// jQuery.Promises, v1.0.4
// Copyright (c) 2011-2017 Michael Heim, Zeilenwechsel.de
// Distributed under MIT license
// http://github.com/hashchange/jquery.promises
;( function ( root, factory ) {
"use strict";
if ( typeof exports === 'object' ) {
module.exports = factory( require( 'jquery' ) );
} else if ( typeof define === 'function' && define.amd ) {
define( ['jquery'], factory );
}
}( this, function ( jQuery ) {
"use strict";
;( function( jQuery ) {
"use strict";
// Detect support for deferred.isResolved, deferred.isRejected in the available jQuery version
var dfdHasFeature = (function () {
var dfd = jQuery.Deferred();
return {
isResolved: !! dfd.isResolved,
isRejected: !! dfd.isRejected
};
})();
jQuery.extend( {
Promises: ( function ( $ ) {
var Promises = function () {
var masterDfd = $.Deferred(),
collected = [],
counter = 0,
block,
blockIndex,
ignoreBelatedCalls = false,
resolveIfCurrent = function ( counterAtInvokation ) {
return function() {
if ( counter === counterAtInvokation ) masterDfd.resolve.apply( this, arguments );
};
},
rejectIfCurrent = function ( counterAtInvokation ) {
return function() {
if ( counter === counterAtInvokation ) masterDfd.reject.apply( this, arguments );
};
},
/**
* Takes an array of objects and removes any duplicates. The first
* occurrence of the object is preserved. The order of elements
* remains unchanged.
*
* @param {Array} arr
* @returns {Array}
*/
toUniqueObjects = function ( arr ) {
var unique = [],
duplicate,
i, j, len, uniqueLen;
for ( i = 0, len = arr.length; i < len; i++ ) {
duplicate = false;
for ( j = 0, uniqueLen = unique.length; j < uniqueLen; j++ ) duplicate = ( arr[i] === unique[j] ) || duplicate;
if ( ! duplicate ) unique.push( arr[i] );
}
return unique;
};
// Make 'new' optional
if ( ! ( this instanceof Promises ) ) {
var obj = new Promises();
return Promises.apply( obj, arguments );
// ... re-runs the constructor function, same as
// obj.constructor.apply( obj, arguments );
}
// Keep `isResolved` and `isRejected` available in jQuery >= 1.8
if ( ! dfdHasFeature.isResolved ) {
this.isResolved = function () {
return this.state() === "resolved";
};
}
if ( ! dfdHasFeature.isRejected ) {
this.isRejected = function () {
return this.state() === "rejected";
};
}
this.add = function () {
if ( collected[0] && ! this.isUnresolved() && ! ignoreBelatedCalls ) {
throw {
name: 'PromisesError',
message: "Can't add promise when Promises is no longer unresolved"
};
}
for ( var i = 0; i < arguments.length; i++ ) collected.push( arguments[i] );
collected = toUniqueObjects( collected );
if ( collected.length ) {
counter++;
$.when.apply( this, collected )
.done( resolveIfCurrent( counter ) )
.fail( rejectIfCurrent( counter ) );
}
return this;
};
this.postpone = function () {
if ( ! block ) {
if ( collected[0] && ! this.isUnresolved() && ! ignoreBelatedCalls ) {
throw {
name: 'PromisesError',
message: "Can't postpone resolution when Promises is no longer unresolved"
};
}
block = $.Deferred();
blockIndex = collected.length;
this.add( block );
}
return this;
};
this.stopPostponing = function () {
if ( block ) {
collected.splice( blockIndex, 1 );
this.add(); // we don't add anything, but the masterDeferred will be updated
block = null;
}
return this;
};
this.ignoreBelated = function ( yesno ) {
ignoreBelatedCalls = ! yesno;
return this;
};
this.isUnresolved = function () {
return ! ( this.isResolved() || this.isRejected() );
};
this.add.apply( this, arguments );
return masterDfd.promise( this );
};
return Promises;
} )( jQuery )
} );
}( jQuery ));
return jQuery.Promises;
} ));
| hashchange/jquery.promises | dist/amd/jquery.promises.js | JavaScript | mit | 6,708 |
import { observable, action, computed } from 'mobx';
class TracksStore {
@observable tracks;
@observable activeTrackId;
@observable activeIdx;
constructor(tracks = []) {
this.tracks = tracks;
this.activeTrackId = null;
this.activeIdx = null;
}
@computed get activeTrack() {
return tracksStore.tracks.find((track) => track.origin.id === tracksStore.activeTrackId);
}
@action setTracks = (tracks) => {
this.tracks = tracks;
}
@action playTrack = (track) => {
this.activeTrackId = track.origin.id;
}
// @action playPreviousTrack() {
// this.tracks.indexOf(this.activeTrackId)
// }
}
const tracksStore = new TracksStore();
export default tracksStore;
| choosenvictim/soundmobx | js/stores/tracksStore.js | JavaScript | mit | 763 |
/* CONFIGURATIONS -- PATH */
const paths = {
src: 'assets/',
dist: 'static/',
templates: 'assets/templates/',
npm: 'node_modules/',
template: 'node_modules/govuk_template_jinja/',
toolkit: 'node_modules/govuk_frontend_toolkit/'
};
export default paths;
| dahfool/navigator | projectpath.babel.js | JavaScript | mit | 279 |
function run(LoginService, $state) {
LoginService.loggedinRequest().then(res => {
console.log('run login request:');
console.log(res);
if (res.loggedin) $state.go('home');
});
}
module.exports = [
'LoginService',
'$state',
run
]; | sjt88/express-angular1-webpack-massive-boilerplate | client/src/js/run.js | JavaScript | mit | 249 |
//Declare gulp requirements.
var argv = require('yargs').argv;
var autoprefix = require('gulp-autoprefixer');
var cache = require('gulp-cache');
var concat = require('gulp-concat');
var fs = require('fs');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var cssnano = require('gulp-cssnano');
var notify = require('gulp-notify');
var rename = require('gulp-rename');
var replace = require('gulp-replace');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var yargs = require('yargs');
//Declare variables.
var die = false;
//Check if this is a development version.
var dev = (!argv.dev) ? false : true;
//Get the package.json version.
var version = JSON.parse(fs.readFileSync('./package.json')).version.split('.');
//For each version value.
for(i = 0; i < version.length; i++) {
//Parse the version as an integer type.
version[i] = parseInt(version[i]);
}
//Get the increment value.
var increment = (!dev) ? ((version[3] % 2 !== 0) ? 1 : 2) : ((version[3] % 2 !== 0) ? 2 : 1);
//Based on the existing version number.
if (version[3] + increment >= 10) {
if (version[2] + 1 >= 10) {
version[1] += 1;
version[2] = 0;
} else {
version[2] += 1;
}
version[3] += increment - 10;
} else {
version[3] += increment;
}
//Rebuild the version.
version = version.join('.');
//Sass.
gulp.task('sass', function() {
//Run Gulp.
return gulp.src('./src/sass/stylesheet.scss')
.pipe(gulpif(!die, gulpif(dev, sourcemaps.init())))
.pipe(sass({
sourcemap: true,
outputStyle: 'expanded',
includePaths: ['./node_modules/foundation-sites/scss']
}))
.on('error', notify.onError(function(error) {
//Set die as true.
die = true;
//Log to the console.
console.error(error);
//Return the error.
return error;
}))
.pipe(autoprefix({browsers: '> 5%'}))
.pipe(gulpif(!die, gulpif(!dev, cssnano())))
.pipe(gulpif(!die, gulpif(dev, sourcemaps.write())))
.pipe(gulpif(!die, gulp.dest('./css/')))
.pipe(gulpif(die, function() {
//Reset die.
die = false;
//Return true.
return true;
}));
});
//Hint.
gulp.task('hint', function() {
//Run Gulp.
return gulp.src('./src/js/**/*.js')
.pipe(jshint())
.pipe(notify(function(file) {
//If not success.
if (!file.jshint.success) {
//Get the errors.
var errors = file.jshint.results.map(function(data) {
//If there's an error.
if (data.error) {
//Increment the error.
return "(" + data.error.line + ":" + data.error.character + ") " + data.error.reason;
}
}).join("\n");
//Display the errors.
return file.relative + "[" + file.jshint.results.length + " errors]\n" + errors;
}
}))
.pipe(jshint.reporter('default'));
});
//Hint.
gulp.task('js', function() {
//Run Gulp.
return gulp.src([
'./node_modules/foundation-sites/dist/js/foundation.js',
'./src/js/**/*.js'
])
.pipe(gulpif(!dev, uglify({'preserveComments': 'license'}).on('error', notify.onError(function(error) {
//Log to the console.
console.error(error);
//Return the error.
return error;
}))))
.pipe(concat('main.js'))
.pipe(gulp.dest('./js/'));
});
//Images.
gulp.task('images', function() {
return gulp.src('./src/images/**/*')
.pipe(cache(imagemin({
interlaced: true,
multipass: true,
optimizationLevel: 5,
progressive: true,
svgoPlugins: [{removeViewBox: false}]
})))
.pipe(gulp.dest('./images/'));
});
//Version control.
gulp.task('version', function() {
//Run Gulp.
/*gulp.src([
'index.html'
], {base: './'})
.pipe(replace(/(.*(css|js))(\?v=.*)?(\".*)/g, '$1?v=' + version + '$4'))
.pipe(gulp.dest('./'));*/
//Run Gulp.
gulp.src('./package.json')
.pipe(replace(/(.*)(\"version\": \")(.*)(\".*)/g, '$1$2' + version + '$4'))
.pipe(gulp.dest('./'));
});
//Watch for changes.
gulp.task('watch', function() {
//Setup watch for Sass.
gulp.watch(['./src/sass/**/*.scss'], ['sass']);
//Setup watch for Hint.
gulp.watch(['./src/js/**/*.js'], ['hint']);
//Setup watch for JS.
gulp.watch(['./src/js/**/*.js'], ['js']);
//Setup watch for images.
gulp.watch(['./src/images/**/*'], ['images']);
});
//Task runner.
gulp.task('default', ['sass', 'hint', 'js', 'images', 'watch', 'version']); | mookman288/FrozenBones-Foundation | gulpfile.js | JavaScript | mit | 4,400 |
// Configure loading modules from the javascripts directory by default
requirejs.config({
baseUrl: 'javascripts',
transitive: true,
paths: {
//
// this section is completed automatically by bower-requirejs in the
// bower postinstall script hook. To manually update, run:
//
// ./node_modules/.bin/bower-requirejs -c public/javascripts/main.js
//
'blueimp-canvas-to-blob': '../bower/blueimp-canvas-to-blob/js/canvas-to-blob',
'load-image': '../bower/blueimp-load-image/js/load-image',
'load-image-ios': '../bower/blueimp-load-image/js/load-image-ios',
'load-image-orientation': '../bower/blueimp-load-image/js/load-image-orientation',
'load-image-meta': '../bower/blueimp-load-image/js/load-image-meta',
'load-image-exif': '../bower/blueimp-load-image/js/load-image-exif',
'load-image-exif-map': '../bower/blueimp-load-image/js/load-image-exif-map',
'blueimp-tmpl': '../bower/blueimp-tmpl/js/tmpl',
jquery: '../bower/jquery/dist/jquery',
'jquery.postmessage-transport': '../bower/jquery-file-upload/js/cors/jquery.postmessage-transport',
'jquery.xdr-transport': '../bower/jquery-file-upload/js/cors/jquery.xdr-transport',
'jquery.ui.widget': '../bower/jquery-file-upload/js/vendor/jquery.ui.widget',
'jquery.fileupload': '../bower/jquery-file-upload/js/jquery.fileupload',
'jquery.fileupload-process': '../bower/jquery-file-upload/js/jquery.fileupload-process',
'jquery.fileupload-validate': '../bower/jquery-file-upload/js/jquery.fileupload-validate',
'jquery.fileupload-image': '../bower/jquery-file-upload/js/jquery.fileupload-image',
'jquery.fileupload-audio': '../bower/jquery-file-upload/js/jquery.fileupload-audio',
'jquery.fileupload-video': '../bower/jquery-file-upload/js/jquery.fileupload-video',
'jquery.fileupload-ui': '../bower/jquery-file-upload/js/jquery.fileupload-ui',
'jquery.fileupload-jquery-ui': '../bower/jquery-file-upload/js/jquery.fileupload-jquery-ui',
'jquery.fileupload-angular': '../bower/jquery-file-upload/js/jquery.fileupload-angular',
'jquery.iframe-transport': '../bower/jquery-file-upload/js/jquery.iframe-transport',
underscore: '../bower/underscore/underscore'
},
packages: [
]
});
// setup file upload handling (upload.js)
requirejs(['upload']);
| Coggle/coggle-opml-importer | public/javascripts/main.js | JavaScript | mit | 2,444 |
/**
* @class Class that allows you to use a web notification.
* @property title {string} The notification's title
* @property body {string} The notification's body
* @property iconUrl {string} The URL where to find the notification's icon
*/
export default class WebNotification {
/**
* Defines an instance of web notification
* @param title {string} The notification's title
* @param body {string} The notification's body
* @param iconUrl {string} The URL where to find the notification's icon
*/
constructor(title, body, iconUrl) {
this.title = title;
this.body = body;
this.iconUrl = iconUrl;
}
/**
* Returns the web notification to render.
* @returns {Notification}
*/
createNotification() {
return new Notification(
this.title,
{ icon: this.iconUrl, body: this.body },
);
}
/**
* Manage the notification.
* @returns {Notification}
*/
notify() {
if (Notification.permission !== 'granted') {
Notification.requestPermission()
.then((permission) => {
if (permission === 'granted') {
return this.createNotification();
}
console.warn('Permission has not been granted.');
return {};
})
.catch(error => console.error(error));
}
return this.createNotification();
}
}
| or-bit/monolith | packages/monolith-frontend/src/Notification/WebNotification.js | JavaScript | mit | 1,513 |
/*global describe, beforeEach, it*/
'use strict';
var assert = require('assert');
describe('gulpify-webapp generator', function () {
it('can be imported without blowing up', function () {
var app = require('../app');
assert(app !== undefined);
});
});
| sukima/generator-gulpify-webapp | test/test-load.js | JavaScript | mit | 267 |
'use strict';
var bach = require('bach');
var values = require('lodash/object/values');
var isEmpty = require('lodash/lang/isEmpty');
var compact = require('lodash/array/compact');
var flatten = require('lodash/array/flatten');
var domReady = require('dooomrdy');
function view(mountpoint, fn){
var elements = this.mountpointElements;
if(!this.mountpoints[mountpoint]){
this.mountpoints[mountpoint] = [];
}
function viewLifecycle(cb){
return fn(elements[mountpoint], cb);
}
this.mountpoints[mountpoint].push(viewLifecycle);
}
function layout(fn){
var container = this._container;
function layoutLifecycle(cb){
return fn(container, cb);
}
this.lifecycle.layout = layoutLifecycle;
}
function addMountpoint(mountpoint, element){
if(!this.mountpoints[mountpoint]){
this.mountpoints[mountpoint] = [];
}
if(!this.mountpointElements[mountpoint]){
this.mountpointElements[mountpoint] = element;
}
}
function removeMountpoint(mountpoint){
delete this.mountpoints[mountpoint];
delete this.mountpointElements[mountpoint];
}
function render(cb){
this._renderCalled = true;
var layoutPipeline = this.lifecycle.layout;
var pipeline = [layoutPipeline];
if(!isEmpty(this.mountpoints)){
var mountpointPipeline = compact(flatten(values(this.mountpoints)));
if(mountpointPipeline.length){
pipeline.push(bach.parallel(mountpointPipeline));
}
}
var renderPipeline = bach.series(pipeline);
domReady(function(){
renderPipeline(cb);
});
}
module.exports = {
view: view,
layout: layout,
addMountpoint: addMountpoint,
removeMountpoint: removeMountpoint,
render: render
};
| iceddev/irken | lib/ui.js | JavaScript | mit | 1,663 |
import React from "react";
import Navigation from "./Navigation";
import Banner from "./Banner";
import ScrollDown from "./ScrollDown";
const Header = () => (
<header id="home">
<Navigation />
<Banner />
<ScrollDown />
</header>
);
export default Header;
| encephalopathy/portfolio | src/components/Header.js | JavaScript | mit | 274 |
/*global granny, $, _, Backbone*/
window.granny = window.granny || {};
granny.BowlView = Backbone.View.extend({
// entry point
initialize: function () {
// pass "this" referring to this object to the listed methods instead of the default "this"
_.bindAll(this, 'moveLeft', 'moveRight', 'addCannon', 'fallCannon', 'missCannon', 'catchWater', 'addEnergy', 'kill', 'endTurn', 'restoreImage');
this.world = granny.World;
// instance the models
this.model = new granny.Bowl();
this.cannons = new granny.Cannons();
this.model.set({
positionY: this.world.get('height') - this.model.get('height') + 12
});
this.event_aggregator.bind('catch:water', this.catchWater);
this.event_aggregator.bind('miss:water', this.kill);
this.event_aggregator.bind('add:cannon', this.addCannon);
this.event_aggregator.bind('add:cannon', this.restoreImage);
this.event_aggregator.bind('miss:cannon', this.missCannon);
this.event_aggregator.bind('end:turn', this.endTurn);
this.event_aggregator.bind('key:leftarrow', this.moveLeft);
this.event_aggregator.bind('key:rightarrow', this.moveRight);
},
moveLeft: function () {
var speed = this.model.get('speed'),
x = this.model.get('positionX'),
marginLeft = this.model.get('marginLeft');
if (x > marginLeft) {
this.model.set({positionX: x - speed});
}
},
moveRight: function () {
var speed = this.model.get('speed'),
x = this.model.get('positionX'),
marginRight = this.model.get('marginRight'),
bowlWidth = this.model.get('width'),
worldWidth = this.world.get('width');
if (x < worldWidth - bowlWidth - marginRight) {
this.model.set({positionX: x + speed});
}
},
addCannon: function () {
var energy = this.model.get('energy'),
bowlX = this.model.get('positionX'),
cannon;
if (energy < 5) {
return;
}
cannon = new granny.Cannon();
cannon.set({positionX: bowlX});
this.model.set({
energy: 0,
currentImage: 0
});
this.cannons.add(cannon);
this.event_aggregator.trigger('addCannon', cannon);
},
fallCannon: function (cannon) {
var cannonY = cannon.get('positionY'),
speed = cannon.get('speed');
cannon.set({positionY: cannonY - speed});
},
missCannon: function (cannon) {
cannon.destroy();
},
catchWater: function (water) {
var that = this,
image = this.model.get('currentImage') + 1,
idAnimation = this.model.get('idActiveAnimation'),
prevImage = 7;
this.addEnergy(1);
if (!idAnimation && image > 5) {
// water splash mega animation
idAnimation = setInterval(function () {
image = prevImage === 7 ? 7 : 6;
prevImage = image === 7 ? 6 : 7;
that.model.set({
currentImage: image,
positionY: that.world.get('height') - that.model.get('height') - 5
});
}, 200);
this.model.set({idActiveAnimation: idAnimation});
} else if (image <= 5) {
this.event_aggregator.trigger('bowl:catch', this.model);
this.model.set({currentImage: image});
} else {
this.event_aggregator.trigger('bowl:catchFull', this.model, 'addSoundFull');
}
},
restoreImage: function () {
var energy = this.model.get('energy'),
idAnimation = this.model.get('idActiveAnimation');
clearTimeout(idAnimation);
this.model.set({
idActiveAnimation: false,
positionY: this.world.get('height') - this.model.get('height') + 12,
currentImage: energy
});
},
addEnergy: function (n) {
var energy = this.model.get('energy');
energy += n;
this.model.set({energy: energy});
console.log('bowl energy: ' + this.model.get('energy'));
},
kill: function () {
var lifes = this.model.get('lifes') - 1;
this.model.set({lifes: lifes});
this.model.set({energy: 0});
this.restoreImage();
// this.model.set({currentImage: 0});
console.log('bowl died! lifes: ' + this.model.get('lifes'));
},
endTurn: function () {
this.cannons.reset();
this.model.reset(['positionX', 'speed', 'energy']);
}
}); | vha/granny | js/views/BowlView.js | JavaScript | mit | 4,781 |
var app = angular.module('shoppingList.index', []);
var passwordRegex = /^[a-zA-Z0-9,.!@#$%^&*_-]{8,16}$/;
var emailRegex = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/
var flag1 = false;
var valid = {
new_email: false,
old_email: false,
password: false,
password1: false,
password2: false,
}
var email_registered = {
new_email: true,
old_email: false,
}
var data = {
}
app.config(function($interpolateProvider , $httpProvider) {
$interpolateProvider.startSymbol('{$');
$interpolateProvider.endSymbol('$}');
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
});
app.directive('password', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
ctrl.$validators.password = function(modelValue, viewValue) {
var isValid = passwordRegex.test(viewValue)
if(viewValue == undefined)
return false;
if (viewValue.length > 0 && !isValid) {
flag1 = true;
elem.css("background-color", "rgba(255, 0, 0, 0.3)")
} else {
flag1 = false;
elem.css("background-color", "white")
}
valid[elem.attr('id')] = isValid;
// ugly fix
data[elem.attr('id')] = viewValue
//
return (isValid);
};
},
};
});
app.directive('match', [function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
ctrl.$validators.match = function(modelValue, viewValue) {
if (viewValue != $("#password1").val() && (!flag1 && viewValue.length > 1)) {
elem.css("background-color", "rgba(255, 102, 0, 0.3)");
valid[elem.attr('id')] = false;
}
}
}
}
}]);
app.directive('emailCheck', [function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
ctrl.$validators.emailCheck = function(modelValue, viewValue) {
if(viewValue.length == 0 && scope.meta != "loginCtrl") {
scope.email_registered = false;
}
if (viewValue.length > 0 && !emailRegex.test(viewValue)) {
elem.css("background-color", "rgba(255, 0, 0, 0.3)")
valid[elem.attr('id')] = false;
} else {
elem.css("background-color", "white")
valid[elem.attr('id')] = true;
}
// ugly fix
data[elem.attr('id')] = viewValue
//
}
}
}
}]);
// app.directive('usernameCheck', [function() {
// return {
// require: 'ngModel',
// link: function(scope, elem, attrs, ctrl) {
// ctrl.$asyncValidators.usernameCheck = function(modelValue, viewValue) {
// var inputEmail = viewValue;
// return $http.post("/email", {
// 'email': inputEmail,
// }, function() {
// // on success
// })
// .done(function() {
// // second on success
// })
// .fail(function() {
// return $q.reject("email already exists")
// })
// .always(function() {
// // finished
// })
// }
// }
// }
// }])
app.controller(
'loginCtrl', ['$scope', '$http', '$cookies',
function($scope, $http, $cookies) {
$scope.meta = "loginCtrl"
$scope.user = {
email: "",
password: "",
}
/*
* This flag is to toggle the warning message
*/
$scope.email_registered = true;
/*
* This flag is to prevent the login button from becoming
* valid if the AJAX call to check the existence of the
* email in the database takes too long
*/
$scope.email_registered_flag = false;
$scope.usernameCheck = function(mode) {
var inputEmail = $('#old_email').val()
var queryString = 'email=' + inputEmail
$http.post('/email/', queryString).then(function(result) {
$scope.email_registered = $scope.email_registered_flag = result.data.exists;
console.log("email_registered", $scope.email_registered)
console.log("email_registered_flag", $scope.email_registered_flag)
});
}
$scope.validate = function() {
return valid.password && valid.old_email && $scope.email_registered && $scope.email_registered_flag;
}
$scope.login = function() {
$scope.user.email = data.old_email;
$scope.user.password = data.password;
var queryString = 'user=' + JSON.stringify($scope.user)
$http.post('/login/', queryString).then(function(result) {
if(result.data.valid)
window.location.href = result.data['next']
}
)
}
// $scope.show_login = function() {
// var cookie = Cookies.get("show_login")
// if(cookie != null && cookie == "true"){
// var modalObj = $("#loginModal").modal();
// modalObj.modal("show");
// }
// Cookies.set("show_login", "false");
// }
}
]
);
app.controller(
'signupCtrl', ['$scope', '$http',
function($scope, $http) {
$scope.meta = "signupCtrl"
$scope.user = {
email: "",
password1: "",
password2: "",
getPassword: function() {
return $scope.user.password1 == $scope.user.password2 ? $scope.user.password1 : null;
}
}
$scope.email_registered = false;
/* This flag is to prevent the login button from becoming
* valid if the AJAX call to check the existence of the
* email in the database takes too long
*/
$scope.email_registered_flag = true;
$scope.validate = function() {
return valid.new_email && valid.password1 && valid.password2 && (!$scope.email_registered) && (!$scope.email_registered_flag);
}
$scope.usernameCheck = function(mode) {
var inputEmail = $('#new_email').val()
var queryString = 'email=' + inputEmail
$http.post('/email/', queryString)
.then(function(result) {
console.log("received result from /email/ ", result);
$scope.email_registered = $scope.email_registered_flag = result.data.exists;
});
}
$scope.register = function() {
$scope.user.email = data.new_email;
$scope.user.password1 = data.password1;
$scope.user.password2 = data.password2;
var dataString = 'user=' + JSON.stringify({
email: $scope.user.email,
password: $scope.user.getPassword(),
});
// TODO: Loading spinner show
$http.post('/register/', dataString)
.then(function(result) {
console.log(result)
// TODO: Spinner hide
if(result.data.valid)
window.location.href = result.data['next']
}
,function(response) {
// Error, spinner hide
});
}
$scope.forgotPassword = function() {
window.location.href = "/forgot_password";
}
}
]
);
// Helper functions
var setEmailRegistered = function(result, scope) {
scope.email_registered = result.exists;
} | danielluker/ShoppingList | webapp/public/js/controllers/index.js | JavaScript | mit | 8,749 |
'use strict';
const request = require('./utils/request');
const { BASE_URL } = require('./constants');
function suggest (opts) {
return new Promise(function (resolve, reject) {
if (!opts && !opts.term) {
throw Error('term missing');
}
const lang = opts.lang || 'en';
const country = opts.country || 'us';
// FIXME duplicated from permissions
const url = `${BASE_URL}/_/PlayStoreUi/data/batchexecute?rpcids=IJ4APc&f.sid=-697906427155521722&bl=boq_playuiserver_20190903.08_p0&hl=${lang}&gl=${country}&authuser&soc-app=121&soc-platform=1&soc-device=1&_reqid=1065213`;
const term = encodeURIComponent(opts.term);
const body = `f.req=%5B%5B%5B%22IJ4APc%22%2C%22%5B%5Bnull%2C%5B%5C%22${term}%5C%22%5D%2C%5B10%5D%2C%5B2%5D%2C4%5D%5D%22%5D%5D%5D`;
const options = Object.assign({
url,
body,
method: 'POST',
followAllRedirects: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
}, opts.requestOptions);
request(options, opts.throttle)
.then((html) => {
const input = JSON.parse(html.substring(5));
const data = JSON.parse(input[0][2]);
if (data === null) {
return [];
}
return data[0][0].map(s => s[0]);
})
.then(resolve)
.catch(reject);
});
}
module.exports = suggest;
| facundoolano/google-play-scraper | lib/suggest.js | JavaScript | mit | 1,375 |
var express = require('express');
exports.setup = function(app) {
var router = express.Router();
var auth = require('./auth');
var routes = require('./routes');
//router.use(auth.setup(app));
router.use(routes.setup(app));
return router;
}; | UnionTTC/project-tracker | routes/index.js | JavaScript | mit | 264 |
/**
* Palvelu huolehtii kayttajan tilan yllapitamisesta
* kontrolleri vaihdosten yli.
*/
angular.module('chatApp')
.factory('userStateService', ['$http', function ($http) {
var channelID;
var username;
var userID;
var userState;
/**
* etterit ja setterit
*/
function setChannelID(value) {
channelID = value;
}
function setUsername(value) {
username = value;
}
function setUserState(value) {
userState = value;
}
function setUserID(value) {
userID = value;
}
function getChannelID() {
return channelID;
}
function getUsername() {
return username;
}
function getUserID() {
return userID;
}
function getState() {
return userState;
}
/**
* Palauttaa käyttäjän tilaavastaavan templaten osoitteen.
*/
function getUserState() {
if (userState === 'queue') {
return 'queue/userInQueue.tpl.html'
} else if (userState === 'chat') {
return 'chatWindow/userInChat.tpl.html'
} else if (userState === 'pro') {
return 'staticErrorPages/sameBrowserError.html'
} else if (userState === 'closed') {
return 'common/chatClosed.tpl.html'
} else {
return 'queue/userToQueue.tpl.html';
}
}
/**
* Lahettaa poistumis ilmoituksen serverille.
*/
function leaveChat() {
$http.post("/leave/" + getChannelID(), {});
}
/**
* Hakee get-pyynnolla palvelimelta kayttajan tiedot.
*/
function getVariablesFormServer() {
return $http.get("/userState");
}
/**
* Asettaa vastauksessa tulleet parametrit palveluun.
*/
function setAllVariables(response) {
setUsername(response.data.username);
setChannelID(response.data.channelId);
setUserID(response.data.userId);
setUserState(response.data.state);
}
var queue = {
getVariablesFormServer: getVariablesFormServer,
setAllVariables: setAllVariables,
setUserState: setUserState,
getUserState: getUserState,
getChannelID: getChannelID,
getUsername: getUsername,
getUserID: getUserID,
leaveChat: leaveChat,
getState: getState
};
return queue;
}]);
| PauliNiva/Sotechat | src/main/webapp/services/userState.srvc.js | JavaScript | mit | 2,693 |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M21 11.5v-1c0-.8-.7-1.5-1.5-1.5H16v6h1.5v-2h1.1l.9 2H21l-.9-2.1c.5-.3.9-.8.9-1.4zm-1.5 0h-2v-1h2v1zm-13-.5h-2V9H3v6h1.5v-2.5h2V15H8V9H6.5v2zM13 9H9.5v6H13c.8 0 1.5-.7 1.5-1.5v-3c0-.8-.7-1.5-1.5-1.5zm0 4.5h-2v-3h2v3z" />
, 'HdrOn');
| kybarg/material-ui | packages/material-ui-icons/src/HdrOn.js | JavaScript | mit | 352 |
(function () {
angular
.module('app')
.controller('MemoryController',
['$scope', function ($scope) {
var vm = this;
vm.chartOptions = {
chart: {
type: 'pieChart',
height: 300,
donut: true,
pie: {
startAngle: function (d) {
return d.startAngle / 2 - Math.PI / 2
},
endAngle: function (d) {
return d.endAngle / 2 - Math.PI / 2
}
},
x: function (d) {
return d.key;
},
y: function (d) {
return d.y;
},
valueFormat: (d3.format(".0f")),
color: ['#E75753', 'rgb(0, 150, 136)'],
showLabels: true,
showLegend: true,
tooltips: false,
labelType: "percent",
titleOffset: -10,
margin: {bottom: -80, left: -20, right: -20}
}
};
$scope.$on('MetricsUpdateReceived', function (event, args) {
refreshChart(args.metrics);
});
function refreshChart(metrics) {
vm.chartOptions.chart.title = metrics["mem"] + " KB";
vm.memoryChartData = [
{key: "Used", y: metrics["mem"] - metrics["mem.free"]},
{key: "Free", y: metrics["mem.free"]}
];
}
}
]);
})();
| bhagwat/actuator-ui | src/app/controllers/MemoryController.js | JavaScript | mit | 1,907 |
module.exports = function(grunt) {
// project config
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
uglify: {
options: {
mangle: true,
report: "gzip",
banner: "/* <%=pkg.name %> <%= grunt.template.today('yyyy-mm-dd') %>*/\n"
},
build: {
src: "public/scripts/src/script.js",
dest: "public/scripts/script.min.js"
}
},
stylus: {
compile: {
files: {
'public/stylesheets/style.css': 'public/stylus/style.styl'
}
}
},
watch: {
js: {
files: "public/scripts/src/*.js",
tasks: 'uglify'
},
css: {
files: "public/stylus/*.styl",
tasks: 'stylus'
}
}
});
// load tasks
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.loadNpmTasks("grunt-contrib-uglify");
grunt.loadNpmTasks("grunt-contrib-stylus");
// register
grunt.registerTask('default', 'watch');
} | lmpablo/GradeBook | Gruntfile.js | JavaScript | mit | 1,165 |
// compiles the information to display the groups of permits near the searched location
var permitsCompiler = function(currentPermitsArray) {
var permitsToDisplay = Handlebars.compile($('#search-results-template').text());
return permitsToDisplay(currentPermitsArray);
};
// compiles the information to display the single permit currently selected by the user
var singlePermitCompiler = function(currentSelectedPermit) {
var permitToDisplay = Handlebars.compile($('#chosen-permit-template').text());
return permitToDisplay(currentSelectedPermit);
};
var moneyPermitsCompiler = function(mostExpensivePermits) {
var permitToShow = Handlebars.compile($('#show-me-the-money').text());
return permitToShow(mostExpensivePermits);
};
| crashtack/301-team-project | code/scripts/views/handlebars_compilers.js | JavaScript | mit | 741 |
import messages from 'lib/text';
import moment from 'moment';
const chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
const transparentize = (color, opacity) => {
const alpha = opacity === undefined ? 0.5 : 1 - opacity;
return Color(color)
.alpha(alpha)
.rgbString();
};
const getOrdersByDate = (orders, dateMoment) => {
return orders.filter(order =>
moment(order.date_placed).isSame(dateMoment, 'day')
);
};
const filterSuccessOrders = order =>
order.paid === true || order.closed === true;
const filterNewOrders = order => !order.paid && !order.closed;
export const getReportDataFromOrders = ordersResponse => {
let reportItems = [];
let dateFrom = moment().subtract(1, 'months');
let dateTo = moment();
const daysDiff = dateFrom.diff(dateTo, 'days');
for (let i = daysDiff; i < 1; i++) {
const reportingDate = moment().add(i, 'days');
const ordersPlacedThisDate = getOrdersByDate(
ordersResponse.data,
reportingDate
);
const totalOrdersCount = ordersPlacedThisDate.length;
const successOrdersCount = ordersPlacedThisDate.filter(filterSuccessOrders)
.length;
const newOrdersCount = ordersPlacedThisDate.filter(filterNewOrders).length;
const successOrdersRevenue = ordersPlacedThisDate
.filter(filterSuccessOrders)
.reduce((a, b) => {
return a + b.grand_total;
}, 0);
reportItems.push({
date: reportingDate.format('D MMM'),
total: totalOrdersCount,
success: successOrdersCount,
new: newOrdersCount,
revenue: successOrdersRevenue
});
}
return reportItems;
};
export const getOrdersDataFromReportData = reportData => {
const labels = reportData.map(item => item.date);
const successData = reportData.map(item => item.success);
const newData = reportData.map(item => item.new);
return {
labels: labels,
datasets: [
{
label: messages.closedAndPaidOrders,
data: successData,
backgroundColor: chartColors.blue,
hoverBackgroundColor: transparentize(chartColors.blue, 0.4)
},
{
label: messages.newOrders,
data: newData,
backgroundColor: chartColors.yellow,
hoverBackgroundColor: transparentize(chartColors.yellow, 0.4)
}
]
};
};
export const getSalesDataFromReportData = reportData => {
const labels = reportData.map(item => item.date);
const revenueData = reportData.map(item => item.revenue);
return {
labels: labels,
datasets: [
{
label: messages.closedAndPaidOrders,
data: revenueData,
backgroundColor: chartColors.blue,
hoverBackgroundColor: transparentize(chartColors.blue, 0.4)
}
]
};
};
| cezerin/cezerin | src/admin/client/modules/reports/ordersBar/utils.js | JavaScript | mit | 2,732 |
const { NAMES, GREETINGS } = require("./dummydata");
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
}
const largeDataSet = [];
let n = 0;
let g = 0;
const CREATE_GREETINGS = 20000;
for (let i = 0; i < CREATE_GREETINGS; i++) {
largeDataSet.push({
name: NAMES[n],
greeting: GREETINGS[g]
});
n++;
if (n === NAMES.length) {
shuffle(NAMES);
n = 0;
}
g++;
if (g === GREETINGS.length) {
shuffle(GREETINGS);
g = 0;
}
}
shuffle(largeDataSet);
console.log("Generated largeDataSet with items: " + largeDataSet.length);
largeDataSet.forEach((l, ix) => (l.id = ix));
module.exports = largeDataSet;
| DJCordhose/react-workshop | code/server/src/largedata.js | JavaScript | mit | 755 |
describe("ContatoController", function() {
var $scope, $httpBackend;
beforeEach(function() {
module('contatooh');
inject(function($injector,_$httpBackend_) {
$scope = $injector.get('$rootScope').$new();
$httpBackend = _$httpBackend_;
$httpBackend.when('GET', '/contatos/1').respond({_id: '1'});
$httpBackend.when('GET', '/contatos') .respond([{}]);
});
});
it("Deve criar um Contato vazio quando nenhum parâmetro de rota for passado",
inject(function($controller) {
$controller('ContatoController',{"$scope" : $scope});
expect($scope.contato._id).toBeUndefined();
}));
it("Deve preencher o Contato quando parâmetro de rota for passado",
inject(function($controller) {
$controller('ContatoController',
{
'$routeParams': {contatoId: 1},
'$scope': $scope
});
$httpBackend.flush();
expect($scope.contato._id).toBeDefined();
}));
}); | cavalerosi/contatooh | test/spec/ContatoControllerSpec.js | JavaScript | mit | 917 |
'use strict'
/**
* Base constructor for all implementations.
*/
const temp = require('temp-path')
const assert = require('assert')
const path = require('path')
const fs = require('mz/fs')
const formats = new Map()
formats.set('gif', require('./gif'))
const video_formats = [
'webm',
'mp4',
'vp8',
'vp9',
'x264',
'x265',
]
for (let format of video_formats) {
formats.set(format, require('./video'))
}
const extensions = new Map()
extensions.set('gif', 'gif')
extensions.set('webm', 'webm')
extensions.set('mp4', 'mp4')
extensions.set('vp8', 'webm')
extensions.set('vp9', 'webm')
extensions.set('x264', 'mp4')
extensions.set('x265', 'mp4')
module.exports = silence
function silence(input, options) {
if (typeof input === 'object') {
options = input
} else {
options.input = input
}
assert(options.output || options.format, '.output required.')
if (options.output) {
options.output = path.resolve(options.output)
let extension = /\.(\w+)$/.exec(options.output)
assert(extension, '.output does not have an extension!')
assert(formats.get(extension[1]), 'Unknown extension: ' + extension[1])
options.format = extension[1]
} else {
options.format = options.format || 'gif'
let extension = extensions.get(options.format)
assert(extension, 'Unknown format: ' + options.format)
options.output = temp() + '.' + extension
}
options.max_size = options.max_size
|| options.maxsize
|| options.maxSize
|| 320
options.fps = options.fps || 20
// if number, convert to seconds.milliseconds
options.start_time = options.start_time
|| options.startTime
|| 0
if (typeof options.start_time === 'number') options.start_time = String(options.start_time / 1000)
// if number, convert to seconds.milliseconds
if (typeof options.duration === 'number') options.duration = String(options.duration / 1000)
const fn = formats.get(options.format)
assert(fn, 'Invalid format: ' + options.format)
return fn(options).then(function () {
return options
})
}
| mgmtio/silence | lib/index.js | JavaScript | mit | 2,054 |
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var cors = require('cors');
var compression = require('compression');
var morgan = require("morgan");
var properties = require('./package.json')
var app = express();
app.set('port', (process.env.PORT || 3000));
app.use(compression());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(morgan(
'common',
{ stream: { write: logRequest } }
));
// ---------------------------------------------------------------------------
// Internal stuff
// ---------------------------------------------------------------------------
// Constants
var DEFAULT_CELLAR = {
id: 0,
name: "Jeremy's cellar",
bottles: [
{ id: 0, name: "Saint Emilion", price: 12.89 }
]
};
// Storage
var bottleId, cellarId, cellars, logs = '';
// Reset data
function reset() {
bottleId = 1;
cellarId = 1;
cellars = [ DEFAULT_CELLAR ];
}
// Get the index of a cellar from its ID
function getCellarIndex(id) {
id = parseInt(id);
for (var i = 0; i < cellars.length; i++) {
if (cellars[i].id === id) {
return i;
}
}
return -1;
}
// Get a cellar from its ID
function getCellar(id) {
var index = getCellarIndex(id);
if (index >= 0) {
return cellars[index];
}
return null;
}
// Get the index of a bottle in a cellar from its ID
function getBottleIndex(cellar, id) {
id = parseInt(id);
for (var i = 0; i < cellar.bottles.length; i++) {
if (cellar.bottles[i].id === id) {
return i;
}
}
return -1;
}
// Get a bottle from its ID
function findBottle(id) {
id = parseInt(id);
for (var i = 0; i < cellars.length; i++) {
var index = getBottleIndex(cellars[i], id);
if (index >= 0) {
return {
cellar: cellars[i],
bottleIndex: index
};
}
}
return null;
}
// Send a 404 error
function notFound(res) {
res.status(404);
res.type('txt').send('404 not found');
}
// Send a 500 error
function invalidRequest(res) {
res.status(500);
res.type('txt').send('Invalid request');
}
// Send an OK response
function responseOk(res) {
res.json({ success: true });
}
// Simple request logger
function logRequest(str) {
logs = str + logs;
}
// ---------------------------------------------------------------------------
// Endpoints
// ---------------------------------------------------------------------------
// GET /
// Get a simple string
app.get('/', function(req, res) {
res.type('txt').send(properties.description + ' v' + properties.version);
});
// GET /api/reset
// Resets the server data
app.get('/api/reset', function(req, res) {
reset();
responseOk(res);
});
// GET /api/logs
// Gets the request logs
app.get('/api/logs', function(req, res) {
res.type('txt').send(logs);
});
// GET /api/cellars
// Get the list of existings cellars
app.get('/api/cellars', function(req, res) {
var result = [];
for (var i = 0; i < cellars.length; i++) {
result[i] = { id: cellars[i].id, name: cellars[i].name };
}
res.jsonp(result);
});
// GET /api/cellars/:id
// Get the detail of an existing cellar id
app.get('/api/cellars/:id', function(req, res) {
var cellar = getCellar(req.params.id);
if (cellar) {
res.jsonp(cellar);
} else {
notFound(res);
}
});
// DELETE /api/cellars/:id
// Remove a cellar
app.delete('/api/cellars/:id', function(req, res) {
var index = getCellarIndex(req.params.id);
if (index >= 0) {
cellars.splice(index, 1);
responseOk(res);
} else {
invalidRequest(res);
}
});
// POST /api/cellars
// Create a new cellar
// Parameter: { name: 'name' }
app.post('/api/cellars', function(req, res) {
if (req.body && req.body.name) {
var cellar = { id: cellarId++, name: req.body.name, bottles: [] };
cellars.push(cellar);
res.json(cellar);
} else {
invalidRequest(res);
}
});
// GET /api/cellars/:id/bottles
// Get the bottles of an existing cellar id
app.get('/api/cellars/:id/bottles', function(req, res) {
var cellar = getCellar(req.params.id);
if (cellar) {
res.jsonp(cellar.bottles);
} else {
notFound(res);
}
});
// POST /api/cellars/:id/bottles
// Add a new bottle to a cellar id
// Parameter: { name: 'name', price: 10 }
app.post('/api/cellars/:id/bottles', function(req, res) {
if (req.body && req.params.id >= 0) {
var cellar = getCellar(req.params.id);
if (cellar && req.body.name && req.body.price) {
var bottle = { id: bottleId++, name: req.body.name, price: req.body.price };
cellar.bottles.push(bottle);
res.json(bottle);
return;
}
}
invalidRequest(res);
});
// DELETE /api/cellars/:id/bottles/:botleId
// Remove a bottle
app.delete('/api/cellars/:id/bottles/:bottleId', function(req, res) {
if (req.body && req.params.id && req.params.bottleId) {
var result = findBottle(req.params.bottleId);
if (result) {
var cellar = result.cellar;
cellar.bottles.splice(result.bottleIndex, 1);
res.json(cellar);
return;
}
}
invalidRequest(res);
});
// Start server
reset();
app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
| sinedied/cellars | server.js | JavaScript | mit | 5,274 |
// base function.
var backstorage = backstorage || {};
// version.
backstorage.VERSION = '0.0.1';
backstorage.repo = repo;
// initialize repo
// export to the root, which is probably `window`.
root.bs = backstorage; | AshanFernando/backstorage | src/main.js | JavaScript | mit | 218 |
/**
* Created by ben on 19/01/16.
*/
angular.module('flos.db', [])
.factory('dbservice', ['$http', '$q', function ($http, $q) {
var dbFunctions = {};
dbFunctions.getGraph = function (graphId) {
return $http.get('/api/graphs/' + graphId);
};
dbFunctions.saveGraph = function (graphId, graphData) {
console.log(graphId, graphData);
return $http.put('/api/graphs/' + graphId, graphData);
};
return dbFunctions;
}]); | bennyrowland/flos | frontend/components/database/db.service.js | JavaScript | mit | 509 |
/**
* Hilo 1.0.0 for amd
* Copyright 2016 alibaba.com
* Licensed under the MIT License
*/
define('hilo/view/Text', ['hilo/core/Class', 'hilo/core/Hilo', 'hilo/view/View', 'hilo/view/CacheMixin'], function(Class, Hilo, View, CacheMixin){
/**
* Hilo
* Copyright 2015 alibaba.com
* Licensed under the MIT License
*/
/**
* <iframe src='../../../examples/Text.html?noHeader' width = '320' height = '240' scrolling='no'></iframe>
* <br/>
* @class Text类提供简单的文字显示功能。复杂的文本功能可以使用DOMElement。
* @augments View
* @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
* @module hilo/view/Text
* @requires hilo/core/Class
* @requires hilo/core/Hilo
* @requires hilo/view/View
* @requires hilo/view/CacheMixin
* @property {String} text 指定要显示的文本内容。
* @property {String} color 指定使用的字体颜色。
* @property {String} textAlign 指定文本的对齐方式。可以是以下任意一个值:'start', 'end', 'left', 'right', and 'center'。
* @property {String} textVAlign 指定文本的垂直对齐方式。可以是以下任意一个值:'top', 'middle', 'bottom'。
* @property {Boolean} outline 指定文本是绘制边框还是填充。
* @property {Number} lineSpacing 指定文本的行距。单位为像素。默认值为0。
* @property {Number} maxWidth 指定文本的最大宽度。默认值为200。
* @property {String} font 文本的字体CSS样式。只读属性。设置字体样式请用setFont方法。
* @property {Number} textWidth 指示文本内容的宽度,只读属性。仅在canvas模式下有效。
* @property {Number} textHeight 指示文本内容的高度,只读属性。仅在canvas模式下有效。
*/
var Text = Class.create(/** @lends Text.prototype */{
Extends: View,
Mixes:CacheMixin,
constructor: function(properties){
properties = properties || {};
this.id = this.id || properties.id || Hilo.getUid('Text');
Text.superclass.constructor.call(this, properties);
// if(!properties.width) this.width = 200; //default width
if(!properties.font) this.font = '12px arial'; //default font style
this._fontHeight = Text.measureFontHeight(this.font);
},
text: null,
color: '#000',
textAlign: null,
textVAlign: null,
outline: false,
lineSpacing: 0,
maxWidth: 200,
font: null, //ready-only
textWidth: 0, //read-only
textHeight: 0, //read-only
/**
* 设置文本的字体CSS样式。
* @param {String} font 要设置的字体CSS样式。
* @returns {Text} Text对象本身。链式调用支持。
*/
setFont: function(font){
var me = this;
if(me.font !== font){
me.font = font;
me._fontHeight = Text.measureFontHeight(font);
}
return me;
},
/**
* 覆盖渲染方法。
* @private
*/
render: function(renderer, delta){
var me = this, canvas = renderer.canvas;
if(renderer.renderType === 'canvas'){
me._draw(renderer.context);
}
else if(renderer.renderType === 'dom'){
var drawable = me.drawable;
var domElement = drawable.domElement;
var style = domElement.style;
style.font = me.font;
style.textAlign = me.textAlign;
style.color = me.color;
style.width = me.width + 'px';
style.height = me.height + 'px';
style.lineHeight = (me._fontHeight + me.lineSpacing) + 'px';
domElement.innerHTML = me.text;
renderer.draw(this);
}
else{
//TODO:自动更新cache
me.cache();
renderer.draw(me);
}
},
/**
* 在指定的渲染上下文上绘制文本。
* @private
*/
_draw: function(context){
var me = this, text = me.text.toString();
if(!text) return;
//set drawing style
context.font = me.font;
context.textAlign = me.textAlign;
context.textBaseline = 'top';
//find and draw all explicit lines
var lines = text.split(/\r\n|\r|\n|<br(?:[ \/])*>/);
var width = 0, height = 0;
var lineHeight = me._fontHeight + me.lineSpacing;
var i, line, w;
var drawLines = [];
for(i = 0, len = lines.length; i < len; i++){
line = lines[i];
w = context.measureText(line).width;
//check if the line need to split
if(w <= me.maxWidth){
drawLines.push({text:line, y:height});
// me._drawTextLine(context, line, height);
if(width < w) width = w;
height += lineHeight;
continue;
}
var str = '', oldWidth = 0, newWidth, j, word;
for(j = 0, wlen = line.length; j < wlen; j++){
word = line[j];
newWidth = context.measureText(str + word).width;
if(newWidth > me.maxWidth){
drawLines.push({text:str, y:height});
// me._drawTextLine(context, str, height);
if(width < oldWidth) width = oldWidth;
height += lineHeight;
str = word;
}else{
oldWidth = newWidth;
str += word;
}
if(j == wlen - 1){
drawLines.push({text:str, y:height});
// me._drawTextLine(context, str, height);
if(str !== word && width < newWidth) width = newWidth;
height += lineHeight;
}
}
}
me.textWidth = width;
me.textHeight = height;
if(!me.width) me.width = width;
if(!me.height) me.height = height;
//vertical alignment
var startY = 0;
switch(me.textVAlign){
case 'middle':
startY = me.height - me.textHeight >> 1;
break;
case 'bottom':
startY = me.height - me.textHeight;
break;
}
//draw background
var bg = me.background;
if(bg){
context.fillStyle = bg;
context.fillRect(0, 0, me.width, me.height);
}
if(me.outline) context.strokeStyle = me.color;
else context.fillStyle = me.color;
//draw text lines
for(var i = 0; i < drawLines.length; i++){
var line = drawLines[i];
me._drawTextLine(context, line.text, startY + line.y);
}
},
/**
* 在指定的渲染上下文上绘制一行文本。
* @private
*/
_drawTextLine: function(context, text, y){
var me = this, x = 0, width = me.width;
switch(me.textAlign){
case 'center':
x = width >> 1;
break;
case 'right':
case 'end':
x = width;
break;
};
if(me.outline) context.strokeText(text, x, y);
else context.fillText(text, x, y);
},
Statics: /** @lends Text */{
/**
* 测算指定字体样式的行高。
* @param {String} font 指定要测算的字体样式。
* @return {Number} 返回指定字体的行高。
*/
measureFontHeight: function(font){
var docElement = document.documentElement, fontHeight;
var elem = Hilo.createElement('div', {style:{font:font, position:'absolute'}, innerHTML:'M'});
docElement.appendChild(elem);
fontHeight = elem.offsetHeight;
docElement.removeChild(elem);
return fontHeight;
}
}
});
return Text;
}); | dsouzadyn/Hilo | build/amd/hilo/view/Text.js | JavaScript | mit | 7,888 |
'use strict';
document.addEventListener('DOMContentLoaded', function () {
const jsOnlyElements = Array.prototype.slice.call(document.getElementsByClassName('js-only'));
jsOnlyElements.forEach(function (element) {
element.className = element.className.replace('js-only', '').trim();
});
});
| ventaquil/picap | assets/javascript/layout.js | JavaScript | mit | 312 |
var request = require('request');
var s = request('http://www.google.com');
s.on('data', function(chunk) {
console.log(">>>Data>>> " + chunk);
});
s.on('end', function() {
console.log(">>>Done!>>>");
}); | veryaustin/exploring-node | 04_events_and_streams/readable_stream.js | JavaScript | mit | 210 |
module.exports = Noop;
function Noop() {}
Noop.run = function() {
console.log('noop');
};
| yxd-hde/lambda-test | lib/noop.js | JavaScript | mit | 96 |
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* Files */
declare class Blob {
constructor(blobParts?: Array<any>, options?: {
type?: string;
endings?: string;
}): void;
isClosed: bool;
size: number;
type: string;
close(): void;
slice(start?: number, end?: number, contentType?: string): Blob;
}
declare class FileReader extends EventTarget {
abort(): void;
DONE: number;
EMPTY: number;
error: DOMError;
LOADING: number;
onabort: (ev: any) => any;
onerror: (ev: any) => any;
onload: (ev: any) => any;
onloadend: (ev: any) => any;
onloadstart: (ev: any) => any;
onprogress: (ev: any) => any;
readAsArrayBuffer(blob: Blob): void;
readAsDataURL(blob: Blob): void;
readAsText(blob: Blob, encoding?: string): void;
readyState: 0 | 1 | 2;
result: string | ArrayBuffer;
}
declare type FilePropertyBag = {
type?: string,
lastModified?: number,
};
declare class File extends Blob {
constructor(
fileBits: $ReadOnlyArray<string | BufferDataSource | Blob>,
filename: string,
options?: FilePropertyBag,
): void;
lastModifiedDate: any;
name: string;
}
declare class FileList {
@@iterator(): Iterator<File>;
length: number;
item(index: number): File;
[index: number]: File;
}
/* DataTransfer */
declare class DataTransfer {
clearData(format?: string): void;
getData(format: string): string;
setData(format: string, data: string): void;
setDragImage(image: Element, x: number, y: number): void;
dropEffect: string;
effectAllowed: string;
files: FileList; // readonly
items: DataTransferItemList; // readonly
types: Array<string>; // readonly
}
declare class DataTransferItemList {
@@iterator(): Iterator<DataTransferItem>;
length: number; // readonly
[index: number]: DataTransferItem;
add(data: string, type: string): ?DataTransferItem;
add(data: File): ?DataTransferItem;
remove(index: number): void;
clear(): void;
};
declare class DataTransferItem {
kind: string; // readonly
type: string; // readonly
getAsString(_callback: ?(data: string) => mixed): void;
getAsFile(): ?File;
};
/* DOM */
declare class DOMError {
name: string;
}
declare type ElementDefinitionOptions = {
extends?: string;
}
declare interface CustomElementRegistry {
define(name: string, ctor: Class<Element>, options?: ElementDefinitionOptions): void;
get(name: string): any;
whenDefined(name: string): Promise<void>;
}
declare interface ShadowRoot extends DocumentFragment {
host: Element;
innerHTML: string;
}
declare type ShadowRootMode = 'open'|'closed';
declare type ShadowRootInit = {
delegatesFocus?: boolean;
mode: ShadowRootMode;
}
type EventHandler = (event: Event) => mixed
type EventListener = {handleEvent: EventHandler} | EventHandler
type MouseEventHandler = (event: MouseEvent) => mixed
type MouseEventListener = {handleEvent: MouseEventHandler} | MouseEventHandler
type FocusEventHandler = (event: FocusEvent) => mixed
type FocusEventListener = {handleEvent: FocusEventHandler} | FocusEventHandler
type KeyboardEventHandler = (event: KeyboardEvent) => mixed
type KeyboardEventListener = {handleEvent: KeyboardEventHandler} | KeyboardEventHandler
type TouchEventHandler = (event: TouchEvent) => mixed
type TouchEventListener = {handleEvent: TouchEventHandler} | TouchEventHandler
type WheelEventHandler = (event: WheelEvent) => mixed
type WheelEventListener = {handleEvent: WheelEventHandler} | WheelEventHandler
type ProgressEventHandler = (event: ProgressEvent) => mixed
type ProgressEventListener = {handleEvent: ProgressEventHandler} | ProgressEventHandler
type DragEventHandler = (event: DragEvent) => mixed
type DragEventListener = {handleEvent: DragEventHandler} | DragEventHandler
type AnimationEventHandler = (event: AnimationEvent) => mixed
type AnimationEventListener = {handleEvent: AnimationEventHandler} | AnimationEventHandler
type MouseEventTypes = 'contextmenu' | 'mousedown' | 'mouseenter' | 'mouseleave' | 'mousemove' | 'mouseout' | 'mouseover' | 'mouseup' | 'click' | 'dblclick';
type FocusEventTypes = 'blur' | 'focus' | 'focusin' | 'focusout';
type KeyboardEventTypes = 'keydown' | 'keyup' | 'keypress';
type TouchEventTypes = 'touchstart' | 'touchmove' | 'touchend' | 'touchcancel';
type WheelEventTypes = 'wheel';
type ProgressEventTypes = 'abort' | 'error' | 'load' | 'loadend' | 'loadstart' | 'progress' | 'timeout';
type DragEventTypes = 'drag' | 'dragend' | 'dragenter' | 'dragexit' | 'dragleave' | 'dragover' | 'dragstart' | 'drop';
type AnimationEventTypes = 'animationstart' | 'animationend' | 'animationiteration';
type EventListenerOptionsOrUseCapture = boolean | {
capture?: boolean,
once?: boolean,
passive?: boolean
};
declare class EventTarget {
addEventListener(type: MouseEventTypes, listener: MouseEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
addEventListener(type: FocusEventTypes, listener: FocusEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
addEventListener(type: KeyboardEventTypes, listener: KeyboardEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
addEventListener(type: TouchEventTypes, listener: TouchEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
addEventListener(type: WheelEventTypes, listener: WheelEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
addEventListener(type: ProgressEventTypes, listener: ProgressEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
addEventListener(type: DragEventTypes, listener: DragEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
addEventListener(type: AnimationEventTypes, listener: AnimationEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
addEventListener(type: string, listener: EventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
removeEventListener(type: MouseEventTypes, listener: MouseEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
removeEventListener(type: FocusEventTypes, listener: FocusEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
removeEventListener(type: KeyboardEventTypes, listener: KeyboardEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
removeEventListener(type: TouchEventTypes, listener: TouchEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
removeEventListener(type: WheelEventTypes, listener: WheelEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
removeEventListener(type: ProgressEventTypes, listener: ProgressEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
removeEventListener(type: DragEventTypes, listener: DragEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
removeEventListener(type: AnimationEventTypes, listener: AnimationEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
removeEventListener(type: string, listener: EventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture): void;
attachEvent?: (type: MouseEventTypes, listener: MouseEventListener) => void;
attachEvent?: (type: FocusEventTypes, listener: FocusEventListener) => void;
attachEvent?: (type: KeyboardEventTypes, listener: KeyboardEventListener) => void;
attachEvent?: (type: TouchEventTypes, listener: TouchEventListener) => void;
attachEvent?: (type: WheelEventTypes, listener: WheelEventListener) => void;
attachEvent?: (type: ProgressEventTypes, listener: ProgressEventListener) => void;
attachEvent?: (type: DragEventTypes, listener: DragEventListener) => void;
attachEvent?: (type: AnimationEventTypes, listener: AnimationEventListener) => void;
attachEvent?: (type: string, listener: EventListener) => void;
detachEvent?: (type: MouseEventTypes, listener: MouseEventListener) => void;
detachEvent?: (type: FocusEventTypes, listener: FocusEventListener) => void;
detachEvent?: (type: KeyboardEventTypes, listener: KeyboardEventListener) => void;
detachEvent?: (type: TouchEventTypes, listener: TouchEventListener) => void;
detachEvent?: (type: WheelEventTypes, listener: WheelEventListener) => void;
detachEvent?: (type: ProgressEventTypes, listener: ProgressEventListener) => void;
detachEvent?: (type: DragEventTypes, listener: DragEventListener) => void;
detachEvent?: (type: AnimationEventTypes, listener: AnimationEventListener) => void;
detachEvent?: (type: string, listener: EventListener) => void;
dispatchEvent(evt: Event): boolean;
// Deprecated
cancelBubble: boolean;
initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void;
}
type Event$Init = {
bubbles?: boolean,
cancelable?: boolean,
composed?: boolean,
scoped?: boolean
}
declare class Event {
constructor(type: string, eventInitDict?: Event$Init): void;
bubbles: boolean;
cancelable: boolean;
currentTarget: EventTarget;
deepPath?: () => EventTarget[];
defaultPrevented: boolean;
eventPhase: number;
isTrusted: boolean;
scoped: boolean;
srcElement: Element;
target: EventTarget;
timeStamp: number;
type: string;
preventDefault(): void;
stopImmediatePropagation(): void;
stopPropagation(): void;
AT_TARGET: number;
BUBBLING_PHASE: number;
CAPTURING_PHASE: number;
// deprecated
initEvent(
type: string,
bubbles: boolean,
cancelable: boolean
): void;
}
type CustomEvent$Init = Event$Init & {
detail?: any;
}
declare class CustomEvent extends Event {
constructor(type: string, eventInitDict?: CustomEvent$Init): void;
detail: any;
// deprecated
initCustomEvent(
type: string,
bubbles: boolean,
cancelable: boolean,
detail: any
): CustomEvent;
}
declare class UIEvent extends Event {
detail: number;
view: any;
}
type MouseEvent$MouseEventInit = {
screenX?: number,
screenY?: number,
clientX?: number,
clientY?: number,
ctrlKey?: boolean,
shiftKey?: boolean,
altKey?: boolean,
metaKey?: boolean,
button?: number,
buttons?: number,
region?: string | null,
relatedTarget?: string | null,
};
declare class MouseEvent extends UIEvent {
constructor(
typeArg: string,
mouseEventInit?: MouseEvent$MouseEventInit,
): void;
altKey: boolean;
button: number;
buttons: number;
clientX: number;
clientY: number;
ctrlKey: boolean;
metaKey: boolean;
movementX: number;
movementY: number;
offsetX: number;
offsetY: number;
pageX: number;
pageY: number;
region: ?string;
screenX: number;
screenY: number;
shiftKey: boolean;
relatedTarget: ?EventTarget;
getModifierState(keyArg: string): boolean;
}
declare class FocusEvent extends UIEvent {
relatedTarget: ?EventTarget;
}
declare class WheelEvent extends MouseEvent {
deltaX: number; // readonly
deltaY: number; // readonly
deltaZ: number; // readonly
deltaMode: 0x00 | 0x01 | 0x02; // readonly
}
declare class DragEvent extends MouseEvent {
dataTransfer: ?DataTransfer; // readonly
}
declare class ProgressEvent extends Event {
lengthComputable: boolean;
loaded: number;
total: number;
// Deprecated
initProgressEvent(
typeArg: string,
canBubbleArg: boolean,
cancelableArg: boolean,
lengthComputableArg: boolean,
loadedArg: number,
totalArg: number
): void;
}
declare class PromiseRejectionEvent extends Event {
promise: Promise<any>;
reason: any;
}
// used for websockets and postMessage, for example. See:
// http://www.w3.org/TR/2011/WD-websockets-20110419/
// and
// http://www.w3.org/TR/2008/WD-html5-20080610/comms.html
// and
// https://html.spec.whatwg.org/multipage/comms.html#the-messageevent-interfaces
declare class MessageEvent extends Event {
data: mixed;
origin: string;
lastEventId: string;
source: WindowProxy;
}
declare class KeyboardEvent extends UIEvent {
altKey: boolean;
code: string;
ctrlKey: boolean;
isComposing: boolean;
key: string;
location: number;
metaKey: boolean;
repeat: boolean;
shiftKey: boolean;
getModifierState(keyArg?: string): boolean;
// Deprecated
charCode: number;
keyCode: number;
which: number;
}
declare class AnimationEvent extends UIEvent {
animationName: string;
elapsedTime: number;
pseudoElement: string;
// deprecated
initAnimationEvent: (
type: 'animationstart' | 'animationend' | 'animationiteration',
canBubble: boolean,
cancelable: boolean,
animationName: string,
elapsedTime: number
) => void;
}
// https://www.w3.org/TR/touch-events/#idl-def-Touch
declare class Touch {
clientX: number,
clientY: number,
identifier: number,
pageX: number,
pageY: number,
screenX: number,
screenY: number,
target: EventTarget,
}
// https://www.w3.org/TR/touch-events/#idl-def-TouchList
// TouchList#item(index) will return null if n > #length. Should #item's
// return type just been Touch?
declare class TouchList {
@@iterator(): Iterator<Touch>;
length: number,
item(index: number): null | Touch,
[index: number]: Touch,
}
// https://www.w3.org/TR/touch-events/#touchevent-interface
declare class TouchEvent extends UIEvent {
altKey: boolean,
changedTouches: TouchList,
ctrlKey: boolean,
metaKey: boolean,
shiftKey: boolean,
targetTouches: TouchList,
touches: TouchList,
}
// https://www.w3.org/TR/webstorage/#the-storageevent-interface
declare class StorageEvent extends Event {
key: ?string,
oldValue: ?string,
newValue: ?string,
url: string,
storageArea: ?Storage,
}
// TODO: *Event
declare class Node extends EventTarget {
baseURI: ?string;
childNodes: NodeList<Node>;
firstChild: ?Node;
lastChild: ?Node;
nextSibling: ?Node;
nodeName: string;
nodeType: number;
nodeValue: string;
ownerDocument: Document;
parentElement: ?Element;
parentNode: ?Node;
previousSibling: ?Node;
rootNode: Node;
textContent: string;
appendChild<T: Node>(newChild: T): T;
cloneNode(deep?: boolean): this;
compareDocumentPosition(other: Node): number;
contains(other: ?Node): boolean;
hasChildNodes(): boolean;
insertBefore<T: Node>(newChild: T, refChild?: ?Node): T;
isDefaultNamespace(namespaceURI: string): boolean;
isEqualNode(arg: Node): boolean;
isSameNode(other: Node): boolean;
lookupNamespaceURI(prefix: string): string;
lookupPrefix(namespaceURI: string): string;
normalize(): void;
removeChild<T: Node>(oldChild: T): T;
replaceChild<T: Node>(newChild: Node, oldChild: T): T;
static ATTRIBUTE_NODE: number;
static CDATA_SECTION_NODE: number;
static COMMENT_NODE: number;
static DOCUMENT_FRAGMENT_NODE: number;
static DOCUMENT_NODE: number;
static DOCUMENT_POSITION_CONTAINED_BY: number;
static DOCUMENT_POSITION_CONTAINS: number;
static DOCUMENT_POSITION_DISCONNECTED: number;
static DOCUMENT_POSITION_FOLLOWING: number;
static DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number;
static DOCUMENT_POSITION_PRECEDING: number;
static DOCUMENT_TYPE_NODE: number;
static ELEMENT_NODE: number;
static ENTITY_NODE: number;
static ENTITY_REFERENCE_NODE: number;
static NOTATION_NODE: number;
static PROCESSING_INSTRUCTION_NODE: number;
static TEXT_NODE: number;
// Non-standard
innerText?: string;
outerText?: string;
}
declare class NodeList<T> {
@@iterator(): Iterator<T>;
length: number;
item(index: number): T;
[index: number]: T;
forEach(callbackfn: (value: T, index: number, list: NodeList<T>) => any, thisArg?: any): void;
entries(): Iterator<[number, T]>;
keys(): Iterator<number>;
values(): Iterator<T>;
}
declare class NamedNodeMap {
@@iterator(): Iterator<Attr>;
length: number;
removeNamedItemNS(namespaceURI: string, localName: string): Attr;
item(index: number): Attr;
[index: number]: Attr;
removeNamedItem(name: string): Attr;
getNamedItem(name: string): Attr;
setNamedItem(arg: Attr): Attr;
getNamedItemNS(namespaceURI: string, localName: string): Attr;
setNamedItemNS(arg: Attr): Attr;
}
declare class Attr extends Node {
isId: boolean;
specified: boolean;
ownerElement: Element | null;
value: string;
name: string;
namespaceURI: string | null;
prefix: string | null;
localName: string;
}
declare class HTMLCollection<Elem: HTMLElement> {
@@iterator(): Iterator<Elem>;
length: number;
item(nameOrIndex?: any, optionalIndex?: any): Elem;
namedItem(name: string): Elem;
[index: number]: Elem;
}
// from https://www.w3.org/TR/custom-elements/#extensions-to-document-interface-to-register
type ElementRegistrationOptions = {
+prototype?: {
// from https://www.w3.org/TR/custom-elements/#types-of-callbacks
+createdCallback?: () => mixed;
+attachedCallback?: () => mixed;
+detachedCallback?: () => mixed;
+attributeChangedCallback?:
// attribute is set
((
attributeLocalName: string,
oldAttributeValue: null,
newAttributeValue: string,
attributeNamespace: string
) => mixed) &
// attribute is changed
((
attributeLocalName: string,
oldAttributeValue: string,
newAttributeValue: string,
attributeNamespace: string
) => mixed) &
// attribute is removed
((
attributeLocalName: string,
oldAttributeValue: string,
newAttributeValue: null,
attributeNamespace: string
) => mixed);
};
+extends?: string;
}
declare class Document extends Node {
URL: string;
adoptNode<T: Node>(source: T): T;
anchors: HTMLCollection<HTMLAnchorElement>;
applets: HTMLCollection<HTMLAppletElement>;
body: HTMLElement | null;
characterSet: string;
close(): void;
cookie: string;
createAttribute(name: string): Attr;
createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr;
createCDATASection(data: string): Text;
createComment(data: string): Comment;
createDocumentFragment(): DocumentFragment;
createElement(tagName: 'a'): HTMLAnchorElement;
createElement(tagName: 'audio'): HTMLAudioElement;
createElement(tagName: 'br'): HTMLBRElement;
createElement(tagName: 'button'): HTMLButtonElement;
createElement(tagName: 'canvas'): HTMLCanvasElement;
createElement(tagName: 'details'): HTMLDetailsElement;
createElement(tagName: 'div'): HTMLDivElement;
createElement(tagName: 'dl'): HTMLDListElement;
createElement(tagName: 'fieldset'): HTMLFieldSetElement;
createElement(tagName: 'form'): HTMLFormElement;
createElement(tagName: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'): HTMLHeadingElement;
createElement(tagName: 'hr'): HTMLHRElement;
createElement(tagName: 'iframe'): HTMLIFrameElement;
createElement(tagName: 'img'): HTMLImageElement;
createElement(tagName: 'input'): HTMLInputElement;
createElement(tagName: 'label'): HTMLLabelElement;
createElement(tagName: 'legend'): HTMLLegendElement;
createElement(tagName: 'li'): HTMLLIElement;
createElement(tagName: 'link'): HTMLLinkElement;
createElement(tagName: 'meta'): HTMLMetaElement;
createElement(tagName: 'ol'): HTMLOListElement;
createElement(tagName: 'optgroup'): HTMLOptGroupElement;
createElement(tagName: 'option'): HTMLOptionElement;
createElement(tagName: 'p'): HTMLParagraphElement;
createElement(tagName: 'pre'): HTMLPreElement;
createElement(tagName: 'script'): HTMLScriptElement;
createElement(tagName: 'select'): HTMLSelectElement;
createElement(tagName: 'source'): HTMLSourceElement;
createElement(tagName: 'span'): HTMLSpanElement;
createElement(tagName: 'style'): HTMLStyleElement;
createElement(tagName: 'textarea'): HTMLTextAreaElement;
createElement(tagName: 'video'): HTMLVideoElement;
createElement(tagName: 'table'): HTMLTableElement;
createElement(tagName: 'caption'): HTMLTableCaptionElement;
createElement(tagName: 'thead' | 'tfoot' | 'tbody'): HTMLTableSectionElement;
createElement(tagName: 'tr'): HTMLTableRowElement;
createElement(tagName: 'td' | 'th'): HTMLTableCellElement;
createElement(tagName: 'template'): HTMLTemplateElement;
createElement(tagName: 'ul'): HTMLUListElement;
createElement(tagName: string): HTMLElement;
createElementNS(namespaceURI: string | null, qualifiedName: string): Element;
createTextNode(data: string): Text;
currentScript: HTMLScriptElement | null;
doctype: DocumentType | null;
documentElement: HTMLElement | null;
documentMode: number;
domain: string | null;
embeds: HTMLCollection<HTMLEmbedElement>;
execCommand(cmdID: string, showUI?: boolean, value?: any): boolean;
forms: HTMLCollection<HTMLFormElement>;
getElementById(elementId: string): HTMLElement | null;
getElementsByClassName(classNames: string): HTMLCollection<HTMLElement>;
getElementsByName(elementName: string): HTMLCollection<HTMLElement>;
getElementsByTagName(name: 'a'): HTMLCollection<HTMLAnchorElement>;
getElementsByTagName(name: 'audio'): HTMLCollection<HTMLAudioElement>;
getElementsByTagName(name: 'br'): HTMLCollection<HTMLBRElement>;
getElementsByTagName(name: 'button'): HTMLCollection<HTMLButtonElement>;
getElementsByTagName(name: 'canvas'): HTMLCollection<HTMLCanvasElement>;
getElementsByTagName(name: 'details'): HTMLCollection<HTMLDetailsElement>;
getElementsByTagName(name: 'div'): HTMLCollection<HTMLDivElement>;
getElementsByTagName(name: 'dl'): HTMLCollection<HTMLDListElement>;
getElementsByTagName(name: 'fieldset'): HTMLCollection<HTMLFieldSetElement>;
getElementsByTagName(name: 'form'): HTMLCollection<HTMLFormElement>;
getElementsByTagName(name: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'): HTMLCollection<HTMLHeadingElement>;
getElementsByTagName(name: 'hr'): HTMLCollection<HTMLHRElement>;
getElementsByTagName(name: 'iframe'): HTMLCollection<HTMLIFrameElement>;
getElementsByTagName(name: 'img'): HTMLCollection<HTMLImageElement>;
getElementsByTagName(name: 'input'): HTMLCollection<HTMLInputElement>;
getElementsByTagName(name: 'label'): HTMLCollection<HTMLLabelElement>;
getElementsByTagName(name: 'legend'): HTMLCollection<HTMLLegendElement>;
getElementsByTagName(name: 'li'): HTMLCollection<HTMLLIElement>;
getElementsByTagName(name: 'link'): HTMLCollection<HTMLLinkElement>;
getElementsByTagName(name: 'meta'): HTMLCollection<HTMLMetaElement>;
getElementsByTagName(name: 'ol'): HTMLCollection<HTMLOListElement>;
getElementsByTagName(name: 'option'): HTMLCollection<HTMLOptionElement>;
getElementsByTagName(name: 'p'): HTMLCollection<HTMLParagraphElement>;
getElementsByTagName(name: 'pre'): HTMLCollection<HTMLPreElement>;
getElementsByTagName(name: 'script'): HTMLCollection<HTMLScriptElement>;
getElementsByTagName(name: 'select'): HTMLCollection<HTMLSelectElement>;
getElementsByTagName(name: 'source'): HTMLCollection<HTMLSourceElement>;
getElementsByTagName(name: 'span'): HTMLCollection<HTMLSpanElement>;
getElementsByTagName(name: 'style'): HTMLCollection<HTMLStyleElement>;
getElementsByTagName(name: 'textarea'): HTMLCollection<HTMLTextAreaElement>;
getElementsByTagName(name: 'video'): HTMLCollection<HTMLVideoElement>;
getElementsByTagName(name: 'table'): HTMLCollection<HTMLTableElement>;
getElementsByTagName(name: 'caption'): HTMLCollection<HTMLTableCaptionElement>;
getElementsByTagName(name: 'thead' | 'tfoot' | 'tbody'): HTMLCollection<HTMLTableSectionElement>;
getElementsByTagName(name: 'tr'): HTMLCollection<HTMLTableRowElement>;
getElementsByTagName(name: 'td' | 'th'): HTMLCollection<HTMLTableCellElement>;
getElementsByTagName(name: 'template'): HTMLCollection<HTMLTemplateElement>;
getElementsByTagName(name: 'ul'): HTMLCollection<HTMLUListElement>;
getElementsByTagName(name: string): HTMLCollection<HTMLElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'a'): HTMLCollection<HTMLAnchorElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'audio'): HTMLCollection<HTMLAudioElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'br'): HTMLCollection<HTMLBRElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'button'): HTMLCollection<HTMLButtonElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'canvas'): HTMLCollection<HTMLCanvasElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'details'): HTMLCollection<HTMLDetailsElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'div'): HTMLCollection<HTMLDivElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'dl'): HTMLCollection<HTMLDListElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'fieldset'): HTMLCollection<HTMLFieldSetElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'form'): HTMLCollection<HTMLFormElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'): HTMLCollection<HTMLHeadingElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'hr'): HTMLCollection<HTMLHRElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'iframe'): HTMLCollection<HTMLIFrameElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'img'): HTMLCollection<HTMLImageElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'input'): HTMLCollection<HTMLInputElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'label'): HTMLCollection<HTMLLabelElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'legend'): HTMLCollection<HTMLLegendElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'li'): HTMLCollection<HTMLLIElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'link'): HTMLCollection<HTMLLinkElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'meta'): HTMLCollection<HTMLMetaElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'ol'): HTMLCollection<HTMLOListElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'option'): HTMLCollection<HTMLOptionElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'p'): HTMLCollection<HTMLParagraphElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'pre'): HTMLCollection<HTMLPreElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'script'): HTMLCollection<HTMLScriptElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'select'): HTMLCollection<HTMLSelectElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'source'): HTMLCollection<HTMLSourceElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'span'): HTMLCollection<HTMLSpanElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'style'): HTMLCollection<HTMLStyleElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'textarea'): HTMLCollection<HTMLTextAreaElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'video'): HTMLCollection<HTMLVideoElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'table'): HTMLCollection<HTMLTableElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'caption'): HTMLCollection<HTMLTableCaptionElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'thead' | 'tfoot' | 'tbody'): HTMLCollection<HTMLTableSectionElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'tr'): HTMLCollection<HTMLTableRowElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'td' | 'th'): HTMLCollection<HTMLTableCellElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'template'): HTMLCollection<HTMLTemplateElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'ul'): HTMLCollection<HTMLUListElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: string): HTMLCollection<HTMLElement>;
head: HTMLElement | null;
images: HTMLCollection<HTMLImageElement>;
implementation: DOMImplementation;
importNode<T: Node>(importedNode: T, deep: boolean): T;
inputEncoding: string;
lastModified: string;
links: HTMLCollection<HTMLLinkElement>;
media: string;
open(url?: string, name?: string, features?: string, replace?: boolean): any;
readyState: string;
referrer: string;
scripts: HTMLCollection<HTMLScriptElement>;
styleSheets: StyleSheetList;
title: string;
visibilityState: 'visible' | 'hidden' | 'prerender' | 'unloaded';
write(...content: Array<string>): void;
writeln(...content: Array<string>): void;
xmlEncoding: string;
xmlStandalone: boolean;
xmlVersion: string;
registerElement(type: string, options?: ElementRegistrationOptions): any;
getSelection(): Selection | null;
// 6.4.6 Focus management APIs
activeElement: HTMLElement | null;
hasFocus(): boolean;
// extension
location: Location;
createEvent(eventInterface: 'CustomEvent'): CustomEvent;
createEvent(eventInterface: string): Event;
createRange(): Range;
elementFromPoint(x: number, y: number): HTMLElement;
defaultView: any;
compatMode: 'BackCompat' | 'CSS1Compat';
hidden: boolean;
// from ParentNode interface
childElementCount: number;
children: HTMLCollection<HTMLElement>;
firstElementChild: ?Element;
lastElementChild: ?Element;
append(...nodes: Array<string | Node>): void;
prepend(...nodes: Array<string | Node>): void;
querySelector(selector: 'a'): HTMLAnchorElement | null;
querySelector(selector: 'audio'): HTMLAudioElement | null;
querySelector(selector: 'br'): HTMLBRElement | null;
querySelector(selector: 'button'): HTMLButtonElement | null;
querySelector(selector: 'canvas'): HTMLCanvasElement | null;
querySelector(selector: 'details'): HTMLDetailsElement | null;
querySelector(selector: 'div'): HTMLDivElement | null;
querySelector(selector: 'dl'): HTMLDListElement | null;
querySelector(selector: 'fieldset'): HTMLFieldSetElement | null;
querySelector(selector: 'form'): HTMLFormElement | null;
querySelector(selector: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'): HTMLHeadingElement;
querySelector(selector: 'hr'): HTMLHRElement | null;
querySelector(selector: 'iframe'): HTMLIFrameElement | null;
querySelector(selector: 'img'): HTMLImageElement | null;
querySelector(selector: 'input'): HTMLInputElement | null;
querySelector(selector: 'label'): HTMLLabelElement | null;
querySelector(selector: 'legend'): HTMLLegendElement | null;
querySelector(selector: 'li'): HTMLLIElement | null;
querySelector(selector: 'link'): HTMLLinkElement | null;
querySelector(selector: 'meta'): HTMLMetaElement | null;
querySelector(selector: 'ol'): HTMLOListElement | null;
querySelector(selector: 'option'): HTMLOptionElement | null;
querySelector(selector: 'p'): HTMLParagraphElement | null;
querySelector(selector: 'pre'): HTMLPreElement | null;
querySelector(selector: 'script'): HTMLScriptElement | null;
querySelector(selector: 'select'): HTMLSelectElement | null;
querySelector(selector: 'source'): HTMLSourceElement | null;
querySelector(selector: 'span'): HTMLSpanElement | null;
querySelector(selector: 'style'): HTMLStyleElement | null;
querySelector(selector: 'textarea'): HTMLTextAreaElement | null;
querySelector(selector: 'video'): HTMLVideoElement | null;
querySelector(selector: 'table'): HTMLTableElement | null;
querySelector(selector: 'caption'): HTMLTableCaptionElement | null;
querySelector(selector: 'thead' | 'tfoot' | 'tbody'): HTMLTableSectionElement | null;
querySelector(selector: 'tr'): HTMLTableRowElement | null;
querySelector(selector: 'td' | 'th'): HTMLTableCellElement | null;
querySelector(selector: 'template'): HTMLTemplateElement | null;
querySelector(selector: 'ul'): HTMLUListElement | null;
querySelector(selector: string): HTMLElement | null;
querySelectorAll(selector: 'a'): NodeList<HTMLAnchorElement>;
querySelectorAll(selector: 'audio'): NodeList<HTMLAudioElement>;
querySelectorAll(selector: 'br'): NodeList<HTMLBRElement>;
querySelectorAll(selector: 'button'): NodeList<HTMLButtonElement>;
querySelectorAll(selector: 'canvas'): NodeList<HTMLCanvasElement>;
querySelectorAll(selector: 'details'): NodeList<HTMLDetailsElement>;
querySelectorAll(selector: 'div'): NodeList<HTMLDivElement>;
querySelectorAll(selector: 'dl'): NodeList<HTMLDListElement>;
querySelectorAll(selector: 'fieldset'): NodeList<HTMLFieldSetElement>;
querySelectorAll(selector: 'form'): NodeList<HTMLFormElement>;
querySelectorAll(selector: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'): NodeList<HTMLHeadingElement>;
querySelectorAll(selector: 'hr'): NodeList<HTMLHRElement>;
querySelectorAll(selector: 'iframe'): NodeList<HTMLIFrameElement>;
querySelectorAll(selector: 'img'): NodeList<HTMLImageElement>;
querySelectorAll(selector: 'input'): NodeList<HTMLInputElement>;
querySelectorAll(selector: 'label'): NodeList<HTMLLabelElement>;
querySelectorAll(selector: 'legend'): NodeList<HTMLLegendElement>;
querySelectorAll(selector: 'li'): NodeList<HTMLLIElement>;
querySelectorAll(selector: 'link'): NodeList<HTMLLinkElement>;
querySelectorAll(selector: 'meta'): NodeList<HTMLMetaElement>;
querySelectorAll(selector: 'ol'): NodeList<HTMLOListElement>;
querySelectorAll(selector: 'option'): NodeList<HTMLOptionElement>;
querySelectorAll(selector: 'p'): NodeList<HTMLParagraphElement>;
querySelectorAll(selector: 'pre'): NodeList<HTMLPreElement>;
querySelectorAll(selector: 'script'): NodeList<HTMLScriptElement>;
querySelectorAll(selector: 'select'): NodeList<HTMLSelectElement>;
querySelectorAll(selector: 'source'): NodeList<HTMLSourceElement>;
querySelectorAll(selector: 'span'): NodeList<HTMLSpanElement>;
querySelectorAll(selector: 'style'): NodeList<HTMLStyleElement>;
querySelectorAll(selector: 'textarea'): NodeList<HTMLTextAreaElement>;
querySelectorAll(selector: 'video'): NodeList<HTMLVideoElement>;
querySelectorAll(selector: 'table'): NodeList<HTMLTableElement>;
querySelectorAll(selector: 'caption'): NodeList<HTMLTableCaptionElement>;
querySelectorAll(selector: 'thead' | 'tfoot' | 'tbody'): NodeList<HTMLTableSectionElement>;
querySelectorAll(selector: 'tr'): NodeList<HTMLTableRowElement>;
querySelectorAll(selector: 'td' | 'th'): NodeList<HTMLTableCellElement>;
querySelectorAll(selector: 'template'): NodeList<HTMLTemplateElement>;
querySelectorAll(selector: 'ul'): NodeList<HTMLUListElement>;
querySelectorAll(selector: string): NodeList<HTMLElement>;
// Interface DocumentTraversal
// http://www.w3.org/TR/2000/REC-DOM-Level-2-Traversal-Range-20001113/traversal.html#Traversal-Document
// Not all combinations of RootNodeT and whatToShow are logically possible.
// The bitmasks NodeFilter.SHOW_CDATA_SECTION,
// NodeFilter.SHOW_ENTITY_REFERENCE, NodeFilter.SHOW_ENTITY, and
// NodeFilter.SHOW_NOTATION are deprecated and do not correspond to types
// that Flow knows about.
// NodeFilter.SHOW_ATTRIBUTE is also deprecated, but corresponds to the
// type Attr. While there is no reason to prefer it to Node.attributes,
// it does have meaning and can be typed: When (whatToShow &
// NodeFilter.SHOW_ATTRIBUTE === 1), RootNodeT must be Attr, and when
// RootNodeT is Attr, bitmasks other than NodeFilter.SHOW_ATTRIBUTE are
// meaningless.
createNodeIterator<RootNodeT: Attr>(root: RootNodeT, whatToShow: 2, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Attr>;
createTreeWalker<RootNodeT: Attr>(root: RootNodeT, whatToShow: 2, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Attr>;
// NodeFilter.SHOW_PROCESSING_INSTRUCTION is not implemented because Flow
// does not currently define a ProcessingInstruction class.
// When (whatToShow & NodeFilter.SHOW_DOCUMENT === 1 || whatToShow &
// NodeFilter.SHOW_DOCUMENT_TYPE === 1), RootNodeT must be Document.
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 256, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Document>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 257, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Document|Element>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 260, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Document|Text>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 261, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Document|Element|Text>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 384, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Document|Comment>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 385, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Document|Element|Comment>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 388, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Document|Text|Comment>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 389, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Document|Element|Text|Comment>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 512, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 513, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Element>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 516, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Text>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 517, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Element|Text>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 640, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Comment>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 641, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Element|Comment>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 644, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Text|Comment>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 645, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Element|Text|Comment>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 768, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Document>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 769, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Document|Element>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 772, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Document|Text>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 773, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Document|Element|Text>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 896, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Document|Comment>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 897, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Document|Element|Comment>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 900, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Document|Text|Comment>;
createNodeIterator<RootNodeT: Document>(root: RootNodeT, whatToShow: 901, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentType|Document|Element|Text|Comment>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 256, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Document>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 257, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Document|Element>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 260, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Document|Text>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 261, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Document|Element|Text>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 384, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Document|Comment>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 385, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Document|Element|Comment>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 388, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Document|Text|Comment>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 389, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Document|Element|Text|Comment>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 512, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 513, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Element>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 516, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Text>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 517, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Element|Text>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 640, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Comment>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 641, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Element|Comment>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 644, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Text|Comment>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 645, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Element|Text|Comment>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 768, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Document>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 769, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Document|Element>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 772, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Document|Text>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 773, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Document|Element|Text>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 896, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Document|Comment>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 897, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Document|Element|Comment>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 900, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Document|Text|Comment>;
createTreeWalker<RootNodeT: Document>(root: RootNodeT, whatToShow: 901, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentType|Document|Element|Text|Comment>;
// When (whatToShow & NodeFilter.SHOW_DOCUMENT_FRAGMENT === 1), RootNodeT
// must be a DocumentFragment.
createNodeIterator<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1024, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentFragment>;
createNodeIterator<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1025, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentFragment|Element>;
createNodeIterator<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1028, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentFragment|Text>;
createNodeIterator<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1029, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentFragment|Element|Text>;
createNodeIterator<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1152, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentFragment|Comment>;
createNodeIterator<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1153, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentFragment|Element|Comment>;
createNodeIterator<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1156, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentFragment|Text|Comment>;
createNodeIterator<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1157, filter?: NodeFilterInterface): NodeIterator<RootNodeT, DocumentFragment|Element|Text|Comment>;
createTreeWalker<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1024, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentFragment>;
createTreeWalker<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1025, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentFragment|Element>;
createTreeWalker<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1028, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentFragment|Text>;
createTreeWalker<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1029, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentFragment|Element|Text>;
createTreeWalker<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1152, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentFragment|Comment>;
createTreeWalker<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1153, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentFragment|Element|Comment>;
createTreeWalker<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1156, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentFragment|Text|Comment>;
createTreeWalker<RootNodeT: DocumentFragment>(root: RootNodeT, whatToShow: 1157, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, DocumentFragment|Element|Text|Comment>;
// In the general case, RootNodeT may be any Node and whatToShow may be
// NodeFilter.SHOW_ALL or any combination of NodeFilter.SHOW_ELEMENT,
// NodeFilter.SHOW_TEXT and/or NodeFilter.SHOW_COMMENT
createNodeIterator<RootNodeT: Node>(root: RootNodeT, whatToShow: 1, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Element>;
createNodeIterator<RootNodeT: Node>(root: RootNodeT, whatToShow: 4, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Text>;
createNodeIterator<RootNodeT: Node>(root: RootNodeT, whatToShow: 5, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Element|Text>;
createNodeIterator<RootNodeT: Node>(root: RootNodeT, whatToShow: 128, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Comment>;
createNodeIterator<RootNodeT: Node>(root: RootNodeT, whatToShow: 129, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Element|Comment>;
createNodeIterator<RootNodeT: Node>(root: RootNodeT, whatToShow: 132, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Text|Comment>;
createNodeIterator<RootNodeT: Node>(root: RootNodeT, whatToShow: 133, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Text|Element|Comment>;
createTreeWalker<RootNodeT: Node>(root: RootNodeT, whatToShow: 1, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Element>;
createTreeWalker<RootNodeT: Node>(root: RootNodeT, whatToShow: 4, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Text>;
createTreeWalker<RootNodeT: Node>(root: RootNodeT, whatToShow: 5, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Element|Text>;
createTreeWalker<RootNodeT: Node>(root: RootNodeT, whatToShow: 128, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Comment>;
createTreeWalker<RootNodeT: Node>(root: RootNodeT, whatToShow: 129, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Element|Comment>;
createTreeWalker<RootNodeT: Node>(root: RootNodeT, whatToShow: 132, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Text|Comment>;
createTreeWalker<RootNodeT: Node>(root: RootNodeT, whatToShow: 133, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Text|Element|Comment>;
// Catch all for when we don't know the value of `whatToShow`
// And for when whatToShow is not provided, it is assumed to be SHOW_ALL
createNodeIterator<RootNodeT: Node>(root: RootNodeT, whatToShow?: number, filter?: NodeFilterInterface): NodeIterator<RootNodeT, Node>;
createTreeWalker<RootNodeT: Node>(root: RootNodeT, whatToShow?: number, filter?: NodeFilterInterface, entityReferenceExpansion?: boolean): TreeWalker<RootNodeT, Node>;
}
declare class DocumentFragment extends Node {
// from ParentNode interface
childElementCount: number;
children: HTMLCollection<HTMLElement>;
firstElementChild: ?Element;
lastElementChild: ?Element;
append(...nodes: Array<string | Node>): void;
prepend(...nodes: Array<string | Node>): void;
querySelector(selector: string): HTMLElement | null;
querySelectorAll(selector: string): NodeList<HTMLElement>;
}
declare class Selection {
anchorNode: Node | null;
anchorOffset: number;
focusNode: Node | null;
focusOffset: number;
isCollapsed: boolean;
rangeCount: number;
type: string;
addRange(range: Range): void;
getRangeAt(index: number): Range;
removeRange(range: Range): void;
removeAllRanges(): void;
collapse(parentNode: Node | null, offset?: number): void;
collapseToStart(): void;
collapseToEnd(): void;
containsNode(aNode: Node, aPartlyContained?: boolean): boolean;
deleteFromDocument(): void;
extend(parentNode: Node, offset?: number): void;
empty(): void;
selectAllChildren(parentNode: Node): void;
setPosition(aNode: Node | null, offset?: number): void;
setBaseAndExtent(anchorNode: Node, anchorOffset: number, focusNode: Node, focusOffset: number): void;
toString(): string;
}
declare class Range { // extension
startOffset: number;
collapsed: boolean;
endOffset: number;
startContainer: Node;
endContainer: Node;
commonAncestorContainer: Node;
setStart(refNode: Node, offset: number): void;
setEndBefore(refNode: Node): void;
setStartBefore(refNode: Node): void;
selectNode(refNode: Node): void;
detach(): void;
getBoundingClientRect(): ClientRect;
toString(): string;
compareBoundaryPoints(how: number, sourceRange: Range): number;
insertNode(newNode: Node): void;
collapse(toStart: boolean): void;
selectNodeContents(refNode: Node): void;
cloneContents(): DocumentFragment;
setEnd(refNode: Node, offset: number): void;
cloneRange(): Range;
getClientRects(): ClientRectList;
surroundContents(newParent: Node): void;
deleteContents(): void;
setStartAfter(refNode: Node): void;
extractContents(): DocumentFragment;
setEndAfter(refNode: Node): void;
createContextualFragment(fragment: string): Node;
static END_TO_END: number;
static START_TO_START: number;
static START_TO_END: number;
static END_TO_START: number;
}
declare var document: Document;
// TODO: HTMLDocument
declare class DOMTokenList {
@@iterator(): Iterator<string>;
length: number;
item(index: number): string;
contains(token: string): boolean;
add(...token: Array<string>): void;
remove(...token: Array<string>): void;
toggle(token: string, force?: boolean): boolean;
forEach(callbackfn: (value: string, index: number, list: DOMTokenList) => any, thisArg?: any): void;
entries(): Iterator<[number, string]>;
keys(): Iterator<number>;
values(): Iterator<string>;
}
declare class Element extends Node {
assignedSlot: ?HTMLSlotElement;
attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot;
attributes: NamedNodeMap;
classList: DOMTokenList;
className: string;
clientHeight: number;
clientLeft: number;
clientTop: number;
clientWidth: number;
id: string;
innerHTML: string;
localName: string;
namespaceURI: ?string;
nextElementSibling: ?Element;
outerHTML: string;
prefix: string | null;
previousElementSibling: ?Element;
scrollHeight: number;
scrollLeft: number;
scrollTop: number;
scrollWidth: number;
tagName: string;
closest(selectors: string): ?Element;
dispatchEvent(event: Event): bool;
getAttribute(name?: string): ?string;
getAttributeNS(namespaceURI: string | null, localName: string): string | null;
getAttributeNode(name: string): Attr | null;
getAttributeNodeNS(namespaceURI: string | null, localName: string): Attr | null;
getBoundingClientRect(): ClientRect;
getClientRects(): ClientRect[];
getElementsByClassName(names: string): HTMLCollection<HTMLElement>;
getElementsByTagName(name: 'a'): HTMLCollection<HTMLAnchorElement>;
getElementsByTagName(name: 'audio'): HTMLCollection<HTMLAudioElement>;
getElementsByTagName(name: 'br'): HTMLCollection<HTMLBRElement>;
getElementsByTagName(name: 'button'): HTMLCollection<HTMLButtonElement>;
getElementsByTagName(name: 'canvas'): HTMLCollection<HTMLCanvasElement>;
getElementsByTagName(name: 'details'): HTMLCollection<HTMLDetailsElement>;
getElementsByTagName(name: 'div'): HTMLCollection<HTMLDivElement>;
getElementsByTagName(name: 'dl'): HTMLCollection<HTMLDListElement>;
getElementsByTagName(name: 'fieldset'): HTMLCollection<HTMLFieldSetElement>;
getElementsByTagName(name: 'form'): HTMLCollection<HTMLFormElement>;
getElementsByTagName(name: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'): HTMLCollection<HTMLHeadingElement>;
getElementsByTagName(name: 'hr'): HTMLCollection<HTMLHRElement>;
getElementsByTagName(name: 'iframe'): HTMLCollection<HTMLIFrameElement>;
getElementsByTagName(name: 'img'): HTMLCollection<HTMLImageElement>;
getElementsByTagName(name: 'input'): HTMLCollection<HTMLInputElement>;
getElementsByTagName(name: 'label'): HTMLCollection<HTMLLabelElement>;
getElementsByTagName(name: 'legend'): HTMLCollection<HTMLLegendElement>;
getElementsByTagName(name: 'li'): HTMLCollection<HTMLLIElement>;
getElementsByTagName(name: 'link'): HTMLCollection<HTMLLinkElement>;
getElementsByTagName(name: 'meta'): HTMLCollection<HTMLMetaElement>;
getElementsByTagName(name: 'ol'): HTMLCollection<HTMLOListElement>;
getElementsByTagName(name: 'option'): HTMLCollection<HTMLOptionElement>;
getElementsByTagName(name: 'p'): HTMLCollection<HTMLParagraphElement>;
getElementsByTagName(name: 'pre'): HTMLCollection<HTMLPreElement>;
getElementsByTagName(name: 'script'): HTMLCollection<HTMLScriptElement>;
getElementsByTagName(name: 'select'): HTMLCollection<HTMLSelectElement>;
getElementsByTagName(name: 'source'): HTMLCollection<HTMLSourceElement>;
getElementsByTagName(name: 'span'): HTMLCollection<HTMLSpanElement>;
getElementsByTagName(name: 'style'): HTMLCollection<HTMLStyleElement>;
getElementsByTagName(name: 'textarea'): HTMLCollection<HTMLTextAreaElement>;
getElementsByTagName(name: 'video'): HTMLCollection<HTMLVideoElement>;
getElementsByTagName(name: 'table'): HTMLCollection<HTMLTableElement>;
getElementsByTagName(name: 'caption'): HTMLCollection<HTMLTableCaptionElement>;
getElementsByTagName(name: 'thead' | 'tfoot' | 'tbody'): HTMLCollection<HTMLTableSectionElement>;
getElementsByTagName(name: 'tr'): HTMLCollection<HTMLTableRowElement>;
getElementsByTagName(name: 'td' | 'th'): HTMLCollection<HTMLTableCellElement>;
getElementsByTagName(name: 'template'): HTMLCollection<HTMLTemplateElement>;
getElementsByTagName(name: 'ul'): HTMLCollection<HTMLUListElement>;
getElementsByTagName(name: string): HTMLCollection<HTMLElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'a'): HTMLCollection<HTMLAnchorElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'audio'): HTMLCollection<HTMLAudioElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'br'): HTMLCollection<HTMLBRElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'button'): HTMLCollection<HTMLButtonElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'canvas'): HTMLCollection<HTMLCanvasElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'details'): HTMLCollection<HTMLDetailsElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'div'): HTMLCollection<HTMLDivElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'dl'): HTMLCollection<HTMLDListElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'fieldset'): HTMLCollection<HTMLFieldSetElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'form'): HTMLCollection<HTMLFormElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'): HTMLCollection<HTMLHeadingElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'hr'): HTMLCollection<HTMLHRElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'iframe'): HTMLCollection<HTMLIFrameElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'img'): HTMLCollection<HTMLImageElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'input'): HTMLCollection<HTMLInputElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'label'): HTMLCollection<HTMLLabelElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'legend'): HTMLCollection<HTMLLegendElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'li'): HTMLCollection<HTMLLIElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'link'): HTMLCollection<HTMLLinkElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'meta'): HTMLCollection<HTMLMetaElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'ol'): HTMLCollection<HTMLOListElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'option'): HTMLCollection<HTMLOptionElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'p'): HTMLCollection<HTMLParagraphElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'pre'): HTMLCollection<HTMLPreElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'script'): HTMLCollection<HTMLScriptElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'select'): HTMLCollection<HTMLSelectElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'source'): HTMLCollection<HTMLSourceElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'span'): HTMLCollection<HTMLSpanElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'style'): HTMLCollection<HTMLStyleElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'textarea'): HTMLCollection<HTMLTextAreaElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'video'): HTMLCollection<HTMLVideoElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'table'): HTMLCollection<HTMLTableElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'caption'): HTMLCollection<HTMLTableCaptionElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'thead' | 'tfoot' | 'tbody'): HTMLCollection<HTMLTableSectionElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'tr'): HTMLCollection<HTMLTableRowElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'td' | 'th'): HTMLCollection<HTMLTableCellElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'template'): HTMLCollection<HTMLTemplateElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: 'ul'): HTMLCollection<HTMLUListElement>;
getElementsByTagNameNS(namespaceURI: string | null, localName: string): HTMLCollection<HTMLElement>;
hasAttribute(name: string): boolean;
hasAttributeNS(namespaceURI: string | null, localName: string): boolean;
insertAdjacentElement(position: 'beforebegin' | 'afterbegin' | 'beforeend' | 'afterend', element: Element): void;
insertAdjacentHTML(position: 'beforebegin' | 'afterbegin' | 'beforeend' | 'afterend', html: string): void;
insertAdjacentText(position: 'beforebegin' | 'afterbegin' | 'beforeend' | 'afterend', text: string): void;
matches(selector: string): bool;
querySelector(selector: string): HTMLElement | null;
querySelectorAll(selector: string): NodeList<HTMLElement>;
releasePointerCapture(pointerId: string): void;
removeAttribute(name?: string): void;
removeAttributeNode(attributeNode: Attr): Attr;
removeAttributeNS(namespaceURI: string | null, localName: string): void;
requestFullscreen(): void;
requestPointerLock(): void;
scrollIntoView(arg?: (boolean | { behavior?: ('auto' | 'instant' | 'smooth'), block?: ('start' | 'end') })): void;
setAttribute(name?: string, value?: string): void;
setAttributeNS(namespaceURI: string | null, qualifiedName: string, value: string): void;
setAttributeNode(newAttr: Attr): Attr | null;
setAttributeNodeNS(newAttr: Attr): Attr | null;
setPointerCapture(pointerId: string): void;
shadowRoot?: ShadowRoot;
slot?: string;
// from ParentNode interface
childElementCount: number;
children: HTMLCollection<HTMLElement>;
firstElementChild: ?Element;
lastElementChild: ?Element;
append(...nodes: Array<string | Node>): void;
prepend(...nodes: Array<string | Node>): void;
// from ChildNode interface
after(...nodes: Array<string | Node>): void;
before(...nodes: Array<string | Node>): void;
replaceWith(...nodes: Array<string | Node>): void;
remove(): void;
}
declare class HTMLElement extends Element {
blur(): void;
click(): void;
focus(): void;
getBoundingClientRect(): ClientRect;
forceSpellcheck(): void;
accessKey: string;
accessKeyLabel: string;
className: string;
contentEditable: string;
contextMenu: ?HTMLMenuElement;
dataset: {[key:string]: string};
dir: 'ltr' | 'rtl' | 'auto';
draggable: bool;
dropzone: any;
hidden: boolean;
id: string;
innerHTML: string;
isContentEditable: boolean;
itemProp: any;
itemScope: bool;
itemType: any;
itemValue: Object;
lang: string;
offsetHeight: number;
offsetLeft: number;
offsetParent: Element;
offsetTop: number;
offsetWidth: number;
onabort: ?Function;
onblur: ?Function;
oncancel: ?Function;
oncanplay: ?Function;
oncanplaythrough: ?Function;
onchange: ?Function;
onclick: ?Function;
oncuechange: ?Function;
ondblclick: ?Function;
ondurationchange: ?Function;
onemptied: ?Function;
onended: ?Function;
onerror: ?Function;
onfocus: ?Function;
oninput: ?Function;
oninvalid: ?Function;
onkeydown: ?Function;
onkeypress: ?Function;
onkeyup: ?Function;
onload: ?Function;
onloadeddata: ?Function;
onloadedmetadata: ?Function;
onloadstart: ?Function;
onmousedown: ?Function;
onmouseenter: ?Function;
onmouseleave: ?Function;
onmousemove: ?Function;
onmouseout: ?Function;
onmouseover: ?Function;
onmouseup: ?Function;
onmousewheel: ?Function;
onpause: ?Function;
onplay: ?Function;
onplaying: ?Function;
onprogress: ?Function;
onratechange: ?Function;
onreadystatechange: ?Function;
onreset: ?Function;
onresize: ?Function;
onscroll: ?Function;
onseeked: ?Function;
onseeking: ?Function;
onselect: ?Function;
onshow: ?Function;
onstalled: ?Function;
onsubmit: ?Function;
onsuspend: ?Function;
ontimeupdate: ?Function;
ontoggle: ?Function;
onvolumechange: ?Function;
onwaiting: ?Function;
properties: any;
spellcheck: boolean;
style: CSSStyleDeclaration;
tabIndex: number;
title: string;
translate: boolean;
}
declare class HTMLSlotElement extends HTMLElement {
name: string;
assignedNodes(options?: {flatten: boolean}): Node[];
}
declare class HTMLTableElement extends HTMLElement {
caption: HTMLTableCaptionElement;
tHead: HTMLTableSectionElement;
tFoot: HTMLTableSectionElement;
tBodies: HTMLCollection<HTMLTableSectionElement>;
rows: HTMLCollection<HTMLTableRowElement>;
createTHead(): HTMLTableSectionElement;
deleteTHead(): void;
createTFoot(): HTMLTableSectionElement;
deleteTFoot(): void;
createCaption(): HTMLTableCaptionElement;
deleteCaption(): void;
insertRow(index: ?number): HTMLTableRowElement;
deleteRow(index: number): void;
}
declare class HTMLTableCaptionElement extends HTMLElement {
}
declare class HTMLTableSectionElement extends HTMLElement {
rows: HTMLCollection<HTMLTableRowElement>;
}
declare class HTMLTableCellElement extends HTMLElement {
colSpan: number;
rowSpan: number;
cellIndex: number;
}
declare class HTMLTableRowElement extends HTMLElement {
align: 'left' | 'right' | 'center';
rowIndex: number;
deleteCell(index: number): void;
insertCell(index: number): HTMLTableCellElement;
}
declare class HTMLMenuElement extends HTMLElement {
getCompact(): bool;
setCompact(compact: bool): void;
}
declare class HTMLBaseElement extends HTMLElement {
href: string;
target: string;
}
declare class HTMLTemplateElement extends HTMLElement {
content: DocumentFragment;
}
declare class CanvasGradient {
addColorStop(offset: number, color: string): void;
}
declare class CanvasPattern {
setTransform(matrix: SVGMatrix): void;
}
declare class ImageBitmap {
close(): void;
width: number;
height: number;
}
type CanvasFillRule = string;
type CanvasImageSource = HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | CanvasRenderingContext2D | ImageBitmap;
declare class HitRegionOptions {
path?: Path2D,
fillRule?: CanvasFillRule,
id?: string,
parentID?: string;
cursor?: string;
control?: Element;
label: ?string;
role: ?string;
};
declare class CanvasDrawingStyles {
lineWidth: number;
lineCap: string;
lineJoin: string;
miterLimit: number;
// dashed lines
setLineDash(segments: Array<number>): void;
getLineDash(): Array<number>;
lineDashOffset: number;
// text
font: string;
textAlign: string;
textBaseline: string;
direction: string;
};
declare class SVGMatrix {
getComponent(index: number): number;
mMultiply(secondMatrix: SVGMatrix): SVGMatrix;
inverse(): SVGMatrix;
mTranslate(x: number, y: number): SVGMatrix;
mScale(scaleFactor: number): SVGMatrix;
mRotate(angle: number): SVGMatrix;
};
declare class TextMetrics {
// x-direction
width: number;
actualBoundingBoxLeft: number;
actualBoundingBoxRight: number;
// y-direction
fontBoundingBoxAscent: number;
fontBoundingBoxDescent: number;
actualBoundingBoxAscent: number;
actualBoundingBoxDescent: number;
emHeightAscent: number;
emHeightDescent: number;
hangingBaseline: number;
alphabeticBaseline: number;
ideographicBaseline: number;
};
declare class Path2D {
addPath(path: Path2D, transformation?: ?SVGMatrix): void;
addPathByStrokingPath(path: Path2D, styles: CanvasDrawingStyles, transformation?: ?SVGMatrix): void;
addText(text: string, styles: CanvasDrawingStyles, transformation: ?SVGMatrix, x: number, y: number, maxWidth?: number): void;
addPathByStrokingText(text: string, styles: CanvasDrawingStyles, transformation: ?SVGMatrix, x: number, y: number, maxWidth?: number): void;
addText(text: string, styles: CanvasDrawingStyles, transformation: ?SVGMatrix, path: Path2D, maxWidth?: number): void;
addPathByStrokingText(text: string, styles: CanvasDrawingStyles, transformation: ?SVGMatrix, path: Path2D, maxWidth?: number): void;
// CanvasPathMethods
// shared path API methods
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number, _: void, _: void): void;
arcTo(x1: number, y1: number, x2: number, y2: number, radiusX: number, radiusY: number, rotation: number): void;
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void;
closePath(): void;
ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;
lineTo(x: number, y: number): void;
moveTo(x: number, y: number): void;
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void;
rect(x: number, y: number, w: number, h: number): void;
};
declare class ImageData {
width: number;
height: number;
data: Uint8ClampedArray;
// constructor methods are used in Worker where CanvasRenderingContext2D
// is unavailable.
// https://html.spec.whatwg.org/multipage/scripting.html#dom-imagedata
constructor(data: Uint8ClampedArray, width: number, height: number): void;
constructor(width: number, height: number): void;
};
declare class CanvasRenderingContext2D {
canvas: HTMLCanvasElement;
// canvas dimensions
width: number;
height: number;
// for contexts that aren't directly fixed to a specific canvas
commit(): void;
// state
save(): void;
restore(): void;
// transformations
currentTransform: SVGMatrix;
scale(x: number, y: number): void;
rotate(angle: number): void;
translate(x: number, y: number): void;
transform(a: number, b: number, c: number, d: number, e: number, f: number): void;
setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void;
resetTransform(): void;
// compositing
globalAlpha: number;
globalCompositeOperation: string;
// image smoothing
imageSmoothingEnabled: boolean;
// colours and styles
strokeStyle: string | CanvasGradient | CanvasPattern;
fillStyle: string | CanvasGradient | CanvasPattern;
createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;
createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient;
createPattern(image: CanvasImageSource, repetition: ?string): CanvasPattern;
// shadows
shadowOffsetX: number;
shadowOffsetY: number;
shadowBlur: number;
shadowColor: string;
// rects
clearRect(x: number, y: number, w: number, h: number): void;
fillRect(x: number, y: number, w: number, h: number): void;
strokeRect(x: number, y: number, w: number, h: number): void;
// path API
beginPath(): void;
fill(fillRule?: CanvasFillRule): void;
fill(path: Path2D, fillRule?: CanvasFillRule): void;
stroke(): void;
stroke(path: Path2D): void;
drawFocusIfNeeded(element: Element): void;
drawFocusIfNeeded(path: Path2D, element: Element): void;
scrollPathIntoView(): void;
scrollPathIntoView(path: Path2D): void;
clip(fillRule?: CanvasFillRule): void;
clip(path: Path2D, fillRule?: CanvasFillRule): void;
resetClip(): void;
isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean;
isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean;
isPointInStroke(x: number, y: number): boolean;
isPointInStroke(path: Path2D, x: number, y: number): boolean;
// text (see also the CanvasDrawingStyles interface)
fillText(text: string, x: number, y: number, maxWidth?: number): void;
strokeText(text: string, x: number, y: number, maxWidth?: number): void;
measureText(text: string): TextMetrics;
// drawing images
drawImage(image: CanvasImageSource, dx: number, dy: number): void;
drawImage(image: CanvasImageSource, dx: number, dy: number, dw: number, dh: number): void;
drawImage(image: CanvasImageSource, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;
// hit regions
addHitRegion(options?: HitRegionOptions): void;
removeHitRegion(id: string): void;
clearHitRegions(): void;
// pixel manipulation
createImageData(sw: number, sh: number): ImageData;
createImageData(imagedata: ImageData): ImageData;
getImageData(sx: number, sy: number, sw: number, sh: number): ImageData;
putImageData(imagedata: ImageData, dx: number, dy: number): void;
putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void;
// CanvasDrawingStyles
// line caps/joins
lineWidth: number;
lineCap: string;
lineJoin: string;
miterLimit: number;
// dashed lines
setLineDash(segments: Array<number>): void;
getLineDash(): Array<number>;
lineDashOffset: number;
// text
font: string;
textAlign: string;
textBaseline: string;
direction: string;
// CanvasPathMethods
// shared path API methods
closePath(): void;
moveTo(x: number, y: number): void;
lineTo(x: number, y: number): void;
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void;
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void;
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void;
arcTo(x1: number, y1: number, x2: number, y2: number, radiusX: number, radiusY: number, rotation: number): void;
rect(x: number, y: number, w: number, h: number): void;
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;
ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;
}
// WebGL idl: https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
type WebGLContextAttributes = {
alpha: bool,
depth: bool,
stencil: bool,
antialias: bool,
premultipliedAlpha: bool,
preserveDrawingBuffer: bool,
preferLowPowerToHighPerformance: bool,
failIfMajorPerformanceCaveat: bool
};
interface WebGLObject {
};
interface WebGLBuffer extends WebGLObject {
};
interface WebGLFramebuffer extends WebGLObject {
};
interface WebGLProgram extends WebGLObject {
};
interface WebGLRenderbuffer extends WebGLObject {
};
interface WebGLShader extends WebGLObject {
};
interface WebGLTexture extends WebGLObject {
};
interface WebGLUniformLocation {
};
interface WebGLActiveInfo {
size: number;
type: number;
name: string;
};
interface WebGLShaderPrecisionFormat {
rangeMin: number;
rangeMax: number;
precision: number;
};
type BufferDataSource = ArrayBuffer | $ArrayBufferView;
type TexImageSource =
ImageBitmap |
ImageData |
HTMLImageElement |
HTMLCanvasElement |
HTMLVideoElement;
type VertexAttribFVSource =
Float32Array |
Array<number>;
/* flow */
declare class WebGLRenderingContext {
static DEPTH_BUFFER_BIT : 0x00000100;
DEPTH_BUFFER_BIT : 0x00000100;
static STENCIL_BUFFER_BIT : 0x00000400;
STENCIL_BUFFER_BIT : 0x00000400;
static COLOR_BUFFER_BIT : 0x00004000;
COLOR_BUFFER_BIT : 0x00004000;
static POINTS : 0x0000;
POINTS : 0x0000;
static LINES : 0x0001;
LINES : 0x0001;
static LINE_LOOP : 0x0002;
LINE_LOOP : 0x0002;
static LINE_STRIP : 0x0003;
LINE_STRIP : 0x0003;
static TRIANGLES : 0x0004;
TRIANGLES : 0x0004;
static TRIANGLE_STRIP : 0x0005;
TRIANGLE_STRIP : 0x0005;
static TRIANGLE_FAN : 0x0006;
TRIANGLE_FAN : 0x0006;
static ZERO : 0;
ZERO : 0;
static ONE : 1;
ONE : 1;
static SRC_COLOR : 0x0300;
SRC_COLOR : 0x0300;
static ONE_MINUS_SRC_COLOR : 0x0301;
ONE_MINUS_SRC_COLOR : 0x0301;
static SRC_ALPHA : 0x0302;
SRC_ALPHA : 0x0302;
static ONE_MINUS_SRC_ALPHA : 0x0303;
ONE_MINUS_SRC_ALPHA : 0x0303;
static DST_ALPHA : 0x0304;
DST_ALPHA : 0x0304;
static ONE_MINUS_DST_ALPHA : 0x0305;
ONE_MINUS_DST_ALPHA : 0x0305;
static DST_COLOR : 0x0306;
DST_COLOR : 0x0306;
static ONE_MINUS_DST_COLOR : 0x0307;
ONE_MINUS_DST_COLOR : 0x0307;
static SRC_ALPHA_SATURATE : 0x0308;
SRC_ALPHA_SATURATE : 0x0308;
static FUNC_ADD : 0x8006;
FUNC_ADD : 0x8006;
static BLEND_EQUATION : 0x8009;
BLEND_EQUATION : 0x8009;
static BLEND_EQUATION_RGB : 0x8009;
BLEND_EQUATION_RGB : 0x8009;
static BLEND_EQUATION_ALPHA : 0x883D;
BLEND_EQUATION_ALPHA : 0x883D;
static FUNC_SUBTRACT : 0x800A;
FUNC_SUBTRACT : 0x800A;
static FUNC_REVERSE_SUBTRACT : 0x800B;
FUNC_REVERSE_SUBTRACT : 0x800B;
static BLEND_DST_RGB : 0x80C8;
BLEND_DST_RGB : 0x80C8;
static BLEND_SRC_RGB : 0x80C9;
BLEND_SRC_RGB : 0x80C9;
static BLEND_DST_ALPHA : 0x80CA;
BLEND_DST_ALPHA : 0x80CA;
static BLEND_SRC_ALPHA : 0x80CB;
BLEND_SRC_ALPHA : 0x80CB;
static CONSTANT_COLOR : 0x8001;
CONSTANT_COLOR : 0x8001;
static ONE_MINUS_CONSTANT_COLOR : 0x8002;
ONE_MINUS_CONSTANT_COLOR : 0x8002;
static CONSTANT_ALPHA : 0x8003;
CONSTANT_ALPHA : 0x8003;
static ONE_MINUS_CONSTANT_ALPHA : 0x8004;
ONE_MINUS_CONSTANT_ALPHA : 0x8004;
static BLEND_COLOR : 0x8005;
BLEND_COLOR : 0x8005;
static ARRAY_BUFFER : 0x8892;
ARRAY_BUFFER : 0x8892;
static ELEMENT_ARRAY_BUFFER : 0x8893;
ELEMENT_ARRAY_BUFFER : 0x8893;
static ARRAY_BUFFER_BINDING : 0x8894;
ARRAY_BUFFER_BINDING : 0x8894;
static ELEMENT_ARRAY_BUFFER_BINDING : 0x8895;
ELEMENT_ARRAY_BUFFER_BINDING : 0x8895;
static STREAM_DRAW : 0x88E0;
STREAM_DRAW : 0x88E0;
static STATIC_DRAW : 0x88E4;
STATIC_DRAW : 0x88E4;
static DYNAMIC_DRAW : 0x88E8;
DYNAMIC_DRAW : 0x88E8;
static BUFFER_SIZE : 0x8764;
BUFFER_SIZE : 0x8764;
static BUFFER_USAGE : 0x8765;
BUFFER_USAGE : 0x8765;
static CURRENT_VERTEX_ATTRIB : 0x8626;
CURRENT_VERTEX_ATTRIB : 0x8626;
static FRONT : 0x0404;
FRONT : 0x0404;
static BACK : 0x0405;
BACK : 0x0405;
static FRONT_AND_BACK : 0x0408;
FRONT_AND_BACK : 0x0408;
static CULL_FACE : 0x0B44;
CULL_FACE : 0x0B44;
static BLEND : 0x0BE2;
BLEND : 0x0BE2;
static DITHER : 0x0BD0;
DITHER : 0x0BD0;
static STENCIL_TEST : 0x0B90;
STENCIL_TEST : 0x0B90;
static DEPTH_TEST : 0x0B71;
DEPTH_TEST : 0x0B71;
static SCISSOR_TEST : 0x0C11;
SCISSOR_TEST : 0x0C11;
static POLYGON_OFFSET_FILL : 0x8037;
POLYGON_OFFSET_FILL : 0x8037;
static SAMPLE_ALPHA_TO_COVERAGE : 0x809E;
SAMPLE_ALPHA_TO_COVERAGE : 0x809E;
static SAMPLE_COVERAGE : 0x80A0;
SAMPLE_COVERAGE : 0x80A0;
static NO_ERROR : 0;
NO_ERROR : 0;
static INVALID_ENUM : 0x0500;
INVALID_ENUM : 0x0500;
static INVALID_VALUE : 0x0501;
INVALID_VALUE : 0x0501;
static INVALID_OPERATION : 0x0502;
INVALID_OPERATION : 0x0502;
static OUT_OF_MEMORY : 0x0505;
OUT_OF_MEMORY : 0x0505;
static CW : 0x0900;
CW : 0x0900;
static CCW : 0x0901;
CCW : 0x0901;
static LINE_WIDTH : 0x0B21;
LINE_WIDTH : 0x0B21;
static ALIASED_POINT_SIZE_RANGE : 0x846D;
ALIASED_POINT_SIZE_RANGE : 0x846D;
static ALIASED_LINE_WIDTH_RANGE : 0x846E;
ALIASED_LINE_WIDTH_RANGE : 0x846E;
static CULL_FACE_MODE : 0x0B45;
CULL_FACE_MODE : 0x0B45;
static FRONT_FACE : 0x0B46;
FRONT_FACE : 0x0B46;
static DEPTH_RANGE : 0x0B70;
DEPTH_RANGE : 0x0B70;
static DEPTH_WRITEMASK : 0x0B72;
DEPTH_WRITEMASK : 0x0B72;
static DEPTH_CLEAR_VALUE : 0x0B73;
DEPTH_CLEAR_VALUE : 0x0B73;
static DEPTH_FUNC : 0x0B74;
DEPTH_FUNC : 0x0B74;
static STENCIL_CLEAR_VALUE : 0x0B91;
STENCIL_CLEAR_VALUE : 0x0B91;
static STENCIL_FUNC : 0x0B92;
STENCIL_FUNC : 0x0B92;
static STENCIL_FAIL : 0x0B94;
STENCIL_FAIL : 0x0B94;
static STENCIL_PASS_DEPTH_FAIL : 0x0B95;
STENCIL_PASS_DEPTH_FAIL : 0x0B95;
static STENCIL_PASS_DEPTH_PASS : 0x0B96;
STENCIL_PASS_DEPTH_PASS : 0x0B96;
static STENCIL_REF : 0x0B97;
STENCIL_REF : 0x0B97;
static STENCIL_VALUE_MASK : 0x0B93;
STENCIL_VALUE_MASK : 0x0B93;
static STENCIL_WRITEMASK : 0x0B98;
STENCIL_WRITEMASK : 0x0B98;
static STENCIL_BACK_FUNC : 0x8800;
STENCIL_BACK_FUNC : 0x8800;
static STENCIL_BACK_FAIL : 0x8801;
STENCIL_BACK_FAIL : 0x8801;
static STENCIL_BACK_PASS_DEPTH_FAIL : 0x8802;
STENCIL_BACK_PASS_DEPTH_FAIL : 0x8802;
static STENCIL_BACK_PASS_DEPTH_PASS : 0x8803;
STENCIL_BACK_PASS_DEPTH_PASS : 0x8803;
static STENCIL_BACK_REF : 0x8CA3;
STENCIL_BACK_REF : 0x8CA3;
static STENCIL_BACK_VALUE_MASK : 0x8CA4;
STENCIL_BACK_VALUE_MASK : 0x8CA4;
static STENCIL_BACK_WRITEMASK : 0x8CA5;
STENCIL_BACK_WRITEMASK : 0x8CA5;
static VIEWPORT : 0x0BA2;
VIEWPORT : 0x0BA2;
static SCISSOR_BOX : 0x0C10;
SCISSOR_BOX : 0x0C10;
static COLOR_CLEAR_VALUE : 0x0C22;
COLOR_CLEAR_VALUE : 0x0C22;
static COLOR_WRITEMASK : 0x0C23;
COLOR_WRITEMASK : 0x0C23;
static UNPACK_ALIGNMENT : 0x0CF5;
UNPACK_ALIGNMENT : 0x0CF5;
static PACK_ALIGNMENT : 0x0D05;
PACK_ALIGNMENT : 0x0D05;
static MAX_TEXTURE_SIZE : 0x0D33;
MAX_TEXTURE_SIZE : 0x0D33;
static MAX_VIEWPORT_DIMS : 0x0D3A;
MAX_VIEWPORT_DIMS : 0x0D3A;
static SUBPIXEL_BITS : 0x0D50;
SUBPIXEL_BITS : 0x0D50;
static RED_BITS : 0x0D52;
RED_BITS : 0x0D52;
static GREEN_BITS : 0x0D53;
GREEN_BITS : 0x0D53;
static BLUE_BITS : 0x0D54;
BLUE_BITS : 0x0D54;
static ALPHA_BITS : 0x0D55;
ALPHA_BITS : 0x0D55;
static DEPTH_BITS : 0x0D56;
DEPTH_BITS : 0x0D56;
static STENCIL_BITS : 0x0D57;
STENCIL_BITS : 0x0D57;
static POLYGON_OFFSET_UNITS : 0x2A00;
POLYGON_OFFSET_UNITS : 0x2A00;
static POLYGON_OFFSET_FACTOR : 0x8038;
POLYGON_OFFSET_FACTOR : 0x8038;
static TEXTURE_BINDING_2D : 0x8069;
TEXTURE_BINDING_2D : 0x8069;
static SAMPLE_BUFFERS : 0x80A8;
SAMPLE_BUFFERS : 0x80A8;
static SAMPLES : 0x80A9;
SAMPLES : 0x80A9;
static SAMPLE_COVERAGE_VALUE : 0x80AA;
SAMPLE_COVERAGE_VALUE : 0x80AA;
static SAMPLE_COVERAGE_INVERT : 0x80AB;
SAMPLE_COVERAGE_INVERT : 0x80AB;
static COMPRESSED_TEXTURE_FORMATS : 0x86A3;
COMPRESSED_TEXTURE_FORMATS : 0x86A3;
static DONT_CARE : 0x1100;
DONT_CARE : 0x1100;
static FASTEST : 0x1101;
FASTEST : 0x1101;
static NICEST : 0x1102;
NICEST : 0x1102;
static GENERATE_MIPMAP_HINT : 0x8192;
GENERATE_MIPMAP_HINT : 0x8192;
static BYTE : 0x1400;
BYTE : 0x1400;
static UNSIGNED_BYTE : 0x1401;
UNSIGNED_BYTE : 0x1401;
static SHORT : 0x1402;
SHORT : 0x1402;
static UNSIGNED_SHORT : 0x1403;
UNSIGNED_SHORT : 0x1403;
static INT : 0x1404;
INT : 0x1404;
static UNSIGNED_INT : 0x1405;
UNSIGNED_INT : 0x1405;
static FLOAT : 0x1406;
FLOAT : 0x1406;
static DEPTH_COMPONENT : 0x1902;
DEPTH_COMPONENT : 0x1902;
static ALPHA : 0x1906;
ALPHA : 0x1906;
static RGB : 0x1907;
RGB : 0x1907;
static RGBA : 0x1908;
RGBA : 0x1908;
static LUMINANCE : 0x1909;
LUMINANCE : 0x1909;
static LUMINANCE_ALPHA : 0x190A;
LUMINANCE_ALPHA : 0x190A;
static UNSIGNED_SHORT_4_4_4_4 : 0x8033;
UNSIGNED_SHORT_4_4_4_4 : 0x8033;
static UNSIGNED_SHORT_5_5_5_1 : 0x8034;
UNSIGNED_SHORT_5_5_5_1 : 0x8034;
static UNSIGNED_SHORT_5_6_5 : 0x8363;
UNSIGNED_SHORT_5_6_5 : 0x8363;
static FRAGMENT_SHADER : 0x8B30;
FRAGMENT_SHADER : 0x8B30;
static VERTEX_SHADER : 0x8B31;
VERTEX_SHADER : 0x8B31;
static MAX_VERTEX_ATTRIBS : 0x8869;
MAX_VERTEX_ATTRIBS : 0x8869;
static MAX_VERTEX_UNIFORM_VECTORS : 0x8DFB;
MAX_VERTEX_UNIFORM_VECTORS : 0x8DFB;
static MAX_VARYING_VECTORS : 0x8DFC;
MAX_VARYING_VECTORS : 0x8DFC;
static MAX_COMBINED_TEXTURE_IMAGE_UNITS : 0x8B4D;
MAX_COMBINED_TEXTURE_IMAGE_UNITS : 0x8B4D;
static MAX_VERTEX_TEXTURE_IMAGE_UNITS : 0x8B4C;
MAX_VERTEX_TEXTURE_IMAGE_UNITS : 0x8B4C;
static MAX_TEXTURE_IMAGE_UNITS : 0x8872;
MAX_TEXTURE_IMAGE_UNITS : 0x8872;
static MAX_FRAGMENT_UNIFORM_VECTORS : 0x8DFD;
MAX_FRAGMENT_UNIFORM_VECTORS : 0x8DFD;
static SHADER_TYPE : 0x8B4F;
SHADER_TYPE : 0x8B4F;
static DELETE_STATUS : 0x8B80;
DELETE_STATUS : 0x8B80;
static LINK_STATUS : 0x8B82;
LINK_STATUS : 0x8B82;
static VALIDATE_STATUS : 0x8B83;
VALIDATE_STATUS : 0x8B83;
static ATTACHED_SHADERS : 0x8B85;
ATTACHED_SHADERS : 0x8B85;
static ACTIVE_UNIFORMS : 0x8B86;
ACTIVE_UNIFORMS : 0x8B86;
static ACTIVE_ATTRIBUTES : 0x8B89;
ACTIVE_ATTRIBUTES : 0x8B89;
static SHADING_LANGUAGE_VERSION : 0x8B8C;
SHADING_LANGUAGE_VERSION : 0x8B8C;
static CURRENT_PROGRAM : 0x8B8D;
CURRENT_PROGRAM : 0x8B8D;
static NEVER : 0x0200;
NEVER : 0x0200;
static LESS : 0x0201;
LESS : 0x0201;
static EQUAL : 0x0202;
EQUAL : 0x0202;
static LEQUAL : 0x0203;
LEQUAL : 0x0203;
static GREATER : 0x0204;
GREATER : 0x0204;
static NOTEQUAL : 0x0205;
NOTEQUAL : 0x0205;
static GEQUAL : 0x0206;
GEQUAL : 0x0206;
static ALWAYS : 0x0207;
ALWAYS : 0x0207;
static KEEP : 0x1E00;
KEEP : 0x1E00;
static REPLACE : 0x1E01;
REPLACE : 0x1E01;
static INCR : 0x1E02;
INCR : 0x1E02;
static DECR : 0x1E03;
DECR : 0x1E03;
static INVERT : 0x150A;
INVERT : 0x150A;
static INCR_WRAP : 0x8507;
INCR_WRAP : 0x8507;
static DECR_WRAP : 0x8508;
DECR_WRAP : 0x8508;
static VENDOR : 0x1F00;
VENDOR : 0x1F00;
static RENDERER : 0x1F01;
RENDERER : 0x1F01;
static VERSION : 0x1F02;
VERSION : 0x1F02;
static NEAREST : 0x2600;
NEAREST : 0x2600;
static LINEAR : 0x2601;
LINEAR : 0x2601;
static NEAREST_MIPMAP_NEAREST : 0x2700;
NEAREST_MIPMAP_NEAREST : 0x2700;
static LINEAR_MIPMAP_NEAREST : 0x2701;
LINEAR_MIPMAP_NEAREST : 0x2701;
static NEAREST_MIPMAP_LINEAR : 0x2702;
NEAREST_MIPMAP_LINEAR : 0x2702;
static LINEAR_MIPMAP_LINEAR : 0x2703;
LINEAR_MIPMAP_LINEAR : 0x2703;
static TEXTURE_MAG_FILTER : 0x2800;
TEXTURE_MAG_FILTER : 0x2800;
static TEXTURE_MIN_FILTER : 0x2801;
TEXTURE_MIN_FILTER : 0x2801;
static TEXTURE_WRAP_S : 0x2802;
TEXTURE_WRAP_S : 0x2802;
static TEXTURE_WRAP_T : 0x2803;
TEXTURE_WRAP_T : 0x2803;
static TEXTURE_2D : 0x0DE1;
TEXTURE_2D : 0x0DE1;
static TEXTURE : 0x1702;
TEXTURE : 0x1702;
static TEXTURE_CUBE_MAP : 0x8513;
TEXTURE_CUBE_MAP : 0x8513;
static TEXTURE_BINDING_CUBE_MAP : 0x8514;
TEXTURE_BINDING_CUBE_MAP : 0x8514;
static TEXTURE_CUBE_MAP_POSITIVE_X : 0x8515;
TEXTURE_CUBE_MAP_POSITIVE_X : 0x8515;
static TEXTURE_CUBE_MAP_NEGATIVE_X : 0x8516;
TEXTURE_CUBE_MAP_NEGATIVE_X : 0x8516;
static TEXTURE_CUBE_MAP_POSITIVE_Y : 0x8517;
TEXTURE_CUBE_MAP_POSITIVE_Y : 0x8517;
static TEXTURE_CUBE_MAP_NEGATIVE_Y : 0x8518;
TEXTURE_CUBE_MAP_NEGATIVE_Y : 0x8518;
static TEXTURE_CUBE_MAP_POSITIVE_Z : 0x8519;
TEXTURE_CUBE_MAP_POSITIVE_Z : 0x8519;
static TEXTURE_CUBE_MAP_NEGATIVE_Z : 0x851A;
TEXTURE_CUBE_MAP_NEGATIVE_Z : 0x851A;
static MAX_CUBE_MAP_TEXTURE_SIZE : 0x851C;
MAX_CUBE_MAP_TEXTURE_SIZE : 0x851C;
static TEXTURE0 : 0x84C0;
TEXTURE0 : 0x84C0;
static TEXTURE1 : 0x84C1;
TEXTURE1 : 0x84C1;
static TEXTURE2 : 0x84C2;
TEXTURE2 : 0x84C2;
static TEXTURE3 : 0x84C3;
TEXTURE3 : 0x84C3;
static TEXTURE4 : 0x84C4;
TEXTURE4 : 0x84C4;
static TEXTURE5 : 0x84C5;
TEXTURE5 : 0x84C5;
static TEXTURE6 : 0x84C6;
TEXTURE6 : 0x84C6;
static TEXTURE7 : 0x84C7;
TEXTURE7 : 0x84C7;
static TEXTURE8 : 0x84C8;
TEXTURE8 : 0x84C8;
static TEXTURE9 : 0x84C9;
TEXTURE9 : 0x84C9;
static TEXTURE10 : 0x84CA;
TEXTURE10 : 0x84CA;
static TEXTURE11 : 0x84CB;
TEXTURE11 : 0x84CB;
static TEXTURE12 : 0x84CC;
TEXTURE12 : 0x84CC;
static TEXTURE13 : 0x84CD;
TEXTURE13 : 0x84CD;
static TEXTURE14 : 0x84CE;
TEXTURE14 : 0x84CE;
static TEXTURE15 : 0x84CF;
TEXTURE15 : 0x84CF;
static TEXTURE16 : 0x84D0;
TEXTURE16 : 0x84D0;
static TEXTURE17 : 0x84D1;
TEXTURE17 : 0x84D1;
static TEXTURE18 : 0x84D2;
TEXTURE18 : 0x84D2;
static TEXTURE19 : 0x84D3;
TEXTURE19 : 0x84D3;
static TEXTURE20 : 0x84D4;
TEXTURE20 : 0x84D4;
static TEXTURE21 : 0x84D5;
TEXTURE21 : 0x84D5;
static TEXTURE22 : 0x84D6;
TEXTURE22 : 0x84D6;
static TEXTURE23 : 0x84D7;
TEXTURE23 : 0x84D7;
static TEXTURE24 : 0x84D8;
TEXTURE24 : 0x84D8;
static TEXTURE25 : 0x84D9;
TEXTURE25 : 0x84D9;
static TEXTURE26 : 0x84DA;
TEXTURE26 : 0x84DA;
static TEXTURE27 : 0x84DB;
TEXTURE27 : 0x84DB;
static TEXTURE28 : 0x84DC;
TEXTURE28 : 0x84DC;
static TEXTURE29 : 0x84DD;
TEXTURE29 : 0x84DD;
static TEXTURE30 : 0x84DE;
TEXTURE30 : 0x84DE;
static TEXTURE31 : 0x84DF;
TEXTURE31 : 0x84DF;
static ACTIVE_TEXTURE : 0x84E0;
ACTIVE_TEXTURE : 0x84E0;
static REPEAT : 0x2901;
REPEAT : 0x2901;
static CLAMP_TO_EDGE : 0x812F;
CLAMP_TO_EDGE : 0x812F;
static MIRRORED_REPEAT : 0x8370;
MIRRORED_REPEAT : 0x8370;
static FLOAT_VEC2 : 0x8B50;
FLOAT_VEC2 : 0x8B50;
static FLOAT_VEC3 : 0x8B51;
FLOAT_VEC3 : 0x8B51;
static FLOAT_VEC4 : 0x8B52;
FLOAT_VEC4 : 0x8B52;
static INT_VEC2 : 0x8B53;
INT_VEC2 : 0x8B53;
static INT_VEC3 : 0x8B54;
INT_VEC3 : 0x8B54;
static INT_VEC4 : 0x8B55;
INT_VEC4 : 0x8B55;
static BOOL : 0x8B56;
BOOL : 0x8B56;
static BOOL_VEC2 : 0x8B57;
BOOL_VEC2 : 0x8B57;
static BOOL_VEC3 : 0x8B58;
BOOL_VEC3 : 0x8B58;
static BOOL_VEC4 : 0x8B59;
BOOL_VEC4 : 0x8B59;
static FLOAT_MAT2 : 0x8B5A;
FLOAT_MAT2 : 0x8B5A;
static FLOAT_MAT3 : 0x8B5B;
FLOAT_MAT3 : 0x8B5B;
static FLOAT_MAT4 : 0x8B5C;
FLOAT_MAT4 : 0x8B5C;
static SAMPLER_2D : 0x8B5E;
SAMPLER_2D : 0x8B5E;
static SAMPLER_CUBE : 0x8B60;
SAMPLER_CUBE : 0x8B60;
static VERTEX_ATTRIB_ARRAY_ENABLED : 0x8622;
VERTEX_ATTRIB_ARRAY_ENABLED : 0x8622;
static VERTEX_ATTRIB_ARRAY_SIZE : 0x8623;
VERTEX_ATTRIB_ARRAY_SIZE : 0x8623;
static VERTEX_ATTRIB_ARRAY_STRIDE : 0x8624;
VERTEX_ATTRIB_ARRAY_STRIDE : 0x8624;
static VERTEX_ATTRIB_ARRAY_TYPE : 0x8625;
VERTEX_ATTRIB_ARRAY_TYPE : 0x8625;
static VERTEX_ATTRIB_ARRAY_NORMALIZED : 0x886A;
VERTEX_ATTRIB_ARRAY_NORMALIZED : 0x886A;
static VERTEX_ATTRIB_ARRAY_POINTER : 0x8645;
VERTEX_ATTRIB_ARRAY_POINTER : 0x8645;
static VERTEX_ATTRIB_ARRAY_BUFFER_BINDING : 0x889F;
VERTEX_ATTRIB_ARRAY_BUFFER_BINDING : 0x889F;
static IMPLEMENTATION_COLOR_READ_TYPE : 0x8B9A;
IMPLEMENTATION_COLOR_READ_TYPE : 0x8B9A;
static IMPLEMENTATION_COLOR_READ_FORMAT : 0x8B9B;
IMPLEMENTATION_COLOR_READ_FORMAT : 0x8B9B;
static COMPILE_STATUS : 0x8B81;
COMPILE_STATUS : 0x8B81;
static LOW_FLOAT : 0x8DF0;
LOW_FLOAT : 0x8DF0;
static MEDIUM_FLOAT : 0x8DF1;
MEDIUM_FLOAT : 0x8DF1;
static HIGH_FLOAT : 0x8DF2;
HIGH_FLOAT : 0x8DF2;
static LOW_INT : 0x8DF3;
LOW_INT : 0x8DF3;
static MEDIUM_INT : 0x8DF4;
MEDIUM_INT : 0x8DF4;
static HIGH_INT : 0x8DF5;
HIGH_INT : 0x8DF5;
static FRAMEBUFFER : 0x8D40;
FRAMEBUFFER : 0x8D40;
static RENDERBUFFER : 0x8D41;
RENDERBUFFER : 0x8D41;
static RGBA4 : 0x8056;
RGBA4 : 0x8056;
static RGB5_A1 : 0x8057;
RGB5_A1 : 0x8057;
static RGB565 : 0x8D62;
RGB565 : 0x8D62;
static DEPTH_COMPONENT16 : 0x81A5;
DEPTH_COMPONENT16 : 0x81A5;
static STENCIL_INDEX : 0x1901;
STENCIL_INDEX : 0x1901;
static STENCIL_INDEX8 : 0x8D48;
STENCIL_INDEX8 : 0x8D48;
static DEPTH_STENCIL : 0x84F9;
DEPTH_STENCIL : 0x84F9;
static RENDERBUFFER_WIDTH : 0x8D42;
RENDERBUFFER_WIDTH : 0x8D42;
static RENDERBUFFER_HEIGHT : 0x8D43;
RENDERBUFFER_HEIGHT : 0x8D43;
static RENDERBUFFER_INTERNAL_FORMAT : 0x8D44;
RENDERBUFFER_INTERNAL_FORMAT : 0x8D44;
static RENDERBUFFER_RED_SIZE : 0x8D50;
RENDERBUFFER_RED_SIZE : 0x8D50;
static RENDERBUFFER_GREEN_SIZE : 0x8D51;
RENDERBUFFER_GREEN_SIZE : 0x8D51;
static RENDERBUFFER_BLUE_SIZE : 0x8D52;
RENDERBUFFER_BLUE_SIZE : 0x8D52;
static RENDERBUFFER_ALPHA_SIZE : 0x8D53;
RENDERBUFFER_ALPHA_SIZE : 0x8D53;
static RENDERBUFFER_DEPTH_SIZE : 0x8D54;
RENDERBUFFER_DEPTH_SIZE : 0x8D54;
static RENDERBUFFER_STENCIL_SIZE : 0x8D55;
RENDERBUFFER_STENCIL_SIZE : 0x8D55;
static FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE : 0x8CD0;
FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE : 0x8CD0;
static FRAMEBUFFER_ATTACHMENT_OBJECT_NAME : 0x8CD1;
FRAMEBUFFER_ATTACHMENT_OBJECT_NAME : 0x8CD1;
static FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL : 0x8CD2;
FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL : 0x8CD2;
static FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE : 0x8CD3;
FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE : 0x8CD3;
static COLOR_ATTACHMENT0 : 0x8CE0;
COLOR_ATTACHMENT0 : 0x8CE0;
static DEPTH_ATTACHMENT : 0x8D00;
DEPTH_ATTACHMENT : 0x8D00;
static STENCIL_ATTACHMENT : 0x8D20;
STENCIL_ATTACHMENT : 0x8D20;
static DEPTH_STENCIL_ATTACHMENT : 0x821A;
DEPTH_STENCIL_ATTACHMENT : 0x821A;
static NONE : 0;
NONE : 0;
static FRAMEBUFFER_COMPLETE : 0x8CD5;
FRAMEBUFFER_COMPLETE : 0x8CD5;
static FRAMEBUFFER_INCOMPLETE_ATTACHMENT : 0x8CD6;
FRAMEBUFFER_INCOMPLETE_ATTACHMENT : 0x8CD6;
static FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT : 0x8CD7;
FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT : 0x8CD7;
static FRAMEBUFFER_INCOMPLETE_DIMENSIONS : 0x8CD9;
FRAMEBUFFER_INCOMPLETE_DIMENSIONS : 0x8CD9;
static FRAMEBUFFER_UNSUPPORTED : 0x8CDD;
FRAMEBUFFER_UNSUPPORTED : 0x8CDD;
static FRAMEBUFFER_BINDING : 0x8CA6;
FRAMEBUFFER_BINDING : 0x8CA6;
static RENDERBUFFER_BINDING : 0x8CA7;
RENDERBUFFER_BINDING : 0x8CA7;
static MAX_RENDERBUFFER_SIZE : 0x84E8;
MAX_RENDERBUFFER_SIZE : 0x84E8;
static INVALID_FRAMEBUFFER_OPERATION : 0x0506;
INVALID_FRAMEBUFFER_OPERATION : 0x0506;
static UNPACK_FLIP_Y_WEBGL : 0x9240;
UNPACK_FLIP_Y_WEBGL : 0x9240;
static UNPACK_PREMULTIPLY_ALPHA_WEBGL : 0x9241;
UNPACK_PREMULTIPLY_ALPHA_WEBGL : 0x9241;
static CONTEXT_LOST_WEBGL : 0x9242;
CONTEXT_LOST_WEBGL : 0x9242;
static UNPACK_COLORSPACE_CONVERSION_WEBGL : 0x9243;
UNPACK_COLORSPACE_CONVERSION_WEBGL : 0x9243;
static BROWSER_DEFAULT_WEBGL : 0x9244;
BROWSER_DEFAULT_WEBGL : 0x9244;
canvas: HTMLCanvasElement;
drawingBufferWidth: number;
drawingBufferHeight: number;
getContextAttributes(): ?WebGLContextAttributes;
isContextLost(): bool;
getSupportedExtensions(): ?Array<string>;
getExtension(name: string): any;
activeTexture(texture: number): void;
attachShader(program: WebGLProgram, shader: WebGLShader): void;
bindAttribLocation(program: WebGLProgram, index: number, name: string): void;
bindBuffer(target: number, buffer: ?WebGLBuffer): void;
bindFramebuffer(target: number, framebuffer: ?WebGLFramebuffer): void;
bindRenderbuffer(target: number, renderbuffer: ?WebGLRenderbuffer): void;
bindTexture(target: number, texture: ?WebGLTexture): void;
blendColor(red: number, green: number, blue: number, alpha: number): void;
blendEquation(mode: number): void;
blendEquationSeparate(modeRGB: number, modeAlpha: number): void;
blendFunc(sfactor: number, dfactor: number): void;
blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void;
bufferData(target: number, size: number, usage: number): void;
bufferData(target: number, data: ?ArrayBuffer, usage: number): void;
bufferData(target: number, data: $ArrayBufferView, usage: number): void;
bufferSubData(target: number, offset: number, data: BufferDataSource): void;
checkFramebufferStatus(target: number): number;
clear(mask: number): void;
clearColor(red: number, green: number, blue: number, alpha: number): void;
clearDepth(depth: number): void;
clearStencil(s: number): void;
colorMask(red: bool, green: bool, blue: bool, alpha: bool): void;
compileShader(shader: WebGLShader): void;
compressedTexImage2D(target: number, level: number, internalformat: number,
width: number, height: number, border: number,
data: $ArrayBufferView): void;
compressedTexSubImage2D(target: number, level: number,
xoffset: number, yoffset: number,
width: number, height: number, format: number,
data: $ArrayBufferView): void;
copyTexImage2D(target: number, level: number, internalformat: number,
x: number, y: number, width: number, height: number,
border: number): void;
copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number,
x: number, y: number, width: number, height: number): void;
createBuffer(): ?WebGLBuffer;
createFramebuffer(): ?WebGLFramebuffer;
createProgram(): ?WebGLProgram;
createRenderbuffer(): ?WebGLRenderbuffer;
createShader(type: number): ?WebGLShader;
createTexture(): ?WebGLTexture;
cullFace(mode: number): void;
deleteBuffer(buffer: ?WebGLBuffer): void;
deleteFramebuffer(framebuffer: ?WebGLFramebuffer): void;
deleteProgram(program: ?WebGLProgram): void;
deleteRenderbuffer(renderbuffer: ?WebGLRenderbuffer): void;
deleteShader(shader: ?WebGLShader): void;
deleteTexture(texture: ?WebGLTexture): void;
depthFunc(func: number): void;
depthMask(flag: bool): void;
depthRange(zNear: number, zFar: number): void;
detachShader(program: WebGLProgram, shader: WebGLShader): void;
disable(cap: number): void;
disableVertexAttribArray(index: number): void;
drawArrays(mode: number, first: number, count: number): void;
drawElements(mode: number, count: number, type: number, offset: number): void;
enable(cap: number): void;
enableVertexAttribArray(index: number): void;
finish(): void;
flush(): void;
framebufferRenderbuffer(target: number, attachment: number,
renderbuffertarget: number,
renderbuffer: ?WebGLRenderbuffer): void;
framebufferTexture2D(target: number, attachment: number, textarget: number,
texture: ?WebGLTexture, level: number): void;
frontFace(mode: number): void;
generateMipmap(target: number): void;
getActiveAttrib(program: WebGLProgram, index: number): ?WebGLActiveInfo;
getActiveUniform(program: WebGLProgram, index: number): ?WebGLActiveInfo;
getAttachedShaders(program: WebGLProgram): ?Array<WebGLShader>;
getAttribLocation(program: WebGLProgram, name: string): number;
getBufferParameter(target: number, pname: number): any;
getParameter(pname: number): any;
getError(): number;
getFramebufferAttachmentParameter(target: number, attachment: number,
pname: number): any;
getProgramParameter(program: WebGLProgram, pname: number): any;
getProgramInfoLog(program: WebGLProgram): ?string;
getRenderbufferParameter(target: number, pname: number): any;
getShaderParameter(shader: WebGLShader, pname: number): any;
getShaderPrecisionFormat(shadertype: number, precisiontype: number): ?WebGLShaderPrecisionFormat;
getShaderInfoLog(shader: WebGLShader): ?string;
getShaderSource(shader: WebGLShader): ?string;
getTexParameter(target: number, pname: number): any;
getUniform(program: WebGLProgram, location: WebGLUniformLocation): any;
getUniformLocation(program: WebGLProgram, name: string): ?WebGLUniformLocation;
getVertexAttrib(index: number, pname: number): any;
getVertexAttribOffset(index: number, pname: number): number;
hint(target: number, mode: number): void;
isBuffer(buffer: ?WebGLBuffer): void;
isEnabled(cap: number): void;
isFramebuffer(framebuffer: ?WebGLFramebuffer): void;
isProgram(program: ?WebGLProgram): void;
isRenderbuffer(renderbuffer: ?WebGLRenderbuffer): void;
isShader(shader: ?WebGLShader): void;
isTexture(texture: ?WebGLTexture): void;
lineWidth(width: number): void;
linkProgram(program: WebGLProgram): void;
pixelStorei(pname: number, param: number): void;
polygonOffset(factor: number, units: number): void;
readPixels(x: number, y: number, width: number, height: number,
format: number, type: number, pixels: ?$ArrayBufferView): void;
renderbufferStorage(target: number, internalformat: number,
width: number, height: number): void;
sampleCoverage(value: number, invert: bool): void;
scissor(x: number, y: number, width: number, height: number): void;
shaderSource(shader: WebGLShader, source: string): void;
stencilFunc(func: number, ref: number, mask: number): void;
stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void;
stencilMask(mask: number): void;
stencilMaskSeparate(face: number, mask: number): void;
stencilOp(fail: number, zfail: number, zpass: number): void;
stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void;
texImage2D(target: number, level: number, internalformat: number,
width: number, height: number, border: number, format: number,
type: number, pixels: ?$ArrayBufferView): void;
texImage2D(target: number, level: number, internalformat: number,
format: number, type: number, source: TexImageSource): void;
texParameterf(target: number, pname: number, param: number): void;
texParameteri(target: number, pname: number, param: number): void;
texSubImage2D(target: number, level: number, xoffset: number, yoffset: number,
width: number, height: number,
format: number, type: number, pixels: ?$ArrayBufferView): void;
texSubImage2D(target: number, level: number, xoffset: number, yoffset: number,
format: number, type: number, source: TexImageSource): void;
uniform1f(location: ?WebGLUniformLocation, x: number): void;
uniform1fv(location: ?WebGLUniformLocation, v: Float32Array): void;
uniform1fv(location: ?WebGLUniformLocation, v: Array<number>): void;
uniform1i(location: ?WebGLUniformLocation, x: number): void;
uniform1iv(location: ?WebGLUniformLocation, v: Int32Array): void;
uniform1iv(location: ?WebGLUniformLocation, v: Array<number>): void;
uniform2f(location: ?WebGLUniformLocation, x: number, y: number): void;
uniform2fv(location: ?WebGLUniformLocation, v: Float32Array): void;
uniform2fv(location: ?WebGLUniformLocation, v: Array<number>): void;
uniform2i(location: ?WebGLUniformLocation, x: number, y: number): void;
uniform2iv(location: ?WebGLUniformLocation, v: Int32Array): void;
uniform2iv(location: ?WebGLUniformLocation, v: Array<number>): void;
uniform3f(location: ?WebGLUniformLocation, x: number, y: number, z: number): void;
uniform3fv(location: ?WebGLUniformLocation, v: Float32Array): void;
uniform3fv(location: ?WebGLUniformLocation, v: Array<number>): void;
uniform3i(location: ?WebGLUniformLocation, x: number, y: number, z: number): void;
uniform3iv(location: ?WebGLUniformLocation, v: Int32Array): void;
uniform3iv(location: ?WebGLUniformLocation, v: Array<number>): void;
uniform4f(location: ?WebGLUniformLocation, x: number, y: number, z: number, w: number): void;
uniform4fv(location: ?WebGLUniformLocation, v: Float32Array): void;
uniform4fv(location: ?WebGLUniformLocation, v: Array<number>): void;
uniform4i(location: ?WebGLUniformLocation, x: number, y: number, z: number, w: number): void;
uniform4iv(location: ?WebGLUniformLocation, v: Int32Array): void;
uniform4iv(location: ?WebGLUniformLocation, v: Array<number>): void;
uniformMatrix2fv(location: ?WebGLUniformLocation, transpose: bool,
value: Float32Array): void;
uniformMatrix2fv(location: ?WebGLUniformLocation, transpose: bool,
value: Array<number>): void;
uniformMatrix3fv(location: ?WebGLUniformLocation, transpose: bool,
value: Float32Array): void;
uniformMatrix3fv(location: ?WebGLUniformLocation, transpose: bool,
value: Array<number>): void;
uniformMatrix4fv(location: ?WebGLUniformLocation, transpose: bool,
value: Float32Array): void;
uniformMatrix4fv(location: ?WebGLUniformLocation, transpose: bool,
value: Array<number>): void;
useProgram(program: ?WebGLProgram): void;
validateProgram(program: WebGLProgram): void;
vertexAttrib1f(index: number, x: number): void;
vertexAttrib1fv(index: number, values: VertexAttribFVSource): void;
vertexAttrib2f(index: number, x: number, y: number): void;
vertexAttrib2fv(index: number, values: VertexAttribFVSource): void;
vertexAttrib3f(index: number, x: number, y: number, z: number): void;
vertexAttrib3fv(index: number, values: VertexAttribFVSource): void;
vertexAttrib4f(index: number, x: number, y: number, z: number, w: number): void;
vertexAttrib4fv(index: number, values: VertexAttribFVSource): void;
vertexAttribPointer(index: number, size: number, type: number,
normalized: bool, stride: number, offset: number): void;
viewport(x: number, y: number, width: number, height: number): void;
};
declare class WebGLContextEvent extends Event {
statusMessage: string;
};
// http://www.w3.org/TR/html5/scripting-1.html#renderingcontext
type RenderingContext = CanvasRenderingContext2D | WebGLRenderingContext;
// http://www.w3.org/TR/html5/scripting-1.html#htmlcanvaselement
declare class HTMLCanvasElement extends HTMLElement {
width: number;
height: number;
getContext(contextId: "2d", ...args: any): CanvasRenderingContext2D;
getContext(contextId: "webgl", contextAttributes?: $Shape<WebGLContextAttributes>): ?WebGLRenderingContext;
// IE currently only supports "experimental-webgl"
getContext(contextId: "experimental-webgl", contextAttributes?: $Shape<WebGLContextAttributes>): ?WebGLRenderingContext;
getContext(contextId: string, ...args: any): ?RenderingContext; // fallback
toDataURL(type?: string, ...args: any): string;
toBlob(callback: (v: File) => void, type?: string, ...args: any): void;
captureStream(frameRate?: number): CanvasCaptureMediaStream;
}
// https://html.spec.whatwg.org/multipage/forms.html#the-details-element
declare class HTMLDetailsElement extends HTMLElement {
open: boolean;
}
declare class HTMLFormElement extends HTMLElement {
@@iterator(): Iterator<HTMLElement>;
[index: number | string]: HTMLElement | null;
acceptCharset: string;
action: string;
elements: HTMLCollection<HTMLElement>;
encoding: string;
enctype: string;
length: number;
method: string;
name: string;
target: string;
checkValidity(): boolean;
reportValidity(): boolean;
reset(): void;
submit(): void;
}
// https://www.w3.org/TR/html5/forms.html#the-fieldset-element
declare class HTMLFieldSetElement extends HTMLElement {
disabled: boolean;
elements: HTMLCollection<HTMLElement>; // readonly
form: HTMLFormElement | null; // readonly
name: string;
type: string; // readonly
checkValidity(): boolean;
setCustomValidity(error: string): void;
}
declare class HTMLLegendElement extends HTMLElement {
form: HTMLFormElement | null; // readonly
}
declare class HTMLIFrameElement extends HTMLElement {
allowFullScreen: boolean;
contentDocument: Document;
contentWindow: any;
frameBorder: string;
height: string;
marginHeight: string;
marginWidth: string;
name: string;
scrolling: string;
sandbox: DOMTokenList;
src: string;
srcDoc: string;
width: string;
}
declare class HTMLImageElement extends HTMLElement {
alt: string;
complete: boolean; // readonly
crossOrigin: ?string;
currentSrc: string; // readonly
height: number;
isMap: boolean;
naturalHeight: number; // readonly
naturalWidth: number; // readonly
sizes: string;
src: string;
srcset: string;
useMap: string;
width: number;
}
declare class Image extends HTMLImageElement {
constructor(width?: number, height?: number): void;
}
declare class MediaError {
MEDIA_ERR_ABORTED: number;
MEDIA_ERR_NETWORK: number;
MEDIA_ERR_DECODE: number;
MEDIA_ERR_SRC_NOT_SUPPORTED: number;
code: number;
message: ?string;
}
declare class TimeRanges {
length: number;
start(index: number): number;
end(index: number): number;
}
declare class AudioTrack {
id: string;
kind: string;
label: string;
language: string;
enabled: boolean;
}
declare class AudioTrackList extends EventTarget {
length: number;
[index: number]: AudioTrack;
getTrackById(id: string): ?AudioTrack;
onchange: (ev: any) => any;
onaddtrack: (ev: any) => any;
onremovetrack: (ev: any) => any;
}
declare class VideoTrack {
id: string;
kind: string;
label: string;
language: string;
selected: boolean;
}
declare class VideoTrackList extends EventTarget {
length: number;
[index: number]: VideoTrack;
getTrackById(id: string): ?VideoTrack;
selectedIndex: number;
onchange: (ev: any) => any;
onaddtrack: (ev: any) => any;
onremovetrack: (ev: any) => any;
}
declare class TextTrackCue extends EventTarget {
constructor(startTime: number, endTime: number, text: string): void;
track: TextTrack;
id: string;
startTime: number;
endTime: number;
pauseOnExit: boolean;
vertical: string;
snapToLines: boolean;
lines: number;
position: number;
size: number;
align: string;
text: string;
getCueAsHTML(): Node;
onenter: (ev: any) => any;
onexit: (ev: any) => any;
}
declare class TextTrackCueList {
@@iterator(): Iterator<TextTrackCue>;
length: number;
[index: number]: TextTrackCue;
getCueById(id: string): ?TextTrackCue;
}
declare class TextTrack extends EventTarget {
kind: string;
label: string;
language: string;
mode: string;
cues: TextTrackCueList;
activeCues: TextTrackCueList;
addCue(cue: TextTrackCue): void;
removeCue(cue: TextTrackCue): void;
oncuechange: (ev: any) => any;
}
declare class TextTrackList extends EventTarget {
length: number;
[index: number]: TextTrack;
onaddtrack: (ev: any) => any;
onremovetrack: (ev: any) => any;
}
declare class HTMLMediaElement extends HTMLElement {
// error state
error: ?MediaError;
// network state
src: string;
srcObject: ?any;
currentSrc: string;
crossOrigin: ?string;
NETWORK_EMPTY: number;
NETWORK_IDLE: number;
NETWORK_LOADING: number;
NETWORK_NO_SOURCE: number;
networkState: number;
preload: string;
buffered: TimeRanges;
load(): void;
canPlayType(type: string): string;
// ready state
HAVE_NOTHING: number;
HAVE_METADATA: number;
HAVE_CURRENT_DATA: number;
HAVE_FUTURE_DATA: number;
HAVE_ENOUGH_DATA: number;
readyState: number;
seeking: boolean;
// playback state
currentTime: number;
duration: number;
startDate: Date;
paused: boolean;
defaultPlaybackRate: number;
playbackRate: number;
played: TimeRanges;
seekable: TimeRanges;
ended: boolean;
autoplay: boolean;
loop: boolean;
play(): Promise<void>;
pause(): void;
fastSeek(): void;
captureStream(): MediaStream;
// media controller
mediaGroup: string;
controller: ?any;
// controls
controls: boolean;
volume: number;
muted: boolean;
defaultMuted: boolean;
// tracks
audioTracks: AudioTrackList;
videoTracks: VideoTrackList;
textTracks: TextTrackList;
addTextTrack(kind: string, label?: string, language?: string): TextTrack;
}
declare class HTMLAudioElement extends HTMLMediaElement {
}
declare class HTMLVideoElement extends HTMLMediaElement {
width: number;
height: number;
videoWidth: number;
videoHeight: number;
poster: string;
}
declare class HTMLSourceElement extends HTMLElement {
src: string;
type: string;
//when used with the picture element
srcset: string;
sizes: string;
media: string;
}
declare class ValidityState {
badInput: boolean;
customError: boolean;
patternMismatch: boolean;
rangeOverflow: boolean;
rangeUnderflow: boolean;
stepMismatch: boolean;
tooLong: boolean;
typeMismatch: boolean;
valueMissing: boolean;
valid: boolean;
}
// http://www.w3.org/TR/html5/forms.html#dom-textarea/input-setselectionrange
type SelectionDirection = 'backward' | 'forward' | 'none';
type SelectionMode = 'select' | 'start' | 'end' | 'preserve';
declare class HTMLInputElement extends HTMLElement {
accept: string;
align: string;
alt: string;
autocomplete: string;
autofocus: boolean;
border: string;
checked: boolean;
complete: boolean;
defaultChecked: boolean;
defaultValue: string;
dirname: string;
disabled: boolean;
dynsrc: string;
files: FileList;
form: HTMLFormElement | null;
formAction: string;
formEncType: string;
formMethod: string;
formNoValidate: boolean;
formTarget: string;
height: string;
hspace: number;
indeterminate: boolean;
labels: NodeList<HTMLLabelElement>;
list: HTMLElement | null;
loop: number;
lowsrc: string;
max: string;
maxLength: number;
min: string;
multiple: boolean;
name: string;
pattern: string;
placeholder: string;
readOnly: boolean;
required: boolean;
selectionDirection: SelectionDirection;
selectionEnd: number;
selectionStart: number;
size: number;
src: string;
start: string;
status: boolean;
step: string;
tabIndex: number;
type: string;
useMap: string;
validationMessage: string;
validity: ValidityState;
value: string;
valueAsDate: Date;
valueAsNumber: number;
vrml: string;
vspace: number;
width: string;
willValidate: boolean;
blur(): void;
checkValidity(): boolean;
setCustomValidity(error: string): void;
click(): void;
createTextRange(): TextRange;
focus(): void;
select(): void;
setRangeText(replacement: string, start?: void, end?: void, selectMode?: void): void;
setRangeText(replacement: string, start: number, end: number, selectMode?: SelectionMode): void;
setSelectionRange(start: number, end: number, direction?: SelectionDirection): void;
}
declare class HTMLButtonElement extends HTMLElement {
disabled: boolean;
form: HTMLFormElement | null;
name: string;
type: string;
value: string;
checkValidity(): boolean;
}
// http://dev.w3.org/html5/spec-preview/the-textarea-element.html
declare class HTMLTextAreaElement extends HTMLElement {
autofocus: boolean;
cols: number;
dirName: string;
disabled: boolean;
form: HTMLFormElement | null;
maxLength: number;
name: string;
placeholder: string;
readOnly: boolean;
required: boolean;
rows: number;
wrap: string;
type: string;
defaultValue: string;
value: string;
textLength: number;
willValidate: boolean;
validity: ValidityState;
validationMessage: string;
checkValidity(): boolean;
setCustomValidity(error: string): void;
labels: NodeList<HTMLLabelElement>;
select(): void;
selectionStart: number;
selectionEnd: number;
selectionDirection: SelectionDirection;
setSelectionRange(start: number, end: number, direction?: SelectionDirection): void;
}
declare class HTMLSelectElement extends HTMLElement {
autocomplete: string;
autofocus: boolean;
disabled: boolean;
form: HTMLFormElement | null;
labels: NodeList<HTMLLabelElement>;
length: number;
multiple: boolean;
name: string;
options: HTMLOptionsCollection;
selectedOptions: HTMLCollection<HTMLOptionElement>;
required: boolean;
selectedIndex: number;
size: number;
type: string;
value: string;
add(element: HTMLElement, before?: HTMLElement): void;
checkValidity(): boolean;
item(index: number): HTMLOptionElement | null;
namedItem(name: string): HTMLOptionElement | null;
remove(index?: number): void;
setCustomValidity(error: string): void;
}
declare class HTMLOptionsCollection extends HTMLCollection<HTMLOptionElement> {
selectedIndex: number;
add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void;
remove(index: number): void;
}
declare class HTMLOptionElement extends HTMLElement {
defaultSelected: boolean;
disabled: boolean;
form: HTMLFormElement | null;
index: number;
label: string;
selected: boolean;
text: string;
value: string;
}
declare class HTMLOptGroupElement extends HTMLElement {
disabled: boolean;
label: string;
}
declare class HTMLAnchorElement extends HTMLElement {
charset: string;
coords: string;
download: string;
hash: string;
host: string;
hostname: string;
href: string;
hreflang: string;
media: string;
name: string;
origin: string;
password: string;
pathname: string;
port: string;
protocol: string;
rel: string;
rev: string;
search: string;
shape: string;
target: string;
text: string;
type: string;
username: string;
}
// http://dev.w3.org/html5/spec-preview/the-label-element.html
declare class HTMLLabelElement extends HTMLElement {
form: HTMLFormElement | null;
htmlFor: string;
control: HTMLElement | null;
}
declare class HTMLLinkElement extends HTMLElement {
crossOrigin: ?('anonymous' | 'use-credentials');
href: string;
hreflang: string;
media: string;
rel: string;
sizes: DOMTokenList;
type: string;
}
declare class HTMLScriptElement extends HTMLElement {
async: boolean;
charset: string;
crossOrigin?: string;
defer: boolean;
src: string;
text: string;
type: string;
}
declare class HTMLStyleElement extends HTMLElement {
disabled: boolean;
media: string;
scoped: boolean;
sheet: ?StyleSheet;
type: string;
}
declare class HTMLParagraphElement extends HTMLElement {
align: 'left' | 'center' | 'right' | 'justify'; // deprecated in HTML 4.01
}
declare class HTMLDivElement extends HTMLElement {}
declare class HTMLSpanElement extends HTMLElement {}
declare class HTMLAppletElement extends HTMLElement {}
declare class HTMLEmbedElement extends HTMLElement {}
declare class HTMLHeadingElement extends HTMLElement {}
declare class HTMLHRElement extends HTMLElement {}
declare class HTMLBRElement extends HTMLElement {}
declare class HTMLDListElement extends HTMLElement {}
declare class HTMLOListElement extends HTMLElement {
reversed: boolean;
start: number;
type: string;
}
declare class HTMLUListElement extends HTMLElement {}
declare class HTMLLIElement extends HTMLElement {
value: number;
}
declare class HTMLPreElement extends HTMLElement {}
declare class HTMLMetaElement extends HTMLElement {
content: string;
httpEquiv: string;
name: string;
}
declare class TextRange {
boundingLeft: number;
htmlText: string;
offsetLeft: number;
boundingWidth: number;
boundingHeight: number;
boundingTop: number;
text: string;
offsetTop: number;
moveToPoint(x: number, y: number): void;
queryCommandValue(cmdID: string): any;
getBookmark(): string;
move(unit: string, count?: number): number;
queryCommandIndeterm(cmdID: string): boolean;
scrollIntoView(fStart?: boolean): void;
findText(string: string, count?: number, flags?: number): boolean;
execCommand(cmdID: string, showUI?: boolean, value?: any): boolean;
getBoundingClientRect(): ClientRect;
moveToBookmark(bookmark: string): boolean;
isEqual(range: TextRange): boolean;
duplicate(): TextRange;
collapse(start?: boolean): void;
queryCommandText(cmdID: string): string;
select(): void;
pasteHTML(html: string): void;
inRange(range: TextRange): boolean;
moveEnd(unit: string, count?: number): number;
getClientRects(): ClientRectList;
moveStart(unit: string, count?: number): number;
parentElement(): Element;
queryCommandState(cmdID: string): boolean;
compareEndPoints(how: string, sourceRange: TextRange): number;
execCommandShowHelp(cmdID: string): boolean;
moveToElementText(element: Element): void;
expand(Unit: string): boolean;
queryCommandSupported(cmdID: string): boolean;
setEndPoint(how: string, SourceRange: TextRange): void;
queryCommandEnabled(cmdID: string): boolean;
}
declare class ClientRect { // extension
left: number;
width: number;
right: number;
top: number;
bottom: number;
height: number;
}
declare class ClientRectList { // extension
@@iterator(): Iterator<ClientRect>;
length: number;
item(index: number): ClientRect;
[index: number]: ClientRect;
}
// TODO: HTML*Element
declare class DOMImplementation {
createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType;
createDocument(namespaceURI: string | null, qualifiedName: string, doctype?: DocumentType | null): Document;
hasFeature(feature: string, version?: string): boolean;
// non-standard
createHTMLDocument(title?: string): Document;
}
declare class DocumentType extends Node {
name: string;
notations: NamedNodeMap;
systemId: string;
internalSubset: string;
entities: NamedNodeMap;
publicId: string;
// from ChildNode interface
after(...nodes: Array<string | Node>): void;
before(...nodes: Array<string | Node>): void;
replaceWith(...nodes: Array<string | Node>): void;
remove(): void;
}
declare class CharacterData extends Node {
length: number;
data: string;
deleteData(offset: number, count: number): void;
replaceData(offset: number, count: number, arg: string): void;
appendData(arg: string): void;
insertData(offset: number, arg: string): void;
substringData(offset: number, count: number): string;
// from ChildNode interface
after(...nodes: Array<string | Node>): void;
before(...nodes: Array<string | Node>): void;
replaceWith(...nodes: Array<string | Node>): void;
remove(): void;
}
declare class Text extends CharacterData {
assignedSlot?: HTMLSlotElement;
wholeText: string;
splitText(offset: number): Text;
replaceWholeText(content: string): Text;
}
declare class Comment extends CharacterData {
text: string;
}
declare class URL {
static createObjectURL(blob: Blob): string;
static createObjectURL(mediaSource: MediaSource): string;
static createFor(blob: Blob): string;
static revokeObjectURL(url: string): void;
constructor(url: string, base?: string | URL): void;
hash: string;
host: string;
hostname: string;
href: string;
origin: string; // readonly
password: string;
pathname: string;
port: string;
protocol: string;
search: string;
searchParams: URLSearchParams; // readonly
username: string;
}
declare class MediaSource extends EventTarget {
sourceBuffers: SourceBufferList;
activeSourceBuffers: SourceBufferList;
readyState: "closed" | "opened" | "ended";
duration: number;
addSourceBuffer(type: string): SourceBuffer;
removeSourceBuffer(sourceBuffer: SourceBuffer): void;
endOfStream(error?: string): void;
static isTypeSupported(type: string): bool;
}
declare class SourceBuffer extends EventTarget {
mode: "segments" | "sequence";
updating: bool;
buffered: TimeRanges;
timestampOffset: number;
audioTracks: AudioTrackList;
videoTracks: VideoTrackList;
textTracks: TextTrackList;
appendWindowStart: number;
appendWindowEnd: number;
appendBuffer(data: ArrayBuffer | $ArrayBufferView): void;
// TODO: Add ReadableStream
// appendStream(stream: ReadableStream, maxSize?: number): void;
abort(): void;
remove(start: number, end: number): void;
trackDefaults: TrackDefaultList;
}
declare class SourceBufferList extends EventTarget {
@@iterator(): Iterator<SourceBuffer>;
[index: number]: SourceBuffer;
length: number;
}
declare class Storage {
length: number;
getItem(key: string): ?string;
setItem(key: string, data: string): void;
clear(): void;
removeItem(key: string): void;
key(index: number): ?string;
[name: string]: ?string;
}
declare class TrackDefaultList {
[index: number]: TrackDefault;
length: number;
}
declare class TrackDefault {
type: "audio" | "video" | "text";
byteStreamTrackID: string;
language: string;
label: string;
kinds: Array<string>;
}
// TODO: The use of `typeof` makes this function signature effectively
// (node: Node) => number, but it should be (node: Node) => 1|2|3
type NodeFilterCallback = (node: Node) =>
typeof NodeFilter.FILTER_ACCEPT |
typeof NodeFilter.FILTER_REJECT |
typeof NodeFilter.FILTER_SKIP;
type NodeFilterInterface = NodeFilterCallback | { acceptNode: NodeFilterCallback }
// TODO: window.NodeFilter exists at runtime and behaves as a constructor
// as far as `instanceof` is concerned, but it is not callable.
declare class NodeFilter {
static SHOW_ALL: -1;
static SHOW_ELEMENT: 1;
static SHOW_ATTRIBUTE: 2; // deprecated
static SHOW_TEXT: 4;
static SHOW_CDATA_SECTION: 8; // deprecated
static SHOW_ENTITY_REFERENCE: 16; // deprecated
static SHOW_ENTITY: 32; // deprecated
static SHOW_PROCESSING_INSTRUCTION: 64;
static SHOW_COMMENT: 128;
static SHOW_DOCUMENT: 256;
static SHOW_DOCUMENT_TYPE: 512;
static SHOW_DOCUMENT_FRAGMENT: 1024;
static SHOW_NOTATION: 2048; // deprecated
static FILTER_ACCEPT: 1;
static FILTER_REJECT: 2;
static FILTER_SKIP: 3;
acceptNode: NodeFilterCallback;
}
// TODO: window.NodeIterator exists at runtime and behaves as a constructor
// as far as `instanceof` is concerned, but it is not callable.
declare class NodeIterator<RootNodeT, WhatToShowT> {
root: RootNodeT;
whatToShow: number;
filter: NodeFilter;
expandEntityReferences: boolean;
referenceNode: RootNodeT | WhatToShowT;
pointerBeforeReferenceNode: boolean;
detach(): void;
previousNode(): WhatToShowT | null;
nextNode(): WhatToShowT | null;
}
// TODO: window.TreeWalker exists at runtime and behaves as a constructor
// as far as `instanceof` is concerned, but it is not callable.
declare class TreeWalker<RootNodeT, WhatToShowT> {
root: RootNodeT;
whatToShow: number;
filter: NodeFilter;
expandEntityReferences: boolean;
currentNode: RootNodeT | WhatToShowT;
parentNode(): WhatToShowT | null;
firstChild(): WhatToShowT | null;
lastChild(): WhatToShowT | null;
previousSibling(): WhatToShowT | null;
nextSibling(): WhatToShowT | null;
previousNode(): WhatToShowT | null;
nextNode(): WhatToShowT | null;
}
/* window */
declare type WindowProxy = any;
declare function alert(message?: any): void;
declare function prompt(message?: any, value?: any): string;
declare function close(): void;
declare function confirm(message?: string): boolean;
declare var event: Event;
declare function getComputedStyle(elt: Element, pseudoElt?: string): any;
declare function requestAnimationFrame(callback: (timestamp: number) => void): number;
declare function cancelAnimationFrame(requestId: number): void;
declare function requestIdleCallback(
cb: (deadline: {didTimeout: boolean, timeRemaining: () => number}) => void,
opts?: {timeout: number},
): number;
declare function cancelIdleCallback(id: number): void;
declare var localStorage: Storage;
declare function focus(): void;
declare function onfocus(ev: Event): any;
declare function onmessage(ev: MessageEvent): any;
declare function open(url?: string, target?: string, features?: string, replace?: boolean): any;
declare var parent: WindowProxy;
declare function print(): void;
declare var self: any;
declare var sessionStorage: Storage;
declare var status: string;
declare var top: WindowProxy;
declare function getSelection(): Selection | null;
declare var customElements: CustomElementRegistry;
| TiddoLangerak/flow | lib/dom.js | JavaScript | mit | 139,204 |
const isString = require("lodash/isString")
const compact = require("lodash/compact")
const hFlex = require("uiks/reaks/hFlex")
const vFlex = require("uiks/reaks/vFlex")
const label = require("uiks/reaks/label")
const innerMargin = require("uiks/reaks/innerMargin")
const style = require("uiks/reaks/style")
const align = require("uiks/reaks/align")
const border = require("uiks/reaks/border")
module.exports = args => {
const {
title,
content,
action,
colors = ctx => ({
backgroundColor: ctx.colors.primary,
color: ctx.colors.textOnPrimary,
}),
noBorder,
} = args
return style(
noBorder
? {}
: {
borderRadius: 2,
boxShadow:
"rgba(0, 0, 0, 0.2) 0px 1px 4px, rgba(0, 0, 0, 0.2) 0px 1px 2px",
},
vFlex(
compact([
[
"fixed",
style(
{
fontWeight: 500,
height: 32,
},
style(
colors,
border(
{ b: { color: "#999" } },
innerMargin(
{ h: 12, v: 2 },
hFlex([
isString(title)
? align({ v: "center" }, label(title))
: title,
["fixed", action && align({ h: "right" }, action)],
])
)
)
)
),
],
content,
])
)
)
}
| KAESapps/uiks | reaks-material/section.js | JavaScript | mit | 1,478 |
{ } ( ) [ ]
. ; , < > <=
>= == != === !==
+ - * % / ++ --
<< >> >>> & | ^
! ~ && || ? :
= += -= *= %= /= <<=
>>= >>>= &= |= ^=
| colinw7/CJavaScript | data/operators.js | JavaScript | mit | 127 |
const { expect } = require('chai');
const EnumKeyword = require('../src/Enum');
describe('Enum Keyword', () => {
it('builds with string', () => {
const keyword = new EnumKeyword('value');
expect(keyword.json()).to.deep.eq({ enum: ['value'] });
});
it('builds with integer', () => {
const keyword = new EnumKeyword(1);
expect(keyword.json()).to.deep.eq({ enum: [1] });
});
it('builds with object', () => {
const keyword = new EnumKeyword({ foo: 'bar' });
expect(keyword.json()).to.deep.eq({ enum: [{ foo: 'bar' }] });
});
it('builds with array', () => {
const keyword = new EnumKeyword([2, 'foo', { bar: 1 }]);
expect(keyword.json()).to.deep.eq({ enum: [2, 'foo', { bar: 1 }] });
});
it('build with context', () => {
const keyword = new EnumKeyword([2, 'foo', { bar: 1 }]);
expect(keyword.json({ test: 'foo' })).to.deep.eq({
enum: [2, 'foo', { bar: 1 }],
test: 'foo',
});
});
});
| RomAnoX/ajv-schema-builder | test/Enum.spec.js | JavaScript | mit | 960 |
'use strict';
module.exports = function(app, passport,auth,io) {
/* Default Index */
var indexDefaultController = require('../controllers/default/index');
app.get('/', indexDefaultController.render);
app.get('/robots.txt', indexDefaultController.bot);
app.get('/sitemap.xml', indexDefaultController.sitemap);
/* Login Index */
var loginController = require('../controllers/login/index');
app.get('/signin',loginController.render);
/* Admin Index */
var indexAdminController = require('../controllers/admin/index');
app.get('/admin',auth.requiresLogin ,indexAdminController.render);
app.post('/user/auth', loginController.auth(passport));
app.get('/signout', loginController.signout);
/* Admin Post Api */
var postController = require('../controllers/api/post');
app.post('/admin/api/post',auth.apiRequiresLogin, postController.create);
app.get('/admin/api/post',auth.apiRequiresLogin, postController.allForAdmin);
app.get('/admin/api/post/:postId',auth.apiRequiresLogin,auth.requireSameAuthor, postController.showForAdmin);
app.put('/admin/api/post/:postId',auth.apiRequiresLogin,auth.requireSameAuthor, postController.update);
app.del('/admin/api/post/:postId',auth.apiRequiresLogin,auth.requireSameAuthor, postController.destroy);
app.post('/admin/api/post/upload',auth.apiRequiresLogin, postController.upload(io));
app.get('/admin/api/post/comments/:postId',auth.apiRequiresLogin, postController.commentsByPostIdForAmin);
/* Public Post Api */
app.get('/api/post',postController.all);
app.get('/api/post/:postId',postController.show);
app.get('/api/post/comments/:postId',postController.commentsByPostId);
app.get('/api/post/:postId/next',postController.next);
app.get('/api/post/:postId/previous',postController.previous);
app.get('/api/post/tag/:tag',postController.fetchByTag);
/* Post Id Param */
app.param('postId', postController.post);
/* Admin Comment Api */
var commentController = require('../controllers/api/comment');
app.post('/admin/api/comment',auth.apiRequiresLogin, commentController.create);
app.put('/admin/api/comment/:commentId',auth.apiRequiresLogin, commentController.update);
/* Public Comment Api */
app.post('/api/comment', commentController.create);
app.get('/api/comment/:commentId', commentController.show);
/* Comment Id Param */
app.param('commentId', commentController.comment);
/* Admin User Api */
var userController = require('../controllers/api/user');
app.post('/admin/api/user',auth.apiRequiresLogin,auth.isAdmin ,userController.create);
app.get('/admin/api/user',auth.apiRequiresLogin,auth.isAdmin, userController.all);
app.get('/admin/api/user/:userId',auth.apiRequiresLogin,auth.isOwnerProfile, userController.show);
app.put('/admin/api/user/:userId',auth.apiRequiresLogin,auth.isOwnerProfile, userController.update);
app.del('/admin/api/user/:userId',auth.apiRequiresLogin,auth.isAdmin, userController.destroy);
app.get('/admin/api/user/email/:userEmail',auth.apiRequiresLogin,userController.showUserByEmail);
/* User Id Param */
app.param('userId', userController.user);
app.param('userEmail', userController.userByEmail);
/* Admin Media Api */
var mediaController = require('../controllers/api/media');
app.post('/admin/api/media',auth.apiRequiresLogin ,mediaController.create(io));
app.get('/admin/api/media',auth.apiRequiresLogin, mediaController.all);
app.get('/admin/api/media/:mediaId',auth.apiRequiresLogin, mediaController.show);
app.put('/admin/api/media/:mediaId',auth.apiRequiresLogin,auth.isOwnerProfile,mediaController.update);
app.del('/admin/api/media/:mediaId',auth.apiRequiresLogin,auth.isAdmin, mediaController.destroy);
app.post('/admin/api/media/:mediaId/crop',auth.apiRequiresLogin ,mediaController.crop);
app.post('/admin/api/media/:mediaId/resize',auth.apiRequiresLogin ,mediaController.resize);
/* Media Id Param */
app.param('mediaId', mediaController.media);
/* Admin Contact Api */
var contactController = require('../controllers/api/contact');
app.get('/admin/api/contact',auth.apiRequiresLogin,auth.isAdmin,contactController.all);
app.get('/admin/api/contact/:contactId',auth.apiRequiresLogin,auth.isAdmin, contactController.show);
/* Public Contact Api */
app.post('/api/contact',contactController.create);
/* Contact Id Param */
app.param('contactId', contactController.contact);
};
| whisher/nodBlog | server/config/routes.js | JavaScript | mit | 4,665 |
var union_c_o_n_t_r_o_l___type =
[
[ "_reserved0", "union_c_o_n_t_r_o_l___type.html#af8c314273a1e4970a5671bd7f8184f50", null ],
[ "_reserved1", "union_c_o_n_t_r_o_l___type.html#aa7a5662079a447f801034d108f80ce49", null ],
[ "b", "union_c_o_n_t_r_o_l___type.html#a48ed3cc0ca4a86a840bf41c09a157bfb", null ],
[ "b", "union_c_o_n_t_r_o_l___type.html#afc7a6501bf929f079e328d9449e28620", null ],
[ "b", "union_c_o_n_t_r_o_l___type.html#aa62abc89b024d8037a1b1ffe596b0d2b", null ],
[ "b", "union_c_o_n_t_r_o_l___type.html#a46e0f774633c38fef256d522b3a8b9ff", null ],
[ "b", "union_c_o_n_t_r_o_l___type.html#ad1def9740e0888591db4d9dfd286b1dc", null ],
[ "b", "union_c_o_n_t_r_o_l___type.html#af45a66b0eb190b99fde62bc6853209b2", null ],
[ "b", "union_c_o_n_t_r_o_l___type.html#ab883f95a669dec8350524b535b2ac942", null ],
[ "FPCA", "union_c_o_n_t_r_o_l___type.html#ac62cfff08e6f055e0101785bad7094cd", null ],
[ "nPRIV", "union_c_o_n_t_r_o_l___type.html#a35c1732cf153b7b5c4bd321cf1de9605", null ],
[ "SPSEL", "union_c_o_n_t_r_o_l___type.html#a8cc085fea1c50a8bd9adea63931ee8e2", null ],
[ "w", "union_c_o_n_t_r_o_l___type.html#a6b642cca3d96da660b1198c133ca2a1f", null ]
]; | team-diana/nucleo-dynamixel | docs/html/union_c_o_n_t_r_o_l___type.js | JavaScript | mit | 1,209 |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage, injectIntl, intlShape } from 'react-intl';
import Relay from 'react-relay/classic';
import RCTooltip from 'rc-tooltip';
import styled from 'styled-components';
import 'react-image-lightbox/style.css';
import Box from '@material-ui/core/Box';
import IconButton from '@material-ui/core/IconButton';
import MoreHoriz from '@material-ui/icons/MoreHoriz';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import Typography from '@material-ui/core/Typography';
import AddAnnotation from './AddAnnotation';
import { can } from '../Can';
import { withSetFlashMessage } from '../FlashMessage';
import ParsedText from '../ParsedText';
import TimeBefore from '../TimeBefore';
import SourcePicture from '../source/SourcePicture';
import ProfileLink from '../layout/ProfileLink';
import UserTooltip from '../user/UserTooltip';
import DeleteAnnotationMutation from '../../relay/mutations/DeleteAnnotationMutation';
import {
getErrorMessage,
parseStringUnixTimestamp,
} from '../../helpers';
import globalStrings from '../../globalStrings';
import { stringHelper } from '../../customHelpers';
import {
units,
black38,
black54,
black87,
caption,
breakWordStyles,
separationGray,
Row,
checkBlue,
} from '../../styles/js/shared';
const StyledAnnotationCardWrapper = styled.div`
width: 100%;
z-index: initial !important;
img {
cursor: pointer;
}
`;
const StyledAvatarColumn = styled.div`
margin-${props => (props.theme.dir === 'rtl' ? 'left' : 'right')}: ${units(3)};
`;
const StyledPrimaryColumn = styled.div`
flex: 1;
.annotation__card-content {
${breakWordStyles}
width: 100%;
& > span:first-child {
flex: 1;
}
}
`;
const StyledAnnotationWrapper = styled.section`
.annotation__card-text {
display: flex;
}
.annotation__timestamp {
color: ${black38};
display: inline;
flex: 1;
white-space: pre;
margin-${props => (props.theme.dir === 'rtl' ? 'left' : 'right')}: ${units(1)};
}
`;
const StyledAnnotationMetadata = styled(Row)`
color: ${black54};
flex-flow: wrap row;
font: ${caption};
.annotation__card-author {
color: ${black87};
padding-${props => (props.theme.dir === 'rtl' ? 'left' : 'right')}: ${units(1)};
}
`;
const StyledAnnotationActionsWrapper = styled.div`
margin-${props => (props.theme.dir === 'rtl' ? 'right' : 'left')}: auto;
`;
// TODO Fix a11y issues
/* eslint jsx-a11y/click-events-have-key-events: 0 */
class Comment extends Component {
constructor(props) {
super(props);
this.state = { editMode: false };
}
handleOpenMenu = (e) => {
e.stopPropagation();
this.setState({ anchorEl: e.currentTarget });
};
handleCloseMenu = () => {
this.setState({ anchorEl: null });
};
handleEdit = () => {
this.setState({ editMode: true });
this.handleCloseMenu();
};
handleCloseEdit = () => {
this.setState({ editMode: false });
};
handleDelete(id) {
const onSuccess = () => {};
Relay.Store.commitUpdate(
new DeleteAnnotationMutation({
parent_type: this.props.annotatedType.replace(/([a-z])([A-Z])/, '$1_$2').toLowerCase(),
annotated: this.props.annotated,
id,
}),
{ onSuccess, onFailure: this.fail },
);
}
fail = (transaction) => {
const message = getErrorMessage(
transaction,
(
<FormattedMessage
{...globalStrings.unknownError}
values={{ supportEmail: stringHelper('SUPPORT_EMAIL') }}
/>
),
);
this.props.setFlashMessage(message, 'error');
};
render() {
const { annotation, annotated } = this.props;
let annotationActions = null;
if (annotation && annotation.annotation_type) {
const canUpdate = can(annotation.permissions, 'update Comment');
const canDestroy = can(annotation.permissions, 'destroy Comment');
const canDoAnnotationActions = canDestroy || canUpdate;
annotationActions = canDoAnnotationActions ? (
<div>
<IconButton
className="menu-button"
onClick={this.handleOpenMenu}
>
<MoreHoriz />
</IconButton>
<Menu
id="customized-menu"
anchorEl={this.state.anchorEl}
keepMounted
open={Boolean(this.state.anchorEl)}
onClose={this.handleCloseMenu}
>
{canUpdate ? (
<MenuItem
className="annotation__update"
onClick={this.handleEdit}
>
<FormattedMessage id="annotation.editButton" defaultMessage="Edit" />
</MenuItem>
) : null}
{canDestroy ? (
<MenuItem
className="annotation__delete"
onClick={this.handleDelete.bind(this, annotation.id)}
>
<FormattedMessage id="annotation.deleteButton" defaultMessage="Delete" />
</MenuItem>
) : null}
<MenuItem>
<a
href={`#annotation-${annotation.dbid}`}
style={{ textDecoration: 'none', color: black87 }}
>
<FormattedMessage
id="annotation.permalink"
defaultMessage="Permalink"
/>
</a>
</MenuItem>
</Menu>
</div>)
: null;
}
const createdAt = parseStringUnixTimestamp(annotation.created_at);
const { user } = annotation.annotator;
const authorName = user
? <ProfileLink className="annotation__author-name" teamUser={user.team_user} /> : null;
const commentText = annotation.text;
const commentContent = JSON.parse(annotation.content);
const contentTemplate = (
<div>
<div className="annotation__card-content">
<div>
{ this.state.editMode ?
<AddAnnotation
cmdText={commentText}
editMode={this.state.editMode}
handleCloseEdit={this.handleCloseEdit}
annotated={annotated}
annotation={annotation}
annotatedType="ProjectMedia"
types={['comment']}
/>
: <ParsedText text={commentText} />
}
</div>
{/* comment file */}
{commentContent.file_path ?
<div>
<Box
component="a"
href={commentContent.file_path}
target="_blank"
rel="noreferrer noopener"
color={checkBlue}
className="annotation__card-file"
>
{commentContent.file_name}
</Box>
</div> : null }
</div>
</div>
);
return (
<StyledAnnotationWrapper
className="annotation annotation--card annotation--comment"
id={`annotation-${annotation.dbid}`}
>
<StyledAnnotationCardWrapper>
<Box
py={2}
borderBottom={`1px ${separationGray} solid`}
className="annotation__card-text annotation__card-activity-comment"
>
{ authorName ?
<RCTooltip placement="top" overlay={<UserTooltip teamUser={user.team_user} />}>
<StyledAvatarColumn className="annotation__avatar-col">
<SourcePicture
className="avatar"
type="user"
object={user.source}
/>
</StyledAvatarColumn>
</RCTooltip> : null }
<StyledPrimaryColumn>
<StyledAnnotationMetadata>
<span className="annotation__card-footer">
{ authorName ?
<ProfileLink
className="annotation__card-author"
teamUser={user.team_user}
/> : null }
<span>
<span className="annotation__timestamp"><TimeBefore date={createdAt} /></span>
</span>
</span>
<StyledAnnotationActionsWrapper>
{annotationActions}
</StyledAnnotationActionsWrapper>
</StyledAnnotationMetadata>
<Typography variant="body1" component="div">
{contentTemplate}
</Typography>
</StyledPrimaryColumn>
</Box>
</StyledAnnotationCardWrapper>
</StyledAnnotationWrapper>
);
}
}
Comment.propTypes = {
// https://github.com/yannickcr/eslint-plugin-react/issues/1389
// eslint-disable-next-line react/no-typos
setFlashMessage: PropTypes.func.isRequired,
intl: intlShape.isRequired,
};
export default withSetFlashMessage(injectIntl(Comment));
| meedan/check-web | src/app/components/annotations/Comment.js | JavaScript | mit | 8,969 |
version https://git-lfs.github.com/spec/v1
oid sha256:ad5e4e8e326ffa0523b9ad9579bd02bdcfd16d7d75fe1d14a0b8a04a3d3d5a23
size 108432
| yogeshsaroya/new-cdnjs | ajax/libs/svg.js/2.0.0-rc.1/svg.js | JavaScript | mit | 131 |
/**
* @author bhouston / http://exocortex.com
*/
QUnit.module( "Triangle" );
QUnit.test( "constructor" , function( assert ) {
var a = new THREE.Triangle();
assert.ok( a.a.equals( zero3 ), "Passed!" );
assert.ok( a.b.equals( zero3 ), "Passed!" );
assert.ok( a.c.equals( zero3 ), "Passed!" );
a = new THREE.Triangle( one3.clone().negate(), one3.clone(), two3.clone() );
assert.ok( a.a.equals( one3.clone().negate() ), "Passed!" );
assert.ok( a.b.equals( one3 ), "Passed!" );
assert.ok( a.c.equals( two3 ), "Passed!" );
});
QUnit.test( "copy" , function( assert ) {
var a = new THREE.Triangle( one3.clone().negate(), one3.clone(), two3.clone() );
var b = new THREE.Triangle().copy( a );
assert.ok( b.a.equals( one3.clone().negate() ), "Passed!" );
assert.ok( b.b.equals( one3 ), "Passed!" );
assert.ok( b.c.equals( two3 ), "Passed!" );
// ensure that it is a true copy
a.a = one3;
a.b = zero3;
a.c = zero3;
assert.ok( b.a.equals( one3.clone().negate() ), "Passed!" );
assert.ok( b.b.equals( one3 ), "Passed!" );
assert.ok( b.c.equals( two3 ), "Passed!" );
});
QUnit.test( "setFromPointsAndIndices" , function( assert ) {
var a = new THREE.Triangle();
var points = [ one3, one3.clone().negate(), two3 ];
a.setFromPointsAndIndices( points, 1, 0, 2 );
assert.ok( a.a.equals( one3.clone().negate() ), "Passed!" );
assert.ok( a.b.equals( one3 ), "Passed!" );
assert.ok( a.c.equals( two3 ), "Passed!" );
});
QUnit.test( "set" , function( assert ) {
var a = new THREE.Triangle();
a.set( one3.clone().negate(), one3, two3 );
assert.ok( a.a.equals( one3.clone().negate() ), "Passed!" );
assert.ok( a.b.equals( one3 ), "Passed!" );
assert.ok( a.c.equals( two3 ), "Passed!" );
});
QUnit.test( "area" , function( assert ) {
var a = new THREE.Triangle();
assert.ok( a.area() == 0, "Passed!" );
a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
assert.ok( a.area() == 0.5, "Passed!" );
a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) );
assert.ok( a.area() == 2, "Passed!" );
// colinear triangle.
a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 3, 0, 0 ) );
assert.ok( a.area() == 0, "Passed!" );
});
QUnit.test( "midpoint" , function( assert ) {
var a = new THREE.Triangle();
assert.ok( a.midpoint().equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" );
a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
assert.ok( a.midpoint().equals( new THREE.Vector3( 1/3, 1/3, 0 ) ), "Passed!" );
a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) );
assert.ok( a.midpoint().equals( new THREE.Vector3( 2/3, 0, 2/3 ) ), "Passed!" );
});
QUnit.test( "normal" , function( assert ) {
var a = new THREE.Triangle();
assert.ok( a.normal().equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" );
a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
assert.ok( a.normal().equals( new THREE.Vector3( 0, 0, 1 ) ), "Passed!" );
a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) );
assert.ok( a.normal().equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" );
});
QUnit.test( "plane" , function( assert ) {
var a = new THREE.Triangle();
assert.notOk( isNaN( a.plane().distanceToPoint( a.a ) ), "Passed!" );
assert.notOk( isNaN( a.plane().distanceToPoint( a.b ) ), "Passed!" );
assert.notOk( isNaN( a.plane().distanceToPoint( a.c ) ), "Passed!" );
assert.notPropEqual( a.plane().normal, { x: NaN, y: NaN, z: NaN }, "Passed!" );
a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
assert.ok( a.plane().distanceToPoint( a.a ) == 0, "Passed!" );
assert.ok( a.plane().distanceToPoint( a.b ) == 0, "Passed!" );
assert.ok( a.plane().distanceToPoint( a.c ) == 0, "Passed!" );
assert.ok( a.plane().normal.equals( a.normal() ), "Passed!" );
a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) );
assert.ok( a.plane().distanceToPoint( a.a ) == 0, "Passed!" );
assert.ok( a.plane().distanceToPoint( a.b ) == 0, "Passed!" );
assert.ok( a.plane().distanceToPoint( a.c ) == 0, "Passed!" );
assert.ok( a.plane().normal.clone().normalize().equals( a.normal() ), "Passed!" );
});
QUnit.test( "barycoordFromPoint" , function( assert ) {
var a = new THREE.Triangle();
var bad = new THREE.Vector3( -2, -1, -1 );
assert.ok( a.barycoordFromPoint( a.a ).equals( bad ), "Passed!" );
assert.ok( a.barycoordFromPoint( a.b ).equals( bad ), "Passed!" );
assert.ok( a.barycoordFromPoint( a.c ).equals( bad ), "Passed!" );
a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
assert.ok( a.barycoordFromPoint( a.a ).equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" );
assert.ok( a.barycoordFromPoint( a.b ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" );
assert.ok( a.barycoordFromPoint( a.c ).equals( new THREE.Vector3( 0, 0, 1 ) ), "Passed!" );
assert.ok( a.barycoordFromPoint( a.midpoint() ).distanceTo( new THREE.Vector3( 1/3, 1/3, 1/3 ) ) < 0.0001, "Passed!" );
a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) );
assert.ok( a.barycoordFromPoint( a.a ).equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" );
assert.ok( a.barycoordFromPoint( a.b ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" );
assert.ok( a.barycoordFromPoint( a.c ).equals( new THREE.Vector3( 0, 0, 1 ) ), "Passed!" );
assert.ok( a.barycoordFromPoint( a.midpoint() ).distanceTo( new THREE.Vector3( 1/3, 1/3, 1/3 ) ) < 0.0001, "Passed!" );
});
QUnit.test( "containsPoint" , function( assert ) {
var a = new THREE.Triangle();
assert.ok( ! a.containsPoint( a.a ), "Passed!" );
assert.ok( ! a.containsPoint( a.b ), "Passed!" );
assert.ok( ! a.containsPoint( a.c ), "Passed!" );
a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
assert.ok( a.containsPoint( a.a ), "Passed!" );
assert.ok( a.containsPoint( a.b ), "Passed!" );
assert.ok( a.containsPoint( a.c ), "Passed!" );
assert.ok( a.containsPoint( a.midpoint() ), "Passed!" );
assert.ok( ! a.containsPoint( new THREE.Vector3( -1, -1, -1 ) ), "Passed!" );
a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) );
assert.ok( a.containsPoint( a.a ), "Passed!" );
assert.ok( a.containsPoint( a.b ), "Passed!" );
assert.ok( a.containsPoint( a.c ), "Passed!" );
assert.ok( a.containsPoint( a.midpoint() ), "Passed!" );
assert.ok( ! a.containsPoint( new THREE.Vector3( -1, -1, -1 ) ), "Passed!" );
});
QUnit.test( "closestPointToPoint" , function( assert ) {
var a = new THREE.Triangle( new THREE.Vector3( -1, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
// point lies inside the triangle
var b0 = a.closestPointToPoint( new THREE.Vector3( 0, 0.5, 0 ) );
assert.ok( b0.equals( new THREE.Vector3( 0, 0.5, 0 ) ), "Passed!" );
// point lies on a vertex
b0 = a.closestPointToPoint( a.a );
assert.ok( b0.equals( a.a ), "Passed!" );
b0 = a.closestPointToPoint( a.b );
assert.ok( b0.equals( a.b ), "Passed!" );
b0 = a.closestPointToPoint( a.c );
assert.ok( b0.equals( a.c ), "Passed!" );
// point lies on an edge
b0 = a.closestPointToPoint( zero3.clone() );
assert.ok( b0.equals( zero3.clone() ), "Passed!" );
// point lies outside the triangle
b0 = a.closestPointToPoint( new THREE.Vector3( -2, 0, 0 ) );
assert.ok( b0.equals( new THREE.Vector3( -1, 0, 0 ) ), "Passed!" );
b0 = a.closestPointToPoint( new THREE.Vector3( 2, 0, 0 ) );
assert.ok( b0.equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" );
b0 = a.closestPointToPoint( new THREE.Vector3( 0, 2, 0 ) );
assert.ok( b0.equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" );
b0 = a.closestPointToPoint( new THREE.Vector3( 0, -2, 0 ) );
assert.ok( b0.equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" );
});
QUnit.test( "equals", function ( assert ) {
var a = new THREE.Triangle(
new THREE.Vector3( 1, 0, 0 ),
new THREE.Vector3( 0, 1, 0 ),
new THREE.Vector3( 0, 0, 1 )
);
var b = new THREE.Triangle(
new THREE.Vector3( 0, 0, 1 ),
new THREE.Vector3( 0, 1, 0 ),
new THREE.Vector3( 1, 0, 0 )
);
var c = new THREE.Triangle(
new THREE.Vector3( - 1, 0, 0 ),
new THREE.Vector3( 0, 1, 0 ),
new THREE.Vector3( 0, 0, 1 )
);
assert.ok( a.equals( a ), "a equals a" );
assert.notOk( a.equals( b ), "a does not equal b" );
assert.notOk( a.equals( c ), "a does not equal c" );
assert.notOk( b.equals( c ), "b does not equal c" );
a.copy( b );
assert.ok( a.equals( a ), "a equals b after copy()" );
} );
| googlecreativelab/three.js | test/unit/src/math/Triangle.js | JavaScript | mit | 9,020 |
const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev
/**
* Webpack Plugins
*/
const DefinePlugin = require('webpack/lib/DefinePlugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const OptimizeJsPlugin = require('optimize-js-plugin');
/**
* Webpack Constants
*/
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 8080;
const BASE_CONFIG = process.env.BASE_CONFIG = {
// 'siteUrl': 'http://localhost:9090/opidc-server'
'siteUrl': '/opidc-server'
};
const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
host: HOST,
port: PORT,
ENV: ENV,
HMR: false,
BASE_CONFIG: JSON.stringify(BASE_CONFIG)
});
module.exports = function (env) {
return webpackMerge(commonConfig({env: ENV}), {
/**
* Developer tool to enhance debugging
*
* See: http://webpack.github.io/docs/configuration.html#devtool
* See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
*/
devtool: 'source-map',
/**
* Options affecting the output of the compilation.
*
* See: http://webpack.github.io/docs/configuration.html#output
*/
output: {
/**
* The output directory as absolute path (required).
*
* See: http://webpack.github.io/docs/configuration.html#output-path
*/
path: helpers.root('dist'),
/**
* Specifies the name of each output file on disk.
* IMPORTANT: You must not specify an absolute path here!
*
* See: http://webpack.github.io/docs/configuration.html#output-filename
*/
filename: 'js/[name].bundle.js',
/**
* The filename of the SourceMaps for the JavaScript files.
* They are inside the output.path directory.
*
* See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
*/
sourceMapFilename: 'js/[name].bundle.map',
/**
* The filename of non-entry chunks as relative path
* inside the output.path directory.
*
* See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
*/
chunkFilename: 'js/[id].chunk.js'
},
/**
* Add additional plugins to the compiler.
*
* See: http://webpack.github.io/docs/configuration.html#plugins
*/
plugins: [
/**
* Webpack plugin to optimize a JavaScript file for faster initial load
* by wrapping eagerly-invoked functions.
*
* See: https://github.com/vigneshshanmugam/optimize-js-plugin
*/
new OptimizeJsPlugin({
sourceMap: false
}),
/**
* Plugin: DedupePlugin
* Description: Prevents the inclusion of duplicate code into your bundle
* and instead applies a copy of the function at runtime.
*
* See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
* See: https://github.com/webpack/docs/wiki/optimization#deduplication
*/
// new DedupePlugin(), // see: https://github.com/angular/angular-cli/issues/1587
/**
* Plugin: DefinePlugin
* Description: Define free variables.
* Useful for having development builds with debug logging or adding global constants.
*
* Environment helpers
*
* See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
*/
// NOTE: when adding more properties make sure you include them in custom-typings.d.ts
new DefinePlugin({
'ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
'BASE_CONFIG': METADATA.BASE_CONFIG,
'process.env': {
'ENV': JSON.stringify(METADATA.ENV),
'NODE_ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
'BASE_CONFIG': METADATA.BASE_CONFIG
}
}),
/**
* Plugin: UglifyJsPlugin
* Description: Minimize all JavaScript output of chunks.
* Loaders are switched into minimizing mode.
*
* See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
*/
// NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
new UglifyJsPlugin({
// beautify: true, //debug
// mangle: false, //debug
// dead_code: false, //debug
// unused: false, //debug
// deadCode: false, //debug
// compress: {
// screw_ie8: true,
// keep_fnames: true,
// drop_debugger: false,
// dead_code: false,
// unused: false
// }, // debug
// comments: true, //debug
beautify: false, //prod
output: {
comments: false
},
mangle: {
screw_ie8: true
}, //prod
compress: {
screw_ie8: true,
warnings: false,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true,
negate_iife: false // we need this for lazy v8
},
comments: false //prod
}),
/**
* Plugin: NormalModuleReplacementPlugin
* Description: Replace resources that matches resourceRegExp with newResource
*
* See: http://webpack.github.io/docs/list-of-plugins.html#normalmodulereplacementplugin
*/
new NormalModuleReplacementPlugin(
/angular2-hmr/,
helpers.root('config/empty.js')
),
new NormalModuleReplacementPlugin(
/zone\.js(\\|\/)dist(\\|\/)long-stack-trace-zone/,
helpers.root('config/empty.js')
),
/**
* Plugin: IgnorePlugin
* Description: Don’t generate modules for requests matching the provided RegExp.
*
* See: http://webpack.github.io/docs/list-of-plugins.html#ignoreplugin
*/
// new IgnorePlugin(/angular2-hmr/),
/**
* Plugin: CompressionPlugin
* Description: Prepares compressed versions of assets to serve
* them with Content-Encoding
*
* See: https://github.com/webpack/compression-webpack-plugin
*/
// install compression-webpack-plugin
// new CompressionPlugin({
// regExp: /\.css$|\.html$|\.js$|\.map$/,
// threshold: 2 * 1024
// })
/**
* Plugin LoaderOptionsPlugin (experimental)
*
* See: https://gist.github.com/sokra/27b24881210b56bbaff7
*/
new LoaderOptionsPlugin({
minimize: true,
debug: false,
options: {
context: helpers.root('src'),
output: {
path: helpers.root('dist')
},
/**
* Static analysis linter for TypeScript advanced options configuration
* Description: An extensible linter for the TypeScript language.
*
* See: https://github.com/wbuchwalter/tslint-loader
*/
tslint: {
emitErrors: true,
failOnHint: true,
resourcePath: 'src'
},
/**
* Html loader advanced options
*
* See: https://github.com/webpack/html-loader#advanced-options
*/
// TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
htmlLoader: {
minimize: true,
removeAttributeQuotes: false,
caseSensitive: true,
customAttrSurround: [
[/#/, /(?:)/],
[/\*/, /(?:)/],
[/\[?\(?/, /(?:)/]
],
customAttrAssign: [/\)?\]?=/]
},
}
}),
],
/*
* Include polyfills or mocks for various node stuff
* Description: Node configuration
*
* See: https://webpack.github.io/docs/configuration.html#node
*/
node: {
global: true,
crypto: 'empty',
process: false,
module: false,
clearImmediate: false,
setImmediate: false
}
});
};
| ashramwen/opidc-admin | config/webpack.prod.js | JavaScript | mit | 8,670 |
/* Copyright (c) 2013
* Sylvain Lancien
* http://www.wibami.com
* 30-10-2013
* Tested with jQuery 1.10.2 and SharePoint 2010
*/
(function ($) {
$.fn.SLN_SPcascadingdropdown = function (options) {
var defaults = {
relationshipList: "Cities", //Name of the list which contains the parent/child relationships.
relationshipParentList: "Countries", //Name of the list which contains the parent items.
relationshipParentListColumn: "Title", //StaticName of the values column in the relationshipParentList.
relationshipListChildColumn: "Title", //StaticName of the child column in the relationshipList
relationshipListParentColumn: "Country", //StaticName of the parent column in the relationshipList
childDropDown: "cities", //Id of the child DropDownList
autoFillParentDropDownList: true, //True : Fill the parent DropDownList with all ParentList values (set false if you want to keep old selected values)
defaulFillChildDropDownList: false, //True: Fill the child DropDownList with all ChildList values if no value is selected for parent DropDownList.
promptText: "--Select item--" //Default text displayed in the dropdownlists
};
var options = $.extend(defaults, options);
return this.each(function () {
//Get parent Dropdownlist ID
var parentDropDown = this.id;
//Get current client context
var context = SP.ClientContext.get_current();
//Fill parent DropDownList with all values
if (options.autoFillParentDropDownList) {
fillDefaults(parentDropDown, options.relationshipParentList, options.relationshipParentListColumn, context, options.defaulFillChildDropDownList);
}
else if (options.defaulFillChildDropDownList) {
//Fill child DropDownList with all values
fillDefaults(options.childDropDown, options.relationshipList, options.relationshipListChildColumn, context, false);
}
$('#' + options.childDropDown).append("<option value='0' selected='true'>" + options.promptText + "</option>");
$('select').change(function (e) {
if (this.id === parentDropDown) {
var childList = context.get_web().get_lists().getByTitle(options.relationshipList);
//Clear child Dropdownlist
$('#' + options.childDropDown).empty();
$('#' + options.childDropDown).append("<option value='0' selected='true'>" + options.promptText + "</option>");
if (this[this.selectedIndex].value !== null && this[this.selectedIndex].value !== 0) {
itemSelected = this[this.selectedIndex].text;
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='" + options.relationshipListParentColumn + "'/>" + "<Value Type='Lookup'>" + itemSelected + "</Value></Eq></Where><OrderBy><FieldRef Name='" + options.relationshipListChildColumn + "' Ascending='True' /></OrderBy></Query><RowLimit>10</RowLimit></View>");
var childListItems = childList.getItems(camlQuery);
context.load(childListItems);
context.executeQueryAsync(Function.createDelegate(this, function () { readListItemSucceeded("#" + options.childDropDown, options.relationshipListChildColumn, childListItems, false); }), readListItemFailed);
}
else {
if (options.defaulFillChildDropDownList) {
//Fill the child DropDownList with all values
fillDefaults(options.childDropDown, options.relationshipList, options.relationshipListChildColumn, context, false);
}
else {
$('#' + options.childDropDown).empty();
$('#' + options.childDropDown).append("<option value='0' selected='true'>" + options.promptText + "</option>");
}
}
$('#' + options.childDropDown).change();
}
});
function fillDefaults(dropdownName, listName, columnName, context, fillChildDropdown) {
var spList = context.get_web().get_lists().getByTitle(listName);
var camlQuery = SP.CamlQuery.createAllItemsQuery();
var listItems = spList.getItems(camlQuery);
context.load(listItems);
context.executeQueryAsync(Function.createDelegate(this, function () { readListItemSucceeded("#" + dropdownName, columnName, listItems, fillChildDropdown); }), readListItemFailed);
}
//executeQueryAsync Succeed
function readListItemSucceeded(dropdownID, columnName, listItems, fillChildDropdown) {
var enumerator = listItems.getEnumerator();
//Clear the current DropDownList
$(dropdownID).empty();
while (enumerator.moveNext()) {
var listItem = enumerator.get_current();
$(dropdownID).append('<option value="' + listItem.get_id().toString() + '">' + listItem.get_item(columnName) + '</option>');
}
//Add promptext as first option and select it
$(dropdownID).prepend("<option value='0' selected='true'>" + options.promptText + "</option>");
$(dropdownID).find("option:first").attr('selected', 'true');
//Fill child DropDownList with all values : We needed to wait for the executeQueryAsync to finish
if (fillChildDropdown) {
fillDefaults(options.childDropDown, options.relationshipList, options.relationshipListChildColumn, context, false);
}
}
//executeQueryAsync Failed
function readListItemFailed(sender, args) {
throw new Error('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
});
};
})(jQuery); | S-Lancien/SLN_SPcascadingdropdown | SLN_SPcascadingdropdown.js | JavaScript | mit | 6,321 |
var Redis = require('../')
, redis = new Redis(6379, 'localhost')
, stream = redis.stream()
stream.pipe(Redis.es.join('\r\n')).pipe(process.stdout)
// interact with the redis network connection directly
// using `Redis.parse`, which is used internally
stream.redis.write(Redis.parse([ 'info' ]))
stream.redis.write(Redis.parse([ 'lpush', 'mylist', 'val' ]))
stream.end()
| tblobaum/redis-stream | example/command-parser.js | JavaScript | mit | 377 |
/**
* Created by Francois on 06.03.2016.
*/
'use strict';
angular.module('gardenApp')
.controller('LogoutCtrl', function ($scope, Auth) {
$scope.logout = function () {
console.log('logging out');
Auth.logout(function (err) {
if (!err) {
window.location = '/';
} else {
console.log('cannot log out')
}
});
};
}); | faspert/GeantVert | app/controllers/LogoutCtrl.js | JavaScript | mit | 484 |
/*
* modified version of THREE.PointerLockControls by mrdoob / http://mrdoob.com
*/
THREE.PointerLockControls = function ( camera ) {
var scope = this;
camera.rotation.set( 0, 0, 0 );
var pitchObject = new THREE.Object3D();
pitchObject.add( camera );
var yawObject = new THREE.Object3D();
yawObject.position.y = 10;
yawObject.add( pitchObject );
var moveForward = false;
var moveBackward = false;
var moveLeft = false;
var moveRight = false;
var isOnObject = false;
var canJump = false;
var velocity = new THREE.Vector3();
var PI_2 = Math.PI / 2;
var onMouseClick = function ( event ) {
if ( scope.enabled === false ) return;
var d_func = controls.getDirection();
var d = d_func( new THREE.Vector3() );
d.multiplyScalar( 50 );
d.add( yawObject.position );
var msg = {
x: d.x,
y: d.y,
z: d.z
};
ws.send( JSON.stringify(msg) );
};
var onMouseMove = function ( event ) {
if ( scope.enabled === false ) return;
var movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
var movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;
yawObject.rotation.y -= movementX * 0.002;
pitchObject.rotation.x -= movementY * 0.002;
pitchObject.rotation.x = Math.max( - PI_2, Math.min( PI_2, pitchObject.rotation.x ) );
};
var onKeyDown = function ( event ) {
switch ( event.keyCode ) {
case 38: // up
case 87: // w
moveForward = true;
break;
case 37: // left
case 65: // a
moveLeft = true; break;
case 40: // down
case 83: // s
moveBackward = true;
break;
case 39: // right
case 68: // d
moveRight = true;
break;
case 32: // space
if ( canJump === true ) velocity.y += 7;
canJump = false;
event.preventDefault();
break;
}
};
var onKeyUp = function ( event ) {
switch( event.keyCode ) {
case 38: // up
case 87: // w
moveForward = false;
break;
case 37: // left
case 65: // a
moveLeft = false;
break;
case 40: // down
case 83: // a
moveBackward = false;
break;
case 39: // right
case 68: // d
moveRight = false;
break;
}
};
document.addEventListener( 'click', onMouseClick, false );
document.addEventListener( 'mousemove', onMouseMove, false );
document.addEventListener( 'keydown', onKeyDown, false );
document.addEventListener( 'keyup', onKeyUp, false );
this.enabled = false;
this.getObject = function () {
return yawObject;
};
this.isOnObject = function ( boolean ) {
isOnObject = boolean;
canJump = boolean;
};
this.getDirection = function() {
// assumes the camera itself is not rotated
var direction = new THREE.Vector3( 0, 0, -1 );
var rotation = new THREE.Euler( 0, 0, 0, "YXZ" );
return function( v ) {
rotation.set( pitchObject.rotation.x, yawObject.rotation.y, 0 );
v.copy( direction ).applyEuler( rotation );
return v;
}
};
this.update = function ( delta ) {
if ( scope.enabled === false ) return;
delta *= 0.1;
velocity.x += ( - velocity.x ) * 0.08 * delta;
velocity.z += ( - velocity.z ) * 0.08 * delta;
velocity.y -= 0.25 * delta;
if ( moveForward ) velocity.z -= 0.12 * delta;
if ( moveBackward ) velocity.z += 0.12 * delta;
if ( moveLeft ) velocity.x -= 0.12 * delta;
if ( moveRight ) velocity.x += 0.12 * delta;
if ( isOnObject === true ) {
velocity.y = Math.max( 0, velocity.y );
}
yawObject.translateX( velocity.x );
yawObject.translateY( velocity.y );
yawObject.translateZ( velocity.z );
if ( yawObject.position.y < 10 ) {
velocity.y = 0;
yawObject.position.y = 10;
canJump = true;
}
};
};
| akjetma/put_cube | public/js/put_cube/controls.js | JavaScript | mit | 3,691 |
Organizations = new Mongo.Collection('organizations');
//TODO: allow/deny rules here
Meteor.methods({
organizationUpdate: function(organizationAttributes) {
check(this.userId, String);
check(organizationAttributes, {
name: String,
info: String,
tags: [String]
});
//TODO: sanitize inputs here
var user = Meteor.user();
var organization = _.extend(organizationAttributes, {
userId: user._id,
username: user.username,
updatedAt: new Date(),
approved: false, // NOTE: every time a user updates their org, this will automatically eliminate it from the list
});
Organizations.update(
{
userId: user._id
},
{
$set: organization
},
{
upsert: true
});
}
});
| petestreet/nw_quadrant_meteor_boilerplate | lib/collections/organizations.js | JavaScript | mit | 932 |
define(['exports', '../common/widget-base', '../common/constants', '../common/decorators', '../common/common', 'syncfusion-javascript/Scripts/ej/datavisualization/ej.bulletgraph.min'], function (exports, _widgetBase, _constants, _decorators, _common) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ejBulletGraph = undefined;
function _initDefineProp(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
});
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
function _initializerWarningHelper(descriptor, context) {
throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');
}
var _dec, _dec2, _dec3, _dec4, _dec5, _class, _desc, _value, _class2, _descriptor;
var ejBulletGraph = exports.ejBulletGraph = (_dec = (0, _common.customElement)(_constants.constants.elementPrefix + 'bullet-graph'), _dec2 = (0, _common.inlineView)('' + _constants.constants.aureliaTemplateString), _dec3 = (0, _decorators.generateBindables)('ejBulletGraph', ['applyRangeStrokeToLabels', 'applyRangeStrokeToTicks', 'captionSettings', 'comparativeMeasureValue', 'enableAnimation', 'enableResizing', 'flowDirection', 'height', 'isResponsive', 'enableGroupSeparator', 'locale', 'orientation', 'qualitativeRanges', 'qualitativeRangeSize', 'quantitativeScaleLength', 'quantitativeScaleSettings', 'theme', 'tooltipSettings', 'value', 'width']), _dec4 = (0, _common.inject)(Element), _dec5 = (0, _common.children)(_constants.constants.elementPrefix + 'qualitative-range'), _dec(_class = _dec2(_class = _dec3(_class = _dec4(_class = (_class2 = function (_WidgetBase) {
_inherits(ejBulletGraph, _WidgetBase);
function ejBulletGraph(element) {
_classCallCheck(this, ejBulletGraph);
var _this = _possibleConstructorReturn(this, _WidgetBase.call(this));
_initDefineProp(_this, 'qualitativeRanges', _descriptor, _this);
_this.element = element;
_this.hasChildProperty = true;
_this.childPropertyName = 'qualitativeRanges';
return _this;
}
return ejBulletGraph;
}(_widgetBase.WidgetBase), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'qualitativeRanges', [_dec5], {
enumerable: true,
initializer: function initializer() {
return [];
}
})), _class2)) || _class) || _class) || _class) || _class);
}); | Dyalog/MiServer | PlugIns/Syncfusion-15.3.0.33/assets/scripts/aurelia/amd/bulletgraph/bulletgraph.js | JavaScript | mit | 4,469 |
/*! videojs-record v1.0.2
* https://github.com/collab-project/videojs-record
* Copyright (c) 2014-2015 - Licensed MIT */
(function (root, factory)
{
if (typeof define === 'function' && define.amd)
{
// AMD. Register as an anonymous module.
define(['videojs'], factory);
}
else if (typeof module === 'object' && module.exports)
{
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require('videojs'));
}
else
{
// Browser globals (root is window)
root.returnExports = factory(root.videojs);
}
}(this, function (videojs)
{
'use strict';
var VjsComponent = videojs.getComponent('Component');
var VjsButton = videojs.getComponent('Button');
videojs.RecordBase = videojs.extend(VjsComponent,
{
// recorder modes
IMAGE_ONLY: 'image_only',
AUDIO_ONLY: 'audio_only',
VIDEO_ONLY: 'video_only',
AUDIO_VIDEO: 'audio_video',
ANIMATION: 'animation',
// recorder engines
RECORDRTC: 'recordrtc',
LIBVORBISJS: 'libvorbis.js',
// browser checks
isEdge: function()
{
return navigator.userAgent.indexOf('Edge') !== -1 && (!!navigator.msSaveBlob || !!navigator.msSaveOrOpenBlob);
},
isOpera: function()
{
return !!window.opera || navigator.userAgent.indexOf('OPR/') !== -1;
},
isChrome: function()
{
return !this.isOpera() && !this.isEdge() && !!navigator.webkitGetUserMedia;
},
/** @constructor */
constructor: function(player, options)
{
VjsComponent.call(this, player, options);
}
});
videojs.RecordRTCEngine = videojs.extend(videojs.RecordBase,
{
/**
* Setup recording engine.
*/
setup: function(stream, mediaType, debug)
{
this.inputStream = stream;
this.mediaType = mediaType;
this.debug = debug;
// setup RecordRTC
this.engine = new MRecordRTC();
this.engine.mediaType = this.mediaType;
this.engine.disableLogs = !this.debug;
// audio settings
this.engine.bufferSize = this.bufferSize;
this.engine.sampleRate = this.sampleRate;
// animated gif settings
this.engine.quality = this.quality;
this.engine.frameRate = this.frameRate;
// connect stream to recording engine
this.engine.addStream(this.inputStream);
},
/**
* Start recording.
*/
start: function()
{
this.engine.startRecording();
},
/**
* Stop recording. Result will be available async when onStopRecording
* is called.
*/
stop: function()
{
this.engine.stopRecording(this.onStopRecording.bind(this));
},
/**
* Invoked when recording is stopped and resulting stream is available.
*
* @param {string} audioVideoWebMURL Reference to the recorded Blob
* object, eg. blob:http://localhost:8080/10100016-4248-9949-b0d6-0bb40db56eba
* @param {string} type Media type, eg. 'video' or 'audio'.
*/
onStopRecording: function(audioVideoWebMURL, type)
{
// store reference to recorded stream URL
this.mediaURL = audioVideoWebMURL;
// store reference to recorded stream data
var recordType = this.player().recorder.getRecordType();
this.engine.getBlob(function(recording)
{
switch (recordType)
{
case this.AUDIO_ONLY:
this.recordedData = recording.audio;
// notify listeners
this.trigger('recordComplete');
break;
case this.VIDEO_ONLY:
case this.AUDIO_VIDEO:
// when recording both audio and video, recordrtc
// calls this twice on chrome, first with audio data
// and then with video data.
// on firefox it's called once but with a single webm
// blob that includes both audio and video data.
if (recording.video !== undefined)
{
// data is video-only but on firefox audio+video
this.recordedData = recording.video;
// on the chrome browser two blobs are created
// containing the separate audio/video streams.
if (recordType === this.AUDIO_VIDEO && this.isChrome())
{
// store both audio and video
this.recordedData = recording;
}
// notify listeners
this.trigger('recordComplete');
}
break;
case this.ANIMATION:
this.recordedData = recording.gif;
// notify listeners
this.trigger('recordComplete');
break;
}
}.bind(this));
}
});
videojs.LibVorbisEngine = videojs.extend(videojs.RecordBase,
{
/**
* Setup recording engine.
*/
setup: function(stream, mediaType, debug)
{
this.inputStream = stream;
this.mediaType = mediaType;
this.debug = debug;
// setup libvorbis.js
this.options = {
workerURL: this.audioWorkerURL,
moduleURL: this.audioModuleURL,
encoderOptions: {
channels: 2,
sampleRate: this.sampleRate,
quality: 0.8
}
};
},
/**
* Start recording.
*/
start: function()
{
this.chunks = [];
this.audioContext = new AudioContext();
this.audioSourceNode = this.audioContext.createMediaStreamSource(this.inputStream);
this.scriptProcessorNode = this.audioContext.createScriptProcessor(this.bufferSize);
libvorbis.OggVbrAsyncEncoder.create(
this.options,
this.onData.bind(this),
this.onStopRecording.bind(this)).then(
this.onEngineCreated.bind(this));
},
/**
* Stop recording.
*/
stop: function()
{
this.audioSourceNode.disconnect(this.scriptProcessorNode);
this.scriptProcessorNode.disconnect(this.audioContext.destination);
this.encoder.finish();
},
/**
* Invoked when the libvorbis encoder is ready for recording.
*/
onEngineCreated: function(encoder)
{
this.encoder = encoder;
this.scriptProcessorNode.onaudioprocess = this.onAudioProcess.bind(this);
this.audioSourceNode.connect(this.scriptProcessorNode);
this.scriptProcessorNode.connect(this.audioContext.destination);
},
/**
* Continous encoding of audio data.
*/
onAudioProcess: function(ev)
{
var inputBuffer = ev.inputBuffer;
var samples = inputBuffer.length;
var ch0 = inputBuffer.getChannelData(0);
var ch1 = inputBuffer.getChannelData(1);
// script processor reuses buffers; we need to make copies
ch0 = new Float32Array(ch0);
ch1 = new Float32Array(ch1);
var channelData = [ch0, ch1];
this.encoder.encode(channelData);
},
/**
*
*/
onData: function(data)
{
this.chunks.push(data);
},
/**
* Invoked when recording is stopped and resulting stream is available.
*/
onStopRecording: function()
{
this.recordedData = new Blob(this.chunks, {type: 'audio/ogg'});
// store reference to recorded stream URL
this.mediaURL = URL.createObjectURL(this.recordedData);
// notify listeners
this.trigger('recordComplete');
}
});
/**
* Record audio/video/images using the Video.js player.
*/
videojs.Recorder = videojs.extend(videojs.RecordBase,
{
/**
* The constructor function for the class.
*
* @param {videojs.Player|Object} player
* @param {Object} options Player options.
*/
constructor: function(player, options)
{
// run base component initializing with new options.
VjsComponent.call(this, player, options);
// record settings
this.recordImage = this.options_.options.image;
this.recordAudio = this.options_.options.audio;
this.recordVideo = this.options_.options.video;
this.recordAnimation = this.options_.options.animation;
this.maxLength = this.options_.options.maxLength;
this.debug = this.options_.options.debug;
// audio settings
this.audioEngine = this.options_.options.audioEngine;
this.audioWorkerURL = this.options_.options.audioWorkerURL;
this.audioModuleURL = this.options_.options.audioModuleURL;
this.audioBufferSize = this.options_.options.audioBufferSize;
this.audioSampleRate = this.options_.options.audioSampleRate;
// animation settings
this.animationFrameRate = this.options_.options.animationFrameRate;
this.animationQuality = this.options_.options.animationQuality;
// recorder state
this._recording = false;
this._processing = false;
this._deviceActive = false;
// cross-browser getUserMedia
this.getUserMedia = (
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia
).bind(navigator);
// wait until player ui is ready
this.player().one('ready', this.setupUI.bind(this));
},
/**
* Player UI is ready.
*/
setupUI: function()
{
// insert custom controls on left-side of controlbar
this.player().controlBar.addChild(this.player().cameraButton);
this.player().controlBar.el().insertBefore(
this.player().cameraButton.el(),
this.player().controlBar.el().firstChild);
this.player().controlBar.el().insertBefore(
this.player().recordToggle.el(),
this.player().controlBar.el().firstChild);
// get rid of unused controls
if (this.player().controlBar.remainingTimeDisplay !== undefined)
{
this.player().controlBar.remainingTimeDisplay.el().style.display = 'none';
}
if (this.player().controlBar.liveDisplay !== undefined)
{
this.player().controlBar.liveDisplay.el().style.display = 'none';
}
// tweak player UI based on type
switch (this.getRecordType())
{
case this.AUDIO_ONLY:
// reference to videojs-wavesurfer plugin
this.surfer = this.player().waveform;
if (this.surfer)
{
if(this.playhead){
// initially hide playhead (fixed in wavesurfer 1.0.25)
this.playhead = this.surfer.el().getElementsByTagName('wave')[1];
this.playhead.style.display = 'none';
}
}
break;
case this.IMAGE_ONLY:
case this.VIDEO_ONLY:
case this.AUDIO_VIDEO:
case this.ANIMATION:
// customize controls
// XXX: below are customizations copied from videojs.wavesurfer that
// tweak the video.js UI...
this.player().bigPlayButton.hide();
if (this.player().options_.controls)
{
// progress control isn't used by this plugin
this.player().controlBar.progressControl.hide();
// prevent controlbar fadeout
this.player().on('userinactive', function(event)
{
this.player().userActive(true);
});
// videojs automatically hides the controls when no valid 'source'
// element is included in the 'audio' tag. Don't. Ever again.
this.player().controlBar.show();
this.player().controlBar.el().style.display = 'flex';
}
break;
}
// disable currentTimeDisplay's 'timeupdate' event listener that
// constantly tries to reset the current time value to 0
this.player().off('timeupdate');
// display max record time
this.setDuration(this.maxLength);
// hide play control
this.player().controlBar.playToggle.hide();
},
/**
* Indicates whether we're currently recording or not.
*/
isRecording: function()
{
return this._recording;
},
/**
* Indicates whether we're currently processing recorded data or not.
*/
isProcessing: function()
{
return this._processing;
},
/**
* Indicates whether the player is destroyed or not.
*/
isDestroyed: function()
{
return this.player() && (this.player().children() === null);
},
/**
* Open the brower's recording device selection dialog.
*/
getDevice: function()
{
// define device callbacks once
if (this.deviceReadyCallback === undefined)
{
this.deviceReadyCallback = this.onDeviceReady.bind(this);
}
if (this.deviceErrorCallback === undefined)
{
this.deviceErrorCallback = this.onDeviceError.bind(this);
}
if (this.engineStopCallback === undefined)
{
this.engineStopCallback = this.onRecordComplete.bind(this);
}
// ask the browser to give us access to media device and get a
// stream reference in the callback function
switch (this.getRecordType())
{
case this.AUDIO_ONLY:
// setup microphone
this.mediaType = {
audio: true,
video: false
};
// remove existing mic listeners
this.surfer.microphone.un('deviceReady',
this.deviceReadyCallback);
this.surfer.microphone.un('deviceError',
this.deviceErrorCallback);
// setup new mic listeners
this.surfer.microphone.on('deviceReady',
this.deviceReadyCallback);
this.surfer.microphone.on('deviceError',
this.deviceErrorCallback);
// disable existing playback events
this.surfer.setupPlaybackEvents(false);
// (re)set surfer liveMode
this.surfer.liveMode = true;
this.surfer.microphone.paused = false;
// open browser device selection dialog
this.surfer.microphone.start();
break;
case this.IMAGE_ONLY:
case this.VIDEO_ONLY:
// setup camera
this.mediaType = {
audio: false,
video: true
};
this.getUserMedia(
this.mediaType,
this.onDeviceReady.bind(this),
this.onDeviceError.bind(this));
break;
case this.AUDIO_VIDEO:
// setup camera and microphone
this.mediaType = {
audio: true,
video: true
};
this.getUserMedia(
this.mediaType,
this.onDeviceReady.bind(this),
this.onDeviceError.bind(this));
break;
case this.ANIMATION:
// setup camera
this.mediaType = {
// animated gif
audio: false,
video: false,
gif: true
};
this.getUserMedia({
audio: false,
video: true
},
this.onDeviceReady.bind(this),
this.onDeviceError.bind(this));
break;
}
},
/**
* Invoked when the device is ready.
*
* @param stream: LocalMediaStream instance.
*/
onDeviceReady: function(stream)
{
this._deviceActive = true;
// store reference to stream for stopping etc.
this.stream = stream;
// forward to listeners
this.player().trigger('deviceReady');
// hide device selection button
this.player().deviceButton.hide();
// reset time (e.g. when stopDevice was used)
this.setDuration(this.maxLength);
this.setCurrentTime(0);
// hide play/pause control (e.g. when stopDevice was used)
this.player().controlBar.playToggle.hide();
// reset playback listeners
this.off(this.player(), 'timeupdate', this.playbackTimeUpdate);
this.off(this.player(), 'pause', this.onPlayerPause);
this.off(this.player(), 'play', this.onPlayerStart);
// setup recording engine
if (this.getRecordType() !== this.IMAGE_ONLY)
{
// currently libvorbis.js is only supported in
// audio-only mode
if (this.getRecordType() !== this.AUDIO_ONLY &&
this.audioEngine === this.LIBVORBISJS)
{
throw new Error('Currently libvorbis.js is only supported in audio-only mode.');
}
// connect stream to recording engine
if (this.audioEngine === this.RECORDRTC)
{
// RecordRTC.js (default)
this.engine = new videojs.RecordRTCEngine(this.player());
}
else if (this.audioEngine === this.LIBVORBISJS)
{
// libvorbis.js
this.engine = new videojs.LibVorbisEngine(this.player());
}
// listen for events
this.engine.on('recordComplete', this.engineStopCallback);
// audio settings
this.engine.bufferSize = this.audioBufferSize;
this.engine.sampleRate = this.audioSampleRate;
this.engine.audioWorkerURL = this.audioWorkerURL;
this.engine.audioModuleURL = this.audioModuleURL;
// animated gif settings
this.engine.quality = this.animationQuality;
this.engine.frameRate = this.animationFrameRate;
this.engine.setup(this.stream, this.mediaType, !this.debug);
// show elements that should never be hidden in animation,
// audio and/or video modus
var element;
var uiElements = [this.player().controlBar.currentTimeDisplay,
this.player().controlBar.timeDivider,
this.player().controlBar.durationDisplay];
for (element in uiElements)
{
uiElements[element].el().style.display = 'block';
uiElements[element].show();
}
// show record button
this.player().recordToggle.show();
}
else
{
// disable record indicator
this.player().recordIndicator.disable();
// setup UI for retrying snapshot (e.g. when stopDevice was
// used)
this.retrySnapshot();
// reset and show camera button
this.player().cameraButton.onStop();
this.player().cameraButton.show();
}
// setup preview
if (this.getRecordType() !== this.AUDIO_ONLY)
{
// show live preview
this.mediaElement = this.player().el().firstChild;
this.mediaElement.controls = false;
// mute incoming audio for feedback loops
this.mediaElement.muted = true;
// hide the volume bar while it's muted
this.displayVolumeControl(false);
// start stream
this.load(URL.createObjectURL(this.stream));
this.mediaElement.play();
}
},
/**
* Invoked when an device error occurred.
*/
onDeviceError: function(code)
{
this._deviceActive = false;
// store code
this.player().deviceErrorCode = code;
// forward error to player
this.player().trigger('deviceError');
},
/**
* Start recording.
*/
start: function()
{
if (!this.isProcessing())
{
this._recording = true;
// hide play control
this.player().controlBar.playToggle.hide();
// setup preview engine
switch (this.getRecordType())
{
case this.AUDIO_ONLY:
// disable playback events
this.surfer.setupPlaybackEvents(false);
if(this.playhead){
// hide playhead
// backwards compat (fixed since wavesurfer 1.0.25)
this.playhead.style.display = 'none';
}
// start/resume live audio visualization
this.surfer.microphone.paused = false;
this.surfer.liveMode = true;
this.player().play();
break;
case this.VIDEO_ONLY:
case this.AUDIO_VIDEO:
this.startVideoPreview();
break;
case this.ANIMATION:
// hide the first frame
this.player().recordCanvas.hide();
// hide the animation
this.player().animationDisplay.hide();
// show preview video
this.mediaElement.style.display = 'block';
// for animations, capture the first frame
// that can be displayed as soon as recording
// is complete
this.captureFrame();
// start video preview **after** capturing first frame
this.startVideoPreview();
break;
}
// start recording
if (this.getRecordType() !== this.IMAGE_ONLY)
{
// start countdown
this.startTime = new Date().getTime();
this.countDown = this.setInterval(
this.onCountDown.bind(this), 100);
// start recording stream
this.engine.start();
}
else
{
// create snapshot
this.createSnapshot();
}
// notify UI
this.player().trigger('startRecord');
}
},
/**
* Stop recording.
*/
stop: function()
{
if (!this.isProcessing())
{
this._recording = false;
this._processing = true;
// notify UI
this.player().trigger('stopRecord');
if (this.getRecordType() !== this.IMAGE_ONLY)
{
// stop countdown
this.clearInterval(this.countDown);
// stop recording stream (result will be available async)
if (this.engine)
{
this.engine.stop();
}
}
else
{
if (this.player().recordedData)
{
// notify listeners that image data is (already) available
this.player().trigger('finishRecord');
}
}
}
},
/**
* Stop device(s) and recording if active.
*/
stopDevice: function()
{
if (this.isRecording())
{
// stop stream once recorded data is available,
// otherwise it'll break recording
this.player().one('finishRecord', this.stopStream.bind(this));
// stop recording
this.stop();
}
else
{
// stop stream now, since there's no recorded data
// being available
this.stopStream();
}
},
/**
* Stop stream and device.
*/
stopStream: function()
{
// stop stream and device
if (this.stream)
{
// use MediaStream.stop in browsers other than Chrome for now
// This will be deprecated in Firefox 44 (see
// https://www.fxsitecompat.com/en-US/docs/2015/mediastream-stop-has-been-deprecated/
// and https://bugzilla.mozilla.org/show_bug.cgi?id=1103188#c106)
if (!this.isChrome())
{
if (this.getRecordType() === this.AUDIO_ONLY)
{
// make the microphone plugin stop it's device
this.surfer.microphone.stopDevice();
}
else
{
// stop MediaStream
this.stream.stop();
}
}
else
{
// use MediaStreamTrack.stop() in Chrome instead of
// MediaStream.stop() (deprecated since Chrome 45)
// https://developers.google.com/web/updates/2015/07/mediastream-deprecations
var track;
switch (this.getRecordType())
{
case this.AUDIO_ONLY:
// make the microphone plugin stop it's device
this.surfer.microphone.stopDevice();
break;
case this.VIDEO_ONLY:
case this.ANIMATION:
case this.IMAGE_ONLY:
track = this.stream.getVideoTracks()[0];
track.stop();
break;
case this.AUDIO_VIDEO:
track = this.stream.getTracks();
for (var index in track)
{
track[index].stop();
}
break;
}
}
this._deviceActive = false;
}
},
/**
* Invoked when recording completed and the resulting stream is
* available.
*/
onRecordComplete: function()
{
// store reference to recorded stream URL
this.mediaURL = this.engine.mediaURL;
// store reference to recorded stream data
switch (this.getRecordType())
{
case this.AUDIO_ONLY:
// show play control
this.player().controlBar.playToggle.show();
// store recorded data
this.player().recordedData = this.engine.recordedData;
// notify listeners that data is available
this.player().trigger('finishRecord');
// Pausing the player so we can visualize the recorded data
// will trigger an async videojs 'pause' event that we have
// to wait for.
this.player().one('pause', function()
{
// setup events during playback
this.surfer.setupPlaybackEvents(true);
// display loader
this.player().loadingSpinner.show();
if(this.playhead){
// show playhead
this.playhead.style.display = 'block';
}
// restore interaction with controls after waveform
// rendering is complete
this.surfer.surfer.once('ready', function()
{
this._processing = false;
}.bind(this));
// visualize recorded stream
this.load(this.player().recordedData);
}.bind(this));
// pause player so user can start playback
this.player().pause();
break;
case this.VIDEO_ONLY:
case this.AUDIO_VIDEO:
// show play control
this.player().controlBar.playToggle.show();
// store recorded data (video-only or firefox audio+video)
this.player().recordedData = this.engine.recordedData;
// notify listeners that data is available
this.player().trigger('finishRecord');
// remove previous listeners
this.off(this.player(), 'pause', this.onPlayerPause);
this.off(this.player(), 'play', this.onPlayerStart);
// Pausing the player so we can visualize the recorded data
// will trigger an async videojs 'pause' event that we have
// to wait for.
this.player().one('pause', function()
{
// video data is ready
this._processing = false;
// hide loader
this.player().loadingSpinner.hide();
// show stream total duration
this.setDuration(this.streamDuration);
// update time during playback
this.on(this.player(), 'timeupdate',
this.playbackTimeUpdate);
// because there are 2 separate data streams for audio
// and video in the Chrome browser, playback the audio
// stream in a new extra audio element and the video
// stream in the regular video.js player.
if (this.getRecordType() === this.AUDIO_VIDEO &&
this.isChrome())
{
if (this.extraAudio === undefined)
{
this.extraAudio = this.createEl('audio');
this.extraAudio.id = 'extraAudio';
// handle volume changes in extra audio
// for chrome
this.player().on('volumechange',
this.onVolumeChange.bind(this));
}
this.extraAudio.src = URL.createObjectURL(
this.player().recordedData.audio);
// pause extra audio when player pauses
this.on(this.player(), 'pause',
this.onPlayerPause);
}
// workaround some browser issues when player starts
this.on(this.player(), 'play', this.onPlayerStart);
// unmute local audio during playback
if (this.getRecordType() === this.AUDIO_VIDEO)
{
this.mediaElement.muted = false;
// show the volume bar when it's unmuted
this.displayVolumeControl(true);
}
// load recorded media
this.load(this.mediaURL);
}.bind(this));
// pause player so user can start playback
this.player().pause();
break;
case this.ANIMATION:
// show play control
this.player().controlBar.playToggle.show();
// store recorded data
this.player().recordedData = this.engine.recordedData;
// notify listeners that data is available
this.player().trigger('finishRecord');
// animation data is ready
this._processing = false;
// hide loader
this.player().loadingSpinner.hide();
// show animation total duration
this.setDuration(this.streamDuration);
// hide preview video
this.mediaElement.style.display = 'none';
// show the first frame
this.player().recordCanvas.show();
// pause player so user can start playback
this.player().pause();
// show animation on play
this.on(this.player(), 'play', this.showAnimation);
// hide animation on pause
this.on(this.player(), 'pause', this.hideAnimation);
break;
}
},
/**
* Fired when the volume in the temporary audio element
* for Chrome in audio+video mode is present.
*/
onVolumeChange: function()
{
var volume = this.player().volume();
if (this.player().muted())
{
// muted volume
volume = 0;
}
this.extraAudio.volume = volume;
},
/**
* Invoked during recording and displays the remaining time.
*/
onCountDown: function()
{
var currentTime = (new Date().getTime() - this.startTime) / 1000;
var duration = this.maxLength;
this.streamDuration = currentTime;
if (currentTime >= duration)
{
// at the end
currentTime = duration;
// stop recording
this.stop();
}
// update duration
this.setDuration(duration);
// update current time
this.setCurrentTime(currentTime, duration);
},
/**
* Updates the player's element displaying the current time.
*
* @param {Number} currentTime (optional) Current position of the
* playhead (in seconds).
* @param {Number} duration (optional) Duration in seconds.
*/
setCurrentTime: function(currentTime, duration)
{
switch (this.getRecordType())
{
case this.AUDIO_ONLY:
this.surfer.setCurrentTime(currentTime, duration);
break;
case this.VIDEO_ONLY:
case this.AUDIO_VIDEO:
case this.ANIMATION:
var time = Math.min(currentTime, duration);
// update control
this.player().controlBar.currentTimeDisplay.el(
).firstChild.innerHTML = this.formatTime(
time, duration);
break;
}
},
/**
* Updates the player's element displaying the duration time.
*
* @param {Number} duration (optional) Duration in seconds.
*/
setDuration: function(duration)
{
switch (this.getRecordType())
{
case this.AUDIO_ONLY:
this.surfer.setDuration(duration);
break;
case this.VIDEO_ONLY:
case this.AUDIO_VIDEO:
case this.ANIMATION:
// update control
this.player().controlBar.durationDisplay.el(
).firstChild.innerHTML = this.formatTime(
duration, duration);
break;
}
},
/**
* Start loading data.
*
* @param {String|Blob|File} url Either the URL of the media file,
* or a Blob or File object.
*/
load: function(url)
{
switch (this.getRecordType())
{
case this.AUDIO_ONLY:
// visualize recorded stream
this.surfer.load(url);
break;
case this.IMAGE_ONLY:
case this.VIDEO_ONLY:
case this.AUDIO_VIDEO:
case this.ANIMATION:
// assign stream to audio/video element src
this.mediaElement.src = url;
break;
}
},
/**
* Cleanup resources.
*/
destroy: function()
{
// prevent callbacks if recording is in progress
if (this.engine)
{
this.engine.off('recordComplete', this.engineStopCallback);
}
// stop recording and device
this.stop();
this.stopDevice();
// stop countdown
this.clearInterval(this.countDown);
// dispose player
switch (this.getRecordType())
{
case this.AUDIO_ONLY:
if (this.surfer)
{
// also disposes player
this.surfer.destroy();
}
break;
case this.IMAGE_ONLY:
case this.VIDEO_ONLY:
case this.AUDIO_VIDEO:
case this.ANIMATION:
this.player().dispose();
break;
}
this._recording = false;
this._processing = false;
this._deviceActive = false;
},
/**
* Get recorder type.
*/
getRecordType: function()
{
if (this.recordImage)
{
return this.IMAGE_ONLY;
}
else if (this.recordAnimation)
{
return this.ANIMATION;
}
else if (this.recordAudio && !this.recordVideo)
{
return this.AUDIO_ONLY;
}
else if (this.recordAudio && this.recordVideo)
{
return this.AUDIO_VIDEO;
}
else if (!this.recordAudio && this.recordVideo)
{
return this.VIDEO_ONLY;
}
},
/**
* Create and display snapshot image.
*/
createSnapshot: function()
{
var recordCanvas = this.captureFrame();
// turn the canvas data into base-64 data with a PNG header
this.player().recordedData = recordCanvas.toDataURL('image/png');
// hide preview video
this.mediaElement.style.display = 'none';
// show the snapshot
this.player().recordCanvas.show();
// stop recording
this.stop();
},
/**
* Reset UI for retrying a snapshot image.
*/
retrySnapshot: function()
{
this._processing = false;
// retry: hide the snapshot
this.player().recordCanvas.hide();
// show preview video
this.player().el().firstChild.style.display = 'block';
},
/**
* Capture frame from camera and copy it to canvas.
*/
captureFrame: function()
{
var recordCanvas = this.player().recordCanvas.el().firstChild;
// set the canvas size to the dimensions of the camera,
// which also wipes it
recordCanvas.width = this.player().width();
recordCanvas.height = this.player().height();
// get a frame of the stream and copy it onto the canvas
recordCanvas.getContext('2d').drawImage(
this.mediaElement, 0, 0,
recordCanvas.width,
recordCanvas.height
);
return recordCanvas;
},
/**
*
*/
startVideoPreview: function()
{
// disable playback events
this.off('timeupdate');
this.off('play');
// mute local audio
this.mediaElement.muted = true;
// hide volume control to prevent feedback
this.displayVolumeControl(false);
// start/resume live preview
this.load(URL.createObjectURL(this.stream));
this.mediaElement.play();
},
/**
* Show animated GIF.
*/
showAnimation: function()
{
var animationDisplay = this.player().animationDisplay.el().firstChild;
// set the image size to the dimensions of the recorded animation
animationDisplay.width = this.player().width();
animationDisplay.height = this.player().height();
// hide the first frame
this.player().recordCanvas.hide();
// show the animation
animationDisplay.src = this.mediaURL;
this.player().animationDisplay.show();
},
/**
* Hide animated GIF.
*/
hideAnimation: function()
{
// show the first frame
this.player().recordCanvas.show();
// hide the animation
this.player().animationDisplay.hide();
},
/**
* Player started playback.
*/
onPlayerStart: function()
{
// workaround firefox issue
if (this.player().seeking())
{
// There seems to be a Firefox issue
// with playing back blobs. The ugly,
// but functional workaround, is to
// simply reset the source. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=969290
this.load(this.mediaURL);
this.player().play();
}
// workaround chrome issue
if (this.getRecordType() === this.AUDIO_VIDEO &&
this.isChrome() && !this._recording)
{
// sync extra audio playhead position with video.js player
this.extraAudio.currentTime = this.player().currentTime();
this.extraAudio.play();
}
},
/**
* Player is paused.
*/
onPlayerPause: function()
{
// pause extra audio when video.js player pauses
this.extraAudio.pause();
},
/**
* Update time during playback.
*/
playbackTimeUpdate: function()
{
this.setCurrentTime(this.player().currentTime(),
this.streamDuration);
},
/**
* Show/hide the volume menu.
*/
displayVolumeControl: function(display)
{
if (this.player().controlBar.volumeMenuButton !== undefined)
{
if (display === true)
{
display = 'block';
}
else
{
display = 'none';
}
this.player().controlBar.volumeMenuButton.el().style.display = display;
}
},
/**
* Format seconds as a time string, H:MM:SS, M:SS or M:SS:MMM.
*
* Supplying a guide (in seconds) will force a number of leading zeros
* to cover the length of the guide.
*
* @param {Number} seconds Number of seconds to be turned into a string
* @param {Number} guide Number (in seconds) to model the string after
* @return {String} Time formatted as H:MM:SS, M:SS or M:SS:MMM.
*/
formatTime: function(seconds, guide)
{
// XXX: integrate method changes in video.js, see
// https://github.com/videojs/video.js/issues/1922
// Default to using seconds as guide
guide = guide || seconds;
var s = Math.floor(seconds % 60),
m = Math.floor(seconds / 60 % 60),
h = Math.floor(seconds / 3600),
gm = Math.floor(guide / 60 % 60),
gh = Math.floor(guide / 3600),
ms = Math.floor((seconds - s) * 1000);
// handle invalid times
if (isNaN(seconds) || seconds === Infinity)
{
// '-' is false for all relational operators (e.g. <, >=) so this
// setting will add the minimum number of fields specified by the
// guide
h = m = s = ms = '-';
}
// Check if we need to show milliseconds
if (guide > 0 && guide < this.msDisplayMax)
{
if (ms < 100)
{
if (ms < 10)
{
ms = '00' + ms;
}
else
{
ms = '0' + ms;
}
}
ms = ':' + ms;
}
else
{
ms = '';
}
// Check if we need to show hours
h = (h > 0 || gh > 0) ? h + ':' : '';
// If hours are showing, we may need to add a leading zero.
// Always show at least one digit of minutes.
m = (((h || gm >= 10) && m < 10) ? '0' + m : m) + ':';
// Check if leading zero is need for seconds
s = ((s < 10) ? '0' + s : s);
return h + m + s + ms;
}
});
var RecordToggle, CameraButton, DeviceButton, RecordIndicator, RecordCanvas,
AnimationDisplay;
/**
* Button to toggle between start and stop recording
* @class
*/
RecordToggle = videojs.extend(VjsButton,
{
/** @constructor */
constructor: function(player, options)
{
VjsButton.call(this, player, options);
this.on('click', this.onClick);
this.on(player, 'startRecord', this.onStart);
this.on(player, 'stopRecord', this.onStop);
}
});
RecordToggle.prototype.onClick = function(e)
{
// stop this event before it bubbles up
e.stopImmediatePropagation();
var recorder = this.player().recorder;
if (!recorder.isRecording())
{
recorder.start();
}
else
{
recorder.stop();
}
};
RecordToggle.prototype.onStart = function()
{
// add the vjs-record-start class to the element so it can change appearance
this.removeClass('vjs-icon-record-start');
this.addClass('vjs-icon-record-stop');
// update label
this.el().firstChild.firstChild.innerHTML = this.localize('Stop');
};
RecordToggle.prototype.onStop = function()
{
// add the vjs-record-stop class to the element so it can change appearance
this.removeClass('vjs-icon-record-stop');
this.addClass('vjs-icon-record-start');
// update label
this.el().firstChild.firstChild.innerHTML = this.localize('Record');
};
/**
* Button to toggle between create and retry snapshot image
* @class
*/
CameraButton = videojs.extend(VjsButton,
{
/** @constructor */
constructor: function(player, options)
{
VjsButton.call(this, player, options);
this.on('click', this.onClick);
this.on(player, 'startRecord', this.onStart);
this.on(player, 'stopRecord', this.onStop);
}
});
CameraButton.prototype.onClick = function(e)
{
// stop this event before it bubbles up
e.stopImmediatePropagation();
var recorder = this.player().recorder;
if (!recorder.isProcessing())
{
// create snapshot
recorder.start();
}
else
{
// retry
recorder.retrySnapshot();
// reset camera button
this.onStop();
}
};
CameraButton.prototype.onStart = function()
{
// add class to the element so it can change appearance
this.removeClass('vjs-icon-photo-camera');
this.addClass('vjs-icon-photo-retry');
// update label
this.el().firstChild.firstChild.innerHTML = this.localize('Retry');
};
CameraButton.prototype.onStop = function()
{
// add class to the element so it can change appearance
this.removeClass('vjs-icon-photo-retry');
this.addClass('vjs-icon-photo-camera');
// update label
this.el().firstChild.firstChild.innerHTML = this.localize('Image');
};
/**
* Button to select recording device
* @class
*/
DeviceButton = videojs.extend(VjsButton,
{
/** @constructor */
constructor: function(player, options)
{
VjsButton.call(this, player, options);
this.on('click', this.onClick);
}
});
DeviceButton.prototype.onClick = function(e)
{
// stop this event before it bubbles up
e.stopImmediatePropagation();
// open device dialog
this.player().recorder.getDevice();
};
/**
* Icon indicating recording is active.
* @class
*/
RecordIndicator = videojs.extend(VjsComponent,
{
/** @constructor */
constructor: function(player, options)
{
VjsComponent.call(this, player, options);
this.on(player, 'startRecord', this.show);
this.on(player, 'stopRecord', this.hide);
}
});
RecordIndicator.prototype.disable = function()
{
// disable record indicator event handlers
this.off(this.player(), 'startRecord', this.show);
this.off(this.player(), 'stopRecord', this.hide);
};
/**
* Canvas for displaying snapshot image.
* @class
*/
RecordCanvas = videojs.extend(VjsComponent);
/**
* Image for displaying animated GIF image.
* @class
*/
AnimationDisplay = videojs.extend(VjsComponent);
/**
* Create a custom button
* @param className {string} class name for the new button
* @param label {string} label for the new button
*/
var createButton = function(className, label, iconName)
{
var props = {
className: 'vjs-' + className + '-button vjs-control vjs-icon-' + iconName,
innerHTML: '<div class="vjs-control-content"><span class="vjs-control-text">' +
label + '</span></div>',
};
var attrs = {
role: 'button',
'aria-live': 'polite', // let the screen reader user know that the text of the button may change
tabIndex: 0
};
return VjsComponent.prototype.createEl('div', props, attrs);
};
var createPlugin = function()
{
var props = {
className: 'vjs-record',
};
var attrs = {
tabIndex: 0
};
return VjsComponent.prototype.createEl('div', props, attrs);
};
// plugin defaults
var defaults = {
// Single snapshot image.
image: false,
// Include audio in the recorded clip.
audio: false,
// Include video in the recorded clip.
video: false,
// Animated GIF.
animation: false,
// Maximum length of the recorded clip.
maxLength: 10,
// Audio recording library to use. Legal values are 'recordrtc'
// and 'libvorbis.js'.
audioEngine: 'recordrtc',
// The size of the audio buffer (in sample-frames) which needs to
// be processed each time onprocessaudio is called.
// From the spec: This value controls how frequently the audioprocess event is
// dispatched and how many sample-frames need to be processed each call.
// Lower values for buffer size will result in a lower (better) latency.
// Higher values will be necessary to avoid audio breakup and glitches.
// Legal values are 256, 512, 1024, 2048, 4096, 8192 or 16384.
audioBufferSize: 4096,
// The audio sample rate (in sample-frames per second) at which the
// AudioContext handles audio. It is assumed that all AudioNodes
// in the context run at this rate. In making this assumption,
// sample-rate converters or "varispeed" processors are not supported
// in real-time processing.
// The sampleRate parameter describes the sample-rate of the
// linear PCM audio data in the buffer in sample-frames per second.
// An implementation must support sample-rates in at least
// the range 22050 to 96000.
audioSampleRate: 44100,
// URL for the audio worker.
audioWorkerURL: '',
// URL for the audio module.
audioModuleURL: '',
// Frame rate in frames per second.
animationFrameRate: 200,
// Sets quality of color quantization (conversion of images to the
// maximum 256 colors allowed by the GIF specification).
// Lower values (minimum = 1) produce better colors,
// but slow processing significantly. 10 is the default,
// and produces good color mapping at reasonable speeds.
// Values greater than 20 do not yield significant improvements
// in speed.
animationQuality: 10,
// Enables console logging for debugging purposes
debug: false
};
/**
* Initialize the plugin.
* @param options (optional) {object} configuration for the plugin
*/
var record = function(options)
{
var settings = videojs.mergeOptions(defaults, options);
var player = this;
// create recorder
player.recorder = new videojs.Recorder(player,
{
'el': createPlugin(),
'options': settings
});
player.addChild(player.recorder);
// add device button
player.deviceButton = new DeviceButton(player,
{
'el': createButton('device', player.localize('Device'),
'device-perm')
});
player.recorder.addChild(player.deviceButton);
// add record indicator
player.recordIndicator = new RecordIndicator(player,
{
'el': VjsComponent.prototype.createEl('div',
{
className: 'vjs-record-indicator vjs-control'
})
});
player.recordIndicator.hide();
player.recorder.addChild(player.recordIndicator);
// add canvas for recording and displaying image
player.recordCanvas = new RecordCanvas(player,
{
'el': VjsComponent.prototype.createEl('div',
{
className: 'vjs-record-canvas',
innerHTML: '<canvas></canvas>'
})
});
player.recordCanvas.hide();
player.recorder.addChild(player.recordCanvas);
// add image for animation display
player.animationDisplay = new AnimationDisplay(player,
{
'el': VjsComponent.prototype.createEl('div',
{
className: 'vjs-animation-display',
innerHTML: '<img />'
})
});
player.animationDisplay.hide();
player.recorder.addChild(player.animationDisplay);
// add camera button
player.cameraButton = new CameraButton(player,
{
'el': createButton('camera', player.localize('Image'),
'photo-camera')
});
player.cameraButton.hide();
// add record toggle
player.recordToggle = new RecordToggle(player,
{
'el': createButton('record', player.localize('Record'),
'record-start')
});
player.recordToggle.hide();
};
// register the plugin
videojs.plugin('record', record);
// return a function to define the module export
return record;
}));
| bygiro/Angular-MultiStreamRecorder | demo/assets/js/videojs.record.js | JavaScript | mit | 59,505 |
var searchData=
[
['row_2ecpp',['Row.cpp',['../Row_8cpp.html',1,'']]],
['row_2eh',['Row.h',['../Row_8h.html',1,'']]],
['row_5ftest_2ecpp',['Row_test.cpp',['../Row__test_8cpp.html',1,'']]],
['row_5ftest_2eh',['Row_test.h',['../Row__test_8h.html',1,'']]]
];
| smc314/helix | html/devdoc/html/search/files_d.js | JavaScript | mit | 264 |
export default function indentString(string, count = 1, options = {}) {
const {
indent = ' ',
includeEmptyLines = false
} = options;
if (typeof string !== 'string') {
throw new TypeError(
`Expected \`input\` to be a \`string\`, got \`${typeof string}\``
);
}
if (typeof count !== 'number') {
throw new TypeError(
`Expected \`count\` to be a \`number\`, got \`${typeof count}\``
);
}
if (count < 0) {
throw new RangeError(
`Expected \`count\` to be at least 0, got \`${count}\``
);
}
if (typeof indent !== 'string') {
throw new TypeError(
`Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``
);
}
if (count === 0) {
return string;
}
const regex = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
return string.replace(regex, indent.repeat(count));
}
| sindresorhus/indent-string | index.js | JavaScript | mit | 820 |
var webpack = require('webpack')
var utils = require('../build/utils')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.config')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
Object.keys(baseWebpackConfig.entry).forEach(function(chunkName) {
baseWebpackConfig.entry[chunkName] = ['./build/dev-client'].concat(baseWebpackConfig.entry[chunkName])
})
module.exports = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
},
devtool: "#cheap-module-eval-source-map",
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new FriendlyErrorsPlugin()
]
}) | SnailGames/snail-fed | config/webpack.dev.config.js | JavaScript | mit | 872 |
8.0.0-beta6:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.0-beta7:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.0-beta9:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.0-beta10:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.0-beta11:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.0-beta12:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.0-beta13:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.0-beta14:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.0-beta15:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.0-beta16:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.0-rc1:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.0-rc2:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.0-rc3:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.0-rc4:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.1:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.2:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.3:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.4:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.5:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.6:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.1.0-beta1:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.1.0-beta2:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.1.0-rc1:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.1.1:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.1.2:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.1.3:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.1.4:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.1.5:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.1.6:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.1.7:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.1.8:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.1.9:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.1.10:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.2.0-beta1:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.2.0-beta2:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.2.0-beta3:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.2.0-rc1:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.2.0-rc2:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.2.1:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.2.2:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.2.3:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.2.4:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.2.5:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.2.6:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.3.0-alpha1:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.3.0-beta1:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.3.0-rc1:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.2.7:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.3.0-rc2:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.0.0:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.1.0:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.2.0:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
8.3.0:2c3eca8a31e04e36332667c831488777a19d7673afdd3f21308d891a84ac11c2
| GoZOo/Drupaloscopy | hashs-database/hashs/core___assets___vendor___jquery.ui___ui___i18n___datepicker-fi.js | JavaScript | mit | 3,910 |
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-favourite-heart',
included: function(app) {
app.import('vendor/style.css');
app.import('vendor/assets/web_heart_animation.png');
}
};
| anilmaurya/ember-favourite-heart | index.js | JavaScript | mit | 219 |
import sinon from "sinon";
export default function createMockTemp(temporaryDirectoryPath) {
return {
mkdir: sinon.spy((directoryName, callback) => {
callback(null, temporaryDirectoryPath);
})
};
}
| FreeAllMedia/akiro | es6/spec/helpers/mockTemp.js | JavaScript | mit | 207 |
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { useSelector } from 'react-redux';
import { makeStyles } from '@material-ui/styles';
import { alpha } from '@material-ui/core/styles';
import IconButton from '@material-ui/core/IconButton';
import Collapse from '@material-ui/core/Collapse';
import NoSsr from '@material-ui/core/NoSsr';
import HighlightedCode from 'docs/src/modules/components/HighlightedCode';
import DemoSandboxed from 'docs/src/modules/components/DemoSandboxed';
import { AdCarbonInline } from 'docs/src/modules/components/AdCarbon';
import getJsxPreview from 'docs/src/modules/utils/getJsxPreview';
import { CODE_VARIANTS } from 'docs/src/modules/constants';
import { useUserLanguage, useTranslate } from 'docs/src/modules/utils/i18n';
const DemoToolbar = React.lazy(() => import('./DemoToolbar'));
// Sync with styles from DemoToolbar
// Importing the styles results in no bundle size reduction
const useDemoToolbarFallbackStyles = makeStyles(
(theme) => {
return {
root: {
display: 'none',
[theme.breakpoints.up('sm')]: {
display: 'flex',
height: theme.spacing(6),
},
},
};
},
{ name: 'DemoToolbar' },
);
export function DemoToolbarFallback() {
const classes = useDemoToolbarFallbackStyles();
const t = useTranslate();
return (
<div aria-busy aria-label={t('demoToolbarLabel')} className={classes.root} role="toolbar" />
);
}
function getDemoName(location) {
return location.replace(/(.+?)(\w+)\.\w+$$/, '$2');
}
function useDemoData(codeVariant, demo, githubLocation) {
const userLanguage = useUserLanguage();
const title = `${getDemoName(githubLocation)} Material Demo`;
if (codeVariant === CODE_VARIANTS.TS && demo.rawTS) {
return {
codeVariant: CODE_VARIANTS.TS,
githubLocation: githubLocation.replace(/\.js$/, '.tsx'),
language: userLanguage,
raw: demo.rawTS,
Component: demo.tsx,
sourceLanguage: 'tsx',
title,
};
}
return {
codeVariant: CODE_VARIANTS.JS,
githubLocation,
language: userLanguage,
raw: demo.raw,
Component: demo.js,
sourceLanguage: 'jsx',
title,
};
}
// TODO: replace with React.useOpaqueReference if it is released
function useUniqueId(prefix) {
// useOpaqueReference
const [id, setId] = React.useState();
React.useEffect(() => {
setId(Math.random().toString(36).slice(2));
}, []);
return id ? `${prefix}${id}` : id;
}
const useStyles = makeStyles(
(theme) => ({
root: {
marginBottom: 40,
marginLeft: theme.spacing(-2),
marginRight: theme.spacing(-2),
[theme.breakpoints.up('sm')]: {
padding: theme.spacing(0, 1),
marginLeft: 0,
marginRight: 0,
},
},
demo: {
position: 'relative',
outline: 0,
margin: 'auto',
display: 'flex',
justifyContent: 'center',
[theme.breakpoints.up('sm')]: {
borderRadius: theme.shape.borderRadius,
},
},
/* Isolate the demo with an outline. */
demoBgOutlined: {
padding: theme.spacing(3),
backgroundColor: theme.palette.background.paper,
border: `1px solid ${alpha(theme.palette.action.active, 0.12)}`,
borderLeftWidth: 0,
borderRightWidth: 0,
[theme.breakpoints.up('sm')]: {
borderLeftWidth: 1,
borderRightWidth: 1,
},
},
/* Prepare the background to display an inner elevation. */
demoBgTrue: {
padding: theme.spacing(3),
backgroundColor: theme.palette.mode === 'dark' ? '#333' : theme.palette.grey[100],
},
/* Make no difference between the demo and the markdown. */
demoBgInline: {
// Maintain alignment with the markdown text
[theme.breakpoints.down('sm')]: {
padding: theme.spacing(3),
},
},
demoHiddenToolbar: {
paddingTop: theme.spacing(2),
[theme.breakpoints.up('sm')]: {
paddingTop: theme.spacing(3),
},
},
code: {
display: 'none',
padding: 0,
marginBottom: theme.spacing(1),
marginRight: 0,
[theme.breakpoints.up('sm')]: {
display: 'block',
},
'& pre': {
overflow: 'auto',
lineHeight: 1.5,
margin: '0 !important',
maxHeight: 'min(68vh, 1000px)',
},
},
anchorLink: {
marginTop: -64, // height of toolbar
position: 'absolute',
},
initialFocus: {
position: 'absolute',
top: 0,
left: 0,
width: theme.spacing(4),
height: theme.spacing(4),
pointerEvents: 'none',
},
}),
{ name: 'Demo' },
);
export default function Demo(props) {
const { demo, demoOptions, disableAd, githubLocation } = props;
const classes = useStyles();
const t = useTranslate();
const codeVariant = useSelector((state) => state.options.codeVariant);
const demoData = useDemoData(codeVariant, demo, githubLocation);
const [demoHovered, setDemoHovered] = React.useState(false);
const handleDemoHover = (event) => {
setDemoHovered(event.type === 'mouseenter');
};
const DemoComponent = demoData.Component;
const demoName = getDemoName(demoData.githubLocation);
const demoSandboxedStyle = React.useMemo(
() => ({
maxWidth: demoOptions.maxWidth,
height: demoOptions.height,
}),
[demoOptions.height, demoOptions.maxWidth],
);
if (demoOptions.bg == null) {
demoOptions.bg = 'outlined';
}
if (demoOptions.iframe) {
demoOptions.bg = true;
}
const [codeOpen, setCodeOpen] = React.useState(demoOptions.defaultCodeOpen || false);
const shownOnce = React.useRef(false);
if (codeOpen) {
shownOnce.current = true;
}
React.useEffect(() => {
const navigatedDemoName = getDemoName(window.location.hash);
if (demoName === navigatedDemoName) {
setCodeOpen(true);
}
}, [demoName]);
const jsx = getJsxPreview(demoData.raw || '');
const showPreview =
!demoOptions.hideToolbar &&
demoOptions.defaultCodeOpen !== false &&
jsx !== demoData.raw &&
jsx.split(/\n/).length <= 17;
const [demoKey, resetDemo] = React.useReducer((key) => key + 1, 0);
const demoId = useUniqueId('demo-');
const demoSourceId = useUniqueId(`demoSource-`);
const openDemoSource = codeOpen || showPreview;
const initialFocusRef = React.useRef(null);
const [showAd, setShowAd] = React.useState(false);
return (
<div className={classes.root}>
<div className={classes.anchorLink} id={`${demoName}`} />
<div
className={clsx(classes.demo, {
[classes.demoHiddenToolbar]: demoOptions.hideToolbar,
[classes.demoBgOutlined]: demoOptions.bg === 'outlined',
[classes.demoBgTrue]: demoOptions.bg === true,
[classes.demoBgInline]: demoOptions.bg === 'inline',
})}
id={demoId}
onMouseEnter={handleDemoHover}
onMouseLeave={handleDemoHover}
>
<IconButton
aria-label={t('initialFocusLabel')}
className={classes.initialFocus}
action={initialFocusRef}
tabIndex={-1}
/>
<DemoSandboxed
key={demoKey}
style={demoSandboxedStyle}
component={DemoComponent}
iframe={demoOptions.iframe}
name={demoName}
onResetDemoClick={resetDemo}
/>
</div>
<div className={classes.anchorLink} id={`${demoName}.js`} />
<div className={classes.anchorLink} id={`${demoName}.tsx`} />
{demoOptions.hideToolbar ? null : (
<NoSsr defer fallback={<DemoToolbarFallback />}>
<React.Suspense fallback={<DemoToolbarFallback />}>
<DemoToolbar
codeOpen={codeOpen}
codeVariant={codeVariant}
demo={demo}
demoData={demoData}
demoHovered={demoHovered}
demoId={demoId}
demoName={demoName}
demoOptions={demoOptions}
demoSourceId={demoSourceId}
initialFocusRef={initialFocusRef}
onCodeOpenChange={() => {
setCodeOpen((open) => !open);
setShowAd(true);
}}
onResetDemoClick={resetDemo}
openDemoSource={openDemoSource}
showPreview={showPreview}
/>
</React.Suspense>
</NoSsr>
)}
<Collapse in={openDemoSource} unmountOnExit>
<div>
<HighlightedCode
className={classes.code}
id={demoSourceId}
code={showPreview && !codeOpen ? jsx : demoData.raw}
language={demoData.sourceLanguage}
/>
</div>
</Collapse>
{showAd && !disableAd && !demoOptions.disableAd ? <AdCarbonInline /> : null}
</div>
);
}
Demo.propTypes = {
demo: PropTypes.object.isRequired,
demoOptions: PropTypes.object.isRequired,
disableAd: PropTypes.bool.isRequired,
githubLocation: PropTypes.string.isRequired,
};
| mbrookes/material-ui | docs/src/modules/components/Demo.js | JavaScript | mit | 9,025 |
import React from 'react';
import Field from '../Field';
import PropProvider from '../FieldPropProvider';
import CheckboxOnly from './CheckboxOnly';
import { fieldCheckbox as propTypes } from '../../../helpers/propTypes';
class CheckboxRaw extends React.Component {
handleChange = (value) => {
const { input } = this.props;
if (input && input.onChange) {
input.onChange(value);
}
};
render() {
const { size, description, trueValue, falseValue, input, disabled } = this.props;
const switchValue = input ? input.value : undefined;
return (
<Field {...this.props} fieldType="switch">
<CheckboxOnly
description={description}
disabled={disabled}
falseValue={falseValue}
onChange={this.handleChange}
size={size}
trueValue={trueValue}
value={switchValue}
/>
</Field>
);
}
}
const Checkbox = PropProvider.withComponent(CheckboxRaw);
Checkbox.propTypes = propTypes;
Checkbox.defaultProps = {
size: 'md'
};
export default Checkbox; | ilxanlar/cathode | src/components/Form/Checkbox/Checkbox.js | JavaScript | mit | 1,071 |
'use strict';
angular.module('mean.storybook').config(['$stateProvider',
function($stateProvider) {
$stateProvider
.state('view', {
url: '/storybook/view/{bookId}/{bookPage}',
templateUrl: 'storybook/views/view.html'
})
.state('write', {
url: '/storybook/write',
templateUrl: 'storybook/views/write.html'
})
.state('list', {
url: '/storybook/list',
templateUrl: 'storybook/views/list.html'
})
.state('cta', {
url: '/storybook/cta',
templateUrl: 'storybook/views/cta.html'
})
.state('edit', {
url: '/storybook/edit/{bookId}/',
templateUrl: 'storybook/views/edit.html'
});
}
]);
| eddotman/attobyte | packages/storybook/public/routes/storybook.js | JavaScript | mit | 830 |
var myHue,sat;
function setup() {
createCanvas(400,400);
}
function draw() {
noStroke();
colorMode(HSB, width);
for (myHue = 0; myHue < width; myHue++) {
for (sat = 0; sat < width; sat++) {
stroke(myHue, sat, sat);
point(myHue, sat);
}
}
} | mateohdzal/MateoHernandez-CreativeCoding | Week 4/Gay-Sad/sketch.js | JavaScript | mit | 257 |
'use strict';
const assert = require('assert');
const Browscap = require('../src/index.js');
suite('checking for issue 1972. (2 tests)', function () {
test('issue-1972-A ["Mozilla/5.0 (compatible; localsearch-web/2.0; +http://www.localsearch.ch/en/legal-notice)"]', function () {
const browscap = new Browscap();
const browser = browscap.getBrowser('Mozilla/5.0 (compatible; localsearch-web/2.0; +http://www.localsearch.ch/en/legal-notice)');
assert.strictEqual(browser['Comment'], 'Search Engines', 'Expected actual "Comment" to be \'Search Engines\' (was \'' + browser['Comment'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser'], 'localsearch', 'Expected actual "Browser" to be \'localsearch\' (was \'' + browser['Browser'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Type'], 'Bot/Crawler', 'Expected actual "Browser_Type" to be \'Bot/Crawler\' (was \'' + browser['Browser_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Bits'], '0', 'Expected actual "Browser_Bits" to be \'0\' (was \'' + browser['Browser_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Maker'], 'unknown', 'Expected actual "Browser_Maker" to be \'unknown\' (was \'' + browser['Browser_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Modus'], 'unknown', 'Expected actual "Browser_Modus" to be \'unknown\' (was \'' + browser['Browser_Modus'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Version'], '2.0', 'Expected actual "Version" to be \'2.0\' (was \'' + browser['Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform'], 'unknown', 'Expected actual "Platform" to be \'unknown\' (was \'' + browser['Platform'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Version'], 'unknown', 'Expected actual "Platform_Version" to be \'unknown\' (was \'' + browser['Platform_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Description'], 'unknown', 'Expected actual "Platform_Description" to be \'unknown\' (was \'' + browser['Platform_Description'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Bits'], '0', 'Expected actual "Platform_Bits" to be \'0\' (was \'' + browser['Platform_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Maker'], 'unknown', 'Expected actual "Platform_Maker" to be \'unknown\' (was \'' + browser['Platform_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Alpha'], false, 'Expected actual "Alpha" to be false (was \'' + browser['Alpha'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Beta'], false, 'Expected actual "Beta" to be false (was \'' + browser['Beta'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Frames'], false, 'Expected actual "Frames" to be false (was \'' + browser['Frames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['IFrames'], false, 'Expected actual "IFrames" to be false (was \'' + browser['IFrames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Tables'], false, 'Expected actual "Tables" to be false (was \'' + browser['Tables'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Cookies'], false, 'Expected actual "Cookies" to be false (was \'' + browser['Cookies'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['JavaScript'], false, 'Expected actual "JavaScript" to be false (was \'' + browser['JavaScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['VBScript'], false, 'Expected actual "VBScript" to be false (was \'' + browser['VBScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['JavaApplets'], false, 'Expected actual "JavaApplets" to be false (was \'' + browser['JavaApplets'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isSyndicationReader'], false, 'Expected actual "isSyndicationReader" to be false (was \'' + browser['isSyndicationReader'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isFake'], false, 'Expected actual "isFake" to be false (was \'' + browser['isFake'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isAnonymized'], false, 'Expected actual "isAnonymized" to be false (was \'' + browser['isAnonymized'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isModified'], false, 'Expected actual "isModified" to be false (was \'' + browser['isModified'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['CssVersion'], '0', 'Expected actual "CssVersion" to be \'0\' (was \'' + browser['CssVersion'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Name'], 'unknown', 'Expected actual "Device_Name" to be \'unknown\' (was \'' + browser['Device_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Maker'], 'unknown', 'Expected actual "Device_Maker" to be \'unknown\' (was \'' + browser['Device_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Type'], 'unknown', 'Expected actual "Device_Type" to be \'unknown\' (was \'' + browser['Device_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Pointing_Method'], 'unknown', 'Expected actual "Device_Pointing_Method" to be \'unknown\' (was \'' + browser['Device_Pointing_Method'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Code_Name'], 'unknown', 'Expected actual "Device_Code_Name" to be \'unknown\' (was \'' + browser['Device_Code_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Brand_Name'], 'unknown', 'Expected actual "Device_Brand_Name" to be \'unknown\' (was \'' + browser['Device_Brand_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Name'], 'unknown', 'Expected actual "RenderingEngine_Name" to be \'unknown\' (was \'' + browser['RenderingEngine_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Version'], 'unknown', 'Expected actual "RenderingEngine_Version" to be \'unknown\' (was \'' + browser['RenderingEngine_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Maker'], 'unknown', 'Expected actual "RenderingEngine_Maker" to be \'unknown\' (was \'' + browser['RenderingEngine_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
});
test('issue-1972-B ["Mozilla/5.0 (X11; Datanyze; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"]', function () {
const browscap = new Browscap();
const browser = browscap.getBrowser('Mozilla/5.0 (X11; Datanyze; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36');
assert.strictEqual(browser['Comment'], 'Data Mining', 'Expected actual "Comment" to be \'Data Mining\' (was \'' + browser['Comment'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser'], 'Datanyze', 'Expected actual "Browser" to be \'Datanyze\' (was \'' + browser['Browser'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Type'], 'Bot/Crawler', 'Expected actual "Browser_Type" to be \'Bot/Crawler\' (was \'' + browser['Browser_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Bits'], '64', 'Expected actual "Browser_Bits" to be \'64\' (was \'' + browser['Browser_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Maker'], 'unknown', 'Expected actual "Browser_Maker" to be \'unknown\' (was \'' + browser['Browser_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Modus'], 'unknown', 'Expected actual "Browser_Modus" to be \'unknown\' (was \'' + browser['Browser_Modus'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Version'], '0.0', 'Expected actual "Version" to be \'0.0\' (was \'' + browser['Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform'], 'Linux', 'Expected actual "Platform" to be \'Linux\' (was \'' + browser['Platform'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Version'], 'unknown', 'Expected actual "Platform_Version" to be \'unknown\' (was \'' + browser['Platform_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Description'], 'Linux', 'Expected actual "Platform_Description" to be \'Linux\' (was \'' + browser['Platform_Description'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Bits'], '64', 'Expected actual "Platform_Bits" to be \'64\' (was \'' + browser['Platform_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Maker'], 'Linux Foundation', 'Expected actual "Platform_Maker" to be \'Linux Foundation\' (was \'' + browser['Platform_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Alpha'], false, 'Expected actual "Alpha" to be false (was \'' + browser['Alpha'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Beta'], false, 'Expected actual "Beta" to be false (was \'' + browser['Beta'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Frames'], true, 'Expected actual "Frames" to be true (was \'' + browser['Frames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['IFrames'], true, 'Expected actual "IFrames" to be true (was \'' + browser['IFrames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Tables'], true, 'Expected actual "Tables" to be true (was \'' + browser['Tables'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Cookies'], true, 'Expected actual "Cookies" to be true (was \'' + browser['Cookies'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['JavaScript'], true, 'Expected actual "JavaScript" to be true (was \'' + browser['JavaScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['VBScript'], false, 'Expected actual "VBScript" to be false (was \'' + browser['VBScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['JavaApplets'], false, 'Expected actual "JavaApplets" to be false (was \'' + browser['JavaApplets'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isSyndicationReader'], false, 'Expected actual "isSyndicationReader" to be false (was \'' + browser['isSyndicationReader'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isFake'], false, 'Expected actual "isFake" to be false (was \'' + browser['isFake'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isAnonymized'], false, 'Expected actual "isAnonymized" to be false (was \'' + browser['isAnonymized'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isModified'], false, 'Expected actual "isModified" to be false (was \'' + browser['isModified'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['CssVersion'], '3', 'Expected actual "CssVersion" to be \'3\' (was \'' + browser['CssVersion'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Name'], 'Linux Desktop', 'Expected actual "Device_Name" to be \'Linux Desktop\' (was \'' + browser['Device_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Maker'], 'unknown', 'Expected actual "Device_Maker" to be \'unknown\' (was \'' + browser['Device_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Type'], 'Desktop', 'Expected actual "Device_Type" to be \'Desktop\' (was \'' + browser['Device_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Pointing_Method'], 'mouse', 'Expected actual "Device_Pointing_Method" to be \'mouse\' (was \'' + browser['Device_Pointing_Method'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Code_Name'], 'Linux Desktop', 'Expected actual "Device_Code_Name" to be \'Linux Desktop\' (was \'' + browser['Device_Code_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Brand_Name'], 'unknown', 'Expected actual "Device_Brand_Name" to be \'unknown\' (was \'' + browser['Device_Brand_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Name'], 'Blink', 'Expected actual "RenderingEngine_Name" to be \'Blink\' (was \'' + browser['RenderingEngine_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Version'], 'unknown', 'Expected actual "RenderingEngine_Version" to be \'unknown\' (was \'' + browser['RenderingEngine_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Maker'], 'Google Inc', 'Expected actual "RenderingEngine_Maker" to be \'Google Inc\' (was \'' + browser['RenderingEngine_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
});
});
| mimmi20/browscap-js | test/issue-1972.js | JavaScript | mit | 15,019 |
function CustomMarker(latlng, map, text, cssClass) {
this.latlng_ = latlng;
this.text_ = text;
this.cssClass_ = cssClass;
this.offset_ = 12;
// Once the LatLng and text are set, add the overlay to the map. This will
// trigger a call to panes_changed which should in turn call draw.
this.setMap(map);
}
CustomMarker.prototype = new google.maps.OverlayView();
CustomMarker.prototype.draw = function() {
var me = this;
// Check if the div has been created.
var div = this.div_;
if (!div) {
// Create a overlay text DIV
div = this.div_ = document.createElement('DIV');
// Create the DIV representing our CustomMarker
div.style.position = "absolute";
div.style.paddingLeft = "0px";
div.style.cursor = 'pointer';
div.setAttribute('class', this.cssClass_);
var p = document.createElement("p");
p.appendChild(document.createTextNode(this.text_));
div.appendChild(p);
google.maps.event.addDomListener(div, "click", function(event) {
google.maps.event.trigger(me, "click");
});
google.maps.event.addDomListener(div, "mouseover", function(event) {
google.maps.event.trigger(me, "mouseover");
});
google.maps.event.addDomListener(div, "mouseout", function(event) {
google.maps.event.trigger(me, "mouseout");
});
// Then add the overlay to the DOM
var panes = this.getPanes();
panes.overlayImage.appendChild(div);
}
// Position the overlay
var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
if (point) {
div.style.left = point.x - this.offset_ + 'px';
div.style.top = point.y - this.offset_ + 'px';
}
};
CustomMarker.prototype.remove = function() {
// Check if the overlay was on the map and needs to be removed.
if (this.div_) {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
CustomMarker.prototype.getPosition = function() {
return this.latlng_;
}; | danagerous/network-map | javascript/CustomMarker.js | JavaScript | mit | 2,073 |
var _ = require('underscore'),
request = require('request'),
log = require('../log/log'),
conf = require('../../conf');
function harvest(task) {
var queen = conf.queen,
host = queen.host,
port = queen.port,
secret = queen.secret,
api = 'http://' + host + ':' + port + '/task?secret=' + secret;
// 移除不必要的内容
delete task.grab;
delete task.done;
request({
method: 'PUT',
url: api,
body: task,
json: true
}, function (err, res, body) {
if (err) {
log.error('TASK_HARVEST_ERROR', err, res, body);
}
});
}
module.exports = harvest; | ninozhang/bee-worker | components/harvest/harvest.js | JavaScript | mit | 682 |
/*
* jQuery autoResize (textarea auto-resizer)
* @copyright James Padolsey http://james.padolsey.com
* @version 1.04
*/
(function($){
$.fn.autoResize = function(options) {
var settings = $.extend({
onResize : function(){},
animate : true,
animateDuration : 100,
animateCallback : function(){},
extraSpace : 12
}, options);
this.filter('textarea').each(function(){
if ($(this).data("initialized")) return;
$(this).data("initialized", true);
var textarea = $(this).css({resize:'none','overflow-y':'hidden'}),
origHeight = textarea.height() - settings.extraSpace,
clone = (function(){
var props = ['height','width','lineHeight','textDecoration','letterSpacing'],
propOb = {};
$.each(props, function(i, prop){
propOb[prop] = textarea.css(prop);
});
return textarea.clone().removeAttr('id').removeAttr('name').css({
position: 'absolute',
top: 0,
left: -9999
}).css(propOb).attr('tabIndex','-1').insertBefore(textarea);
})(),
lastScrollTop = null,
updateSize = function() {
clone.height(0).val(textarea.val()).scrollTop(10000);
var scrollTop = Math.max(clone.scrollTop(), origHeight) + settings.extraSpace,
toChange = textarea.add(clone);
if (lastScrollTop === scrollTop) { return; }
lastScrollTop = scrollTop;
settings.onResize.call(this);
settings.animate && textarea.css('display') === 'block' ?
toChange.stop().animate({height:scrollTop}, settings.animateDuration, settings.animateCallback)
: toChange.height(scrollTop);
};
textarea
.unbind('.dynSiz')
.bind('keyup.dynSiz', updateSize)
.bind('keydown.dynSiz', updateSize)
.bind('change.dynSiz', updateSize);
updateSize();
});
return this;
};
})(jQuery); | qmagico/cdn | static/js/autotextbox-resizer.js | JavaScript | mit | 2,345 |
/**
* Abstract action strategy
* @constructor
*/
function ActionStrategy() {
}
/**
* Create action e.g mail, push, http call
* @param actionType
* @param data
* @param cb
*/
ActionStrategy.prototype.createAction = function (actionType, data, cb) {
throw new Error("should be implemented in subclasses");
};
/**
* exports
*/
module.exports = ActionStrategy; | ziyasal/watch-tower | app/lib/action-strategies/action-strategy.js | JavaScript | mit | 373 |
var React = require('react');
var NotFoundPage = React.createClass({
render: function(){
return (
<h2>Page Not Found.</h2>
);
}
});
module.exports = NotFoundPage;
| fatsheepcn/react-magazine | src/scripts/pages/NotFoundPage.js | JavaScript | mit | 212 |
"use strict";
var log4js = require('log4js');
var logger = log4js.getLogger("base");
var EntityResult = (function () {
function EntityResult() {
}
;
EntityResult.prototype.getRequestResult = function () {
if (this.data) {
var retValue = { d: {} };
retValue.d = this.data;
for (var prop in retValue.d) {
if (retValue.d[prop] instanceof Date) {
retValue.d[prop] = "/Date(" + retValue.d[prop].getTime() + ")/";
}
else {
this.handleDateExpandedProperties(retValue.d[prop]);
}
}
return retValue;
}
else {
var retValue2 = { value: {} };
retValue2.value = this.value;
return retValue2;
}
};
;
EntityResult.prototype.handleDateExpandedProperties = function (oExpanded) {
if (oExpanded instanceof Array) {
for (var expanded in oExpanded) {
for (var property in oExpanded[expanded]) {
if (oExpanded[expanded][property] instanceof Date) {
oExpanded[expanded][property] = "/Date(" + oExpanded[expanded][property].getTime() + ")/";
}
else {
if (oExpanded[expanded][property] instanceof Array || oExpanded[expanded][property] instanceof Object) {
this.handleDateExpandedProperties(oExpanded[expanded][property]);
}
}
}
}
}
else if (oExpanded instanceof Object) {
for (var property in oExpanded) {
if (oExpanded[property] instanceof Date) {
oExpanded[property] = "/Date(" + oExpanded[property].getTime() + ")/";
}
else {
if (oExpanded[property] instanceof Array || oExpanded[property] instanceof Object) {
this.handleDateExpandedProperties(oExpanded[property]);
}
}
}
}
};
return EntityResult;
}());
exports.EntityResult = EntityResult;
var BaseRequestHandler = (function () {
function BaseRequestHandler() {
}
BaseRequestHandler.prototype.setConfig = function (config) {
_setConfig.call(this, config);
};
;
BaseRequestHandler.prototype.setODataVersion = function (res, version) {
if (!version) {
version = "4.0";
}
if (version === "4.0") {
res.set('OData-Version', version);
}
else if (version === "2.0") {
res.set('dataserviceversion', version);
}
};
BaseRequestHandler.prototype.handleError = function (err, res) {
if (typeof err === 'object') {
console.error(err);
res.status(500).send(err.toString());
}
else if (typeof err === 'number') {
res.sendStatus(err);
}
else {
console.error('undefined error');
res.sendStatus(500);
}
};
return BaseRequestHandler;
}());
exports.BaseRequestHandler = BaseRequestHandler;
function _setConfig(config) {
logger.info("component config set to %s", JSON.stringify(config, null, '\t'));
this.oDataServerConfig = config;
}
//# sourceMappingURL=BaseRequestHandler.js.map | htammen/n-odata-server | lib/base/BaseRequestHandler.js | JavaScript | mit | 3,448 |
$(function() {
MobilePages.page('home')
.addProperty(
'init',
function init() {
});
MobilePages.page('second')
.addProperty(
'init',
function init() {
});
}); | tackk/MobilePages | example/js/app.js | JavaScript | mit | 257 |
var gulp = require('gulp'),
browserSync = require('browser-sync'),
sass = require('gulp-sass'),
order = require('gulp-order'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify');
var paths = {
images: 'images/',
css: 'css/',
sass: 'sass/',
js: 'js/',
proxy: 'http://localhost/site/'
};
gulp.task('serve', ['sass', 'minify-js'],function() {
browserSync.init({
proxy: paths.proxy
});
gulp.watch(['**/*', '!node_modules/**']).on('change', function() {
browserSync.reload({stream: true});
});
gulp.watch(paths.sass+'**/*.scss',['sass']);
gulp.watch(paths.js+'src/**/*.js', ['minify-js']);
});
gulp.task('sass', function() {
return gulp.src(paths.sass+'**/*.scss')
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
.pipe(gulp.dest(paths.css))
.pipe(browserSync.stream());
});
gulp.task('minify-js', function() {
return gulp.src(paths.js+'src/**/*.js')
.pipe(order([
'libs/jquery-3.2.1.min.js',
'libs/*.js',
'**/*.js'
]))
.pipe(concat('build.js'))
.pipe(uglify())
.pipe(gulp.dest(paths.js))
.pipe(browserSync.stream());
});
gulp.task('default', ['serve']); | rodrigocichetto/site | user/themes/cichetto/gulpfile.js | JavaScript | mit | 1,319 |
'use strict';
var util = require('util'),
ScriptBase = require('../script-base.js'),
path = require('path'),
angularUtils = require('../util.js');
var Generator = module.exports = function Generator() {
ScriptBase.apply(this, arguments);
this.sourceRoot(path.join(__dirname, '../templates'));
if (typeof this.env.options.appPath === 'undefined') {
try {
this.env.options.appPath = require(path.join(process.cwd(), 'bower.json')).appPath;
} catch (e) {
}
this.env.options.appPath = this.env.options.appPath || 'app';
}
};
util.inherits(Generator, ScriptBase);
Generator.prototype.askForConstantValue = function askFor() {
var cb = this.async();
this.prompt([{
type: 'input',
name: 'constant',
message: 'Enter the value for the constant \'' + this.name + '\' : '
}], function (props) {
this.constantValue = props.constant;
if (typeof (this.constantValue) === 'string') {
this.constantValue = '\'' + this.constantValue + '\'';
}
cb();
}.bind(this));
};
Generator.prototype.createConstant = function createViewFiles() {
var config = {
file: path.join(
this.env.options.appPath,
'js/app.js'
),
needle: '/* ---> Do not delete this comment (Constants) <--- */',
splicable: [
'app.constant(\'' + this.name + '\', ' + this.constantValue + ');'
]
};
angularUtils.rewriteFile(config);
console.log('Added Constant : ' + this.name);
};
| aamirshah/generator-boom | constant/index.js | JavaScript | mit | 1,581 |
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Thrown when an optimistic lock cannot be used in query builder.
*/
var OptimisticLockCanNotBeUsedError = /** @class */ (function (_super) {
__extends(OptimisticLockCanNotBeUsedError, _super);
function OptimisticLockCanNotBeUsedError() {
var _this = _super.call(this) || this;
_this.name = "OptimisticLockCanNotBeUsedError";
Object.setPrototypeOf(_this, OptimisticLockCanNotBeUsedError.prototype);
_this.message = "The optimistic lock can be used only with getOne() method.";
return _this;
}
return OptimisticLockCanNotBeUsedError;
}(Error));
exports.OptimisticLockCanNotBeUsedError = OptimisticLockCanNotBeUsedError;
//# sourceMappingURL=OptimisticLockCanNotBeUsedError.js.map
| JacksonLee2019/CS341-VolunteerSchedule | node_modules/typeorm/error/OptimisticLockCanNotBeUsedError.js | JavaScript | mit | 1,312 |
const express = require('express'),
Post = require('../models/post'),
axios = require('axios')
// Functions imported with 'require' must be set to var, not const.
var checkAuth = require('./index.js').checkAuth
/* apoc require statement must always go after the explicit loading of the
* .env file */
require('dotenv').load()
const apoc = require('apoc')
module.exports = (() => {
'use strict';
const router = express.Router();
const postsProjection = {
__v: false,
}
router.get('/', checkAuth, (req, res) => {
Post.find({}, postsProjection, (err, posts) => {
if (err) throw err
else {
res.json({ posts })
}
})
})
/* Endpoint: Delete single post based on new attempt. */
router.get('/delete/:id', checkAuth, (req, res) => {
Post.remove( Post.findById(req.params.id), postsProjection,
(err, result) => {
console.log('Endpoint: Delete Post')
if (err) {
console.log('Error in delete post')
res.status(204).send()
}
else {
console.log('Success in Delete Post') //, result)
res.status(200).send()
//res.json({result})
}
})
})
/* Endpoint: Delete Many Posts Based on */
/* not working yet */
/* ~TEMP~ Delete Many Posts */
router.post('/deleteMany', checkAuth, (req, res) => {
/* json data */
var errorsInDeleting=false
console.log('Endpoint: Delete Many Posts')
for(var key in req.body.deleteIds) {
var idToDelete = req.body.deleteIds[key]
console.log('ID : ', idToDelete )
/* Delete One ID */
Post.remove(Post.findById(idToDelete), postsProjection,
(err, result) => {
if (err) {
console.log('Failure (Error): Delete Post ', err)
//res.status(204).send()//No record
}
if (!result) {//.length<1) {//} || result.length<1) {
console.log('FAIL: No Results')
console.log('FAIL: Did Not Delete ID: ', idToDelete)
errorsInDeleting=true
//res.status(204).send()//No record
}
else {
console.log('Success in Delete Post')//, result)
console.log('Deleted Post ID:', idToDelete )
//res.status(200).send()
}
})
/* try find [2] */
// Post.find( Post.findById( idToDelete ) , function(err, posts) {
// if (err) throw err
// if (!posts || (posts.length<1) ) {
// console.log('Total Posts Found: ', posts.length)
// console.log('No Post Found matching the keyword.')
// //res.json({ posts })
// }
// else {
// console.log('Total Posts Found: ', posts.length)
// console.log('')
// console.log('POSTS: ')
// console.log(' ',posts)
// Post.remove( Post.findById( idToDelete ) ,(err, result) => {} )
// //res.json({ posts })
// }
// })
/* */
} //End for
res.json({})
})
/* Used by toro-net */
router.post('/create', (req, res) => {
const newPost = new Post({
username: req.user.username,
title: req.body.title,
body: req.body.body,
createdOn: new Date
})
Post.create(newPost, (err) => {
if (err) {
console.log('Error detected: ', err)
res.status(409).send()
}
else {
console.log('Post created successfully!')
res.redirect('/')
}
})
})
/* Used by test-script */
router.post('/create/api', (req, res) => {
console.log(req.body)
const newPost = new Post({
username: req.body.username,
title: req.body.title,
body: req.body.body,
createdOn: new Date
})
Post.create(newPost, (err) => {
if (err) {
console.log('Error detected: ', err)
res.status(409).send()
}
else {
console.log('Post created successfully!')
res.redirect('/')
}
})
})
router.put('/update/:id', checkAuth, (req, res, next) => {
console.log("EndPoint : update Post")
Post.update(Post.findById(req.params.id), req.body, (err, result) => {
if (err) {
console.log("Post record doesn't exist!")
res.status(204).send()
}
else {
console.log("success")
res.status(200).send()
}
})
})
/* The User object returned by passport does not have userId, switched
* to username */
router.get('/list/:username', checkAuth, (req, res) => {
const queryString =
`MATCH (u:User {username: '${req.params['username']}'})-[r:isFriends*1..1]-(v:User)
WHERE u <> v
RETURN r`
const query = apoc.query(queryString)
query.exec().then((result) => {
var resultMap = new Map()
/* Do not change variables back to const!! */
for (var i = 0; i < result[0]['data'].length; i++) {
var dataList = result[0]['data'][i]['row'][0]
for (var j = 0; j < dataList.length; j++) {
var rowNames = dataList[j]['connects'].split('<-->')
rowNames = rowNames.sort()
if ( resultMap.has(rowNames[0]) ) {
if ( !resultMap.get(rowNames[0]).includes(rowNames[1]) ) {
resultMap.get(rowNames[0]).push(rowNames[1])
}
} else {
resultMap.set(rowNames[0], [rowNames[1]])
}
}
}
var friendList = []
resultMap.forEach((value, key) => {
friendList.push(value)
})
friendList[0].push(req.params['username'])
Post.find().where('username').in(friendList[0]).exec(function (err, records) {
if (err) {
console.log("Error: ", err)
res.status(400).send()
} else {
console.log('Post Successfully Retrived')
console.log(records)
res.send(records)
}
})
// Post.find({ 'username': req.params.username }, (err, result) => {
// if (err) {
// console.log("Error: ", err)
// res.status(200).send()
// }
// else {
// console.log('Post Successfully Retrived')
// console.log(result)
// res.send(result)
// }
// })
}, (fail) => {
console.log(fail)
})
})
return router
})()
| ErnestUrzua/csc583-midterm | server/routes/posts.js | JavaScript | mit | 6,326 |
/* Read an article */
(function () {
'use strict';
var uid = location.pathname.split('/')[2];
var $articleTitle = $('#articleTitle');
var $title = $('title');
var $target = $('.target');
var $zen = $('#zen');
var $editBtn = $('.fixed-action-btn');
var $retypeName = $('#retypeName');
var $delete = $('.modal-footer button.disabled');
// Retrieve the article
$.get('/articles/' + uid)
.done(function (res) {
$title.append(' - ' + res.title);
$articleTitle.text(res.title);
$retypeName.attr('placeholder', res.title);
$retypeName.next().addClass('active');
if (!res.content) res.content = '*Aucun contenu pour le moment. Vous pouvez éditer cet article via le menu.*';
var html = marked(res.content, {
breaks: true,
sanitize: true,
highlight: function (code) {
return hljs.highlightAuto(code).value;
}
});
$target.html(html);
// Fix https://github.com/chjj/marked/issues/255
$('pre code').addClass('hljs');
// KateX
renderMathInElement($target[0]);
})
.fail(function (res) {
location.href = '/error/' + res.status;
});
// Zen click
$zen.click(function () {
var isEnabled = !$zen.children().hasClass('mdi-action-visibility');
if (!isEnabled) {
$zen.css('opacity', 0.6);
$editBtn.fadeOut();
$zen.children().removeClass('mdi-action-visibility').addClass('mdi-action-visibility-off');
$('.read > .row:first-child').slideUp();
$('body').attr('style', 'background-color: #333;color: rgba(255, 255, 255, 0.6) !important');
} else {
$zen.css('opacity', 1);
$editBtn.fadeIn();
$zen.children().removeClass('mdi-action-visibility-off').addClass('mdi-action-visibility');
$('.read > .row:first-child').slideDown();
$('body').removeAttr('style');
}
});
// Remove article
$retypeName.keyup(function () {
if ($retypeName.val() === $retypeName.attr('placeholder')) {
$retypeName.removeClass('invalid').addClass('valid');
$delete.removeClass('disabled').removeAttr('disabled');
} else {
$retypeName.removeClass('valid').addClass('invalid');
$delete.addClass('disabled').attr('disabled', '');
}
});
$delete.click(function () {
$delete.addClass('disabeld').attr('disabled', '');
$.ajax({ url: '/articles/' + uid, type: 'DELETE' })
.done(function () {
location.href = '/';
})
.fail(function (res) {
location.href = '/error/' + res.status;
});
});
// Enable zen tooltip and modals
$('.tooltipped').tooltip();
$('.modal-trigger').leanModal();
}());
| ungdev/wiki | public/js/read.js | JavaScript | mit | 3,071 |
'use strict';
const {
validateRequest,
validateRequestWithBody,
validateBody,
webhook,
} = require('../lib/webhooks/webhooks');
const httpMocks = require('node-mocks-http');
const url = require('url');
const defaultParams = {
CallSid: 'CA1234567890ABCDE',
Caller: '+14158675309',
Digits: '1234',
From: '+14158675309',
To: '+18005551212',
};
const token = '12345';
const defaultSignature = 'RSOYDt4T1cUTdK1PDd93/VVr8B8=';
const requestUrl = 'https://mycompany.com/myapp.php?foo=1&bar=2';
const body = '{"property": "value", "boolean": true}';
const bodySignature = '0a1ff7634d9ab3b95db5c9a2dfe9416e41502b283a80c7cf19632632f96e6620';
const requestUrlWithHash = requestUrl + '&bodySHA256=' + bodySignature;
const requestUrlWithHashSignature = 'a9nBmqA0ju/hNViExpshrM61xv4=';
const requestUrlWithHashSignatureEmptyBody = 'Ldidvp12m26NI7eqEvxnEpkd9Hc=';
const bodySignatureEmpty = '44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a';
const requestUrlWithHashEmpty = requestUrl + '&bodySHA256=' + bodySignatureEmpty;
describe('Request validation', () => {
it('should succeed with the correct signature', () => {
const isValid = validateRequest(token, defaultSignature, requestUrl, defaultParams);
expect(isValid).toBeTruthy();
});
it('should fail when given the wrong signature', () => {
const isValid = validateRequest(token, 'WRONG_SIGNATURE', requestUrl, defaultParams);
expect(isValid).toBeFalsy();
});
it('should validate post body correctly', () => {
const isValid = validateBody(body, bodySignature);
expect(isValid).toBeTruthy();
});
it('should fail to validate with wrong sha', () => {
const isValid = validateBody(body, 'WRONG_HASH');
expect(isValid).toBeFalsy();
});
it('should validate request body when given', () => {
const isValid = validateRequestWithBody(token, requestUrlWithHashSignature, requestUrlWithHash, body);
expect(isValid).toBeTruthy();
});
it('should validate request body when empty', () => {
const isValid = validateRequestWithBody(token, requestUrlWithHashSignatureEmptyBody, requestUrlWithHashEmpty, '{}');
expect(isValid).toBeTruthy();
});
it('should validate request body with only sha param', () => {
const sig = bodySignature.replace('+', '%2B').replace('=', '%3D');
const shortUrl = 'https://mycompany.com/myapp.php?bodySHA256=' + sig;
const isValid = validateRequestWithBody(token, 'y77kIzt2vzLz71DgmJGsen2scGs=', shortUrl, body);
expect(isValid).toBeTruthy();
});
it('should fail validation if given body but no bodySHA256 param', () => {
const isValid = validateRequestWithBody(token, defaultSignature, requestUrl, defaultParams, body);
expect(isValid).toBeFalsy();
});
it('should fail when signature undefined', () => {
const isValid = validateRequest(token, undefined, requestUrl, defaultParams);
expect(isValid).toBeFalsy();
});
it('should validate https urls with ports by stripping them', () => {
const requestUrlWithPort = requestUrl.replace('.com', '.com:1234');
const isValid = validateRequest(token, defaultSignature, requestUrlWithPort, defaultParams);
expect(isValid).toBeTruthy();
});
it('should validate http urls with ports', () => {
let requestUrlWithPort = requestUrl.replace('.com', '.com:1234');
requestUrlWithPort = requestUrlWithPort.replace('https', 'http');
const signature = 'Zmvh+3yNM1Phv2jhDCwEM3q5ebU='; // hash of http url with port 1234
const isValid = validateRequest(token, signature, requestUrlWithPort, defaultParams);
expect(isValid).toBeTruthy();
});
it('should validate https urls without ports by adding standard port 443', () => {
const signature = 'kvajT1Ptam85bY51eRf/AJRuM3w='; // hash of https url with port 443
const isValid = validateRequest(token, signature, requestUrl, defaultParams);
expect(isValid).toBeTruthy();
});
it('should validate http urls without ports by adding standard port 80', () => {
const requestUrlHttp = requestUrl.replace('https', 'http');
const signature = '0ZXoZLH/DfblKGATFgpif+LLRf4='; // hash of http url with port 80
const isValid = validateRequest(token, signature, requestUrlHttp, defaultParams);
expect(isValid).toBeTruthy();
});
it('should validate urls with credentials', () => {
const urlWithCreds = 'https://user:pass@mycompany.com/myapp.php?foo=1&bar=2';
const signature = 'CukzLTc1tT5dXEDIHm/tKBanW10='; // hash of this url
const isValid = validateRequest(token, signature, urlWithCreds, defaultParams);
expect(isValid).toBeTruthy();
});
it('should validate urls with just username', () => {
const urlWithCreds = 'https://user@mycompany.com/myapp.php?foo=1&bar=2';
const signature = '2YRLlVAflCqxaNicjMpJcSTgzSs='; // hash of this url
const isValid = validateRequest(token, signature, urlWithCreds, defaultParams);
expect(isValid).toBeTruthy();
});
it('should validate urls with credentials by adding port', () => {
const urlWithCreds = 'https://user:pass@mycompany.com/myapp.php?foo=1&bar=2';
const signature = 'ZQFR1PTIZXF2MXB8ZnKCvnnA+rI='; // hash of this url with port 443
const isValid = validateRequest(token, signature, urlWithCreds, defaultParams);
expect(isValid).toBeTruthy();
});
it('should validate urls with special characters', () => {
const specialRequestUrl = requestUrl + '&Body=It\'s+amazing';
const signature = 'dsq4Ehbj6cs+KdTkpF5sSSplOWw=';
const isValid = validateRequest(token, signature, specialRequestUrl, defaultParams);
expect(isValid).toBeTruthy();
});
it('should validate request body with an array parameter', () => {
const paramsWithArray = { 'MessagingBinding.Address': ['+1325xxxxxxx', '+1415xxxxxxx'] };
const signature = '83O6e2vORAoJHUNzJjDWN1jz+BA=';
const isValid = validateRequest(token, signature, requestUrl, paramsWithArray);
expect(isValid).toBeTruthy();
});
});
describe('Request validation middleware', () => {
const fullUrl = new url.URL(requestUrl);
const defaultRequest = {
method: 'POST',
protocol: fullUrl.protocol,
host: fullUrl.host,
headers: {
'X-Twilio-Signature': defaultSignature,
host: fullUrl.host,
},
url: fullUrl.pathname + fullUrl.search,
originalUrl: fullUrl.pathname + fullUrl.search,
body: defaultParams,
};
const defaultRequestWithoutTwilioSignature = {
method: 'POST',
protocol: fullUrl.protocol,
host: fullUrl.host,
headers: {
host: fullUrl.host,
},
url: fullUrl.pathname + fullUrl.search,
originalUrl: fullUrl.pathname + fullUrl.search,
body: defaultParams,
};
const middleware = webhook(token);
let response;
beforeEach(() => {
response = httpMocks.createResponse();
});
it('should validate standard requests', done => {
const request = httpMocks.createRequest(defaultRequest);
middleware(request, response, () => {
// This test will only pass if the middleware calls next().
done();
});
expect(response.statusCode).toEqual(200);
});
it('should send 403 for invalid signatures', () => {
const newUrl = fullUrl.pathname + fullUrl.search + '&somethingUnexpected=true';
const request = httpMocks.createRequest(Object.assign({}, defaultRequest, {
originalUrl: newUrl,
}));
middleware(request, response, () => {
expect(true).toBeFalsy();
});
expect(response.statusCode).toEqual(403);
});
it('should bypass validation if given {validate:false}', done => {
const request = httpMocks.createRequest(defaultRequest);
const middleware = webhook(token, {
validate: false,
});
middleware(request, response, () => {
done();
});
expect(response.statusCode).toEqual(200);
});
it('should accept manual host+proto', done => {
const request = httpMocks.createRequest(Object.assign({}, defaultRequest, {
host: 'someothercompany.com',
protocol: 'http',
headers: Object.assign({}, defaultRequest.headers, {
host: 'someothercompany.com',
}),
}));
const middleware = webhook(token, {
host: 'mycompany.com',
protocol: 'https',
});
middleware(request, response, () => {
done();
});
expect(response.statusCode).toEqual(200);
});
it('should accept manual url and override host+proto', done => {
const request = httpMocks.createRequest(Object.assign({}, defaultRequest, {
host: 'someothercompany.com',
protocol: 'http',
headers: Object.assign({}, defaultRequest.headers, {
host: 'someothercompany.com',
}),
}));
const middleware = webhook(token, {
host: 'myothercompany.com',
protocol: 'ftp',
url: requestUrl,
});
middleware(request, response, () => {
done();
});
expect(response.statusCode).toEqual(200);
if (response.statusCode !== 200) {
done();
}
});
it('should validate post body if given a query param', done => {
const request = httpMocks.createRequest(Object.assign({}, defaultRequest, {
originalUrl: requestUrlWithHash.substring(requestUrlWithHash.indexOf('.com/') + 4),
body,
headers: Object.assign({}, defaultRequest.headers, {
'X-Twilio-Signature': requestUrlWithHashSignature,
}),
}));
request.rawBody = body;
middleware(request, response, () => {
done();
});
expect(response.statusCode).toEqual(200);
if (response.statusCode !== 200) {
done();
}
});
it('should fail validation of post body with wrong hash', () => {
const request = httpMocks.createRequest(Object.assign({}, defaultRequest, {
originalUrl: requestUrlWithHash.substring(requestUrlWithHash.indexOf('.com/') + 4).slice(0, -1),
body,
headers: Object.assign({}, defaultRequest.headers, {
'X-Twilio-Signature': requestUrlWithHashSignature,
}),
}));
middleware(request, response, () => {
expect(true).toBeFalsy();
});
expect(response.statusCode).toEqual(403);
});
it('should fail if no twilio signature is provided in the request headers', () => {
const newUrl = fullUrl.pathname + fullUrl.search + '&somethingUnexpected=true';
const request = httpMocks.createRequest(Object.assign({},
defaultRequestWithoutTwilioSignature, {
originalUrl: newUrl,
}));
middleware(request, response, () => {
expect(true).toBeFalsy();
});
expect(response.statusCode).toEqual(400);
});
});
| twilio/twilio-node | spec/validation.spec.js | JavaScript | mit | 10,584 |
/* eslint-disable */
import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, FormattedMessage } from 'react-intl';
import Box from '../Box';
import Button from '../Button';
import FormField from '../FormField';
import Notification from '../Notification';
import Select from '../Select';
import {
createValidator,
passwordValidation,
passwordAgainValidation,
emailValidation,
nameValidation,
capitalizeFirstLetter,
} from '../../core/validation';
const messages = defineMessages({
email: {
id: 'settings.email',
defaultMessage: 'Your current email address',
description: 'Email label in settings',
},
emailNew: {
id: 'settings.emailNew',
defaultMessage: 'New email address',
description: 'Email label in settings for new address',
},
error: {
id: 'action.error',
defaultMessage: 'Action failed. Please retry!',
description: 'Short failure notification ',
},
});
const initState = {
email: '',
errors: {
email: { touched: false },
},
};
const EmailInput = ({
error,
emailStatus,
handleChange,
value,
showEmailField,
}) => {
return (
<fieldset>
{error && (
<div style={{ backgroundColor: 'rgba(255, 50, 77, 0.3)' }}>
<FormattedMessage {...messages.error} />
</div>
)}
<FormField
label={
<FormattedMessage
{...messages[showEmailField ? 'emailNew' : 'email']}
/>
}
error={error}
help={emailStatus}
>
<input
type="text"
onChange={handleChange}
value={value}
name="email"
readOnly={showEmailField === false}
/>
</FormField>
</fieldset>
);
};
export default EmailInput;
| nambawan/g-old | src/components/UserSettings/EmailInput.js | JavaScript | mit | 1,777 |
var _ = require("lodash");
var Stream = require("stream");
function gulpIife(userOptions) {
"use strict";
var defaultOptions = { useStrict: true, trimCode: true, prependSemicolon: true, bindThis: false };
var options = _.merge({}, defaultOptions, userOptions);
var stream = new Stream.Transform({ objectMode: true });
stream._transform = function(file, encoding, callback) {
var contents = String(file.contents);
var wrappedContents = surroundWithIife(contents, options);
file.contents = Buffer(wrappedContents);
callback(null, file);
};
return stream;
}
function surroundWithIife(code, options) {
var args = options.args ? options.args.join(", ") : "",
params = options.params ? options.params.join(", ") : (args !== "" ? args : ""),
bindThis = options.bindThis ? ".bind(this)" : "",
leadingCode = "(function(" + params + ") {\n",
trimmedCode = options.trimCode ? code.trim() : code,
trailingCode = "\n}" + bindThis + "(" + args + "));\n";
if (options.prependSemicolon) {
leadingCode = ";" + leadingCode;
}
if (options.useStrict && !code.match(/^\s*(['"])use strict\1;/)) {
leadingCode += '"use strict";\n\n';
}
return leadingCode + trimmedCode + trailingCode;
}
module.exports = gulpIife;
| bernhardw/gulp-iife | index.js | JavaScript | mit | 1,342 |
import Card from 'components/Card'
import Header from 'components/Header'
import Spinner from 'components/Spinner'
import CmcFilter from 'components/CmcFilter'
import UserBadge from 'components/UserBadge'
import LatestSet from 'components/LatestSet'
import ManaBadge from 'components/ManaBadge'
import LockButton from 'components/LockButton'
import ColorFilter from 'components/ColorFilter'
import CardDetails from 'components/CardDetails'
import ColorButtons from 'components/ColorButtons'
import SearchModule from 'components/SearchModule'
import AllNoneToggle from 'components/AllNoneToggle'
import LoadingScreen from 'components/LoadingScreen'
import CardsSearchList from 'components/CardsSearchList'
import CollectionStats from 'components/CollectionStats'
import MonoMultiToggle from 'components/MonoMultiToggle'
import CardDetailsPopup from 'components/CardDetailsPopup'
export {
Card,
Header,
Spinner,
CmcFilter,
UserBadge,
LatestSet,
ManaBadge,
LockButton,
ColorFilter,
CardDetails,
ColorButtons,
SearchModule,
AllNoneToggle,
LoadingScreen,
CardsSearchList,
CollectionStats,
MonoMultiToggle,
CardDetailsPopup
}
| robertkirsz/magic-cards-manager | src/components/index.js | JavaScript | mit | 1,249 |
Router.map(function (){
this.route('home', {
path: '/'
});
});
this.route('channel', {
path: '/channel/:_id'
});
});
| tamzi/ProjectAmelia | tat/lib/routes.js | JavaScript | mit | 132 |
/* */
(function(process) {
'use strict';
Object.defineProperty(exports, "__esModule", {value: true});
exports.mergeStyles = mergeStyles;
exports.mergeAndPrefix = mergeAndPrefix;
exports.prepareStyles = prepareStyles;
var _autoPrefix = require('../styles/auto-prefix');
var _autoPrefix2 = _interopRequireDefault(_autoPrefix);
var _reactAddonsUpdate = require('react-addons-update');
var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate);
var _warning = require('warning');
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
var reTranslate = /((^|\s)translate(3d|X)?\()(\-?[\d]+)/;
var reSkew = /((^|\s)skew(x|y)?\()\s*(\-?[\d]+)(deg|rad|grad)(,\s*(\-?[\d]+)(deg|rad|grad))?/;
function mergeSingle(objA, objB) {
if (!objA)
return objB;
if (!objB)
return objA;
return (0, _reactAddonsUpdate2.default)(objA, {$merge: objB});
}
function ensureDirection(muiTheme, style) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!style.didFlip, 'You\'re calling ensureDirection() on the same style\n object twice.') : undefined;
style = mergeStyles({didFlip: 'true'}, style);
}
if (!muiTheme || !muiTheme.isRtl)
return style;
var flippedAttributes = {
right: 'left',
left: 'right',
marginRight: 'marginLeft',
marginLeft: 'marginRight',
paddingRight: 'paddingLeft',
paddingLeft: 'paddingRight',
borderRight: 'borderLeft',
borderLeft: 'borderRight'
};
var newStyle = {};
Object.keys(style).forEach(function(attribute) {
var value = style[attribute];
var key = attribute;
if (flippedAttributes.hasOwnProperty(attribute)) {
key = flippedAttributes[attribute];
}
switch (attribute) {
case 'float':
case 'textAlign':
if (value === 'right') {
value = 'left';
} else if (value === 'left') {
value = 'right';
}
break;
case 'direction':
if (value === 'ltr') {
value = 'rtl';
} else if (value === 'rtl') {
value = 'ltr';
}
break;
case 'transform':
var matches = undefined;
if (matches = value.match(reTranslate)) {
value = value.replace(matches[0], matches[1] + -parseFloat(matches[4]));
}
if (matches = value.match(reSkew)) {
value = value.replace(matches[0], matches[1] + -parseFloat(matches[4]) + matches[5] + matches[6] ? ',' + -parseFloat(matches[7]) + matches[8] : '');
}
break;
case 'transformOrigin':
if (value.indexOf('right') > -1) {
value = value.replace('right', 'left');
} else if (value.indexOf('left') > -1) {
value = value.replace('left', 'right');
}
break;
}
newStyle[key] = value;
});
return newStyle;
}
function mergeStyles(base) {
for (var _len = arguments.length,
args = Array(_len > 1 ? _len - 1 : 0),
_key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
for (var i = 0; i < args.length; i++) {
if (args[i]) {
base = mergeSingle(base, args[i]);
}
}
return base;
}
function mergeAndPrefix() {
process.env.NODE_ENV !== "production" ? (0, _warning2.default)(false, 'Use of mergeAndPrefix() has been deprecated. ' + 'Please use mergeStyles() for merging styles, and then prepareStyles() for prefixing and ensuring direction.') : undefined;
return _autoPrefix2.default.all(mergeStyles.apply(undefined, arguments));
}
function prepareStyles(muiTheme) {
var style = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
for (var _len2 = arguments.length,
styles = Array(_len2 > 2 ? _len2 - 2 : 0),
_key2 = 2; _key2 < _len2; _key2++) {
styles[_key2 - 2] = arguments[_key2];
}
if (styles) {
style = mergeStyles.apply(undefined, [style].concat(styles));
}
var flipped = ensureDirection(muiTheme, style);
return muiTheme.prefix(flipped);
}
exports.default = {
mergeStyles: mergeStyles,
mergeAndPrefix: mergeAndPrefix,
prepareStyles: prepareStyles
};
})(require('process'));
| nayashooter/ES6_React-Bootstrap | public/jspm_packages/npm/material-ui@0.14.4/lib/utils/styles.js | JavaScript | mit | 4,458 |
import WorkshopCard from './WorkshopCard'
export default WorkshopCard
| eunvanz/handpokemon2 | src/components/WorkshopCard/index.js | JavaScript | mit | 71 |
var Notifications;
(function (Notifications) {
var NotificationsViewModel = (function () {
function NotificationsViewModel() {
this.error = ko.observable();
this.warning = ko.observable();
this.success = ko.observable();
this.errorQueue = $.Topic("message/error");
this.warningQueue = $.Topic("message/warning");
this.infoQueue = $.Topic("message/info");
this.settingsQueue = $.Topic("message/settingsChanged");
this.loaded = ko.observable(false);
this.settingsQueue.subscribe(this.settingsChanged.bind(this));
var s = new Notifications.Settings();
s.useLegacyMessages = false;
s.useToasts = true;
this.settingsQueue.publish(s);
}
NotificationsViewModel.prototype.settingsChanged = function (s) {
this.errorQueue.unsubscribe();
this.warningQueue.unsubscribe();
this.infoQueue.unsubscribe();
if(s.useLegacyMessages) {
this.errorQueue.subscribe(this.error);
this.warningQueue.subscribe(this.warning);
this.infoQueue.subscribe(this.success);
}
if(s.useToasts) {
this.errorQueue.subscribe(toastr.error);
this.warningQueue.subscribe(toastr.warning);
this.infoQueue.subscribe(toastr.success);
}
};
return NotificationsViewModel;
})();
Notifications.NotificationsViewModel = NotificationsViewModel;
NotificationsViewModel.instance = new NotificationsViewModel();
ko.applyBindings(NotificationsViewModel.instance, document.getElementById("messages"));
NotificationsViewModel.instance.loaded(true);
})(Notifications || (Notifications = {}));
| teelahti/TD2013LongRunningTasks | TD2013LongRunningTasks/Scripts/Notifications/NotificationsViewModel.js | JavaScript | mit | 1,837 |
var input = [60, 30, 90, 20, 80, 70, 10, 100, 25, 15, 75, 45];
var barWidth = 40;
var width = (barWidth + 10) * input.length;
var height = 350;
var code = d3.select("#code-text");
var barChart = d3.select(".drawingArea")
.append("svg:svg")
.attr("width", width + 200)
.attr("height", height + 200)
.attr("id", "barChart");
var positions = [];
var textPositions = [];
createRects(input);
//Pivot marker left
var pivotMarkerLeft;
//Pivot marker Right
var pivotMarkerRight;
//Panning
var pan = d3.zoom()
.on("zoom", panning);
barChart.call(pan);
var codeDisplayManager = new CodeDisplayManager('javascript', 'quickSort');
function createRects(data) {
positions = [];
textPositions = [];
barChart.selectAll("rect")
.data(data)
.enter()
.append("svg:rect")
.attr("x", function(d, index) { return index * (width / data.length) + 100; })
.attr("y", function (d) { return height - (d/Math.max.apply(null, data)) * 250 - 50; })
.attr("height", function (d) { return d / Math.max.apply(null, data) * 250; })
.attr("width", barWidth)
.attr("class", function(d, i) { return "element" + i})
.attr("fill", function(d) { return "red"; });
barChart.selectAll("text")
.data(data)
.enter()
.append("text")
.text(function(d) { return d; })
.attr("x", function(d, index) { return index * (width / data.length) + barWidth / 4 + 100; })
.attr("y", height - 30 )
.attr("width", barWidth)
.attr("class", function (d, i) { return "element" + i });
pivotMarkerLeft = barChart.append("polygon")
.attr("fill", "yellow")
.attr("stroke", "blue")
.attr("stroke-width", "2")
.attr("points", "05,30 15,10 25,30")
.attr("opacity", "0")
.attr("id", "pivotMarkerLeft");
pivotMarkerRight = barChart.append("polygon")
.attr("fill", "yellow")
.attr("stroke", "blue")
.attr("stroke-width", "2")
.attr("points", "05,30 15,10 25,30")
.attr("opacity", "0")
.attr("id", "pivotMarkerRight")
for(var i = 0; i < data.length; i++) {
positions.push([i * (width / data.length) + 100, height - (data[i]/Math.max.apply(null, data)) * 250 - 50]);
textPositions.push([i * (width / data.length) + barWidth / 4 + 100, height - 30]);
}
}
function panning() {
barChart.attr("transform", d3.event.transform);
}
function startMedianOfThree() {
codeDisplayManager.loadFunctions('quickSortMedianOfThree', 'partition', 'insertionSort');
codeDisplayManager.changeFunction('quickSortMedianOfThree');
sort(true);
}
function startMedianOfOne() {
codeDisplayManager.loadFunctions('quickSortLeftPivot', 'partition', 'insertionSort');
codeDisplayManager.changeFunction('quickSortLeftPivot');
sort(false);
}
function sort(median) {
$('#barChart').empty();
createRects(input)
var qs = new QuickSort(input.slice());
qs.sort(median);
}
function markPivot(a, pivot, line) {
var text = barChart.selectAll("text").filter(".element" + a);
var translation = getTranslate(text);
var targetX = textPositions[a][0] - 7;
var targetY = textPositions[a][1];
if(pivot == 'left') {
appendAnimation(line, [{ e: '#pivotMarkerLeft', p: { attr: { opacity: 1 }, x: targetX, y: targetY }, o: { duration: 1 } }], codeDisplayManager);
} else {
appendAnimation(line, [{ e: '#pivotMarkerRight', p: { attr: { opacity: 1 }, x: targetX, y: targetY }, o: { duration: 1 } }], codeDisplayManager);
}
return true;
}
function highlightPivot(index) {
removeHighlightPivot();
appendAnimation(null, [{ e: $('.element' + index).filter('rect'), p: { attr: {stroke:'green', 'stroke-width': 5}}, o: {duration:1}}], null);
}
function removeHighlightPivot() {
appendAnimation(null, [{ e: '#barChart rect', p: { attr: { stroke: 'none' } }, o: { duration: 1 } }], null);
}
function swap(a, b, line) {
var elementA = $(".element" + a);
var elementB = $(".element" + b);
appendAnimation(line, [
{ e: elementA.filter("rect"), p: { attr: { x: positions[b][0] } }, o: { duration: 1 } },
{ e: elementA.filter("text"), p: { attr: { x: positions[b][0] + barWidth / 4 } }, o: { duration: 1, position: '-=1' } },
{ e: elementB.filter("rect"), p: { attr: { x: positions[a][0] } }, o: { duration: 1, position: '-=1' } },
{ e: elementB.filter("text"), p: { attr: { x: positions[a][0] + barWidth / 4 } }, o: { duration: 1, position: '-=1' } }
], codeDisplayManager);
elementA.attr('class', 'element' + b);
elementB.attr('class', 'element' + a);
}
function colorPartition(from, to, direction, line) {
var animations = [];
for(var i = from; i <= to; i++) {
var element = d3.select(".element" + i);
var currentTranslation = getTranslate(element);
var y = parseInt(currentTranslation[1]);
var x = parseInt(currentTranslation[0]);
y = y + 50;
var delta;
if(direction == "left") {
x = x - 50/(y/50);
delta = -50 / (y / 50);
} else if(direction == "right") {
x = x + 50/(y/50);
delta = 50 / (y / 50);
}
textPositions[i][0] += delta;
textPositions[i][1] += 50;
animations.push({ e: $("#barChart .element" + i), p: { x: '+=' + delta, y: '+=50' }, o: { duration: 1, position: '-=1' } })
}
animations[0].o.position = '+=0';
appendAnimation(line, animations, codeDisplayManager);
hideArrows();
}
function hideArrows() {
appendAnimation(null, [{ e: '#pivotMarkerLeft, #pivotMarkerRight', p: { attr: { opacity: "0" } }, o: { duration: 1, position: '-=1' } }], null);
}
function getTranslate(element) {
var transformString = element.attr("transform");
if(transformString != "" && transformString != null) {
var res = transformString.substring(transformString.indexOf("(")+1, transformString.indexOf(")")).split(",");
if(res[4] == null) res[4] = 0;
if(res[5] == null) res[5] = 0;
return res;
}
return [0, 0, 0, 0, 0, 0];
}
function merge(line) {
appendAnimation(line, [{ e: '#barChart rect, #barChart text', p: { x: 0, y: 0 }, o: { duration: 1 } }], codeDisplayManager);
}
function highlight(a, b, colorA, colorB, line) {
colorA = colorA || "blue";
colorB = colorB || "blue";
var elementA = $(".element" + a).filter("rect");
var elementB = $(".element" + b).filter("rect");
appendAnimation(line, [
{ e: elementA.filter("rect"), p: { attr: { fill: colorA } }, o: { duration: 1 } },
{ e: elementB.filter("rect"), p: { attr: { fill: colorB } }, o: { duration: 1, position: '-=1' } }
], codeDisplayManager);
return true;
}
function clearAllHighlight() {
appendAnimation(null, [{ e: '#barChart rect', p: { attr: { fill: "red" } }, o: { duration: 1 } }], null);
}
function clearHighlight(element, origColor) {
origColor = origColor || "red";
appendAnimation(null, [{ e: $(".element" + element).filter("rect"), p: { attr: { fill: origColor } }, o: { duration: 1 } }], null);
}
function highlightCode(lines, functionName) {
if (functionName)
codeDisplayManager.changeFunction(functionName);
appendCodeLines(lines, codeDisplayManager);
} | DAT200-Visualization-Team/DAT200-Visualization | js/visualization/QuickSortVisualization.js | JavaScript | mit | 7,386 |
module.exports = function (grunt) {
//TODO: move ./app/node-webkit.app out of the directory before building
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
release_name: 'Bmr-v0.0.4',
nw_dev_file: 'node-webkit.app',
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'js/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
},
jshint: {
all: ['Gruntfile.js', 'js/**/*.js']
},
sass: {
dist: {
files: [{
expand: true,
cwd: './app/sass',
src: ['*.scss'],
dest: './app/css',
ext: '.css'
}]
}
},
shell: {
move: {
command: 'mv ./app/<%= nw_dev_file %> ./tmp',
options: {
stdout: true,
stderr: true
}
},
moveback: {
command: 'mv ./tmp/<%= nw_dev_file %> ./app/',
options: {
stdout: true,
stderr: true
}
},
handlebars: {
command: 'handlebars -e tpl ./app/templates -f ./app/js/templates.js'
}
},
watch: {
css: {
files: './app/sass/**/*.scss',
tasks: ['sass']
},
templates: {
files: './app/templates/**/*.tpl',
tasks: ['shell:handlebars']
}
},
nodewebkit: {
options: {
version: '0.8.0',
build_dir: './build', // Where the build version of my node-webkit app is saved
mac: true,
win: true,
linux32: true,
linux64: true
},
src: ['./app/**/*']
},
// make a zipfile
compress: {
mac: {
mode: 'zip',
options: {
archive: 'dist/<%= release_name %>-mac.zip'
},
files: [
{
expand: true,
cwd: 'build/releases/bmr/mac/',
src: ['**/*'],
dest: '<%= release_name %>-mac'
}
]
},
linux32: {
mode: 'tgz',
options: {
archive: 'dist/<%= release_name %>-linux32.tgz'
},
files: [
{
expand: true,
cwd: 'build/releases/bmr/linux32/',
src: ['**/*'],
dest: '<%= release_name %>-linux32'
}
]
},
linux64: {
mode: 'tgz',
options: {
archive: 'dist/<%= release_name %>-linux64.tgz'
},
files: [
{
expand: true,
cwd: 'build/releases/bmr/linux64/',
src: ['**/*'],
dest: '<%= release_name %>-linux64'
}
]
},
win: {
mode: 'zip',
options: {
archive: 'dist/<%= release_name %>-win.zip'
},
files: [
{
expand: true,
cwd: 'build/releases/bmr/win/',
src: ['**/*'],
dest: '<%= release_name %>-win'
}
]
}
}
});
// Load the plugin that provides the "uglify" task.
//grunt.loadNpmTasks('grunt-contrib-uglify');
//grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-node-webkit-builder');
grunt.loadNpmTasks('grunt-contrib-compress');
grunt.loadNpmTasks('grunt-shell');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
// Default task(s).
//grunt.registerTask('default', ['uglify']);
grunt.registerTask('default', [
'shell:move'
, 'shell:handlebars'
, 'sass'
, 'nodewebkit'
, 'shell:moveback'
, 'compress:mac'
, 'compress:linux32'
, 'compress:linux64'
, 'compress:win'
]);
};
| chovy/bmr | Gruntfile.js | JavaScript | mit | 4,788 |
(function() {
'use strict';
angular
.module('app.say', []);
})(); | lcdporto/bieber-say-app | app/say/say.module.js | JavaScript | mit | 81 |
import Phaser from 'phaser';
import { centerGameObjects } from '../utils';
export default class extends Phaser.State {
init() {}
preload() {
this.loaderBg = this.add.sprite(this.game.world.centerX, this.game.world.centerY, 'loaderBg');
this.loaderBar = this.add.sprite(this.game.world.centerX, this.game.world.centerY, 'loaderBar');
centerGameObjects([this.loaderBg, this.loaderBar]);
this.load.setPreloadSprite(this.loaderBar);
//
// load your assets
//
this.load.image('deathCircle', 'assets/images/deathCircle.png');
this.load.image('mushroom', 'assets/images/mushroom2.png');
this.load.image('waveman_bullet_blue', 'assets/images/waveman_bullet_2.png');
this.load.image('wasd', 'assets/images/wasd.png');
this.load.image('space_bar', 'assets/images/space_bar.png');
this.load.spritesheet('explosion', 'assets/images/explode.png', 128, 128);
this.load.spritesheet('goat', 'assets/images/goats.png', 45, 45);
// Load audio assets
this.loadAudio();
this.load.image('ufo', 'assets/images/ufo.png');
this.load.spritesheet('suicidalBlob', 'assets/images/suicidalBlob.png', 512, 696, 4);
this.load.image('waveman', 'assets/images/waveman.png');
this.load.image('background_intro', 'assets/images/bg_intro.png');
this.load.image('background', 'assets/images/starfield.jpg');
this.load.image('thrusters', 'assets/images/thrusters.png');
this.load.shader('stars', 'assets/shaders/stars.frag');
this.load.image('red_gem', 'assets/images/hud_gem_red.png');
this.load.spritesheet('button_start', 'assets/images/start_button.png');
this.load.spritesheet('button_howtoplay', 'assets/images/howtoplay_button.png');
}
create() {
this.state.start('GameIntro');
}
render() {
}
loadAudio() {
// Load music files
this.game.load.audio('menu_song', 'assets/sounds/music/menu_screen.mp3', 1, true);
this.game.load.audio('waveman_complete', 'assets/sounds/music/WaveMan_Complete.mp3', 1, true);
this.game.load.audio('waveman_intro', 'assets/sounds/music/WaveMan_Intro.mp3', 1, true);
this.game.load.audio('waveman_is_dying_1', 'assets/sounds/music/WaveMan_IsDying1.mp3', 1, true);
this.game.load.audio('waveman_is_dying_2', 'assets/sounds/music/WaveMan_IsDying2.mp3', 1, true);
this.game.load.audio('waveman_main', 'assets/sounds/music/WaveMan_Main.mp3', 1, true);
this.game.load.audio('waveman_verse_1', 'assets/sounds/music/WaveMan_Verse1.mp3', 1, true);
this.game.load.audio('waveman_verse_2', 'assets/sounds/music/WaveMan_Verse2.mp3', 1, true);
// Load SFX files
this.game.load.audio('waveman_alien_damage_1', 'assets/sounds/sfx/WaveMan_AlienDamage1.mp3');
this.game.load.audio('waveman_alien_damage_2', 'assets/sounds/sfx/WaveMan_AlienDamage2.mp3');
this.game.load.audio('waveman_alien_damage_3', 'assets/sounds/sfx/WaveMan_AlienDamage3.mp3');
this.game.load.audio('waveman_alien_damage_4', 'assets/sounds/sfx/WaveMan_AlienDamage4.mp3');
this.game.load.audio('waveman_laser_shot_1', 'assets/sounds/sfx/WaveMan_LaserShot1.mp3');
this.game.load.audio('waveman_laser_shot_2', 'assets/sounds/sfx/WaveMan_LaserShot2.mp3');
this.game.load.audio('waveman_laser_shot_3', 'assets/sounds/sfx/WaveMan_LaserShot3.mp3');
this.game.load.audio('waveman_laser_shot_4', 'assets/sounds/sfx/WaveMan_LaserShot4.mp3');
this.game.load.audio('waveman_laser_shot_5', 'assets/sounds/sfx/WaveMan_LaserShot5.mp3');
this.game.load.audio('waveman_long_laser_shot_1', 'assets/sounds/sfx/WaveMan_LongLaserShot1.mp3');
this.game.load.audio('waveman_long_laser_shot_2', 'assets/sounds/sfx/WaveMan_LongLaserShot2.mp3');
this.game.load.audio('waveman_long_laser_shot_3', 'assets/sounds/sfx/WaveMan_LongLaserShot3.mp3');
this.game.load.audio('waveman_long_laser_shot_4', 'assets/sounds/sfx/WaveMan_LongLaserShot4.mp3');
this.game.load.audio('waveman_long_laser_shot_5', 'assets/sounds/sfx/WaveMan_LongLaserShot5.mp3');
this.game.load.audio('waveman_ship_thrusters', 'assets/sounds/sfx/WaveMan_ShipThruster.mp3');
this.game.load.audio('waveman_smooth_laser_shot_1', 'assets/sounds/sfx/WaveMan_SmoothLaserShot1.mp3');
this.game.load.audio('waveman_smooth_laser_shot_2', 'assets/sounds/sfx/WaveMan_SmoothLaserShot2.mp3');
this.game.load.audio('waveman_smooth_laser_shot_3', 'assets/sounds/sfx/WaveMan_SmoothLaserShot3.mp3');
this.game.load.audio('waveman_smooth_laser_shot_4', 'assets/sounds/sfx/WaveMan_SmoothLaserShot4.mp3');
this.game.load.audio('waveman_weird_alien_noise_1', 'assets/sounds/sfx/WaveMan_WeirdAlienNoise1.mp3');
this.game.load.audio('waveman_weird_alien_noise_2', 'assets/sounds/sfx/WaveMan_WeirdAlienNoise2.mp3');
this.game.load.audio('waveman_weird_alien_noise_3', 'assets/sounds/sfx/WaveMan_WeirdAlienNoise3.mp3');
this.game.load.audio('waveman_weird_alien_noise_4', 'assets/sounds/sfx/WaveMan_WeirdAlienNoise4.mp3');
this.game.load.audio('WaveMan_Explosion', 'assets/sounds/sfx/WaveMan_Explosion.mp3');
}
}
| Zargath/REA_MTLGameJam2017 | src/states/Splash.js | JavaScript | mit | 5,050 |
// @flow
import type { RepositoryT } from '@gitcub/types/gh'
import css from '@styled-system/css'
import * as React from 'react'
import { FaRegFolderOpen } from 'react-icons/fa'
import { useDispatch, useSelector } from 'react-redux'
import List from '../components/common/blocks/List'
import Panel from '../components/common/blocks/Panel'
import InnerContainer from '../components/common/layouts/InnerContainer'
import rootReducer from '../ducks'
import * as RepositoriesAction from '../ducks/repositories'
const Home = ({
repositories
}: {|
repositories: $ReadOnlyArray<RepositoryT>
|}) => (
<InnerContainer>
<div
css={css({
display: 'flex',
mt: 4
})}
>
<div css={{ flexGrow: 1 }}>
<List lined>
<li>ACTIVITY_1</li>
<li>ACTIVITY_2</li>
<li>ACTIVITY_3</li>
</List>
</div>
<div
css={css({
width: '320px',
ml: 4
})}
>
<Panel>
<Panel.Header>Public Repositories</Panel.Header>
<Panel.Body noPadding>
<List lined withLRPadding>
{repositories.map((repo, i) => (
<li
css={{
display: 'flex',
alignItems: 'center'
}}
key={i}
>
<FaRegFolderOpen css={css({ mr: 1 })} />
<a href={`/${repo.full_name}`}>{repo.full_name}</a>
</li>
))}
</List>
</Panel.Body>
</Panel>
</div>
</div>
</InnerContainer>
)
export default Home
export const HomeContainer = () => {
const dispatch = useDispatch()
React.useEffect(() => {
;(async () => {
dispatch(await RepositoriesAction.fetch())
})()
}, [dispatch])
const repositories = useSelector(
(state: $Call<typeof rootReducer>) => state.repositories
)
return <Home repositories={repositories} />
}
| keik/gh | packages/app-frontend/components/Home.js | JavaScript | mit | 1,987 |
define(function(require) {
var Detection = require('lavaca/env/Detection'),
View = require('lavaca/mvc/View'),
Promise = require('lavaca/util/Promise'),
viewManager = require('lavaca/mvc/ViewManager'),
History = require('lavaca/net/History');
require('lavaca/fx/Animation'); //jquery plugins
/**
* A View from which all other application Views can extend.
* Adds support for animating between views.
*
* @class app.ui.views.BaseView
* @extends Lavaca.mvc.View
*
*/
var BaseView = View.extend(function() {
View.apply(this, arguments);
this.mapEvent('.cancel', 'tap', this.onTapCancel);
}, {
/**
* The name of the template used by the view
* @property {String} template
* @default 'default'
*/
template: 'default',
/**
* The name of the template used by the view
* @property {Object} pageTransition
* @default 'default'
*/
pageTransition: {
'in': '',
'out': '',
'inReverse': '',
'outReverse': ''
},
/**
* Executes when the template renders successfully. This implementation
* adds support for animations between views, based off of the animation
* property on the prototype.
* @method onRenderSuccess
*
* @param {Event} e The render event. This object should have a string property named "html"
* that contains the template's rendered HTML output.
*/
onRenderSuccess: function() {
View.prototype.onRenderSuccess.apply(this, arguments);
},
/**
* Handler for when a cancel control is tapped
* @method onTapCancel
*
* @param {Event} e The tap event.
*/
onTapCancel: function(e) {
e.preventDefault();
viewManager.dismiss(e.currentTarget);
},
/**
* Executes when the user navigates to this view. This implementation
* adds support for animations between views, based off of the animation
* property on the prototype.
* @method enter
*
* @param {jQuery} container The parent element of all views
* @param {Array} exitingViews The views that are exiting as this one enters
* @return {Lavaca.util.Promise} A promise
*/
enter: function(container, exitingViews) {
var isRoutingBack = History.isRoutingBack;
return View.prototype.enter.apply(this, arguments)
.then(function() {
if (isRoutingBack) {
if (History.animationBreadcrumb.length > 0) {
this.pageTransition = History.animationBreadcrumb.pop();
}
} else {
History.animationBreadcrumb.push(this.pageTransition);
}
var animationIn = isRoutingBack ? this.pageTransition['inReverse']:this.pageTransition['in'],
animationOut = isRoutingBack ? this.pageTransition['outReverse']:this.pageTransition['out'],
i = -1,
exitingView;
var triggerEnterComplete = function() {
this.trigger('entercomplete');
this.shell.removeClass(animationIn);
};
if (Detection.animationEnabled && animationIn !== '') {
if (exitingViews.length) {
i = -1;
while (!!(exitingView = exitingViews[++i])) {
exitingView.shell.addClass(animationOut);
if (animationOut === '') {
exitingView.exitPromise.resolve();
}
}
}
if ((this.layer > 0 || exitingViews.length > 0)) {
this.shell
.nextAnimationEnd(triggerEnterComplete.bind(this))
.addClass(animationIn + ' current');
} else {
this.shell.addClass('current');
this.trigger('entercomplete');
}
} else {
this.shell.addClass('current');
if (exitingViews.length > 0) {
i = -1;
while (!!(exitingView = exitingViews[++i])) {
exitingView.shell.removeClass('current');
if (exitingView.exitPromise) {
exitingView.exitPromise.resolve();
}
}
}
this.trigger('entercomplete');
}
});
},
/**
* Executes when the user navigates away from this view. This implementation
* adds support for animations between views, based off of the animation
* property on the prototype.
* @method exit
*
* @param {jQuery} container The parent element of all views
* @param {Array} enteringViews The views that are entering as this one exits
* @return {Lavaca.util.Promise} A promise
*/
exit: function(container, enteringViews) {
var animation = History.isRoutingBack ? this.pageTransition['outReverse'] : (enteringViews.length ? enteringViews[0].pageTransition['out'] : '');
if (History.isRoutingBack && this.shell.data('layer-index') > 0) {
this.pageTransition = History.animationBreadcrumb.pop();
animation = this.pageTransition['outReverse'];
}
if (Detection.animationEnabled && animation) {
this.exitPromise = new Promise(this);
this.shell
.nextAnimationEnd(function() {
View.prototype.exit.apply(this, arguments).then(function() {
this.exitPromise.resolve();
});
this.shell.removeClass(animation + ' current');
}.bind(this))
.addClass(animation);
return this.exitPromise;
} else {
this.shell.removeClass('current');
return View.prototype.exit.apply(this, arguments);
}
}
});
return BaseView;
});
| georgehenderson/lavaca-parse-authflow | src/www/js/app/ui/views/BaseView.js | JavaScript | mit | 5,742 |
require('./leaflet_tileloader_mixin');
/**
* full canvas layer implementation for Leaflet
*/
L.CanvasLayer = L.Class.extend({
includes: [L.Mixin.Events, L.Mixin.TileLoader],
options: {
minZoom: 0,
maxZoom: 28,
tileSize: 256,
subdomains: 'abc',
errorTileUrl: '',
attribution: '',
zoomOffset: 0,
opacity: 1,
unloadInvisibleTiles: L.Browser.mobile,
updateWhenIdle: L.Browser.mobile,
tileLoader: false, // installs tile loading events
zoomAnimation: true
},
initialize: function (options) {
var self = this;
options = options || {};
//this.project = this._project.bind(this);
this.render = this.render.bind(this);
L.Util.setOptions(this, options);
this._canvas = this._createCanvas();
// backCanvas for zoom animation
if (this.options.zoomAnimation) {
this._backCanvas = this._createCanvas();
}
this._ctx = this._canvas.getContext('2d');
this.currentAnimationFrame = -1;
this.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
return window.setTimeout(callback, 1000 / 60);
};
this.cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame ||
window.webkitCancelAnimationFrame || window.msCancelAnimationFrame || function(id) { clearTimeout(id); };
},
_createCanvas: function() {
var canvas;
canvas = document.createElement('canvas');
canvas.style.position = 'absolute';
canvas.style.top = 0;
canvas.style.left = 0;
canvas.style.pointerEvents = "none";
canvas.style.zIndex = this.options.zIndex || 0;
var className = 'leaflet-tile-container';
if (this.options.zoomAnimation) {
className += ' leaflet-zoom-animated';
}
canvas.setAttribute('class', className);
return canvas;
},
onAdd: function (map) {
this._map = map;
// add container with the canvas to the tile pane
// the container is moved in the oposite direction of the
// map pane to keep the canvas always in (0, 0)
var tilePane = this._map._panes.tilePane;
var _container = L.DomUtil.create('div', 'leaflet-layer');
_container.appendChild(this._canvas);
if (this.options.zoomAnimation) {
_container.appendChild(this._backCanvas);
this._backCanvas.style.display = 'none';
}
tilePane.appendChild(_container);
this._container = _container;
// hack: listen to predrag event launched by dragging to
// set container in position (0, 0) in screen coordinates
map.dragging._draggable.on('predrag', function() {
var d = map.dragging._draggable;
L.DomUtil.setPosition(this._canvas, { x: -d._newPos.x, y: -d._newPos.y });
}, this);
map.on({ 'viewreset': this._reset }, this);
map.on('move', this.redraw, this);
map.on('resize', this._reset, this);
if (this.options.zoomAnimation) {
map.on({
'zoomanim': this._animateZoom,
'zoomend': this._endZoomAnim,
'moveend': this._reset
}, this);
}
if(this.options.tileLoader) {
this._initTileLoader();
}
this._reset();
},
_animateZoom: function (e) {
if (!this._animating) {
this._animating = true;
}
var back = this._backCanvas;
back.width = this._canvas.width;
back.height = this._canvas.height;
// paint current canvas in back canvas with trasnformation
var pos = this._canvas._leaflet_pos || { x: 0, y: 0 };
back.getContext('2d').drawImage(this._canvas, 0, 0);
L.DomUtil.setPosition(back, L.DomUtil.getPosition(this._canvas));
// hide original
this._canvas.style.display = 'none';
back.style.display = 'block';
var map = this._map;
var scale = map.getZoomScale(e.zoom);
var newCenter = map._latLngToNewLayerPoint(map.getCenter(), e.zoom, e.center);
var oldCenter = map._latLngToNewLayerPoint(e.center, e.zoom, e.center);
var origin = {
x: newCenter.x - oldCenter.x + pos.x,
y: newCenter.y - oldCenter.y + pos.y
};
var bg = back;
var transform = L.DomUtil.TRANSFORM;
setTimeout(function() {
bg.style[transform] = L.DomUtil.getTranslateString(origin) + ' scale(' + e.scale + ') ';
}, 0)
},
_endZoomAnim: function () {
this._animating = false;
this._canvas.style.display = 'block';
this._backCanvas.style.display = 'none';
this._backCanvas.style[L.DomUtil.TRANSFORM] = '';
},
getCanvas: function() {
return this._canvas;
},
getAttribution: function() {
return this.options.attribution;
},
draw: function() {
return this._reset();
},
onRemove: function (map) {
this._container.parentNode.removeChild(this._container);
map.off({
'viewreset': this._reset,
'move': this._render,
'moveend': this._reset,
'resize': this._reset,
'zoomanim': this._animateZoom,
'zoomend': this._endZoomAnim
}, this);
},
addTo: function (map) {
map.addLayer(this);
return this;
},
error: function (callback) {
this.provider.options.errorCallback = callback;
return this;
},
setOpacity: function (opacity) {
this.options.opacity = opacity;
this._updateOpacity();
return this;
},
setZIndex: function(zIndex) {
this._canvas.style.zIndex = zIndex;
if (this.options.zoomAnimation) {
this._backCanvas.style.zIndex = zIndex;
}
},
bringToFront: function () {
return this;
},
bringToBack: function () {
return this;
},
_reset: function () {
var size = this._map.getSize();
this._canvas.width = size.x;
this._canvas.height = size.y;
// fix position
var pos = L.DomUtil.getPosition(this._map.getPanes().mapPane);
if (pos) {
L.DomUtil.setPosition(this._canvas, { x: -pos.x, y: -pos.y });
}
this.onResize();
this._render();
},
/*
_project: function(x) {
var point = this._map.latLngToLayerPoint(new L.LatLng(x[1], x[0]));
return [point.x, point.y];
},
*/
_updateOpacity: function () { },
_render: function() {
if (this.currentAnimationFrame >= 0) {
this.cancelAnimationFrame.call(window, this.currentAnimationFrame);
}
this.currentAnimationFrame = this.requestAnimationFrame.call(window, this.render);
},
// use direct: true if you are inside an animation frame call
redraw: function(direct) {
var domPosition = L.DomUtil.getPosition(this._map.getPanes().mapPane);
if (domPosition) {
L.DomUtil.setPosition(this._canvas, { x: -domPosition.x, y: -domPosition.y });
}
if (direct) {
this.render();
} else {
this._render();
}
},
onResize: function() {
},
render: function() {
throw new Error('render function should be implemented');
}
});
| thayumanavar77/thayumanavar77.github.io | js/lib/torque/leaflet/canvas_layer.js | JavaScript | mit | 7,016 |
const expressingBeGoingToWithYaoPattern = require('./expressingBeGoingToWithYaoPattern');
const {
assertAllExamplesMatch,
assertNoneMatch,
assertAllMatch,
} = require('../lib/testUtils');
test('matches all examples', async () => {
await assertAllExamplesMatch(expressingBeGoingToWithYaoPattern);
});
test('extra examples', async () => {
await assertAllMatch(expressingBeGoingToWithYaoPattern, [
'今天晚上老板要和我们一起加班。',
'我要先回家把东西放下,之后去咖啡店找你。',
]);
});
test("doesn't match negative examples", async () => {
await assertNoneMatch(expressingBeGoingToWithYaoPattern, [
'我们公司有很多外国人,所以我们要说英文。',
'中秋节是中国最重要的传统节日之一。',
'终于要放假了,开心吧?',
]);
});
| chanind/cn-grammar-matcher | src/patterns/expressingBeGoingToWithYaoPattern.test.js | JavaScript | mit | 832 |
/* @flow */
/**
* TransferMoney use case
*/
export default function TransferMoney(source: Account, destination: Account, amount: number) {
banker = this;
banker.transfer();
role banker {
transfer() {
source.withdraw();
destination.deposit();
}
}
role source {
withdraw() {
if (this.balance < amount) {
throw Error('Insufficient funds');
}
this.decreaseBalance(amount);
}
}
role destination {
deposit() {
this.increaseBalance(amount);
}
}
role amount {}
} | mbrowne/babel-dci | babel-plugin-transform-dci/examples/TransferMoney-simplified/TransferMoney.js | JavaScript | mit | 506 |
function vbox_test() {
var vbox1 = vbox();
var vbox2 = vbox();
vbox2.innerHTML = '<span></span>';
test_scroll(vbox2);
appendChild(vbox1, vbox2);
return vbox1;
} | yunxu1019/efront | coms/zimoli/vbox_test.js | JavaScript | mit | 184 |
version https://git-lfs.github.com/spec/v1
oid sha256:3d781f778fd75100e9cf1d6981f25d728692d080b4ef39fe891bc63ecfa17f7a
size 856
| yogeshsaroya/new-cdnjs | ajax/libs/highlight.js/8.4/languages/lisp.min.js | JavaScript | mit | 128 |
import { Signal } from '../../core/Signal';
import * as TicTacToe from './TicTacToe';
import { Grid } from './Grid';
import { Player } from './Player';
const { _, X, O } = TicTacToe;
/*!
\class Match
*/
export class Match {
constructor() {
this.grid = new Grid();
this.players = [];
this.current = -1;
this.state = TicTacToe.WaitingForPlayersState;
this.stateChanged = new Signal();
this.movePassed = new Signal();
this.playerRemoved = new Signal();
this.move = this.move.bind(this);
}
clear() {
while (this.players.length !== 0)
this.removePlayer(this.players[0]);
this.grid.clear();
}
setState(state, winner) {
if (state !== this.state) {
this.state = state;
this.stateChanged(state, winner);
}
}
currentPlayer() {
if (this.current >= 0 && this.current < this.players.length)
return this.players[this.current];
}
findPlayer(predicate) {
return this.players.find(predicate);
}
nextMove() {
if (this.state !== TicTacToe.MatchRunningState)
return;
this.current++;
if (this.current === this.players.length)
this.current = 0;
const player = this.currentPlayer();
this.movePassed(player);
player.passMove();
}
start() {
if (this.state === TicTacToe.MatchRunningState
|| this.players.length !== TicTacToe.MaxPlayers)
return;
this.grid.clear();
this.setState(TicTacToe.MatchRunningState);
this.current = -1;
this.nextMove();
}
addPlayer(player) {
if (this.players.length === TicTacToe.MaxPlayers)
return;
player.setMatch(this);
player.moved.connect(this.move);
this.players.push(player);
if (this.players.length === TicTacToe.MaxPlayers) {
const player1 = this.players[0];
const player2 = this.players[1];
player1.setMark(X);
player1.setIndex(TicTacToe.Player1);
player2.setMark(O);
player2.setIndex(TicTacToe.Player2);
this.setState(TicTacToe.PlayersReadyState);
player1.setName(player1.name);
player1.setScore(0);
player2.setName(player2.name);
player2.setScore(0);
this.start();
}
}
removePlayer(player) {
const index = this.players.indexOf(player);
if (index !== -1) {
const player = this.players.splice(index, 1)[0];
player.moved.disconnect(this.move);
player.setMatch(null);
this.playerRemoved(player);
if (this.players.length === 1) {
this.current = 0;
const winner = this.players[0];
winner.setScore(winner.score + 1);
this.setState(TicTacToe.MatchFinishedState, winner);
}
this.current = -1;
this.setState(TicTacToe.WaitingForPlayersState);
}
}
move(player, row, column) {
if (this.state === TicTacToe.MatchRunningState) {
if (this.currentPlayer() === player) {
const result = this.grid.setCell(row, column, player.mark, player.index);
switch (result) {
case TicTacToe.WinState: player.setScore(player.score + 1); this.setState(TicTacToe.MatchFinishedState, player); this.current = -1; break;
case TicTacToe.DrawState: this.setState(TicTacToe.MatchFinishedState); this.current = -1; break;
case TicTacToe.ProceedState: this.nextMove(); break;
case TicTacToe.DiscardState: default: break;
}
}
}
else if (this.state === TicTacToe.MatchFinishedState) { // restarting with players order swapped
this.players.push(this.players.shift());
this.players[0].setMark(X);
this.players[1].setMark(O);
this.start();
}
}
dump() {
return {
index: this.grid.dump(),
players: this.players.map((player) => player.dump()),
current: this.current,
state: this.state
};
}
restore(state) {
this.grid = Grid.restore(state.grid);
this.players = state.players.map((player) => Player.restore(player));
this.current = state.current;
this.state = state.state;
}
}
| evg656e/tictactoe | lib/tictactoe/base/Match.js | JavaScript | mit | 4,546 |
module.exports = {
Store: require('./lib/store'),
Action: require('./lib/action'),
mixins: {
StoreMixin: require('./lib/mixins/storeMixin')
}
}
| thewei/react-native-immutable | index.js | JavaScript | mit | 168 |
const config = require('../../../knexfile').extweb
const knex = require('knex')(config)
const getRepeatEligibility = require('./get-repeat-eligibility')
const claimTypeEnum = require('../../constants/claim-type-enum')
module.exports = function (reference, claimId, claimType) {
return knex('Claim')
.where({ Reference: reference, ClaimId: claimId })
.first('EligibilityId')
.then(function (claim) {
if (claimType === claimTypeEnum.REPEAT_CLAIM || claimType === claimTypeEnum.REPEAT_DUPLICATE) {
return getRepeatEligibility(reference, null, claim.EligibilityId)
} else {
return knex('Visitor')
.where({ Reference: reference, EligibilityId: claim.EligibilityId })
.first('HouseNumberAndStreet', 'Town', 'PostCode', 'DateOfBirth', 'Benefit', 'Relationship')
}
})
}
| ministryofjustice/apvs-external-web | app/services/data/get-address-and-link-details.js | JavaScript | mit | 835 |
(function() {
'use strict';
angular
.module('ui-highcharts')
.factory('$uiHighChartsManager', highChartsManager);
highChartsManager.$inject = [
'$uiHighchartsAddWatchers',
'$uiHighchartsTransclude',
'$uiHighchartsHandleAttrs',
];
/* @ngInject */
/* jshint -W003 */
function highChartsManager(addWatchers, transclude, handleAttrs) {
var service = {
createInstance: createInstance,
};
return service;
function createInstance(type, $element, $scope, $attrs, $transclude) { /* jshint ignore:line */
//compling options and transludes content.
$scope.options = $.extend(true, $scope.options, { chart: { renderTo: $element[0] } });
transclude($scope, $transclude());
handleAttrs($scope, $attrs);
//creates chart and watchers.
var chart = new Highcharts[type]($scope.options);
addWatchers(chart, $scope, $attrs);
//adds chart reference to parent scope if id attribute is provided.
if ($attrs.id && $scope.$parent) {
if (!$scope.$parent[$attrs.id]) {
$scope.$parent[$attrs.id] = chart;
} else {
throw new Error('A HighChart object with reference ' + $attrs.chart + ' has already been initialized.');
}
}
}
}
})();
| gevgeny/ui-highcharts | src/highChartsManager.js | JavaScript | mit | 1,289 |
export const SET_PASSPHRASE = 'SET_PASSPHRASE'
export const setPassphrase = (passphrase) => {
return {
type: SET_PASSPHRASE,
payload: passphrase,
}
}
export const SAVE_PASSPHRASE = 'SAVE_PASSPHRASE'
export const savePassphrase = () => {
return {
type: SAVE_PASSPHRASE,
}
}
export const SET_TMP_PASSPHRASE = 'SET_TMP_PASSPHRASE'
export const setTmpPassphrase = (passphrase) => {
return {
type: SET_TMP_PASSPHRASE,
payload: passphrase,
}
}
export const SET_TMP_PASSPHRASE_CONFIRMATION = 'SET_TMP_PASSPHRASE_CONFIRMATION'
export const setTmpPassphraseConfirmation = (passphrase) => {
return {
type: SET_TMP_PASSPHRASE_CONFIRMATION,
payload: passphrase,
}
}
export const SET_ENCRYPTED_CONTENT = 'SET_ENCRYPTED_CONTENT'
export const setEncryptedContent = (encryptedContent) => {
return {
type: SET_ENCRYPTED_CONTENT,
payload: encryptedContent,
}
}
export const SET_DECRYPTED = 'SET_DECRYPTED'
export const setDecrypted = (isDecrypted) => {
return {
type: SET_DECRYPTED,
payload: isDecrypted,
}
}
export const SET_DECRYPTION_ERROR = 'SET_DECRYPTION_ERROR'
export const setDecryptionError = (error) => {
return {
type: SET_DECRYPTION_ERROR,
payload: error,
}
}
export const SET_LOADING = 'SET_LOADING'
export const setLoading = (loading) => {
return {
type: SET_LOADING,
payload: loading,
}
}
export const SET_SAVING_STATE = 'SET_SAVING_STATE'
export const setSavingState = (newState) => {
return {
type: SET_SAVING_STATE,
payload: newState,
}
}
| getvault/getvault.github.io | src/redux/vault/vault.actions.js | JavaScript | mit | 1,551 |