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
|
---|---|---|---|---|---|
/**
Breaks up a long string
@method breakUp
@for Handlebars
**/
Handlebars.registerHelper('breakUp', function(property, hint, options) {
var prop = Ember.Handlebars.get(this, property, options);
if (!prop) return "";
hint = Ember.Handlebars.get(this, hint, options);
return Discourse.Formatter.breakUp(prop, hint);
});
/**
Truncates long strings
@method shorten
@for Handlebars
**/
Handlebars.registerHelper('shorten', function(property, options) {
return Ember.Handlebars.get(this, property, options).substring(0,35);
});
/**
Produces a link to a topic
@method topicLink
@for Handlebars
**/
Handlebars.registerHelper('topicLink', function(property, options) {
var topic = Ember.Handlebars.get(this, property, options),
title = topic.get('fancy_title') || topic.get('title');
return "<a href='" + topic.get('lastUnreadUrl') + "' class='title'>" + title + "</a>";
});
/**
Produces a link to a category given a category object and helper options
@method categoryLinkHTML
@param {Discourse.Category} category to link to
@param {Object} options standard from handlebars
**/
function categoryLinkHTML(category, options) {
var categoryOptions = {};
if (options.hash) {
if (options.hash.allowUncategorized) {
categoryOptions.allowUncategorized = true;
}
if (options.hash.categories) {
categoryOptions.categories = Em.Handlebars.get(this, options.hash.categories, options);
}
}
return new Handlebars.SafeString(Discourse.HTML.categoryLink(category, categoryOptions));
}
/**
Produces a link to a category
@method categoryLink
@for Handlebars
**/
Handlebars.registerHelper('categoryLink', function(property, options) {
return categoryLinkHTML(Ember.Handlebars.get(this, property, options), options);
});
Handlebars.registerHelper('categoryLinkRaw', function(property, options) {
return categoryLinkHTML(property, options);
});
/**
Produces a bound link to a category
@method boundCategoryLink
@for Handlebars
**/
Ember.Handlebars.registerBoundHelper('boundCategoryLink', categoryLinkHTML);
/**
Produces a link to a route with support for i18n on the title
@method titledLinkTo
@for Handlebars
**/
Handlebars.registerHelper('titledLinkTo', function(name, object) {
var options = [].slice.call(arguments, -1)[0];
if (options.hash.titleKey) {
options.hash.title = I18n.t(options.hash.titleKey);
}
if (arguments.length === 3) {
return Ember.Handlebars.helpers.linkTo.call(this, name, object, options);
} else {
return Ember.Handlebars.helpers.linkTo.call(this, name, options);
}
});
/**
Shorten a URL for display by removing common components
@method shortenUrl
@for Handlebars
**/
Handlebars.registerHelper('shortenUrl', function(property, options) {
var url;
url = Ember.Handlebars.get(this, property, options);
// Remove trailing slash if it's a top level URL
if (url.match(/\//g).length === 3) {
url = url.replace(/\/$/, '');
}
url = url.replace(/^https?:\/\//, '');
url = url.replace(/^www\./, '');
return url.substring(0,80);
});
/**
Display a property in lower case
@method lower
@for Handlebars
**/
Handlebars.registerHelper('lower', function(property, options) {
var o;
o = Ember.Handlebars.get(this, property, options);
if (o && typeof o === 'string') {
return o.toLowerCase();
} else {
return "";
}
});
/**
Show an avatar for a user, intelligently making use of available properties
@method avatar
@for Handlebars
**/
Handlebars.registerHelper('avatar', function(user, options) {
if (typeof user === 'string') {
user = Ember.Handlebars.get(this, user, options);
}
if (user) {
var username = Em.get(user, 'username');
if (!username) username = Em.get(user, options.hash.usernamePath);
var avatarTemplate;
var template = options.hash.template;
if (template && template !== 'avatar_template') {
avatarTemplate = Em.get(user, template);
if (!avatarTemplate) avatarTemplate = Em.get(user, 'user.' + template);
}
if (!avatarTemplate) avatarTemplate = Em.get(user, 'avatar_template');
if (!avatarTemplate) avatarTemplate = Em.get(user, 'user.avatar_template');
var title;
if (!options.hash.ignoreTitle) {
// first try to get a title
title = Em.get(user, 'title');
// if there was no title provided
if (!title) {
// try to retrieve a description
var description = Em.get(user, 'description');
// if a description has been provided
if (description && description.length > 0) {
// preprend the username before the description
title = username + " - " + description;
}
}
}
return new Handlebars.SafeString(Discourse.Utilities.avatarImg({
size: options.hash.imageSize,
extraClasses: Em.get(user, 'extras') || options.hash.extraClasses,
title: title || username,
avatarTemplate: avatarTemplate
}));
} else {
return '';
}
});
/**
Bound avatar helper.
Will rerender whenever the "avatar_template" changes.
@method boundAvatar
@for Handlebars
**/
Ember.Handlebars.registerBoundHelper('boundAvatar', function(user, options) {
return new Handlebars.SafeString(Discourse.Utilities.avatarImg({
size: options.hash.imageSize,
avatarTemplate: Em.get(user, options.hash.template || 'avatar_template')
}));
}, 'avatar_template', 'uploaded_avatar_template', 'gravatar_template');
/**
Nicely format a date without a binding since the date doesn't need to change.
@method unboundDate
@for Handlebars
**/
Handlebars.registerHelper('unboundDate', function(property, options) {
var dt = new Date(Ember.Handlebars.get(this, property, options));
return Discourse.Formatter.longDate(dt);
});
/**
Live refreshing age helper
@method unboundDate
@for Handlebars
**/
Handlebars.registerHelper('unboundAge', function(property, options) {
var dt = new Date(Ember.Handlebars.get(this, property, options));
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(dt));
});
/**
Live refreshing age helper, with a tooltip showing the date and time
@method unboundAgeWithTooltip
@for Handlebars
**/
Handlebars.registerHelper('unboundAgeWithTooltip', function(property, options) {
var dt = new Date(Ember.Handlebars.get(this, property, options));
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(dt, {title: true}));
});
/**
Display a date related to an edit of a post
@method editDate
@for Handlebars
**/
Handlebars.registerHelper('editDate', function(property, options) {
// autoupdating this is going to be painful
var date = new Date(Ember.Handlebars.get(this, property, options));
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(date, {format: 'medium', title: true, leaveAgo: true, wrapInSpan: false}));
});
/**
Displays a percentile based on a `percent_rank` field
@method percentile
@for Ember.Handlebars
**/
Ember.Handlebars.registerHelper('percentile', function(property, options) {
var percentile = Ember.Handlebars.get(this, property, options);
return Math.round((1.0 - percentile) * 100);
});
/**
Displays a float nicely
@method float
@for Ember.Handlebars
**/
Ember.Handlebars.registerHelper('float', function(property, options) {
var x = Ember.Handlebars.get(this, property, options);
if (!x) return "0";
if (Math.round(x) === x) return x;
return x.toFixed(3);
});
/**
Display logic for numbers.
@method number
@for Handlebars
**/
Handlebars.registerHelper('number', function(property, options) {
var orig = parseInt(Ember.Handlebars.get(this, property, options), 10);
if (isNaN(orig)) { orig = 0; }
var title = orig;
if (options.hash.numberKey) {
title = I18n.t(options.hash.numberKey, { number: orig });
}
// Round off the thousands to one decimal place
var n = orig;
if (orig > 999 && !options.hash.noTitle) {
n = (orig / 1000).toFixed(1) + "K";
}
var classNames = 'number';
if (options.hash['class']) {
classNames += ' ' + Ember.Handlebars.get(this, options.hash['class'], options);
}
var result = "<span class='" + classNames + "'";
if (n !== title) {
result += " title='" + Handlebars.Utils.escapeExpression(title) + "'";
}
result += ">" + n + "</span>";
return new Handlebars.SafeString(result);
});
/**
Display logic for dates.
@method date
@for Handlebars
**/
Handlebars.registerHelper('date', function(property, options) {
var leaveAgo;
if (property.hash) {
if (property.hash.leaveAgo) {
leaveAgo = property.hash.leaveAgo === "true";
}
if (property.hash.path) {
property = property.hash.path;
}
}
var val = Ember.Handlebars.get(this, property, options);
if (val) {
var date = new Date(val);
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(date, {format: 'medium', title: true, leaveAgo: leaveAgo}));
}
});
/**
Look for custom html content in the preload store.
@method customHTML
@for Handlebars
**/
Handlebars.registerHelper('customHTML', function(property) {
var html = PreloadStore.get("customHTML");
if (html && html[property] && html[property].length) {
return new Handlebars.SafeString(html[property]);
}
});
| tadp/learnswift | app/assets/javascripts/discourse/helpers/application_helpers.js | JavaScript | mit | 9,347 |
'use strict';
const styles = require('./styles');
const permsToString = require('./perms-to-string');
const sizeToString = require('./size-to-string');
const sortFiles = require('./sort-files');
const fs = require('fs');
const path = require('path');
const he = require('he');
const etag = require('../etag');
const url = require('url');
const status = require('../status-handlers');
const supportedIcons = styles.icons;
const css = styles.css;
module.exports = (opts) => {
// opts are parsed by opts.js, defaults already applied
const cache = opts.cache;
const root = path.resolve(opts.root);
const baseDir = opts.baseDir;
const humanReadable = opts.humanReadable;
const hidePermissions = opts.hidePermissions;
const handleError = opts.handleError;
const showDotfiles = opts.showDotfiles;
const si = opts.si;
const weakEtags = opts.weakEtags;
return function middleware(req, res, next) {
// Figure out the path for the file from the given url
const parsed = url.parse(req.url);
const pathname = decodeURIComponent(parsed.pathname);
const dir = path.normalize(
path.join(
root,
path.relative(
path.join('/', baseDir),
pathname
)
)
);
fs.stat(dir, (statErr, stat) => {
if (statErr) {
if (handleError) {
status[500](res, next, { error: statErr });
} else {
next();
}
return;
}
// files are the listing of dir
fs.readdir(dir, (readErr, _files) => {
let files = _files;
if (readErr) {
if (handleError) {
status[500](res, next, { error: readErr });
} else {
next();
}
return;
}
// Optionally exclude dotfiles from directory listing.
if (!showDotfiles) {
files = files.filter(filename => filename.slice(0, 1) !== '.');
}
res.setHeader('content-type', 'text/html');
res.setHeader('etag', etag(stat, weakEtags));
res.setHeader('last-modified', (new Date(stat.mtime)).toUTCString());
res.setHeader('cache-control', cache);
function render(dirs, renderFiles, lolwuts) {
// each entry in the array is a [name, stat] tuple
let html = `${[
'<!doctype html>',
'<html>',
' <head>',
' <meta charset="utf-8">',
' <meta name="viewport" content="width=device-width">',
` <title>Index of ${he.encode(pathname)}</title>`,
` <style type="text/css">${css}</style>`,
' </head>',
' <body>',
`<h1>Index of ${he.encode(pathname)}</h1>`,
].join('\n')}\n`;
html += '<table>';
const failed = false;
const writeRow = (file) => {
// render a row given a [name, stat] tuple
const isDir = file[1].isDirectory && file[1].isDirectory();
let href = `${parsed.pathname.replace(/\/$/, '')}/${encodeURIComponent(file[0])}`;
// append trailing slash and query for dir entry
if (isDir) {
href += `/${he.encode((parsed.search) ? parsed.search : '')}`;
}
const displayName = he.encode(file[0]) + ((isDir) ? '/' : '');
const ext = file[0].split('.').pop();
const classForNonDir = supportedIcons[ext] ? ext : '_page';
const iconClass = `icon-${isDir ? '_blank' : classForNonDir}`;
// TODO: use stylessheets?
html += `${'<tr>' +
'<td><i class="icon '}${iconClass}"></i></td>`;
if (!hidePermissions) {
html += `<td class="perms"><code>(${permsToString(file[1])})</code></td>`;
}
html +=
`<td class="file-size"><code>${sizeToString(file[1], humanReadable, si)}</code></td>` +
`<td class="display-name"><a href="${href}">${displayName}</a></td>` +
'</tr>\n';
};
dirs.sort((a, b) => a[0].toString().localeCompare(b[0].toString())).forEach(writeRow);
renderFiles.sort((a, b) => a.toString().localeCompare(b.toString())).forEach(writeRow);
lolwuts.sort((a, b) => a[0].toString().localeCompare(b[0].toString())).forEach(writeRow);
html += '</table>\n';
html += `<br><address>Node.js ${
process.version
}/ <a href="https://github.com/jfhbrook/node-ecstatic">ecstatic</a> ` +
`server running @ ${
he.encode(req.headers.host || '')}</address>\n` +
'</body></html>'
;
if (!failed) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(html);
}
}
sortFiles(dir, files, (lolwuts, dirs, sortedFiles) => {
// It's possible to get stat errors for all sorts of reasons here.
// Unfortunately, our two choices are to either bail completely,
// or just truck along as though everything's cool. In this case,
// I decided to just tack them on as "??!?" items along with dirs
// and files.
//
// Whatever.
// if it makes sense to, add a .. link
if (path.resolve(dir, '..').slice(0, root.length) === root) {
fs.stat(path.join(dir, '..'), (err, s) => {
if (err) {
if (handleError) {
status[500](res, next, { error: err });
} else {
next();
}
return;
}
dirs.unshift(['..', s]);
render(dirs, sortedFiles, lolwuts);
});
} else {
render(dirs, sortedFiles, lolwuts);
}
});
});
});
};
};
| ManakCP/NestJs | node_modules/ecstatic/lib/ecstatic/show-dir/index.js | JavaScript | mit | 5,853 |
'use strict'
const assert = require('assert')
const http = require('http')
const https = require('https')
const { kState, kOptions } = require('./symbols')
const {
codes: { FST_ERR_HTTP2_INVALID_VERSION }
} = require('./errors')
function createServer (options, httpHandler) {
assert(options, 'Missing options')
assert(httpHandler, 'Missing http handler')
var server = null
if (options.serverFactory) {
server = options.serverFactory(httpHandler, options)
} else if (options.https) {
if (options.http2) {
server = http2().createSecureServer(options.https, httpHandler)
} else {
server = https.createServer(options.https, httpHandler)
}
} else if (options.http2) {
server = http2().createServer(httpHandler)
server.on('session', sessionTimeout(options.http2SessionTimeout))
} else {
server = http.createServer(httpHandler)
}
return { server, listen }
// `this` is the Fastify object
function listen () {
const normalizeListenArgs = (args) => {
if (args.length === 0) {
return { port: 0, host: 'localhost' }
}
const cb = typeof args[args.length - 1] === 'function' ? args.pop() : undefined
const options = { cb: cb }
const firstArg = args[0]
const argsLength = args.length
const lastArg = args[argsLength - 1]
/* Deal with listen (options) || (handle[, backlog]) */
if (typeof firstArg === 'object' && firstArg !== null) {
options.backlog = argsLength > 1 ? lastArg : undefined
Object.assign(options, firstArg)
} else if (typeof firstArg === 'string' && isNaN(firstArg)) {
/* Deal with listen (pipe[, backlog]) */
options.path = firstArg
options.backlog = argsLength > 1 ? lastArg : undefined
} else {
/* Deal with listen ([port[, host[, backlog]]]) */
options.port = argsLength >= 1 && firstArg ? firstArg : 0
// This will listen to what localhost is.
// It can be 127.0.0.1 or ::1, depending on the operating system.
// Fixes https://github.com/fastify/fastify/issues/1022.
options.host = argsLength >= 2 && args[1] ? args[1] : 'localhost'
options.backlog = argsLength >= 3 ? args[2] : undefined
}
return options
}
const listenOptions = normalizeListenArgs(Array.from(arguments))
const cb = listenOptions.cb
const wrap = err => {
server.removeListener('error', wrap)
if (!err) {
const address = logServerAddress()
cb(null, address)
} else {
this[kState].listening = false
cb(err, null)
}
}
const listenPromise = (listenOptions) => {
if (this[kState].listening) {
return Promise.reject(new Error('Fastify is already listening'))
}
return this.ready().then(() => {
var errEventHandler
var errEvent = new Promise((resolve, reject) => {
errEventHandler = (err) => {
this[kState].listening = false
reject(err)
}
server.once('error', errEventHandler)
})
var listen = new Promise((resolve, reject) => {
server.listen(listenOptions, () => {
server.removeListener('error', errEventHandler)
resolve(logServerAddress())
})
// we set it afterwards because listen can throw
this[kState].listening = true
})
return Promise.race([
errEvent, // e.g invalid port range error is always emitted before the server listening
listen
])
})
}
const logServerAddress = () => {
var address = server.address()
const isUnixSocket = typeof address === 'string'
if (!isUnixSocket) {
if (address.address.indexOf(':') === -1) {
address = address.address + ':' + address.port
} else {
address = '[' + address.address + ']:' + address.port
}
}
address = (isUnixSocket ? '' : ('http' + (this[kOptions].https ? 's' : '') + '://')) + address
this.log.info('Server listening at ' + address)
return address
}
if (cb === undefined) return listenPromise(listenOptions)
this.ready(err => {
if (err != null) return cb(err)
if (this[kState].listening) {
return cb(new Error('Fastify is already listening'), null)
}
server.once('error', wrap)
server.listen(listenOptions, wrap)
this[kState].listening = true
})
}
}
function http2 () {
try {
return require('http2')
} catch (err) {
throw new FST_ERR_HTTP2_INVALID_VERSION()
}
}
function sessionTimeout (timeout) {
return function (session) {
session.setTimeout(timeout, close)
}
}
function close () {
this.close()
}
module.exports = { createServer }
| cdnjs/cdnjs | ajax/libs/fastify/2.15.3/lib/server.js | JavaScript | mit | 4,813 |
module.exports={title:"LiveChat",slug:"livechat",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>LiveChat</title><path d="'+this.path+'"/></svg>'},path:"M23.849 14.91c-.24 2.94-2.73 5.22-5.7 5.19h-3.15l-6 3.9v-3.9l6-3.9h3.15c.93.03 1.71-.66 1.83-1.59.18-3 .18-6-.06-9-.06-.84-.75-1.47-1.56-1.53-2.04-.09-4.2-.18-6.36-.18s-4.32.06-6.36.21c-.84.06-1.5.69-1.56 1.53-.21 3-.24 6-.06 9 .09.93.9 1.59 1.83 1.56h3.15v3.9h-3.15a5.644 5.644 0 01-5.7-5.19c-.21-3.21-.18-6.39.06-9.6a5.57 5.57 0 015.19-5.1c2.1-.15 4.35-.21 6.6-.21s4.5.06 6.63.24a5.57 5.57 0 015.19 5.1c.21 3.18.24 6.39.03 9.57z",source:"https://livechat.design/",hex:"FFD000",guidelines:"https://livechat.design/",license:void 0}; | cdnjs/cdnjs | ajax/libs/simple-icons/5.24.0/livechat.min.js | JavaScript | mit | 733 |
OW_FriendRequest = function( itemKey, params )
{
var listLoaded = false;
var model = OW.Console.getData(itemKey);
var list = OW.Console.getItem(itemKey);
var counter = new OW_DataModel();
counter.addObserver(this);
this.onDataChange = function( data )
{
var newCount = data.get('new');
var counterNumber = newCount > 0 ? newCount : data.get('all');
list.setCounter(counterNumber, newCount > 0);
if ( counterNumber > 0 )
{
list.showItem();
}
};
list.onHide = function()
{
counter.set('new', 0);
list.getItems().removeClass('ow_console_new_message');
model.set('counter', counter.get());
};
list.onShow = function()
{
if ( counter.get('all') <= 0 )
{
this.showNoContent();
return;
}
if ( counter.get('new') > 0 || !listLoaded )
{
this.loadList();
listLoaded = true;
}
};
model.addObserver(function()
{
if ( !list.opened )
{
counter.set(model.get('counter'));
}
});
this.accept = function( requestKey, userId )
{
var item = list.getItem(requestKey);
var c = {};
if ( item.hasClass('ow_console_new_message') )
{
c["new"] = counter.get("new") - 1;
}
c["all"] = counter.get("all") - 1;
counter.set(c);
this.send('friends-accept', {id: userId});
$('#friend_request_accept_'+userId).addClass( "ow_hidden");
$('#friend_request_ignore_'+userId).addClass( "ow_hidden");
return this;
};
this.ignore = function( requestKey, userId )
{
var item = list.getItem(requestKey);
var c = {};
this.send('friends-ignore', {id: userId});
if ( item.hasClass('ow_console_new_message') )
{
c["new"] = counter.get("new") - 1;
}
c["all"] = counter.get("all") - 1;
counter.set(c);
list.removeItem(item);
return this;
};
this.send = function( command, data )
{
var request = $.ajax({
url: params.rsp,
type: "POST",
data: {
"command": command,
"data": JSON.stringify(data)
},
dataType: "json"
});
request.done(function( res )
{
if ( res && res.script )
{
OW.addScript(res.script);
}
});
return this;
};
}
OW.FriendRequest = null; | seret/oxtebafu | ow_static/plugins/friends/js/friend_request.js | JavaScript | gpl-2.0 | 2,629 |
jQuery(document).ready(function($) {
$(".zilla-tabs").tabs();
$(".zilla-toggle").each( function () {
var $this = $(this);
if( $this.attr('data-id') == 'closed' ) {
$this.accordion({ header: '.zilla-toggle-title', collapsible: true, active: false });
} else {
$this.accordion({ header: '.zilla-toggle-title', collapsible: true});
}
$this.on('accordionactivate', function( e, ui ) {
$this.accordion('refresh');
});
$(window).on('resize', function() {
$this.accordion('refresh');
});
});
}); | XDocker/web | wp-content/themes/scrolle/admin/zilla-shortcodes/js/zilla-shortcodes-lib.js | JavaScript | gpl-2.0 | 529 |
;(function (window, document) {
'use strict';
/**
* Global storage manager
*
* The storage manager provides a unified way to store items in the localStorage and sessionStorage.
* It uses a polyfill that uses cookies as a fallback when no localStorage or sessionStore is available or working.
*
* @example
*
* Saving an item to localStorage:
*
* StorageManager.setItem('local', 'key', 'value');
*
* Retrieving it:
*
* var item = StorageManager.getItem('local', 'key'); // item === 'value'
*
* Basically you can use every method of the Storage interface (http://www.w3.org/TR/webstorage/#the-storage-interface)
* But notice that you have to pass the storage type ('local' | 'session') in the first parameter for every call.
*
* @example
*
* Getting the localStorage/sessionStorage (polyfill) object
*
* var localStorage = StorageManager.getStorage('local');
* var sessionStorage = StorageManager.getStorage('session');
*
* You can also use its shorthands:
*
* var localStorage = StorageManager.getLocalStorage();
* var sessionStorage = StorageManager.getSessionStorage();
*/
window.StorageManager = (function () {
var storage = {
local: window.localStorage,
session: window.sessionStorage
},
p;
/**
* Helper function to detect if cookies are enabled.
* @returns {boolean}
*/
function hasCookiesSupport() {
// if cookies are already present assume cookie support
if ('cookie' in document && (document.cookie.length > 0)) {
return true;
}
document.cookie = 'testcookie=1;';
var writeTest = (document.cookie.indexOf('testcookie') !== -1);
document.cookie = 'testcookie=1' + ';expires=Sat, 01-Jan-2000 00:00:00 GMT';
return writeTest;
}
// test for safari's "QUOTA_EXCEEDED_ERR: DOM Exception 22" issue.
for (p in storage) {
if (!storage.hasOwnProperty(p)) {
continue;
}
try {
storage[p].setItem('storage', '');
storage[p].removeItem('storage');
} catch (err) {
}
}
// Just return the public API instead of all available functions
return {
/**
* Returns the storage object/polyfill of the given type.
*
* @returns {Storage|StoragePolyFill}
*/
getStorage: function (type) {
return storage[type];
},
/**
* Returns the sessionStorage object/polyfill.
*
* @returns {Storage|StoragePolyFill}
*/
getSessionStorage: function () {
return this.getStorage('session');
},
/**
* Returns the localStorage object/polyfill.
*
* @returns {Storage|StoragePolyFill}
*/
getLocalStorage: function () {
return this.getStorage('local');
},
/**
* Calls the clear() method of the storage from the given type.
*
* @param {String} type
*/
clear: function (type) {
this.getStorage(type).clear();
},
/**
* Calls the getItem() method of the storage from the given type.
*
* @param {String} type
* @param {String} key
* @returns {String}
*/
getItem: function (type, key) {
return this.getStorage(type).getItem(key);
},
/**
* Calls the key() method of the storage from the given type.
*
* @param {String} type
* @param {Number|String} i
* @returns {String}
*/
key: function (type, i) {
return this.getStorage(type).key(i);
},
/**
* Calls the removeItem() method of the storage from the given type.
*
* @param {String} type
* @param {String} key
*/
removeItem: function (type, key) {
this.getStorage(type).removeItem(key);
},
/**
* Calls the setItem() method of the storage from the given type.
*
* @param {String} type
* @param {String} key
* @param {String} value
*/
setItem: function (type, key, value) {
this.getStorage(type).setItem(key, value);
},
/**
* Helper function call to check if cookies are enabled.
*/
hasCookiesSupport: hasCookiesSupport()
};
})();
})(window, document);
| jhit/shopware | themes/Frontend/Responsive/frontend/_public/src/js/jquery.storage-manager.js | JavaScript | agpl-3.0 | 5,074 |
// [Name] SVGFECompositeElement-dom-k1-attr.js
// [Expected rendering result] Four circle with different opacity merged with feComposite filter - and a series of PASS messages
description("Tests dynamic updates of the 'k1' attribute of the SVGFECompositeElement object")
createSVGTestCase();
var defsElement = createSVGElement("defs");
rootSVGElement.appendChild(defsElement);
var off1 = createSVGElement("feOffset");
off1.setAttribute("dx", "35");
off1.setAttribute("dy", "25");
off1.setAttribute("result", "off1");
var flood1 = createSVGElement("feFlood");
flood1.setAttribute("flood-color", "#408067");
flood1.setAttribute("flood-opacity", ".8");
flood1.setAttribute("result", "F1");
var overComposite1 = createSVGElement("feComposite");
overComposite1.setAttribute("in", "F1");
overComposite1.setAttribute("in2", "off1");
overComposite1.setAttribute("operator", "arithmetic");
overComposite1.setAttribute("k1", "1.9");
overComposite1.setAttribute("k2", ".1");
overComposite1.setAttribute("k3", ".5");
overComposite1.setAttribute("k4", ".3");
overComposite1.setAttribute("result", "C1");
var off2 = createSVGElement("feOffset");
off2.setAttribute("in", "SourceGraphic");
off2.setAttribute("dx", "60");
off2.setAttribute("dy", "50");
off2.setAttribute("result", "off2");
var flood2 = createSVGElement("feFlood");
flood2.setAttribute("flood-color", "#408067");
flood2.setAttribute("flood-opacity", ".6");
flood2.setAttribute("result", "F2");
var overComposite2 = createSVGElement("feComposite");
overComposite2.setAttribute("in", "F2");
overComposite2.setAttribute("in2", "off2");
overComposite2.setAttribute("operator", "in");
overComposite2.setAttribute("result", "C2");
var off3 = createSVGElement("feOffset");
off3.setAttribute("in", "SourceGraphic");
off3.setAttribute("dx", "85");
off3.setAttribute("dy", "75");
off3.setAttribute("result", "off3");
var flood3 = createSVGElement("feFlood");
flood3.setAttribute("flood-color", "#408067");
flood3.setAttribute("flood-opacity", ".4");
flood3.setAttribute("result", "F3");
var overComposite3 = createSVGElement("feComposite");
overComposite3.setAttribute("in2", "off3");
overComposite3.setAttribute("operator", "in");
overComposite3.setAttribute("result", "C3");
var merge = createSVGElement("feMerge");
var mergeNode1 = createSVGElement("feMergeNode");
mergeNode1.setAttribute("in", "C1");
var mergeNode2 = createSVGElement("feMergeNode");
mergeNode2.setAttribute("in", "C2");
var mergeNode3 = createSVGElement("feMergeNode");
mergeNode3.setAttribute("in", "C3");
var mergeNode4 = createSVGElement("feMergeNode");
mergeNode4.setAttribute("in", "SourceGraphic");
merge.appendChild(mergeNode3);
merge.appendChild(mergeNode2);
merge.appendChild(mergeNode1);
merge.appendChild(mergeNode4);
var overFilter = createSVGElement("filter");
overFilter.setAttribute("id", "overFilter");
overFilter.setAttribute("filterUnits", "objectBoundingBox");
overFilter.setAttribute("x", "0");
overFilter.setAttribute("y", "0");
overFilter.setAttribute("width", "3.5");
overFilter.setAttribute("height", "4");
overFilter.appendChild(off1);
overFilter.appendChild(flood1);
overFilter.appendChild(overComposite1);
overFilter.appendChild(off2);
overFilter.appendChild(flood2);
overFilter.appendChild(overComposite2);
overFilter.appendChild(off3);
overFilter.appendChild(flood3);
overFilter.appendChild(overComposite3);
overFilter.appendChild(merge);
defsElement.appendChild(overFilter);
rootSVGElement.setAttribute("height", "200");
var rect1 = createSVGElement("circle");
rect1.setAttribute("cx", "100");
rect1.setAttribute("cy", "50");
rect1.setAttribute("r", "50");
rect1.setAttribute("fill", "#408067");
rect1.setAttribute("filter", "url(#overFilter)");
rootSVGElement.appendChild(rect1);
shouldBeEqualToString("overComposite1.getAttribute('k1')", "1.9");
function repaintTest() {
overComposite1.setAttribute("k1", ".5");
shouldBeEqualToString("overComposite1.getAttribute('k1')", ".5");
completeTest();
}
var successfullyParsed = true;
| youfoh/webkit-efl | LayoutTests/svg/dynamic-updates/script-tests/SVGFECompositeElement-dom-k1-attr.js | JavaScript | lgpl-2.1 | 4,008 |
// register-web-ui-test.js
//
// Test that the home page shows an invitation to join
//
// Copyright 2012, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var assert = require("assert"),
vows = require("vows"),
oauthutil = require("./lib/oauth"),
Browser = require("zombie"),
Step = require("step"),
setupApp = oauthutil.setupApp,
setupAppConfig = oauthutil.setupAppConfig;
var suite = vows.describe("layout test");
// A batch to test some of the layout basics
suite.addBatch({
"When we set up the app": {
topic: function() {
setupAppConfig({site: "Test"}, this.callback);
},
teardown: function(app) {
if (app && app.close) {
app.close();
}
},
"it works": function(err, app) {
assert.ifError(err);
},
"and we visit the root URL": {
topic: function() {
var browser,
callback = this.callback;
browser = new Browser();
browser.visit("http://localhost:4815/main/register", function(err, br) {
callback(err, br);
});
},
"it works": function(err, br) {
assert.ifError(err);
assert.isTrue(br.success);
},
"and we check the content": {
topic: function(br) {
var callback = this.callback;
callback(null, br);
},
"it includes a registration div": function(err, br) {
assert.ok(br.query("div#registerpage"));
},
"it includes a registration form": function(err, br) {
assert.ok(br.query("div#registerpage form"));
},
"the registration form has a nickname field": function(err, br) {
assert.ok(br.query("div#registerpage form input[name=\"nickname\"]"));
},
"the registration form has a password field": function(err, br) {
assert.ok(br.query("div#registerpage form input[name=\"password\"]"));
},
"the registration form has a password repeat field": function(err, br) {
assert.ok(br.query("div#registerpage form input[name=\"repeat\"]"));
},
"the registration form has a submit button": function(err, br) {
assert.ok(br.query("div#registerpage form button[type=\"submit\"]"));
},
"and we submit the form": {
topic: function() {
var callback = this.callback,
br = arguments[0];
Step(
function() {
br.fill("nickname", "sparks", this);
},
function(err) {
if (err) throw err;
br.fill("password", "redplainsrider1", this);
},
function(err) {
if (err) throw err;
br.fill("repeat", "redplainsrider1", this);
},
function(err) {
if (err) throw err;
br.pressButton("button[type=\"submit\"]", this);
},
function(err) {
if (err) {
callback(err, null);
} else {
callback(null, br);
}
}
);
},
"it works": function(err, br) {
assert.ifError(err);
assert.isTrue(br.success);
}
}
}
}
}
});
suite["export"](module);
| OpenSocial/pump.io | test/register-web-ui-test.js | JavaScript | apache-2.0 | 4,694 |
/*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This file handles the search result data.
*
* @since 1.4.1
* @author [email protected]
*/
define([
'./search-result-model',
], function (
model
) {
'use strict';
/**
* search with the given metadata.
* @param {Object} metadata - search condition(keyword, replace with, scope, options)
* @param {viewCallback} callback - out-param(search results)
*/
function handleFind(metadata, callback) {
model.makeFindData(metadata, function (err, title, store) {
if (err) {
callback(err);
} else {
callback(null, {
title : title,
store : store
});
}
});
}
/**
* replace the code with the given metadata.
* @param {Object} metadata - replacing condition(keyword, replace with, scope, options)
* @param {viewCallback} callback - out-param(the replacement result)
*/
function handleReplace(metadata, callback) {
model.makeReplaceData(metadata, function (err, title) {
if (err) {
callback(err);
} else {
callback(null, title);
}
});
}
/**
* set the search scope
* @param {string} scope - set the range of scope(selection, project, workspace)
* @param {ViewCallback} callback - out-param(a path of scope)
*/
function handleSelection(scope, callback) {
model.getScopePath(scope, function (err, scope) {
if (err) {
callback(err);
} else {
callback(null, scope);
}
});
}
/**
* select item replaced
* @param {object} item - item replaced or not
* @param {boolean} checked - item value
* @param {ViewCallback} callback - set a value in the view.
*/
function handleCheckbox(item, checked, callback) {
model.updateReplacePaths(item, checked, function () {
callback();
});
}
return {
handleFind : handleFind,
handleReplace : handleReplace,
handleSelection : handleSelection,
handleCheckbox : handleCheckbox
};
});
| kyungmi/webida-client | apps/ide/src/plugins/webida.ide.search-result/search-result-controller.js | JavaScript | apache-2.0 | 2,843 |
//// [stringLiteralTypesOverloads03.ts]
interface Base {
x: string;
y: number;
}
interface HelloOrWorld extends Base {
p1: boolean;
}
interface JustHello extends Base {
p2: boolean;
}
interface JustWorld extends Base {
p3: boolean;
}
let hello: "hello";
let world: "world";
let helloOrWorld: "hello" | "world";
function f(p: "hello"): JustHello;
function f(p: "hello" | "world"): HelloOrWorld;
function f(p: "world"): JustWorld;
function f(p: string): Base;
function f(...args: any[]): any {
return undefined;
}
let fResult1 = f(hello);
let fResult2 = f(world);
let fResult3 = f(helloOrWorld);
function g(p: string): Base;
function g(p: "hello"): JustHello;
function g(p: "hello" | "world"): HelloOrWorld;
function g(p: "world"): JustWorld;
function g(...args: any[]): any {
return undefined;
}
let gResult1 = g(hello);
let gResult2 = g(world);
let gResult3 = g(helloOrWorld);
//// [stringLiteralTypesOverloads03.js]
var hello;
var world;
var helloOrWorld;
function f() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return undefined;
}
var fResult1 = f(hello);
var fResult2 = f(world);
var fResult3 = f(helloOrWorld);
function g() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return undefined;
}
var gResult1 = g(hello);
var gResult2 = g(world);
var gResult3 = g(helloOrWorld);
//// [stringLiteralTypesOverloads03.d.ts]
interface Base {
x: string;
y: number;
}
interface HelloOrWorld extends Base {
p1: boolean;
}
interface JustHello extends Base {
p2: boolean;
}
interface JustWorld extends Base {
p3: boolean;
}
declare let hello: "hello";
declare let world: "world";
declare let helloOrWorld: "hello" | "world";
declare function f(p: "hello"): JustHello;
declare function f(p: "hello" | "world"): HelloOrWorld;
declare function f(p: "world"): JustWorld;
declare function f(p: string): Base;
declare let fResult1: JustHello;
declare let fResult2: JustWorld;
declare let fResult3: HelloOrWorld;
declare function g(p: string): Base;
declare function g(p: "hello"): JustHello;
declare function g(p: "hello" | "world"): HelloOrWorld;
declare function g(p: "world"): JustWorld;
declare let gResult1: JustHello;
declare let gResult2: JustWorld;
declare let gResult3: Base;
| jwbay/TypeScript | tests/baselines/reference/stringLiteralTypesOverloads03.js | JavaScript | apache-2.0 | 2,432 |
(function() {
'use strict';
angular.module('replicationControllers', [])
.service('replicationControllerService', ['$q', ReplicationControllerDataService]);
/**
* Replication Controller DataService
* Mock async data service.
*
* @returns {{loadAll: Function}}
* @constructor
*/
function ReplicationControllerDataService($q) {
var replicationControllers = {
"kind": "List",
"apiVersion": "v1",
"metadata": {},
"items": [
{
"kind": "ReplicationController",
"apiVersion": "v1",
"metadata": {
"name": "redis-master",
"namespace": "default",
"selfLink": "/api/v1/namespaces/default/replicationcontrollers/redis-master",
"uid": "f12969e0-ff77-11e4-8f2d-080027213276",
"resourceVersion": "28",
"creationTimestamp": "2015-05-21T05:12:14Z",
"labels": {
"name": "redis-master"
}
},
"spec": {
"replicas": 1,
"selector": {
"name": "redis-master"
},
"template": {
"metadata": {
"creationTimestamp": null,
"labels": {
"name": "redis-master"
}
},
"spec": {
"containers": [
{
"name": "master",
"image": "redis",
"ports": [
{
"containerPort": 6379,
"protocol": "TCP"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"imagePullPolicy": "IfNotPresent",
"capabilities": {},
"securityContext": {
"capabilities": {},
"privileged": false
}
}
],
"restartPolicy": "Always",
"dnsPolicy": "ClusterFirst",
"serviceAccount": ""
}
}
},
"status": {
"replicas": 1
}
}
]};
// Uses promises
return {
loadAll: function() {
// Simulate async call
return $q.when(replicationControllers);
}
};
}
})();
| kubernetes-ui/kube-ui | master/components/dashboard/js/modules/services/replicationControllersMock.js | JavaScript | apache-2.0 | 2,865 |
module.exports = function(hljs) {
var ELIXIR_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_.]*(\\!|\\?)?';
var ELIXIR_METHOD_RE = '[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?';
var ELIXIR_KEYWORDS =
'and false then defined module in return redo retry end for true self when ' +
'next until do begin unless nil break not case cond alias while ensure or ' +
'include use alias fn quote require import with|0';
var SUBST = {
className: 'subst',
begin: '#\\{', end: '}',
lexemes: ELIXIR_IDENT_RE,
keywords: ELIXIR_KEYWORDS
};
var SIGIL_DELIMITERS = '[/|([{<"\']'
var LOWERCASE_SIGIL = {
className: 'string',
begin: '~[a-z]' + '(?=' + SIGIL_DELIMITERS + ')',
contains: [
{
endsParent:true,
contains: [{
contains: [hljs.BACKSLASH_ESCAPE, SUBST],
variants: [
{ begin: /"/, end: /"/ },
{ begin: /'/, end: /'/ },
{ begin: /\//, end: /\// },
{ begin: /\|/, end: /\|/ },
{ begin: /\(/, end: /\)/ },
{ begin: /\[/, end: /\]/ },
{ begin: /\{/, end: /\}/ },
{ begin: /</, end: />/ }
]
}]
},
],
};
var UPCASE_SIGIL = {
className: 'string',
begin: '~[A-Z]' + '(?=' + SIGIL_DELIMITERS + ')',
contains: [
{ begin: /"/, end: /"/ },
{ begin: /'/, end: /'/ },
{ begin: /\//, end: /\// },
{ begin: /\|/, end: /\|/ },
{ begin: /\(/, end: /\)/ },
{ begin: /\[/, end: /\]/ },
{ begin: /\{/, end: /\}/ },
{ begin: /\</, end: /\>/ }
]
};
var STRING = {
className: 'string',
contains: [hljs.BACKSLASH_ESCAPE, SUBST],
variants: [
{
begin: /"""/, end: /"""/,
},
{
begin: /'''/, end: /'''/,
},
{
begin: /~S"""/, end: /"""/,
contains: []
},
{
begin: /~S"/, end: /"/,
contains: []
},
{
begin: /~S'''/, end: /'''/,
contains: []
},
{
begin: /~S'/, end: /'/,
contains: []
},
{
begin: /'/, end: /'/
},
{
begin: /"/, end: /"/
},
]
};
var FUNCTION = {
className: 'function',
beginKeywords: 'def defp defmacro', end: /\B\b/, // the mode is ended by the title
contains: [
hljs.inherit(hljs.TITLE_MODE, {
begin: ELIXIR_IDENT_RE,
endsParent: true
})
]
};
var CLASS = hljs.inherit(FUNCTION, {
className: 'class',
beginKeywords: 'defimpl defmodule defprotocol defrecord', end: /\bdo\b|$|;/
});
var ELIXIR_DEFAULT_CONTAINS = [
STRING,
UPCASE_SIGIL,
LOWERCASE_SIGIL,
hljs.HASH_COMMENT_MODE,
CLASS,
FUNCTION,
{
begin: '::'
},
{
className: 'symbol',
begin: ':(?![\\s:])',
contains: [STRING, {begin: ELIXIR_METHOD_RE}],
relevance: 0
},
{
className: 'symbol',
begin: ELIXIR_IDENT_RE + ':(?!:)',
relevance: 0
},
{
className: 'number',
begin: '(\\b0o[0-7_]+)|(\\b0b[01_]+)|(\\b0x[0-9a-fA-F_]+)|(-?\\b[1-9][0-9_]*(.[0-9_]+([eE][-+]?[0-9]+)?)?)',
relevance: 0
},
{
className: 'variable',
begin: '(\\$\\W)|((\\$|\\@\\@?)(\\w+))'
},
{
begin: '->'
},
{ // regexp container
begin: '(' + hljs.RE_STARTERS_RE + ')\\s*',
contains: [
hljs.HASH_COMMENT_MODE,
{
className: 'regexp',
illegal: '\\n',
contains: [hljs.BACKSLASH_ESCAPE, SUBST],
variants: [
{
begin: '/', end: '/[a-z]*'
},
{
begin: '%r\\[', end: '\\][a-z]*'
}
]
}
],
relevance: 0
}
];
SUBST.contains = ELIXIR_DEFAULT_CONTAINS;
return {
lexemes: ELIXIR_IDENT_RE,
keywords: ELIXIR_KEYWORDS,
contains: ELIXIR_DEFAULT_CONTAINS
};
}; | ZenekeZene/zenekezene.github.io | node_modules/highlight.js/lib/languages/elixir.js | JavaScript | apache-2.0 | 3,976 |
CKEDITOR.plugins.setLang("flash","eu",{access:"Scriptak baimendu",accessAlways:"Beti",accessNever:"Inoiz ere ez",accessSameDomain:"Domeinu berdinekoak",alignAbsBottom:"Abs Behean",alignAbsMiddle:"Abs Erdian",alignBaseline:"Oinan",alignTextTop:"Testua Goian",bgcolor:"Atzeko kolorea",chkFull:"Onartu Pantaila osoa",chkLoop:"Begizta",chkMenu:"Flasharen Menua Gaitu",chkPlay:"Automatikoki Erreproduzitu",flashvars:"Flash Aldagaiak",hSpace:"HSpace",properties:"Flasharen Ezaugarriak",propertiesTab:"Ezaugarriak",
quality:"Kalitatea",qualityAutoHigh:"Auto Altua",qualityAutoLow:"Auto Baxua",qualityBest:"Hoberena",qualityHigh:"Altua",qualityLow:"Baxua",qualityMedium:"Ertaina",scale:"Eskalatu",scaleAll:"Dena erakutsi",scaleFit:"Doitu",scaleNoBorder:"Ertzik gabe",title:"Flasharen Ezaugarriak",vSpace:"VSpace",validateHSpace:"HSpace zenbaki bat izan behar da.",validateSrc:"Mesedez URL esteka idatzi",validateVSpace:"VSpace zenbaki bat izan behar da.",windowMode:"Leihoaren modua",windowModeOpaque:"Opakoa",windowModeTransparent:"Gardena",
windowModeWindow:"Leihoa"}); | viticm/pfadmin | vendor/frozennode/administrator/public/js/ckeditor/plugins/flash/lang/eu.js | JavaScript | apache-2.0 | 1,063 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* The length property of the search method is 1
*
* @path ch15/15.5/15.5.4/15.5.4.12/S15.5.4.12_A11.js
* @description Checking String.prototype.search.length
*/
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (!(String.prototype.search.hasOwnProperty("length"))) {
$ERROR('#1: String.prototype.search.hasOwnProperty("length") return true. Actual: '+String.prototype.search.hasOwnProperty("length"));
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#2
if (String.prototype.search.length !== 1) {
$ERROR('#2: String.prototype.search.length === 1. Actual: '+String.prototype.search.length );
}
//
//////////////////////////////////////////////////////////////////////////////
| hippich/typescript | tests/Fidelity/test262/suite/ch15/15.5/15.5.4/15.5.4.12/S15.5.4.12_A11.js | JavaScript | apache-2.0 | 988 |
// This file was procedurally generated from the following sources:
// - src/dstr-binding-for-await/ary-ptrn-rest-id-iter-step-err.case
// - src/dstr-binding-for-await/error/for-await-of-async-gen-var.template
/*---
description: Error forwarding when IteratorStep returns an abrupt completion (for-await-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
features: [generators, destructuring-binding, async-iteration]
flags: [generated, async]
info: |
IterationStatement :
for await ( ForDeclaration of AssignmentExpression ) Statement
[...]
2. Return ? ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult,
lexicalBinding, labelSet, async).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
4. Let destructuring be IsDestructuring of lhs.
[...]
6. Repeat
[...]
j. If destructuring is false, then
[...]
k. Else
i. If lhsKind is assignment, then
[...]
ii. Else if lhsKind is varBinding, then
[...]
iii. Else,
1. Assert: lhsKind is lexicalBinding.
2. Assert: lhs is a ForDeclaration.
3. Let status be the result of performing BindingInitialization
for lhs passing nextValue and iterationEnv as arguments.
[...]
13.3.3.6 Runtime Semantics: IteratorBindingInitialization
BindingRestElement : ... BindingIdentifier
1. Let lhs be ResolveBinding(StringValue of BindingIdentifier,
environment).
2. ReturnIfAbrupt(lhs). 3. Let A be ArrayCreate(0). 4. Let n=0. 5. Repeat,
a. If iteratorRecord.[[done]] is false,
i. Let next be IteratorStep(iteratorRecord.[[iterator]]).
ii. If next is an abrupt completion, set iteratorRecord.[[done]] to
true.
iii. ReturnIfAbrupt(next).
---*/
var first = 0;
var second = 0;
var iter = function*() {
first += 1;
throw new Test262Error();
second += 1;
}();
async function * gen() {
for await (var [...x] of [iter]) {
return;
}
}
gen().next()
.then(_ => {
throw new Test262Error("Expected async function to reject, but resolved.");
}, ({ constructor }) => {
assert.sameValue(constructor, Test262Error);
})
.then($DONE, $DONE);
| sebastienros/jint | Jint.Tests.Test262/test/language/statements/for-await-of/async-gen-dstr-var-ary-ptrn-rest-id-iter-step-err.js | JavaScript | bsd-2-clause | 2,326 |
// This file was procedurally generated from the following sources:
// - src/dstr-binding-for-await/obj-ptrn-id-init-fn-name-cover.case
// - src/dstr-binding-for-await/default/for-await-of-async-gen-const.template
/*---
description: SingleNameBinding assigns `name` to "anonymous" functions "through" cover grammar (for-await-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
features: [destructuring-binding, async-iteration]
flags: [generated, async]
info: |
IterationStatement :
for await ( ForDeclaration of AssignmentExpression ) Statement
[...]
2. Return ? ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult,
lexicalBinding, labelSet, async).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
4. Let destructuring be IsDestructuring of lhs.
[...]
6. Repeat
[...]
j. If destructuring is false, then
[...]
k. Else
i. If lhsKind is assignment, then
[...]
ii. Else if lhsKind is varBinding, then
[...]
iii. Else,
1. Assert: lhsKind is lexicalBinding.
2. Assert: lhs is a ForDeclaration.
3. Let status be the result of performing BindingInitialization
for lhs passing nextValue and iterationEnv as arguments.
[...]
13.3.3.7 Runtime Semantics: KeyedBindingInitialization
SingleNameBinding : BindingIdentifier Initializer_opt
[...]
6. If Initializer is present and v is undefined, then
[...]
d. If IsAnonymousFunctionDefinition(Initializer) is true, then
i. Let hasNameProperty be HasOwnProperty(v, "name").
ii. ReturnIfAbrupt(hasNameProperty).
iii. If hasNameProperty is false, perform SetFunctionName(v,
bindingId).
---*/
var iterCount = 0;
async function *fn() {
for await (const { cover = (function () {}), xCover = (0, function() {}) } of [{}]) {
assert.sameValue(cover.name, 'cover');
assert.notSameValue(xCover.name, 'xCover');
iterCount += 1;
}
}
fn().next()
.then(() => assert.sameValue(iterCount, 1, 'iteration occurred as expected'), $DONE)
.then($DONE, $DONE);
| sebastienros/jint | Jint.Tests.Test262/test/language/statements/for-await-of/async-gen-dstr-const-obj-ptrn-id-init-fn-name-cover.js | JavaScript | bsd-2-clause | 2,244 |
/*
* Copyright (c) 2008-2015 The Open Source Geospatial Foundation
*
* Published under the BSD license.
* See https://github.com/geoext/geoext2/blob/master/license.txt for the full
* text of the license.
*/
/*
* @include OpenLayers/Util.js
* @requires GeoExt/Version.js
*/
/**
* The permalink provider.
*
* Sample code displaying a new permalink each time the map is moved:
*
* // create permalink provider
* var permalinkProvider = Ext.create('GeoExt.state.PermalinkProvider', {});
* // set it in the state manager
* Ext.state.Manager.setProvider(permalinkProvider);
* // create a map panel, and make it stateful
* var mapPanel = Ext.create('GeoExt.panel.Map', {
* renderTo: "map",
* layers: [
* new OpenLayers.Layer.WMS(
* "Global Imagery",
* "http://maps.opengeo.org/geowebcache/service/wms",
* {layers: "bluemarble"}
* )
* ],
* stateId: "map",
* prettyStateKeys: true // for pretty permalinks
* });
* // display permalink each time state is changed
* permalinkProvider.on({
* statechange: function(provider, name, value) {
* alert(provider.getLink());
* }
* });
*
* @class GeoExt.state.PermalinkProvider
*/
Ext.define('GeoExt.state.PermalinkProvider', {
extend : 'Ext.state.Provider',
requires : [
'GeoExt.Version'
],
alias : 'widget.gx_permalinkprovider',
/**
*
*/
constructor: function(config){
this.callParent(arguments);
config = config || {};
var url = config.url;
delete config.url;
Ext.apply(this, config);
this.state = this.readURL(url);
},
/**
* Specifies whether type of state values should be encoded and decoded.
* Set it to `false` if you work with components that don't require
* encoding types, and want pretty permalinks.
*
* @property{Boolean}
* @private
*/
encodeType: true,
/**
* Create a state object from a URL.
*
* @param url {String} The URL to get the state from.
* @return {Object} The state object.
* @private
*/
readURL: function(url) {
var state = {};
var params = OpenLayers.Util.getParameters(url);
var k, split, stateId;
for(k in params) {
if(params.hasOwnProperty(k)) {
split = k.split("_");
if(split.length > 1) {
stateId = split[0];
state[stateId] = state[stateId] || {};
state[stateId][split.slice(1).join("_")] = this.encodeType ?
this.decodeValue(params[k]) : params[k];
}
}
}
return state;
},
/**
* Returns the permalink corresponding to the current state.
*
* @param base {String} The base URL, optional.
* @return {String} The permalink.
*/
getLink: function(base) {
base = base || document.location.href;
var params = {};
var id, k, state = this.state;
for(id in state) {
if(state.hasOwnProperty(id)) {
for(k in state[id]) {
params[id + "_" + k] = this.encodeType ?
unescape(this.encodeValue(state[id][k])) : state[id][k];
}
}
}
// merge params in the URL into the state params
OpenLayers.Util.applyDefaults(
params, OpenLayers.Util.getParameters(base));
var paramsStr = OpenLayers.Util.getParameterString(params);
var qMark = base.indexOf("?");
if(qMark > 0) {
base = base.substring(0, qMark);
}
return Ext.urlAppend(base, paramsStr);
}
});
| m-click/geoext2 | src/GeoExt/state/PermalinkProvider.js | JavaScript | bsd-3-clause | 3,856 |
tinyMCE.init({
theme: "advanced",
mode: "specific_textareas",
editor_selector: "tinymce",
plugins: "fullscreen,autoresize,searchreplace,mediapicker,inlinepopups",
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_buttons1: "search,replace,|,cut,copy,paste,|,undo,redo,|,mediapicker,|,link,unlink,charmap,emoticon,codeblock,|,bold,italic,|,numlist,bullist,formatselect,|,code,fullscreen",
theme_advanced_buttons2: "",
theme_advanced_buttons3: "",
convert_urls: false,
valid_elements: "*[*]",
// shouldn't be needed due to the valid_elements setting, but TinyMCE would strip script.src without it.
extended_valid_elements: "script[type|defer|src|language]"
});
| BankNotes/Web | src/Orchard.Web/Modules/TinyMce/Scripts/orchard-tinymce.js | JavaScript | bsd-3-clause | 772 |
// PhantomJS is missing Function.prototype.bind:
// http://code.google.com/p/phantomjs/issues/detail?id=522
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
| vince0508/wegoto_iD | test/lib/bind-shim.js | JavaScript | isc | 897 |
export default function identity(x) {
return x;
}
| d3/d3-arrays | src/identity.js | JavaScript | isc | 52 |
'use strict';
var _ = require('lodash');
var webpack = require('webpack');
var mergeWebpackConfig = function (config) {
// Load webpackConfig only when using `grunt:webpack`
// load of grunt tasks is faster
var webpackConfig = require('./webpack.config');
return _.merge({}, webpackConfig, config, function (a, b) {
if (_.isArray(a)) {
return a.concat(b);
}
});
};
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sass: {
min: {
files: {
'dist/react-datepicker.css': 'src/stylesheets/datepicker.scss'
},
options: {
sourcemap: 'none',
style: 'expanded'
}
},
unmin: {
files: {
'dist/react-datepicker.min.css': 'src/stylesheets/datepicker.scss'
},
options: {
sourcemap: 'none',
style: 'compressed'
}
}
},
watch: {
jshint: {
files: ['src/**/*.js', 'src/**/*.jsx'],
tasks: ['jshint']
},
jest: {
files: ['src/**/*.jsx', 'src/**/*.js', 'test/**/*.js'],
tasks: ['jest']
},
css: {
files: '**/*.scss',
tasks: ['sass']
},
webpack: {
files: ['src/**/*.js', 'src/**/*.jsx'],
tasks: ['webpack']
}
},
scsslint: {
files: 'src/stylesheets/*.scss',
options: {
config: '.scss-lint.yml',
colorizeOutput: true
}
},
jshint: {
all: ['src/**/*.jsx', 'src/**/*.js'],
options: {
eqnull: true
}
},
webpack: {
example: {
entry: './example/boot',
output: {
filename: 'example.js',
library: 'ExampleApp',
path: './example/'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{test: /\.js/, loaders: ['babel-loader'], exclude: /node_modules/}
]
},
node: {Buffer: false},
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
]
},
unmin: mergeWebpackConfig({
output: {
filename: 'react-datepicker.js'
}
}),
min: mergeWebpackConfig({
output: {
filename: 'react-datepicker.min.js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
]
})
}
});
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-scss-lint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-jsxhint');
grunt.loadNpmTasks('grunt-webpack');
grunt.registerTask('default', ['watch', 'scsslint']);
grunt.registerTask('travis', ['jshint', 'jest', 'scsslint']);
grunt.registerTask('build', ['jshint', 'scsslint', 'webpack', 'sass']);
grunt.registerTask('jest', require('./grunt/tasks/jest'));
};
| lCharlie123l/react-datepicker | gruntfile.js | JavaScript | mit | 3,123 |
var ArrayProto = Array.prototype;
var ObjProto = Object.prototype;
var escapeMap = {
'&': '&',
'"': '"',
"'": ''',
"<": '<',
">": '>'
};
var escapeRegex = /[&"'<>]/g;
var lookupEscape = function(ch) {
return escapeMap[ch];
};
var exports = module.exports = {};
exports.withPrettyErrors = function(path, withInternals, func) {
try {
return func();
} catch (e) {
if (!e.Update) {
// not one of ours, cast it
e = new exports.TemplateError(e);
}
e.Update(path);
// Unless they marked the dev flag, show them a trace from here
if (!withInternals) {
var old = e;
e = new Error(old.message);
e.name = old.name;
}
throw e;
}
};
exports.TemplateError = function(message, lineno, colno) {
var err = this;
if (message instanceof Error) { // for casting regular js errors
err = message;
message = message.name + ": " + message.message;
} else {
if(Error.captureStackTrace) {
Error.captureStackTrace(err);
}
}
err.name = 'Template render error';
err.message = message;
err.lineno = lineno;
err.colno = colno;
err.firstUpdate = true;
err.Update = function(path) {
var message = "(" + (path || "unknown path") + ")";
// only show lineno + colno next to path of template
// where error occurred
if (this.firstUpdate) {
if(this.lineno && this.colno) {
message += ' [Line ' + this.lineno + ', Column ' + this.colno + ']';
}
else if(this.lineno) {
message += ' [Line ' + this.lineno + ']';
}
}
message += '\n ';
if (this.firstUpdate) {
message += ' ';
}
this.message = message + (this.message || '');
this.firstUpdate = false;
return this;
};
return err;
};
exports.TemplateError.prototype = Error.prototype;
exports.escape = function(val) {
return val.replace(escapeRegex, lookupEscape);
};
exports.isFunction = function(obj) {
return ObjProto.toString.call(obj) == '[object Function]';
};
exports.isArray = Array.isArray || function(obj) {
return ObjProto.toString.call(obj) == '[object Array]';
};
exports.isString = function(obj) {
return ObjProto.toString.call(obj) == '[object String]';
};
exports.isObject = function(obj) {
return ObjProto.toString.call(obj) == '[object Object]';
};
exports.groupBy = function(obj, val) {
var result = {};
var iterator = exports.isFunction(val) ? val : function(obj) { return obj[val]; };
for(var i=0; i<obj.length; i++) {
var value = obj[i];
var key = iterator(value, i);
(result[key] || (result[key] = [])).push(value);
}
return result;
};
exports.toArray = function(obj) {
return Array.prototype.slice.call(obj);
};
exports.without = function(array) {
var result = [];
if (!array) {
return result;
}
var index = -1,
length = array.length,
contains = exports.toArray(arguments).slice(1);
while(++index < length) {
if(exports.indexOf(contains, array[index]) === -1) {
result.push(array[index]);
}
}
return result;
};
exports.extend = function(obj, obj2) {
for(var k in obj2) {
obj[k] = obj2[k];
}
return obj;
};
exports.repeat = function(char_, n) {
var str = '';
for(var i=0; i<n; i++) {
str += char_;
}
return str;
};
exports.each = function(obj, func, context) {
if(obj == null) {
return;
}
if(ArrayProto.each && obj.each == ArrayProto.each) {
obj.forEach(func, context);
}
else if(obj.length === +obj.length) {
for(var i=0, l=obj.length; i<l; i++) {
func.call(context, obj[i], i, obj);
}
}
};
exports.map = function(obj, func) {
var results = [];
if(obj == null) {
return results;
}
if(ArrayProto.map && obj.map === ArrayProto.map) {
return obj.map(func);
}
for(var i=0; i<obj.length; i++) {
results[results.length] = func(obj[i], i);
}
if(obj.length === +obj.length) {
results.length = obj.length;
}
return results;
};
exports.asyncIter = function(arr, iter, cb) {
var i = -1;
function next() {
i++;
if(i < arr.length) {
iter(arr[i], i, next, cb);
}
else {
cb();
}
}
next();
};
exports.asyncFor = function(obj, iter, cb) {
var keys = exports.keys(obj);
var len = keys.length;
var i = -1;
function next() {
i++;
var k = keys[i];
if(i < len) {
iter(k, obj[k], i, len, next);
}
else {
cb();
}
}
next();
};
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill
exports.indexOf = Array.prototype.indexOf ?
function (arr, searchElement, fromIndex) {
return Array.prototype.indexOf.call(arr, searchElement, fromIndex);
} :
function (arr, searchElement, fromIndex) {
var length = this.length >>> 0; // Hack to convert object.length to a UInt32
fromIndex = +fromIndex || 0;
if(Math.abs(fromIndex) === Infinity) {
fromIndex = 0;
}
if(fromIndex < 0) {
fromIndex += length;
if (fromIndex < 0) {
fromIndex = 0;
}
}
for(;fromIndex < length; fromIndex++) {
if (arr[fromIndex] === searchElement) {
return fromIndex;
}
}
return -1;
};
if(!Array.prototype.map) {
Array.prototype.map = function() {
throw new Error("map is unimplemented for this js engine");
};
}
exports.keys = function(obj) {
if(Object.prototype.keys) {
return obj.keys();
}
else {
var keys = [];
for(var k in obj) {
if(obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
}
}
| angyukai/boulderactive2016-landing-page | node_modules/nunjucks/src/lib.js | JavaScript | mit | 6,222 |
$.widget("metro.slider", {
version: "3.0.0",
options: {
position: 0,
accuracy: 0,
color: 'default',
completeColor: 'default',
markerColor: 'default',
colors: false,
showHint: false,
permanentHint: false,
hintPosition: 'top',
vertical: false,
min: 0,
max: 100,
animate: true,
minValue: 0,
maxValue: 100,
currValue: 0,
returnType: 'value',
target: false,
onChange: function(value, slider){},
_slider : {
vertical: false,
offset: 0,
length: 0,
marker: 0,
ppp: 0,
start: 0,
stop: 0
}
},
_create: function(){
var that = this,
element = this.element;
var o = this.options,
s = o._slider;
$.each(element.data(), function(key, value){
if (key in o) {
try {
o[key] = $.parseJSON(value);
} catch (e) {
o[key] = value;
}
}
});
o.accuracy = o.accuracy < 0 ? 0 : o.accuracy;
o.min = o.min < 0 ? 0 : o.min;
o.min = o.min > o.max ? o.max : o.min;
o.max = o.max > 100 ? 100 : o.max;
o.max = o.max < o.min ? o.min : o.max;
o.position = this._correctValue(element.data('position') > o.min ? (element.data('position') > o.max ? o.max : element.data('position')) : o.min);
o.colors = o.colors ? o.colors.split(",") : false;
s.vertical = o.vertical;
if (o.vertical && !element.hasClass('vertical')) {
element.addClass('vertical');
}
if (o.permanentHint && !element.hasClass('permanent-hint')) {
element.addClass('permanent-hint');
}
if (!o.vertical && o.hintPosition === 'bottom') {
element.addClass('hint-bottom');
}
if (o.vertical && o.hintPosition === 'left') {
element.addClass('hint-left');
}
this._createSlider();
this._initPoints();
this._placeMarker(o.position);
var event_down = isTouchDevice() ? 'touchstart' : 'mousedown';
element.children('.marker').on(event_down, function (e) {
e.preventDefault();
that._startMoveMarker(e);
});
element.on(event_down, function (e) {
e.preventDefault();
that._startMoveMarker(e);
});
element.data('slider', this);
},
_startMoveMarker: function(e){
var element = this.element, o = this.options, that = this, hint = element.children('.slider-hint');
var returnedValue;
var event_move = isTouchDevice() ? 'touchmove' : 'mousemove';
var event_up = isTouchDevice() ? 'touchend' : 'mouseup mouseleave';
$(element).on(event_move, function (event) {
that._movingMarker(event);
if (!element.hasClass('permanent-hint')) {
hint.css('display', 'block');
}
});
$(element).on(event_up, function () {
$(element).off('mousemove');
$(element).off('mouseup');
element.data('value', o.position);
element.trigger('changed', o.position);
returnedValue = o.returnType === 'value' ? that._valueToRealValue(o.position) : o.position;
if (!element.hasClass('permanent-hint')) {
hint.css('display', 'none');
}
});
this._initPoints();
this._movingMarker(e);
},
_movingMarker: function (ev) {
var element = this.element, o = this.options;
var cursorPos,
percents,
valuePix,
vertical = o._slider.vertical,
sliderOffset = o._slider.offset,
sliderStart = o._slider.start,
sliderEnd = o._slider.stop,
sliderLength = o._slider.length,
markerSize = o._slider.marker;
var event = !isTouchDevice() ? ev.originalEvent : ev.originalEvent.touches[0];
//console.log(event);
if (vertical) {
cursorPos = event.pageY - sliderOffset;
} else {
cursorPos = event.pageX - sliderOffset;
}
if (cursorPos < sliderStart) {
cursorPos = sliderStart;
} else if (cursorPos > sliderEnd) {
cursorPos = sliderEnd;
}
if (vertical) {
valuePix = sliderLength - cursorPos - markerSize / 2;
} else {
valuePix = cursorPos - markerSize / 2;
}
percents = this._pixToPerc(valuePix);
this._placeMarker(percents);
o.currValue = this._valueToRealValue(percents);
o.position = percents;
var returnedValue = o.returnType === 'value' ? this._valueToRealValue(o.position) : o.position;
if (o.target) {
$(o.target).val(returnedValue);
}
if (typeof o.onChange === 'function') {
o.onChange(returnedValue, element);
} else {
if (typeof window[o.onChange] === 'function') {
window[o.onChange](returnedValue, element);
} else {
var result = eval("(function(){"+o.onChange+"})");
result.call(returnedValue, element);
}
}
},
_placeMarker: function (value) {
var size, size2, o = this.options, colorParts, colorIndex = 0, colorDelta, element = this.element,
marker = this.element.children('.marker'),
complete = this.element.children('.complete'),
hint = this.element.children('.slider-hint'), hintValue,
oldPos = this._percToPix(o.position);
colorParts = o.colors.length;
colorDelta = o._slider.length / colorParts;
if (o._slider.vertical) {
var oldSize = this._percToPix(o.position) + o._slider.marker,
oldSize2 = o._slider.length - oldSize;
size = this._percToPix(value) + o._slider.marker;
size2 = o._slider.length - size;
this._animate(marker.css('top', oldSize2),{top: size2});
this._animate(complete.css('height', oldSize),{height: size});
if (colorParts) {
colorIndex = Math.round(size / colorDelta)-1;
complete.css('background-color', o.colors[colorIndex<0?0:colorIndex]);
}
if (o.showHint) {
hintValue = this._valueToRealValue(value);
hint.html(hintValue).css('top', size2 - hint.height()/2 + (element.hasClass('large') ? 8 : 0));
}
} else {
size = this._percToPix(value);
this._animate(marker.css('left', oldPos),{left: size});
this._animate(complete.css('width', oldPos),{width: size});
if (colorParts) {
colorIndex = Math.round(size / colorDelta)-1;
complete.css('background-color', o.colors[colorIndex<0?0:colorIndex]);
}
if (o.showHint) {
hintValue = this._valueToRealValue(value);
hint.html(hintValue).css({left: size - hint.width() / 2 + (element.hasClass('large') ? 6 : 0)});
}
}
},
_valueToRealValue: function(value){
var o = this.options;
var real_value;
var percent_value = (o.maxValue - o.minValue) / 100;
real_value = value * percent_value + o.minValue;
return Math.round(real_value);
},
_animate: function (obj, val) {
var o = this.options;
if(o.animate) {
obj.stop(true).animate(val);
} else {
obj.css(val);
}
},
_pixToPerc: function (valuePix) {
var valuePerc;
valuePerc = valuePix * this.options._slider.ppp;
return Math.round(this._correctValue(valuePerc));
},
_percToPix: function (value) {
if (this.options._slider.ppp === 0) {
return 0;
}
return Math.round(value / this.options._slider.ppp);
},
_correctValue: function (value) {
var o = this.options;
var accuracy = o.accuracy;
var max = o.max;
var min = o.min;
if (accuracy === 0) {
return value;
}
if (value === max) {
return max;
}
if (value === min) {
return min;
}
value = Math.floor(value / accuracy) * accuracy + Math.round(value % accuracy / accuracy) * accuracy;
if (value > max) {
return max;
}
if (value < min) {
return min;
}
return value;
},
_initPoints: function(){
var o = this.options, s = o._slider, element = this.element;
if (s.vertical) {
s.offset = element.offset().top;
s.length = element.height();
s.marker = element.children('.marker').height();
} else {
s.offset = element.offset().left;
s.length = element.width();
s.marker = element.children('.marker').width();
}
s.ppp = o.max / (s.length - s.marker);
s.start = s.marker / 2;
s.stop = s.length - s.marker / 2;
},
_createSlider: function(){
var element = this.element,
o = this.options,
complete, marker, hint;
element.html('');
complete = $("<div/>").addClass("complete").appendTo(element);
marker = $("<a/>").addClass("marker").appendTo(element);
if (o.showHint) {
hint = $("<span/>").addClass("slider-hint").appendTo(element);
}
if (o.color !== 'default') {
if (o.color.isColor()) {
element.css('background-color', o.color);
} else {
element.addClass(o.color);
}
}
if (o.completeColor !== 'default') {
if (o.completeColor.isColor()) {
complete.css('background-color', o.completeColor);
} else {
complete.addClass(o.completeColor);
}
}
if (o.markerColor !== 'default') {
if (o.markerColor.isColor()) {
marker.css('background-color', o.markerColor);
} else {
marker.addClass(o.markerColor);
}
}
},
value: function (value) {
var element = this.element, o = this.options, returnedValue;
if (typeof value !== 'undefined') {
value = value > o.max ? o.max : value;
value = value < o.min ? o.min : value;
this._placeMarker(parseInt(value));
o.position = parseInt(value);
returnedValue = o.returnType === 'value' ? this._valueToRealValue(o.position) : o.position;
if (typeof o.onChange === 'function') {
o.onChange(returnedValue, element);
} else {
if (typeof window[o.onChange] === 'function') {
window[o.onChange](returnedValue, element);
} else {
var result = eval("(function(){"+o.onChange+"})");
result.call(returnedValue, element);
}
}
return this;
} else {
returnedValue = o.returnType === 'value' ? this._valueToRealValue(o.position) : o.position;
return returnedValue;
}
},
_destroy: function(){},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
});
| ckc/Metro-UI-CSS | js/widgets/slider.js | JavaScript | mit | 11,712 |
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ReactDOM from 'react-dom';
import Col from '../src/Col';
describe('Col', () => {
it('Should set Offset of zero', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Col xsOffset={0} smOffset={0} mdOffset={0} lgOffset={0} />
);
let instanceClassName = ReactDOM.findDOMNode(instance).className;
assert.ok(instanceClassName.match(/\bcol-xs-offset-0\b/));
assert.ok(instanceClassName.match(/\bcol-sm-offset-0\b/));
assert.ok(instanceClassName.match(/\bcol-md-offset-0\b/));
assert.ok(instanceClassName.match(/\bcol-lg-offset-0\b/));
});
it('Should set Pull of zero', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Col xsPull={0} smPull={0} mdPull={0} lgPull={0} />
);
let instanceClassName = ReactDOM.findDOMNode(instance).className;
assert.ok(instanceClassName.match(/\bcol-xs-pull-0\b/));
assert.ok(instanceClassName.match(/\bcol-sm-pull-0\b/));
assert.ok(instanceClassName.match(/\bcol-md-pull-0\b/));
assert.ok(instanceClassName.match(/\bcol-lg-pull-0\b/));
});
it('Should set Push of zero', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Col xsPush={0} smPush={0} mdPush={0} lgPush={0} />
);
let instanceClassName = ReactDOM.findDOMNode(instance).className;
assert.ok(instanceClassName.match(/\bcol-xs-push-0\b/));
assert.ok(instanceClassName.match(/\bcol-sm-push-0\b/));
assert.ok(instanceClassName.match(/\bcol-md-push-0\b/));
assert.ok(instanceClassName.match(/\bcol-lg-push-0\b/));
});
it('Should set Hidden to true', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Col xsHidden smHidden mdHidden lgHidden />
);
let instanceClassName = ReactDOM.findDOMNode(instance).className;
assert.ok(instanceClassName.match(/\bhidden-xs\b/));
assert.ok(instanceClassName.match(/\bhidden-sm\b/));
assert.ok(instanceClassName.match(/\bhidden-md\b/));
assert.ok(instanceClassName.match(/\bhidden-lg\b/));
});
});
| mmarcant/react-bootstrap | test/ColSpec.js | JavaScript | mit | 2,095 |
import _extends from"@babel/runtime/helpers/extends";import _objectWithoutProperties from"@babel/runtime/helpers/objectWithoutProperties";var _excluded=["value","getRootRef"];import{createScopedElement}from"../../lib/jsxRuntime";import{getClassName}from"../../helpers/getClassName";import{usePlatform}from"../../hooks/usePlatform";var Progress=function(e){var r=e.value,t=e.getRootRef,o=_objectWithoutProperties(e,_excluded),e=usePlatform();return createScopedElement("div",_extends({"aria-valuenow":r},o,{role:"progressbar","aria-valuemin":0,"aria-valuemax":100,ref:t,vkuiClass:getClassName("Progress",e)}),createScopedElement("div",{vkuiClass:"Progress__bg","aria-hidden":"true"}),createScopedElement("div",{vkuiClass:"Progress__in",style:{width:"".concat(r,"%")},"aria-hidden":"true"}))};Progress.defaultProps={value:0};export default Progress; | cdnjs/cdnjs | ajax/libs/vkui/4.22.1/components/Progress/Progress.min.js | JavaScript | mit | 847 |
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
/**
* Module: @exports TYPO3/CMS/Rtehtmlarea/HTMLArea/UserAgent/HtmlArea
* Initialization script of TYPO3 htmlArea RTE
*/
define(['TYPO3/CMS/Rtehtmlarea/HTMLArea/UserAgent/UserAgent',
'TYPO3/CMS/Rtehtmlarea/HTMLArea/Util/Util',
'TYPO3/CMS/Rtehtmlarea/HTMLArea/Configuration/Config',
'TYPO3/CMS/Rtehtmlarea/HTMLArea/Editor/Editor'],
function (UserAgent, Util, Config, Editor) {
/**
*
* @type {{RE_htmlTag: RegExp, RE_tagName: RegExp, RE_head: RegExp, RE_body: RegExp, reservedClassNames: RegExp, RE_email: RegExp, RE_url: RegExp, RE_numberOrPunctuation: RegExp, init: Function, initEditor: Function, localize: Function, appendToLog: Function}}
* @exports TYPO3/CMS/Rtehtmlarea/HTMLArea/UserAgent/HtmlArea
*/
var HtmlArea = {
/***************************************************
* COMPILED REGULAR EXPRESSIONS *
***************************************************/
RE_htmlTag : /<.[^<>]*?>/g,
RE_tagName : /(<\/|<)\s*([^ \t\n>]+)/ig,
RE_head : /<head>((.|\n)*?)<\/head>/i,
RE_body : /<body>((.|\n)*?)<\/body>/i,
reservedClassNames : /htmlarea/,
RE_email : /([0-9a-z]+([a-z0-9_-]*[0-9a-z])*){1}(\.[0-9a-z]+([a-z0-9_-]*[0-9a-z])*)*@([0-9a-z]+([a-z0-9_-]*[0-9a-z])*\.)+[a-z]{2,9}/i,
RE_url : /(([^:/?#]+):\/\/)?(([a-z0-9_]+:[a-z0-9_]+@)?[a-z0-9_-]{2,}(\.[a-z0-9_-]{2,})+\.[a-z]{2,5}(:[0-9]+)?(\/\S+)*\/?)/i,
RE_numberOrPunctuation : /[0-9.(),;:!¡?¿%#$'"_+=\\\/-]*/g,
/***************************************************
* INITIALIZATION *
***************************************************/
init: function () {
if (!HTMLArea.isReady) {
// Apply global configuration settings
Util.apply(HtmlArea, RTEarea[0]);
HTMLArea.isReady = true;
HtmlArea.appendToLog('', 'HTMLArea', 'init', 'Editor url set to: ' + HtmlArea.editorUrl, 'info');
HtmlArea.appendToLog('', 'HTMLArea', 'init', 'Editor content skin CSS set to: ' + HtmlArea.editedContentCSS, 'info');
Util.apply(HTMLArea, HtmlArea);
}
},
/**
* Create an editor when HTMLArea is loaded and when Ext is ready
*
* @param string editorId: the id of the editor
* @return boolean false if successful
*/
initEditor: function (editorId) {
if (document.getElementById('pleasewait' + editorId)) {
if (UserAgent.isSupported()) {
document.getElementById('pleasewait' + editorId).style.display = 'block';
document.getElementById('editorWrap' + editorId).style.visibility = 'hidden';
if (!HTMLArea.isReady) {
var self = this;
window.setTimeout(function () {
return self.initEditor(editorId);
}, 150);
} else {
// Create an editor for the textarea
var editor = new Editor(Util.apply(new Config(editorId), RTEarea[editorId]));
editor.generate();
return false;
}
} else {
document.getElementById('pleasewait' + editorId).style.display = 'none';
document.getElementById('editorWrap' + editorId).style.visibility = 'visible';
}
}
return true;
},
/***************************************************
* LOCALIZATION *
***************************************************/
localize: function (label, plural) {
var i = plural || 0;
var localized = HTMLArea.I18N.dialogs[label] || HTMLArea.I18N.tooltips[label] || HTMLArea.I18N.msg[label] || '';
if (typeof localized === 'object' && localized !== null && typeof localized[i] !== 'undefined') {
localized = localized[i]['target'];
}
return localized;
},
/***************************************************
* LOGGING *
***************************************************/
/**
* Write message to JavaScript console
*
* @param string editorId: the id of the editor issuing the message
* @param string objectName: the name of the object issuing the message
* @param string functionName: the name of the function issuing the message
* @param string text: the text of the message
* @param string type: the type of message: 'log', 'info', 'warn' or 'error'
* @return void
*/
appendToLog: function (editorId, objectName, functionName, text, type) {
var str = 'RTE[' + editorId + '][' + objectName + '::' + functionName + ']: ' + text;
if (typeof type === 'undefined') {
var type = 'info';
}
// IE may not have any console
if (typeof console === 'object' && console !== null && typeof console[type] !== 'undefined') {
console[type](str);
}
}
};
return Util.apply(HTMLArea, HtmlArea);
});
| liayn/TYPO3.CMS | typo3/sysext/rtehtmlarea/Resources/Public/JavaScript/HTMLArea/HTMLArea.js | JavaScript | gpl-2.0 | 5,129 |
export default {
content: {
width: '100%',
padding: 10,
marginRight: 20,
},
header: {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
},
};
| mcldev/geonode | geonode/monitoring/frontend/src/components/organisms/geonode-layers-analytics/styles.js | JavaScript | gpl-3.0 | 197 |
/*
* PLUGIN LoginMGR
*
* Latvian language file.
*
* Author:
*/
theUILang.accLogin = "Login";
theUILang.accPassword = "Password";
theUILang.accAccounts = "Accounts";
theUILang.accAuto = "Autologin";
theUILang.acAutoNone = "None";
theUILang.acAutoDay = "Every day";
theUILang.acAutoWeek = "Every week";
theUILang.acAutoMonth = "Every month";
thePlugins.get("loginmgr").langLoaded(); | Rapiddot/ruTorrent | plugins/loginmgr/lang/lv.js | JavaScript | gpl-3.0 | 408 |
/**
* Created by panos on 4/5/16.
*/
import angular from 'angular/index'
let _app = new WeakMap()
export default class Register {
constructor (appName, deps) {
deps = deps || []
let module
try {
module = angular.module(appName)
} catch (error) {
module = angular.module(appName, deps)
}
_app.set(this, module)
}
config (constructorFn) {
constructorFn = this._normalizeConstructor(constructorFn)
let factoryArray = this._createFactoryArray(constructorFn)
_app.get(this).config(factoryArray)
return this
}
constant (name, obj) {
_app.get(this).constant(name, obj)
return this
}
controller (name, constructorFn) {
_app.get(this).controller(name, constructorFn)
return this
}
directive (name, constructorFn) {
constructorFn = this._normalizeConstructor(constructorFn)
if (!constructorFn.prototype.compile) {
// create an empty compile function if none was defined
constructorFn.prototype.compile = () => {}
}
let originalCompileFn = this._cloneFunction(constructorFn.prototype.compile)
// Decorate the compile method to automatically return the link method (if it exists)
// and bind it to the context of the constructor (so `this` works correctly).
// This gets around the problem of a non-lexical "this" which occurs when the directive class itself
// returns `this.link` from within the compile function.
this._override(constructorFn.prototype, 'compile', () => {
return function() {
originalCompileFn.apply(this, arguments)
if (constructorFn.prototype.link) {
return constructorFn.prototype.link.bind(this)
}
}
})
let factoryArray = this._createFactoryArray(constructorFn)
_app.get(this).directive(name, factoryArray)
return this
}
factory (name, constructorFn) {
constructorFn = this._normalizeConstructor(constructorFn)
let factoryArray = this._createFactoryArray(constructorFn)
_app.get(this).factory(name, factoryArray)
return this
}
filter (name, constructorFn) {
constructorFn = this._normalizeConstructor(constructorFn)
let factoryArray = this._createFactoryArray(constructorFn)
_app.get(this).filter(name, factoryArray)
return this
}
provider (name, constructorFn) {
_app.get(this).provider(name, constructorFn)
return this
}
run (constructorFn) {
constructorFn = this._normalizeConstructor(constructorFn)
let factoryArray = this._createFactoryArray(constructorFn)
_app.get(this).run(factoryArray)
return this
}
service (name, constructorFn) {
_app.get(this).service(name, constructorFn)
return this
}
value (name, object) {
_app.get(this).value(name, object)
return this
}
/**
* If the constructorFn is an array of type ['dep1', 'dep2', ..., constructor() {}]
* we need to pull out the array of dependencies and add it as an $inject property of the
* actual constructor function.
* @param input
* @returns {*}
* @private
*/
_normalizeConstructor (input) {
let constructorFn
if (input.constructor == Array) {
let injected = input.slice(0, input.length - 1)
constructorFn = input[input.length - 1]
constructorFn.$inject = injected
} else {
constructorFn = input
}
return constructorFn
}
/**
* Convert a constructor function into a factory function which returns a new instance of that
* constructor, with the correct dependencies automatically injected as arguments.
*
* In order to inject the dependencies, they must be attached to the constructor function with the
* `$inject` property annotation.
*
* @param constructorFn
* @returns {Array.<T>}
* @private
*/
_createFactoryArray(constructorFn) {
// get the array of dependencies that are needed by this component (as contained in the `$inject` array)
let args = constructorFn.$inject || []
let factoryArray = args.slice()
// The factoryArray uses Angular's array notation whereby each element of the array is the name of a
// dependency, and the final item is the factory function itself.
factoryArray.push((...args) => {
// return new constructorFn(...args)
let instance = new constructorFn(...args)
for (let key in instance) {
instance[key] = instance[key]
}
return instance
})
return factoryArray
}
/**
* Clone a function
* @param original
* @returns {Function}
* @private
*/
_cloneFunction (original) {
return function() {
return original.apply(this, arguments);
}
}
/**
* Override an object's method with a new one specified by `callback`
* @param object
* @param method
* @param callback
* @private
*/
_override (object, method, callback) {
object[method] = callback(object[method])
}
} | ClaroBot/Distribution | plugin/website/Resources/modules/utils/register.js | JavaScript | gpl-3.0 | 4,922 |
/*!
* This is a `i18n` language object.
*
* Spanish
*
* @author
* Jalios (Twitter: @Jalios)
* Sascha Greuel (Twitter: @SoftCreatR)
* Rafael Miranda (GitHub: @rafa8626)
*
* @see core/i18n.js
*/
(function (exports) {
if (exports.es === undefined) {
exports.es = {
'mejs.plural-form': 1,
// core/mediaelement.js
'mejs.download-file': 'Descargar archivo',
// renderers/flash.js
'mejs.install-flash': 'Esta usando un navegador que no tiene activado o instalado el reproductor de Flash. Por favor active el plugin del reproductor de Flash o descargue la versión más reciente en https://get.adobe.com/flashplayer/',
// features/fullscreen.js
'mejs.fullscreen': 'Pantalla completa',
// features/playpause.js
'mejs.play': 'Reproducción',
'mejs.pause': 'Pausa',
// features/progress.js
'mejs.time-slider': 'Control deslizante de tiempo',
'mejs.time-help-text': 'Use las flechas Izquierda/Derecha para avanzar un segundo y las flechas Arriba/Abajo para avanzar diez segundos.',
'mejs.live-broadcast': 'Transmisión en Vivo',
// features/volume.js
'mejs.volume-help-text': 'Use las flechas Arriba/Abajo para subir o bajar el volumen.',
'mejs.unmute': 'Reactivar silencio',
'mejs.mute': 'Silencio',
'mejs.volume-slider': 'Control deslizante de volumen',
// core/player.js
'mejs.video-player': 'Reproductor de video',
'mejs.audio-player': 'Reproductor de audio',
// features/tracks.js
'mejs.captions-subtitles': 'Leyendas/Subtítulos',
'mejs.captions-chapters': 'Capítulos',
'mejs.none': 'Ninguno',
'mejs.afrikaans': 'Afrikaans',
'mejs.albanian': 'Albano',
'mejs.arabic': 'Árabe',
'mejs.belarusian': 'Bielorruso',
'mejs.bulgarian': 'Búlgaro',
'mejs.catalan': 'Catalán',
'mejs.chinese': 'Chino',
'mejs.chinese-simplified': 'Chino (Simplificado)',
'mejs.chinese-traditional': 'Chino (Tradicional)',
'mejs.croatian': 'Croata',
'mejs.czech': 'Checo',
'mejs.danish': 'Danés',
'mejs.dutch': 'Holandés',
'mejs.english': 'Inglés',
'mejs.estonian': 'Estoniano',
'mejs.filipino': 'Filipino',
'mejs.finnish': 'Finlandés',
'mejs.french': 'Francés',
'mejs.galician': 'Gallego',
'mejs.german': 'Alemán',
'mejs.greek': 'Griego',
'mejs.haitian-creole': 'Haitiano Criollo',
'mejs.hebrew': 'Hebreo',
'mejs.hindi': 'Hindi',
'mejs.hungarian': 'Húngaro',
'mejs.icelandic': 'Islandés',
'mejs.indonesian': 'Indonesio',
'mejs.irish': 'Irlandés',
'mejs.italian': 'Italiano',
'mejs.japanese': 'Japonés',
'mejs.korean': 'Coreano',
'mejs.latvian': 'Letón',
'mejs.lithuanian': 'Lituano',
'mejs.macedonian': 'Macedonio',
'mejs.malay': 'Malayo',
'mejs.maltese': 'Maltés',
'mejs.norwegian': 'Noruego',
'mejs.persian': 'Persa',
'mejs.polish': 'Polaco',
'mejs.portuguese': 'Portugués',
'mejs.romanian': 'Rumano',
'mejs.russian': 'Ruso',
'mejs.serbian': 'Serbio',
'mejs.slovak': 'Eslovaco',
'mejs.slovenian': 'Eslovenio',
'mejs.spanish': 'Español',
'mejs.swahili': 'Swahili',
'mejs.swedish': 'Suizo',
'mejs.tagalog': 'Tagalog',
'mejs.thai': 'Tailandés',
'mejs.turkish': 'Turco',
'mejs.ukrainian': 'Ucraniano',
'mejs.vietnamese': 'Vietnamita',
'mejs.welsh': 'Galés',
'mejs.yiddish': 'Yiddish'
};
}
})(mejs.i18n); | ntja/smartschool | v2/public/js/plugins/mediaelement/src/js/languages/es.js | JavaScript | gpl-3.0 | 3,360 |
odoo.define('website_event.ticket_details', function (require) {
var publicWidget = require('web.public.widget');
publicWidget.registry.ticketDetailsWidget = publicWidget.Widget.extend({
selector: '.o_wevent_js_ticket_details',
events: {
'click .o_wevent_registration_btn': '_onTicketDetailsClick',
'change .custom-select': '_onTicketQuantityChange'
},
start: function (){
this.foldedByDefault = this.$el.data('foldedByDefault') === 1;
return this._super.apply(this, arguments);
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* @private
*/
_getTotalTicketCount: function (){
var ticketCount = 0;
this.$('.custom-select').each(function (){
ticketCount += parseInt($(this).val());
});
return ticketCount;
},
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* @private
* @param {*} ev
*/
_onTicketDetailsClick: function (ev){
ev.preventDefault();
if (this.foldedByDefault){
$(ev.currentTarget).toggleClass('btn-primary text-left pl-0');
$(ev.currentTarget).siblings().toggleClass('d-none');
this.$('.close').toggleClass('d-none');
}
},
/**
* @private
*/
_onTicketQuantityChange: function (){
this.$('button.btn-primary').attr('disabled', this._getTotalTicketCount() === 0);
}
});
return publicWidget.registry.ticketDetailsWidget;
});
| ddico/odoo | addons/website_event/static/src/js/website_event_ticket_details.js | JavaScript | agpl-3.0 | 1,926 |
/*
***** BEGIN LICENSE BLOCK *****
Copyright © 2009 Center for History and New Media
George Mason University, Fairfax, Virginia, USA
http://zotero.org
This file is part of Zotero.
Zotero is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Zotero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Zotero. If not, see <http://www.gnu.org/licenses/>.
***** END LICENSE BLOCK *****
*/
var noteEditor;
var notifierUnregisterID;
function onLoad() {
noteEditor = document.getElementById('zotero-note-editor');
noteEditor.mode = 'edit';
noteEditor.focus();
// Set font size from pref
Zotero.setFontSize(noteEditor);
if (window.arguments) {
var io = window.arguments[0];
}
var itemID = io.itemID;
var collectionID = io.collectionID;
var parentItemID = io.parentItemID;
if (itemID) {
var ref = Zotero.Items.get(itemID);
var clearUndo = noteEditor.item ? noteEditor.item.id != ref.id : false;
noteEditor.item = ref;
// If loading new or different note, disable undo while we repopulate the text field
// so Undo doesn't end up clearing the field. This also ensures that Undo doesn't
// undo content from another note into the current one.
if (clearUndo) {
noteEditor.clearUndo();
}
document.title = ref.getNoteTitle();
}
else {
if (parentItemID) {
var ref = Zotero.Items.get(parentItemID);
noteEditor.parent = ref;
}
else {
if (collectionID && collectionID != '' && collectionID != 'undefined') {
noteEditor.collection = Zotero.Collections.get(collectionID);
}
}
noteEditor.refresh();
}
notifierUnregisterID = Zotero.Notifier.registerObserver(NotifyCallback, 'item');
}
function onUnload()
{
if(noteEditor && noteEditor.value)
noteEditor.save();
Zotero.Notifier.unregisterObserver(notifierUnregisterID);
}
var NotifyCallback = {
notify: function(action, type, ids){
if (noteEditor.item && ids.indexOf(noteEditor.item.id) != -1) {
noteEditor.item = noteEditor.item;
// If the document title hasn't yet been set, reset undo so
// undoing to empty isn't possible
var noteTitle = noteEditor.note.getNoteTitle();
if (!document.title && noteTitle != '') {
noteEditor.clearUndo();
document.title = noteTitle;
}
// Update the window name (used for focusing) in case this is a new note
window.name = 'zotero-note-' + noteEditor.item.id;
}
}
}
addEventListener("load", function(e) { onLoad(e); }, false);
addEventListener("unload", function(e) { onUnload(e); }, false); | egh/zotero | chrome/content/zotero/note.js | JavaScript | agpl-3.0 | 3,063 |
//// [objectBindingPatternKeywordIdentifiers01.ts]
var { while } = { while: 1 }
//// [objectBindingPatternKeywordIdentifiers01.js]
var = { "while": 1 }["while"];
| jwbay/TypeScript | tests/baselines/reference/objectBindingPatternKeywordIdentifiers01.js | JavaScript | apache-2.0 | 170 |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xml_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/xml'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules;
var XmlBehaviour = require("./behaviour/xml").XmlBehaviour;
var XmlFoldMode = require("./folding/xml").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new XmlHighlightRules().getRules());
this.$behaviour = new XmlBehaviour();
this.foldingRules = new XmlFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.getNextLineIndent = function(state, line, tab) {
return this.$getIndent(line);
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/xml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var xmlUtil = require("./xml_util");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var XmlHighlightRules = function() {
this.$rules = {
start : [{
token : "text",
regex : "<\\!\\[CDATA\\[",
next : "cdata"
}, {
token : "xml-pe",
regex : "<\\?.*?\\?>"
}, {
token : "comment",
merge : true,
regex : "<\\!--",
next : "comment"
}, {
token : "xml-pe",
regex : "<\\!.*?>"
}, {
token : "meta.tag", // opening tag
regex : "<\\/?",
next : "tag"
}, {
token : "text",
regex : "\\s+"
}, {
token : "constant.character.entity",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}, {
token : "text",
regex : "[^<]+"
}],
cdata : [{
token : "text",
regex : "\\]\\]>",
next : "start"
}, {
token : "text",
regex : "\\s+"
}, {
token : "text",
regex : "(?:[^\\]]|\\](?!\\]>))+"
}],
comment : [{
token : "comment",
regex : ".*?-->",
next : "start"
}, {
token : "comment",
merge : true,
regex : ".+"
}]
};
xmlUtil.tag(this.$rules, "tag", "start");
};
oop.inherits(XmlHighlightRules, TextHighlightRules);
exports.XmlHighlightRules = XmlHighlightRules;
});
define('ace/mode/xml_util', ['require', 'exports', 'module' ], function(require, exports, module) {
function string(state) {
return [{
token : "string",
regex : '".*?"'
}, {
token : "string", // multi line string start
merge : true,
regex : '["].*',
next : state + "_qqstring"
}, {
token : "string",
regex : "'.*?'"
}, {
token : "string", // multi line string start
merge : true,
regex : "['].*",
next : state + "_qstring"
}];
}
function multiLineString(quote, state) {
return [{
token : "string",
merge : true,
regex : ".*?" + quote,
next : state
}, {
token : "string",
merge : true,
regex : '.+'
}];
}
exports.tag = function(states, name, nextState, tagMap) {
states[name] = [{
token : "text",
regex : "\\s+"
}, {
token : !tagMap ? "meta.tag.tag-name" : function(value) {
if (tagMap[value])
return "meta.tag.tag-name." + tagMap[value];
else
return "meta.tag.tag-name";
},
merge : true,
regex : "[-_a-zA-Z0-9:]+",
next : name + "_embed_attribute_list"
}, {
token: "empty",
regex: "",
next : name + "_embed_attribute_list"
}];
states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list");
states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list");
states[name + "_embed_attribute_list"] = [{
token : "meta.tag",
merge : true,
regex : "\/?>",
next : nextState
}, {
token : "keyword.operator",
regex : "="
}, {
token : "entity.other.attribute-name",
regex : "[-_a-zA-Z0-9:]+"
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : "text",
regex : "\\s+"
}].concat(string(name));
};
});
define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle', 'ace/token_iterator'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = require("./cstyle").CstyleBehaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
function hasType(token, type) {
var hasType = true;
var typeList = token.type.split('.');
var needleList = type.split('.');
needleList.forEach(function(needle){
if (typeList.indexOf(needle) == -1) {
hasType = false;
return false;
}
});
return hasType;
}
var XmlBehaviour = function () {
this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour
this.add("autoclosing", "insertion", function (state, action, editor, session, text) {
if (text == '>') {
var position = editor.getCursorPosition();
var iterator = new TokenIterator(session, position.row, position.column);
var token = iterator.getCurrentToken();
var atCursor = false;
if (!token || !hasType(token, 'meta.tag') && !(hasType(token, 'text') && token.value.match('/'))){
do {
token = iterator.stepBackward();
} while (token && (hasType(token, 'string') || hasType(token, 'keyword.operator') || hasType(token, 'entity.attribute-name') || hasType(token, 'text')));
} else {
atCursor = true;
}
if (!token || !hasType(token, 'meta.tag-name') || iterator.stepBackward().value.match('/')) {
return
}
var tag = token.value;
if (atCursor){
var tag = tag.substring(0, position.column - token.start);
}
return {
text: '>' + '</' + tag + '>',
selection: [1, 1]
}
}
});
this.add('autoindent', 'insertion', function (state, action, editor, session, text) {
if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChars = line.substring(cursor.column, cursor.column + 2);
if (rightChars == '</') {
var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString();
var next_indent = this.$getIndent(session.doc.getLine(cursor.row));
return {
text: '\n' + indent + '\n' + next_indent,
selection: [1, indent.length, 1, indent.length]
}
}
}
});
}
oop.inherits(XmlBehaviour, Behaviour);
exports.XmlBehaviour = XmlBehaviour;
});
define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/token_iterator', 'ace/lib/lang'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");
var SAFE_INSERT_IN_TOKENS =
["text", "paren.rparen", "punctuation.operator"];
var SAFE_INSERT_BEFORE_TOKENS =
["text", "paren.rparen", "punctuation.operator", "comment"];
var autoInsertedBrackets = 0;
var autoInsertedRow = -1;
var autoInsertedLineEnd = "";
var maybeInsertedBrackets = 0;
var maybeInsertedRow = -1;
var maybeInsertedLineStart = "";
var maybeInsertedLineEnd = "";
var CstyleBehaviour = function () {
CstyleBehaviour.isSaneInsertion = function(editor, session) {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
return false;
}
iterator.stepForward();
return iterator.getCurrentTokenRow() !== cursor.row ||
this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
};
CstyleBehaviour.$matchTokenType = function(token, types) {
return types.indexOf(token.type || token) > -1;
};
CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isAutoInsertedClosing(cursor, line, autoInsertedLineEnd[0]))
autoInsertedBrackets = 0;
autoInsertedRow = cursor.row;
autoInsertedLineEnd = bracket + line.substr(cursor.column);
autoInsertedBrackets++;
};
CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isMaybeInsertedClosing(cursor, line))
maybeInsertedBrackets = 0;
maybeInsertedRow = cursor.row;
maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
maybeInsertedLineEnd = line.substr(cursor.column);
maybeInsertedBrackets++;
};
CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
return autoInsertedBrackets > 0 &&
cursor.row === autoInsertedRow &&
bracket === autoInsertedLineEnd[0] &&
line.substr(cursor.column) === autoInsertedLineEnd;
};
CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
return maybeInsertedBrackets > 0 &&
cursor.row === maybeInsertedRow &&
line.substr(cursor.column) === maybeInsertedLineEnd &&
line.substr(0, cursor.column) == maybeInsertedLineStart;
};
CstyleBehaviour.popAutoInsertedClosing = function() {
autoInsertedLineEnd = autoInsertedLineEnd.substr(1);
autoInsertedBrackets--;
};
CstyleBehaviour.clearMaybeInsertedClosing = function() {
maybeInsertedBrackets = 0;
maybeInsertedRow = -1;
};
this.add("braces", "insertion", function (state, action, editor, session, text) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (text == '{') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
return {
text: '{' + selected + '}',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
if (/[\]\}\)]/.test(line[cursor.column])) {
CstyleBehaviour.recordAutoInsert(editor, session, "}");
return {
text: '{}',
selection: [1, 1]
};
} else {
CstyleBehaviour.recordMaybeInsert(editor, session, "{");
return {
text: '{',
selection: [1, 1]
};
}
}
} else if (text == '}') {
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n" || text == "\r\n") {
var closing = "";
if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
closing = lang.stringRepeat("}", maybeInsertedBrackets);
CstyleBehaviour.clearMaybeInsertedClosing();
}
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}' || closing !== "") {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column}, '}');
if (!openBracePos)
return null;
var indent = this.getNextLineIndent(state, line.substring(0, cursor.column), session.getTabString());
var next_indent = this.$getIndent(line);
return {
text: '\n' + indent + '\n' + next_indent + closing,
selection: [1, indent.length, 1, indent.length]
};
}
}
});
this.add("braces", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
} else {
maybeInsertedBrackets--;
}
}
});
this.add("parens", "insertion", function (state, action, editor, session, text) {
if (text == '(') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '(' + selected + ')',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, ")");
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("brackets", "insertion", function (state, action, editor, session, text) {
if (text == '[') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '[' + selected + ']',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, "]");
return {
text: '[]',
selection: [1, 1]
};
}
} else if (text == ']') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ']') {
var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("brackets", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '[') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ']') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"' || text == "'") {
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
return {
text: quote + selected + quote,
selection: false
};
} else {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
if (leftChar == '\\') {
return null;
}
var tokens = session.getTokens(selection.start.row);
var col = 0, token;
var quotepos = -1; // Track whether we're inside an open quote.
for (var x = 0; x < tokens.length; x++) {
token = tokens[x];
if (token.type == "string") {
quotepos = -1;
} else if (quotepos < 0) {
quotepos = token.value.indexOf(quote);
}
if ((token.value.length + col) > selection.start.column) {
break;
}
col += tokens[x].value.length;
}
if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
if (!CstyleBehaviour.isSaneInsertion(editor, session))
return;
return {
text: quote + quote,
selection: [1,1]
};
} else if (token && token.type === "string") {
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == quote) {
return {
text: '',
selection: [1, 1]
};
}
}
}
}
});
this.add("string_dquotes", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == '"') {
range.end.column++;
return range;
}
}
});
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) {
var oop = require("../../lib/oop");
var lang = require("../../lib/lang");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var TokenIterator = require("../../token_iterator").TokenIterator;
var FoldMode = exports.FoldMode = function(voidElements) {
BaseFoldMode.call(this);
this.voidElements = voidElements || {};
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.getFoldWidget = function(session, foldStyle, row) {
var tag = this._getFirstTagInLine(session, row);
if (tag.closing)
return foldStyle == "markbeginend" ? "end" : "";
if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()])
return "";
if (tag.selfClosing)
return "";
if (tag.value.indexOf("/" + tag.tagName) !== -1)
return "";
return "start";
};
this._getFirstTagInLine = function(session, row) {
var tokens = session.getTokens(row);
var value = "";
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.type.indexOf("meta.tag") === 0)
value += token.value;
else
value += lang.stringRepeat(" ", token.value.length);
}
return this._parseTag(value);
};
this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/;
this._parseTag = function(tag) {
var match = this.tagRe.exec(tag);
var column = this.tagRe.lastIndex || 0;
this.tagRe.lastIndex = 0;
return {
value: tag,
match: match ? match[2] : "",
closing: match ? !!match[3] : false,
selfClosing: match ? !!match[5] || match[2] == "/>" : false,
tagName: match ? match[4] : "",
column: match[1] ? column + match[1].length : column
};
};
this._readTagForward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token)
return null;
var value = "";
var start;
do {
if (token.type.indexOf("meta.tag") === 0) {
if (!start) {
var start = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn()
};
}
value += token.value;
if (value.indexOf(">") !== -1) {
var tag = this._parseTag(value);
tag.start = start;
tag.end = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn() + token.value.length
};
iterator.stepForward();
return tag;
}
}
} while(token = iterator.stepForward());
return null;
};
this._readTagBackward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token)
return null;
var value = "";
var end;
do {
if (token.type.indexOf("meta.tag") === 0) {
if (!end) {
end = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn() + token.value.length
};
}
value = token.value + value;
if (value.indexOf("<") !== -1) {
var tag = this._parseTag(value);
tag.end = end;
tag.start = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn()
};
iterator.stepBackward();
return tag;
}
}
} while(token = iterator.stepBackward());
return null;
};
this._pop = function(stack, tag) {
while (stack.length) {
var top = stack[stack.length-1];
if (!tag || top.tagName == tag.tagName) {
return stack.pop();
}
else if (this.voidElements[tag.tagName]) {
return;
}
else if (this.voidElements[top.tagName]) {
stack.pop();
continue;
} else {
return null;
}
}
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
var firstTag = this._getFirstTagInLine(session, row);
if (!firstTag.match)
return null;
var isBackward = firstTag.closing || firstTag.selfClosing;
var stack = [];
var tag;
if (!isBackward) {
var iterator = new TokenIterator(session, row, firstTag.column);
var start = {
row: row,
column: firstTag.column + firstTag.tagName.length + 2
};
while (tag = this._readTagForward(iterator)) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else
continue;
}
if (tag.closing) {
this._pop(stack, tag);
if (stack.length == 0)
return Range.fromPoints(start, tag.start);
}
else {
stack.push(tag)
}
}
}
else {
var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length);
var end = {
row: row,
column: firstTag.column
};
while (tag = this._readTagBackward(iterator)) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else
continue;
}
if (!tag.closing) {
this._pop(stack, tag);
if (stack.length == 0) {
tag.start.column += tag.tagName.length + 2;
return Range.fromPoints(tag.start, end);
}
}
else {
stack.push(tag)
}
}
}
};
}).call(FoldMode.prototype);
}); | McLeodMoores/starling | projects/web/web-engine/prototype/scripts/lib/ace/mode-xml.js | JavaScript | apache-2.0 | 29,974 |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'preview', 'sv', {
preview: 'Förhandsgranska'
} );
| ldilov/uidb | plugins/ckeditor/plugins/preview/lang/sv.js | JavaScript | apache-2.0 | 225 |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'div', 'de-ch', {
IdInputLabel: 'Kennung',
advisoryTitleInputLabel: 'Tooltip',
cssClassInputLabel: 'Formatvorlagenklasse',
edit: 'Div bearbeiten',
inlineStyleInputLabel: 'Inline Stil',
langDirLTRLabel: 'Links nach Rechs (LTR)',
langDirLabel: 'Sprachrichtung',
langDirRTLLabel: 'Rechs nach Links (RTL)',
languageCodeInputLabel: 'Sprachcode',
remove: 'Div entfernen',
styleSelectLabel: 'Stil',
title: 'Div Container erzeugen',
toolbar: 'Div Container erzeugen'
} );
| ldilov/uidb | plugins/ckeditor/plugins/div/lang/de-ch.js | JavaScript | apache-2.0 | 649 |
/*global define, $, console, window, history, tizen*/
/**
* Init page module
*/
define({
name: 'views/audioPage',
def: function viewsAudioPage() {
'use strict';
var appControl = null,
appControlReplyCallback = null;
function onLaunchSuccess() {
console.log('launchAppControl', 'onLaunchSuccess');
}
function onLaunchError() {
console.error('launchAppControl', 'onLaunchError');
}
function launch() {
if (typeof tizen !== 'undefined') {
return;
}
tizen.application.launchAppControl(
appControl,
"com.samsung.w-voicerecorder",
onLaunchSuccess,
onLaunchError,
appControlReplyCallback
);
}
function init() {
if (typeof tizen !== 'undefined' && typeof tizen.ApplicationControl === 'function') {
appControl = new tizen.ApplicationControl(
"http://tizen.org/appcontrol/operation/create_content",
null,
"audio/amr",
null
);
} else {
console.warn('tizen.ApplicationControl not available');
}
appControlReplyCallback = {
// callee sent a reply
onsuccess: function onsuccess(data) {
var i = 0,
key = "http://tizen.org/appcontrol/data/selected";
for (i; i < data.length; i += 1) {
if (data[i].key == key) {
console.log('selected image is ' + data[i].value[0]);
}
}
},
// callee returned failure
onfailure: function onfailure() {
console.error('The launch application control failed');
}
};
}
return {
init: init,
launch: launch
};
}
});
| cwz920716/jalangi2 | tests/evernote/js/views/audioPage.js | JavaScript | apache-2.0 | 2,117 |
/**
* @license
* Copyright 2015 Google Inc. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Implements an OpenPGP key generator using ECC keys.
*/
goog.provide('e2e.openpgp.KeyGenerator');
goog.require('e2e');
goog.require('e2e.Hkdf');
goog.require('e2e.algorithm.KeyLocations');
goog.require('e2e.asymmetric.keygenerator');
goog.require('e2e.async.Result');
goog.require('e2e.cipher.Algorithm');
goog.require('e2e.error.InvalidArgumentsError');
goog.require('e2e.hash.Sha256');
goog.require('e2e.openpgp');
goog.require('e2e.openpgp.DummyS2k');
goog.require('e2e.openpgp.EncryptedCipher');
goog.require('e2e.openpgp.Mpi');
goog.require('e2e.openpgp.block.TransferablePublicKey');
goog.require('e2e.openpgp.block.TransferableSecretKey');
goog.require('e2e.openpgp.error.UnsupportedError');
goog.require('e2e.openpgp.packet.PublicKey');
goog.require('e2e.openpgp.packet.PublicSubkey');
goog.require('e2e.openpgp.packet.SecretKey');
goog.require('e2e.openpgp.packet.SecretSubkey');
goog.require('e2e.openpgp.packet.Signature');
goog.require('e2e.openpgp.packet.SignatureSub');
goog.require('e2e.openpgp.packet.UserId');
goog.require('e2e.random');
goog.require('e2e.signer.Algorithm');
goog.require('goog.array');
/**
* Implements an OpenPGP key generator
* @constructor
*/
e2e.openpgp.KeyGenerator = function() {};
/**
* ECC key generation seed
* @type {?e2e.ByteArray}
* @private
*/
e2e.openpgp.KeyGenerator.prototype.eccSeed_;
/**
* Number of keys generated from ECC generation seed
* @type {?number}
* @private
*/
e2e.openpgp.KeyGenerator.prototype.eccCount_;
/**
* Size in bytes for the ECC key generation seed.
* @const
*/
e2e.openpgp.KeyGenerator.ECC_SEED_SIZE = 16;
/**
* Returns the ECC key generation seed and key count backup data.
* @return {!e2e.openpgp.KeyringBackupInfo}
*/
e2e.openpgp.KeyGenerator.prototype.getGeneratorState = function() {
return {
seed: this.eccSeed_,
count: this.eccCount_
};
};
/**
* Initializes the ECC key generation seed and key count.
* @param {e2e.openpgp.KeyringBackupInfo} backupInfo
*/
e2e.openpgp.KeyGenerator.prototype.setGeneratorState = function(backupInfo) {
if (goog.isDefAndNotNull(backupInfo) && backupInfo.count % 2) {
throw new e2e.error.InvalidArgumentsError('Keys must be restored in pairs');
}
this.eccSeed_ = goog.isDefAndNotNull(backupInfo) ? (backupInfo.seed ||
null) : null;
this.eccCount_ = goog.isDefAndNotNull(backupInfo) ? (backupInfo.count ||
null) : null;
};
/**
* Generates and imports to the key ring a master signing key and a subordinate
* encryption key.
* @param {string} email The email to associate the key with.
* @param {!e2e.signer.Algorithm} keyAlgo Algorithm of the master key.
* It must be one of the digital signature algorithms.
* @param {number} keyLength Length in bits of the master key.
* @param {e2e.cipher.Algorithm} subkeyAlgo Algorithm of the subkey.
* It must be one of the cipher algorithms.
* @param {number} subkeyLength Length in bits of the subkey.
* @param {!e2e.algorithm.KeyLocations=} opt_keyLocation Where should the key be
* stored? (default to JS)
* @return {e2e.async.Result.<!Array.<!e2e.openpgp.block.TransferableKey>>}
* The generated public key and secret key in an array.
*/
e2e.openpgp.KeyGenerator.prototype.generateKey = function(email,
keyAlgo,
keyLength,
subkeyAlgo,
subkeyLength,
opt_keyLocation) {
var keyData = {
'pubKey': new Array(),
'privKey': new Array()
};
if (!goog.isDef(opt_keyLocation)) {
opt_keyLocation = e2e.algorithm.KeyLocations.JAVASCRIPT;
}
if (opt_keyLocation == e2e.algorithm.KeyLocations.JAVASCRIPT) {
var fingerprint;
if (keyAlgo == e2e.signer.Algorithm.ECDSA &&
keyLength == 256) {
var ecdsa = e2e.asymmetric.keygenerator.newEcdsaWithP256(
this.getNextKey_(keyLength));
this.extractKeyData_(keyData, ecdsa);
fingerprint = keyData.pubKey[0].fingerprint;
}
if (subkeyAlgo == e2e.cipher.Algorithm.ECDH &&
subkeyLength == 256) {
var ecdh = e2e.asymmetric.keygenerator.newEcdhWithP256(
this.getNextKey_(subkeyLength));
this.extractKeyData_(keyData, ecdh, true);
}
return e2e.async.Result.toResult(this.certifyKeys_(email, keyData));
} else if (opt_keyLocation == e2e.algorithm.KeyLocations.WEB_CRYPTO) {
if (keyAlgo == e2e.signer.Algorithm.RSA) {
if ((keyLength != 4096 && keyLength != 8192) ||
subkeyAlgo != e2e.cipher.Algorithm.RSA || subkeyLength != keyLength) {
throw new e2e.openpgp.error.UnsupportedError(
'WebCrypto RSA keyLength must be 4096 or 8192');
}
return e2e.asymmetric.keygenerator.newWebCryptoRsaKeys(
keyLength).addCallback(
function(ciphers) {
this.extractKeyData_(keyData, ciphers[0]);
this.extractKeyData_(keyData, ciphers[1]);
return this.certifyKeys_(email, keyData);
});
}
} else if (opt_keyLocation == e2e.algorithm.KeyLocations.HARDWARE) {
// TODO(user): https://code.google.com/p/end-to-end/issues/detail?id=130
throw new e2e.openpgp.error.UnsupportedError(
'Hardware keygen not supported yet');
}
// Should never happen.
throw new e2e.openpgp.error.UnsupportedError(
'Unsupported key type or length.');
};
/**
* @param {string} email The email to associate the key with.
* @param {{privKey: Array, pubKey: Array}} keyData
* @return {!Array.<!e2e.openpgp.block.TransferableKey>}
* @private
*/
e2e.openpgp.KeyGenerator.prototype.certifyKeys_ = function(email, keyData) {
if (keyData['pubKey'].length == 2 && keyData['privKey'].length == 2) {
// TODO(evn): Move this code to a .construct.
var primaryKey = keyData['privKey'][0];
var uid = new e2e.openpgp.packet.UserId(email);
uid.certifyBy(primaryKey);
keyData['privKey'][1].bindTo(
primaryKey,
e2e.openpgp.packet.Signature.SignatureType.SUBKEY,
e2e.openpgp.packet.SignatureSub.KeyFlags.ENCRYPT_COMMUNICATION |
e2e.openpgp.packet.SignatureSub.KeyFlags.ENCRYPT_STORAGE);
keyData['pubKey'][1].bindTo(
primaryKey,
e2e.openpgp.packet.Signature.SignatureType.SUBKEY,
e2e.openpgp.packet.SignatureSub.KeyFlags.ENCRYPT_COMMUNICATION |
e2e.openpgp.packet.SignatureSub.KeyFlags.ENCRYPT_STORAGE
);
var privKeyBlock = new e2e.openpgp.block.TransferableSecretKey();
privKeyBlock.keyPacket = primaryKey;
privKeyBlock.addUnverifiedSubKey(keyData['privKey'][1]);
privKeyBlock.addUnverifiedUserId(uid);
var pubKeyBlock = new e2e.openpgp.block.TransferablePublicKey();
pubKeyBlock.keyPacket = keyData['pubKey'][0];
pubKeyBlock.addUnverifiedSubKey(keyData['pubKey'][1]);
pubKeyBlock.addUnverifiedUserId(uid);
privKeyBlock.processSignatures();
pubKeyBlock.processSignatures();
return [pubKeyBlock, privKeyBlock];
}
// Should never happen.
throw new e2e.openpgp.error.UnsupportedError(
'Unsupported key type or length.');
};
/**
* Extracts serialized key data contained in a crypto object.
* @param {{privKey: Array, pubKey: Array}} keyData The map
* to store the extracted data.
* @param {!e2e.cipher.Cipher|!e2e.signer.Signer} cryptor
* The crypto object to extract key material.
* @param {boolean=} opt_subKey Whether the key is a subkey. Defaults to false.
* @param {boolean=} opt_isJS Whether the key material is stored in JS.
* Default to true.
* @private
*/
e2e.openpgp.KeyGenerator.prototype.extractKeyData_ = function(
keyData, cryptor, opt_subKey, opt_isJS) {
var version = 0x04;
var timestamp = 0;
var publicConstructor = opt_subKey ?
e2e.openpgp.packet.PublicSubkey : e2e.openpgp.packet.PublicKey;
var secretConstructor = opt_subKey ?
e2e.openpgp.packet.SecretSubkey : e2e.openpgp.packet.SecretKey;
var pubKey = new publicConstructor(
version, timestamp, cryptor);
var serializedPubKey = pubKey.serializePacketBody();
if (!goog.isDef(opt_isJS)) {
opt_isJS = true;
}
var serializedPrivKey;
if (opt_isJS) {
// privKey is MPI, needs to serialize to get the right byte array.
var privKey = e2e.openpgp.Mpi.serialize(cryptor.getKey()['privKey']);
serializedPrivKey = goog.array.flatten(
serializedPubKey,
/* key is not encrypted individually. */
e2e.openpgp.EncryptedCipher.KeyDerivationType.PLAINTEXT,
privKey,
e2e.openpgp.calculateNumericChecksum(privKey));
} else {
// Use dummy s2k
var s2k = new e2e.openpgp.DummyS2k(new e2e.hash.Sha256,
[0x45, 0x32, 0x45],
e2e.openpgp.DummyS2k.E2E_modes.WEB_CRYPTO);
serializedPrivKey = goog.array.flatten(
serializedPubKey,
e2e.openpgp.EncryptedCipher.KeyDerivationType.S2K_CHECKSUM,
s2k.serialize(), [0], [0]);
}
privKey = secretConstructor.parse(serializedPrivKey);
privKey.cipher.unlockKey();
keyData['privKey'].push(privKey);
keyData['pubKey'].push(
publicConstructor.parse(serializedPubKey));
};
/**
* Generates the next key in the sequence based on the ECC generation seed
* @param {number} keyLength Length in bits of the key.
* @private
* @return {!e2e.ByteArray} Deterministic privKey based on ECC seed.
*/
e2e.openpgp.KeyGenerator.prototype.getNextKey_ = function(keyLength) {
if (!this.eccSeed_) {
this.eccSeed_ = e2e.random.getRandomBytes(
e2e.openpgp.KeyGenerator.ECC_SEED_SIZE);
this.eccCount_ = 0;
}
if (++this.eccCount_ > 0x7F) {
throw new e2e.openpgp.error.UnsupportedError('Too many ECC keys generated');
}
if (keyLength % 8) {
throw new e2e.openpgp.error.UnsupportedError(
'Key length is not a multiple of 8');
}
return new e2e.Hkdf(new e2e.hash.Sha256()).getHKDF(this.eccSeed_,
e2e.dwordArrayToByteArray([this.eccCount_]), keyLength / 8);
};
| adhintz/end-to-end | src/javascript/crypto/e2e/openpgp/keygenerator.js | JavaScript | apache-2.0 | 10,724 |
/* *
*
* (c) 2010-2018 Torstein Honsi
*
* License: www.highcharts.com/license
*
* */
/**
* Options to align the element relative to the chart or another box.
*
* @interface Highcharts.AlignObject
*//**
* Horizontal alignment. Can be one of `left`, `center` and `right`.
*
* @name Highcharts.AlignObject#align
* @type {string|undefined}
*
* @default left
*//**
* Vertical alignment. Can be one of `top`, `middle` and `bottom`.
*
* @name Highcharts.AlignObject#verticalAlign
* @type {string|undefined}
*
* @default top
*//**
* Horizontal pixel offset from alignment.
*
* @name Highcharts.AlignObject#x
* @type {number|undefined}
*
* @default 0
*//**
* Vertical pixel offset from alignment.
*
* @name Highcharts.AlignObject#y
* @type {number|undefined}
*
* @default 0
*//**
* Use the `transform` attribute with translateX and translateY custom
* attributes to align this elements rather than `x` and `y` attributes.
*
* @name Highcharts.AlignObject#alignByTranslate
* @type {boolean|undefined}
*
* @default false
*/
/**
* Bounding box of an element.
*
* @interface Highcharts.BBoxObject
*//**
* Height of the bounding box.
*
* @name Highcharts.BBoxObject#height
* @type {number}
*//**
* Width of the bounding box.
*
* @name Highcharts.BBoxObject#width
* @type {number}
*//**
* Horizontal position of the bounding box.
*
* @name Highcharts.BBoxObject#x
* @type {number}
*//**
* Vertical position of the bounding box.
*
* @name Highcharts.BBoxObject#y
* @type {number}
*/
/**
* A clipping rectangle that can be applied to one or more {@link SVGElement}
* instances. It is instanciated with the {@link SVGRenderer#clipRect} function
* and applied with the {@link SVGElement#clip} function.
*
* @example
* var circle = renderer.circle(100, 100, 100)
* .attr({ fill: 'red' })
* .add();
* var clipRect = renderer.clipRect(100, 100, 100, 100);
*
* // Leave only the lower right quarter visible
* circle.clip(clipRect);
*
* @typedef {Highcharts.SVGElement} Highcharts.ClipRectElement
*/
/**
* The font metrics.
*
* @interface Highcharts.FontMetricsObject
*//**
* The baseline relative to the top of the box.
*
* @name Highcharts.FontMetricsObject#b
* @type {number}
*//**
* The line height.
*
* @name Highcharts.FontMetricsObject#h
* @type {number}
*//**
* The font size.
*
* @name Highcharts.FontMetricsObject#f
* @type {number}
*/
/**
* Gradient options instead of a solid color.
*
* @example
* // Linear gradient used as a color option
* color: {
* linearGradient: { x1: 0, x2: 0, y1: 0, y2: 1 },
* stops: [
* [0, '#003399'], // start
* [0.5, '#ffffff'], // middle
* [1, '#3366AA'] // end
* ]
* }
* }
*
* @interface Highcharts.GradientColorObject
*//**
* Holds an object that defines the start position and the end position relative
* to the shape.
*
* @name Highcharts.GradientColorObject#linearGradient
* @type {Highcharts.LinearGradientColorObject|undefined}
*//**
* Holds an object that defines the center position and the radius.
*
* @name Highcharts.GradientColorObject#radialGradient
* @type {Highcharts.RadialGradientColorObject|undefined}
*//**
* The first item in each tuple is the position in the gradient, where 0 is the
* start of the gradient and 1 is the end of the gradient. Multiple stops can be
* applied. The second item is the color for each stop. This color can also be
* given in the rgba format.
*
* @name Highcharts.GradientColorObject#stops
* @type {Array<Array<number,Highcharts.ColorString>>|undefined}
*/
/**
* Defines the start position and the end position for a gradient relative
* to the shape. Start position (x1, y1) and end position (x2, y2) are relative
* to the shape, where 0 means top/left and 1 is bottom/right.
*
* @interface Highcharts.LinearGradientColorObject
*//**
* Start horizontal position of the gradient. Float ranges 0-1.
*
* @name Highcharts.LinearGradientColorObject#x1
* @type {number}
*//**
* End horizontal position of the gradient. Float ranges 0-1.
*
* @name Highcharts.LinearGradientColorObject#x2
* @type {number}
*//**
* Start vertical position of the gradient. Float ranges 0-1.
*
* @name Highcharts.LinearGradientColorObject#y1
* @type {number}
*//**
* End vertical position of the gradient. Float ranges 0-1.
*
* @name Highcharts.LinearGradientColorObject#y2
* @type {number}
*/
/**
* Defines the center position and the radius for a gradient.
*
* @interface Highcharts.RadialGradientColorObject
*//**
* Center horizontal position relative to the shape. Float ranges 0-1.
*
* @name Highcharts.RadialGradientColorObject#cx
* @type {number}
*//**
* Center vertical position relative to the shape. Float ranges 0-1.
*
* @name Highcharts.RadialGradientColorObject#cy
* @type {number}
*//**
* Radius relative to the shape. Float ranges 0-1.
*
* @name Highcharts.RadialGradientColorObject#r
* @type {number}
*/
/**
* A rectangle.
*
* @interface Highcharts.RectangleObject
*//**
* Height of the rectangle.
*
* @name Highcharts.RectangleObject#height
* @type {number}
*//**
* Width of the rectangle.
*
* @name Highcharts.RectangleObject#width
* @type {number}
*//**
* Horizontal position of the rectangle.
*
* @name Highcharts.RectangleObject#x
* @type {number}
*//**
* Vertical position of the rectangle.
*
* @name Highcharts.RectangleObject#y
* @type {number}
*/
/**
* The shadow options.
*
* @interface Highcharts.ShadowOptionsObject
*//**
* The shadow color.
*
* @name Highcharts.ShadowOptionsObject#color
* @type {string|undefined}
*
* @default #000000
*//**
* The horizontal offset from the element.
*
* @name Highcharts.ShadowOptionsObject#offsetX
* @type {number|undefined}
*
* @default 1
*//**
* The vertical offset from the element.
*
* @name Highcharts.ShadowOptionsObject#offsetY
* @type {number|undefined}
*
* @default 1
*//**
* The shadow opacity.
*
* @name Highcharts.ShadowOptionsObject#opacity
* @type {number|undefined}
*
* @default 0.15
*//**
* The shadow width or distance from the element.
*
* @name Highcharts.ShadowOptionsObject#width
* @type {number|undefined}
*
* @default 3
*/
/**
* Serialized form of an SVG definition, including children. Some key
* property names are reserved: tagName, textContent, and children.
*
* @interface Highcharts.SVGDefinitionObject
*//**
* @name Highcharts.SVGDefinitionObject#[key:string]
* @type {number|string|Array<Highcharts.SVGDefinitionObject>|undefined}
*//**
* @name Highcharts.SVGDefinitionObject#children
* @type {Array<Highcharts.SVGDefinitionObject>|undefined}
*//**
* @name Highcharts.SVGDefinitionObject#tagName
* @type {string|undefined}
*//**
* @name Highcharts.SVGDefinitionObject#textContent
* @type {string|undefined}
*/
/**
* An extendable collection of functions for defining symbol paths.
*
* @typedef Highcharts.SymbolDictionary
*
* @property {Function|undefined} [key:Highcharts.SymbolKey]
*/
/**
* Can be one of `arc`, `callout`, `circle`, `diamond`, `square`,
* `triangle`, `triangle-down`. Symbols are used internally for point
* markers, button and label borders and backgrounds, or custom shapes.
* Extendable by adding to {@link SVGRenderer#symbols}.
*
* @typedef {string} Highcharts.SymbolKey
* @validvalue ["arc", "callout", "circle", "diamond", "square", "triangle",
* "triangle-down"]
*/
/**
* Additional options, depending on the actual symbol drawn.
*
* @interface Highcharts.SymbolOptionsObject
*//**
* The anchor X position for the `callout` symbol. This is where the chevron
* points to.
*
* @name Highcharts.SymbolOptionsObject#anchorX
* @type {number}
*//**
* The anchor Y position for the `callout` symbol. This is where the chevron
* points to.
*
* @name Highcharts.SymbolOptionsObject#anchorY
* @type {number}
*//**
* The end angle of an `arc` symbol.
*
* @name Highcharts.SymbolOptionsObject#end
* @type {number}
*//**
* Whether to draw `arc` symbol open or closed.
*
* @name Highcharts.SymbolOptionsObject#open
* @type {boolean}
*//**
* The radius of an `arc` symbol, or the border radius for the `callout` symbol.
*
* @name Highcharts.SymbolOptionsObject#r
* @type {number}
*//**
* The start angle of an `arc` symbol.
*
* @name Highcharts.SymbolOptionsObject#start
* @type {number}
*/
'use strict';
import H from './Globals.js';
import './Utilities.js';
import './Color.js';
var SVGElement,
SVGRenderer,
addEvent = H.addEvent,
animate = H.animate,
attr = H.attr,
charts = H.charts,
color = H.color,
css = H.css,
createElement = H.createElement,
defined = H.defined,
deg2rad = H.deg2rad,
destroyObjectProperties = H.destroyObjectProperties,
doc = H.doc,
extend = H.extend,
erase = H.erase,
hasTouch = H.hasTouch,
isArray = H.isArray,
isFirefox = H.isFirefox,
isMS = H.isMS,
isObject = H.isObject,
isString = H.isString,
isWebKit = H.isWebKit,
merge = H.merge,
noop = H.noop,
objectEach = H.objectEach,
pick = H.pick,
pInt = H.pInt,
removeEvent = H.removeEvent,
splat = H.splat,
stop = H.stop,
svg = H.svg,
SVG_NS = H.SVG_NS,
symbolSizes = H.symbolSizes,
win = H.win;
/**
* The SVGElement prototype is a JavaScript wrapper for SVG elements used in the
* rendering layer of Highcharts. Combined with the {@link
* Highcharts.SVGRenderer} object, these prototypes allow freeform annotation
* in the charts or even in HTML pages without instanciating a chart. The
* SVGElement can also wrap HTML labels, when `text` or `label` elements are
* created with the `useHTML` parameter.
*
* The SVGElement instances are created through factory functions on the {@link
* Highcharts.SVGRenderer} object, like {@link Highcharts.SVGRenderer#rect|
* rect}, {@link Highcharts.SVGRenderer#path|path}, {@link
* Highcharts.SVGRenderer#text|text}, {@link Highcharts.SVGRenderer#label|
* label}, {@link Highcharts.SVGRenderer#g|g} and more.
*
* @class
* @name Highcharts.SVGElement
*/
SVGElement = H.SVGElement = function () {
return this;
};
extend(SVGElement.prototype, /** @lends Highcharts.SVGElement.prototype */ {
// Default base for animation
opacity: 1,
SVG_NS: SVG_NS,
/**
* For labels, these CSS properties are applied to the `text` node directly.
*
* @private
* @name Highcharts.SVGElement#textProps
* @type {Array<string>}
*/
textProps: ['direction', 'fontSize', 'fontWeight', 'fontFamily',
'fontStyle', 'color', 'lineHeight', 'width', 'textAlign',
'textDecoration', 'textOverflow', 'textOutline', 'cursor'],
/**
* Initialize the SVG element. This function only exists to make the
* initiation process overridable. It should not be called directly.
*
* @function Highcharts.SVGElement#init
*
* @param {Highcharts.SVGRenderer} renderer
* The SVGRenderer instance to initialize to.
*
* @param {string} nodeName
* The SVG node name.
*/
init: function (renderer, nodeName) {
/**
* The primary DOM node. Each `SVGElement` instance wraps a main DOM
* node, but may also represent more nodes.
*
* @name Highcharts.SVGElement#element
* @type {Highcharts.SVGDOMElement|Highcharts.HTMLDOMElement}
*/
this.element = nodeName === 'span' ?
createElement(nodeName) :
doc.createElementNS(this.SVG_NS, nodeName);
/**
* The renderer that the SVGElement belongs to.
*
* @name Highcharts.SVGElement#renderer
* @type {Highcharts.SVGRenderer}
*/
this.renderer = renderer;
},
/**
* Animate to given attributes or CSS properties.
*
* @sample highcharts/members/element-on/
* Setting some attributes by animation
*
* @function Highcharts.SVGElement#animate
*
* @param {Highcharts.SVGAttributes} params
* SVG attributes or CSS to animate.
*
* @param {Highcharts.AnimationOptionsObject} [options]
* Animation options.
*
* @param {Function} [complete]
* Function to perform at the end of animation.
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
animate: function (params, options, complete) {
var animOptions = H.animObject(
pick(options, this.renderer.globalAnimation, true)
);
if (animOptions.duration !== 0) {
// allows using a callback with the global animation without
// overwriting it
if (complete) {
animOptions.complete = complete;
}
animate(this, params, animOptions);
} else {
this.attr(params, null, complete);
if (animOptions.step) {
animOptions.step.call(this);
}
}
return this;
},
/**
* Build and apply an SVG gradient out of a common JavaScript configuration
* object. This function is called from the attribute setters. An event
* hook is added for supporting other complex color types.
*
* @private
* @function Highcharts.SVGElement#complexColor
*
* @param {Highcharts.GradientColorObject} color
* The gradient options structure.
*
* @param {string} prop
* The property to apply, can either be `fill` or `stroke`.
*
* @param {Highcharts.SVGDOMElement} elem
* SVG DOM element to apply the gradient on.
*/
complexColor: function (color, prop, elem) {
var renderer = this.renderer,
colorObject,
gradName,
gradAttr,
radAttr,
gradients,
gradientObject,
stops,
stopColor,
stopOpacity,
radialReference,
id,
key = [],
value;
H.fireEvent(this.renderer, 'complexColor', {
args: arguments
}, function () {
// Apply linear or radial gradients
if (color.radialGradient) {
gradName = 'radialGradient';
} else if (color.linearGradient) {
gradName = 'linearGradient';
}
if (gradName) {
gradAttr = color[gradName];
gradients = renderer.gradients;
stops = color.stops;
radialReference = elem.radialReference;
// Keep < 2.2 kompatibility
if (isArray(gradAttr)) {
color[gradName] = gradAttr = {
x1: gradAttr[0],
y1: gradAttr[1],
x2: gradAttr[2],
y2: gradAttr[3],
gradientUnits: 'userSpaceOnUse'
};
}
// Correct the radial gradient for the radial reference system
if (
gradName === 'radialGradient' &&
radialReference &&
!defined(gradAttr.gradientUnits)
) {
// Save the radial attributes for updating
radAttr = gradAttr;
gradAttr = merge(
gradAttr,
renderer.getRadialAttr(radialReference, radAttr),
{ gradientUnits: 'userSpaceOnUse' }
);
}
// Build the unique key to detect whether we need to create a
// new element (#1282)
objectEach(gradAttr, function (val, n) {
if (n !== 'id') {
key.push(n, val);
}
});
objectEach(stops, function (val) {
key.push(val);
});
key = key.join(',');
// Check if a gradient object with the same config object is
// created within this renderer
if (gradients[key]) {
id = gradients[key].attr('id');
} else {
// Set the id and create the element
gradAttr.id = id = H.uniqueKey();
gradients[key] = gradientObject =
renderer.createElement(gradName)
.attr(gradAttr)
.add(renderer.defs);
gradientObject.radAttr = radAttr;
// The gradient needs to keep a list of stops to be able to
// destroy them
gradientObject.stops = [];
stops.forEach(function (stop) {
var stopObject;
if (stop[1].indexOf('rgba') === 0) {
colorObject = H.color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
stopObject = renderer.createElement('stop').attr({
offset: stop[0],
'stop-color': stopColor,
'stop-opacity': stopOpacity
}).add(gradientObject);
// Add the stop element to the gradient
gradientObject.stops.push(stopObject);
});
}
// Set the reference to the gradient object
value = 'url(' + renderer.url + '#' + id + ')';
elem.setAttribute(prop, value);
elem.gradient = key;
// Allow the color to be concatenated into tooltips formatters
// etc. (#2995)
color.toString = function () {
return value;
};
}
});
},
/**
* Apply a text outline through a custom CSS property, by copying the text
* element and apply stroke to the copy. Used internally. Contrast checks at
* [example](https://jsfiddle.net/highcharts/43soe9m1/2/).
*
* @example
* // Specific color
* text.css({
* textOutline: '1px black'
* });
* // Automatic contrast
* text.css({
* color: '#000000', // black text
* textOutline: '1px contrast' // => white outline
* });
*
* @private
* @function Highcharts.SVGElement#applyTextOutline
*
* @param {string} textOutline
* A custom CSS `text-outline` setting, defined by `width color`.
*/
applyTextOutline: function (textOutline) {
var elem = this.element,
tspans,
tspan,
hasContrast = textOutline.indexOf('contrast') !== -1,
styles = {},
color,
strokeWidth,
firstRealChild,
i;
// When the text shadow is set to contrast, use dark stroke for light
// text and vice versa.
if (hasContrast) {
styles.textOutline = textOutline = textOutline.replace(
/contrast/g,
this.renderer.getContrast(elem.style.fill)
);
}
// Extract the stroke width and color
textOutline = textOutline.split(' ');
color = textOutline[textOutline.length - 1];
strokeWidth = textOutline[0];
if (strokeWidth && strokeWidth !== 'none' && H.svg) {
this.fakeTS = true; // Fake text shadow
tspans = [].slice.call(elem.getElementsByTagName('tspan'));
// In order to get the right y position of the clone,
// copy over the y setter
this.ySetter = this.xSetter;
// Since the stroke is applied on center of the actual outline, we
// need to double it to get the correct stroke-width outside the
// glyphs.
strokeWidth = strokeWidth.replace(
/(^[\d\.]+)(.*?)$/g,
function (match, digit, unit) {
return (2 * digit) + unit;
}
);
// Remove shadows from previous runs. Iterate from the end to
// support removing items inside the cycle (#6472).
i = tspans.length;
while (i--) {
tspan = tspans[i];
if (tspan.getAttribute('class') === 'highcharts-text-outline') {
// Remove then erase
erase(tspans, elem.removeChild(tspan));
}
}
// For each of the tspans, create a stroked copy behind it.
firstRealChild = elem.firstChild;
tspans.forEach(function (tspan, y) {
var clone;
// Let the first line start at the correct X position
if (y === 0) {
tspan.setAttribute('x', elem.getAttribute('x'));
y = elem.getAttribute('y');
tspan.setAttribute('y', y || 0);
if (y === null) {
elem.setAttribute('y', 0);
}
}
// Create the clone and apply outline properties
clone = tspan.cloneNode(1);
attr(clone, {
'class': 'highcharts-text-outline',
'fill': color,
'stroke': color,
'stroke-width': strokeWidth,
'stroke-linejoin': 'round'
});
elem.insertBefore(clone, firstRealChild);
});
}
},
// Custom attributes used for symbols, these should be filtered out when
// setting SVGElement attributes (#9375).
symbolCustomAttribs: [
'x',
'y',
'width',
'height',
'r',
'start',
'end',
'innerR',
'anchorX',
'anchorY',
'rounded'
],
/**
* Apply native and custom attributes to the SVG elements.
*
* In order to set the rotation center for rotation, set x and y to 0 and
* use `translateX` and `translateY` attributes to position the element
* instead.
*
* Attributes frequently used in Highcharts are `fill`, `stroke`,
* `stroke-width`.
*
* @sample highcharts/members/renderer-rect/
* Setting some attributes
*
* @example
* // Set multiple attributes
* element.attr({
* stroke: 'red',
* fill: 'blue',
* x: 10,
* y: 10
* });
*
* // Set a single attribute
* element.attr('stroke', 'red');
*
* // Get an attribute
* element.attr('stroke'); // => 'red'
*
* @function Highcharts.SVGElement#attr
*
* @param {string|Highcharts.SVGAttributes} [hash]
* The native and custom SVG attributes.
*
* @param {string} [val]
* If the type of the first argument is `string`, the second can be a
* value, which will serve as a single attribute setter. If the first
* argument is a string and the second is undefined, the function
* serves as a getter and the current value of the property is
* returned.
*
* @param {Function} [complete]
* A callback function to execute after setting the attributes. This
* makes the function compliant and interchangeable with the
* {@link SVGElement#animate} function.
*
* @param {boolean} [continueAnimation=true]
* Used internally when `.attr` is called as part of an animation
* step. Otherwise, calling `.attr` for an attribute will stop
* animation for that attribute.
*
* @return {number|string|Highcharts.SVGElement}
* If used as a setter, it returns the current
* {@link Highcharts.SVGElement} so the calls can be chained. If
* used as a getter, the current value of the attribute is returned.
*/
attr: function (hash, val, complete, continueAnimation) {
var key,
element = this.element,
hasSetSymbolSize,
ret = this,
skipAttr,
setter,
symbolCustomAttribs = this.symbolCustomAttribs;
// single key-value pair
if (typeof hash === 'string' && val !== undefined) {
key = hash;
hash = {};
hash[key] = val;
}
// used as a getter: first argument is a string, second is undefined
if (typeof hash === 'string') {
ret = (this[hash + 'Getter'] || this._defaultGetter).call(
this,
hash,
element
);
// setter
} else {
objectEach(hash, function eachAttribute(val, key) {
skipAttr = false;
// Unless .attr is from the animator update, stop current
// running animation of this property
if (!continueAnimation) {
stop(this, key);
}
// Special handling of symbol attributes
if (
this.symbolName &&
H.inArray(key, symbolCustomAttribs) !== -1
) {
if (!hasSetSymbolSize) {
this.symbolAttr(hash);
hasSetSymbolSize = true;
}
skipAttr = true;
}
if (this.rotation && (key === 'x' || key === 'y')) {
this.doTransform = true;
}
if (!skipAttr) {
setter = this[key + 'Setter'] || this._defaultSetter;
setter.call(this, val, key, element);
// Let the shadow follow the main element
if (
!this.styledMode &&
this.shadows &&
/^(width|height|visibility|x|y|d|transform|cx|cy|r)$/
.test(key)
) {
this.updateShadows(key, val, setter);
}
}
}, this);
this.afterSetters();
}
// In accordance with animate, run a complete callback
if (complete) {
complete.call(this);
}
return ret;
},
/**
* This method is executed in the end of `attr()`, after setting all
* attributes in the hash. In can be used to efficiently consolidate
* multiple attributes in one SVG property -- e.g., translate, rotate and
* scale are merged in one "transform" attribute in the SVG node.
*
* @private
* @function Highcharts.SVGElement#afterSetters
*/
afterSetters: function () {
// Update transform. Do this outside the loop to prevent redundant
// updating for batch setting of attributes.
if (this.doTransform) {
this.updateTransform();
this.doTransform = false;
}
},
/**
* Update the shadow elements with new attributes.
*
* @private
* @function Highcharts.SVGElement#updateShadows
*
* @param {string} key
* The attribute name.
*
* @param {string|number} value
* The value of the attribute.
*
* @param {Function} setter
* The setter function, inherited from the parent wrapper.
*/
updateShadows: function (key, value, setter) {
var shadows = this.shadows,
i = shadows.length;
while (i--) {
setter.call(
shadows[i],
key === 'height' ?
Math.max(value - (shadows[i].cutHeight || 0), 0) :
key === 'd' ? this.d : value,
key,
shadows[i]
);
}
},
/**
* Add a class name to an element.
*
* @function Highcharts.SVGElement#addClass
*
* @param {string} className
* The new class name to add.
*
* @param {boolean} [replace=false]
* When true, the existing class name(s) will be overwritten with
* the new one. When false, the new one is added.
*
* @return {Highcharts.SVGElement}
* Return the SVG element for chainability.
*/
addClass: function (className, replace) {
var currentClassName = this.attr('class') || '';
if (currentClassName.indexOf(className) === -1) {
if (!replace) {
className =
(currentClassName + (currentClassName ? ' ' : '') +
className).replace(' ', ' ');
}
this.attr('class', className);
}
return this;
},
/**
* Check if an element has the given class name.
*
* @function Highcharts.SVGElement#hasClass
*
* @param {string} className
* The class name to check for.
*
* @return {boolean}
* Whether the class name is found.
*/
hasClass: function (className) {
return (this.attr('class') || '').split(' ').indexOf(className) !== -1;
},
/**
* Remove a class name from the element.
*
* @function Highcharts.SVGElement#removeClass
*
* @param {string|RegExp} className
* The class name to remove.
*
* @return {Highcharts.SVGElement} Returns the SVG element for chainability.
*/
removeClass: function (className) {
return this.attr(
'class',
(this.attr('class') || '').replace(className, '')
);
},
/**
* If one of the symbol size affecting parameters are changed,
* check all the others only once for each call to an element's
* .attr() method
*
* @private
* @function Highcharts.SVGElement#symbolAttr
*
* @param {Highcharts.Dictionary<number|string>} hash
* The attributes to set.
*/
symbolAttr: function (hash) {
var wrapper = this;
[
'x',
'y',
'r',
'start',
'end',
'width',
'height',
'innerR',
'anchorX',
'anchorY'
].forEach(function (key) {
wrapper[key] = pick(hash[key], wrapper[key]);
});
wrapper.attr({
d: wrapper.renderer.symbols[wrapper.symbolName](
wrapper.x,
wrapper.y,
wrapper.width,
wrapper.height,
wrapper
)
});
},
/**
* Apply a clipping rectangle to this element.
*
* @function Highcharts.SVGElement#clip
*
* @param {Highcharts.ClipRectElement} [clipRect]
* The clipping rectangle. If skipped, the current clip is removed.
*
* @return {Highcharts.SVGElement}
* Returns the SVG element to allow chaining.
*/
clip: function (clipRect) {
return this.attr(
'clip-path',
clipRect ?
'url(' + this.renderer.url + '#' + clipRect.id + ')' :
'none'
);
},
/**
* Calculate the coordinates needed for drawing a rectangle crisply and
* return the calculated attributes.
*
* @function Highcharts.SVGElement#crisp
*
* @param {Highcharts.RectangleObject} rect
* Rectangle to crisp.
*
* @param {number} [strokeWidth]
* The stroke width to consider when computing crisp positioning. It
* can also be set directly on the rect parameter.
*
* @return {Highcharts.RectangleObject}
* The modified rectangle arguments.
*/
crisp: function (rect, strokeWidth) {
var wrapper = this,
normalizer;
strokeWidth = strokeWidth || rect.strokeWidth || 0;
// Math.round because strokeWidth can sometimes have roundoff errors
normalizer = Math.round(strokeWidth) % 2 / 2;
// normalize for crisp edges
rect.x = Math.floor(rect.x || wrapper.x || 0) + normalizer;
rect.y = Math.floor(rect.y || wrapper.y || 0) + normalizer;
rect.width = Math.floor(
(rect.width || wrapper.width || 0) - 2 * normalizer
);
rect.height = Math.floor(
(rect.height || wrapper.height || 0) - 2 * normalizer
);
if (defined(rect.strokeWidth)) {
rect.strokeWidth = strokeWidth;
}
return rect;
},
/**
* Set styles for the element. In addition to CSS styles supported by
* native SVG and HTML elements, there are also some custom made for
* Highcharts, like `width`, `ellipsis` and `textOverflow` for SVG text
* elements.
*
* @sample highcharts/members/renderer-text-on-chart/
* Styled text
*
* @function Highcharts.SVGElement#css
*
* @param {Highcharts.CSSObject} styles
* The new CSS styles.
*
* @return {Highcharts.SVGElement}
* Return the SVG element for chaining.
*/
css: function (styles) {
var oldStyles = this.styles,
newStyles = {},
elem = this.element,
textWidth,
serializedCss = '',
hyphenate,
hasNew = !oldStyles,
// These CSS properties are interpreted internally by the SVG
// renderer, but are not supported by SVG and should not be added to
// the DOM. In styled mode, no CSS should find its way to the DOM
// whatsoever (#6173, #6474).
svgPseudoProps = ['textOutline', 'textOverflow', 'width'];
// convert legacy
if (styles && styles.color) {
styles.fill = styles.color;
}
// Filter out existing styles to increase performance (#2640)
if (oldStyles) {
objectEach(styles, function (style, n) {
if (style !== oldStyles[n]) {
newStyles[n] = style;
hasNew = true;
}
});
}
if (hasNew) {
// Merge the new styles with the old ones
if (oldStyles) {
styles = extend(
oldStyles,
newStyles
);
}
// Get the text width from style
if (styles) {
// Previously set, unset it (#8234)
if (styles.width === null || styles.width === 'auto') {
delete this.textWidth;
// Apply new
} else if (
elem.nodeName.toLowerCase() === 'text' &&
styles.width
) {
textWidth = this.textWidth = pInt(styles.width);
}
}
// store object
this.styles = styles;
if (textWidth && (!svg && this.renderer.forExport)) {
delete styles.width;
}
// Serialize and set style attribute
if (elem.namespaceURI === this.SVG_NS) { // #7633
hyphenate = function (a, b) {
return '-' + b.toLowerCase();
};
objectEach(styles, function (style, n) {
if (svgPseudoProps.indexOf(n) === -1) {
serializedCss +=
n.replace(/([A-Z])/g, hyphenate) + ':' +
style + ';';
}
});
if (serializedCss) {
attr(elem, 'style', serializedCss); // #1881
}
} else {
css(elem, styles);
}
if (this.added) {
// Rebuild text after added. Cache mechanisms in the buildText
// will prevent building if there are no significant changes.
if (this.element.nodeName === 'text') {
this.renderer.buildText(this);
}
// Apply text outline after added
if (styles && styles.textOutline) {
this.applyTextOutline(styles.textOutline);
}
}
}
return this;
},
/**
* Get the computed style. Only in styled mode.
*
* @example
* chart.series[0].points[0].graphic.getStyle('stroke-width'); // => '1px'
*
* @function Highcharts.SVGElement#getStyle
*
* @param {string} prop
* The property name to check for.
*
* @return {string}
* The current computed value.
*/
getStyle: function (prop) {
return win.getComputedStyle(this.element || this, '')
.getPropertyValue(prop);
},
/**
* Get the computed stroke width in pixel values. This is used extensively
* when drawing shapes to ensure the shapes are rendered crisp and
* positioned correctly relative to each other. Using
* `shape-rendering: crispEdges` leaves us less control over positioning,
* for example when we want to stack columns next to each other, or position
* things pixel-perfectly within the plot box.
*
* The common pattern when placing a shape is:
* - Create the SVGElement and add it to the DOM. In styled mode, it will
* now receive a stroke width from the style sheet. In classic mode we
* will add the `stroke-width` attribute.
* - Read the computed `elem.strokeWidth()`.
* - Place it based on the stroke width.
*
* @function Highcharts.SVGElement#strokeWidth
*
* @return {number}
* The stroke width in pixels. Even if the given stroke widtch (in
* CSS or by attributes) is based on `em` or other units, the pixel
* size is returned.
*/
strokeWidth: function () {
// In non-styled mode, read the stroke width as set by .attr
if (!this.renderer.styledMode) {
return this['stroke-width'] || 0;
}
// In styled mode, read computed stroke width
var val = this.getStyle('stroke-width'),
ret,
dummy;
// Read pixel values directly
if (val.indexOf('px') === val.length - 2) {
ret = pInt(val);
// Other values like em, pt etc need to be measured
} else {
dummy = doc.createElementNS(SVG_NS, 'rect');
attr(dummy, {
'width': val,
'stroke-width': 0
});
this.element.parentNode.appendChild(dummy);
ret = dummy.getBBox().width;
dummy.parentNode.removeChild(dummy);
}
return ret;
},
/**
* Add an event listener. This is a simple setter that replaces all other
* events of the same type, opposed to the {@link Highcharts#addEvent}
* function.
*
* @sample highcharts/members/element-on/
* A clickable rectangle
*
* @function Highcharts.SVGElement#on
*
* @param {string} eventType
* The event type. If the type is `click`, Highcharts will internally
* translate it to a `touchstart` event on touch devices, to prevent
* the browser from waiting for a click event from firing.
*
* @param {Function} handler
* The handler callback.
*
* @return {Highcharts.SVGElement}
* The SVGElement for chaining.
*/
on: function (eventType, handler) {
var svgElement = this,
element = svgElement.element;
// touch
if (hasTouch && eventType === 'click') {
element.ontouchstart = function (e) {
svgElement.touchEventFired = Date.now(); // #2269
e.preventDefault();
handler.call(element, e);
};
element.onclick = function (e) {
if (win.navigator.userAgent.indexOf('Android') === -1 ||
Date.now() - (svgElement.touchEventFired || 0) > 1100) {
handler.call(element, e);
}
};
} else {
// simplest possible event model for internal use
element['on' + eventType] = handler;
}
return this;
},
/**
* Set the coordinates needed to draw a consistent radial gradient across
* a shape regardless of positioning inside the chart. Used on pie slices
* to make all the slices have the same radial reference point.
*
* @function Highcharts.SVGElement#setRadialReference
*
* @param {Array<number>} coordinates
* The center reference. The format is `[centerX, centerY, diameter]`
* in pixels.
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
setRadialReference: function (coordinates) {
var existingGradient = this.renderer.gradients[this.element.gradient];
this.element.radialReference = coordinates;
// On redrawing objects with an existing gradient, the gradient needs
// to be repositioned (#3801)
if (existingGradient && existingGradient.radAttr) {
existingGradient.animate(
this.renderer.getRadialAttr(
coordinates,
existingGradient.radAttr
)
);
}
return this;
},
/**
* Move an object and its children by x and y values.
*
* @function Highcharts.SVGElement#translate
*
* @param {number} x
* The x value.
*
* @param {number} y
* The y value.
*/
translate: function (x, y) {
return this.attr({
translateX: x,
translateY: y
});
},
/**
* Invert a group, rotate and flip. This is used internally on inverted
* charts, where the points and graphs are drawn as if not inverted, then
* the series group elements are inverted.
*
* @function Highcharts.SVGElement#invert
*
* @param {boolean} inverted
* Whether to invert or not. An inverted shape can be un-inverted by
* setting it to false.
*
* @return {Highcharts.SVGElement}
* Return the SVGElement for chaining.
*/
invert: function (inverted) {
var wrapper = this;
wrapper.inverted = inverted;
wrapper.updateTransform();
return wrapper;
},
/**
* Update the transform attribute based on internal properties. Deals with
* the custom `translateX`, `translateY`, `rotation`, `scaleX` and `scaleY`
* attributes and updates the SVG `transform` attribute.
*
* @private
* @function Highcharts.SVGElement#updateTransform
*/
updateTransform: function () {
var wrapper = this,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
scaleX = wrapper.scaleX,
scaleY = wrapper.scaleY,
inverted = wrapper.inverted,
rotation = wrapper.rotation,
matrix = wrapper.matrix,
element = wrapper.element,
transform;
// Flipping affects translate as adjustment for flipping around the
// group's axis
if (inverted) {
translateX += wrapper.width;
translateY += wrapper.height;
}
// Apply translate. Nearly all transformed elements have translation,
// so instead of checking for translate = 0, do it always (#1767,
// #1846).
transform = ['translate(' + translateX + ',' + translateY + ')'];
// apply matrix
if (defined(matrix)) {
transform.push(
'matrix(' + matrix.join(',') + ')'
);
}
// apply rotation
if (inverted) {
transform.push('rotate(90) scale(-1,1)');
} else if (rotation) { // text rotation
transform.push(
'rotate(' + rotation + ' ' +
pick(this.rotationOriginX, element.getAttribute('x'), 0) +
' ' +
pick(this.rotationOriginY, element.getAttribute('y') || 0) + ')'
);
}
// apply scale
if (defined(scaleX) || defined(scaleY)) {
transform.push(
'scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'
);
}
if (transform.length) {
element.setAttribute('transform', transform.join(' '));
}
},
/**
* Bring the element to the front. Alternatively, a new zIndex can be set.
*
* @sample highcharts/members/element-tofront/
* Click an element to bring it to front
*
* @function Highcharts.SVGElement#toFront
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
toFront: function () {
var element = this.element;
element.parentNode.appendChild(element);
return this;
},
/**
* Align the element relative to the chart or another box.
*
* @function Highcharts.SVGElement#align
*
* @param {Highcharts.AlignObject} [alignOptions]
* The alignment options. The function can be called without this
* parameter in order to re-align an element after the box has been
* updated.
*
* @param {boolean} [alignByTranslate]
* Align element by translation.
*
* @param {string|Highcharts.BBoxObject} [box]
* The box to align to, needs a width and height. When the box is a
* string, it refers to an object in the Renderer. For example, when
* box is `spacingBox`, it refers to `Renderer.spacingBox` which
* holds `width`, `height`, `x` and `y` properties.
*
* @return {Highcharts.SVGElement} Returns the SVGElement for chaining.
*/
align: function (alignOptions, alignByTranslate, box) {
var align,
vAlign,
x,
y,
attribs = {},
alignTo,
renderer = this.renderer,
alignedObjects = renderer.alignedObjects,
alignFactor,
vAlignFactor;
// First call on instanciate
if (alignOptions) {
this.alignOptions = alignOptions;
this.alignByTranslate = alignByTranslate;
if (!box || isString(box)) {
this.alignTo = alignTo = box || 'renderer';
// prevent duplicates, like legendGroup after resize
erase(alignedObjects, this);
alignedObjects.push(this);
box = null; // reassign it below
}
// When called on resize, no arguments are supplied
} else {
alignOptions = this.alignOptions;
alignByTranslate = this.alignByTranslate;
alignTo = this.alignTo;
}
box = pick(box, renderer[alignTo], renderer);
// Assign variables
align = alignOptions.align;
vAlign = alignOptions.verticalAlign;
x = (box.x || 0) + (alignOptions.x || 0); // default: left align
y = (box.y || 0) + (alignOptions.y || 0); // default: top align
// Align
if (align === 'right') {
alignFactor = 1;
} else if (align === 'center') {
alignFactor = 2;
}
if (alignFactor) {
x += (box.width - (alignOptions.width || 0)) / alignFactor;
}
attribs[alignByTranslate ? 'translateX' : 'x'] = Math.round(x);
// Vertical align
if (vAlign === 'bottom') {
vAlignFactor = 1;
} else if (vAlign === 'middle') {
vAlignFactor = 2;
}
if (vAlignFactor) {
y += (box.height - (alignOptions.height || 0)) / vAlignFactor;
}
attribs[alignByTranslate ? 'translateY' : 'y'] = Math.round(y);
// Animate only if already placed
this[this.placed ? 'animate' : 'attr'](attribs);
this.placed = true;
this.alignAttr = attribs;
return this;
},
/**
* Get the bounding box (width, height, x and y) for the element. Generally
* used to get rendered text size. Since this is called a lot in charts,
* the results are cached based on text properties, in order to save DOM
* traffic. The returned bounding box includes the rotation, so for example
* a single text line of rotation 90 will report a greater height, and a
* width corresponding to the line-height.
*
* @sample highcharts/members/renderer-on-chart/
* Draw a rectangle based on a text's bounding box
*
* @function Highcharts.SVGElement#getBBox
*
* @param {boolean} [reload]
* Skip the cache and get the updated DOM bouding box.
*
* @param {number} [rot]
* Override the element's rotation. This is internally used on axis
* labels with a value of 0 to find out what the bounding box would
* be have been if it were not rotated.
*
* @return {Highcharts.BBoxObject}
* The bounding box with `x`, `y`, `width` and `height` properties.
*/
getBBox: function (reload, rot) {
var wrapper = this,
bBox, // = wrapper.bBox,
renderer = wrapper.renderer,
width,
height,
rotation,
rad,
element = wrapper.element,
styles = wrapper.styles,
fontSize,
textStr = wrapper.textStr,
toggleTextShadowShim,
cache = renderer.cache,
cacheKeys = renderer.cacheKeys,
isSVG = element.namespaceURI === wrapper.SVG_NS,
cacheKey;
rotation = pick(rot, wrapper.rotation);
rad = rotation * deg2rad;
fontSize = renderer.styledMode ? (
element &&
SVGElement.prototype.getStyle.call(element, 'font-size')
) : (
styles && styles.fontSize
);
// Avoid undefined and null (#7316)
if (defined(textStr)) {
cacheKey = textStr.toString();
// Since numbers are monospaced, and numerical labels appear a lot
// in a chart, we assume that a label of n characters has the same
// bounding box as others of the same length. Unless there is inner
// HTML in the label. In that case, leave the numbers as is (#5899).
if (cacheKey.indexOf('<') === -1) {
cacheKey = cacheKey.replace(/[0-9]/g, '0');
}
// Properties that affect bounding box
cacheKey += [
'',
rotation || 0,
fontSize,
wrapper.textWidth, // #7874, also useHTML
styles && styles.textOverflow // #5968
]
.join(',');
}
if (cacheKey && !reload) {
bBox = cache[cacheKey];
}
// No cache found
if (!bBox) {
// SVG elements
if (isSVG || renderer.forExport) {
try { // Fails in Firefox if the container has display: none.
// When the text shadow shim is used, we need to hide the
// fake shadows to get the correct bounding box (#3872)
toggleTextShadowShim = this.fakeTS && function (display) {
[].forEach.call(
element.querySelectorAll(
'.highcharts-text-outline'
),
function (tspan) {
tspan.style.display = display;
}
);
};
// Workaround for #3842, Firefox reporting wrong bounding
// box for shadows
if (toggleTextShadowShim) {
toggleTextShadowShim('none');
}
bBox = element.getBBox ?
// SVG: use extend because IE9 is not allowed to change
// width and height in case of rotation (below)
extend({}, element.getBBox()) : {
// Legacy IE in export mode
width: element.offsetWidth,
height: element.offsetHeight
};
// #3842
if (toggleTextShadowShim) {
toggleTextShadowShim('');
}
} catch (e) {}
// If the bBox is not set, the try-catch block above failed. The
// other condition is for Opera that returns a width of
// -Infinity on hidden elements.
if (!bBox || bBox.width < 0) {
bBox = { width: 0, height: 0 };
}
// VML Renderer or useHTML within SVG
} else {
bBox = wrapper.htmlGetBBox();
}
// True SVG elements as well as HTML elements in modern browsers
// using the .useHTML option need to compensated for rotation
if (renderer.isSVG) {
width = bBox.width;
height = bBox.height;
// Workaround for wrong bounding box in IE, Edge and Chrome on
// Windows. With Highcharts' default font, IE and Edge report
// a box height of 16.899 and Chrome rounds it to 17. If this
// stands uncorrected, it results in more padding added below
// the text than above when adding a label border or background.
// Also vertical positioning is affected.
// https://jsfiddle.net/highcharts/em37nvuj/
// (#1101, #1505, #1669, #2568, #6213).
if (isSVG) {
bBox.height = height = (
{
'11px,17': 14,
'13px,20': 16
}[
styles && styles.fontSize + ',' + Math.round(height)
] ||
height
);
}
// Adjust for rotated text
if (rotation) {
bBox.width = Math.abs(height * Math.sin(rad)) +
Math.abs(width * Math.cos(rad));
bBox.height = Math.abs(height * Math.cos(rad)) +
Math.abs(width * Math.sin(rad));
}
}
// Cache it. When loading a chart in a hidden iframe in Firefox and
// IE/Edge, the bounding box height is 0, so don't cache it (#5620).
if (cacheKey && bBox.height > 0) {
// Rotate (#4681)
while (cacheKeys.length > 250) {
delete cache[cacheKeys.shift()];
}
if (!cache[cacheKey]) {
cacheKeys.push(cacheKey);
}
cache[cacheKey] = bBox;
}
}
return bBox;
},
/**
* Show the element after it has been hidden.
*
* @function Highcharts.SVGElement#show
*
* @param {boolean} [inherit=false]
* Set the visibility attribute to `inherit` rather than `visible`.
* The difference is that an element with `visibility="visible"`
* will be visible even if the parent is hidden.
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
show: function (inherit) {
return this.attr({ visibility: inherit ? 'inherit' : 'visible' });
},
/**
* Hide the element, equivalent to setting the `visibility` attribute to
* `hidden`.
*
* @function Highcharts.SVGElement#hide
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
hide: function () {
return this.attr({ visibility: 'hidden' });
},
/**
* Fade out an element by animating its opacity down to 0, and hide it on
* complete. Used internally for the tooltip.
*
* @function Highcharts.SVGElement#fadeOut
*
* @param {number} [duration=150]
* The fade duration in milliseconds.
*/
fadeOut: function (duration) {
var elemWrapper = this;
elemWrapper.animate({
opacity: 0
}, {
duration: duration || 150,
complete: function () {
// #3088, assuming we're only using this for tooltips
elemWrapper.attr({ y: -9999 });
}
});
},
/**
* Add the element to the DOM. All elements must be added this way.
*
* @sample highcharts/members/renderer-g
* Elements added to a group
*
* @function Highcharts.SVGElement#add
*
* @param {Highcharts.SVGElement|Highcharts.SVGDOMElement} [parent]
* The parent item to add it to. If undefined, the element is added
* to the {@link Highcharts.SVGRenderer.box}.
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
add: function (parent) {
var renderer = this.renderer,
element = this.element,
inserted;
if (parent) {
this.parentGroup = parent;
}
// mark as inverted
this.parentInverted = parent && parent.inverted;
// build formatted text
if (this.textStr !== undefined) {
renderer.buildText(this);
}
// Mark as added
this.added = true;
// If we're adding to renderer root, or other elements in the group
// have a z index, we need to handle it
if (!parent || parent.handleZ || this.zIndex) {
inserted = this.zIndexSetter();
}
// If zIndex is not handled, append at the end
if (!inserted) {
(parent ? parent.element : renderer.box).appendChild(element);
}
// fire an event for internal hooks
if (this.onAdd) {
this.onAdd();
}
return this;
},
/**
* Removes an element from the DOM.
*
* @private
* @function Highcharts.SVGElement#safeRemoveChild
*
* @param {Highcharts.SVGDOMElement|Highcharts.HTMLDOMElement} element
* The DOM node to remove.
*/
safeRemoveChild: function (element) {
var parentNode = element.parentNode;
if (parentNode) {
parentNode.removeChild(element);
}
},
/**
* Destroy the element and element wrapper and clear up the DOM and event
* hooks.
*
* @function Highcharts.SVGElement#destroy
*/
destroy: function () {
var wrapper = this,
element = wrapper.element || {},
renderer = wrapper.renderer,
parentToClean =
renderer.isSVG &&
element.nodeName === 'SPAN' &&
wrapper.parentGroup,
grandParent,
ownerSVGElement = element.ownerSVGElement,
i,
clipPath = wrapper.clipPath;
// remove events
element.onclick = element.onmouseout = element.onmouseover =
element.onmousemove = element.point = null;
stop(wrapper); // stop running animations
if (clipPath && ownerSVGElement) {
// Look for existing references to this clipPath and remove them
// before destroying the element (#6196).
// The upper case version is for Edge
[].forEach.call(
ownerSVGElement.querySelectorAll('[clip-path],[CLIP-PATH]'),
function (el) {
var clipPathAttr = el.getAttribute('clip-path'),
clipPathId = clipPath.element.id;
// Include the closing paranthesis in the test to rule out
// id's from 10 and above (#6550). Edge puts quotes inside
// the url, others not.
if (
clipPathAttr.indexOf('(#' + clipPathId + ')') > -1 ||
clipPathAttr.indexOf('("#' + clipPathId + '")') > -1
) {
el.removeAttribute('clip-path');
}
}
);
wrapper.clipPath = clipPath.destroy();
}
// Destroy stops in case this is a gradient object
if (wrapper.stops) {
for (i = 0; i < wrapper.stops.length; i++) {
wrapper.stops[i] = wrapper.stops[i].destroy();
}
wrapper.stops = null;
}
// remove element
wrapper.safeRemoveChild(element);
if (!renderer.styledMode) {
wrapper.destroyShadows();
}
// In case of useHTML, clean up empty containers emulating SVG groups
// (#1960, #2393, #2697).
while (
parentToClean &&
parentToClean.div &&
parentToClean.div.childNodes.length === 0
) {
grandParent = parentToClean.parentGroup;
wrapper.safeRemoveChild(parentToClean.div);
delete parentToClean.div;
parentToClean = grandParent;
}
// remove from alignObjects
if (wrapper.alignTo) {
erase(renderer.alignedObjects, wrapper);
}
objectEach(wrapper, function (val, key) {
delete wrapper[key];
});
return null;
},
/**
* Add a shadow to the element. Must be called after the element is added to
* the DOM. In styled mode, this method is not used, instead use `defs` and
* filters.
*
* @example
* renderer.rect(10, 100, 100, 100)
* .attr({ fill: 'red' })
* .shadow(true);
*
* @function Highcharts.SVGElement#shadow
*
* @param {boolean|Highcharts.ShadowOptionsObject} shadowOptions
* The shadow options. If `true`, the default options are applied. If
* `false`, the current shadow will be removed.
*
* @param {Highcharts.SVGElement} [group]
* The SVG group element where the shadows will be applied. The
* default is to add it to the same parent as the current element.
* Internally, this is ised for pie slices, where all the shadows are
* added to an element behind all the slices.
*
* @param {boolean} [cutOff]
* Used internally for column shadows.
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
shadow: function (shadowOptions, group, cutOff) {
var shadows = [],
i,
shadow,
element = this.element,
strokeWidth,
shadowWidth,
shadowElementOpacity,
// compensate for inverted plot area
transform;
if (!shadowOptions) {
this.destroyShadows();
} else if (!this.shadows) {
shadowWidth = pick(shadowOptions.width, 3);
shadowElementOpacity = (shadowOptions.opacity || 0.15) /
shadowWidth;
transform = this.parentInverted ?
'(-1,-1)' :
'(' + pick(shadowOptions.offsetX, 1) + ', ' +
pick(shadowOptions.offsetY, 1) + ')';
for (i = 1; i <= shadowWidth; i++) {
shadow = element.cloneNode(0);
strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
attr(shadow, {
'stroke':
shadowOptions.color || '#000000',
'stroke-opacity': shadowElementOpacity * i,
'stroke-width': strokeWidth,
'transform': 'translate' + transform,
'fill': 'none'
});
shadow.setAttribute(
'class',
(shadow.getAttribute('class') || '') + ' highcharts-shadow'
);
if (cutOff) {
attr(
shadow,
'height',
Math.max(attr(shadow, 'height') - strokeWidth, 0)
);
shadow.cutHeight = strokeWidth;
}
if (group) {
group.element.appendChild(shadow);
} else if (element.parentNode) {
element.parentNode.insertBefore(shadow, element);
}
shadows.push(shadow);
}
this.shadows = shadows;
}
return this;
},
/**
* Destroy shadows on the element.
*
* @private
* @function Highcharts.SVGElement#destroyShadows
*/
destroyShadows: function () {
(this.shadows || []).forEach(function (shadow) {
this.safeRemoveChild(shadow);
}, this);
this.shadows = undefined;
},
/**
* @private
* @function Highcharts.SVGElement#xGetter
*
* @param {string} key
*
* @return {number|string|null}
*/
xGetter: function (key) {
if (this.element.nodeName === 'circle') {
if (key === 'x') {
key = 'cx';
} else if (key === 'y') {
key = 'cy';
}
}
return this._defaultGetter(key);
},
/**
* Get the current value of an attribute or pseudo attribute,
* used mainly for animation. Called internally from
* the {@link Highcharts.SVGRenderer#attr} function.
*
* @private
* @function Highcharts.SVGElement#_defaultGetter
*
* @param {string} key
* Property key.
*
* @return {number|string|null}
* Property value.
*/
_defaultGetter: function (key) {
var ret = pick(
this[key + 'Value'], // align getter
this[key],
this.element ? this.element.getAttribute(key) : null,
0
);
if (/^[\-0-9\.]+$/.test(ret)) { // is numerical
ret = parseFloat(ret);
}
return ret;
},
/**
* @private
* @function Highcharts.SVGElement#dSettter
*
* @param {number|string|Highcharts.SVGPathArray} value
*
* @param {string} key
*
* @param {Highcharts.SVGDOMElement} element
*/
dSetter: function (value, key, element) {
if (value && value.join) { // join path
value = value.join(' ');
}
if (/(NaN| {2}|^$)/.test(value)) {
value = 'M 0 0';
}
// Check for cache before resetting. Resetting causes disturbance in the
// DOM, causing flickering in some cases in Edge/IE (#6747). Also
// possible performance gain.
if (this[key] !== value) {
element.setAttribute(key, value);
this[key] = value;
}
},
/**
* @private
* @function Highcharts.SVGElement#dashstyleSetter
*
* @param {string} value
*/
dashstyleSetter: function (value) {
var i,
strokeWidth = this['stroke-width'];
// If "inherit", like maps in IE, assume 1 (#4981). With HC5 and the new
// strokeWidth function, we should be able to use that instead.
if (strokeWidth === 'inherit') {
strokeWidth = 1;
}
value = value && value.toLowerCase();
if (value) {
value = value
.replace('shortdashdotdot', '3,1,1,1,1,1,')
.replace('shortdashdot', '3,1,1,1')
.replace('shortdot', '1,1,')
.replace('shortdash', '3,1,')
.replace('longdash', '8,3,')
.replace(/dot/g, '1,3,')
.replace('dash', '4,3,')
.replace(/,$/, '')
.split(','); // ending comma
i = value.length;
while (i--) {
value[i] = pInt(value[i]) * strokeWidth;
}
value = value.join(',')
.replace(/NaN/g, 'none'); // #3226
this.element.setAttribute('stroke-dasharray', value);
}
},
/**
* @private
* @function Highcharts.SVGElement#alignSetter
*
* @param {"start"|"middle"|"end"} value
*/
alignSetter: function (value) {
var convert = { left: 'start', center: 'middle', right: 'end' };
this.alignValue = value;
this.element.setAttribute('text-anchor', convert[value]);
},
/**
* @private
* @function Highcharts.SVGElement#opacitySetter
*
* @param {string} value
*
* @param {string} key
*
* @param {Highcharts.SVGDOMElement} element
*/
opacitySetter: function (value, key, element) {
this[key] = value;
element.setAttribute(key, value);
},
/**
* @private
* @function Highcharts.SVGElement#titleSetter
*
* @param {string} value
*/
titleSetter: function (value) {
var titleNode = this.element.getElementsByTagName('title')[0];
if (!titleNode) {
titleNode = doc.createElementNS(this.SVG_NS, 'title');
this.element.appendChild(titleNode);
}
// Remove text content if it exists
if (titleNode.firstChild) {
titleNode.removeChild(titleNode.firstChild);
}
titleNode.appendChild(
doc.createTextNode(
// #3276, #3895
(String(pick(value), ''))
.replace(/<[^>]*>/g, '')
.replace(/</g, '<')
.replace(/>/g, '>')
)
);
},
/**
* @private
* @function Highcharts.SVGElement#textSetter
*
* @param {string} value
*/
textSetter: function (value) {
if (value !== this.textStr) {
// Delete bBox memo when the text changes
delete this.bBox;
this.textStr = value;
if (this.added) {
this.renderer.buildText(this);
}
}
},
/**
* @private
* @function Highcharts.SVGElement#fillSetter
*
* @param {Highcharts.Color|Highcharts.ColorString} value
*
* @param {string} key
*
* @param {Highcharts.SVGDOMElement} element
*/
fillSetter: function (value, key, element) {
if (typeof value === 'string') {
element.setAttribute(key, value);
} else if (value) {
this.complexColor(value, key, element);
}
},
/**
* @private
* @function Highcharts.SVGElement#visibilitySetter
*
* @param {string} value
*
* @param {string} key
*
* @param {Highcharts.SVGDOMElement} element
*/
visibilitySetter: function (value, key, element) {
// IE9-11 doesn't handle visibilty:inherit well, so we remove the
// attribute instead (#2881, #3909)
if (value === 'inherit') {
element.removeAttribute(key);
} else if (this[key] !== value) { // #6747
element.setAttribute(key, value);
}
this[key] = value;
},
/**
* @private
* @function Highcharts.SVGElement#zIndexSetter
*
* @param {string} value
*
* @param {string} key
*
* @return {boolean}
*/
zIndexSetter: function (value, key) {
var renderer = this.renderer,
parentGroup = this.parentGroup,
parentWrapper = parentGroup || renderer,
parentNode = parentWrapper.element || renderer.box,
childNodes,
otherElement,
otherZIndex,
element = this.element,
inserted,
undefinedOtherZIndex,
svgParent = parentNode === renderer.box,
run = this.added,
i;
if (defined(value)) {
// So we can read it for other elements in the group
element.setAttribute('data-z-index', value);
value = +value;
if (this[key] === value) { // Only update when needed (#3865)
run = false;
}
} else if (defined(this[key])) {
element.removeAttribute('data-z-index');
}
this[key] = value;
// Insert according to this and other elements' zIndex. Before .add() is
// called, nothing is done. Then on add, or by later calls to
// zIndexSetter, the node is placed on the right place in the DOM.
if (run) {
value = this.zIndex;
if (value && parentGroup) {
parentGroup.handleZ = true;
}
childNodes = parentNode.childNodes;
for (i = childNodes.length - 1; i >= 0 && !inserted; i--) {
otherElement = childNodes[i];
otherZIndex = otherElement.getAttribute('data-z-index');
undefinedOtherZIndex = !defined(otherZIndex);
if (otherElement !== element) {
if (
// Negative zIndex versus no zIndex:
// On all levels except the highest. If the parent is
// <svg>, then we don't want to put items before <desc>
// or <defs>
(value < 0 && undefinedOtherZIndex && !svgParent && !i)
) {
parentNode.insertBefore(element, childNodes[i]);
inserted = true;
} else if (
// Insert after the first element with a lower zIndex
pInt(otherZIndex) <= value ||
// If negative zIndex, add this before first undefined
// zIndex element
(
undefinedOtherZIndex &&
(!defined(value) || value >= 0)
)
) {
parentNode.insertBefore(
element,
childNodes[i + 1] || null // null for oldIE export
);
inserted = true;
}
}
}
if (!inserted) {
parentNode.insertBefore(
element,
childNodes[svgParent ? 3 : 0] || null // null for oldIE
);
inserted = true;
}
}
return inserted;
},
/**
* @private
* @function Highcharts.SVGElement#_defaultSetter
*
* @param {string} value
*
* @param {string} key
*
* @param {Highcharts.SVGDOMElement} element
*/
_defaultSetter: function (value, key, element) {
element.setAttribute(key, value);
}
});
// Some shared setters and getters
SVGElement.prototype.yGetter =
SVGElement.prototype.xGetter;
SVGElement.prototype.translateXSetter =
SVGElement.prototype.translateYSetter =
SVGElement.prototype.rotationSetter =
SVGElement.prototype.verticalAlignSetter =
SVGElement.prototype.rotationOriginXSetter =
SVGElement.prototype.rotationOriginYSetter =
SVGElement.prototype.scaleXSetter =
SVGElement.prototype.scaleYSetter =
SVGElement.prototype.matrixSetter = function (value, key) {
this[key] = value;
this.doTransform = true;
};
// WebKit and Batik have problems with a stroke-width of zero, so in this case
// we remove the stroke attribute altogether. #1270, #1369, #3065, #3072.
SVGElement.prototype['stroke-widthSetter'] =
/**
* @private
* @function Highcharts.SVGElement#strokeSetter
*
* @param {number|string} value
*
* @param {string} key
*
* @param {Highcharts.SVGDOMElement} element
*/
SVGElement.prototype.strokeSetter = function (value, key, element) {
this[key] = value;
// Only apply the stroke attribute if the stroke width is defined and larger
// than 0
if (this.stroke && this['stroke-width']) {
// Use prototype as instance may be overridden
SVGElement.prototype.fillSetter.call(
this,
this.stroke,
'stroke',
element
);
element.setAttribute('stroke-width', this['stroke-width']);
this.hasStroke = true;
} else if (key === 'stroke-width' && value === 0 && this.hasStroke) {
element.removeAttribute('stroke');
this.hasStroke = false;
}
};
/**
* Allows direct access to the Highcharts rendering layer in order to draw
* primitive shapes like circles, rectangles, paths or text directly on a chart,
* or independent from any chart. The SVGRenderer represents a wrapper object
* for SVG in modern browsers. Through the VMLRenderer, part of the `oldie.js`
* module, it also brings vector graphics to IE <= 8.
*
* An existing chart's renderer can be accessed through {@link Chart.renderer}.
* The renderer can also be used completely decoupled from a chart.
*
* @sample highcharts/members/renderer-on-chart
* Annotating a chart programmatically.
* @sample highcharts/members/renderer-basic
* Independent SVG drawing.
*
* @example
* // Use directly without a chart object.
* var renderer = new Highcharts.Renderer(parentNode, 600, 400);
*
* @class
* @name Highcharts.SVGRenderer
*
* @param {Highcharts.HTMLDOMElement} container
* Where to put the SVG in the web page.
*
* @param {number} width
* The width of the SVG.
*
* @param {number} height
* The height of the SVG.
*
* @param {boolean} [forExport=false]
* Whether the rendered content is intended for export.
*
* @param {boolean} [allowHTML=true]
* Whether the renderer is allowed to include HTML text, which will be
* projected on top of the SVG.
*/
SVGRenderer = H.SVGRenderer = function () {
this.init.apply(this, arguments);
};
extend(SVGRenderer.prototype, /** @lends Highcharts.SVGRenderer.prototype */ {
/**
* A pointer to the renderer's associated Element class. The VMLRenderer
* will have a pointer to VMLElement here.
*
* @name Highcharts.SVGRenderer#Element
* @type {Highcharts.SVGElement}
*/
Element: SVGElement,
SVG_NS: SVG_NS,
/**
* Initialize the SVGRenderer. Overridable initiator function that takes
* the same parameters as the constructor.
*
* @function Highcharts.SVGRenderer#init
*
* @param {Highcharts.HTMLDOMElement} container
* Where to put the SVG in the web page.
*
* @param {number} width
* The width of the SVG.
*
* @param {number} height
* The height of the SVG.
*
* @param {boolean} [forExport=false]
* Whether the rendered content is intended for export.
*
* @param {boolean} [allowHTML=true]
* Whether the renderer is allowed to include HTML text, which will
* be projected on top of the SVG.
*
* @param {boolean} [styledMode=false]
* Whether the renderer belongs to a chart that is in styled mode.
* If it does, it will avoid setting presentational attributes in
* some cases, but not when set explicitly through `.attr` and `.css`
* etc.
*
* @return {void}
*/
init: function (
container,
width,
height,
style,
forExport,
allowHTML,
styledMode
) {
var renderer = this,
boxWrapper,
element,
desc;
boxWrapper = renderer.createElement('svg')
.attr({
'version': '1.1',
'class': 'highcharts-root'
});
if (!styledMode) {
boxWrapper.css(this.getStyle(style));
}
element = boxWrapper.element;
container.appendChild(element);
// Always use ltr on the container, otherwise text-anchor will be
// flipped and text appear outside labels, buttons, tooltip etc (#3482)
attr(container, 'dir', 'ltr');
// For browsers other than IE, add the namespace attribute (#1978)
if (container.innerHTML.indexOf('xmlns') === -1) {
attr(element, 'xmlns', this.SVG_NS);
}
// object properties
renderer.isSVG = true;
/**
* The root `svg` node of the renderer.
*
* @name Highcharts.SVGRenderer#box
* @type {Highcharts.SVGDOMElement}
*/
this.box = element;
/**
* The wrapper for the root `svg` node of the renderer.
*
* @name Highcharts.SVGRenderer#boxWrapper
* @type {Highcharts.SVGElement}
*/
this.boxWrapper = boxWrapper;
renderer.alignedObjects = [];
/**
* Page url used for internal references.
*
* @private
* @name Highcharts.SVGRenderer#url
* @type {string}
*/
// #24, #672, #1070
this.url = (
(isFirefox || isWebKit) &&
doc.getElementsByTagName('base').length
) ?
win.location.href
.split('#')[0] // remove the hash
.replace(/<[^>]*>/g, '') // wing cut HTML
// escape parantheses and quotes
.replace(/([\('\)])/g, '\\$1')
// replace spaces (needed for Safari only)
.replace(/ /g, '%20') :
'';
// Add description
desc = this.createElement('desc').add();
desc.element.appendChild(
doc.createTextNode('Created with @product.name@ @product.version@')
);
/**
* A pointer to the `defs` node of the root SVG.
*
* @name Highcharts.SVGRenderer#defs
* @type {Highcharts.SVGElement}
*/
renderer.defs = this.createElement('defs').add();
renderer.allowHTML = allowHTML;
renderer.forExport = forExport;
renderer.styledMode = styledMode;
renderer.gradients = {}; // Object where gradient SvgElements are stored
renderer.cache = {}; // Cache for numerical bounding boxes
renderer.cacheKeys = [];
renderer.imgCount = 0;
renderer.setSize(width, height, false);
// Issue 110 workaround:
// In Firefox, if a div is positioned by percentage, its pixel position
// may land between pixels. The container itself doesn't display this,
// but an SVG element inside this container will be drawn at subpixel
// precision. In order to draw sharp lines, this must be compensated
// for. This doesn't seem to work inside iframes though (like in
// jsFiddle).
var subPixelFix, rect;
if (isFirefox && container.getBoundingClientRect) {
subPixelFix = function () {
css(container, { left: 0, top: 0 });
rect = container.getBoundingClientRect();
css(container, {
left: (Math.ceil(rect.left) - rect.left) + 'px',
top: (Math.ceil(rect.top) - rect.top) + 'px'
});
};
// run the fix now
subPixelFix();
// run it on resize
renderer.unSubPixelFix = addEvent(win, 'resize', subPixelFix);
}
},
/**
* General method for adding a definition to the SVG `defs` tag. Can be used
* for gradients, fills, filters etc. Styled mode only. A hook for adding
* general definitions to the SVG's defs tag. Definitions can be referenced
* from the CSS by its `id`. Read more in
* [gradients, shadows and patterns](https://www.highcharts.com/docs/chart-design-and-style/gradients-shadows-and-patterns).
* Styled mode only.
*
* @function Highcharts.SVGRenderer#definition
*
* @param {Highcharts.SVGDefinitionObject} def
* A serialized form of an SVG definition, including children.
*
* @return {Highcharts.SVGElement}
* The inserted node.
*/
definition: function (def) {
var ren = this;
function recurse(config, parent) {
var ret;
splat(config).forEach(function (item) {
var node = ren.createElement(item.tagName),
attr = {};
// Set attributes
objectEach(item, function (val, key) {
if (
key !== 'tagName' &&
key !== 'children' &&
key !== 'textContent'
) {
attr[key] = val;
}
});
node.attr(attr);
// Add to the tree
node.add(parent || ren.defs);
// Add text content
if (item.textContent) {
node.element.appendChild(
doc.createTextNode(item.textContent)
);
}
// Recurse
recurse(item.children || [], node);
ret = node;
});
// Return last node added (on top level it's the only one)
return ret;
}
return recurse(def);
},
/**
* Get the global style setting for the renderer.
*
* @private
* @function Highcharts.SVGRenderer#getStyle
*
* @param {Highcharts.CSSObject} style
* Style settings.
*
* @return {Highcharts.CSSObject}
* The style settings mixed with defaults.
*/
getStyle: function (style) {
this.style = extend({
fontFamily: '"Lucida Grande", "Lucida Sans Unicode", ' +
'Arial, Helvetica, sans-serif',
fontSize: '12px'
}, style);
return this.style;
},
/**
* Apply the global style on the renderer, mixed with the default styles.
*
* @function Highcharts.SVGRenderer#setStyle
*
* @param {Highcharts.CSSObject} style
* CSS to apply.
*/
setStyle: function (style) {
this.boxWrapper.css(this.getStyle(style));
},
/**
* Detect whether the renderer is hidden. This happens when one of the
* parent elements has `display: none`. Used internally to detect when we
* needto render preliminarily in another div to get the text bounding boxes
* right.
*
* @function Highcharts.SVGRenderer#isHidden
*
* @return {boolean}
* True if it is hidden.
*/
isHidden: function () { // #608
return !this.boxWrapper.getBBox().width;
},
/**
* Destroys the renderer and its allocated members.
*
* @function Highcharts.SVGRenderer#destroy
*/
destroy: function () {
var renderer = this,
rendererDefs = renderer.defs;
renderer.box = null;
renderer.boxWrapper = renderer.boxWrapper.destroy();
// Call destroy on all gradient elements
destroyObjectProperties(renderer.gradients || {});
renderer.gradients = null;
// Defs are null in VMLRenderer
// Otherwise, destroy them here.
if (rendererDefs) {
renderer.defs = rendererDefs.destroy();
}
// Remove sub pixel fix handler (#982)
if (renderer.unSubPixelFix) {
renderer.unSubPixelFix();
}
renderer.alignedObjects = null;
return null;
},
/**
* Create a wrapper for an SVG element. Serves as a factory for
* {@link SVGElement}, but this function is itself mostly called from
* primitive factories like {@link SVGRenderer#path}, {@link
* SVGRenderer#rect} or {@link SVGRenderer#text}.
*
* @function Highcharts.SVGRenderer#createElement
*
* @param {string} nodeName
* The node name, for example `rect`, `g` etc.
*
* @return {Highcharts.SVGElement}
* The generated SVGElement.
*/
createElement: function (nodeName) {
var wrapper = new this.Element();
wrapper.init(this, nodeName);
return wrapper;
},
/**
* Dummy function for plugins, called every time the renderer is updated.
* Prior to Highcharts 5, this was used for the canvg renderer.
*
* @deprecated
* @function Highcharts.SVGRenderer#draw
*/
draw: noop,
/**
* Get converted radial gradient attributes according to the radial
* reference. Used internally from the {@link SVGElement#colorGradient}
* function.
*
* @private
* @function Highcharts.SVGRenderer#getRadialAttr
*
* @param {Array<number>} radialReference
*
* @param {Highcharts.SVGAttributes} gradAttr
*
* @return {Highcharts.SVGAttributes}
*/
getRadialAttr: function (radialReference, gradAttr) {
return {
cx: (radialReference[0] - radialReference[2] / 2) +
gradAttr.cx * radialReference[2],
cy: (radialReference[1] - radialReference[2] / 2) +
gradAttr.cy * radialReference[2],
r: gradAttr.r * radialReference[2]
};
},
/**
* Truncate the text node contents to a given length. Used when the css
* width is set. If the `textOverflow` is `ellipsis`, the text is truncated
* character by character to the given length. If not, the text is
* word-wrapped line by line.
*
* @private
* @function Highcharts.SVGRenderer#truncate
*
* @param {Highcharts.SVGElement} wrapper
*
* @param {Highcharts.SVGDOMElement} tspan
*
* @param {string} text
*
* @param {Array.<string>} words
*
* @param {number} width
*
* @param {Function} getString
*
* @return {boolean}
* True if tspan is too long.
*/
truncate: function (
wrapper,
tspan,
text,
words,
startAt,
width,
getString
) {
var renderer = this,
rotation = wrapper.rotation,
str,
// Word wrap can not be truncated to shorter than one word, ellipsis
// text can be completely blank.
minIndex = words ? 1 : 0,
maxIndex = (text || words).length,
currentIndex = maxIndex,
// Cache the lengths to avoid checking the same twice
lengths = [],
updateTSpan = function (s) {
if (tspan.firstChild) {
tspan.removeChild(tspan.firstChild);
}
if (s) {
tspan.appendChild(doc.createTextNode(s));
}
},
getSubStringLength = function (charEnd, concatenatedEnd) {
// charEnd is useed when finding the character-by-character
// break for ellipsis, concatenatedEnd is used for word-by-word
// break for word wrapping.
var end = concatenatedEnd || charEnd;
if (lengths[end] === undefined) {
// Modern browsers
if (tspan.getSubStringLength) {
// Fails with DOM exception on unit-tests/legend/members
// of unknown reason. Desired width is 0, text content
// is "5" and end is 1.
try {
lengths[end] = startAt + tspan.getSubStringLength(
0,
words ? end + 1 : end
);
} catch (e) {}
// Legacy
} else if (renderer.getSpanWidth) { // #9058 jsdom
updateTSpan(getString(text || words, charEnd));
lengths[end] = startAt +
renderer.getSpanWidth(wrapper, tspan);
}
}
return lengths[end];
},
actualWidth,
truncated;
wrapper.rotation = 0; // discard rotation when computing box
actualWidth = getSubStringLength(tspan.textContent.length);
truncated = startAt + actualWidth > width;
if (truncated) {
// Do a binary search for the index where to truncate the text
while (minIndex <= maxIndex) {
currentIndex = Math.ceil((minIndex + maxIndex) / 2);
// When checking words for word-wrap, we need to build the
// string and measure the subStringLength at the concatenated
// word length.
if (words) {
str = getString(words, currentIndex);
}
actualWidth = getSubStringLength(
currentIndex,
str && str.length - 1
);
if (minIndex === maxIndex) {
// Complete
minIndex = maxIndex + 1;
} else if (actualWidth > width) {
// Too large. Set max index to current.
maxIndex = currentIndex - 1;
} else {
// Within width. Set min index to current.
minIndex = currentIndex;
}
}
// If max index was 0 it means the shortest possible text was also
// too large. For ellipsis that means only the ellipsis, while for
// word wrap it means the whole first word.
if (maxIndex === 0) {
// Remove ellipsis
updateTSpan('');
// If the new text length is one less than the original, we don't
// need the ellipsis
} else if (!(text && maxIndex === text.length - 1)) {
updateTSpan(str || getString(text || words, currentIndex));
}
}
// When doing line wrapping, prepare for the next line by removing the
// items from this line.
if (words) {
words.splice(0, currentIndex);
}
wrapper.actualWidth = actualWidth;
wrapper.rotation = rotation; // Apply rotation again.
return truncated;
},
/**
* A collection of characters mapped to HTML entities. When `useHTML` on an
* element is true, these entities will be rendered correctly by HTML. In
* the SVG pseudo-HTML, they need to be unescaped back to simple characters,
* so for example `<` will render as `<`.
*
* @example
* // Add support for unescaping quotes
* Highcharts.SVGRenderer.prototype.escapes['"'] = '"';
*
* @name Highcharts.SVGRenderer#escapes
* @type {Highcharts.Dictionary<string>}
*/
escapes: {
'&': '&',
'<': '<',
'>': '>',
"'": ''', // eslint-disable-line quotes
'"': '"'
},
/**
* Parse a simple HTML string into SVG tspans. Called internally when text
* is set on an SVGElement. The function supports a subset of HTML tags, CSS
* text features like `width`, `text-overflow`, `white-space`, and also
* attributes like `href` and `style`.
*
* @private
* @function Highcharts.SVGRenderer#buildText
*
* @param {Highcharts.SVGElement} wrapper
* The parent SVGElement.
*/
buildText: function (wrapper) {
var textNode = wrapper.element,
renderer = this,
forExport = renderer.forExport,
textStr = pick(wrapper.textStr, '').toString(),
hasMarkup = textStr.indexOf('<') !== -1,
lines,
childNodes = textNode.childNodes,
truncated,
parentX = attr(textNode, 'x'),
textStyles = wrapper.styles,
width = wrapper.textWidth,
textLineHeight = textStyles && textStyles.lineHeight,
textOutline = textStyles && textStyles.textOutline,
ellipsis = textStyles && textStyles.textOverflow === 'ellipsis',
noWrap = textStyles && textStyles.whiteSpace === 'nowrap',
fontSize = textStyles && textStyles.fontSize,
textCache,
isSubsequentLine,
i = childNodes.length,
tempParent = width && !wrapper.added && this.box,
getLineHeight = function (tspan) {
var fontSizeStyle;
if (!renderer.styledMode) {
fontSizeStyle =
/(px|em)$/.test(tspan && tspan.style.fontSize) ?
tspan.style.fontSize :
(fontSize || renderer.style.fontSize || 12);
}
return textLineHeight ?
pInt(textLineHeight) :
renderer.fontMetrics(
fontSizeStyle,
// Get the computed size from parent if not explicit
tspan.getAttribute('style') ? tspan : textNode
).h;
},
unescapeEntities = function (inputStr, except) {
objectEach(renderer.escapes, function (value, key) {
if (!except || except.indexOf(value) === -1) {
inputStr = inputStr.toString().replace(
new RegExp(value, 'g'), // eslint-disable-line security/detect-non-literal-regexp
key
);
}
});
return inputStr;
},
parseAttribute = function (s, attr) {
var start,
delimiter;
start = s.indexOf('<');
s = s.substring(start, s.indexOf('>') - start);
start = s.indexOf(attr + '=');
if (start !== -1) {
start = start + attr.length + 1;
delimiter = s.charAt(start);
if (delimiter === '"' || delimiter === "'") { // eslint-disable-line quotes
s = s.substring(start + 1);
return s.substring(0, s.indexOf(delimiter));
}
}
};
// The buildText code is quite heavy, so if we're not changing something
// that affects the text, skip it (#6113).
textCache = [
textStr,
ellipsis,
noWrap,
textLineHeight,
textOutline,
fontSize,
width
].join(',');
if (textCache === wrapper.textCache) {
return;
}
wrapper.textCache = textCache;
// Remove old text
while (i--) {
textNode.removeChild(childNodes[i]);
}
// Skip tspans, add text directly to text node. The forceTSpan is a hook
// used in text outline hack.
if (
!hasMarkup &&
!textOutline &&
!ellipsis &&
!width &&
textStr.indexOf(' ') === -1
) {
textNode.appendChild(doc.createTextNode(unescapeEntities(textStr)));
// Complex strings, add more logic
} else {
if (tempParent) {
// attach it to the DOM to read offset width
tempParent.appendChild(textNode);
}
if (hasMarkup) {
lines = renderer.styledMode ? (
textStr.replace(
/<(b|strong)>/g,
'<span class="highcharts-strong">'
)
.replace(
/<(i|em)>/g,
'<span class="highcharts-emphasized">'
)
) : (
textStr
.replace(
/<(b|strong)>/g,
'<span style="font-weight:bold">'
)
.replace(
/<(i|em)>/g,
'<span style="font-style:italic">'
)
);
lines = lines
.replace(/<a/g, '<span')
.replace(/<\/(b|strong|i|em|a)>/g, '</span>')
.split(/<br.*?>/g);
} else {
lines = [textStr];
}
// Trim empty lines (#5261)
lines = lines.filter(function (line) {
return line !== '';
});
// build the lines
lines.forEach(function buildTextLines(line, lineNo) {
var spans,
spanNo = 0,
lineLength = 0;
line = line
// Trim to prevent useless/costly process on the spaces
// (#5258)
.replace(/^\s+|\s+$/g, '')
.replace(/<span/g, '|||<span')
.replace(/<\/span>/g, '</span>|||');
spans = line.split('|||');
spans.forEach(function buildTextSpans(span) {
if (span !== '' || spans.length === 1) {
var attributes = {},
tspan = doc.createElementNS(
renderer.SVG_NS,
'tspan'
),
classAttribute,
styleAttribute, // #390
hrefAttribute;
classAttribute = parseAttribute(span, 'class');
if (classAttribute) {
attr(tspan, 'class', classAttribute);
}
styleAttribute = parseAttribute(span, 'style');
if (styleAttribute) {
styleAttribute = styleAttribute.replace(
/(;| |^)color([ :])/,
'$1fill$2'
);
attr(tspan, 'style', styleAttribute);
}
// Not for export - #1529
hrefAttribute = parseAttribute(span, 'href');
if (hrefAttribute && !forExport) {
attr(
tspan,
'onclick',
'location.href=\"' + hrefAttribute + '\"'
);
attr(tspan, 'class', 'highcharts-anchor');
if (!renderer.styledMode) {
css(tspan, { cursor: 'pointer' });
}
}
// Strip away unsupported HTML tags (#7126)
span = unescapeEntities(
span.replace(/<[a-zA-Z\/](.|\n)*?>/g, '') || ' '
);
// Nested tags aren't supported, and cause crash in
// Safari (#1596)
if (span !== ' ') {
// add the text node
tspan.appendChild(doc.createTextNode(span));
// First span in a line, align it to the left
if (!spanNo) {
if (lineNo && parentX !== null) {
attributes.x = parentX;
}
} else {
attributes.dx = 0; // #16
}
// add attributes
attr(tspan, attributes);
// Append it
textNode.appendChild(tspan);
// first span on subsequent line, add the line
// height
if (!spanNo && isSubsequentLine) {
// allow getting the right offset height in
// exporting in IE
if (!svg && forExport) {
css(tspan, { display: 'block' });
}
// Set the line height based on the font size of
// either the text element or the tspan element
attr(
tspan,
'dy',
getLineHeight(tspan)
);
}
// Check width and apply soft breaks or ellipsis
if (width) {
var words = span.replace(
/([^\^])-/g,
'$1- '
).split(' '), // #1273
hasWhiteSpace = !noWrap && (
spans.length > 1 ||
lineNo ||
words.length > 1
),
wrapLineNo = 0,
dy = getLineHeight(tspan);
if (ellipsis) {
truncated = renderer.truncate(
wrapper,
tspan,
span,
undefined,
0,
// Target width
Math.max(
0,
// Substract the font face to make
// room for the ellipsis itself
width - parseInt(fontSize || 12, 10)
),
// Build the text to test for
function (text, currentIndex) {
return text.substring(
0,
currentIndex
) + '\u2026';
}
);
} else if (hasWhiteSpace) {
while (words.length) {
// For subsequent lines, create tspans
// with the same style attributes as the
// parent text node.
if (
words.length &&
!noWrap &&
wrapLineNo > 0
) {
tspan = doc.createElementNS(
SVG_NS,
'tspan'
);
attr(tspan, {
dy: dy,
x: parentX
});
if (styleAttribute) { // #390
attr(
tspan,
'style',
styleAttribute
);
}
// Start by appending the full
// remaining text
tspan.appendChild(
doc.createTextNode(
words.join(' ')
.replace(/- /g, '-')
)
);
textNode.appendChild(tspan);
}
// For each line, truncate the remaining
// words into the line length.
renderer.truncate(
wrapper,
tspan,
null,
words,
wrapLineNo === 0 ? lineLength : 0,
width,
// Build the text to test for
function (text, currentIndex) {
return words
.slice(0, currentIndex)
.join(' ')
.replace(/- /g, '-');
}
);
lineLength = wrapper.actualWidth;
wrapLineNo++;
}
}
}
spanNo++;
}
}
});
// To avoid beginning lines that doesn't add to the textNode
// (#6144)
isSubsequentLine = (
isSubsequentLine ||
textNode.childNodes.length
);
});
if (ellipsis && truncated) {
wrapper.attr(
'title',
unescapeEntities(wrapper.textStr, ['<', '>']) // #7179
);
}
if (tempParent) {
tempParent.removeChild(textNode);
}
// Apply the text outline
if (textOutline && wrapper.applyTextOutline) {
wrapper.applyTextOutline(textOutline);
}
}
},
/**
* Returns white for dark colors and black for bright colors.
*
* @function Highcharts.SVGRenderer#getContrast
*
* @param {Highcharts.ColorString} rgba
* The color to get the contrast for.
*
* @return {string}
* The contrast color, either `#000000` or `#FFFFFF`.
*/
getContrast: function (rgba) {
rgba = color(rgba).rgba;
// The threshold may be discussed. Here's a proposal for adding
// different weight to the color channels (#6216)
rgba[0] *= 1; // red
rgba[1] *= 1.2; // green
rgba[2] *= 0.5; // blue
return rgba[0] + rgba[1] + rgba[2] > 1.8 * 255 ? '#000000' : '#FFFFFF';
},
/**
* Create a button with preset states.
*
* @function Highcharts.SVGRenderer#button
*
* @param {string} text
* The text or HTML to draw.
*
* @param {number} x
* The x position of the button's left side.
*
* @param {number} y
* The y position of the button's top side.
*
* @param {Function} callback
* The function to execute on button click or touch.
*
* @param {Highcharts.SVGAttributes} [normalState]
* SVG attributes for the normal state.
*
* @param {Highcharts.SVGAttributes} [hoverState]
* SVG attributes for the hover state.
*
* @param {Highcharts.SVGAttributes} [pressedState]
* SVG attributes for the pressed state.
*
* @param {Highcharts.SVGAttributes} [disabledState]
* SVG attributes for the disabled state.
*
* @param {Highcharts.SymbolKey} [shape=rect]
* The shape type.
*
* @return {Highcharts.SVGElement}
* The button element.
*/
button: function (
text,
x,
y,
callback,
normalState,
hoverState,
pressedState,
disabledState,
shape
) {
var label = this.label(
text,
x,
y,
shape,
null,
null,
null,
null,
'button'
),
curState = 0,
styledMode = this.styledMode;
// Default, non-stylable attributes
label.attr(merge({
'padding': 8,
'r': 2
}, normalState));
if (!styledMode) {
// Presentational
var normalStyle,
hoverStyle,
pressedStyle,
disabledStyle;
// Normal state - prepare the attributes
normalState = merge({
fill: '#f7f7f7',
stroke: '#cccccc',
'stroke-width': 1,
style: {
color: '#333333',
cursor: 'pointer',
fontWeight: 'normal'
}
}, normalState);
normalStyle = normalState.style;
delete normalState.style;
// Hover state
hoverState = merge(normalState, {
fill: '#e6e6e6'
}, hoverState);
hoverStyle = hoverState.style;
delete hoverState.style;
// Pressed state
pressedState = merge(normalState, {
fill: '#e6ebf5',
style: {
color: '#000000',
fontWeight: 'bold'
}
}, pressedState);
pressedStyle = pressedState.style;
delete pressedState.style;
// Disabled state
disabledState = merge(normalState, {
style: {
color: '#cccccc'
}
}, disabledState);
disabledStyle = disabledState.style;
delete disabledState.style;
}
// Add the events. IE9 and IE10 need mouseover and mouseout to funciton
// (#667).
addEvent(label.element, isMS ? 'mouseover' : 'mouseenter', function () {
if (curState !== 3) {
label.setState(1);
}
});
addEvent(label.element, isMS ? 'mouseout' : 'mouseleave', function () {
if (curState !== 3) {
label.setState(curState);
}
});
label.setState = function (state) {
// Hover state is temporary, don't record it
if (state !== 1) {
label.state = curState = state;
}
// Update visuals
label.removeClass(
/highcharts-button-(normal|hover|pressed|disabled)/
)
.addClass(
'highcharts-button-' +
['normal', 'hover', 'pressed', 'disabled'][state || 0]
);
if (!styledMode) {
label.attr([
normalState,
hoverState,
pressedState,
disabledState
][state || 0])
.css([
normalStyle,
hoverStyle,
pressedStyle,
disabledStyle
][state || 0]);
}
};
// Presentational attributes
if (!styledMode) {
label
.attr(normalState)
.css(extend({ cursor: 'default' }, normalStyle));
}
return label
.on('click', function (e) {
if (curState !== 3) {
callback.call(label, e);
}
});
},
/**
* Make a straight line crisper by not spilling out to neighbour pixels.
*
* @function Highcharts.SVGRenderer#crispLine
*
* @param {Highcharts.SVGPathArray} points
* The original points on the format `['M', 0, 0, 'L', 100, 0]`.
*
* @param {number} width
* The width of the line.
*
* @return {Highcharts.SVGPathArray}
* The original points array, but modified to render crisply.
*/
crispLine: function (points, width) {
// normalize to a crisp line
if (points[1] === points[4]) {
// Substract due to #1129. Now bottom and left axis gridlines behave
// the same.
points[1] = points[4] = Math.round(points[1]) - (width % 2 / 2);
}
if (points[2] === points[5]) {
points[2] = points[5] = Math.round(points[2]) + (width % 2 / 2);
}
return points;
},
/**
* Draw a path, wraps the SVG `path` element.
*
* @sample highcharts/members/renderer-path-on-chart/
* Draw a path in a chart
* @sample highcharts/members/renderer-path/
* Draw a path independent from a chart
*
* @example
* var path = renderer.path(['M', 10, 10, 'L', 30, 30, 'z'])
* .attr({ stroke: '#ff00ff' })
* .add();
*
* @function Highcharts.SVGRenderer#path
*
* @param {Highcharts.SVGPathArray} [path]
* An SVG path definition in array form.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*
*//**
* Draw a path, wraps the SVG `path` element.
*
* @function Highcharts.SVGRenderer#path
*
* @param {Highcharts.SVGAttributes} [attribs]
* The initial attributes.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*/
path: function (path) {
var attribs = this.styledMode ? {} : {
fill: 'none'
};
if (isArray(path)) {
attribs.d = path;
} else if (isObject(path)) { // attributes
extend(attribs, path);
}
return this.createElement('path').attr(attribs);
},
/**
* Draw a circle, wraps the SVG `circle` element.
*
* @sample highcharts/members/renderer-circle/
* Drawing a circle
*
* @function Highcharts.SVGRenderer#circle
*
* @param {number} [x]
* The center x position.
*
* @param {number} [y]
* The center y position.
*
* @param {number} [r]
* The radius.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*//**
* Draw a circle, wraps the SVG `circle` element.
*
* @function Highcharts.SVGRenderer#circle
*
* @param {Highcharts.SVGAttributes} [attribs]
* The initial attributes.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*/
circle: function (x, y, r) {
var attribs = (
isObject(x) ?
x :
x === undefined ? {} : { x: x, y: y, r: r }
),
wrapper = this.createElement('circle');
// Setting x or y translates to cx and cy
wrapper.xSetter = wrapper.ySetter = function (value, key, element) {
element.setAttribute('c' + key, value);
};
return wrapper.attr(attribs);
},
/**
* Draw and return an arc.
*
* @sample highcharts/members/renderer-arc/
* Drawing an arc
*
* @function Highcharts.SVGRenderer#arc
*
* @param {number} [x=0]
* Center X position.
*
* @param {number} [y=0]
* Center Y position.
*
* @param {number} [r=0]
* The outer radius of the arc.
*
* @param {number} [innerR=0]
* Inner radius like used in donut charts.
*
* @param {number} [start=0]
* The starting angle of the arc in radians, where 0 is to the right
* and `-Math.PI/2` is up.
*
* @param {number} [end=0]
* The ending angle of the arc in radians, where 0 is to the right
* and `-Math.PI/2` is up.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*//**
* Draw and return an arc. Overloaded function that takes arguments object.
*
* @function Highcharts.SVGRenderer#arc
*
* @param {Highcharts.SVGAttributes} attribs
* Initial SVG attributes.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*/
arc: function (x, y, r, innerR, start, end) {
var arc,
options;
if (isObject(x)) {
options = x;
y = options.y;
r = options.r;
innerR = options.innerR;
start = options.start;
end = options.end;
x = options.x;
} else {
options = {
innerR: innerR,
start: start,
end: end
};
}
// Arcs are defined as symbols for the ability to set
// attributes in attr and animate
arc = this.symbol('arc', x, y, r, r, options);
arc.r = r; // #959
return arc;
},
/**
* Draw and return a rectangle.
*
* @function Highcharts.SVGRenderer#rect
*
* @param {number} [x]
* Left position.
*
* @param {number} [y]
* Top position.
*
* @param {number} [width]
* Width of the rectangle.
*
* @param {number} [height]
* Height of the rectangle.
*
* @param {number} [r]
* Border corner radius.
*
* @param {number} [strokeWidth]
* A stroke width can be supplied to allow crisp drawing.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*//**
* Draw and return a rectangle.
*
* @sample highcharts/members/renderer-rect-on-chart/
* Draw a rectangle in a chart
* @sample highcharts/members/renderer-rect/
* Draw a rectangle independent from a chart
*
* @function Highcharts.SVGRenderer#rect
*
* @param {Highcharts.SVGAttributes} [attributes]
* General SVG attributes for the rectangle.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*/
rect: function (x, y, width, height, r, strokeWidth) {
r = isObject(x) ? x.r : r;
var wrapper = this.createElement('rect'),
attribs = isObject(x) ? x : x === undefined ? {} : {
x: x,
y: y,
width: Math.max(width, 0),
height: Math.max(height, 0)
};
if (!this.styledMode) {
if (strokeWidth !== undefined) {
attribs.strokeWidth = strokeWidth;
attribs = wrapper.crisp(attribs);
}
attribs.fill = 'none';
}
if (r) {
attribs.r = r;
}
wrapper.rSetter = function (value, key, element) {
attr(element, {
rx: value,
ry: value
});
};
return wrapper.attr(attribs);
},
/**
* Resize the {@link SVGRenderer#box} and re-align all aligned child
* elements.
*
* @sample highcharts/members/renderer-g/
* Show and hide grouped objects
*
* @function Highcharts.SVGRenderer#setSize
*
* @param {number} width
* The new pixel width.
*
* @param {number} height
* The new pixel height.
*
* @param {boolean|Highcharts.AnimationOptionsObject} [animate=true]
* Whether and how to animate.
*/
setSize: function (width, height, animate) {
var renderer = this,
alignedObjects = renderer.alignedObjects,
i = alignedObjects.length;
renderer.width = width;
renderer.height = height;
renderer.boxWrapper.animate({
width: width,
height: height
}, {
step: function () {
this.attr({
viewBox: '0 0 ' + this.attr('width') + ' ' +
this.attr('height')
});
},
duration: pick(animate, true) ? undefined : 0
});
while (i--) {
alignedObjects[i].align();
}
},
/**
* Create and return an svg group element. Child
* {@link Highcharts.SVGElement} objects are added to the group by using the
* group as the first parameter in {@link Highcharts.SVGElement#add|add()}.
*
* @function Highcharts.SVGRenderer#g
*
* @param {string} [name]
* The group will be given a class name of `highcharts-{name}`. This
* can be used for styling and scripting.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*/
g: function (name) {
var elem = this.createElement('g');
return name ? elem.attr({ 'class': 'highcharts-' + name }) : elem;
},
/**
* Display an image.
*
* @sample highcharts/members/renderer-image-on-chart/
* Add an image in a chart
* @sample highcharts/members/renderer-image/
* Add an image independent of a chart
*
* @function Highcharts.SVGRenderer#image
*
* @param {string} src
* The image source.
*
* @param {number} [x]
* The X position.
*
* @param {number} [y]
* The Y position.
*
* @param {number} [width]
* The image width. If omitted, it defaults to the image file width.
*
* @param {number} [height]
* The image height. If omitted it defaults to the image file
* height.
*
* @param {Function} [onload]
* Event handler for image load.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*/
image: function (src, x, y, width, height, onload) {
var attribs = {
preserveAspectRatio: 'none'
},
elemWrapper,
dummy,
setSVGImageSource = function (el, src) {
// Set the href in the xlink namespace
if (el.setAttributeNS) {
el.setAttributeNS(
'http://www.w3.org/1999/xlink', 'href', src
);
} else {
// could be exporting in IE
// using href throws "not supported" in ie7 and under,
// requries regex shim to fix later
el.setAttribute('hc-svg-href', src);
}
},
onDummyLoad = function (e) {
setSVGImageSource(elemWrapper.element, src);
onload.call(elemWrapper, e);
};
// optional properties
if (arguments.length > 1) {
extend(attribs, {
x: x,
y: y,
width: width,
height: height
});
}
elemWrapper = this.createElement('image').attr(attribs);
// Add load event if supplied
if (onload) {
// We have to use a dummy HTML image since IE support for SVG image
// load events is very buggy. First set a transparent src, wait for
// dummy to load, and then add the real src to the SVG image.
setSVGImageSource(
elemWrapper.element,
'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' /* eslint-disable-line */
);
dummy = new win.Image();
addEvent(dummy, 'load', onDummyLoad);
dummy.src = src;
if (dummy.complete) {
onDummyLoad({});
}
} else {
setSVGImageSource(elemWrapper.element, src);
}
return elemWrapper;
},
/**
* Draw a symbol out of pre-defined shape paths from
* {@link SVGRenderer#symbols}.
* It is used in Highcharts for point makers, which cake a `symbol` option,
* and label and button backgrounds like in the tooltip and stock flags.
*
* @function Highcharts.SVGRenderer#symbol
*
* @param {symbol} symbol
* The symbol name.
*
* @param {number} x
* The X coordinate for the top left position.
*
* @param {number} y
* The Y coordinate for the top left position.
*
* @param {number} width
* The pixel width.
*
* @param {number} height
* The pixel height.
*
* @param {Highcharts.SymbolOptionsObject} [options]
* Additional options, depending on the actual symbol drawn.
*
* @return {Highcharts.SVGElement}
*/
symbol: function (symbol, x, y, width, height, options) {
var ren = this,
obj,
imageRegex = /^url\((.*?)\)$/,
isImage = imageRegex.test(symbol),
sym = !isImage && (this.symbols[symbol] ? symbol : 'circle'),
// get the symbol definition function
symbolFn = sym && this.symbols[sym],
// check if there's a path defined for this symbol
path = defined(x) && symbolFn && symbolFn.call(
this.symbols,
Math.round(x),
Math.round(y),
width,
height,
options
),
imageSrc,
centerImage;
if (symbolFn) {
obj = this.path(path);
if (!ren.styledMode) {
obj.attr('fill', 'none');
}
// expando properties for use in animate and attr
extend(obj, {
symbolName: sym,
x: x,
y: y,
width: width,
height: height
});
if (options) {
extend(obj, options);
}
// Image symbols
} else if (isImage) {
imageSrc = symbol.match(imageRegex)[1];
// Create the image synchronously, add attribs async
obj = this.image(imageSrc);
// The image width is not always the same as the symbol width. The
// image may be centered within the symbol, as is the case when
// image shapes are used as label backgrounds, for example in flags.
obj.imgwidth = pick(
symbolSizes[imageSrc] && symbolSizes[imageSrc].width,
options && options.width
);
obj.imgheight = pick(
symbolSizes[imageSrc] && symbolSizes[imageSrc].height,
options && options.height
);
/**
* Set the size and position
*/
centerImage = function () {
obj.attr({
width: obj.width,
height: obj.height
});
};
/**
* Width and height setters that take both the image's physical size
* and the label size into consideration, and translates the image
* to center within the label.
*/
['width', 'height'].forEach(function (key) {
obj[key + 'Setter'] = function (value, key) {
var attribs = {},
imgSize = this['img' + key],
trans = key === 'width' ? 'translateX' : 'translateY';
this[key] = value;
if (defined(imgSize)) {
if (this.element) {
this.element.setAttribute(key, imgSize);
}
if (!this.alignByTranslate) {
attribs[trans] = ((this[key] || 0) - imgSize) / 2;
this.attr(attribs);
}
}
};
});
if (defined(x)) {
obj.attr({
x: x,
y: y
});
}
obj.isImg = true;
if (defined(obj.imgwidth) && defined(obj.imgheight)) {
centerImage();
} else {
// Initialize image to be 0 size so export will still function
// if there's no cached sizes.
obj.attr({ width: 0, height: 0 });
// Create a dummy JavaScript image to get the width and height.
createElement('img', {
onload: function () {
var chart = charts[ren.chartIndex];
// Special case for SVGs on IE11, the width is not
// accessible until the image is part of the DOM
// (#2854).
if (this.width === 0) {
css(this, {
position: 'absolute',
top: '-999em'
});
doc.body.appendChild(this);
}
// Center the image
symbolSizes[imageSrc] = { // Cache for next
width: this.width,
height: this.height
};
obj.imgwidth = this.width;
obj.imgheight = this.height;
if (obj.element) {
centerImage();
}
// Clean up after #2854 workaround.
if (this.parentNode) {
this.parentNode.removeChild(this);
}
// Fire the load event when all external images are
// loaded
ren.imgCount--;
if (!ren.imgCount && chart && chart.onload) {
chart.onload();
}
},
src: imageSrc
});
this.imgCount++;
}
}
return obj;
},
/**
* An extendable collection of functions for defining symbol paths.
*
* @name Highcharts.SVGRenderer#symbols
* @type {Highcharts.SymbolDictionary}
*/
symbols: {
'circle': function (x, y, w, h) {
// Return a full arc
return this.arc(x + w / 2, y + h / 2, w / 2, h / 2, {
start: 0,
end: Math.PI * 2,
open: false
});
},
'square': function (x, y, w, h) {
return [
'M', x, y,
'L', x + w, y,
x + w, y + h,
x, y + h,
'Z'
];
},
'triangle': function (x, y, w, h) {
return [
'M', x + w / 2, y,
'L', x + w, y + h,
x, y + h,
'Z'
];
},
'triangle-down': function (x, y, w, h) {
return [
'M', x, y,
'L', x + w, y,
x + w / 2, y + h,
'Z'
];
},
'diamond': function (x, y, w, h) {
return [
'M', x + w / 2, y,
'L', x + w, y + h / 2,
x + w / 2, y + h,
x, y + h / 2,
'Z'
];
},
'arc': function (x, y, w, h, options) {
var start = options.start,
rx = options.r || w,
ry = options.r || h || w,
proximity = 0.001,
fullCircle =
Math.abs(options.end - options.start - 2 * Math.PI) <
proximity,
// Substract a small number to prevent cos and sin of start and
// end from becoming equal on 360 arcs (related: #1561)
end = options.end - proximity,
innerRadius = options.innerR,
open = pick(options.open, fullCircle),
cosStart = Math.cos(start),
sinStart = Math.sin(start),
cosEnd = Math.cos(end),
sinEnd = Math.sin(end),
// Proximity takes care of rounding errors around PI (#6971)
longArc = options.end - start - Math.PI < proximity ? 0 : 1,
arc;
arc = [
'M',
x + rx * cosStart,
y + ry * sinStart,
'A', // arcTo
rx, // x radius
ry, // y radius
0, // slanting
longArc, // long or short arc
1, // clockwise
x + rx * cosEnd,
y + ry * sinEnd
];
if (defined(innerRadius)) {
arc.push(
open ? 'M' : 'L',
x + innerRadius * cosEnd,
y + innerRadius * sinEnd,
'A', // arcTo
innerRadius, // x radius
innerRadius, // y radius
0, // slanting
longArc, // long or short arc
0, // clockwise
x + innerRadius * cosStart,
y + innerRadius * sinStart
);
}
arc.push(open ? '' : 'Z'); // close
return arc;
},
/**
* Callout shape used for default tooltips, also used for rounded
* rectangles in VML
*/
'callout': function (x, y, w, h, options) {
var arrowLength = 6,
halfDistance = 6,
r = Math.min((options && options.r) || 0, w, h),
safeDistance = r + halfDistance,
anchorX = options && options.anchorX,
anchorY = options && options.anchorY,
path;
path = [
'M', x + r, y,
'L', x + w - r, y, // top side
'C', x + w, y, x + w, y, x + w, y + r, // top-right corner
'L', x + w, y + h - r, // right side
'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-rgt
'L', x + r, y + h, // bottom side
'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner
'L', x, y + r, // left side
'C', x, y, x, y, x + r, y // top-left corner
];
// Anchor on right side
if (anchorX && anchorX > w) {
// Chevron
if (
anchorY > y + safeDistance &&
anchorY < y + h - safeDistance
) {
path.splice(13, 3,
'L', x + w, anchorY - halfDistance,
x + w + arrowLength, anchorY,
x + w, anchorY + halfDistance,
x + w, y + h - r
);
// Simple connector
} else {
path.splice(13, 3,
'L', x + w, h / 2,
anchorX, anchorY,
x + w, h / 2,
x + w, y + h - r
);
}
// Anchor on left side
} else if (anchorX && anchorX < 0) {
// Chevron
if (
anchorY > y + safeDistance &&
anchorY < y + h - safeDistance
) {
path.splice(33, 3,
'L', x, anchorY + halfDistance,
x - arrowLength, anchorY,
x, anchorY - halfDistance,
x, y + r
);
// Simple connector
} else {
path.splice(33, 3,
'L', x, h / 2,
anchorX, anchorY,
x, h / 2,
x, y + r
);
}
} else if ( // replace bottom
anchorY &&
anchorY > h &&
anchorX > x + safeDistance &&
anchorX < x + w - safeDistance
) {
path.splice(23, 3,
'L', anchorX + halfDistance, y + h,
anchorX, y + h + arrowLength,
anchorX - halfDistance, y + h,
x + r, y + h
);
} else if ( // replace top
anchorY &&
anchorY < 0 &&
anchorX > x + safeDistance &&
anchorX < x + w - safeDistance
) {
path.splice(3, 3,
'L', anchorX - halfDistance, y,
anchorX, y - arrowLength,
anchorX + halfDistance, y,
w - r, y
);
}
return path;
}
},
/**
* Define a clipping rectangle. The clipping rectangle is later applied
* to {@link SVGElement} objects through the {@link SVGElement#clip}
* function.
*
* @example
* var circle = renderer.circle(100, 100, 100)
* .attr({ fill: 'red' })
* .add();
* var clipRect = renderer.clipRect(100, 100, 100, 100);
*
* // Leave only the lower right quarter visible
* circle.clip(clipRect);
*
* @function Highcharts.SVGRenderer#clipRect
*
* @param {string} id
*
* @param {number} x
*
* @param {number} y
*
* @param {number} width
*
* @param {number} height
*
* @return {Highcharts.ClipRectElement}
* A clipping rectangle.
*/
clipRect: function (x, y, width, height) {
var wrapper,
id = H.uniqueKey(),
clipPath = this.createElement('clipPath').attr({
id: id
}).add(this.defs);
wrapper = this.rect(x, y, width, height, 0).add(clipPath);
wrapper.id = id;
wrapper.clipPath = clipPath;
wrapper.count = 0;
return wrapper;
},
/**
* Draw text. The text can contain a subset of HTML, like spans and anchors
* and some basic text styling of these. For more advanced features like
* border and background, use {@link Highcharts.SVGRenderer#label} instead.
* To update the text after render, run `text.attr({ text: 'New text' })`.
*
* @sample highcharts/members/renderer-text-on-chart/
* Annotate the chart freely
* @sample highcharts/members/renderer-on-chart/
* Annotate with a border and in response to the data
* @sample highcharts/members/renderer-text/
* Formatted text
*
* @function Highcharts.SVGRenderer#text
*
* @param {string} str
* The text of (subset) HTML to draw.
*
* @param {number} x
* The x position of the text's lower left corner.
*
* @param {number} y
* The y position of the text's lower left corner.
*
* @param {boolean} [useHTML=false]
* Use HTML to render the text.
*
* @return {Highcharts.SVGElement}
* The text object.
*/
text: function (str, x, y, useHTML) {
// declare variables
var renderer = this,
wrapper,
attribs = {};
if (useHTML && (renderer.allowHTML || !renderer.forExport)) {
return renderer.html(str, x, y);
}
attribs.x = Math.round(x || 0); // X always needed for line-wrap logic
if (y) {
attribs.y = Math.round(y);
}
if (defined(str)) {
attribs.text = str;
}
wrapper = renderer.createElement('text')
.attr(attribs);
if (!useHTML) {
wrapper.xSetter = function (value, key, element) {
var tspans = element.getElementsByTagName('tspan'),
tspan,
parentVal = element.getAttribute(key),
i;
for (i = 0; i < tspans.length; i++) {
tspan = tspans[i];
// If the x values are equal, the tspan represents a
// linebreak
if (tspan.getAttribute(key) === parentVal) {
tspan.setAttribute(key, value);
}
}
element.setAttribute(key, value);
};
}
return wrapper;
},
/**
* Utility to return the baseline offset and total line height from the font
* size.
*
* @function Highcharts.SVGRenderer#fontMetrics
*
* @param {string} [fontSize]
* The current font size to inspect. If not given, the font size
* will be found from the DOM element.
*
* @param {Highcharts.SVGElement|Highcharts.SVGDOMElement} [elem]
* The element to inspect for a current font size.
*
* @return {Highcharts.FontMetricsObject}
* The font metrics.
*/
fontMetrics: function (fontSize, elem) {
var lineHeight,
baseline;
if (this.styledMode) {
fontSize = elem && SVGElement.prototype.getStyle.call(
elem,
'font-size'
);
} else {
fontSize = fontSize ||
// When the elem is a DOM element (#5932)
(elem && elem.style && elem.style.fontSize) ||
// Fall back on the renderer style default
(this.style && this.style.fontSize);
}
// Handle different units
if (/px/.test(fontSize)) {
fontSize = pInt(fontSize);
} else if (/em/.test(fontSize)) {
// The em unit depends on parent items
fontSize = parseFloat(fontSize) *
(elem ? this.fontMetrics(null, elem.parentNode).f : 16);
} else {
fontSize = 12;
}
// Empirical values found by comparing font size and bounding box
// height. Applies to the default font family.
// https://jsfiddle.net/highcharts/7xvn7/
lineHeight = fontSize < 24 ? fontSize + 3 : Math.round(fontSize * 1.2);
baseline = Math.round(lineHeight * 0.8);
return {
h: lineHeight,
b: baseline,
f: fontSize
};
},
/**
* Correct X and Y positioning of a label for rotation (#1764).
*
* @private
* @function Highcharts.SVGRenderer#rotCorr
*
* @param {number} baseline
*
* @param {number} rotation
*
* @param {boolean} alterY
*/
rotCorr: function (baseline, rotation, alterY) {
var y = baseline;
if (rotation && alterY) {
y = Math.max(y * Math.cos(rotation * deg2rad), 4);
}
return {
x: (-baseline / 3) * Math.sin(rotation * deg2rad),
y: y
};
},
/**
* Draw a label, which is an extended text element with support for border
* and background. Highcharts creates a `g` element with a text and a `path`
* or `rect` inside, to make it behave somewhat like a HTML div. Border and
* background are set through `stroke`, `stroke-width` and `fill` attributes
* using the {@link Highcharts.SVGElement#attr|attr} method. To update the
* text after render, run `label.attr({ text: 'New text' })`.
*
* @sample highcharts/members/renderer-label-on-chart/
* A label on the chart
*
* @function Highcharts.SVGRenderer#label
*
* @param {string} str
* The initial text string or (subset) HTML to render.
*
* @param {number} x
* The x position of the label's left side.
*
* @param {number} y
* The y position of the label's top side or baseline, depending on
* the `baseline` parameter.
*
* @param {string} [shape='rect']
* The shape of the label's border/background, if any. Defaults to
* `rect`. Other possible values are `callout` or other shapes
* defined in {@link Highcharts.SVGRenderer#symbols}.
*
* @param {string} [shape='rect']
* The shape of the label's border/background, if any. Defaults to
* `rect`. Other possible values are `callout` or other shapes
* defined in {@link Highcharts.SVGRenderer#symbols}.
*
* @param {number} [anchorX]
* In case the `shape` has a pointer, like a flag, this is the
* coordinates it should be pinned to.
*
* @param {number} [anchorY]
* In case the `shape` has a pointer, like a flag, this is the
* coordinates it should be pinned to.
*
* @param {boolean} [useHTML=false]
* Wether to use HTML to render the label.
*
* @param {boolean} [baseline=false]
* Whether to position the label relative to the text baseline,
* like {@link Highcharts.SVGRenderer#text|renderer.text}, or to the
* upper border of the rectangle.
*
* @param {string} [className]
* Class name for the group.
*
* @return {Highcharts.SVGElement}
* The generated label.
*/
label: function (
str,
x,
y,
shape,
anchorX,
anchorY,
useHTML,
baseline,
className
) {
var renderer = this,
styledMode = renderer.styledMode,
wrapper = renderer.g(className !== 'button' && 'label'),
text = wrapper.text = renderer.text('', 0, 0, useHTML)
.attr({
zIndex: 1
}),
box,
bBox,
alignFactor = 0,
padding = 3,
paddingLeft = 0,
width,
height,
wrapperX,
wrapperY,
textAlign,
deferredAttr = {},
strokeWidth,
baselineOffset,
hasBGImage = /^url\((.*?)\)$/.test(shape),
needsBox = styledMode || hasBGImage,
getCrispAdjust = function () {
return styledMode ?
box.strokeWidth() % 2 / 2 :
(strokeWidth ? parseInt(strokeWidth, 10) : 0) % 2 / 2;
},
updateBoxSize,
updateTextPadding,
boxAttr;
if (className) {
wrapper.addClass('highcharts-' + className);
}
/* This function runs after the label is added to the DOM (when the
bounding box is available), and after the text of the label is
updated to detect the new bounding box and reflect it in the border
box. */
updateBoxSize = function () {
var style = text.element.style,
crispAdjust,
attribs = {};
bBox = (
(width === undefined || height === undefined || textAlign) &&
defined(text.textStr) &&
text.getBBox()
); // #3295 && 3514 box failure when string equals 0
wrapper.width = (
(width || bBox.width || 0) +
2 * padding +
paddingLeft
);
wrapper.height = (height || bBox.height || 0) + 2 * padding;
// Update the label-scoped y offset
baselineOffset = padding + Math.min(
renderer.fontMetrics(style && style.fontSize, text).b,
// Math.min because of inline style (#9400)
bBox ? bBox.height : Infinity
);
if (needsBox) {
// Create the border box if it is not already present
if (!box) {
// Symbol definition exists (#5324)
wrapper.box = box = renderer.symbols[shape] || hasBGImage ?
renderer.symbol(shape) :
renderer.rect();
box.addClass( // Don't use label className for buttons
(className === 'button' ? '' : 'highcharts-label-box') +
(className ? ' highcharts-' + className + '-box' : '')
);
box.add(wrapper);
crispAdjust = getCrispAdjust();
attribs.x = crispAdjust;
attribs.y = (baseline ? -baselineOffset : 0) + crispAdjust;
}
// Apply the box attributes
attribs.width = Math.round(wrapper.width);
attribs.height = Math.round(wrapper.height);
box.attr(extend(attribs, deferredAttr));
deferredAttr = {};
}
};
/*
* This function runs after setting text or padding, but only if padding
* is changed.
*/
updateTextPadding = function () {
var textX = paddingLeft + padding,
textY;
// determin y based on the baseline
textY = baseline ? 0 : baselineOffset;
// compensate for alignment
if (
defined(width) &&
bBox &&
(textAlign === 'center' || textAlign === 'right')
) {
textX += { center: 0.5, right: 1 }[textAlign] *
(width - bBox.width);
}
// update if anything changed
if (textX !== text.x || textY !== text.y) {
text.attr('x', textX);
// #8159 - prevent misplaced data labels in treemap
// (useHTML: true)
if (text.hasBoxWidthChanged) {
bBox = text.getBBox(true);
updateBoxSize();
}
if (textY !== undefined) {
text.attr('y', textY);
}
}
// record current values
text.x = textX;
text.y = textY;
};
/*
* Set a box attribute, or defer it if the box is not yet created
*/
boxAttr = function (key, value) {
if (box) {
box.attr(key, value);
} else {
deferredAttr[key] = value;
}
};
/*
* After the text element is added, get the desired size of the border
* box and add it before the text in the DOM.
*/
wrapper.onAdd = function () {
text.add(wrapper);
wrapper.attr({
// Alignment is available now (#3295, 0 not rendered if given
// as a value)
text: (str || str === 0) ? str : '',
x: x,
y: y
});
if (box && defined(anchorX)) {
wrapper.attr({
anchorX: anchorX,
anchorY: anchorY
});
}
};
/*
* Add specific attribute setters.
*/
// only change local variables
wrapper.widthSetter = function (value) {
width = H.isNumber(value) ? value : null; // width:auto => null
};
wrapper.heightSetter = function (value) {
height = value;
};
wrapper['text-alignSetter'] = function (value) {
textAlign = value;
};
wrapper.paddingSetter = function (value) {
if (defined(value) && value !== padding) {
padding = wrapper.padding = value;
updateTextPadding();
}
};
wrapper.paddingLeftSetter = function (value) {
if (defined(value) && value !== paddingLeft) {
paddingLeft = value;
updateTextPadding();
}
};
// change local variable and prevent setting attribute on the group
wrapper.alignSetter = function (value) {
value = { left: 0, center: 0.5, right: 1 }[value];
if (value !== alignFactor) {
alignFactor = value;
// Bounding box exists, means we're dynamically changing
if (bBox) {
wrapper.attr({ x: wrapperX }); // #5134
}
}
};
// apply these to the box and the text alike
wrapper.textSetter = function (value) {
if (value !== undefined) {
text.textSetter(value);
}
updateBoxSize();
updateTextPadding();
};
// apply these to the box but not to the text
wrapper['stroke-widthSetter'] = function (value, key) {
if (value) {
needsBox = true;
}
strokeWidth = this['stroke-width'] = value;
boxAttr(key, value);
};
if (styledMode) {
wrapper.rSetter = function (value, key) {
boxAttr(key, value);
};
} else {
wrapper.strokeSetter =
wrapper.fillSetter =
wrapper.rSetter = function (value, key) {
if (key !== 'r') {
if (key === 'fill' && value) {
needsBox = true;
}
// for animation getter (#6776)
wrapper[key] = value;
}
boxAttr(key, value);
};
}
wrapper.anchorXSetter = function (value, key) {
anchorX = wrapper.anchorX = value;
boxAttr(key, Math.round(value) - getCrispAdjust() - wrapperX);
};
wrapper.anchorYSetter = function (value, key) {
anchorY = wrapper.anchorY = value;
boxAttr(key, value - wrapperY);
};
// rename attributes
wrapper.xSetter = function (value) {
wrapper.x = value; // for animation getter
if (alignFactor) {
value -= alignFactor * ((width || bBox.width) + 2 * padding);
// Force animation even when setting to the same value (#7898)
wrapper['forceAnimate:x'] = true;
}
wrapperX = Math.round(value);
wrapper.attr('translateX', wrapperX);
};
wrapper.ySetter = function (value) {
wrapperY = wrapper.y = Math.round(value);
wrapper.attr('translateY', wrapperY);
};
// Redirect certain methods to either the box or the text
var baseCss = wrapper.css;
var wrapperExtension = {
/**
* Pick up some properties and apply them to the text instead of the
* wrapper.
*/
css: function (styles) {
if (styles) {
var textStyles = {};
// Create a copy to avoid altering the original object
// (#537)
styles = merge(styles);
wrapper.textProps.forEach(function (prop) {
if (styles[prop] !== undefined) {
textStyles[prop] = styles[prop];
delete styles[prop];
}
});
text.css(textStyles);
// Update existing text and box
if ('width' in textStyles) {
updateBoxSize();
}
// Keep updated (#9400)
if ('fontSize' in textStyles) {
updateBoxSize();
updateTextPadding();
}
}
return baseCss.call(wrapper, styles);
},
/*
* Return the bounding box of the box, not the group.
*/
getBBox: function () {
return {
width: bBox.width + 2 * padding,
height: bBox.height + 2 * padding,
x: bBox.x - padding,
y: bBox.y - padding
};
},
/**
* Destroy and release memory.
*/
destroy: function () {
// Added by button implementation
removeEvent(wrapper.element, 'mouseenter');
removeEvent(wrapper.element, 'mouseleave');
if (text) {
text = text.destroy();
}
if (box) {
box = box.destroy();
}
// Call base implementation to destroy the rest
SVGElement.prototype.destroy.call(wrapper);
// Release local pointers (#1298)
wrapper =
renderer =
updateBoxSize =
updateTextPadding =
boxAttr = null;
}
};
if (!styledMode) {
/**
* Apply the shadow to the box.
*
* @ignore
* @function Highcharts.SVGElement#shadow
*
* @return {Highcharts.SVGElement}
*/
wrapperExtension.shadow = function (b) {
if (b) {
updateBoxSize();
if (box) {
box.shadow(b);
}
}
return wrapper;
};
}
return extend(wrapper, wrapperExtension);
}
}); // end SVGRenderer
// general renderer
H.Renderer = SVGRenderer;
| extend1994/cdnjs | ajax/libs/highcharts/7.0.1/es-modules/parts/SvgRenderer.js | JavaScript | mit | 165,077 |
// wrapped by build app
define("FileSaver/demo/demo", ["dojo","dijit","dojox"], function(dojo,dijit,dojox){
/* FileSaver.js demo script
* 2012-01-23
*
* By Eli Grey, http://eligrey.com
* License: X11/MIT
* See LICENSE.md
*/
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/demo/demo.js */
(function(view) {
"use strict";
// The canvas drawing portion of the demo is based off the demo at
// http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/
var
document = view.document
, $ = function(id) {
return document.getElementById(id);
}
, session = view.sessionStorage
// only get URL when necessary in case Blob.js hasn't defined it yet
, get_blob = function() {
return view.Blob;
}
, canvas = $("canvas")
, canvas_options_form = $("canvas-options")
, canvas_filename = $("canvas-filename")
, canvas_clear_button = $("canvas-clear")
, text = $("text")
, text_options_form = $("text-options")
, text_filename = $("text-filename")
, html = $("html")
, html_options_form = $("html-options")
, html_filename = $("html-filename")
, ctx = canvas.getContext("2d")
, drawing = false
, x_points = session.x_points || []
, y_points = session.y_points || []
, drag_points = session.drag_points || []
, add_point = function(x, y, dragging) {
x_points.push(x);
y_points.push(y);
drag_points.push(dragging);
}
, draw = function(){
canvas.width = canvas.width;
ctx.lineWidth = 6;
ctx.lineJoin = "round";
ctx.strokeStyle = "#000000";
var
i = 0
, len = x_points.length
;
for(; i < len; i++) {
ctx.beginPath();
if (i && drag_points[i]) {
ctx.moveTo(x_points[i-1], y_points[i-1]);
} else {
ctx.moveTo(x_points[i]-1, y_points[i]);
}
ctx.lineTo(x_points[i], y_points[i]);
ctx.closePath();
ctx.stroke();
}
}
, stop_drawing = function() {
drawing = false;
}
// Title guesser and document creator available at https://gist.github.com/1059648
, guess_title = function(doc) {
var
h = "h6 h5 h4 h3 h2 h1".split(" ")
, i = h.length
, headers
, header_text
;
while (i--) {
headers = doc.getElementsByTagName(h[i]);
for (var j = 0, len = headers.length; j < len; j++) {
header_text = headers[j].textContent.trim();
if (header_text) {
return header_text;
}
}
}
}
, doc_impl = document.implementation
, create_html_doc = function(html) {
var
dt = doc_impl.createDocumentType('html', null, null)
, doc = doc_impl.createDocument("http://www.w3.org/1999/xhtml", "html", dt)
, doc_el = doc.documentElement
, head = doc_el.appendChild(doc.createElement("head"))
, charset_meta = head.appendChild(doc.createElement("meta"))
, title = head.appendChild(doc.createElement("title"))
, body = doc_el.appendChild(doc.createElement("body"))
, i = 0
, len = html.childNodes.length
;
charset_meta.setAttribute("charset", html.ownerDocument.characterSet);
for (; i < len; i++) {
body.appendChild(doc.importNode(html.childNodes.item(i), true));
}
var title_text = guess_title(doc);
if (title_text) {
title.appendChild(doc.createTextNode(title_text));
}
return doc;
}
;
canvas.width = 500;
canvas.height = 300;
if (typeof x_points === "string") {
x_points = JSON.parse(x_points);
} if (typeof y_points === "string") {
y_points = JSON.parse(y_points);
} if (typeof drag_points === "string") {
drag_points = JSON.parse(drag_points);
} if (session.canvas_filename) {
canvas_filename.value = session.canvas_filename;
} if (session.text) {
text.value = session.text;
} if (session.text_filename) {
text_filename.value = session.text_filename;
} if (session.html) {
html.innerHTML = session.html;
} if (session.html_filename) {
html_filename.value = session.html_filename;
}
drawing = true;
draw();
drawing = false;
canvas_clear_button.addEventListener("click", function() {
canvas.width = canvas.width;
x_points.length =
y_points.length =
drag_points.length =
0;
}, false);
canvas.addEventListener("mousedown", function(event) {
event.preventDefault();
drawing = true;
add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, false);
draw();
}, false);
canvas.addEventListener("mousemove", function(event) {
if (drawing) {
add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, true);
draw();
}
}, false);
canvas.addEventListener("mouseup", stop_drawing, false);
canvas.addEventListener("mouseout", stop_drawing, false);
canvas_options_form.addEventListener("submit", function(event) {
event.preventDefault();
canvas.toBlob(function(blob) {
saveAs(
blob
, (canvas_filename.value || canvas_filename.placeholder) + ".png"
);
}, "image/png");
}, false);
text_options_form.addEventListener("submit", function(event) {
event.preventDefault();
var BB = get_blob();
saveAs(
new BB(
[text.value || text.placeholder]
, {type: "text/plain;charset=" + document.characterSet}
)
, (text_filename.value || text_filename.placeholder) + ".txt"
);
}, false);
html_options_form.addEventListener("submit", function(event) {
event.preventDefault();
var
BB = get_blob()
, xml_serializer = new XMLSerializer
, doc = create_html_doc(html)
;
saveAs(
new BB(
[xml_serializer.serializeToString(doc)]
, {type: "application/xhtml+xml;charset=" + document.characterSet}
)
, (html_filename.value || html_filename.placeholder) + ".xhtml"
);
}, false);
view.addEventListener("unload", function() {
session.x_points = JSON.stringify(x_points);
session.y_points = JSON.stringify(y_points);
session.drag_points = JSON.stringify(drag_points);
session.canvas_filename = canvas_filename.value;
session.text = text.value;
session.text_filename = text_filename.value;
session.html = html.innerHTML;
session.html_filename = html_filename.value;
}, false);
}(self));
});
| dawenx/p3_web | public/js/release/FileSaver/demo/demo.js | JavaScript | mit | 5,888 |
/* ****************************************************************************
* Start Flags series code *
*****************************************************************************/
var symbols = SVGRenderer.prototype.symbols;
// 1 - set default options
defaultPlotOptions.flags = merge(defaultPlotOptions.column, {
dataGrouping: null,
fillColor: 'white',
lineWidth: 1,
pointRange: 0, // #673
//radius: 2,
shape: 'flag',
stackDistance: 12,
states: {
hover: {
lineColor: 'black',
fillColor: '#FCFFC5'
}
},
style: {
fontSize: '11px',
fontWeight: 'bold',
textAlign: 'center'
},
tooltip: {
pointFormat: '{point.text}<br/>'
},
threshold: null,
y: -30
});
// 2 - Create the CandlestickSeries object
seriesTypes.flags = extendClass(seriesTypes.column, {
type: 'flags',
sorted: false,
noSharedTooltip: true,
takeOrdinalPosition: false, // #1074
trackerGroups: ['markerGroup'],
forceCrop: true,
/**
* Inherit the initialization from base Series
*/
init: Series.prototype.init,
/**
* One-to-one mapping from options to SVG attributes
*/
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
fill: 'fillColor',
stroke: 'color',
'stroke-width': 'lineWidth',
r: 'radius'
},
/**
* Extend the translate method by placing the point on the related series
*/
translate: function () {
seriesTypes.column.prototype.translate.apply(this);
var series = this,
options = series.options,
chart = series.chart,
points = series.points,
cursor = points.length - 1,
point,
lastPoint,
optionsOnSeries = options.onSeries,
onSeries = optionsOnSeries && chart.get(optionsOnSeries),
step = onSeries && onSeries.options.step,
onData = onSeries && onSeries.points,
i = onData && onData.length,
xAxis = series.xAxis,
xAxisExt = xAxis.getExtremes(),
leftPoint,
lastX,
rightPoint,
currentDataGrouping;
// relate to a master series
if (onSeries && onSeries.visible && i) {
currentDataGrouping = onSeries.currentDataGrouping;
lastX = onData[i - 1].x + (currentDataGrouping ? currentDataGrouping.totalRange : 0); // #2374
// sort the data points
points.sort(function (a, b) {
return (a.x - b.x);
});
while (i-- && points[cursor]) {
point = points[cursor];
leftPoint = onData[i];
if (leftPoint.x <= point.x && leftPoint.plotY !== UNDEFINED) {
if (point.x <= lastX) { // #803
point.plotY = leftPoint.plotY;
// interpolate between points, #666
if (leftPoint.x < point.x && !step) {
rightPoint = onData[i + 1];
if (rightPoint && rightPoint.plotY !== UNDEFINED) {
point.plotY +=
((point.x - leftPoint.x) / (rightPoint.x - leftPoint.x)) * // the distance ratio, between 0 and 1
(rightPoint.plotY - leftPoint.plotY); // the y distance
}
}
}
cursor--;
i++; // check again for points in the same x position
if (cursor < 0) {
break;
}
}
}
}
// Add plotY position and handle stacking
each(points, function (point, i) {
// Undefined plotY means the point is either on axis, outside series range or hidden series.
// If the series is outside the range of the x axis it should fall through with
// an undefined plotY, but then we must remove the shapeArgs (#847).
if (point.plotY === UNDEFINED) {
if (point.x >= xAxisExt.min && point.x <= xAxisExt.max) { // we're inside xAxis range
point.plotY = chart.chartHeight - xAxis.bottom - (xAxis.opposite ? xAxis.height : 0) + xAxis.offset - chart.plotTop;
} else {
point.shapeArgs = {}; // 847
}
}
// if multiple flags appear at the same x, order them into a stack
lastPoint = points[i - 1];
if (lastPoint && lastPoint.plotX === point.plotX) {
if (lastPoint.stackIndex === UNDEFINED) {
lastPoint.stackIndex = 0;
}
point.stackIndex = lastPoint.stackIndex + 1;
}
});
},
/**
* Draw the markers
*/
drawPoints: function () {
var series = this,
pointAttr,
points = series.points,
chart = series.chart,
renderer = chart.renderer,
plotX,
plotY,
options = series.options,
optionsY = options.y,
shape,
i,
point,
graphic,
stackIndex,
crisp = (options.lineWidth % 2 / 2),
anchorX,
anchorY,
outsideRight;
i = points.length;
while (i--) {
point = points[i];
outsideRight = point.plotX > series.xAxis.len;
plotX = point.plotX + (outsideRight ? crisp : -crisp);
stackIndex = point.stackIndex;
shape = point.options.shape || options.shape;
plotY = point.plotY;
if (plotY !== UNDEFINED) {
plotY = point.plotY + optionsY + crisp - (stackIndex !== UNDEFINED && stackIndex * options.stackDistance);
}
anchorX = stackIndex ? UNDEFINED : point.plotX + crisp; // skip connectors for higher level stacked points
anchorY = stackIndex ? UNDEFINED : point.plotY;
graphic = point.graphic;
// only draw the point if y is defined and the flag is within the visible area
if (plotY !== UNDEFINED && plotX >= 0 && !outsideRight) {
// shortcuts
pointAttr = point.pointAttr[point.selected ? 'select' : ''];
if (graphic) { // update
graphic.attr({
x: plotX,
y: plotY,
r: pointAttr.r,
anchorX: anchorX,
anchorY: anchorY
});
} else {
graphic = point.graphic = renderer.label(
point.options.title || options.title || 'A',
plotX,
plotY,
shape,
anchorX,
anchorY,
options.useHTML
)
.css(merge(options.style, point.style))
.attr(pointAttr)
.attr({
align: shape === 'flag' ? 'left' : 'center',
width: options.width,
height: options.height
})
.add(series.markerGroup)
.shadow(options.shadow);
}
// Set the tooltip anchor position
point.tooltipPos = [plotX, plotY];
} else if (graphic) {
point.graphic = graphic.destroy();
}
}
},
/**
* Extend the column trackers with listeners to expand and contract stacks
*/
drawTracker: function () {
var series = this,
points = series.points;
TrackerMixin.drawTrackerPoint.apply(this);
// Bring each stacked flag up on mouse over, this allows readability of vertically
// stacked elements as well as tight points on the x axis. #1924.
each(points, function (point) {
var graphic = point.graphic;
if (graphic) {
addEvent(graphic.element, 'mouseover', function () {
// Raise this point
if (point.stackIndex > 0 && !point.raised) {
point._y = graphic.y;
graphic.attr({
y: point._y - 8
});
point.raised = true;
}
// Revert other raised points
each(points, function (otherPoint) {
if (otherPoint !== point && otherPoint.raised && otherPoint.graphic) {
otherPoint.graphic.attr({
y: otherPoint._y
});
otherPoint.raised = false;
}
});
});
}
});
},
/**
* Disable animation
*/
animate: noop
});
// create the flag icon with anchor
symbols.flag = function (x, y, w, h, options) {
var anchorX = (options && options.anchorX) || x,
anchorY = (options && options.anchorY) || y;
return [
'M', anchorX, anchorY,
'L', x, y + h,
x, y,
x + w, y,
x + w, y + h,
x, y + h,
'M', anchorX, anchorY,
'Z'
];
};
// create the circlepin and squarepin icons with anchor
each(['circle', 'square'], function (shape) {
symbols[shape + 'pin'] = function (x, y, w, h, options) {
var anchorX = options && options.anchorX,
anchorY = options && options.anchorY,
path = symbols[shape](x, y, w, h),
labelTopOrBottomY;
if (anchorX && anchorY) {
// if the label is below the anchor, draw the connecting line from the top edge of the label
// otherwise start drawing from the bottom edge
labelTopOrBottomY = (y > anchorY) ? y : y + h;
path.push('M', anchorX, labelTopOrBottomY, 'L', anchorX, anchorY);
}
return path;
};
});
// The symbol callbacks are generated on the SVGRenderer object in all browsers. Even
// VML browsers need this in order to generate shapes in export. Now share
// them with the VMLRenderer.
if (Renderer === Highcharts.VMLRenderer) {
each(['flag', 'circlepin', 'squarepin'], function (shape) {
VMLRenderer.prototype.symbols[shape] = symbols[shape];
});
}
/* ****************************************************************************
* End Flags series code *
*****************************************************************************/
| Ecodev/gims | htdocs/lib/highcharts.com/js/parts/FlagsSeries.js | JavaScript | mit | 8,576 |
version https://git-lfs.github.com/spec/v1
oid sha256:f09386339b7a083e92b706c491817eb6f328805c49481a614f996a194d761fdc
size 1848
| yogeshsaroya/new-cdnjs | ajax/libs/dojo/1.9.7/cldr/nls/zh/ethiopic.js.uncompressed.js | JavaScript | mit | 129 |
if (typeof (QP) == "undefined" || !QP) {
var QP = {}
};
(function() {
/* Draws the lines linking nodes in query plan diagram.
root - The document element in which the diagram is contained. */
QP.drawLines = function(root) {
if (root === null || root === undefined) {
// Try and find it ourselves
root = $(".qp-root").parent();
} else {
// Make sure the object passed is jQuery wrapped
root = $(root);
}
internalDrawLines(root);
};
/* Internal implementaiton of drawLines. */
function internalDrawLines(root) {
var canvas = getCanvas(root);
var canvasElm = canvas[0];
// Check for browser compatability
if (canvasElm.getContext !== null && canvasElm.getContext !== undefined) {
// Chrome is usually too quick with document.ready
window.setTimeout(function() {
var context = canvasElm.getContext("2d");
// The first root node may be smaller than the full query plan if using overflow
var firstNode = $(".qp-tr", root);
canvasElm.width = firstNode.outerWidth(true);
canvasElm.height = firstNode.outerHeight(true);
var offset = canvas.offset();
$(".qp-tr", root).each(function() {
var from = $("> * > .qp-node", $(this));
$("> * > .qp-tr > * > .qp-node", $(this)).each(function() {
drawLine(context, offset, from, $(this));
});
});
context.stroke();
}, 1);
}
}
/* Locates or creates the canvas element to use to draw lines for a given root element. */
function getCanvas(root) {
var returnValue = $("canvas", root);
if (returnValue.length == 0) {
root.prepend($("<canvas></canvas>")
.css("position", "absolute")
.css("top", 0).css("left", 0)
);
returnValue = $("canvas", root);
}
return returnValue;
}
/* Draws a line between two nodes.
context - The canvas context with which to draw.
offset - Canvas offset in the document.
from - The document jQuery object from which to draw the line.
to - The document jQuery object to which to draw the line. */
function drawLine(context, offset, from, to) {
var fromOffset = from.offset();
fromOffset.top += from.outerHeight() / 2;
fromOffset.left += from.outerWidth();
var toOffset = to.offset();
toOffset.top += to.outerHeight() / 2;
var midOffsetLeft = fromOffset.left / 2 + toOffset.left / 2;
context.moveTo(fromOffset.left - offset.left, fromOffset.top - offset.top);
context.lineTo(midOffsetLeft - offset.left, fromOffset.top - offset.top);
context.lineTo(midOffsetLeft - offset.left, toOffset.top - offset.top);
context.lineTo(toOffset.left - offset.left, toOffset.top - offset.top);
}
})(); | jemmy655/sqlfiddle | src/main/webapp/javascripts/libs/xplans/mssql.js | JavaScript | mit | 3,162 |
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.0-rc4-master-c81f9f1
*/
goog.provide('ng.material.components.swipe');
goog.require('ng.material.core');
/**
* @ngdoc module
* @name material.components.swipe
* @description Swipe module!
*/
/**
* @ngdoc directive
* @module material.components.swipe
* @name mdSwipeLeft
*
* @restrict A
*
* @description
* The md-swipe-left directive allows you to specify custom behavior when an element is swiped
* left.
*
* @usage
* <hljs lang="html">
* <div md-swipe-left="onSwipeLeft()">Swipe me left!</div>
* </hljs>
*/
/**
* @ngdoc directive
* @module material.components.swipe
* @name mdSwipeRight
*
* @restrict A
*
* @description
* The md-swipe-right directive allows you to specify custom behavior when an element is swiped
* right.
*
* @usage
* <hljs lang="html">
* <div md-swipe-right="onSwipeRight()">Swipe me right!</div>
* </hljs>
*/
/**
* @ngdoc directive
* @module material.components.swipe
* @name mdSwipeUp
*
* @restrict A
*
* @description
* The md-swipe-up directive allows you to specify custom behavior when an element is swiped
* up.
*
* @usage
* <hljs lang="html">
* <div md-swipe-up="onSwipeUp()">Swipe me up!</div>
* </hljs>
*/
/**
* @ngdoc directive
* @module material.components.swipe
* @name mdSwipeDown
*
* @restrict A
*
* @description
* The md-swipe-down directive allows you to specify custom behavior when an element is swiped
* down.
*
* @usage
* <hljs lang="html">
* <div md-swipe-down="onSwipDown()">Swipe me down!</div>
* </hljs>
*/
angular.module('material.components.swipe', ['material.core'])
.directive('mdSwipeLeft', getDirective('SwipeLeft'))
.directive('mdSwipeRight', getDirective('SwipeRight'))
.directive('mdSwipeUp', getDirective('SwipeUp'))
.directive('mdSwipeDown', getDirective('SwipeDown'));
function getDirective(name) {
var directiveName = 'md' + name;
var eventName = '$md.' + name.toLowerCase();
DirectiveFactory.$inject = ["$parse"];
return DirectiveFactory;
/* ngInject */
function DirectiveFactory($parse) {
return { restrict: 'A', link: postLink };
function postLink(scope, element, attr) {
var fn = $parse(attr[directiveName]);
element.on(eventName, function(ev) {
scope.$apply(function() { fn(scope, { $event: ev }); });
});
}
}
}
ng.material.components.swipe = angular.module("material.components.swipe"); | JoPaRoRo/Fleet | web/assets/global/plugins/angular-material/modules/closure/swipe/swipe_1.js | JavaScript | mit | 2,501 |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v18.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LinkedList = (function () {
function LinkedList() {
this.first = null;
this.last = null;
}
LinkedList.prototype.add = function (item) {
var entry = {
item: item,
next: null
};
if (this.last) {
this.last.next = entry;
}
else {
this.first = entry;
}
this.last = entry;
};
LinkedList.prototype.remove = function () {
var result = this.first;
if (result) {
this.first = result.next;
if (!this.first) {
this.last = null;
}
}
return result.item;
};
LinkedList.prototype.isEmpty = function () {
return !this.first;
};
return LinkedList;
}());
exports.LinkedList = LinkedList;
var LinkedListItem = (function () {
function LinkedListItem() {
}
return LinkedListItem;
}());
| sashberd/cdnjs | ajax/libs/ag-grid/18.0.0/lib/misc/linkedList.js | JavaScript | mit | 1,186 |
/**
* This pagination style shows Previous/Next buttons, and page numbers only
* for "known" pages that are visited at least once time using [Next>] button.
* Initially only Prev/Next buttons are shown (Prev is initially disabled).
*
* [<Previous] [Next>]
*
* When user navigates through the pages using [Next>] button, navigation shows
* the numbers for the previous pages. As an example, when user reaches page 2,
* page numbers 1 and 2 are shown:
*
* [<Previous] 1 2 [Next>]
*
* When user reaches page 4, page numbers 1, 2, 3, and 4 are shown:
*
* [<Previous] 1 2 3 4 [Next>]
*
* When user navigates back, pagination will remember the last page number
* he reached and the numbesr up to the last known page are shown. As an example,
* when user returns to the page 2, page numbers 1, 2, 3, and 4 are still shown:
*
* [<Previous] 1 2 3 4 [Next>]
*
* This pagination style is designed for users who will not directly jump to
* the random page that they have not opened before. Assumption is that users
* will discover new pages using [Next>] button. This pagination enables users
* to easily go back and forth to any page that they discovered.
*
* Key benefit: This pagination supports usual pagination pattern and does not
* require server to return total count of items just to calculate last page and
* all numbers. This migh be huge performance benefit because server does not
* need to execute two queries in server-side processing mode:
* - One to get the records that will be shown on the current page,
* - Second to get the total count just to calculate full pagination.
*
* Without second query, page load time might be 2x faster, especially in cases
* when server can quickly get top 100 records, but it would need to scan entire
* database table just to calculate the total count and position of the last
* page. This pagination style is reasonable trade-off between simple and fullnumbers
* pagination.
*
* @name Simple Incremental navigation (Bootstrap)
* @summary Shows forward/back buttons and all known page numbers.
* @author [Jovan Popovic](http://github.com/JocaPC)
*
* @example
* $(document).ready(function() {
* $('#example').dataTable( {
* "pagingType": "simple_incremental_bootstrap"
* } );
* } );
*/
$.fn.dataTableExt.oPagination.simple_incremental_bootstrap = {
"fnInit": function (oSettings, nPaging, fnCallbackDraw) {
$(nPaging).prepend($("<ul class=\"pagination\"></ul>"));
var ul = $("ul", $(nPaging));
nFirst = document.createElement('li');
nPrevious = document.createElement('li');
nNext = document.createElement('li');
$(nPrevious).append($('<span>' + (oSettings.oLanguage.oPaginate.sPrevious) + '</span>'));
$(nFirst).append($('<span>1</span>'));
$(nNext).append($('<span>' + (oSettings.oLanguage.oPaginate.sNext) + '</span>'));
nFirst.className = "paginate_button first active";
nPrevious.className = "paginate_button previous";
nNext.className = "paginate_button next";
ul.append(nPrevious);
ul.append(nFirst);
ul.append(nNext);
$(nFirst).click(function () {
oSettings.oApi._fnPageChange(oSettings, "first");
fnCallbackDraw(oSettings);
});
$(nPrevious).click(function () {
if (!(oSettings._iDisplayStart === 0)) {
oSettings.oApi._fnPageChange(oSettings, "previous");
fnCallbackDraw(oSettings);
}
});
$(nNext).click(function () {
if(oSettings.aiDisplay.length < oSettings._iDisplayLength){
oSettings._iRecordsTotal = oSettings._iDisplayStart + oSettings.aiDisplay.length;
}else{
oSettings._iRecordsTotal = oSettings._iDisplayStart + oSettings._iDisplayLength + 1;
}
if (!(oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay()
||
oSettings.aiDisplay.length < oSettings._iDisplayLength)) {
oSettings.oApi._fnPageChange(oSettings, "next");
fnCallbackDraw(oSettings);
}
});
/* Disallow text selection */
$(nFirst).bind('selectstart', function () { return false; });
$(nPrevious).bind('selectstart', function () { return false; });
$(nNext).bind('selectstart', function () { return false; });
// Reset dynamically generated pages on length/filter change.
$(oSettings.nTable).DataTable().on('length.dt', function (e, settings, len) {
$("li.dynamic_page_item", nPaging).remove();
});
$(oSettings.nTable).DataTable().on('search.dt', function (e, settings, len) {
$("li.dynamic_page_item", nPaging).remove();
});
},
/*
* Function: oPagination.simple_incremental_bootstrap.fnUpdate
* Purpose: Update the list of page buttons shows
* Inputs: object:oSettings - dataTables settings object
* function:fnCallbackDraw - draw function which must be called on update
*/
"fnUpdate": function (oSettings, fnCallbackDraw) {
if (!oSettings.aanFeatures.p) {
return;
}
/* Loop over each instance of the pager */
var an = oSettings.aanFeatures.p;
for (var i = 0, iLen = an.length ; i < iLen ; i++) {
var buttons = an[i].getElementsByTagName('li');
$(buttons).removeClass("active");
if (oSettings._iDisplayStart === 0) {
buttons[0].className = "paginate_buttons disabled previous";
buttons[buttons.length - 1].className = "paginate_button enabled next";
} else {
buttons[0].className = "paginate_buttons enabled previous";
}
var page = Math.round(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1;
if (page == buttons.length-1 && oSettings.aiDisplay.length > 0) {
$new = $('<li class="dynamic_page_item active"><span>' + page + "</span></li>");
$(buttons[buttons.length - 1]).before($new);
$new.click(function () {
$(oSettings.nTable).DataTable().page(page-1);
fnCallbackDraw(oSettings);
});
} else
$(buttons[page]).addClass("active");
if (oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay()
||
oSettings.aiDisplay.length < oSettings._iDisplayLength) {
buttons[buttons.length - 1].className = "paginate_button disabled next";
}
}
}
};
| cdnjs/cdnjs | ajax/libs/datatables-plugins/1.11.5/pagination/simple_incremental_bootstrap.js | JavaScript | mit | 6,799 |
module.exports={title:"Kibana",hex:"005571",source:"https://www.elastic.co/brand",svg:'<svg aria-labelledby="simpleicons-kibana-icon" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title id="simpleicons-kibana-icon">Kibana icon</title><path d="M21.04 23.99H4.18l9.88-11.86c4.23 2.76 6.98 7.04 6.98 11.86zm0-23.95H3.08v21.55z"/></svg>\n'}; | cdnjs/cdnjs | ajax/libs/simple-icons/1.9.9/kibana.min.js | JavaScript | mit | 358 |
/* YUI 3.9.0 (build 5827) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */
YUI.add('yui-later', function (Y, NAME) {
/**
* Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module,
* <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-later
*/
var NO_ARGS = [];
/**
* Executes the supplied function in the context of the supplied
* object 'when' milliseconds later. Executes the function a
* single time unless periodic is set to true.
* @for YUI
* @method later
* @param when {int} the number of milliseconds to wait until the fn
* is executed.
* @param o the context object.
* @param fn {Function|String} the function to execute or the name of
* the method in the 'o' object to execute.
* @param data [Array] data that is provided to the function. This
* accepts either a single item or an array. If an array is provided,
* the function is executed with one parameter for each array item.
* If you need to pass a single array parameter, it needs to be wrapped
* in an array [myarray].
*
* Note: native methods in IE may not have the call and apply methods.
* In this case, it will work, but you are limited to four arguments.
*
* @param periodic {boolean} if true, executes continuously at supplied
* interval until canceled.
* @return {object} a timer object. Call the cancel() method on this
* object to stop the timer.
*/
Y.later = function(when, o, fn, data, periodic) {
when = when || 0;
data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS;
o = o || Y.config.win || Y;
var cancelled = false,
method = (o && Y.Lang.isString(fn)) ? o[fn] : fn,
wrapper = function() {
// IE 8- may execute a setInterval callback one last time
// after clearInterval was called, so in order to preserve
// the cancel() === no more runny-run, we have to jump through
// an extra hoop.
if (!cancelled) {
if (!method.apply) {
method(data[0], data[1], data[2], data[3]);
} else {
method.apply(o, data || NO_ARGS);
}
}
},
id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when);
return {
id: id,
interval: periodic,
cancel: function() {
cancelled = true;
if (this.interval) {
clearInterval(id);
} else {
clearTimeout(id);
}
}
};
};
Y.Lang.later = Y.later;
}, '3.9.0', {"requires": ["yui-base"]});
| alafon/ezpublish-community-built | ezpublish_legacy/extension/ezjscore/design/standard/lib/yui/3.9.0/build/yui-later/yui-later.js | JavaScript | gpl-2.0 | 2,686 |
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*
* Version: 5.3.1 (2020-05-27)
*/
(function () {
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');
var getNonEditableClass = function (editor) {
return editor.getParam('noneditable_noneditable_class', 'mceNonEditable');
};
var getEditableClass = function (editor) {
return editor.getParam('noneditable_editable_class', 'mceEditable');
};
var getNonEditableRegExps = function (editor) {
var nonEditableRegExps = editor.getParam('noneditable_regexp', []);
if (nonEditableRegExps && nonEditableRegExps.constructor === RegExp) {
return [nonEditableRegExps];
} else {
return nonEditableRegExps;
}
};
var hasClass = function (checkClassName) {
return function (node) {
return (' ' + node.attr('class') + ' ').indexOf(checkClassName) !== -1;
};
};
var replaceMatchWithSpan = function (editor, content, cls) {
return function (match) {
var args = arguments, index = args[args.length - 2];
var prevChar = index > 0 ? content.charAt(index - 1) : '';
if (prevChar === '"') {
return match;
}
if (prevChar === '>') {
var findStartTagIndex = content.lastIndexOf('<', index);
if (findStartTagIndex !== -1) {
var tagHtml = content.substring(findStartTagIndex, index);
if (tagHtml.indexOf('contenteditable="false"') !== -1) {
return match;
}
}
}
return '<span class="' + cls + '" data-mce-content="' + editor.dom.encode(args[0]) + '">' + editor.dom.encode(typeof args[1] === 'string' ? args[1] : args[0]) + '</span>';
};
};
var convertRegExpsToNonEditable = function (editor, nonEditableRegExps, e) {
var i = nonEditableRegExps.length, content = e.content;
if (e.format === 'raw') {
return;
}
while (i--) {
content = content.replace(nonEditableRegExps[i], replaceMatchWithSpan(editor, content, getNonEditableClass(editor)));
}
e.content = content;
};
var setup = function (editor) {
var editClass, nonEditClass;
var contentEditableAttrName = 'contenteditable';
editClass = ' ' + global$1.trim(getEditableClass(editor)) + ' ';
nonEditClass = ' ' + global$1.trim(getNonEditableClass(editor)) + ' ';
var hasEditClass = hasClass(editClass);
var hasNonEditClass = hasClass(nonEditClass);
var nonEditableRegExps = getNonEditableRegExps(editor);
editor.on('PreInit', function () {
if (nonEditableRegExps.length > 0) {
editor.on('BeforeSetContent', function (e) {
convertRegExpsToNonEditable(editor, nonEditableRegExps, e);
});
}
editor.parser.addAttributeFilter('class', function (nodes) {
var i = nodes.length, node;
while (i--) {
node = nodes[i];
if (hasEditClass(node)) {
node.attr(contentEditableAttrName, 'true');
} else if (hasNonEditClass(node)) {
node.attr(contentEditableAttrName, 'false');
}
}
});
editor.serializer.addAttributeFilter(contentEditableAttrName, function (nodes) {
var i = nodes.length, node;
while (i--) {
node = nodes[i];
if (!hasEditClass(node) && !hasNonEditClass(node)) {
continue;
}
if (nonEditableRegExps.length > 0 && node.attr('data-mce-content')) {
node.name = '#text';
node.type = 3;
node.raw = true;
node.value = node.attr('data-mce-content');
} else {
node.attr(contentEditableAttrName, null);
}
}
});
});
};
function Plugin () {
global.add('noneditable', function (editor) {
setup(editor);
});
}
Plugin();
}());
| francbartoli/geonode | geonode/static/lib/js/plugins/noneditable/plugin.js | JavaScript | gpl-3.0 | 4,286 |
import {helper} from 'ember-helper';
import {htmlSafe} from 'ember-string';
import ghostPaths from 'ghost-admin/utils/ghost-paths';
// Handlebars Helper {{gh-path}}
// Usage: Assume 'http://www.myghostblog.org/myblog/'
// {{gh-path}} or {{gh-path 'blog'}} for Ghost's root (/myblog/)
// {{gh-path 'admin'}} for Ghost's admin root (/myblog/ghost/)
// {{gh-path 'api'}} for Ghost's api root (/myblog/ghost/api/v0.1/)
// {{gh-path 'admin' '/assets/hi.png'}} for resolved url (/myblog/ghost/assets/hi.png)
export default helper(function (params) {
let paths = ghostPaths();
let [path, url] = params;
let base;
if (!path) {
path = 'blog';
}
if (!/^(blog|admin|api)$/.test(path)) {
url = path;
path = 'blog';
}
switch (path.toString()) {
case 'blog':
base = paths.blogRoot;
break;
case 'admin':
base = paths.adminRoot;
break;
case 'api':
base = paths.apiRoot;
break;
default:
base = paths.blogRoot;
break;
}
// handle leading and trailing slashes
base = base[base.length - 1] !== '/' ? `${base}/` : base;
if (url && url.length > 0) {
if (url[0] === '/') {
url = url.substr(1);
}
base = base + url;
}
return htmlSafe(base);
});
| Elektro1776/latestEarthables | core/client/app/helpers/gh-path.js | JavaScript | gpl-3.0 | 1,375 |
var ccoding_stds_naming =
[
[ "Naming Overview", "ccoding_stds_naming.html#cstdsNaming", [
[ "Be Descriptive", "ccoding_stds_naming.html#descript", null ],
[ "Prefixes", "ccoding_stds_naming.html#prefix", null ],
[ "Component Interfaces", "ccoding_stds_naming.html#cstdsInterComponentInterfaces", null ],
[ "Module Interfaces", "ccoding_stds_naming.html#cstdsInterModuleInterfaces", null ]
] ],
[ "Files", "ccoding_stds_naming.html#cstdsFiles", null ],
[ "Macros", "ccoding_stds_naming.html#cstdsMacros", null ],
[ "Types", "ccoding_stds_name_types.html", [
[ "Suffix", "ccoding_stds_name_types.html#cstdsNameSuffix", null ],
[ "Prefix", "ccoding_stds_name_types.html#cstdsNameTypesPrefix", null ],
[ "Name", "ccoding_stds_name_types.html#cstdsNameType", null ],
[ "Cardinal Types", "ccoding_stds_name_types.html#cstdsCardinalTypes", null ],
[ "Enumeration Members", "ccoding_stds_name_types.html#cstdsEnumerationMembers", null ],
[ "Struct and Union Namespaces", "ccoding_stds_name_types.html#cstdsStructandUnionNamespaces", null ],
[ "Struct and Union Members", "ccoding_stds_name_types.html#cstdsStructandUnionMembers", null ]
] ],
[ "Functions", "ccoding_stds_name_funcs.html", [
[ "Prefix", "ccoding_stds_name_funcs.html#cstdsFuncsPrefix", null ],
[ "Camel Case", "ccoding_stds_name_funcs.html#cstdsCamelCaseName", null ],
[ "Verbage", "ccoding_stds_name_funcs.html#cstdsVerbage", null ]
] ],
[ "Variables & Function Parameters", "ccoding_stds_param.html", [
[ "Camel Case", "ccoding_stds_param.html#cstdsparamCamelCase", null ],
[ "Prefix", "ccoding_stds_param.html#cstdsparamPrefix", null ],
[ "Pointers", "ccoding_stds_param.html#cstdsparamPointers", null ],
[ "Static Variables", "ccoding_stds_param.html#cstdsparamStaticVariables", null ],
[ "Abbreviations", "ccoding_stds_param.html#cstdsparamAbbreviations", null ]
] ]
]; | legatoproject/legato-docs | 15_10/ccoding_stds_naming.js | JavaScript | mpl-2.0 | 1,987 |
var global = newGlobal();
var arrayIter = (new global.Array())[global.Symbol.iterator]();
var ArrayIteratorPrototype = Object.getPrototypeOf(arrayIter);
var arrayIterProtoBase = Object.getPrototypeOf(ArrayIteratorPrototype);
var IteratorPrototype = arrayIterProtoBase;
delete IteratorPrototype.next;
var obj = global.eval('({a: 1})')
for (var x in obj) {}
assertEq(x, "a");
| cstipkovic/spidermonkey-research | js/src/jit-test/tests/basic/cross-global-for-in.js | JavaScript | mpl-2.0 | 376 |
odoo.define('website_sale.s_products_searchbar', function (require) {
'use strict';
const concurrency = require('web.concurrency');
const publicWidget = require('web.public.widget');
const { qweb } = require('web.core');
/**
* @todo maybe the custom autocomplete logic could be extract to be reusable
*/
publicWidget.registry.productsSearchBar = publicWidget.Widget.extend({
selector: '.o_wsale_products_searchbar_form',
xmlDependencies: ['/website_sale/static/src/xml/website_sale_utils.xml'],
events: {
'input .search-query': '_onInput',
'focusout': '_onFocusOut',
'keydown .search-query': '_onKeydown',
},
autocompleteMinWidth: 300,
/**
* @constructor
*/
init: function () {
this._super.apply(this, arguments);
this._dp = new concurrency.DropPrevious();
this._onInput = _.debounce(this._onInput, 400);
this._onFocusOut = _.debounce(this._onFocusOut, 100);
},
/**
* @override
*/
start: function () {
this.$input = this.$('.search-query');
this.order = this.$('.o_wsale_search_order_by').val();
this.limit = parseInt(this.$input.data('limit'));
this.displayDescription = !!this.$input.data('displayDescription');
this.displayPrice = !!this.$input.data('displayPrice');
this.displayImage = !!this.$input.data('displayImage');
if (this.limit) {
this.$input.attr('autocomplete', 'off');
}
return this._super.apply(this, arguments);
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* @private
*/
_fetch: function () {
return this._rpc({
route: '/shop/products/autocomplete',
params: {
'term': this.$input.val(),
'options': {
'order': this.order,
'limit': this.limit,
'display_description': this.displayDescription,
'display_price': this.displayPrice,
'max_nb_chars': Math.round(Math.max(this.autocompleteMinWidth, parseInt(this.$el.width())) * 0.22),
},
},
});
},
/**
* @private
*/
_render: function (res) {
var $prevMenu = this.$menu;
this.$el.toggleClass('dropdown show', !!res);
if (res) {
var products = res['products'];
this.$menu = $(qweb.render('website_sale.productsSearchBar.autocomplete', {
products: products,
hasMoreProducts: products.length < res['products_count'],
currency: res['currency'],
widget: this,
}));
this.$menu.css('min-width', this.autocompleteMinWidth);
this.$el.append(this.$menu);
}
if ($prevMenu) {
$prevMenu.remove();
}
},
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* @private
*/
_onInput: function () {
if (!this.limit) {
return;
}
this._dp.add(this._fetch()).then(this._render.bind(this));
},
/**
* @private
*/
_onFocusOut: function () {
if (!this.$el.has(document.activeElement).length) {
this._render();
}
},
/**
* @private
*/
_onKeydown: function (ev) {
switch (ev.which) {
case $.ui.keyCode.ESCAPE:
this._render();
break;
case $.ui.keyCode.UP:
case $.ui.keyCode.DOWN:
ev.preventDefault();
if (this.$menu) {
let $element = ev.which === $.ui.keyCode.UP ? this.$menu.children().last() : this.$menu.children().first();
$element.focus();
}
break;
}
},
});
});
| ddico/odoo | addons/website_sale/static/src/snippets/s_products_searchbar/000.js | JavaScript | agpl-3.0 | 4,128 |
#!/usr/bin/env node
//
// Copyright 2012 Iris Couch, all rights reserved.
//
// Test displaying DNS records
var fs = require('fs')
var tap = require('tap')
var test = tap.test
var util = require('util')
var Message = require('../message')
test('Display a message', function(t) {
var file = 'oreilly.com-response'
fs.readFile(__dirname+'/../_test_data/'+file, function(er, data) {
if(er)
throw er
var msg = new Message(data)
, str = util.format('%s', msg)
, json = JSON.stringify(msg)
t.type(str, 'string', 'Message can stringify')
var obj = JSON.parse(util.format('%j', msg))
t.equal(obj.id, 45753, 'JSON round-trip: id')
t.equal(obj.type, 'response', 'JSON round-trip: type')
t.equal(obj.opcode, 'query', 'JSON round-trip: opcode')
t.equal(obj.authoritative, true, 'JSON round-trip: authoritative')
t.equal(obj.truncated, false, 'JSON round-trip: truncated')
t.equal(obj.recursion_desired, true, 'JSON round-trip: recursion_desired')
t.equal(obj.recursion_available, true, 'JSON round-trip: recursion_available')
t.equal(obj.responseCode, 0, 'JSON round-trip: responseCode')
t.end()
})
})
| jhs/dnsd | test/print.js | JavaScript | apache-2.0 | 1,173 |
//// [topLevelLambda.ts]
module M {
var f = () => {this.window;}
}
//// [topLevelLambda.js]
var M;
(function (M) {
var _this = this;
var f = function () {
_this.window;
};
})(M || (M = {}));
| RReverser/TSX | tests/baselines/reference/topLevelLambda.js | JavaScript | apache-2.0 | 225 |
define("dojox/editor/plugins/nls/mk/TableDialog", {
//begin v1.x content
insertTableTitle: "Вметни табела",
modifyTableTitle: "Модифицирај табела",
rows: "Редови",
columns: "Колони",
align: "Порамни:",
cellPadding: "Дополнување на ќелија:",
cellSpacing: "Растојание меѓу ќелии:",
tableWidth: "Ширина на табела:",
backgroundColor: "Боја на заднина:",
borderColor: "Боја на раб:",
borderThickness: "Дебелина на раб:",
percent: "процент",
pixels: "пиксели",
"default": "стандардно",
left: "лево",
center: "центар",
right: "десно",
buttonSet: "Постави", // translated elsewhere?
buttonInsert: "Вметни",
buttonCancel: "Откажи",
selectTableLabel: "Избери табела",
insertTableRowBeforeLabel: "Додај ред пред",
insertTableRowAfterLabel: "Додај ред после",
insertTableColumnBeforeLabel: "Додај колона пред",
insertTableColumnAfterLabel: "Додај колона после",
deleteTableRowLabel: "Избриши ред",
deleteTableColumnLabel: "Избриши колона",
colorTableCellTitle: "Боја на заднина на ќелија на табела",
tableContextMenuTitle: "Контекстуално мени на табела"
//end v1.x content
});
| Caspar12/zh.sw | zh.web.site.admin/src/main/resources/static/js/dojo/dojox/editor/plugins/nls/mk/TableDialog.js.uncompressed.js | JavaScript | apache-2.0 | 1,440 |
define("dojo/robot", ["dojo", "doh/robot", "dojo/window"], function(dojo) {
dojo.experimental("dojo.robot");
(function(){
// users who use doh+dojo get the added convenience of dojo.mouseMoveAt,
// instead of computing the absolute coordinates of their elements themselves
dojo.mixin(doh.robot,{
_resolveNode: function(/*String||DOMNode||Function*/ n){
if(typeof n == "function"){
// if the user passed a function returning a node, evaluate it
n = n();
}
return n? dojo.byId(n) : null;
},
_scrollIntoView: function(/*Node*/ n){
// scrolls the passed node into view, scrolling all ancester frames/windows as well.
// Assumes parent iframes can be made fully visible given the current browser window size
var d = dojo,
dr = doh.robot,
p = null;
d.forEach(dr._getWindowChain(n), function(w){
d.withGlobal(w, function(){
// get the position of the node wrt its parent window
// if it is a parent frame, its padding and border extents will get added in
var p2 = d.position(n, false),
b = d._getPadBorderExtents(n),
oldp = null;
// if p2 is the position of the original passed node, store the position away as p
// otherwise, node is actually an iframe. in this case, add the iframe's position wrt its parent window and also the iframe's padding and border extents
if(!p){
p = p2;
}else{
oldp = p;
p = {x: p.x+p2.x+b.l,
y: p.y+p2.y+b.t,
w: p.w,
h: p.h};
}
// scroll the parent window so that the node translated into the parent window's coordinate space is in view
dojo.window.scrollIntoView(n,p);
// adjust position for the new scroll offsets
p2 = d.position(n, false);
if(!oldp){
p = p2;
}else{
p = {x: oldp.x+p2.x+b.l,
y: oldp.y+p2.y+b.t,
w: p.w,
h: p.h};
}
// get the parent iframe so it can be scrolled too
n = w.frameElement;
});
});
},
_position: function(/*Node*/ n){
// Returns the dojo.position of the passed node wrt the passed window's viewport,
// following any parent iframes containing the node and clipping the node to each iframe.
// precondition: _scrollIntoView already called
var d = dojo, p = null, M = Math.max, m = Math.min;
// p: the returned position of the node
d.forEach(doh.robot._getWindowChain(n), function(w){
d.withGlobal(w, function(){
// get the position of the node wrt its parent window
// if it is a parent frame, its padding and border extents will get added in
var p2 = d.position(n, false), b = d._getPadBorderExtents(n);
// if p2 is the position of the original passed node, store the position away as p
// otherwise, node is actually an iframe. in this case, add the iframe's position wrt its parent window and also the iframe's padding and border extents
if(!p){
p = p2;
}else{
var view;
d.withGlobal(n.contentWindow,function(){
view=dojo.window.getBox();
});
p2.r = p2.x+view.w;
p2.b = p2.y+view.h;
p = {x: M(p.x+p2.x,p2.x)+b.l, // clip left edge of node wrt the iframe
y: M(p.y+p2.y,p2.y)+b.t, // top edge
r: m(p.x+p2.x+p.w,p2.r)+b.l, // right edge (to compute width)
b: m(p.y+p2.y+p.h,p2.b)+b.t}; // bottom edge (to compute height)
// save a few bytes by computing width and height from r and b
p.w = p.r-p.x;
p.h = p.b-p.y;
}
// the new node is now the old node's parent iframe
n=w.frameElement;
});
});
return p;
},
_getWindowChain : function(/*Node*/ n){
// Returns an array of windows starting from the passed node's parent window and ending at dojo's window
var cW = dojo.window.get(n.ownerDocument);
var arr=[cW];
var f = cW.frameElement;
return (cW == dojo.global || f == null)? arr : arr.concat(doh.robot._getWindowChain(f));
},
scrollIntoView : function(/*String||DOMNode||Function*/ node, /*Number, optional*/ delay){
// summary:
// Scroll the passed node into view, if it is not.
//
// node:
// The id of the node, or the node itself, to move the mouse to.
// If you pass an id or a function that returns a node, the node will not be evaluated until the movement executes.
// This is useful if you need to move the mouse to an node that is not yet present.
//
// delay:
// Delay, in milliseconds, to wait before firing.
// The delay is a delta with respect to the previous automation call.
//
doh.robot.sequence(function(){
doh.robot._scrollIntoView(doh.robot._resolveNode(node));
}, delay);
},
mouseMoveAt : function(/*String||DOMNode||Function*/ node, /*Integer, optional*/ delay, /*Integer, optional*/ duration, /*Number, optional*/ offsetX, /*Number, optional*/ offsetY){
// summary:
// Moves the mouse over the specified node at the specified relative x,y offset.
//
// description:
// Moves the mouse over the specified node at the specified relative x,y offset.
// If you do not specify an offset, mouseMove will default to move to the middle of the node.
// Example: to move the mouse over a ComboBox's down arrow node, call doh.mouseMoveAt(dijit.byId('setvaluetest').downArrowNode);
//
// node:
// The id of the node, or the node itself, to move the mouse to.
// If you pass an id or a function that returns a node, the node will not be evaluated until the movement executes.
// This is useful if you need to move the mouse to an node that is not yet present.
//
// delay:
// Delay, in milliseconds, to wait before firing.
// The delay is a delta with respect to the previous automation call.
// For example, the following code ends after 600ms:
// doh.robot.mouseClick({left:true}, 100) // first call; wait 100ms
// doh.robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
//
// duration:
// Approximate time Robot will spend moving the mouse
// The default is 100ms.
//
// offsetX:
// x offset relative to the node, in pixels, to move the mouse. The default is half the node's width.
//
// offsetY:
// y offset relative to the node, in pixels, to move the mouse. The default is half the node's height.
//
doh.robot._assertRobot();
duration = duration||100;
this.sequence(function(){
node=doh.robot._resolveNode(node);
doh.robot._scrollIntoView(node);
var pos = doh.robot._position(node);
if(offsetY === undefined){
offsetX=pos.w/2;
offsetY=pos.h/2;
}
var x = pos.x+offsetX;
var y = pos.y+offsetY;
doh.robot._mouseMove(x, y, false, duration);
}, delay, duration);
}
});
})();
return doh.robot;
});
| sulistionoadi/belajar-springmvc-dojo | training-web/src/main/webapp/js/dojotoolkit/dojo/robot.js | JavaScript | apache-2.0 | 6,577 |
(function($) {
$.fn.toc = function(options) {
var self = this;
var opts = $.extend({}, jQuery.fn.toc.defaults, options);
var container = $(opts.container);
var headings = $(opts.selectors, container);
var activeClassName = opts.prefix+'-active';
var scrollTo = function(e) {
if (opts.smoothScrolling) {
e.preventDefault();
var elScrollTo = $(e.target).attr('href');
var $el = $(elScrollTo.replace(":", "\\:"));
var callbackCalled = false;
$('body,html').animate({ scrollTop: $el.offset().top - opts.scrollOffset }, 400, 'swing', function(e) {
location.hash = elScrollTo;
if (!callbackCalled){
opts.onScrollFinish.call(self);
callbackCalled = true;
}
});
}
$('li', self).removeClass(activeClassName);
$(e.target).parent().addClass(activeClassName);
};
//highlight on scroll
var timeout;
var highlightOnScroll = function(e) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
var top = $(window).scrollTop(),
highlighted;
headings.each(function(i, heading) {
var $h = $(heading);
var htop = $h.offset().top - opts.highlightOffset;
if (htop >= top) {
$('li', self).removeClass(activeClassName);
highlighted = $('li:eq('+(i)+')', self).addClass(activeClassName);
opts.onHighlight(highlighted);
return false;
}
});
}, 50);
};
if (opts.highlightOnScroll) {
$(window).bind('scroll', highlightOnScroll);
highlightOnScroll();
}
//Perform search and hide unmatched elements
var tocList;
var treeObject = {};
//Create the tree
var createTree = function(ul) {
var prevLevel = {level: -1, index: -1, parent: -1, val: ''};
var levelParent = {0: -1};
tocList = ul.children("li");
tocList.each(function(i) {
var me = $(this).removeClass("toc-active");
var currentLevel = parseInt(me.attr('class').trim().slice(-1));
if (currentLevel > prevLevel.level) {
currentParent = prevLevel.index;
} else if (currentLevel == prevLevel.level) {
currentParent = prevLevel.parent;
} else if (currentLevel < prevLevel.level) {
currentParent = levelParent[currentLevel] || prevLevel.parent;
}
levelParent[currentLevel] = currentParent;
var currentVal = $('a', this).text().trim().toLowerCase();
treeObject[i] = {
val: currentVal,
level: currentLevel,
parent: currentParent
}
prevLevel = {index: i, val: currentVal, level: currentLevel, parent: currentParent};
});
}
//Show the parents recursively
var showParents = function(key) {
var me = treeObject[key];
if (me.parent > -1) {
$(tocList[me.parent]).show();
showParents(me.parent);
}
};
//Perform the search
var search = function(searchVal) {
searchVal = searchVal.trim().toLowerCase();
for (var key in treeObject) {
var me = treeObject[key];
if (me.val.indexOf(searchVal) !== -1 || searchVal.length == 0) {
$(tocList[key]).show();
if ($(tocList[me.parent]).is(":hidden")) {
showParents(key);
}
} else {
$(tocList[key]).hide();
}
}
}
return this.each(function() {
//build TOC
var el = $(this);
var searchVal = '';
var searchForm = $("<form/>", {class: "form-search quick-search"})
.append($("<input/>", {type: "text", class: "input-medium search-query", placeholder: "Quick Search"}))
.append($("<i/>", {class: "icon icon-search search-icon"}));
searchForm.css({'position': 'fixed', 'top': '45px', 'padding-right': '20px'});
$(".search-icon", searchForm).css({'marginLeft': '-20px', 'marginTop': '3px'});
var ul = $('<ul/>');
headings.each(function(i, heading) {
var $h = $(heading);
//add anchor
var anchor = $('<span/>').attr('id', opts.anchorName(i, heading, opts.prefix)).insertBefore($h);
//build TOC item
var a = $('<a/>')
.text(opts.headerText(i, heading, $h))
.attr('href', '#' + opts.anchorName(i, heading, opts.prefix))
.bind('click', function(e) {
scrollTo(e);
el.trigger('selected', $(this).attr('href'));
});
var li = $('<li/>')
.addClass(opts.itemClass(i, heading, $h, opts.prefix))
.append(a);
ul.append(li);
});
el.html(ul);
el.parent().prepend(searchForm);
el.css({'top': '80px'});
//create the tree
createTree(ul)
//set intent timer
var intentTimer;
var accumulatedTime = 0;
//bind quick search
el.siblings('.quick-search').children('.search-query').bind('keyup', function(e) {
if (accumulatedTime < 1000) {
window.clearTimeout(intentTimer);
}
var me = $(this);
if (me.val().length > 0) {
$(".search-icon").removeClass("icon-search").addClass("icon-remove-circle").css('cursor', 'pointer');
} else {
$(".search-icon").removeClass("icon-remove-circle").addClass("icon-search").css('cursor', 'auto');
}
var intentTime = 500 - (me.val().length * 10);
accumulatedTime += intentTime;
intentTimer = window.setTimeout(function() {
if (searchVal == me.val()) {
return false;
}
searchVal = me.val();
search(me.val());
accumulatedTime = 0;
}, intentTime);
});
// Make text clear icon work
$(".search-icon").click(function(e) {
if($(this).hasClass('icon-remove-circle')) {
$('.search-query').val('').trigger('keyup');
} else {
$('.search-query').focus();
}
});
//set positions of search box and TOC
var navHeight = $(".navbar").height();
var searchHeight = $(".quick-search").height();
$(".quick-search").css({'top': navHeight + 10 + 'px', 'position': 'fixed'});
el.css('top', navHeight + searchHeight + 15 + 'px');
});
};
jQuery.fn.toc.defaults = {
container: 'body',
selectors: 'h1,h2,h3',
smoothScrolling: true,
prefix: 'toc',
scrollOffset: 0,
onHighlight: function() {},
highlightOnScroll: true,
highlightOffset: 10,
anchorName: function(i, heading, prefix) {
return prefix+i;
},
headerText: function(i, heading, $heading) {
return $heading.text();
},
itemClass: function(i, heading, $heading, prefix) {
return prefix + '-' + $heading[0].tagName.toLowerCase();
}
};
})(jQuery);
| sconway/pulley-scroll | js/scroll-magic/docs/scripts/toc.js | JavaScript | apache-2.0 | 6,511 |
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['jquery.sap.global','sap/ui/core/ComponentContainer'],function(q,C){"use strict";var $=q,_=false,a=null,b=null;return{start:function(c){if(_){throw"sap.ui.test.launchers.componentLauncher: Start was called twice without teardown";}c.async=true;var p=sap.ui.component(c);_=true;return p.then(function(o){var i=q.sap.uid();b=$('<div id="'+i+'" class="sapUiOpaComponent"></div>');$("body").append(b).addClass("sapUiOpaBodyComponent");a=new C({component:o});a.placeAt(i);});},hasLaunched:function(){return _;},teardown:function(){if(!_){throw"sap.ui.test.launchers.componentLauncher: Teardown has been called but there was no start";}a.destroy();b.remove();_=false;$("body").removeClass("sapUiOpaBodyComponent");}};},true);
| and1985129/digitalofficemobile | www/lib/ui5/sap/ui/test/launchers/componentLauncher.js | JavaScript | apache-2.0 | 921 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Contains the third and last part of the {@link CKEDITOR} object
* definition.
*/
// Remove the CKEDITOR.loadFullCore reference defined on ckeditor_basic.
delete CKEDITOR.loadFullCore;
/**
* Holds references to all editor instances created. The name of the properties
* in this object correspond to instance names, and their values contains the
* {@link CKEDITOR.editor} object representing them.
* @type {Object}
* @example
* alert( <b>CKEDITOR.instances</b>.editor1.name ); // "editor1"
*/
CKEDITOR.instances = {};
/**
* The document of the window holding the CKEDITOR object.
* @type {CKEDITOR.dom.document}
* @example
* alert( <b>CKEDITOR.document</b>.getBody().getName() ); // "body"
*/
CKEDITOR.document = new CKEDITOR.dom.document( document );
/**
* Adds an editor instance to the global {@link CKEDITOR} object. This function
* is available for internal use mainly.
* @param {CKEDITOR.editor} editor The editor instance to be added.
* @example
*/
CKEDITOR.add = function( editor )
{
CKEDITOR.instances[ editor.name ] = editor;
editor.on( 'focus', function()
{
if ( CKEDITOR.currentInstance != editor )
{
CKEDITOR.currentInstance = editor;
CKEDITOR.fire( 'currentInstance' );
}
});
editor.on( 'blur', function()
{
if ( CKEDITOR.currentInstance == editor )
{
CKEDITOR.currentInstance = null;
CKEDITOR.fire( 'currentInstance' );
}
});
};
/**
* Removes an editor instance from the global {@link CKEDITOR} object. This function
* is available for internal use only. External code must use {@link CKEDITOR.editor.prototype.destroy}
* to avoid memory leaks.
* @param {CKEDITOR.editor} editor The editor instance to be removed.
* @example
*/
CKEDITOR.remove = function( editor )
{
delete CKEDITOR.instances[ editor.name ];
};
/**
* Perform global clean up to free as much memory as possible
* when there are no instances left
*/
CKEDITOR.on( 'instanceDestroyed', function ()
{
if ( CKEDITOR.tools.isEmpty( this.instances ) )
CKEDITOR.fire( 'reset' );
});
// Load the bootstrap script.
CKEDITOR.loader.load( 'core/_bootstrap' ); // @Packager.RemoveLine
// Tri-state constants.
/**
* Used to indicate the ON or ACTIVE state.
* @constant
* @example
*/
CKEDITOR.TRISTATE_ON = 1;
/**
* Used to indicate the OFF or NON ACTIVE state.
* @constant
* @example
*/
CKEDITOR.TRISTATE_OFF = 2;
/**
* Used to indicate DISABLED state.
* @constant
* @example
*/
CKEDITOR.TRISTATE_DISABLED = 0;
/**
* The editor which is currently active (have user focus).
* @name CKEDITOR.currentInstance
* @type CKEDITOR.editor
* @see CKEDITOR#currentInstance
* @example
* function showCurrentEditorName()
* {
* if ( CKEDITOR.currentInstance )
* alert( CKEDITOR.currentInstance.name );
* else
* alert( 'Please focus an editor first.' );
* }
*/
/**
* Fired when the CKEDITOR.currentInstance object reference changes. This may
* happen when setting the focus on different editor instances in the page.
* @name CKEDITOR#currentInstance
* @event
* var editor; // Variable to hold a reference to the current editor.
* CKEDITOR.on( 'currentInstance' , function( e )
* {
* editor = CKEDITOR.currentInstance;
* });
*/
/**
* Fired when the last instance has been destroyed. This event is used to perform
* global memory clean up.
* @name CKEDITOR#reset
* @event
*/
| Videl/ALK | web/ckeditor/_source/core/ckeditor.js | JavaScript | mit | 3,716 |
/**
@module breeze
**/
var EntityAction = (function () {
/**
EntityAction is an 'Enum' containing all of the valid actions that can occur to an 'Entity'.
@class EntityAction
@static
**/
var entityActionMethods = {
isAttach: function () {
return !!this.isAttach;
},
isDetach: function () {
return !!this.isDetach;
},
isModification: function () {
return !!this.isModification;
}
};
var EntityAction = new Enum("EntityAction", entityActionMethods);
/**
Attach - Entity was attached via an AttachEntity call.
@property Attach {EntityAction}
@final
@static
**/
EntityAction.Attach = EntityAction.addSymbol({ isAttach: true});
/**
AttachOnQuery - Entity was attached as a result of a query.
@property AttachOnQuery {EntityAction}
@final
@static
**/
EntityAction.AttachOnQuery = EntityAction.addSymbol({ isAttach: true});
/**
AttachOnImport - Entity was attached as a result of an import.
@property AttachOnImport {EntityAction}
@final
@static
**/
EntityAction.AttachOnImport = EntityAction.addSymbol({ isAttach: true});
/**
Detach - Entity was detached.
@property Detach {EntityAction}
@final
@static
**/
EntityAction.Detach = EntityAction.addSymbol({ isDetach: true });
/**
MergeOnQuery - Properties on the entity were merged as a result of a query.
@property MergeOnQuery {EntityAction}
@final
@static
**/
EntityAction.MergeOnQuery = EntityAction.addSymbol({ isModification: true });
/**
MergeOnImport - Properties on the entity were merged as a result of an import.
@property MergeOnImport {EntityAction}
@final
@static
**/
EntityAction.MergeOnImport = EntityAction.addSymbol({ isModification: true });
/**
MergeOnSave - Properties on the entity were merged as a result of a save
@property MergeOnSave {EntityAction}
@final
@static
**/
EntityAction.MergeOnSave = EntityAction.addSymbol({ isModification: true });
/**
PropertyChange - A property on the entity was changed.
@property PropertyChange {EntityAction}
@final
@static
**/
EntityAction.PropertyChange = EntityAction.addSymbol({ isModification: true});
/**
EntityStateChange - The EntityState of the entity was changed.
@property EntityStateChange {EntityAction}
@final
@static
**/
EntityAction.EntityStateChange = EntityAction.addSymbol();
/**
AcceptChanges - AcceptChanges was called on the entity, or its entityState was set to Unmodified.
@property AcceptChanges {EntityAction}
@final
@static
**/
EntityAction.AcceptChanges = EntityAction.addSymbol();
/**
RejectChanges - RejectChanges was called on the entity.
@property RejectChanges {EntityAction}
@final
@static
**/
EntityAction.RejectChanges = EntityAction.addSymbol({ isModification: true});
/**
Clear - The EntityManager was cleared. All entities detached.
@property Clear {EntityAction}
@final
@static
**/
EntityAction.Clear = EntityAction.addSymbol({ isDetach: true});
EntityAction.resolveSymbols();
return EntityAction;
})();
breeze.EntityAction = EntityAction;
| edigitalresearch/breeze.js | src/a30_entityAction.js | JavaScript | mit | 3,148 |
/**
* Globalize v1.4.0-alpha.2
*
* http://github.com/jquery/globalize
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2018-03-09T13:51Z
*/
/*!
* Globalize v1.4.0-alpha.2 2018-03-09T13:51Z Released under the MIT license
* http://git.io/TrdQbw
*/
(function( root, factory ) {
// UMD returnExports
if ( typeof define === "function" && define.amd ) {
// AMD
define([
"cldr",
"../globalize",
"./number",
"cldr/event",
"cldr/supplemental"
], factory );
} else if ( typeof exports === "object" ) {
// Node, CommonJS
module.exports = factory( require( "cldrjs" ), require( "../globalize" ) );
} else {
// Extend global
factory( root.Cldr, root.Globalize );
}
}(this, function( Cldr, Globalize ) {
var createError = Globalize._createError,
createErrorUnsupportedFeature = Globalize._createErrorUnsupportedFeature,
formatMessage = Globalize._formatMessage,
isPlainObject = Globalize._isPlainObject,
looseMatching = Globalize._looseMatching,
numberNumberingSystemDigitsMap = Globalize._numberNumberingSystemDigitsMap,
numberSymbol = Globalize._numberSymbol,
regexpEscape = Globalize._regexpEscape,
removeLiteralQuotes = Globalize._removeLiteralQuotes,
runtimeBind = Globalize._runtimeBind,
stringPad = Globalize._stringPad,
validate = Globalize._validate,
validateCldr = Globalize._validateCldr,
validateDefaultLocale = Globalize._validateDefaultLocale,
validateParameterPresence = Globalize._validateParameterPresence,
validateParameterType = Globalize._validateParameterType,
validateParameterTypePlainObject = Globalize._validateParameterTypePlainObject,
validateParameterTypeString = Globalize._validateParameterTypeString;
var validateParameterTypeDate = function( value, name ) {
validateParameterType( value, name, value === undefined || value instanceof Date, "Date" );
};
var createErrorInvalidParameterValue = function( name, value ) {
return createError( "E_INVALID_PAR_VALUE", "Invalid `{name}` value ({value}).", {
name: name,
value: value
});
};
/**
* Create a map between the skeleton fields and their positions, e.g.,
* {
* G: 0
* y: 1
* ...
* }
*/
var validateSkeletonFieldsPosMap = "GyYuUrQqMLlwWEecdDFghHKkmsSAzZOvVXx".split( "" ).reduce(function( memo, item, i ) {
memo[ item ] = i;
return memo;
}, {});
/**
* validateSkeleton( skeleton )
*
* skeleton: Assume `j` has already been converted into a localized hour field.
*/
var validateSkeleton = function validateSkeleton( skeleton ) {
var last,
// Using easier to read variable.
fieldsPosMap = validateSkeletonFieldsPosMap;
// "The fields are from the Date Field Symbol Table in Date Format Patterns"
// Ref: http://www.unicode.org/reports/tr35/tr35-dates.html#availableFormats_appendItems
// I.e., check for invalid characters.
skeleton.replace( /[^GyYuUrQqMLlwWEecdDFghHKkmsSAzZOvVXx]/, function( field ) {
throw createError(
"E_INVALID_OPTIONS", "Invalid field `{invalidField}` of skeleton `{value}`",
{
invalidField: field,
type: "skeleton",
value: skeleton
}
);
});
// "The canonical order is from top to bottom in that table; that is, yM not My".
// http://www.unicode.org/reports/tr35/tr35-dates.html#availableFormats_appendItems
// I.e., check for invalid order.
skeleton.split( "" ).every(function( field ) {
if ( fieldsPosMap[ field ] < last ) {
throw createError(
"E_INVALID_OPTIONS", "Invalid order `{invalidField}` of skeleton `{value}`",
{
invalidField: field,
type: "skeleton",
value: skeleton
}
);
}
last = fieldsPosMap[ field ];
return true;
});
};
/**
* Returns a new object created by using `object`'s values as keys, and the keys as values.
*/
var objectInvert = function( object, fn ) {
fn = fn || function( object, key, value ) {
object[ value ] = key;
return object;
};
return Object.keys( object ).reduce(function( newObject, key ) {
return fn( newObject, key, object[ key ] );
}, {});
};
// Invert key and values, e.g., {"e": "eEc"} ==> {"e": "e", "E": "e", "c": "e"}.
var dateExpandPatternSimilarFieldsMap = objectInvert({
"e": "eEc",
"L": "ML"
}, function( object, key, value ) {
value.split( "" ).forEach(function( field ) {
object[ field ] = key;
});
return object;
});
var dateExpandPatternNormalizePatternType = function( character ) {
return dateExpandPatternSimilarFieldsMap[ character ] || character;
};
var datePatternRe = ( /([a-z])\1*|'([^']|'')+'|''|./ig );
var stringRepeat = function( str, count ) {
var i, result = "";
for ( i = 0; i < count; i++ ) {
result = result + str;
}
return result;
};
var dateExpandPatternAugmentFormat = function( requestedSkeleton, bestMatchFormat ) {
var i, j, matchedType, matchedLength, requestedType, requestedLength,
// Using an easier to read variable.
normalizePatternType = dateExpandPatternNormalizePatternType;
requestedSkeleton = requestedSkeleton.match( datePatternRe );
bestMatchFormat = bestMatchFormat.match( datePatternRe );
for ( i = 0; i < bestMatchFormat.length; i++ ) {
matchedType = bestMatchFormat[i].charAt( 0 );
matchedLength = bestMatchFormat[i].length;
for ( j = 0; j < requestedSkeleton.length; j++ ) {
requestedType = requestedSkeleton[j].charAt( 0 );
requestedLength = requestedSkeleton[j].length;
if ( normalizePatternType( matchedType ) === normalizePatternType( requestedType ) &&
matchedLength < requestedLength
) {
bestMatchFormat[i] = stringRepeat( matchedType, requestedLength );
}
}
}
return bestMatchFormat.join( "" );
};
var dateExpandPatternCompareFormats = function( formatA, formatB ) {
var a, b, distance, lenA, lenB, typeA, typeB, i, j,
// Using easier to read variables.
normalizePatternType = dateExpandPatternNormalizePatternType;
if ( formatA === formatB ) {
return 0;
}
formatA = formatA.match( datePatternRe );
formatB = formatB.match( datePatternRe );
if ( formatA.length !== formatB.length ) {
return -1;
}
distance = 1;
for ( i = 0; i < formatA.length; i++ ) {
a = formatA[ i ].charAt( 0 );
typeA = normalizePatternType( a );
typeB = null;
for ( j = 0; j < formatB.length; j++ ) {
b = formatB[ j ].charAt( 0 );
typeB = normalizePatternType( b );
if ( typeA === typeB ) {
break;
} else {
typeB = null;
}
}
if ( typeB === null ) {
return -1;
}
lenA = formatA[ i ].length;
lenB = formatB[ j ].length;
distance = distance + Math.abs( lenA - lenB );
// Most symbols have a small distance from each other, e.g., M ≅ L; E ≅ c; a ≅ b ≅ B;
// H ≅ k ≅ h ≅ K; ...
if ( a !== b ) {
distance += 1;
}
// Numeric (l<3) and text fields (l>=3) are given a larger distance from each other.
if ( ( lenA < 3 && lenB >= 3 ) || ( lenA >= 3 && lenB < 3 ) ) {
distance += 20;
}
}
return distance;
};
var dateExpandPatternGetBestMatchPattern = function( cldr, askedSkeleton ) {
var availableFormats, pattern, ratedFormats, skeleton,
path = "dates/calendars/gregorian/dateTimeFormats/availableFormats",
// Using easier to read variables.
augmentFormat = dateExpandPatternAugmentFormat,
compareFormats = dateExpandPatternCompareFormats;
pattern = cldr.main([ path, askedSkeleton ]);
if ( askedSkeleton && !pattern ) {
availableFormats = cldr.main([ path ]);
ratedFormats = [];
for ( skeleton in availableFormats ) {
ratedFormats.push({
skeleton: skeleton,
pattern: availableFormats[ skeleton ],
rate: compareFormats( askedSkeleton, skeleton )
});
}
ratedFormats = ratedFormats
.filter( function( format ) {
return format.rate > -1;
} )
.sort( function( formatA, formatB ) {
return formatA.rate - formatB.rate;
});
if ( ratedFormats.length ) {
pattern = augmentFormat( askedSkeleton, ratedFormats[0].pattern );
}
}
return pattern;
};
/**
* expandPattern( options, cldr )
*
* @options [Object] if String, it's considered a skeleton. Object accepts:
* - skeleton: [String] lookup availableFormat;
* - date: [String] ( "full" | "long" | "medium" | "short" );
* - time: [String] ( "full" | "long" | "medium" | "short" );
* - datetime: [String] ( "full" | "long" | "medium" | "short" );
* - raw: [String] For more info see datetime/format.js.
*
* @cldr [Cldr instance].
*
* Return the corresponding pattern.
* Eg for "en":
* - "GyMMMd" returns "MMM d, y G";
* - { skeleton: "GyMMMd" } returns "MMM d, y G";
* - { date: "full" } returns "EEEE, MMMM d, y";
* - { time: "full" } returns "h:mm:ss a zzzz";
* - { datetime: "full" } returns "EEEE, MMMM d, y 'at' h:mm:ss a zzzz";
* - { raw: "dd/mm" } returns "dd/mm";
*/
var dateExpandPattern = function( options, cldr ) {
var dateSkeleton, result, skeleton, timeSkeleton, type,
// Using easier to read variables.
getBestMatchPattern = dateExpandPatternGetBestMatchPattern;
function combineDateTime( type, datePattern, timePattern ) {
return formatMessage(
cldr.main([
"dates/calendars/gregorian/dateTimeFormats",
type
]),
[ timePattern, datePattern ]
);
}
switch ( true ) {
case "skeleton" in options:
skeleton = options.skeleton;
// Preferred hour (j).
skeleton = skeleton.replace( /j/g, function() {
return cldr.supplemental.timeData.preferred();
});
validateSkeleton( skeleton );
// Try direct map (note that getBestMatchPattern handles it).
// ... or, try to "best match" the whole skeleton.
result = getBestMatchPattern(
cldr,
skeleton
);
if ( result ) {
break;
}
// ... or, try to "best match" the date and time parts individually.
timeSkeleton = skeleton.split( /[^hHKkmsSAzZOvVXx]/ ).slice( -1 )[ 0 ];
dateSkeleton = skeleton.split( /[^GyYuUrQqMLlwWdDFgEec]/ )[ 0 ];
dateSkeleton = getBestMatchPattern(
cldr,
dateSkeleton
);
timeSkeleton = getBestMatchPattern(
cldr,
timeSkeleton
);
if ( /(MMMM|LLLL).*[Ec]/.test( dateSkeleton ) ) {
type = "full";
} else if ( /MMMM|LLLL/.test( dateSkeleton ) ) {
type = "long";
} else if ( /MMM|LLL/.test( dateSkeleton ) ) {
type = "medium";
} else {
type = "short";
}
if ( dateSkeleton && timeSkeleton ) {
result = combineDateTime( type, dateSkeleton, timeSkeleton );
} else {
result = dateSkeleton || timeSkeleton;
}
break;
case "date" in options:
case "time" in options:
result = cldr.main([
"dates/calendars/gregorian",
"date" in options ? "dateFormats" : "timeFormats",
( options.date || options.time )
]);
break;
case "datetime" in options:
result = combineDateTime( options.datetime,
cldr.main([ "dates/calendars/gregorian/dateFormats", options.datetime ]),
cldr.main([ "dates/calendars/gregorian/timeFormats", options.datetime ])
);
break;
case "raw" in options:
result = options.raw;
break;
default:
throw createErrorInvalidParameterValue({
name: "options",
value: options
});
}
return result;
};
var dateWeekDays = [ "sun", "mon", "tue", "wed", "thu", "fri", "sat" ];
/**
* firstDayOfWeek
*/
var dateFirstDayOfWeek = function( cldr ) {
return dateWeekDays.indexOf( cldr.supplemental.weekData.firstDay() );
};
/**
* getTimeZoneName( length, type )
*/
var dateGetTimeZoneName = function( length, type, timeZone, cldr ) {
var metaZone, result;
if ( !timeZone ) {
return;
}
result = cldr.main([
"dates/timeZoneNames/zone",
timeZone,
length < 4 ? "short" : "long",
type
]);
if ( result ) {
return result;
}
// The latest metazone data of the metazone array.
// TODO expand to support the historic metazones based on the given date.
metaZone = cldr.supplemental([
"metaZones/metazoneInfo/timezone", timeZone, 0,
"usesMetazone/_mzone"
]);
return cldr.main([
"dates/timeZoneNames/metazone",
metaZone,
length < 4 ? "short" : "long",
type
]);
};
/**
* timezoneHourFormatShortH( hourFormat )
*
* @hourFormat [String]
*
* Unofficial deduction of the short hourFormat given time zone `hourFormat` element.
* Official spec is pending resolution: http://unicode.org/cldr/trac/ticket/8293
*
* Example:
* - "+HH.mm;-HH.mm" => "+H;-H"
* - "+HH:mm;-HH:mm" => "+H;-H"
* - "+HH:mm;−HH:mm" => "+H;−H" (Note MINUS SIGN \u2212)
* - "+HHmm;-HHmm" => "+H:-H"
*/
var dateTimezoneHourFormatH = function( hourFormat ) {
return hourFormat
.split( ";" )
.map(function( format ) {
return format.slice( 0, format.indexOf( "H" ) + 1 );
})
.join( ";" );
};
/**
* timezoneHourFormatLongHm( hourFormat )
*
* @hourFormat [String]
*
* Unofficial deduction of the short hourFormat given time zone `hourFormat` element.
* Official spec is pending resolution: http://unicode.org/cldr/trac/ticket/8293
*
* Example (hFormat === "H"): (used for short Hm)
* - "+HH.mm;-HH.mm" => "+H.mm;-H.mm"
* - "+HH:mm;-HH:mm" => "+H:mm;-H:mm"
* - "+HH:mm;−HH:mm" => "+H:mm;−H:mm" (Note MINUS SIGN \u2212)
* - "+HHmm;-HHmm" => "+Hmm:-Hmm"
*
* Example (hFormat === "HH": (used for long Hm)
* - "+HH.mm;-HH.mm" => "+HH.mm;-HH.mm"
* - "+HH:mm;-HH:mm" => "+HH:mm;-HH:mm"
* - "+H:mm;-H:mm" => "+HH:mm;-HH:mm"
* - "+HH:mm;−HH:mm" => "+HH:mm;−HH:mm" (Note MINUS SIGN \u2212)
* - "+HHmm;-HHmm" => "+HHmm:-HHmm"
*/
var dateTimezoneHourFormatHm = function( hourFormat, hFormat ) {
return hourFormat
.split( ";" )
.map(function( format ) {
var parts = format.split( /H+/ );
parts.splice( 1, 0, hFormat );
return parts.join( "" );
})
.join( ";" );
};
var runtimeCacheDataBind = function( key, data ) {
var fn = function() {
return data;
};
fn.dataCacheKey = key;
return fn;
};
/**
* properties( pattern, cldr )
*
* @pattern [String] raw pattern.
* ref: http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns
*
* @cldr [Cldr instance].
*
* Return the properties given the pattern and cldr.
*
* TODO Support other calendar types.
*/
var dateFormatProperties = function( pattern, cldr, timeZone ) {
var properties = {
numberFormatters: {},
pattern: pattern,
timeSeparator: numberSymbol( "timeSeparator", cldr )
},
widths = [ "abbreviated", "wide", "narrow" ];
function setNumberFormatterPattern( pad ) {
properties.numberFormatters[ pad ] = stringPad( "", pad );
}
if ( timeZone ) {
properties.timeZoneData = runtimeCacheDataBind( "iana/" + timeZone, {
offsets: cldr.get([ "globalize-iana/zoneData", timeZone, "offsets" ]),
untils: cldr.get([ "globalize-iana/zoneData", timeZone, "untils" ]),
isdsts: cldr.get([ "globalize-iana/zoneData", timeZone, "isdsts" ])
});
}
pattern.replace( datePatternRe, function( current ) {
var aux, chr, daylightTzName, formatNumber, genericTzName, length, standardTzName;
chr = current.charAt( 0 );
length = current.length;
if ( chr === "j" ) {
// Locale preferred hHKk.
// http://www.unicode.org/reports/tr35/tr35-dates.html#Time_Data
properties.preferredTime = chr = cldr.supplemental.timeData.preferred();
}
// ZZZZ: same as "OOOO".
if ( chr === "Z" && length === 4 ) {
chr = "O";
length = 4;
}
// z...zzz: "{shortRegion}", eg. "PST" or "PDT".
// zzzz: "{regionName} {Standard Time}" or "{regionName} {Daylight Time}",
// e.g., "Pacific Standard Time" or "Pacific Daylight Time".
// http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns
if ( chr === "z" ) {
standardTzName = dateGetTimeZoneName( length, "standard", timeZone, cldr );
daylightTzName = dateGetTimeZoneName( length, "daylight", timeZone, cldr );
if ( standardTzName ) {
properties.standardTzName = standardTzName;
}
if ( daylightTzName ) {
properties.daylightTzName = daylightTzName;
}
// Fall through the "O" format in case one name is missing.
if ( !standardTzName || !daylightTzName ) {
chr = "O";
if ( length < 4 ) {
length = 1;
}
}
}
// v...vvv: "{shortRegion}", eg. "PT".
// vvvv: "{regionName} {Time}" or "{regionName} {Time}",
// e.g., "Pacific Time"
// http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns
if ( chr === "v" ) {
genericTzName = dateGetTimeZoneName( length, "generic", timeZone, cldr );
// Fall back to "V" format.
if ( !genericTzName ) {
chr = "V";
length = 4;
}
}
switch ( chr ) {
// Era
case "G":
properties.eras = cldr.main([
"dates/calendars/gregorian/eras",
length <= 3 ? "eraAbbr" : ( length === 4 ? "eraNames" : "eraNarrow" )
]);
break;
// Year
case "y":
// Plain year.
formatNumber = true;
break;
case "Y":
// Year in "Week of Year"
properties.firstDay = dateFirstDayOfWeek( cldr );
properties.minDays = cldr.supplemental.weekData.minDays();
formatNumber = true;
break;
case "u": // Extended year. Need to be implemented.
case "U": // Cyclic year name. Need to be implemented.
throw createErrorUnsupportedFeature({
feature: "year pattern `" + chr + "`"
});
// Quarter
case "Q":
case "q":
if ( length > 2 ) {
if ( !properties.quarters ) {
properties.quarters = {};
}
if ( !properties.quarters[ chr ] ) {
properties.quarters[ chr ] = {};
}
properties.quarters[ chr ][ length ] = cldr.main([
"dates/calendars/gregorian/quarters",
chr === "Q" ? "format" : "stand-alone",
widths[ length - 3 ]
]);
} else {
formatNumber = true;
}
break;
// Month
case "M":
case "L":
if ( length > 2 ) {
if ( !properties.months ) {
properties.months = {};
}
if ( !properties.months[ chr ] ) {
properties.months[ chr ] = {};
}
properties.months[ chr ][ length ] = cldr.main([
"dates/calendars/gregorian/months",
chr === "M" ? "format" : "stand-alone",
widths[ length - 3 ]
]);
} else {
formatNumber = true;
}
break;
// Week - Week of Year (w) or Week of Month (W).
case "w":
case "W":
properties.firstDay = dateFirstDayOfWeek( cldr );
properties.minDays = cldr.supplemental.weekData.minDays();
formatNumber = true;
break;
// Day
case "d":
case "D":
case "F":
formatNumber = true;
break;
case "g":
// Modified Julian day. Need to be implemented.
throw createErrorUnsupportedFeature({
feature: "Julian day pattern `g`"
});
// Week day
case "e":
case "c":
if ( length <= 2 ) {
properties.firstDay = dateFirstDayOfWeek( cldr );
formatNumber = true;
break;
}
/* falls through */
case "E":
if ( !properties.days ) {
properties.days = {};
}
if ( !properties.days[ chr ] ) {
properties.days[ chr ] = {};
}
if ( length === 6 ) {
// If short day names are not explicitly specified, abbreviated day names are
// used instead.
// http://www.unicode.org/reports/tr35/tr35-dates.html#months_days_quarters_eras
// http://unicode.org/cldr/trac/ticket/6790
properties.days[ chr ][ length ] = cldr.main([
"dates/calendars/gregorian/days",
chr === "c" ? "stand-alone" : "format",
"short"
]) || cldr.main([
"dates/calendars/gregorian/days",
chr === "c" ? "stand-alone" : "format",
"abbreviated"
]);
} else {
properties.days[ chr ][ length ] = cldr.main([
"dates/calendars/gregorian/days",
chr === "c" ? "stand-alone" : "format",
widths[ length < 3 ? 0 : length - 3 ]
]);
}
break;
// Period (AM or PM)
case "a":
properties.dayPeriods = {
am: cldr.main(
"dates/calendars/gregorian/dayPeriods/format/wide/am"
),
pm: cldr.main(
"dates/calendars/gregorian/dayPeriods/format/wide/pm"
)
};
break;
// Hour
case "h": // 1-12
case "H": // 0-23
case "K": // 0-11
case "k": // 1-24
// Minute
case "m":
// Second
case "s":
case "S":
case "A":
formatNumber = true;
break;
// Zone
case "v":
if ( length !== 1 && length !== 4 ) {
throw createErrorUnsupportedFeature({
feature: "timezone pattern `" + pattern + "`"
});
}
properties.genericTzName = genericTzName;
break;
case "V":
if ( length === 1 ) {
throw createErrorUnsupportedFeature({
feature: "timezone pattern `" + pattern + "`"
});
}
if ( timeZone ) {
if ( length === 2 ) {
properties.timeZoneName = timeZone;
break;
}
var timeZoneName,
exemplarCity = cldr.main([
"dates/timeZoneNames/zone", timeZone, "exemplarCity"
]);
if ( length === 3 ) {
if ( !exemplarCity ) {
exemplarCity = cldr.main([
"dates/timeZoneNames/zone/Etc/Unknown/exemplarCity"
]);
}
timeZoneName = exemplarCity;
}
if ( exemplarCity && length === 4 ) {
timeZoneName = formatMessage(
cldr.main(
"dates/timeZoneNames/regionFormat"
),
[ exemplarCity ]
);
}
if ( timeZoneName ) {
properties.timeZoneName = timeZoneName;
break;
}
}
if ( current === "v" ) {
length = 1;
}
/* falls through */
case "O":
// O: "{gmtFormat}+H;{gmtFormat}-H" or "{gmtZeroFormat}", eg. "GMT-8" or "GMT".
// OOOO: "{gmtFormat}{hourFormat}" or "{gmtZeroFormat}", eg. "GMT-08:00" or "GMT".
properties.gmtFormat = cldr.main( "dates/timeZoneNames/gmtFormat" );
properties.gmtZeroFormat = cldr.main( "dates/timeZoneNames/gmtZeroFormat" );
// Unofficial deduction of the hourFormat variations.
// Official spec is pending resolution: http://unicode.org/cldr/trac/ticket/8293
aux = cldr.main( "dates/timeZoneNames/hourFormat" );
properties.hourFormat = length < 4 ?
[ dateTimezoneHourFormatH( aux ), dateTimezoneHourFormatHm( aux, "H" ) ] :
dateTimezoneHourFormatHm( aux, "HH" );
/* falls through */
case "Z":
case "X":
case "x":
setNumberFormatterPattern( 1 );
setNumberFormatterPattern( 2 );
break;
}
if ( formatNumber ) {
setNumberFormatterPattern( length );
}
});
return properties;
};
var dateFormatterFn = function( dateToPartsFormatter ) {
return function dateFormatter( value ) {
return dateToPartsFormatter( value ).map( function( part ) {
return part.value;
}).join( "" );
};
};
/**
* parseProperties( cldr )
*
* @cldr [Cldr instance].
*
* @timeZone [String] FIXME.
*
* Return parser properties.
*/
var dateParseProperties = function( cldr, timeZone ) {
var properties = {
preferredTimeData: cldr.supplemental.timeData.preferred()
};
if ( timeZone ) {
properties.timeZoneData = runtimeCacheDataBind( "iana/" + timeZone, {
offsets: cldr.get([ "globalize-iana/zoneData", timeZone, "offsets" ]),
untils: cldr.get([ "globalize-iana/zoneData", timeZone, "untils" ]),
isdsts: cldr.get([ "globalize-iana/zoneData", timeZone, "isdsts" ])
});
}
return properties;
};
var ZonedDateTime = (function() {
function definePrivateProperty(object, property, value) {
Object.defineProperty(object, property, {
value: value
});
}
function getUntilsIndex(original, untils) {
var index = 0;
var originalTime = original.getTime();
// TODO Should we do binary search for improved performance?
while (index < untils.length - 1 && originalTime >= untils[index]) {
index++;
}
return index;
}
function setWrap(fn) {
var offset1 = this.getTimezoneOffset();
var ret = fn();
this.original.setTime(new Date(this.getTime()));
var offset2 = this.getTimezoneOffset();
if (offset2 - offset1) {
this.original.setMinutes(this.original.getMinutes() + offset2 - offset1);
}
return ret;
}
var ZonedDateTime = function(date, timeZoneData) {
definePrivateProperty(this, "original", new Date(date.getTime()));
definePrivateProperty(this, "local", new Date(date.getTime()));
definePrivateProperty(this, "timeZoneData", timeZoneData);
definePrivateProperty(this, "setWrap", setWrap);
if (!(timeZoneData.untils && timeZoneData.offsets && timeZoneData.isdsts)) {
throw new Error("Invalid IANA data");
}
this.setTime(this.local.getTime() - this.getTimezoneOffset() * 60 * 1000);
};
ZonedDateTime.prototype.clone = function() {
return new ZonedDateTime(this.original, this.timeZoneData);
};
// Date field getters.
["getFullYear", "getMonth", "getDate", "getDay", "getHours", "getMinutes",
"getSeconds", "getMilliseconds"].forEach(function(method) {
// Corresponding UTC method, e.g., "getUTCFullYear" if method === "getFullYear".
var utcMethod = "getUTC" + method.substr(3);
ZonedDateTime.prototype[method] = function() {
return this.local[utcMethod]();
};
});
// Note: Define .valueOf = .getTime for arithmetic operations like date1 - date2.
ZonedDateTime.prototype.valueOf =
ZonedDateTime.prototype.getTime = function() {
return this.local.getTime() + this.getTimezoneOffset() * 60 * 1000;
};
ZonedDateTime.prototype.getTimezoneOffset = function() {
var index = getUntilsIndex(this.original, this.timeZoneData.untils);
return this.timeZoneData.offsets[index];
};
// Date field setters.
["setFullYear", "setMonth", "setDate", "setHours", "setMinutes", "setSeconds", "setMilliseconds"].forEach(function(method) {
// Corresponding UTC method, e.g., "setUTCFullYear" if method === "setFullYear".
var utcMethod = "setUTC" + method.substr(3);
ZonedDateTime.prototype[method] = function(value) {
var local = this.local;
// Note setWrap is needed for seconds and milliseconds just because
// abs(value) could be >= a minute.
return this.setWrap(function() {
return local[utcMethod](value);
});
};
});
ZonedDateTime.prototype.setTime = function(time) {
return this.local.setTime(time);
};
ZonedDateTime.prototype.isDST = function() {
var index = getUntilsIndex(this.original, this.timeZoneData.untils);
return Boolean(this.timeZoneData.isdsts[index]);
};
ZonedDateTime.prototype.inspect = function() {
var index = getUntilsIndex(this.original, this.timeZoneData.untils);
var abbrs = this.timeZoneData.abbrs;
return this.local.toISOString().replace(/Z$/, "") + " " +
(abbrs && abbrs[index] + " " || (this.getTimezoneOffset() * -1) + " ") +
(this.isDST() ? "(daylight savings)" : "");
};
ZonedDateTime.prototype.toDate = function() {
return new Date(this.getTime());
};
// Type cast getters.
["toISOString", "toJSON", "toUTCString"].forEach(function(method) {
ZonedDateTime.prototype[method] = function() {
return this.toDate()[method]();
};
});
return ZonedDateTime;
}());
/**
* isLeapYear( year )
*
* @year [Number]
*
* Returns an indication whether the specified year is a leap year.
*/
var dateIsLeapYear = function( year ) {
return new Date( year, 1, 29 ).getMonth() === 1;
};
/**
* lastDayOfMonth( date )
*
* @date [Date]
*
* Return the last day of the given date's month
*/
var dateLastDayOfMonth = function( date ) {
return new Date( date.getFullYear(), date.getMonth() + 1, 0 ).getDate();
};
/**
* startOf changes the input to the beginning of the given unit.
*
* For example, starting at the start of a day, resets hours, minutes
* seconds and milliseconds to 0. Starting at the month does the same, but
* also sets the date to 1.
*
* Returns the modified date
*/
var dateStartOf = function( date, unit ) {
date = date instanceof ZonedDateTime ? date.clone() : new Date( date.getTime() );
switch ( unit ) {
case "year":
date.setMonth( 0 );
/* falls through */
case "month":
date.setDate( 1 );
/* falls through */
case "day":
date.setHours( 0 );
/* falls through */
case "hour":
date.setMinutes( 0 );
/* falls through */
case "minute":
date.setSeconds( 0 );
/* falls through */
case "second":
date.setMilliseconds( 0 );
}
return date;
};
/**
* Differently from native date.setDate(), this function returns a date whose
* day remains inside the month boundaries. For example:
*
* setDate( FebDate, 31 ): a "Feb 28" date.
* setDate( SepDate, 31 ): a "Sep 30" date.
*/
var dateSetDate = function( date, day ) {
var lastDay = new Date( date.getFullYear(), date.getMonth() + 1, 0 ).getDate();
date.setDate( day < 1 ? 1 : day < lastDay ? day : lastDay );
};
/**
* Differently from native date.setMonth(), this function adjusts date if
* needed, so final month is always the one set.
*
* setMonth( Jan31Date, 1 ): a "Feb 28" date.
* setDate( Jan31Date, 8 ): a "Sep 30" date.
*/
var dateSetMonth = function( date, month ) {
var originalDate = date.getDate();
date.setDate( 1 );
date.setMonth( month );
dateSetDate( date, originalDate );
};
var outOfRange = function( value, low, high ) {
return value < low || value > high;
};
/**
* parse( value, tokens, properties )
*
* @value [String] string date.
*
* @tokens [Object] tokens returned by date/tokenizer.
*
* @properties [Object] output returned by date/tokenizer-properties.
*
* ref: http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns
*/
var dateParse = function( value, tokens, properties ) {
var amPm, day, daysOfYear, month, era, hour, hour12, timezoneOffset, valid,
YEAR = 0,
MONTH = 1,
DAY = 2,
HOUR = 3,
MINUTE = 4,
SECOND = 5,
MILLISECONDS = 6,
date = new Date(),
truncateAt = [],
units = [ "year", "month", "day", "hour", "minute", "second", "milliseconds" ];
// Create globalize date with given timezone data.
if ( properties.timeZoneData ) {
date = new ZonedDateTime( date, properties.timeZoneData() );
}
if ( !tokens.length ) {
return null;
}
valid = tokens.every(function( token ) {
var century, chr, value, length;
if ( token.type === "literal" ) {
// continue
return true;
}
chr = token.type.charAt( 0 );
length = token.type.length;
if ( chr === "j" ) {
// Locale preferred hHKk.
// http://www.unicode.org/reports/tr35/tr35-dates.html#Time_Data
chr = properties.preferredTimeData;
}
switch ( chr ) {
// Era
case "G":
truncateAt.push( YEAR );
era = +token.value;
break;
// Year
case "y":
value = token.value;
if ( length === 2 ) {
if ( outOfRange( value, 0, 99 ) ) {
return false;
}
// mimic dojo/date/locale: choose century to apply, according to a sliding
// window of 80 years before and 20 years after present year.
century = Math.floor( date.getFullYear() / 100 ) * 100;
value += century;
if ( value > date.getFullYear() + 20 ) {
value -= 100;
}
}
date.setFullYear( value );
truncateAt.push( YEAR );
break;
case "Y": // Year in "Week of Year"
throw createErrorUnsupportedFeature({
feature: "year pattern `" + chr + "`"
});
// Quarter (skip)
case "Q":
case "q":
break;
// Month
case "M":
case "L":
if ( length <= 2 ) {
value = token.value;
} else {
value = +token.value;
}
if ( outOfRange( value, 1, 12 ) ) {
return false;
}
// Setting the month later so that we have the correct year and can determine
// the correct last day of February in case of leap year.
month = value;
truncateAt.push( MONTH );
break;
// Week (skip)
case "w": // Week of Year.
case "W": // Week of Month.
break;
// Day
case "d":
day = token.value;
truncateAt.push( DAY );
break;
case "D":
daysOfYear = token.value;
truncateAt.push( DAY );
break;
case "F":
// Day of Week in month. eg. 2nd Wed in July.
// Skip
break;
// Week day
case "e":
case "c":
case "E":
// Skip.
// value = arrayIndexOf( dateWeekDays, token.value );
break;
// Period (AM or PM)
case "a":
amPm = token.value;
break;
// Hour
case "h": // 1-12
value = token.value;
if ( outOfRange( value, 1, 12 ) ) {
return false;
}
hour = hour12 = true;
date.setHours( value === 12 ? 0 : value );
truncateAt.push( HOUR );
break;
case "K": // 0-11
value = token.value;
if ( outOfRange( value, 0, 11 ) ) {
return false;
}
hour = hour12 = true;
date.setHours( value );
truncateAt.push( HOUR );
break;
case "k": // 1-24
value = token.value;
if ( outOfRange( value, 1, 24 ) ) {
return false;
}
hour = true;
date.setHours( value === 24 ? 0 : value );
truncateAt.push( HOUR );
break;
case "H": // 0-23
value = token.value;
if ( outOfRange( value, 0, 23 ) ) {
return false;
}
hour = true;
date.setHours( value );
truncateAt.push( HOUR );
break;
// Minute
case "m":
value = token.value;
if ( outOfRange( value, 0, 59 ) ) {
return false;
}
date.setMinutes( value );
truncateAt.push( MINUTE );
break;
// Second
case "s":
value = token.value;
if ( outOfRange( value, 0, 59 ) ) {
return false;
}
date.setSeconds( value );
truncateAt.push( SECOND );
break;
case "A":
date.setHours( 0 );
date.setMinutes( 0 );
date.setSeconds( 0 );
/* falls through */
case "S":
value = Math.round( token.value * Math.pow( 10, 3 - length ) );
date.setMilliseconds( value );
truncateAt.push( MILLISECONDS );
break;
// Zone
case "z":
case "Z":
case "O":
case "v":
case "V":
case "X":
case "x":
if ( typeof token.value === "number" ) {
timezoneOffset = token.value;
}
break;
}
return true;
});
if ( !valid ) {
return null;
}
// 12-hour format needs AM or PM, 24-hour format doesn't, ie. return null
// if amPm && !hour12 || !amPm && hour12.
if ( hour && !( !amPm ^ hour12 ) ) {
return null;
}
if ( era === 0 ) {
// 1 BC = year 0
date.setFullYear( date.getFullYear() * -1 + 1 );
}
if ( month !== undefined ) {
dateSetMonth( date, month - 1 );
}
if ( day !== undefined ) {
if ( outOfRange( day, 1, dateLastDayOfMonth( date ) ) ) {
return null;
}
date.setDate( day );
} else if ( daysOfYear !== undefined ) {
if ( outOfRange( daysOfYear, 1, dateIsLeapYear( date.getFullYear() ) ? 366 : 365 ) ) {
return null;
}
date.setMonth( 0 );
date.setDate( daysOfYear );
}
if ( hour12 && amPm === "pm" ) {
date.setHours( date.getHours() + 12 );
}
if ( timezoneOffset !== undefined ) {
date.setMinutes( date.getMinutes() + timezoneOffset - date.getTimezoneOffset() );
}
// Truncate date at the most precise unit defined. Eg.
// If value is "12/31", and pattern is "MM/dd":
// => new Date( <current Year>, 12, 31, 0, 0, 0, 0 );
truncateAt = Math.max.apply( null, truncateAt );
date = dateStartOf( date, units[ truncateAt ] );
// Get date back from globalize date.
if ( date instanceof ZonedDateTime ) {
date = date.toDate();
}
return date;
};
/**
* tokenizer( value, numberParser, properties )
*
* @value [String] string date.
*
* @numberParser [Function]
*
* @properties [Object] output returned by date/tokenizer-properties.
*
* Returns an Array of tokens, eg. value "5 o'clock PM", pattern "h 'o''clock' a":
* [{
* type: "h",
* lexeme: "5"
* }, {
* type: "literal",
* lexeme: " "
* }, {
* type: "literal",
* lexeme: "o'clock"
* }, {
* type: "literal",
* lexeme: " "
* }, {
* type: "a",
* lexeme: "PM",
* value: "pm"
* }]
*
* OBS: lexeme's are always String and may return invalid ranges depending of the token type.
* Eg. "99" for month number.
*
* Return an empty Array when not successfully parsed.
*/
var dateTokenizer = function( value, numberParser, properties ) {
var digitsRe, valid,
tokens = [],
widths = [ "abbreviated", "wide", "narrow" ];
digitsRe = properties.digitsRe;
value = looseMatching( value );
valid = properties.pattern.match( datePatternRe ).every(function( current ) {
var aux, chr, length, numeric, tokenRe,
token = {};
function hourFormatParse( tokenRe, numberParser ) {
var aux, isPositive,
match = value.match( tokenRe );
numberParser = numberParser || function( value ) {
return +value;
};
if ( !match ) {
return false;
}
isPositive = match[ 1 ];
// hourFormat containing H only, e.g., `+H;-H`
if ( match.length < 6 ) {
aux = isPositive ? 1 : 3;
token.value = numberParser( match[ aux ] ) * 60;
// hourFormat containing H and m, e.g., `+HHmm;-HHmm`
} else if ( match.length < 10 ) {
aux = isPositive ? [ 1, 3 ] : [ 5, 7 ];
token.value = numberParser( match[ aux[ 0 ] ] ) * 60 +
numberParser( match[ aux[ 1 ] ] );
// hourFormat containing H, m, and s e.g., `+HHmmss;-HHmmss`
} else {
aux = isPositive ? [ 1, 3, 5 ] : [ 7, 9, 11 ];
token.value = numberParser( match[ aux[ 0 ] ] ) * 60 +
numberParser( match[ aux[ 1 ] ] ) +
numberParser( match[ aux[ 2 ] ] ) / 60;
}
if ( isPositive ) {
token.value *= -1;
}
return true;
}
function oneDigitIfLengthOne() {
if ( length === 1 ) {
// Unicode equivalent to /\d/
numeric = true;
return tokenRe = digitsRe;
}
}
function oneOrTwoDigitsIfLengthOne() {
if ( length === 1 ) {
// Unicode equivalent to /\d\d?/
numeric = true;
return tokenRe = new RegExp( "^(" + digitsRe.source + "){1,2}" );
}
}
function oneOrTwoDigitsIfLengthOneOrTwo() {
if ( length === 1 || length === 2 ) {
// Unicode equivalent to /\d\d?/
numeric = true;
return tokenRe = new RegExp( "^(" + digitsRe.source + "){1,2}" );
}
}
function twoDigitsIfLengthTwo() {
if ( length === 2 ) {
// Unicode equivalent to /\d\d/
numeric = true;
return tokenRe = new RegExp( "^(" + digitsRe.source + "){2}" );
}
}
// Brute-force test every locale entry in an attempt to match the given value.
// Return the first found one (and set token accordingly), or null.
function lookup( path ) {
var array = properties[ path.join( "/" ) ];
if ( !array ) {
return null;
}
// array of pairs [key, value] sorted by desc value length.
array.some(function( item ) {
var valueRe = item[ 1 ];
if ( valueRe.test( value ) ) {
token.value = item[ 0 ];
tokenRe = item[ 1 ];
return true;
}
});
return null;
}
token.type = current;
chr = current.charAt( 0 );
length = current.length;
if ( chr === "Z" ) {
// Z..ZZZ: same as "xxxx".
if ( length < 4 ) {
chr = "x";
length = 4;
// ZZZZ: same as "OOOO".
} else if ( length < 5 ) {
chr = "O";
length = 4;
// ZZZZZ: same as "XXXXX"
} else {
chr = "X";
length = 5;
}
}
if ( chr === "z" ) {
if ( properties.standardOrDaylightTzName ) {
token.value = null;
tokenRe = properties.standardOrDaylightTzName;
}
}
// v...vvv: "{shortRegion}", eg. "PT".
// vvvv: "{regionName} {Time}" or "{regionName} {Time}",
// e.g., "Pacific Time"
// http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns
if ( chr === "v" ) {
if ( properties.genericTzName ) {
token.value = null;
tokenRe = properties.genericTzName;
// Fall back to "V" format.
} else {
chr = "V";
length = 4;
}
}
if ( chr === "V" && properties.timeZoneName ) {
token.value = length === 2 ? properties.timeZoneName : null;
tokenRe = properties.timeZoneNameRe;
}
switch ( chr ) {
// Era
case "G":
lookup([
"gregorian/eras",
length <= 3 ? "eraAbbr" : ( length === 4 ? "eraNames" : "eraNarrow" )
]);
break;
// Year
case "y":
case "Y":
numeric = true;
// number l=1:+, l=2:{2}, l=3:{3,}, l=4:{4,}, ...
if ( length === 1 ) {
// Unicode equivalent to /\d+/.
tokenRe = new RegExp( "^(" + digitsRe.source + ")+" );
} else if ( length === 2 ) {
// Lenient parsing: there's no year pattern to indicate non-zero-padded 2-digits
// year, so parser accepts both zero-padded and non-zero-padded for `yy`.
//
// Unicode equivalent to /\d\d?/
tokenRe = new RegExp( "^(" + digitsRe.source + "){1,2}" );
} else {
// Unicode equivalent to /\d{length,}/
tokenRe = new RegExp( "^(" + digitsRe.source + "){" + length + ",}" );
}
break;
// Quarter
case "Q":
case "q":
// number l=1:{1}, l=2:{2}.
// lookup l=3...
oneDigitIfLengthOne() || twoDigitsIfLengthTwo() ||
lookup([
"gregorian/quarters",
chr === "Q" ? "format" : "stand-alone",
widths[ length - 3 ]
]);
break;
// Month
case "M":
case "L":
// number l=1:{1,2}, l=2:{2}.
// lookup l=3...
//
// Lenient parsing: skeleton "yMd" (i.e., one M) may include MM for the pattern,
// therefore parser accepts both zero-padded and non-zero-padded for M and MM.
// Similar for L.
oneOrTwoDigitsIfLengthOneOrTwo() || lookup([
"gregorian/months",
chr === "M" ? "format" : "stand-alone",
widths[ length - 3 ]
]);
break;
// Day
case "D":
// number {l,3}.
if ( length <= 3 ) {
// Equivalent to /\d{length,3}/
numeric = true;
tokenRe = new RegExp( "^(" + digitsRe.source + "){" + length + ",3}" );
}
break;
case "W":
case "F":
// number l=1:{1}.
oneDigitIfLengthOne();
break;
// Week day
case "e":
case "c":
// number l=1:{1}, l=2:{2}.
// lookup for length >=3.
if ( length <= 2 ) {
oneDigitIfLengthOne() || twoDigitsIfLengthTwo();
break;
}
/* falls through */
case "E":
if ( length === 6 ) {
// Note: if short day names are not explicitly specified, abbreviated day
// names are used instead http://www.unicode.org/reports/tr35/tr35-dates.html#months_days_quarters_eras
lookup([
"gregorian/days",
[ chr === "c" ? "stand-alone" : "format" ],
"short"
]) || lookup([
"gregorian/days",
[ chr === "c" ? "stand-alone" : "format" ],
"abbreviated"
]);
} else {
lookup([
"gregorian/days",
[ chr === "c" ? "stand-alone" : "format" ],
widths[ length < 3 ? 0 : length - 3 ]
]);
}
break;
// Period (AM or PM)
case "a":
lookup([
"gregorian/dayPeriods/format/wide"
]);
break;
// Week
case "w":
// number l1:{1,2}, l2:{2}.
oneOrTwoDigitsIfLengthOne() || twoDigitsIfLengthTwo();
break;
// Day, Hour, Minute, or Second
case "d":
case "h":
case "H":
case "K":
case "k":
case "j":
case "m":
case "s":
// number l1:{1,2}, l2:{2}.
//
// Lenient parsing:
// - skeleton "hms" (i.e., one m) always includes mm for the pattern, i.e., it's
// impossible to use a different skeleton to parse non-zero-padded minutes,
// therefore parser accepts both zero-padded and non-zero-padded for m. Similar
// for seconds s.
// - skeleton "hms" (i.e., one h) may include h or hh for the pattern, i.e., it's
// impossible to use a different skeleton to parser non-zero-padded hours for some
// locales, therefore parser accepts both zero-padded and non-zero-padded for h.
// Similar for d (in skeleton yMd).
oneOrTwoDigitsIfLengthOneOrTwo();
break;
case "S":
// number {l}.
// Unicode equivalent to /\d{length}/
numeric = true;
tokenRe = new RegExp( "^(" + digitsRe.source + "){" + length + "}" );
break;
case "A":
// number {l+5}.
// Unicode equivalent to /\d{length+5}/
numeric = true;
tokenRe = new RegExp( "^(" + digitsRe.source + "){" + ( length + 5 ) + "}" );
break;
// Zone
case "v":
case "V":
case "z":
if ( tokenRe && tokenRe.test( value ) ) {
break;
}
if ( chr === "V" && length === 2 ) {
break;
}
/* falls through */
case "O":
// O: "{gmtFormat}+H;{gmtFormat}-H" or "{gmtZeroFormat}", eg. "GMT-8" or "GMT".
// OOOO: "{gmtFormat}{hourFormat}" or "{gmtZeroFormat}", eg. "GMT-08:00" or "GMT".
if ( value === properties[ "timeZoneNames/gmtZeroFormat" ] ) {
token.value = 0;
tokenRe = properties[ "timeZoneNames/gmtZeroFormatRe" ];
} else {
aux = properties[ "timeZoneNames/hourFormat" ].some(function( hourFormatRe ) {
if ( hourFormatParse( hourFormatRe, numberParser ) ) {
tokenRe = hourFormatRe;
return true;
}
});
if ( !aux ) {
return null;
}
}
break;
case "X":
// Same as x*, except it uses "Z" for zero offset.
if ( value === "Z" ) {
token.value = 0;
tokenRe = /^Z/;
break;
}
/* falls through */
case "x":
// x: hourFormat("+HH[mm];-HH[mm]")
// xx: hourFormat("+HHmm;-HHmm")
// xxx: hourFormat("+HH:mm;-HH:mm")
// xxxx: hourFormat("+HHmm[ss];-HHmm[ss]")
// xxxxx: hourFormat("+HH:mm[:ss];-HH:mm[:ss]")
aux = properties.x.some(function( hourFormatRe ) {
if ( hourFormatParse( hourFormatRe ) ) {
tokenRe = hourFormatRe;
return true;
}
});
if ( !aux ) {
return null;
}
break;
case "'":
token.type = "literal";
tokenRe = new RegExp( "^" + regexpEscape( removeLiteralQuotes( current ) ) );
break;
default:
token.type = "literal";
tokenRe = new RegExp( "^" + regexpEscape( current ) );
}
if ( !tokenRe ) {
return false;
}
// Get lexeme and consume it.
value = value.replace( tokenRe, function( lexeme ) {
token.lexeme = lexeme;
if ( numeric ) {
token.value = numberParser( lexeme );
}
return "";
});
if ( !token.lexeme ) {
return false;
}
if ( numeric && isNaN( token.value ) ) {
return false;
}
tokens.push( token );
return true;
});
if ( value !== "" ) {
valid = false;
}
return valid ? tokens : [];
};
var dateParserFn = function( numberParser, parseProperties, tokenizerProperties ) {
return function dateParser( value ) {
var tokens;
validateParameterPresence( value, "value" );
validateParameterTypeString( value, "value" );
tokens = dateTokenizer( value, numberParser, tokenizerProperties );
return dateParse( value, tokens, parseProperties ) || null;
};
};
var objectFilter = function( object, testRe ) {
var key,
copy = {};
for ( key in object ) {
if ( testRe.test( key ) ) {
copy[ key ] = object[ key ];
}
}
return copy;
};
/**
* tokenizerProperties( pattern, cldr )
*
* @pattern [String] raw pattern.
*
* @cldr [Cldr instance].
*
* Return Object with data that will be used by tokenizer.
*/
var dateTokenizerProperties = function( pattern, cldr, timeZone ) {
var digitsReSource,
properties = {
pattern: looseMatching( pattern )
},
timeSeparator = numberSymbol( "timeSeparator", cldr ),
widths = [ "abbreviated", "wide", "narrow" ];
digitsReSource = numberNumberingSystemDigitsMap( cldr );
digitsReSource = digitsReSource ? "[" + digitsReSource + "]" : "\\d";
properties.digitsRe = new RegExp( digitsReSource );
// Transform:
// - "+H;-H" -> /\+(\d\d?)|-(\d\d?)/
// - "+HH;-HH" -> /\+(\d\d)|-(\d\d)/
// - "+HHmm;-HHmm" -> /\+(\d\d)(\d\d)|-(\d\d)(\d\d)/
// - "+HH:mm;-HH:mm" -> /\+(\d\d):(\d\d)|-(\d\d):(\d\d)/
//
// If gmtFormat is GMT{0}, the regexp must fill {0} in each side, e.g.:
// - "+H;-H" -> /GMT\+(\d\d?)|GMT-(\d\d?)/
function hourFormatRe( hourFormat, gmtFormat, digitsReSource, timeSeparator ) {
var re;
if ( !digitsReSource ) {
digitsReSource = "\\d";
}
if ( !gmtFormat ) {
gmtFormat = "{0}";
}
re = hourFormat
.replace( "+", "\\+" )
// Unicode equivalent to (\\d\\d)
.replace( /HH|mm|ss/g, "((" + digitsReSource + "){2})" )
// Unicode equivalent to (\\d\\d?)
.replace( /H|m/g, "((" + digitsReSource + "){1,2})" );
if ( timeSeparator ) {
re = re.replace( /:/g, timeSeparator );
}
re = re.split( ";" ).map(function( part ) {
return gmtFormat.replace( "{0}", part );
}).join( "|" );
return new RegExp( "^" + re );
}
function populateProperties( path, value ) {
// Skip
var skipRe = /(timeZoneNames\/zone|supplemental\/metaZones|timeZoneNames\/metazone|timeZoneNames\/regionFormat|timeZoneNames\/gmtFormat)/;
if ( skipRe.test( path ) ) {
return;
}
if ( !value ) {
return;
}
// The `dates` and `calendars` trim's purpose is to reduce properties' key size only.
path = path.replace( /^.*\/dates\//, "" ).replace( /calendars\//, "" );
// Specific filter for "gregorian/dayPeriods/format/wide".
if ( path === "gregorian/dayPeriods/format/wide" ) {
value = objectFilter( value, /^am|^pm/ );
}
// Transform object into array of pairs [key, /value/], sort by desc value length.
if ( isPlainObject( value ) ) {
value = Object.keys( value ).map(function( key ) {
return [ key, new RegExp( "^" + regexpEscape( looseMatching( value[ key ] ) ) ) ];
}).sort(function( a, b ) {
return b[ 1 ].source.length - a[ 1 ].source.length;
});
// If typeof value === "string".
} else {
value = looseMatching( value );
}
properties[ path ] = value;
}
function regexpSourceSomeTerm( terms ) {
return "(" + terms.filter(function( item ) {
return item;
}).reduce(function( memo, item ) {
return memo + "|" + item;
}) + ")";
}
cldr.on( "get", populateProperties );
pattern.match( datePatternRe ).forEach(function( current ) {
var aux, chr, daylightTzName, gmtFormat, length, standardTzName;
chr = current.charAt( 0 );
length = current.length;
if ( chr === "Z" ) {
if ( length < 5 ) {
chr = "O";
length = 4;
} else {
chr = "X";
length = 5;
}
}
// z...zzz: "{shortRegion}", eg. "PST" or "PDT".
// zzzz: "{regionName} {Standard Time}" or "{regionName} {Daylight Time}",
// e.g., "Pacific Standard Time" or "Pacific Daylight Time".
// http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns
if ( chr === "z" ) {
standardTzName = dateGetTimeZoneName( length, "standard", timeZone, cldr );
daylightTzName = dateGetTimeZoneName( length, "daylight", timeZone, cldr );
if ( standardTzName ) {
standardTzName = regexpEscape( looseMatching( standardTzName ) );
}
if ( daylightTzName ) {
daylightTzName = regexpEscape( looseMatching( daylightTzName ) );
}
if ( standardTzName || daylightTzName ) {
properties.standardOrDaylightTzName = new RegExp(
"^" + regexpSourceSomeTerm([ standardTzName, daylightTzName ])
);
}
// Fall through the "O" format in case one name is missing.
if ( !standardTzName || !daylightTzName ) {
chr = "O";
if ( length < 4 ) {
length = 1;
}
}
}
// v...vvv: "{shortRegion}", eg. "PT".
// vvvv: "{regionName} {Time}" or "{regionName} {Time}",
// e.g., "Pacific Time"
// http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns
if ( chr === "v" ) {
if ( length !== 1 && length !== 4 ) {
throw createErrorUnsupportedFeature({
feature: "timezone pattern `" + pattern + "`"
});
}
var genericTzName = dateGetTimeZoneName( length, "generic", timeZone, cldr );
if ( genericTzName ) {
properties.genericTzName = new RegExp(
"^" + regexpEscape( looseMatching( genericTzName ) )
);
chr = "O";
// Fall back to "V" format.
} else {
chr = "V";
length = 4;
}
}
switch ( chr ) {
// Era
case "G":
cldr.main([
"dates/calendars/gregorian/eras",
length <= 3 ? "eraAbbr" : ( length === 4 ? "eraNames" : "eraNarrow" )
]);
break;
// Year
case "u": // Extended year. Need to be implemented.
case "U": // Cyclic year name. Need to be implemented.
throw createErrorUnsupportedFeature({
feature: "year pattern `" + chr + "`"
});
// Quarter
case "Q":
case "q":
if ( length > 2 ) {
cldr.main([
"dates/calendars/gregorian/quarters",
chr === "Q" ? "format" : "stand-alone",
widths[ length - 3 ]
]);
}
break;
// Month
case "M":
case "L":
// number l=1:{1,2}, l=2:{2}.
// lookup l=3...
if ( length > 2 ) {
cldr.main([
"dates/calendars/gregorian/months",
chr === "M" ? "format" : "stand-alone",
widths[ length - 3 ]
]);
}
break;
// Day
case "g":
// Modified Julian day. Need to be implemented.
throw createErrorUnsupportedFeature({
feature: "Julian day pattern `g`"
});
// Week day
case "e":
case "c":
// lookup for length >=3.
if ( length <= 2 ) {
break;
}
/* falls through */
case "E":
if ( length === 6 ) {
// Note: if short day names are not explicitly specified, abbreviated day
// names are used instead http://www.unicode.org/reports/tr35/tr35-dates.html#months_days_quarters_eras
cldr.main([
"dates/calendars/gregorian/days",
[ chr === "c" ? "stand-alone" : "format" ],
"short"
]) || cldr.main([
"dates/calendars/gregorian/days",
[ chr === "c" ? "stand-alone" : "format" ],
"abbreviated"
]);
} else {
cldr.main([
"dates/calendars/gregorian/days",
[ chr === "c" ? "stand-alone" : "format" ],
widths[ length < 3 ? 0 : length - 3 ]
]);
}
break;
// Period (AM or PM)
case "a":
cldr.main(
"dates/calendars/gregorian/dayPeriods/format/wide"
);
break;
// Zone
case "V":
if ( length === 1 ) {
throw createErrorUnsupportedFeature({
feature: "timezone pattern `" + pattern + "`"
});
}
if ( timeZone ) {
if ( length === 2 ) {
// Skip looseMatching processing since timeZone is a canonical posix value.
properties.timeZoneName = timeZone;
properties.timeZoneNameRe = new RegExp( "^" + regexpEscape( timeZone ) );
break;
}
var timeZoneName,
exemplarCity = cldr.main([
"dates/timeZoneNames/zone", timeZone, "exemplarCity"
]);
if ( length === 3 ) {
if ( !exemplarCity ) {
exemplarCity = cldr.main([
"dates/timeZoneNames/zone/Etc/Unknown/exemplarCity"
]);
}
timeZoneName = exemplarCity;
}
if ( exemplarCity && length === 4 ) {
timeZoneName = formatMessage(
cldr.main(
"dates/timeZoneNames/regionFormat"
),
[ exemplarCity ]
);
}
if ( timeZoneName ) {
timeZoneName = looseMatching( timeZoneName );
properties.timeZoneName = timeZoneName;
properties.timeZoneNameRe = new RegExp(
"^" + regexpEscape( timeZoneName )
);
}
}
if ( current === "v" ) {
length = 1;
}
/* falls through */
case "z":
case "O":
gmtFormat = cldr.main( "dates/timeZoneNames/gmtFormat" );
cldr.main( "dates/timeZoneNames/gmtZeroFormat" );
cldr.main( "dates/timeZoneNames/hourFormat" );
properties[ "timeZoneNames/gmtZeroFormatRe" ] =
new RegExp( "^" + regexpEscape( properties[ "timeZoneNames/gmtZeroFormat" ] ) );
aux = properties[ "timeZoneNames/hourFormat" ];
properties[ "timeZoneNames/hourFormat" ] = (
length < 4 ?
[ dateTimezoneHourFormatHm( aux, "H" ), dateTimezoneHourFormatH( aux ) ] :
[ dateTimezoneHourFormatHm( aux, "HH" ) ]
).map(function( hourFormat ) {
return hourFormatRe(
hourFormat,
gmtFormat,
digitsReSource,
timeSeparator
);
});
/* falls through */
case "X":
case "x":
// x: hourFormat("+HH[mm];-HH[mm]")
// xx: hourFormat("+HHmm;-HHmm")
// xxx: hourFormat("+HH:mm;-HH:mm")
// xxxx: hourFormat("+HHmm[ss];-HHmm[ss]")
// xxxxx: hourFormat("+HH:mm[:ss];-HH:mm[:ss]")
properties.x = [
[ "+HHmm;-HHmm", "+HH;-HH" ],
[ "+HHmm;-HHmm" ],
[ "+HH:mm;-HH:mm" ],
[ "+HHmmss;-HHmmss", "+HHmm;-HHmm" ],
[ "+HH:mm:ss;-HH:mm:ss", "+HH:mm;-HH:mm" ]
][ length - 1 ].map(function( hourFormat ) {
return hourFormatRe( hourFormat );
});
}
});
cldr.off( "get", populateProperties );
return properties;
};
/**
* dayOfWeek( date, firstDay )
*
* @date
*
* @firstDay the result of `dateFirstDayOfWeek( cldr )`
*
* Return the day of the week normalized by the territory's firstDay [0-6].
* Eg for "mon":
* - return 0 if territory is GB, or BR, or DE, or FR (week starts on "mon");
* - return 1 if territory is US (week starts on "sun");
* - return 2 if territory is EG (week starts on "sat");
*/
var dateDayOfWeek = function( date, firstDay ) {
return ( date.getDay() - firstDay + 7 ) % 7;
};
/**
* distanceInDays( from, to )
*
* Return the distance in days between from and to Dates.
*/
var dateDistanceInDays = function( from, to ) {
var inDays = 864e5;
return ( to.getTime() - from.getTime() ) / inDays;
};
/**
* dayOfYear
*
* Return the distance in days of the date to the begin of the year [0-d].
*/
var dateDayOfYear = function( date ) {
return Math.floor( dateDistanceInDays( dateStartOf( date, "year" ), date ) );
};
// Invert key and values, e.g., {"year": "yY"} ==> {"y": "year", "Y": "year"}
var dateFieldsMap = objectInvert({
"era": "G",
"year": "yY",
"quarter": "qQ",
"month": "ML",
"week": "wW",
"day": "dDF",
"weekday": "ecE",
"dayperiod": "a",
"hour": "hHkK",
"minute": "m",
"second": "sSA",
"zone": "zvVOxX"
}, function( object, key, value ) {
value.split( "" ).forEach(function( symbol ) {
object[ symbol ] = key;
});
return object;
});
/**
* millisecondsInDay
*/
var dateMillisecondsInDay = function( date ) {
// TODO Handle daylight savings discontinuities
return date - dateStartOf( date, "day" );
};
/**
* hourFormat( date, format, timeSeparator, formatNumber )
*
* Return date's timezone offset according to the format passed.
* Eg for format when timezone offset is 180:
* - "+H;-H": -3
* - "+HHmm;-HHmm": -0300
* - "+HH:mm;-HH:mm": -03:00
* - "+HH:mm:ss;-HH:mm:ss": -03:00:00
*/
var dateTimezoneHourFormat = function( date, format, timeSeparator, formatNumber ) {
var absOffset,
offset = date.getTimezoneOffset();
absOffset = Math.abs( offset );
formatNumber = formatNumber || {
1: function( value ) {
return stringPad( value, 1 );
},
2: function( value ) {
return stringPad( value, 2 );
}
};
return format
// Pick the correct sign side (+ or -).
.split( ";" )[ offset > 0 ? 1 : 0 ]
// Localize time separator
.replace( ":", timeSeparator )
// Update hours offset.
.replace( /HH?/, function( match ) {
return formatNumber[ match.length ]( Math.floor( absOffset / 60 ) );
})
// Update minutes offset and return.
.replace( /mm/, function() {
return formatNumber[ 2 ]( Math.floor( absOffset % 60 ) );
})
// Update minutes offset and return.
.replace( /ss/, function() {
return formatNumber[ 2 ]( Math.floor( absOffset % 1 * 60 ) );
});
};
/**
* format( date, properties )
*
* @date [Date instance].
*
* @properties
*
* TODO Support other calendar types.
*
* Disclosure: this function borrows excerpts of dojo/date/locale.
*/
var dateFormat = function( date, numberFormatters, properties ) {
var parts = [];
var timeSeparator = properties.timeSeparator;
// create globalize date with given timezone data
if ( properties.timeZoneData ) {
date = new ZonedDateTime( date, properties.timeZoneData() );
}
properties.pattern.replace( datePatternRe, function( current ) {
var aux, dateField, type, value,
chr = current.charAt( 0 ),
length = current.length;
if ( chr === "j" ) {
// Locale preferred hHKk.
// http://www.unicode.org/reports/tr35/tr35-dates.html#Time_Data
chr = properties.preferredTime;
}
if ( chr === "Z" ) {
// Z..ZZZ: same as "xxxx".
if ( length < 4 ) {
chr = "x";
length = 4;
// ZZZZ: same as "OOOO".
} else if ( length < 5 ) {
chr = "O";
length = 4;
// ZZZZZ: same as "XXXXX"
} else {
chr = "X";
length = 5;
}
}
// z...zzz: "{shortRegion}", e.g., "PST" or "PDT".
// zzzz: "{regionName} {Standard Time}" or "{regionName} {Daylight Time}",
// e.g., "Pacific Standard Time" or "Pacific Daylight Time".
if ( chr === "z" ) {
if ( date.isDST ) {
value = date.isDST() ? properties.daylightTzName : properties.standardTzName;
}
// Fall back to "O" format.
if ( !value ) {
chr = "O";
if ( length < 4 ) {
length = 1;
}
}
}
switch ( chr ) {
// Era
case "G":
value = properties.eras[ date.getFullYear() < 0 ? 0 : 1 ];
break;
// Year
case "y":
// Plain year.
// The length specifies the padding, but for two letters it also specifies the
// maximum length.
value = date.getFullYear();
if ( length === 2 ) {
value = String( value );
value = +value.substr( value.length - 2 );
}
break;
case "Y":
// Year in "Week of Year"
// The length specifies the padding, but for two letters it also specifies the
// maximum length.
// yearInWeekofYear = date + DaysInAWeek - (dayOfWeek - firstDay) - minDays
value = new Date( date.getTime() );
value.setDate(
value.getDate() + 7 -
dateDayOfWeek( date, properties.firstDay ) -
properties.firstDay -
properties.minDays
);
value = value.getFullYear();
if ( length === 2 ) {
value = String( value );
value = +value.substr( value.length - 2 );
}
break;
// Quarter
case "Q":
case "q":
value = Math.ceil( ( date.getMonth() + 1 ) / 3 );
if ( length > 2 ) {
value = properties.quarters[ chr ][ length ][ value ];
}
break;
// Month
case "M":
case "L":
value = date.getMonth() + 1;
if ( length > 2 ) {
value = properties.months[ chr ][ length ][ value ];
}
break;
// Week
case "w":
// Week of Year.
// woy = ceil( ( doy + dow of 1/1 ) / 7 ) - minDaysStuff ? 1 : 0.
// TODO should pad on ww? Not documented, but I guess so.
value = dateDayOfWeek( dateStartOf( date, "year" ), properties.firstDay );
value = Math.ceil( ( dateDayOfYear( date ) + value ) / 7 ) -
( 7 - value >= properties.minDays ? 0 : 1 );
break;
case "W":
// Week of Month.
// wom = ceil( ( dom + dow of `1/month` ) / 7 ) - minDaysStuff ? 1 : 0.
value = dateDayOfWeek( dateStartOf( date, "month" ), properties.firstDay );
value = Math.ceil( ( date.getDate() + value ) / 7 ) -
( 7 - value >= properties.minDays ? 0 : 1 );
break;
// Day
case "d":
value = date.getDate();
break;
case "D":
value = dateDayOfYear( date ) + 1;
break;
case "F":
// Day of Week in month. eg. 2nd Wed in July.
value = Math.floor( date.getDate() / 7 ) + 1;
break;
// Week day
case "e":
case "c":
if ( length <= 2 ) {
// Range is [1-7] (deduced by example provided on documentation)
// TODO Should pad with zeros (not specified in the docs)?
value = dateDayOfWeek( date, properties.firstDay ) + 1;
break;
}
/* falls through */
case "E":
value = dateWeekDays[ date.getDay() ];
value = properties.days[ chr ][ length ][ value ];
break;
// Period (AM or PM)
case "a":
value = properties.dayPeriods[ date.getHours() < 12 ? "am" : "pm" ];
break;
// Hour
case "h": // 1-12
value = ( date.getHours() % 12 ) || 12;
break;
case "H": // 0-23
value = date.getHours();
break;
case "K": // 0-11
value = date.getHours() % 12;
break;
case "k": // 1-24
value = date.getHours() || 24;
break;
// Minute
case "m":
value = date.getMinutes();
break;
// Second
case "s":
value = date.getSeconds();
break;
case "S":
value = Math.round( date.getMilliseconds() * Math.pow( 10, length - 3 ) );
break;
case "A":
value = Math.round( dateMillisecondsInDay( date ) * Math.pow( 10, length - 3 ) );
break;
// Zone
case "z":
break;
case "v":
// v...vvv: "{shortRegion}", eg. "PT".
// vvvv: "{regionName} {Time}",
// e.g., "Pacific Time".
if ( properties.genericTzName ) {
value = properties.genericTzName;
break;
}
/* falls through */
case "V":
//VVVV: "{explarCity} {Time}", e.g., "Los Angeles Time"
if ( properties.timeZoneName ) {
value = properties.timeZoneName;
break;
}
if ( current === "v" ) {
length = 1;
}
/* falls through */
case "O":
// O: "{gmtFormat}+H;{gmtFormat}-H" or "{gmtZeroFormat}", eg. "GMT-8" or "GMT".
// OOOO: "{gmtFormat}{hourFormat}" or "{gmtZeroFormat}", eg. "GMT-08:00" or "GMT".
if ( date.getTimezoneOffset() === 0 ) {
value = properties.gmtZeroFormat;
} else {
// If O..OOO and timezone offset has non-zero minutes, show minutes.
if ( length < 4 ) {
aux = date.getTimezoneOffset();
aux = properties.hourFormat[ aux % 60 - aux % 1 === 0 ? 0 : 1 ];
} else {
aux = properties.hourFormat;
}
value = dateTimezoneHourFormat(
date,
aux,
timeSeparator,
numberFormatters
);
value = properties.gmtFormat.replace( /\{0\}/, value );
}
break;
case "X":
// Same as x*, except it uses "Z" for zero offset.
if ( date.getTimezoneOffset() === 0 ) {
value = "Z";
break;
}
/* falls through */
case "x":
// x: hourFormat("+HH[mm];-HH[mm]")
// xx: hourFormat("+HHmm;-HHmm")
// xxx: hourFormat("+HH:mm;-HH:mm")
// xxxx: hourFormat("+HHmm[ss];-HHmm[ss]")
// xxxxx: hourFormat("+HH:mm[:ss];-HH:mm[:ss]")
aux = date.getTimezoneOffset();
// If x and timezone offset has non-zero minutes, use xx (i.e., show minutes).
if ( length === 1 && aux % 60 - aux % 1 !== 0 ) {
length += 1;
}
// If (xxxx or xxxxx) and timezone offset has zero seconds, use xx or xxx
// respectively (i.e., don't show optional seconds).
if ( ( length === 4 || length === 5 ) && aux % 1 === 0 ) {
length -= 2;
}
value = [
"+HH;-HH",
"+HHmm;-HHmm",
"+HH:mm;-HH:mm",
"+HHmmss;-HHmmss",
"+HH:mm:ss;-HH:mm:ss"
][ length - 1 ];
value = dateTimezoneHourFormat( date, value, ":" );
break;
// timeSeparator
case ":":
value = timeSeparator;
break;
// ' literals.
case "'":
value = removeLiteralQuotes( current );
break;
// Anything else is considered a literal, including [ ,:/.@#], chinese, japonese, and
// arabic characters.
default:
value = current;
}
if ( typeof value === "number" ) {
value = numberFormatters[ length ]( value );
}
dateField = dateFieldsMap[ chr ];
type = dateField ? dateField : "literal";
// Concat two consecutive literals
if ( type === "literal" && parts.length && parts[ parts.length - 1 ].type === "literal" ) {
parts[ parts.length - 1 ].value += value;
return;
}
parts.push( { type: type, value: value } );
});
return parts;
};
var dateToPartsFormatterFn = function( numberFormatters, properties ) {
return function dateToPartsFormatter( value ) {
validateParameterPresence( value, "value" );
validateParameterTypeDate( value, "value" );
return dateFormat( value, numberFormatters, properties );
};
};
function optionsHasStyle( options ) {
return options.skeleton !== undefined ||
options.date !== undefined ||
options.time !== undefined ||
options.datetime !== undefined ||
options.raw !== undefined;
}
function validateRequiredCldr( path, value ) {
validateCldr( path, value, {
skip: [
/dates\/calendars\/gregorian\/dateTimeFormats\/availableFormats/,
/dates\/calendars\/gregorian\/days\/.*\/short/,
/dates\/timeZoneNames\/zone/,
/dates\/timeZoneNames\/metazone/,
/globalize-iana/,
/supplemental\/metaZones/,
/supplemental\/timeData\/(?!001)/,
/supplemental\/weekData\/(?!001)/
]
});
}
function validateOptionsPreset( options ) {
validateOptionsPresetEach( "date", options );
validateOptionsPresetEach( "time", options );
validateOptionsPresetEach( "datetime", options );
}
function validateOptionsPresetEach( type, options ) {
var value = options[ type ];
validate(
"E_INVALID_OPTIONS",
"Invalid `{{type}: \"{value}\"}`.",
value === undefined || [ "short", "medium", "long", "full" ].indexOf( value ) !== -1,
{ type: type, value: value }
);
}
function validateOptionsSkeleton( pattern, skeleton ) {
validate(
"E_INVALID_OPTIONS",
"Invalid `{skeleton: \"{value}\"}` based on provided CLDR.",
skeleton === undefined || ( typeof pattern === "string" && pattern ),
{ type: "skeleton", value: skeleton }
);
}
function validateRequiredIana( timeZone ) {
return function( path, value ) {
if ( !/globalize-iana/.test( path ) ) {
return;
}
validate(
"E_MISSING_IANA_TZ",
"Missing required IANA timezone content for `{timeZone}`: `{path}`.",
value,
{
path: path.replace( /globalize-iana\//, "" ),
timeZone: timeZone
}
);
};
}
/**
* .loadTimeZone( json )
*
* @json [JSON]
*
* Load IANA timezone data.
*/
Globalize.loadTimeZone = function( json ) {
var customData = {
"globalize-iana": json
};
validateParameterPresence( json, "json" );
validateParameterTypePlainObject( json, "json" );
Cldr.load( customData );
};
/**
* .dateFormatter( options )
*
* @options [Object] see date/expand_pattern for more info.
*
* Return a date formatter function (of the form below) according to the given options and the
* default/instance locale.
*
* fn( value )
*
* @value [Date]
*
* Return a function that formats a date according to the given `format` and the default/instance
* locale.
*/
Globalize.dateFormatter =
Globalize.prototype.dateFormatter = function( options ) {
var args, dateToPartsFormatter, returnFn;
validateParameterTypePlainObject( options, "options" );
options = options || {};
if ( !optionsHasStyle( options ) ) {
options.skeleton = "yMd";
}
args = [ options ];
dateToPartsFormatter = this.dateToPartsFormatter( options );
returnFn = dateFormatterFn( dateToPartsFormatter );
runtimeBind( args, this.cldr, returnFn, [ dateToPartsFormatter ] );
return returnFn;
};
/**
* .dateToPartsFormatter( options )
*
* @options [Object] see date/expand_pattern for more info.
*
* Return a date formatter function (of the form below) according to the given options and the
* default/instance locale.
*
* fn( value )
*
* @value [Date]
*
* Return a function that formats a date to parts according to the given `format`
* and the default/instance
* locale.
*/
Globalize.dateToPartsFormatter =
Globalize.prototype.dateToPartsFormatter = function( options ) {
var args, cldr, numberFormatters, pad, pattern, properties, returnFn,
timeZone, ianaListener;
validateParameterTypePlainObject( options, "options" );
cldr = this.cldr;
options = options || {};
if ( !optionsHasStyle( options ) ) {
options.skeleton = "yMd";
}
validateOptionsPreset( options );
validateDefaultLocale( cldr );
timeZone = options.timeZone;
validateParameterTypeString( timeZone, "options.timeZone" );
args = [ options ];
cldr.on( "get", validateRequiredCldr );
if ( timeZone ) {
ianaListener = validateRequiredIana( timeZone );
cldr.on( "get", ianaListener );
}
pattern = dateExpandPattern( options, cldr );
validateOptionsSkeleton( pattern, options.skeleton );
properties = dateFormatProperties( pattern, cldr, timeZone );
cldr.off( "get", validateRequiredCldr );
if ( ianaListener ) {
cldr.off( "get", ianaListener );
}
// Create needed number formatters.
numberFormatters = properties.numberFormatters;
delete properties.numberFormatters;
for ( pad in numberFormatters ) {
numberFormatters[ pad ] = this.numberFormatter({
raw: numberFormatters[ pad ]
});
}
returnFn = dateToPartsFormatterFn( numberFormatters, properties );
runtimeBind( args, cldr, returnFn, [ numberFormatters, properties ] );
return returnFn;
};
/**
* .dateParser( options )
*
* @options [Object] see date/expand_pattern for more info.
*
* Return a function that parses a string date according to the given `formats` and the
* default/instance locale.
*/
Globalize.dateParser =
Globalize.prototype.dateParser = function( options ) {
var args, cldr, numberParser, parseProperties, pattern, returnFn, timeZone,
tokenizerProperties;
validateParameterTypePlainObject( options, "options" );
cldr = this.cldr;
options = options || {};
if ( !optionsHasStyle( options ) ) {
options.skeleton = "yMd";
}
validateOptionsPreset( options );
validateDefaultLocale( cldr );
timeZone = options.timeZone;
validateParameterTypeString( timeZone, "options.timeZone" );
args = [ options ];
cldr.on( "get", validateRequiredCldr );
if ( timeZone ) {
cldr.on( "get", validateRequiredIana( timeZone ) );
}
pattern = dateExpandPattern( options, cldr );
validateOptionsSkeleton( pattern, options.skeleton );
tokenizerProperties = dateTokenizerProperties( pattern, cldr, timeZone );
parseProperties = dateParseProperties( cldr, timeZone );
cldr.off( "get", validateRequiredCldr );
if ( timeZone ) {
cldr.off( "get", validateRequiredIana( timeZone ) );
}
numberParser = this.numberParser({ raw: "0" });
returnFn = dateParserFn( numberParser, parseProperties, tokenizerProperties );
runtimeBind( args, cldr, returnFn, [ numberParser, parseProperties, tokenizerProperties ] );
return returnFn;
};
/**
* .formatDate( value, options )
*
* @value [Date]
*
* @options [Object] see date/expand_pattern for more info.
*
* Formats a date or number according to the given options string and the default/instance locale.
*/
Globalize.formatDate =
Globalize.prototype.formatDate = function( value, options ) {
validateParameterPresence( value, "value" );
validateParameterTypeDate( value, "value" );
return this.dateFormatter( options )( value );
};
/**
* .formatDateToParts( value, options )
*
* @value [Date]
*
* @options [Object] see date/expand_pattern for more info.
*
* Formats a date or number to parts according to the given options and the default/instance locale.
*/
Globalize.formatDateToParts =
Globalize.prototype.formatDateToParts = function( value, options ) {
validateParameterPresence( value, "value" );
validateParameterTypeDate( value, "value" );
return this.dateToPartsFormatter( options )( value );
};
/**
* .parseDate( value, options )
*
* @value [String]
*
* @options [Object] see date/expand_pattern for more info.
*
* Return a Date instance or null.
*/
Globalize.parseDate =
Globalize.prototype.parseDate = function( value, options ) {
validateParameterPresence( value, "value" );
validateParameterTypeString( value, "value" );
return this.dateParser( options )( value );
};
return Globalize;
}));
| ahocevar/cdnjs | ajax/libs/globalize/1.4.0-alpha.2/globalize/date.js | JavaScript | mit | 74,659 |
/**
* v1.0.45 generated on: Mon May 30 2016 15:59:00 GMT-0500 (CDT)
* Copyright (c) 2014-2016, Ecor Ventures LLC. All Rights Reserved. See LICENSE (BSD).
*/
"use strict";if(window.NGN=window.NGN||{},window.NGN.DATA=window.NGN.DATA||{},!NGN.HTTP)throw new Error("NGN.DATA.Proxy requires NGN.HTTP.");window.NGN.DATA.Proxy=function(e){if(e=e||{},!e.store)throw new Error("NGN.DATA.Proxy requires a NGN.DATA.Store.");e.store.proxy=this,Object.defineProperties(this,{store:NGN.define(!0,!1,!1,e.store),url:NGN.define(!0,!0,!1,e.url||"http://localhost"),username:NGN.define(!0,!0,!1,e.username||null),password:NGN.define(!0,!0,!1,e.password||null),token:NGN.define(!0,!0,!1,e.token||null),actions:NGN._get(function(){return{create:e.store._created,update:e.store.records.filter(function(r){return e.store._created.indexOf(r)<0&&e.store._deleted.indexOf(r)<0?!1:r.modified}).map(function(e){return e}),"delete":e.store._deleted}}),save:NGN.define(!0,!1,!0,function(){}),fetch:NGN.define(!0,!1,!0,function(){})})},NGN.DATA.util.inherit(NGN.DATA.util.EventEmitter,NGN.DATA.Proxy); | abishekrsrikaanth/jsdelivr | files/chassis/1.0.45/data.proxy.min.js | JavaScript | mit | 1,077 |
import util from "../utils";
class ApplicationService {
getServiceFramework(controller) {
let sf = util.utilities.sf;
sf.moduleRoot = "PersonaBar";
sf.controller = controller;
return sf;
}
getGeneralSettings(callback) {
const sf = this.getServiceFramework("SEO");
sf.get("GetGeneralSettings", {}, callback);
}
updateGeneralSettings(payload, callback, failureCallback) {
const sf = this.getServiceFramework("SEO");
sf.post("UpdateGeneralSettings", payload, callback, failureCallback);
}
getRegexSettings(callback) {
const sf = this.getServiceFramework("SEO");
sf.get("GetRegexSettings", {}, callback);
}
updateRegexSettings(payload, callback, failureCallback) {
const sf = this.getServiceFramework("SEO");
sf.post("UpdateRegexSettings", payload, callback, failureCallback);
}
testUrl(pageId, queryString, customPageName, callback) {
const sf = this.getServiceFramework("SEO");
sf.get("TestUrl?pageId=" + pageId + "&queryString=" + encodeURIComponent(queryString) + "&customPageName=" + encodeURIComponent(customPageName), {}, callback);
}
testUrlRewrite(uri, callback) {
const sf = this.getServiceFramework("SEO");
sf.get("TestUrlRewrite?uri=" + uri, {}, callback);
}
getSitemapSettings(callback) {
const sf = this.getServiceFramework("SEO");
sf.get("GetSitemapSettings", {}, callback);
}
updateSitemapSettings(payload, callback, failureCallback) {
const sf = this.getServiceFramework("SEO");
sf.post("UpdateSitemapSettings", payload, callback, failureCallback);
}
getSitemapProviders(callback) {
const sf = this.getServiceFramework("SEO");
sf.get("GetSitemapProviders", {}, callback);
}
updateSitemapProvider(payload, callback, failureCallback) {
const sf = this.getServiceFramework("SEO");
sf.post("UpdateSitemapProvider", payload, callback, failureCallback);
}
createVerification(verification, callback, failureCallback) {
const sf = this.getServiceFramework("SEO");
sf.post("CreateVerification?verification=" + verification, {}, callback, failureCallback);
}
clearCache(callback, failureCallback) {
const sf = this.getServiceFramework("SEO");
sf.post("ResetCache", {}, callback, failureCallback);
}
getExtensionUrlProviders(callback) {
const sf = this.getServiceFramework("SEO");
sf.get("GetExtensionUrlProviders", {}, callback);
}
updateExtensionUrlProviderStatus(payload, callback, failureCallback) {
const sf = this.getServiceFramework("SEO");
sf.post("UpdateExtensionUrlProviderStatus", payload, callback, failureCallback);
}
}
const applicationService = new ApplicationService();
export default applicationService; | dnnsoftware/Dnn.AdminExperience.Extensions | src/Modules/Settings/Dnn.PersonaBar.Seo/Seo.Web/src/services/applicationService.js | JavaScript | mit | 2,914 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
'use strict';
// THIS CHECK SHOULD BE THE FIRST THING IN THIS FILE
// This is to ensure that we catch env issues before we error while requiring other dependencies.
const engines = require('./package.json').engines;
require('./tools/check-environment')({
requiredNodeVersion: engines.node,
requiredNpmVersion: engines.npm,
requiredYarnVersion: engines.yarn
});
const gulp = require('gulp');
// See `tools/gulp-tasks/README.md` for information about task loading.
function loadTask(fileName, taskName) {
const taskModule = require('./tools/gulp-tasks/' + fileName);
const task = taskName ? taskModule[taskName] : taskModule;
return task(gulp);
}
gulp.task('format:enforce', loadTask('format', 'enforce'));
gulp.task('format', loadTask('format', 'format'));
gulp.task('build.sh', loadTask('build', 'all'));
gulp.task('build.sh:no-bundle', loadTask('build', 'no-bundle'));
gulp.task('public-api:enforce', loadTask('public-api', 'enforce'));
gulp.task('public-api:update', ['build.sh'], loadTask('public-api', 'update'));
gulp.task('lint', ['format:enforce', 'validate-commit-messages', 'tslint']);
gulp.task('tslint', ['tools:build'], loadTask('lint'));
gulp.task('validate-commit-messages', loadTask('validate-commit-message'));
gulp.task('tools:build', loadTask('tools-build'));
gulp.task('check-cycle', loadTask('check-cycle'));
gulp.task('serve', loadTask('serve', 'default'));
gulp.task('serve-examples', loadTask('serve', 'examples'));
gulp.task('changelog', loadTask('changelog'));
gulp.task('check-env', () => {/* this is a noop because the env test ran already above */});
| chalin/angular | gulpfile.js | JavaScript | mit | 1,800 |
function initMessaging(){var e=[];chrome.runtime.onMessage.addListener(function(n,t){n.source=n.target=kango,"undefined"!=typeof n.tab&&(kango.tab.isPrivate=function(){return n.tab.isPrivate});for(var r=0;r<e.length;r++)e[r](n)}),kango.dispatchMessage=function(e,n){var t={name:e,data:n,origin:"tab",source:null,target:null};return chrome.runtime.sendMessage(t),!0},kango.addEventListener=function(n,t){if("message"==n){for(var r=0;r<e.length;r++)if(e[r]==t)return;e.push(t)}}}kango.browser={getName:function(){return"chrome"}},kango.io={getResourceUrl:function(e){return chrome.extension.getURL(e)}}; | boxfoot/toolkit-for-ynab | lib/kango-framework-latest/src/js/chrome/includes/content_kango.part.js | JavaScript | mit | 601 |
QUnit.module('pages > strategy > tabs > logger', function () {
const logger = KC3StrategyTabs.logger.definition;
QUnit.module('filters > logTypes', {
beforeEach() { this.subject = logger.filterFuncs.logTypes; },
}, function () {
QUnit.test('check type is set to visible', function (assert) {
logger.filterState.logTypes = { yellow: true, purple: false };
assert.ok(this.subject({ type: 'yellow' }));
assert.notOk(this.subject({ type: 'purple' }));
});
});
QUnit.module('filters > contexts', {
beforeEach() { this.subject = logger.filterFuncs.contexts; },
}, function () {
QUnit.test('check context is set to visible', function (assert) {
logger.filterState.contexts = { banana: true, potato: false };
assert.ok(this.subject({ context: 'banana' }));
assert.notOk(this.subject({ context: 'potato' }));
});
});
QUnit.module('filters > logSearch', {
beforeEach() { this.subject = logger.filterFuncs.logSearch; },
}, function () {
QUnit.test('search message', function (assert) {
logger.filterState.logSearch = 'small';
assert.equal(this.subject({ message: 'a big blue dog' }), false);
assert.equal(this.subject({ message: 'a small blue dog' }), true);
});
QUnit.test('search data', function (assert) {
logger.filterState.logSearch = 'banana';
assert.equal(this.subject({ data: ['red', 'blue'] }), false);
assert.equal(this.subject({ data: ['apple', 'orange', 'banana'] }), true);
});
QUnit.test('case-insensitive search', function (assert) {
logger.filterState.logSearch = 'tea';
assert.equal(this.subject({ message: 'Drinks', data: ['Coffee', 'TEA'] }), true);
});
});
QUnit.module('isDateSplit', {
beforeEach() { this.subject = logger.isDateSplit; },
}, function () {
QUnit.test('true if specified times are on different days', function (assert) {
const result = this.subject({ timestamp: new Date(2017, 1, 1).getTime() },
{ timestamp: new Date(2017, 1, 2).getTime() });
assert.equal(result, true);
});
QUnit.test('false if specified times are on the same day', function (assert) {
const result = this.subject({ timestamp: new Date(2017, 1, 1, 5) },
{ timestamp: new Date(2017, 1, 1, 20) });
assert.equal(result, false);
});
});
QUnit.module('createDateSeparator', {
beforeEach() { this.subject = logger.createDateSeparator; },
}, function () {
QUnit.test('success', function (assert) {
const entry = { timestamp: new Date().getTime() };
const result = this.subject(entry);
assert.deepEqual(result, {
type: 'dateSeparator',
timestamp: entry.timestamp,
});
});
});
QUnit.module('elementFactory > error > formatStack', {
beforeEach() { this.subject = logger.formatStack; },
}, function () {
QUnit.test('undefined stack', function (assert) {
const result = this.subject();
assert.equal(result, '');
});
QUnit.test('replace chrome extension id', function (assert) {
const stack = `at loadLogEntries (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/pages/strategy/tabs/logger/logger.js:56:18)
at Object.execute (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/pages/strategy/tabs/logger/logger.js:30:21)
at chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/library/objects/StrategyTab.js:80:21
at Object.success (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/library/objects/StrategyTab.js:40:6)
at i (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:2:27151)
at Object.fireWith [as resolveWith] (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:2:27914)
at z (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:4:12059)
at XMLHttpRequest.<anonymous> (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:4:15619)`;
const result = this.subject(stack);
assert.equal(result, `at loadLogEntries (src/pages/strategy/tabs/logger/logger.js:56:18)
at Object.execute (src/pages/strategy/tabs/logger/logger.js:30:21)
at src/library/objects/StrategyTab.js:80:21
at Object.success (src/library/objects/StrategyTab.js:40:6)
at i (src/assets/js/jquery.min.js:2:27151)
at Object.fireWith [as resolveWith] (src/assets/js/jquery.min.js:2:27914)
at z (src/assets/js/jquery.min.js:4:12059)
at XMLHttpRequest.<anonymous> (src/assets/js/jquery.min.js:4:15619)`);
});
});
QUnit.module('getCallsite', {
beforeEach() { this.subject = logger.getCallsite; },
}, function () {
QUnit.test('named function', function (assert) {
const stack = `Error: message
at loadLogEntries (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/pages/strategy/tabs/logger/logger.js:56:18)
at Object.execute (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/pages/strategy/tabs/logger/logger.js:30:21)
at chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/library/objects/StrategyTab.js:80:21
at Object.success (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/library/objects/StrategyTab.js:40:6)
at i (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:2:27151)
at Object.fireWith [as resolveWith] (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:2:27914)
at z (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:4:12059)
at XMLHttpRequest.<anonymous> (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:4:15619)`;
const result = this.subject(stack);
assert.deepEqual(result, {
short: 'logger.js:56',
full: 'src/pages/strategy/tabs/logger/logger.js:56:18',
});
});
QUnit.test('anonymous function', function (assert) {
const stack = `Error: gameScreenChg
at chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/library/modules/Service.js:471:12
at EventImpl.dispatchToListener (extensions::event_bindings:388:22)
at Event.publicClassPrototype.(anonymous function) [as dispatchToListener] (extensions::utils:149:26)
at EventImpl.dispatch_ (extensions::event_bindings:372:35)
at EventImpl.dispatch (extensions::event_bindings:394:17)
at Event.publicClassPrototype.(anonymous function) [as dispatch] (extensions::utils:149:26)
at messageListener (extensions::messaging:196:29)`;
const result = this.subject(stack);
assert.deepEqual(result, {
short: 'Service.js:471',
full: 'src/library/modules/Service.js:471:12',
});
});
});
});
| sinsinpub/KC3Kai | tests/pages/strategy/tabs/logger/logger.js | JavaScript | mit | 6,574 |
import { installation as ActionTypes, extension as ExtensionActionTypes } from "constants/actionTypes";
import { InstallationService } from "services";
const installationActions = {
parsePackage(file, callback, errorCallback) {
return (dispatch) => {
InstallationService.parsePackage(file, (data) => {
dispatch({
type: ActionTypes.PARSED_INSTALLATION_PACKAGE,
payload: JSON.parse(data)
});
if (callback) {
callback(data);
}
}, errorCallback);
};
},
navigateWizard(wizardStep, callback) {
return (dispatch) => {
dispatch({
type: ActionTypes.GO_TO_WIZARD_STEP,
payload: {
wizardStep
}
});
if (callback) {
setTimeout(() => {
callback();
}, 0);
}
};
},
setInstallingAvailablePackage(FileName, PackageType, callback) {
return (dispatch) => {
dispatch({
type: ActionTypes.INSTALLING_AVAILABLE_PACKAGE,
payload: {
PackageType,
FileName
}
});
if (callback) {
setTimeout(() => {
callback();
}, 0);
}
};
},
notInstallingAvailablePackage(callback) {
return (dispatch) => {
dispatch({
type: ActionTypes.NOT_INSTALLING_AVAILABLE_PACKAGE
});
if (callback) {
setTimeout(() => {
callback();
}, 0);
}
};
},
installExtension(file, newExtension, legacyType, isPortalPackage, callback, addToList) {
let _newExtension = JSON.parse(JSON.stringify(newExtension));
return (dispatch) => {
InstallationService.installPackage(file, legacyType, isPortalPackage, (data) => {
dispatch({
type: ActionTypes.INSTALLED_EXTENSION_LOGS,
payload: JSON.parse(data)
});
if (addToList) {
_newExtension.packageId = JSON.parse(data).newPackageId;
_newExtension.inUse = "No";
dispatch({
type: ExtensionActionTypes.INSTALLED_EXTENSION,
payload: {
PackageInfo: _newExtension,
logs: JSON.parse(data).logs
}
});
}
if (callback) {
callback(data);
}
});
};
},
clearParsedInstallationPackage(callback) {
return (dispatch) => {
dispatch({
type: ActionTypes.CLEAR_PARSED_INSTALLATION_PACKAGE
});
if (callback) {
callback();
}
};
},
toggleAcceptLicense(value, callback) {
return (dispatch) => {
dispatch({
type: ActionTypes.TOGGLE_ACCEPT_LICENSE,
payload: value
});
if (callback) {
callback();
}
};
},
setViewingLog(value, callback) {
return (dispatch) => {
dispatch({
type: ActionTypes.TOGGLE_VIEWING_LOG,
payload: value
});
if (callback) {
callback();
}
};
},
setIsPortalPackage(value, callback) {
return (dispatch) => {
dispatch({
type: ActionTypes.SET_IS_PORTAL_PACKAGE,
payload: value
});
if (callback) {
callback();
}
};
}
};
export default installationActions;
| dnnsoftware/Dnn.AdminExperience.Extensions | src/Modules/Settings/Dnn.PersonaBar.Extensions/Extensions.Web/src/actions/installation.js | JavaScript | mit | 4,016 |
'use strict';
/* Controllers */
app
// Flot Chart controller
.controller('FlotChartDemoCtrl', ['$scope', function($scope) {
$scope.d = [ [1,6.5],[2,6.5],[3,7],[4,8],[5,7.5],[6,7],[7,6.8],[8,7],[9,7.2],[10,7],[11,6.8],[12,7] ];
$scope.d0_1 = [ [0,7],[1,6.5],[2,12.5],[3,7],[4,9],[5,6],[6,11],[7,6.5],[8,8],[9,7] ];
$scope.d0_2 = [ [0,4],[1,4.5],[2,7],[3,4.5],[4,3],[5,3.5],[6,6],[7,3],[8,4],[9,3] ];
$scope.d1_1 = [ [10, 120], [20, 70], [30, 70], [40, 60] ];
$scope.d1_2 = [ [10, 50], [20, 60], [30, 90], [40, 35] ];
$scope.d1_3 = [ [10, 80], [20, 40], [30, 30], [40, 20] ];
$scope.d2 = [];
for (var i = 0; i < 20; ++i) {
$scope.d2.push([i, Math.round( Math.sin(i)*100)/100] );
}
$scope.d3 = [
{ label: "iPhone5S", data: 40 },
{ label: "iPad Mini", data: 10 },
{ label: "iPad Mini Retina", data: 20 },
{ label: "iPhone4S", data: 12 },
{ label: "iPad Air", data: 18 }
];
$scope.refreshData = function(){
$scope.d0_1 = $scope.d0_2;
};
$scope.getRandomData = function() {
var data = [],
totalPoints = 150;
if (data.length > 0)
data = data.slice(1);
while (data.length < totalPoints) {
var prev = data.length > 0 ? data[data.length - 1] : 50,
y = prev + Math.random() * 10 - 5;
if (y < 0) {
y = 0;
} else if (y > 100) {
y = 100;
}
data.push(Math.round(y*100)/100);
}
// Zip the generated y values with the x values
var res = [];
for (var i = 0; i < data.length; ++i) {
res.push([i, data[i]])
}
return res;
}
$scope.d4 = $scope.getRandomData();
}]);
| tahirakhan/bilal-cattle-farm | public/src/js/controllers/chart.js | JavaScript | mit | 1,725 |
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
/***************************************************
* Color utilities
***************************************************/
define('TYPO3/CMS/Rtehtmlarea/HTMLArea/Util/String',
['TYPO3/CMS/Rtehtmlarea/HTMLArea/UserAgent/UserAgent'],
function (UserAgent) {
// Create the ruler
if (!document.getElementById('htmlarea-ruler')) {
// Insert the css rule in the stylesheet
var styleSheet = document.styleSheets[0];
var selector = '#htmlarea-ruler';
var style = 'visibility: hidden; white-space: nowrap;';
var rule = selector + ' { ' + style + ' }';
if (!UserAgent.isIEBeforeIE9) {
try {
styleSheet.insertRule(rule, styleSheet.cssRules.length);
} catch (e) {}
} else {
styleSheet.addRule(selector, style);
}
//Insert the ruler on the document
var ruler = document.createElement('span');
ruler.setAttribute('id', 'htmlarea-ruler');
document.body.appendChild(ruler);
}
/**
* Get the visual length of a string
*/
String.prototype.visualLength = function() {
var ruler = document.getElementById('htmlarea-ruler');
ruler.innerHTML = this;
return ruler.offsetWidth;
};
/**
* Set an ellipsis on a string
*/
String.prototype.ellipsis = function(length) {
var temp = this;
var trimmed = this;
if (temp.visualLength() > length) {
trimmed += "...";
while (trimmed.visualLength() > length) {
temp = temp.substring(0, temp.length-1);
trimmed = temp + "...";
}
}
return trimmed;
};
});
| Loopshape/Portfolio | typo3_src-7.3.1/typo3/sysext/rtehtmlarea/Resources/Public/JavaScript/HTMLArea/Util/String.js | JavaScript | gpl-2.0 | 1,882 |
/*
Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang("codesnippet","bg",{button:"Въвеждане на блок с код",codeContents:"Съдържание на кода",emptySnippetError:"Блока с код не може да бъде празен.",language:"Език",title:"Блок с код",pathName:"блок с код"}); | maddy2101/TYPO3.CMS | typo3/sysext/rte_ckeditor/Resources/Public/JavaScript/Contrib/plugins/codesnippet/lang/bg.js | JavaScript | gpl-2.0 | 477 |
DV.Schema.helpers = {
HOST_EXTRACTOR : (/https?:\/\/([^\/]+)\//),
annotationClassName: '.DV-annotation',
// Bind all events for the docviewer
// live/delegate are the preferred methods of event attachment
bindEvents: function(context){
var boundZoom = this.events.compile('zoom');
var doc = context.models.document;
var value = _.indexOf(doc.ZOOM_RANGES, doc.zoomLevel);
var viewer = this.viewer;
viewer.slider = viewer.$('.DV-zoomBox').slider({
step: 1,
min: 0,
max: 4,
value: value,
slide: function(el,d){
boundZoom(context.models.document.ZOOM_RANGES[parseInt(d.value, 10)]);
},
change: function(el,d){
boundZoom(context.models.document.ZOOM_RANGES[parseInt(d.value, 10)]);
}
});
// next/previous
var history = viewer.history;
var compiled = viewer.compiled;
compiled.next = this.events.compile('next');
compiled.previous = this.events.compile('previous');
var states = context.states;
viewer.$('.DV-navControls').delegate('span.DV-next','click', compiled.next);
viewer.$('.DV-navControls').delegate('span.DV-previous','click', compiled.previous);
viewer.$('.DV-annotationView').delegate('.DV-trigger','click',function(e){
e.preventDefault();
context.open('ViewAnnotation');
});
viewer.$('.DV-documentView').delegate('.DV-trigger','click',function(e){
// history.save('document/p'+context.models.document.currentPage());
context.open('ViewDocument');
});
viewer.$('.DV-thumbnailsView').delegate('.DV-trigger','click',function(e){
context.open('ViewThumbnails');
});
viewer.$('.DV-textView').delegate('.DV-trigger','click',function(e){
// history.save('text/p'+context.models.document.currentPage());
context.open('ViewText');
});
viewer.$('.DV-allAnnotations').delegate('.DV-annotationGoto .DV-trigger','click', DV.jQuery.proxy(this.gotoPage, this));
viewer.$('.DV-allAnnotations').delegate('.DV-annotationTitle .DV-trigger','click', DV.jQuery.proxy(this.gotoPage, this));
viewer.$('form.DV-searchDocument').submit(this.events.compile('search'));
viewer.$('.DV-searchBar').delegate('.DV-closeSearch','click',function(e){
viewer.$('.DV-searchBar').fadeOut(250);
e.preventDefault();
// history.save('text/p'+context.models.document.currentPage());
});
viewer.$('.DV-searchBox').delegate('.DV-searchInput-cancel', 'click', DV.jQuery.proxy(this.clearSearch, this));
viewer.$('.DV-searchResults').delegate('span.DV-resultPrevious','click', DV.jQuery.proxy(this.highlightPreviousMatch, this));
viewer.$('.DV-searchResults').delegate('span.DV-resultNext','click', DV.jQuery.proxy(this.highlightNextMatch, this));
// Prevent navigation elements from being selectable when clicked.
viewer.$('.DV-trigger').bind('selectstart', function(){ return false; });
this.elements.viewer.delegate('.DV-fullscreen', 'click', _.bind(this.openFullScreen, this));
var boundToggle = DV.jQuery.proxy(this.annotationBridgeToggle, this);
var collection = this.elements.collection;
collection.delegate('.DV-annotationTab','click', boundToggle);
collection.delegate('.DV-annotationRegion','click', DV.jQuery.proxy(this.annotationBridgeShow, this));
collection.delegate('.DV-annotationNext','click', DV.jQuery.proxy(this.annotationBridgeNext, this));
collection.delegate('.DV-annotationPrevious','click', DV.jQuery.proxy(this.annotationBridgePrevious, this));
collection.delegate('.DV-showEdit','click', DV.jQuery.proxy(this.showAnnotationEdit, this));
collection.delegate('.DV-cancelEdit','click', DV.jQuery.proxy(this.cancelAnnotationEdit, this));
collection.delegate('.DV-saveAnnotation','click', DV.jQuery.proxy(this.saveAnnotation, this));
collection.delegate('.DV-saveAnnotationDraft','click', DV.jQuery.proxy(this.saveAnnotation, this));
collection.delegate('.DV-deleteAnnotation','click', DV.jQuery.proxy(this.deleteAnnotation, this));
collection.delegate('.DV-pageNumber', 'click', _.bind(this.permalinkPage, this, 'document'));
collection.delegate('.DV-textCurrentPage', 'click', _.bind(this.permalinkPage, this, 'text'));
collection.delegate('.DV-annotationTitle', 'click', _.bind(this.permalinkAnnotation, this));
collection.delegate('.DV-permalink', 'click', _.bind(this.permalinkAnnotation, this));
// Thumbnails
viewer.$('.DV-thumbnails').delegate('.DV-thumbnail-page', 'click', function(e) {
var $thumbnail = viewer.$(e.currentTarget);
if (!viewer.openEditor) {
var pageIndex = $thumbnail.closest('.DV-thumbnail').attr('data-pageNumber') - 1;
viewer.models.document.setPageIndex(pageIndex);
viewer.open('ViewDocument');
// viewer.history.save('document/p'+pageNumber);
}
});
// Handle iPad / iPhone scroll events...
_.bindAll(this, 'touchStart', 'touchMove', 'touchEnd');
this.elements.window[0].ontouchstart = this.touchStart;
this.elements.window[0].ontouchmove = this.touchMove;
this.elements.window[0].ontouchend = this.touchEnd;
this.elements.well[0].ontouchstart = this.touchStart;
this.elements.well[0].ontouchmove = this.touchMove;
this.elements.well[0].ontouchend = this.touchEnd;
viewer.$('.DV-descriptionToggle').live('click',function(e){
e.preventDefault();
e.stopPropagation();
viewer.$('.DV-descriptionText').toggle();
viewer.$('.DV-descriptionToggle').toggleClass('DV-showDescription');
});
var cleanUp = DV.jQuery.proxy(viewer.pageSet.cleanUp, this);
this.elements.window.live('mousedown',
function(e){
var el = viewer.$(e.target);
if (el.parents().is('.DV-annotation') || el.is('.DV-annotation')) return true;
if(context.elements.window.hasClass('DV-coverVisible')){
if((el.width() - parseInt(e.clientX,10)) >= 15){
cleanUp();
}
}
}
);
var docId = viewer.schema.document.id;
//if(DV.jQuery.browser.msie == true){
// this.elements.browserDocument.bind('focus.' + docId, DV.jQuery.proxy(this.focusWindow,this));
// this.elements.browserDocument.bind('focusout.' + docId, DV.jQuery.proxy(this.focusOut,this));
// }else{
this.elements.browserWindow.bind('focus.' + docId, DV.jQuery.proxy(this.focusWindow,this));
this.elements.browserWindow.bind('blur.' + docId, DV.jQuery.proxy(this.blurWindow,this));
// }
// When the document is scrolled, even in the background, resume polling.
this.elements.window.bind('scroll.' + docId, DV.jQuery.proxy(this.focusWindow, this));
this.elements.coverPages.live('mousedown', cleanUp);
viewer.acceptInput = this.elements.currentPage.acceptInput({ changeCallBack: DV.jQuery.proxy(this.acceptInputCallBack,this) });
},
// Unbind jQuery events that have been bound to objects outside of the viewer.
unbindEvents: function() {
var viewer = this.viewer;
var docId = viewer.schema.document.id;
if(DV.jQuery.browser.msie == true){
this.elements.browserDocument.unbind('focus.' + docId);
this.elements.browserDocument.unbind('focusout.' + docId);
}else{
viewer.helpers.elements.browserWindow.unbind('focus.' + docId);
viewer.helpers.elements.browserWindow.unbind('blur.' + docId);
}
viewer.helpers.elements.browserWindow.unbind('scroll.' + docId);
_.each(viewer.observers, function(obs){ viewer.helpers.removeObserver(obs); });
},
// We're entering the Notes tab -- make sure that there are no data-src
// attributes remaining.
ensureAnnotationImages : function() {
this.viewer.$(".DV-img[data-src]").each(function() {
var el = DV.jQuery(this);
el.attr('src', el.attr('data-src'));
});
},
startCheckTimer: function(){
var _t = this.viewer;
var _check = function(){
_t.events.check();
};
this.viewer.checkTimer = setInterval(_check,100);
},
stopCheckTimer: function(){
clearInterval(this.viewer.checkTimer);
},
blurWindow: function(){
if(this.viewer.isFocus === true){
this.viewer.isFocus = false;
// pause draw timer
this.stopCheckTimer();
}else{
return;
}
},
focusOut: function(){
if(this.viewer.activeElement != document.activeElement){
this.viewer.activeElement = document.activeElement;
this.viewer.isFocus = true;
}else{
// pause draw timer
this.viewer.isFocus = false;
this.viewer.helpers.stopCheckTimer();
return;
}
},
focusWindow: function(){
if(this.viewer.isFocus === true){
return;
}else{
this.viewer.isFocus = true;
// restart draw timer
this.startCheckTimer();
}
},
touchStart : function(e) {
e.stopPropagation();
e.preventDefault();
var touch = e.changedTouches[0];
this._moved = false;
this._touchX = touch.pageX;
this._touchY = touch.pageY;
},
touchMove : function(e) {
var el = e.currentTarget;
var touch = e.changedTouches[0];
var xDiff = this._touchX - touch.pageX;
var yDiff = this._touchY - touch.pageY;
el.scrollLeft += xDiff;
el.scrollTop += yDiff;
this._touchX -= xDiff;
this._touchY -= yDiff;
if (yDiff != 0 || xDiff != 0) this._moved = true;
},
touchEnd : function(e) {
if (!this._moved) {
var touch = e.changedTouches[0];
var target = touch.target;
var fakeClick = document.createEvent('MouseEvent');
while (target.nodeType !== 1) target = target.parentNode;
fakeClick.initMouseEvent('click', true, true, touch.view, 1,
touch.screenX, touch.screenY, touch.clientX, touch.clientY,
false, false, false, false, 0, null);
target.dispatchEvent(fakeClick);
}
this._moved = false;
},
// Click to open a page's permalink.
permalinkPage : function(mode, e) {
if (mode == 'text') {
var number = this.viewer.models.document.currentPage();
} else {
var pageId = this.viewer.$(e.target).closest('.DV-set').attr('data-id');
var page = this.viewer.pageSet.pages[pageId];
var number = page.pageNumber;
this.jump(page.index);
}
this.viewer.history.save(mode + '/p' + number);
},
// Click to open an annotation's permalink.
permalinkAnnotation : function(e) {
var id = this.viewer.$(e.target).closest('.DV-annotation').attr('data-id');
var anno = this.viewer.models.annotations.getAnnotation(id);
var sid = anno.server_id || anno.id;
if (this.viewer.state == 'ViewDocument') {
this.viewer.pageSet.showAnnotation(anno);
this.viewer.history.save('document/p' + anno.pageNumber + '/a' + sid);
} else {
this.viewer.history.save('annotation/a' + sid);
}
},
setDocHeight: function(height,diff) {
this.elements.bar.css('height', height);
this.elements.window[0].scrollTop += diff;
},
getWindowDimensions: function(){
var d = {
height: window.innerHeight ? window.innerHeight : this.elements.browserWindow.height(),
width: this.elements.browserWindow.width()
};
return d;
},
// Is the given URL on a remote domain?
isCrossDomain : function(url) {
var match = url.match(this.HOST_EXTRACTOR);
return match && (match[1] != window.location.host);
},
resetScrollState: function(){
this.elements.window.scrollTop(0);
},
gotoPage: function(e){
e.preventDefault();
var aid = this.viewer.$(e.target).parents('.DV-annotation').attr('rel').replace('aid-','');
var annotation = this.models.annotations.getAnnotation(aid);
var viewer = this.viewer;
if(viewer.state !== 'ViewDocument'){
this.models.document.setPageIndex(annotation.index);
viewer.open('ViewDocument');
// this.viewer.history.save('document/p'+(parseInt(annotation.index,10)+1));
}
},
openFullScreen : function() {
var doc = this.viewer.schema.document;
var url = doc.canonicalURL.replace(/#\S+$/,"");
var currentPage = this.models.document.currentPage();
// construct url fragment based on current viewer state
switch (this.viewer.state) {
case 'ViewAnnotation':
url += '#annotation/a' + this.viewer.activeAnnotationId; // default to the top of the annotations page.
break;
case 'ViewDocument':
url += '#document/p' + currentPage;
break;
case 'ViewSearch':
url += '#search/p' + currentPage + '/' + encodeURIComponent(this.elements.searchInput.val());
break;
case 'ViewText':
url += '#text/p' + currentPage;
break;
case 'ViewThumbnails':
url += '#pages/p' + currentPage; // need to set up a route to catch this.
break;
}
window.open(url, "documentviewer", "toolbar=no,resizable=yes,scrollbars=no,status=no");
},
// Determine the correct DOM page ordering for a given page index.
sortPages : function(pageIndex) {
if (pageIndex == 0 || pageIndex % 3 == 1) return ['p0', 'p1', 'p2'];
if (pageIndex % 3 == 2) return ['p1', 'p2', 'p0'];
if (pageIndex % 3 == 0) return ['p2', 'p0', 'p1'];
},
addObserver: function(observerName){
this.removeObserver(observerName);
this.viewer.observers.push(observerName);
},
removeObserver: function(observerName){
var observers = this.viewer.observers;
for(var i = 0,len=observers.length;i<len;i++){
if(observerName === observers[i]){
observers.splice(i,1);
}
}
},
toggleContent: function(toggleClassName){
this.elements.viewer.removeClass('DV-viewText DV-viewSearch DV-viewDocument DV-viewAnnotations DV-viewThumbnails').addClass('DV-'+toggleClassName);
},
jump: function(pageIndex, modifier, forceRedraw){
modifier = (modifier) ? parseInt(modifier, 10) : 0;
var position = this.models.document.getOffset(parseInt(pageIndex, 10)) + modifier;
this.elements.window[0].scrollTop = position;
this.models.document.setPageIndex(pageIndex);
if (forceRedraw) this.viewer.pageSet.redraw(true);
if (this.viewer.state === 'ViewThumbnails') {
this.viewer.thumbnails.highlightCurrentPage();
}
},
shift: function(argHash){
var windowEl = this.elements.window;
var scrollTopShift = windowEl.scrollTop() + argHash.deltaY;
var scrollLeftShift = windowEl.scrollLeft() + argHash.deltaX;
windowEl.scrollTop(scrollTopShift);
windowEl.scrollLeft(scrollLeftShift);
},
getAppState: function(){
var docModel = this.models.document;
var currentPage = (docModel.currentIndex() == 0) ? 1 : docModel.currentPage();
return { page: currentPage, zoom: docModel.zoomLevel, view: this.viewer.state };
},
constructPages: function(){
var pages = [];
var totalPagesToCreate = (this.viewer.schema.data.totalPages < 3) ? this.viewer.schema.data.totalPages : 3;
var height = this.models.pages.height;
for (var i = 0; i < totalPagesToCreate; i++) {
pages.push(JST.pages({ pageNumber: i+1, pageIndex: i , pageImageSource: null, baseHeight: height }));
}
return pages.join('');
},
// Position the viewer on the page. For a full screen viewer, this means
// absolute from the current y offset to the bottom of the viewport.
positionViewer : function() {
var offset = this.elements.viewer.position();
this.elements.viewer.css({position: 'absolute', top: offset.top, bottom: 0, left: offset.left, right: offset.left});
},
unsupportedBrowser : function() {
if (!(DV.jQuery.browser.msie && DV.jQuery.browser.version <= "6.0")) return false;
DV.jQuery(this.viewer.options.container).html(JST.unsupported({viewer : this.viewer}));
return true;
},
registerHashChangeEvents: function(){
var events = this.events;
var history = this.viewer.history;
// Default route
history.defaultCallback = _.bind(events.handleHashChangeDefault,this.events);
// Handle page loading
history.register(/document\/p(\d*)$/, _.bind(events.handleHashChangeViewDocumentPage,this.events));
// Legacy NYT stuff
history.register(/p(\d*)$/, _.bind(events.handleHashChangeLegacyViewDocumentPage,this.events));
history.register(/p=(\d*)$/, _.bind(events.handleHashChangeLegacyViewDocumentPage,this.events));
// Handle annotation loading in document view
history.register(/document\/p(\d*)\/a(\d*)$/, _.bind(events.handleHashChangeViewDocumentAnnotation,this.events));
// Handle annotation loading in annotation view
history.register(/annotation\/a(\d*)$/, _.bind(events.handleHashChangeViewAnnotationAnnotation,this.events));
// Handle loading of the pages view
history.register(/pages$/, _.bind(events.handleHashChangeViewPages, events));
// Handle page loading in text view
history.register(/text\/p(\d*)$/, _.bind(events.handleHashChangeViewText,this.events));
// Handle entity display requests.
history.register(/entity\/p(\d*)\/(.*)\/(\d+):(\d+)$/, _.bind(events.handleHashChangeViewEntity,this.events));
// Handle search requests
history.register(/search\/p(\d*)\/(.*)$/, _.bind(events.handleHashChangeViewSearchRequest,this.events));
},
// Sets up the zoom slider to match the appropriate for the specified
// initial zoom level, and real document page sizes.
autoZoomPage: function() {
var windowWidth = this.elements.window.outerWidth(true);
var zoom;
if (this.viewer.options.zoom == 'auto') {
zoom = Math.min(
700,
windowWidth - (this.viewer.models.pages.REDUCED_PADDING * 2)
);
} else {
zoom = this.viewer.options.zoom;
}
// Setup ranges for auto-width zooming
var ranges = [];
if (zoom <= 500) {
var zoom2 = (zoom + 700) / 2;
ranges = [zoom, zoom2, 700, 850, 1000];
} else if (zoom <= 750) {
var zoom2 = ((1000 - 700) / 3) + zoom;
var zoom3 = ((1000 - 700) / 3)*2 + zoom;
ranges = [.66*zoom, zoom, zoom2, zoom3, 1000];
} else if (750 < zoom && zoom <= 850){
var zoom2 = ((1000 - zoom) / 2) + zoom;
ranges = [.66*zoom, 700, zoom, zoom2, 1000];
} else if (850 < zoom && zoom < 1000){
var zoom2 = ((zoom - 700) / 2) + 700;
ranges = [.66*zoom, 700, zoom2, zoom, 1000];
} else if (zoom >= 1000) {
zoom = 1000;
ranges = this.viewer.models.document.ZOOM_RANGES;
}
this.viewer.models.document.ZOOM_RANGES = ranges;
this.viewer.slider.slider({'value': parseInt(_.indexOf(ranges, zoom), 10)});
this.events.zoom(zoom);
},
handleInitialState: function(){
var initialRouteMatch = this.viewer.history.loadURL(true);
if(!initialRouteMatch) {
var opts = this.viewer.options;
this.viewer.open('ViewDocument');
if (opts.note) {
this.viewer.pageSet.showAnnotation(this.viewer.models.annotations.byId[opts.note]);
} else if (opts.page) {
this.jump(opts.page - 1);
}
}
}
};
| cloudbearings/providence | viewers/apps/src/nytDocumentViewer/public/javascripts/DV/helpers/helpers.js | JavaScript | gpl-3.0 | 19,944 |
// Plugin: jQuery.scrollSpeed
// Source: github.com/nathco/jQuery.scrollSpeed
// Author: Nathan Rutzky
// Update: 1.0.2
(function($) {
jQuery.scrollSpeed = function(step, speed, easing) {
var $document = $(document),
$window = $(window),
$body = $('html, body'),
option = easing || 'default',
root = 0,
scroll = false,
scrollY,
scrollX,
view;
if (window.navigator.msPointerEnabled)
return false;
$window.on('mousewheel DOMMouseScroll', function(e) {
var deltaY = e.originalEvent.wheelDeltaY,
detail = e.originalEvent.detail;
scrollY = $document.height() > $window.height();
scrollX = $document.width() > $window.width();
scroll = true;
if (scrollY) {
view = $window.height();
if (deltaY < 0 || detail > 0)
root = (root + view) >= $document.height() ? root : root += step;
if (deltaY > 0 || detail < 0)
root = root <= 0 ? 0 : root -= step;
$body.stop().animate({
scrollTop: root
}, speed, option, function() {
scroll = false;
});
}
if (scrollX) {
view = $window.width();
if (deltaY < 0 || detail > 0)
root = (root + view) >= $document.width() ? root : root += step;
if (deltaY > 0 || detail < 0)
root = root <= 0 ? 0 : root -= step;
$body.stop().animate({
scrollLeft: root
}, speed, option, function() {
scroll = false;
});
}
return false;
}).on('scroll', function() {
if (scrollY && !scroll) root = $window.scrollTop();
if (scrollX && !scroll) root = $window.scrollLeft();
}).on('resize', function() {
if (scrollY && !scroll) view = $window.height();
if (scrollX && !scroll) view = $window.width();
});
};
jQuery.easing.default = function (x,t,b,c,d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
};
})(jQuery); | haas26u/zu-store | web/libs/jQuery.scrollSpeed/jQuery.scrollSpeed.js | JavaScript | gpl-3.0 | 2,827 |
/* Copyright (c) Business Objects 2006. All rights reserved. */
/*
================================================================================
ParameterUI
Widget for displaying and editing parameter values. Contains one or many
ParameterValueRows and, optionally, UI that allows rows to be added.
================================================================================
*/
bobj.crv.params.newParameterUI = function(kwArgs) {
kwArgs = MochiKit.Base.update({
id: bobj.uniqueId(),
canChangeOnPanel: false,
allowCustom: false,
isPassword : false,
isReadOnlyParam: true,
allowRange : false,
values: [],
defaultValues: null,
width: '200px',
changeValueCB: null,
enterPressCB: null,
openAdvDialogCB: null,
maxNumParameterDefaultValues: 200,
tooltip : null,
calendarProperties : {displayValueFormat : '' , isTimeShown : false, hasButton : false, iconUrl : ''},
maxNumValuesDisplayed : 7,
canOpenAdvDialog : false
}, kwArgs);
var o = newWidget(kwArgs.id);
// Update instance with constructor arguments
bobj.fillIn(o, kwArgs);
o.displayAllValues = false;
// Update instance with member functions
MochiKit.Base.update(o, bobj.crv.params.ParameterUI);
o._createMenu();
o._rows = [];
o._infoRow = new bobj.crv.params.ParameterInfoRow(o.id);
return o;
};
bobj.crv.params.ParameterUI = {
/**
* Creates single menubar for all parameter value rows of current param UI
*/
_createMenu : function() {
var dvLength = this.defaultValues.length;
if (dvLength > 0) {
var kwArgs = {
originalValues : this.defaultValues
};
if (dvLength == this.maxNumParameterDefaultValues) {
kwArgs.originalValues[this.maxNumParameterDefaultValues] = L_bobj_crv_ParamsMaxNumDefaultValues;
MochiKit.Base.update (kwArgs, {
openAdvDialogCB : this.openAdvDialogCB,
maxNumParameterDefaultValues : this.maxNumParameterDefaultValues
});
}
this._defaultValuesMenu = bobj.crv.params.newScrollMenuWidget (kwArgs);
} else {
this._defaultValuesMenu = null;
}
},
setFocusOnRow : function(rowIndex) {
var row = this._rows[rowIndex];
if (row)
row.focus ();
},
/*
* Disables tabbing if dis is true
*/
setTabDisabled : function(dis) {
for(var i = 0, len = this._rows.length; i < len; i++) {
this._rows[i].setTabDisabled(dis);
}
this._infoRow.setTabDisabled(dis);
},
init : function() {
Widget_init.call (this);
var rows = this._rows;
for ( var i = 0, len = rows.length; i < len; ++i) {
rows[i].init ();
}
MochiKit.Signal.connect(this._infoRow, "switch", this, '_onSwitchDisplayAllValues');
this.refreshUI ();
},
/**
* Processes actions triggered by clicks on "x more values" or "collapse" button displayed in inforow
*/
_onSwitchDisplayAllValues: function() {
this.displayAllValues = !this.displayAllValues;
var TIME_INTERVAL = 10; /* 10 msec or 100 actions per second */
var timerIndex = 0;
if(this.displayAllValues) {
if (this.values.length > this._rows.length) {
for(var i = this._rows.length, l = this.values.length; i < l; i++) {
var addRow = function(paramUI, value) {
return function() { return paramUI._addRow(value); };
};
timerIndex++;
setTimeout(addRow(this, this.values[i]), TIME_INTERVAL * timerIndex);
}
}
}
else {
if(this._rows.length > this.maxNumValuesDisplayed) {
for(var i = this._rows.length -1; i >= this.maxNumValuesDisplayed; i--) {
var deleteRow = function(paramUI, rowIndex) {
return function() { return paramUI.deleteValue(rowIndex); };
};
timerIndex++;
setTimeout(deleteRow(this, i), TIME_INTERVAL * timerIndex);
}
}
}
var signalResize = function(paramUI) {
return function() {MochiKit.Signal.signal(paramUI, 'ParameterUIResized'); };
};
setTimeout(signalResize(this), TIME_INTERVAL * timerIndex);
},
getHTML : function() {
var rowsHtml = '';
var values = this.values;
var rows = this._rows;
var rowsCount = Math.min (values.length, this.maxNumValuesDisplayed);
for ( var i = 0; i < rowsCount; ++i) {
rows.push (this._getRow (values[i]));
rowsHtml += rows[i].getHTML ();
}
return bobj.html.DIV ( {
id : this.id,
style : {
width : bobj.unitValue (this.width),
'padding-left' : '20px'
}
}, rowsHtml);
},
_getNewValueRowArgs : function(value) {
return {
value : value,
defaultValues : this.defaultValues,
width : this.width,
isReadOnlyParam : this.isReadOnlyParam,
canChangeOnPanel : this.canChangeOnPanel,
allowCustom : this.allowCustom,
isPassword : this.isPassword,
calendarProperties : this.calendarProperties,
defaultValuesMenu : this._defaultValuesMenu,
tooltip : this.tooltip,
isRangeValue : this.allowRange,
canOpenAdvDialog : this.canOpenAdvDialog
};
},
_getNewValueRowConstructor : function() {
return bobj.crv.params.newParameterValueRow;
},
_getRow : function(value) {
var row = this._getNewValueRowConstructor()(this._getNewValueRowArgs(value));
var bind = MochiKit.Base.bind;
row.changeCB = bind(this._onChangeValue, this, row);
row.enterCB = bind(this._onEnterValue, this, row);
return row;
},
_addRow : function(value) {
var row = this._getRow (value);
this._rows.push (row);
append (this.layer, row.getHTML ());
row.init ();
this.refreshUI ();
return row;
},
_onChangeValue : function(row) {
if (this.changeValueCB) {
this.changeValueCB (this._getRowIndex (row), row.getValue ());
}
},
_onEnterValue : function(row) {
if (this.enterPressCB) {
this.enterPressCB (this._getRowIndex (row));
}
},
_getRowIndex : function(row) {
if (row) {
var rows = this._rows;
for ( var i = 0, len = rows.length; i < len; ++i) {
if (rows[i] === row) {
return i;
}
}
}
return -1;
},
getNumValues : function() {
return this._rows.length;
},
refreshUI : function() {
if (this.allowRange)
this.alignRangeRows ();
var displayInfoRow = false;
var infoRowText = "";
if (this.values.length > this.maxNumValuesDisplayed) {
displayInfoRow = true;
if(this.displayAllValues)
infoRowText = L_bobj_crv_Collapse;
else {
var hiddenValuesCount = this.values.length - this.maxNumValuesDisplayed;
infoRowText = (hiddenValuesCount == 1) ? L_bobj_crv_ParamsMoreValue : L_bobj_crv_ParamsMoreValues;
infoRowText = infoRowText.replace ("%1", hiddenValuesCount);
}
}
this._infoRow.setText (infoRowText);
this._infoRow.setVisible (displayInfoRow);
},
getValueAt : function(index) {
var row = this._rows[index];
if (row) {
return row.getValue ();
}
return null;
},
getValues : function() {
var values = [];
for ( var i = 0, len = this._rows.length; i < len; ++i) {
values.push (this._rows[i].getValue ());
}
return values;
},
setValueAt : function(index, value) {
var row = this._rows[index];
if (row) {
row.setValue (value);
}
this.refreshUI ();
},
resetValues : function(values) {
if (!values) {
return;
}
this.values = values;
var valuesLen = values.length;
var rowsLen = this._rows.length;
//Resets value
for ( var i = 0; i < valuesLen && i < rowsLen; ++i) {
this._rows[i].reset (values[i]);
}
//removes newly added values that are not commited
if (rowsLen > valuesLen) {
for ( var i = rowsLen - 1; i >= valuesLen; --i) {
// delete from the end to minimize calls to setBgColor
this.deleteValue (i);
}
}
//re-adds removed values
else if (valuesLen > rowsLen) {
for ( var i = rowsLen; i < valuesLen && (this.displayAllValues || i < this.maxNumValuesDisplayed); ++i) {
var row = this._addRow (values[i]);
}
}
MochiKit.Signal.signal(this, 'ParameterUIResized');
this.refreshUI ();
},
alignRangeRows : function() {
if (!this.allowRange)
return;
var lowerBoundWidth = 0;
for ( var i = 0, l = this._rows.length; i < l; i++) {
var row = this._rows[i];
var rangeField = row._valueWidget;
lowerBoundWidth = Math.max (lowerBoundWidth, rangeField.getLowerBoundValueWidth ());
}
for ( var i = 0, l = this._rows.length; i < l; i++) {
var row = this._rows[i];
var rangeField = row._valueWidget;
rangeField.setLowerBoundValueWidth (lowerBoundWidth);
}
},
setValues : function(values) {
if (!values)
return;
this.values = values;
var valuesLen = values.length;
var rowsLen = this._rows.length;
for ( var i = 0; i < valuesLen && i < rowsLen; ++i) {
this._rows[i].setValue (values[i]);
}
if (rowsLen > valuesLen) {
for ( var i = rowsLen - 1; i >= valuesLen; --i) {
// delete from the end to minimize calls to setBgColor
this.deleteValue (i);
}
} else if (valuesLen > rowsLen) {
for ( var i = rowsLen; i < valuesLen && (this.displayAllValues || i < this.maxNumValuesDisplayed); ++i) {
this._addRow (values[i]);
}
}
MochiKit.Signal.signal(this, 'ParameterUIResized');
this.refreshUI ();
},
setCleanValue : function(index, value) {
var row = this._rows[index];
if (row)
row.setCleanValue (value);
},
deleteValue : function(index) {
if (index >= 0 && index < this._rows.length) {
var row = this._rows[index];
row.layer.parentNode.removeChild (row.layer);
_widgets[row.widx] = null;
this._rows.splice (index, 1);
var rowsLen = this._rows.length;
}
this.refreshUI ();
},
setWarning : function(index, warning) {
var row = this._rows[index];
if (row) {
row.setWarning (warning);
}
},
getWarning : function(index) {
var row = this._rows[index];
if (row)
return row.getWarning ();
return null;
},
resize : function(w) {
if (w !== null) {
this.width = w;
if (this.layer) {
bobj.setOuterSize (this.layer, w);
}
}
}
};
| johndavedecano/tanghalangpasigenyo | aspnet_client/system_web/4_0_30319/crystalreportviewers13/js/crviewer/ParameterUI.js | JavaScript | gpl-3.0 | 12,193 |
/*
Copyright 2008-2015 Clipperz Srl
This file is part of Clipperz, the online password manager.
For further information about its features and functionalities please
refer to http://www.clipperz.com.
* Clipperz is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
* Clipperz is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public
License along with Clipperz. If not, see http://www.gnu.org/licenses/.
*/
Clipperz.Base.module('Clipperz.PM.UI.Web.Components');
//#############################################################################
Clipperz.PM.UI.Web.Components.FaviconColumnManager = function(args) {
args = args || {};
Clipperz.PM.UI.Web.Components.FaviconColumnManager.superclass.constructor.call(this, args);
return this;
}
//=============================================================================
Clipperz.Base.extend(Clipperz.PM.UI.Web.Components.FaviconColumnManager, Clipperz.PM.UI.Web.Components.ColumnManager, {
'toString': function () {
return "Clipperz.PM.UI.Web.Components.FaviconColumnManager component";
},
//-------------------------------------------------------------------------
'renderCell': function(aRowElement, anObject) {
var faviconImageElement;
var faviconUrl;
faviconImageElement = this.getId('favicon');
faviconUrl = anObject[this.name()];
if (faviconUrl == null) {
faviconUrl = Clipperz.PM.Strings.getValue('defaultFaviconUrl');
}
Clipperz.DOM.Helper.append(aRowElement, {tag:'td', cls:this.cssClass(), children:[
{tag:'img', id:faviconImageElement, src:faviconUrl}
]});
MochiKit.Signal.connect(faviconImageElement, 'onload', this, 'handleLoadedFaviconImage');
MochiKit.Signal.connect(faviconImageElement, 'onerror', this, 'handleMissingFaviconImage');
MochiKit.Signal.connect(faviconImageElement, 'onabort', this, 'handleMissingFaviconImage');
},
//-----------------------------------------------------
'handleLoadedFaviconImage': function(anEvent) {
MochiKit.Signal.disconnectAllTo(anEvent.src());
if (anEvent.src().complete == false) {
anEvent.src().src = Clipperz.PM.Strings.getValue('defaultFaviconUrl');
}
},
//-----------------------------------------------------
'handleMissingFaviconImage': function(anEvent) {
MochiKit.Signal.disconnectAllTo(anEvent.src());
anEvent.src().src = Clipperz.PM.Strings.getValue('defaultFaviconUrl');
},
//-----------------------------------------------------
'__syntax_fix__' : 'syntax fix'
});
| gcsolaroli/password-manager | frontend/gamma/js/Clipperz/PM/UI/Web/Components/FaviconColumnManager.js | JavaScript | agpl-3.0 | 2,902 |
const test = require('ava');
const {replaceUrls, toInaboxDocument} = require('../app-utils');
test('replaceUrls("minified", ...)', async (t) => {
const mode = 'minified';
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/v0.js"></script>'
),
'<script src="/dist/v0.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/shadow-v0.js"></script>'
),
'<script src="/dist/shadow-v0.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/amp4ads-v0.js"></script>'
),
'<script src="/dist/amp4ads-v0.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/video-iframe-integration-v0.js"></script>'
),
'<script src="/dist/video-iframe-integration-v0.js"></script>'
);
t.is(
replaceUrls(
mode,
'<link rel="stylesheet" href="https://cdn.ampproject.org/v0/amp-whatever-1.0.css" />'
),
'<link rel="stylesheet" href="/dist/v0/amp-whatever-1.0.css" />'
);
t.is(
replaceUrls(
mode,
`
<head>
<script src="https://cdn.ampproject.org/v0.js"></script>
<script src="https://cdn.ampproject.org/v0/amp-foo-0.1.js"></script>
<link rel="stylesheet" href="https://cdn.ampproject.org/v0/amp-foo-1.0.css" />
</head>
`
),
`
<head>
<script src="/dist/v0.js"></script>
<script src="/dist/v0/amp-foo-0.1.js"></script>
<link rel="stylesheet" href="/dist/v0/amp-foo-1.0.css" />
</head>
`
);
});
test('replaceUrls("minified", ..., hostName)', async (t) => {
const mode = 'minified';
const hostName = 'https://foo.bar';
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/v0.js"></script>',
hostName
),
'<script src="https://foo.bar/dist/v0.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/shadow-v0.js"></script>',
hostName
),
'<script src="https://foo.bar/dist/shadow-v0.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/amp4ads-v0.js"></script>',
hostName
),
'<script src="https://foo.bar/dist/amp4ads-v0.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/video-iframe-integration-v0.js"></script>',
hostName
),
'<script src="https://foo.bar/dist/video-iframe-integration-v0.js"></script>'
);
t.is(
replaceUrls(
mode,
'<link rel="stylesheet" href="https://cdn.ampproject.org/v0/amp-whatever-1.0.css" />',
hostName
),
'<link rel="stylesheet" href="https://foo.bar/dist/v0/amp-whatever-1.0.css" />'
);
t.is(
replaceUrls(
mode,
`
<head>
<script src="https://cdn.ampproject.org/v0.js"></script>
<script src="https://cdn.ampproject.org/v0/amp-foo-0.1.js"></script>
<link rel="stylesheet" href="https://cdn.ampproject.org/v0/amp-foo-1.0.css" />
</head>
`,
hostName
),
`
<head>
<script src="https://foo.bar/dist/v0.js"></script>
<script src="https://foo.bar/dist/v0/amp-foo-0.1.js"></script>
<link rel="stylesheet" href="https://foo.bar/dist/v0/amp-foo-1.0.css" />
</head>
`
);
});
test('replaceUrls("default", ...)', async (t) => {
const mode = 'default';
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/v0.js"></script>'
),
'<script src="/dist/amp.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/shadow-v0.js"></script>'
),
'<script src="/dist/amp-shadow.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/amp4ads-v0.js"></script>'
),
'<script src="/dist/amp-inabox.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/video-iframe-integration-v0.js"></script>'
),
'<script src="/dist/video-iframe-integration.js"></script>'
);
t.is(
replaceUrls(
mode,
'<link rel="stylesheet" href="https://cdn.ampproject.org/v0/amp-whatever-1.0.css" />'
),
'<link rel="stylesheet" href="/dist/v0/amp-whatever-1.0.css" />'
);
t.is(
replaceUrls(
mode,
`
<head>
<script src="https://cdn.ampproject.org/v0.js"></script>
<script src="https://cdn.ampproject.org/v0/amp-foo-0.1.js"></script>
<link rel="stylesheet" href="https://cdn.ampproject.org/v0/amp-foo-1.0.css" />
</head>
`
),
`
<head>
<script src="/dist/amp.js"></script>
<script src="/dist/v0/amp-foo-0.1.max.js"></script>
<link rel="stylesheet" href="/dist/v0/amp-foo-1.0.css" />
</head>
`
);
});
test('replaceUrls("default", ..., hostName)', async (t) => {
const mode = 'default';
const hostName = 'https://foo.bar';
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/v0.js"></script>',
hostName
),
'<script src="https://foo.bar/dist/amp.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/shadow-v0.js"></script>',
hostName
),
'<script src="https://foo.bar/dist/amp-shadow.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/amp4ads-v0.js"></script>',
hostName
),
'<script src="https://foo.bar/dist/amp-inabox.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/video-iframe-integration-v0.js"></script>',
hostName
),
'<script src="https://foo.bar/dist/video-iframe-integration.js"></script>'
);
t.is(
replaceUrls(
mode,
'<link rel="stylesheet" href="https://cdn.ampproject.org/v0/amp-whatever-1.0.css" />',
hostName
),
'<link rel="stylesheet" href="https://foo.bar/dist/v0/amp-whatever-1.0.css" />'
);
t.is(
replaceUrls(
mode,
`
<head>
<script src="https://cdn.ampproject.org/v0.js"></script>
<script src="https://cdn.ampproject.org/v0/amp-foo-0.1.js"></script>
<link rel="stylesheet" href="https://cdn.ampproject.org/v0/amp-foo-1.0.css" />
</head>
`,
hostName
),
`
<head>
<script src="https://foo.bar/dist/amp.js"></script>
<script src="https://foo.bar/dist/v0/amp-foo-0.1.max.js"></script>
<link rel="stylesheet" href="https://foo.bar/dist/v0/amp-foo-1.0.css" />
</head>
`
);
});
test('replaceUrls(rtv, ...)', async (t) => {
const mode = '123456789012345';
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/v0.js"></script>'
),
'<script src="https://cdn.ampproject.org/rtv/123456789012345/v0.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/shadow-v0.js"></script>'
),
'<script src="https://cdn.ampproject.org/rtv/123456789012345/shadow-v0.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/amp4ads-v0.js"></script>'
),
'<script src="https://cdn.ampproject.org/rtv/123456789012345/amp4ads-v0.js"></script>'
);
t.is(
replaceUrls(
mode,
'<script src="https://cdn.ampproject.org/video-iframe-integration-v0.js"></script>'
),
'<script src="https://cdn.ampproject.org/rtv/123456789012345/video-iframe-integration-v0.js"></script>'
);
t.is(
replaceUrls(
mode,
'<link rel="stylesheet" href="https://cdn.ampproject.org/v0/amp-whatever-1.0.css" />'
),
'<link rel="stylesheet" href="https://cdn.ampproject.org/rtv/123456789012345/v0/amp-whatever-1.0.css" />'
);
t.is(
replaceUrls(
mode,
`
<head>
<script src="https://cdn.ampproject.org/v0.js"></script>
<script src="https://cdn.ampproject.org/v0/amp-foo-0.1.js"></script>
<link rel="stylesheet" href="https://cdn.ampproject.org/v0/amp-foo-1.0.css" />
</head>
`
),
`
<head>
<script src="https://cdn.ampproject.org/rtv/123456789012345/v0.js"></script>
<script src="https://cdn.ampproject.org/rtv/123456789012345/v0/amp-foo-0.1.js"></script>
<link rel="stylesheet" href="https://cdn.ampproject.org/rtv/123456789012345/v0/amp-foo-1.0.css" />
</head>
`
);
});
test('toInaboxDocument(...)', async (t) => {
t.is(
toInaboxDocument(
`<html amp>
<head>
<script src="https://cdn.ampproject.org/v0.js"></script>
<script src="https://cdn.ampproject.org/v0/amp-video-0.1.js"></script>
</head>
</html>`
),
`<html amp4ads>
<head>
<script src="https://cdn.ampproject.org/amp4ads-v0.js"></script>
<script src="https://cdn.ampproject.org/v0/amp-video-0.1.js"></script>
</head>
</html>`
);
});
test('replaceUrls("minified", toInaboxDocument(...))', async (t) => {
const mode = 'minified';
const hostName = '';
t.is(
replaceUrls(
mode,
toInaboxDocument(
'<script src="https://cdn.ampproject.org/v0.js"></script>'
),
hostName
),
'<script src="/dist/amp4ads-v0.js"></script>'
);
});
test('replaceUrls("default", toInaboxDocument(...))', async (t) => {
const mode = 'default';
const hostName = '';
t.is(
replaceUrls(
mode,
toInaboxDocument(
'<script src="https://cdn.ampproject.org/v0.js"></script>'
),
hostName
),
'<script src="/dist/amp-inabox.js"></script>'
);
});
test('replaceUrls(rtv, toInaboxDocument(...))', async (t) => {
const mode = '123456789012345';
const hostName = '';
t.is(
replaceUrls(
mode,
toInaboxDocument(
'<script src="https://cdn.ampproject.org/v0.js"></script>'
),
hostName
),
'<script src="https://cdn.ampproject.org/rtv/123456789012345/amp4ads-v0.js"></script>'
);
});
| honeybadgerdontcare/amphtml | build-system/server/test/app-utils.test.js | JavaScript | apache-2.0 | 10,266 |
/**
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// @codekit-prepend 'third_party/signals.min.js'
// @codekit-prepend 'third_party/requestAnimationFrame.js'
var CDS = {};
// @codekit-append 'helper/event-publisher.js'
// @codekit-append 'helper/util.js'
// @codekit-append 'helper/history.js'
// @codekit-append 'helper/analytics.js'
// @codekit-append 'helper/theme.js'
// @codekit-append 'helper/video-embedder.js'
// @codekit-append 'components/button.js'
// @codekit-append 'components/card.js'
// @codekit-append 'components/cards.js'
// @codekit-append 'components/toast.js'
// @codekit-append 'components/masthead.js'
// @codekit-append 'components/schedule.js'
// @codekit-append 'bootstrap.js'
| andreimuntean/devsummit | src/static/scripts/cds.js | JavaScript | apache-2.0 | 1,278 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(async function() {
TestRunner.addResult(`Tests that stepInto doesn't pause in InjectedScriptSource.\n`);
await TestRunner.loadLegacyModule('sources'); await TestRunner.loadTestModule('sources_test_runner');
await TestRunner.showPanel('sources');
await TestRunner.evaluateInPagePromise(`
function testFunction()
{
debugger;
console.log(123);
return 239; // stack result should point here
}
`);
SourcesTestRunner.startDebuggerTestPromise(/* quiet */ true)
.then(() => SourcesTestRunner.runTestFunctionAndWaitUntilPausedPromise())
.then(() => stepIntoPromise())
.then(() => stepIntoPromise())
.then((callFrames) => SourcesTestRunner.captureStackTrace(callFrames))
.then(() => SourcesTestRunner.completeDebuggerTest());
function stepIntoPromise() {
var cb;
var p = new Promise(fullfill => cb = fullfill);
SourcesTestRunner.stepInto();
SourcesTestRunner.waitUntilResumed(() => SourcesTestRunner.waitUntilPaused(cb));
return p;
}
})();
| scheib/chromium | third_party/blink/web_tests/http/tests/devtools/sources/debugger-step/debugger-step-in-ignore-injected-script.js | JavaScript | bsd-3-clause | 1,215 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(async function() {
TestRunner.addResult(`Tests Summary view of detailed heap snapshots. The "Show All" button must show all nodes.\n`);
await TestRunner.loadTestModule('heap_profiler_test_runner');
await TestRunner.showPanel('heap_profiler');
var instanceCount = 25;
function createHeapSnapshot() {
return HeapProfilerTestRunner.createHeapSnapshot(instanceCount);
}
HeapProfilerTestRunner.runHeapSnapshotTestSuite([function testShowAll(next) {
HeapProfilerTestRunner.takeAndOpenSnapshot(createHeapSnapshot, step1);
function step1() {
HeapProfilerTestRunner.switchToView('Summary', step2);
}
function step2() {
var row = HeapProfilerTestRunner.findRow('A');
TestRunner.assertEquals(true, !!row, '"A" row');
HeapProfilerTestRunner.expandRow(row, step3);
}
function step3(row) {
var count = row.data['count'];
TestRunner.assertEquals(instanceCount.toString(), count);
var buttonsNode = HeapProfilerTestRunner.findButtonsNode(row);
TestRunner.assertEquals(true, !!buttonsNode, 'buttons node');
var words = buttonsNode.showAll.textContent.split(' ');
for (var i = 0; i < words.length; ++i) {
var maybeNumber = parseInt(words[i], 10);
if (!isNaN(maybeNumber))
TestRunner.assertEquals(
instanceCount - row.dataGrid.defaultPopulateCount(), maybeNumber, buttonsNode.showAll.textContent);
}
HeapProfilerTestRunner.clickShowMoreButton('showAll', buttonsNode, step4);
}
function step4(row) {
var rowsShown = HeapProfilerTestRunner.countDataRows(row);
TestRunner.assertEquals(instanceCount, rowsShown, 'after showAll click');
var buttonsNode = HeapProfilerTestRunner.findButtonsNode(row);
TestRunner.assertEquals(false, !!buttonsNode, 'buttons node found when all instances are shown!');
setTimeout(next, 0);
}
}]);
})();
| chromium/chromium | third_party/blink/web_tests/http/tests/devtools/profiler/heap-snapshot-summary-show-all.js | JavaScript | bsd-3-clause | 2,080 |
'use strict';
exports.baseTechPath = require.resolve('./level-proto.js');
| bem-archive/bem-tools | lib/techs/v2/tech-docs.js | JavaScript | mit | 75 |
import merge from "ember-data/system/merge";
import RootState from "ember-data/system/model/states";
import Relationships from "ember-data/system/relationships/state/create";
import Snapshot from "ember-data/system/snapshot";
import EmptyObject from "ember-data/system/empty-object";
var Promise = Ember.RSVP.Promise;
var get = Ember.get;
var set = Ember.set;
var _extractPivotNameCache = new EmptyObject();
var _splitOnDotCache = new EmptyObject();
function splitOnDot(name) {
return _splitOnDotCache[name] || (
_splitOnDotCache[name] = name.split('.')
);
}
function extractPivotName(name) {
return _extractPivotNameCache[name] || (
_extractPivotNameCache[name] = splitOnDot(name)[0]
);
}
function retrieveFromCurrentState(key) {
return function() {
return get(this.currentState, key);
};
}
var guid = 0;
/**
`InternalModel` is the Model class that we use internally inside Ember Data to represent models.
Internal ED methods should only deal with `InternalModel` objects. It is a fast, plain Javascript class.
We expose `DS.Model` to application code, by materializing a `DS.Model` from `InternalModel` lazily, as
a performance optimization.
`InternalModel` should never be exposed to application code. At the boundaries of the system, in places
like `find`, `push`, etc. we convert between Models and InternalModels.
We need to make sure that the properties from `InternalModel` are correctly exposed/proxied on `Model`
if they are needed.
@class InternalModel
*/
export default function InternalModel(type, id, store, container, data) {
this.type = type;
this.id = id;
this.store = store;
this.container = container;
this._data = data || new EmptyObject();
this.modelName = type.modelName;
this.dataHasInitialized = false;
//Look into making this lazy
this._deferredTriggers = [];
this._attributes = new EmptyObject();
this._inFlightAttributes = new EmptyObject();
this._relationships = new Relationships(this);
this._recordArrays = undefined;
this.currentState = RootState.empty;
this.isReloading = false;
this.isError = false;
this.error = null;
this[Ember.GUID_KEY] = guid++ + 'internal-model';
/*
implicit relationships are relationship which have not been declared but the inverse side exists on
another record somewhere
For example if there was
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr()
})
```
but there is also
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr(),
comments: DS.hasMany('comment')
})
```
would have a implicit post relationship in order to be do things like remove ourselves from the post
when we are deleted
*/
this._implicitRelationships = new EmptyObject();
}
InternalModel.prototype = {
isEmpty: retrieveFromCurrentState('isEmpty'),
isLoading: retrieveFromCurrentState('isLoading'),
isLoaded: retrieveFromCurrentState('isLoaded'),
hasDirtyAttributes: retrieveFromCurrentState('hasDirtyAttributes'),
isSaving: retrieveFromCurrentState('isSaving'),
isDeleted: retrieveFromCurrentState('isDeleted'),
isNew: retrieveFromCurrentState('isNew'),
isValid: retrieveFromCurrentState('isValid'),
dirtyType: retrieveFromCurrentState('dirtyType'),
constructor: InternalModel,
materializeRecord: function() {
Ember.assert("Materialized " + this.modelName + " record with id:" + this.id + "more than once", this.record === null || this.record === undefined);
// lookupFactory should really return an object that creates
// instances with the injections applied
this.record = this.type._create({
store: this.store,
container: this.container,
_internalModel: this,
currentState: get(this, 'currentState'),
isError: this.isError,
adapterError: this.error
});
this._triggerDeferredTriggers();
},
recordObjectWillDestroy: function() {
this.record = null;
},
deleteRecord: function() {
this.send('deleteRecord');
},
save: function(options) {
var promiseLabel = "DS: Model#save " + this;
var resolver = Ember.RSVP.defer(promiseLabel);
this.store.scheduleSave(this, resolver, options);
return resolver.promise;
},
startedReloading: function() {
this.isReloading = true;
if (this.record) {
set(this.record, 'isReloading', true);
}
},
finishedReloading: function() {
this.isReloading = false;
if (this.record) {
set(this.record, 'isReloading', false);
}
},
reload: function() {
this.startedReloading();
var record = this;
var promiseLabel = "DS: Model#reload of " + this;
return new Promise(function(resolve) {
record.send('reloadRecord', resolve);
}, promiseLabel).then(function() {
record.didCleanError();
return record;
}, function(error) {
record.didError(error);
throw error;
}, "DS: Model#reload complete, update flags").finally(function () {
record.finishedReloading();
record.updateRecordArrays();
});
},
getRecord: function() {
if (!this.record) {
this.materializeRecord();
}
return this.record;
},
unloadRecord: function() {
this.send('unloadRecord');
},
eachRelationship: function(callback, binding) {
return this.type.eachRelationship(callback, binding);
},
eachAttribute: function(callback, binding) {
return this.type.eachAttribute(callback, binding);
},
inverseFor: function(key) {
return this.type.inverseFor(key);
},
setupData: function(data) {
var changedKeys = this._changedKeys(data.attributes);
merge(this._data, data.attributes);
this.pushedData();
if (this.record) {
this.record._notifyProperties(changedKeys);
}
this.didInitalizeData();
},
becameReady: function() {
Ember.run.schedule('actions', this.store.recordArrayManager, this.store.recordArrayManager.recordWasLoaded, this);
},
didInitalizeData: function() {
if (!this.dataHasInitialized) {
this.becameReady();
this.dataHasInitialized = true;
}
},
destroy: function() {
if (this.record) {
return this.record.destroy();
}
},
/**
@method createSnapshot
@private
*/
createSnapshot: function(options) {
var adapterOptions = options && options.adapterOptions;
var snapshot = new Snapshot(this);
snapshot.adapterOptions = adapterOptions;
return snapshot;
},
/**
@method loadingData
@private
@param {Promise} promise
*/
loadingData: function(promise) {
this.send('loadingData', promise);
},
/**
@method loadedData
@private
*/
loadedData: function() {
this.send('loadedData');
this.didInitalizeData();
},
/**
@method notFound
@private
*/
notFound: function() {
this.send('notFound');
},
/**
@method pushedData
@private
*/
pushedData: function() {
this.send('pushedData');
},
flushChangedAttributes: function() {
this._inFlightAttributes = this._attributes;
this._attributes = new EmptyObject();
},
/**
@method adapterWillCommit
@private
*/
adapterWillCommit: function() {
this.send('willCommit');
},
/**
@method adapterDidDirty
@private
*/
adapterDidDirty: function() {
this.send('becomeDirty');
this.updateRecordArraysLater();
},
/**
@method send
@private
@param {String} name
@param {Object} context
*/
send: function(name, context) {
var currentState = get(this, 'currentState');
if (!currentState[name]) {
this._unhandledEvent(currentState, name, context);
}
return currentState[name](this, context);
},
notifyHasManyAdded: function(key, record, idx) {
if (this.record) {
this.record.notifyHasManyAdded(key, record, idx);
}
},
notifyHasManyRemoved: function(key, record, idx) {
if (this.record) {
this.record.notifyHasManyRemoved(key, record, idx);
}
},
notifyBelongsToChanged: function(key, record) {
if (this.record) {
this.record.notifyBelongsToChanged(key, record);
}
},
notifyPropertyChange: function(key) {
if (this.record) {
this.record.notifyPropertyChange(key);
}
},
rollbackAttributes: function() {
var dirtyKeys = Object.keys(this._attributes);
this._attributes = new EmptyObject();
if (get(this, 'isError')) {
this._inFlightAttributes = new EmptyObject();
this.didCleanError();
}
//Eventually rollback will always work for relationships
//For now we support it only out of deleted state, because we
//have an explicit way of knowing when the server acked the relationship change
if (this.isDeleted()) {
//TODO: Should probably move this to the state machine somehow
this.becameReady();
}
if (this.isNew()) {
this.clearRelationships();
}
if (this.isValid()) {
this._inFlightAttributes = new EmptyObject();
}
this.send('rolledBack');
this.record._notifyProperties(dirtyKeys);
},
/**
@method transitionTo
@private
@param {String} name
*/
transitionTo: function(name) {
// POSSIBLE TODO: Remove this code and replace with
// always having direct reference to state objects
var pivotName = extractPivotName(name);
var currentState = get(this, 'currentState');
var state = currentState;
do {
if (state.exit) { state.exit(this); }
state = state.parentState;
} while (!state.hasOwnProperty(pivotName));
var path = splitOnDot(name);
var setups = [];
var enters = [];
var i, l;
for (i=0, l=path.length; i<l; i++) {
state = state[path[i]];
if (state.enter) { enters.push(state); }
if (state.setup) { setups.push(state); }
}
for (i=0, l=enters.length; i<l; i++) {
enters[i].enter(this);
}
set(this, 'currentState', state);
//TODO Consider whether this is the best approach for keeping these two in sync
if (this.record) {
set(this.record, 'currentState', state);
}
for (i=0, l=setups.length; i<l; i++) {
setups[i].setup(this);
}
this.updateRecordArraysLater();
},
_unhandledEvent: function(state, name, context) {
var errorMessage = "Attempted to handle event `" + name + "` ";
errorMessage += "on " + String(this) + " while in state ";
errorMessage += state.stateName + ". ";
if (context !== undefined) {
errorMessage += "Called with " + Ember.inspect(context) + ".";
}
throw new Ember.Error(errorMessage);
},
triggerLater: function() {
var length = arguments.length;
var args = new Array(length);
for (var i = 0; i < length; i++) {
args[i] = arguments[i];
}
if (this._deferredTriggers.push(args) !== 1) {
return;
}
Ember.run.scheduleOnce('actions', this, '_triggerDeferredTriggers');
},
_triggerDeferredTriggers: function() {
//TODO: Before 1.0 we want to remove all the events that happen on the pre materialized record,
//but for now, we queue up all the events triggered before the record was materialized, and flush
//them once we have the record
if (!this.record) {
return;
}
for (var i=0, l= this._deferredTriggers.length; i<l; i++) {
this.record.trigger.apply(this.record, this._deferredTriggers[i]);
}
this._deferredTriggers.length = 0;
},
/**
@method clearRelationships
@private
*/
clearRelationships: function() {
this.eachRelationship((name, relationship) => {
if (this._relationships.has(name)) {
var rel = this._relationships.get(name);
rel.clear();
rel.destroy();
}
});
Object.keys(this._implicitRelationships).forEach((key) => {
this._implicitRelationships[key].clear();
this._implicitRelationships[key].destroy();
});
},
/**
When a find request is triggered on the store, the user can optionally pass in
attributes and relationships to be preloaded. These are meant to behave as if they
came back from the server, except the user obtained them out of band and is informing
the store of their existence. The most common use case is for supporting client side
nested URLs, such as `/posts/1/comments/2` so the user can do
`store.find('comment', 2, {post:1})` without having to fetch the post.
Preloaded data can be attributes and relationships passed in either as IDs or as actual
models.
@method _preloadData
@private
@param {Object} preload
*/
_preloadData: function(preload) {
//TODO(Igor) consider the polymorphic case
Object.keys(preload).forEach((key) => {
var preloadValue = get(preload, key);
var relationshipMeta = this.type.metaForProperty(key);
if (relationshipMeta.isRelationship) {
this._preloadRelationship(key, preloadValue);
} else {
this._data[key] = preloadValue;
}
});
},
_preloadRelationship: function(key, preloadValue) {
var relationshipMeta = this.type.metaForProperty(key);
var type = relationshipMeta.type;
if (relationshipMeta.kind === 'hasMany') {
this._preloadHasMany(key, preloadValue, type);
} else {
this._preloadBelongsTo(key, preloadValue, type);
}
},
_preloadHasMany: function(key, preloadValue, type) {
Ember.assert("You need to pass in an array to set a hasMany property on a record", Ember.isArray(preloadValue));
var internalModel = this;
var recordsToSet = preloadValue.map((recordToPush) => {
return internalModel._convertStringOrNumberIntoInternalModel(recordToPush, type);
});
//We use the pathway of setting the hasMany as if it came from the adapter
//because the user told us that they know this relationships exists already
this._relationships.get(key).updateRecordsFromAdapter(recordsToSet);
},
_preloadBelongsTo: function(key, preloadValue, type) {
var recordToSet = this._convertStringOrNumberIntoInternalModel(preloadValue, type);
//We use the pathway of setting the hasMany as if it came from the adapter
//because the user told us that they know this relationships exists already
this._relationships.get(key).setRecord(recordToSet);
},
_convertStringOrNumberIntoInternalModel: function(value, type) {
if (typeof value === 'string' || typeof value === 'number') {
return this.store._internalModelForId(type, value);
}
if (value._internalModel) {
return value._internalModel;
}
return value;
},
/**
@method updateRecordArrays
@private
*/
updateRecordArrays: function() {
this._updatingRecordArraysLater = false;
this.store.dataWasUpdated(this.type, this);
},
setId: function(id) {
Ember.assert('A record\'s id cannot be changed once it is in the loaded state', this.id === null || this.id === id || this.isNew());
this.id = id;
},
didError: function(error) {
this.error = error;
this.isError = true;
if (this.record) {
this.record.setProperties({
isError: true,
adapterError: error
});
}
},
didCleanError: function() {
this.error = null;
this.isError = false;
if (this.record) {
this.record.setProperties({
isError: false,
adapterError: null
});
}
},
/**
If the adapter did not return a hash in response to a commit,
merge the changed attributes and relationships into the existing
saved data.
@method adapterDidCommit
*/
adapterDidCommit: function(data) {
if (data) {
data = data.attributes;
}
this.didCleanError();
var changedKeys = this._changedKeys(data);
merge(this._data, this._inFlightAttributes);
if (data) {
merge(this._data, data);
}
this._inFlightAttributes = new EmptyObject();
this.send('didCommit');
this.updateRecordArraysLater();
if (!data) { return; }
this.record._notifyProperties(changedKeys);
},
/**
@method updateRecordArraysLater
@private
*/
updateRecordArraysLater: function() {
// quick hack (something like this could be pushed into run.once
if (this._updatingRecordArraysLater) { return; }
this._updatingRecordArraysLater = true;
Ember.run.schedule('actions', this, this.updateRecordArrays);
},
addErrorMessageToAttribute: function(attribute, message) {
var record = this.getRecord();
get(record, 'errors').add(attribute, message);
},
removeErrorMessageFromAttribute: function(attribute) {
var record = this.getRecord();
get(record, 'errors').remove(attribute);
},
clearErrorMessages: function() {
var record = this.getRecord();
get(record, 'errors').clear();
},
// FOR USE DURING COMMIT PROCESS
/**
@method adapterDidInvalidate
@private
*/
adapterDidInvalidate: function(errors) {
var attribute;
for (attribute in errors) {
if (errors.hasOwnProperty(attribute)) {
this.addErrorMessageToAttribute(attribute, errors[attribute]);
}
}
this._saveWasRejected();
},
/**
@method adapterDidError
@private
*/
adapterDidError: function(error) {
this.send('becameError');
this.didError(error);
this._saveWasRejected();
},
_saveWasRejected: function() {
var keys = Object.keys(this._inFlightAttributes);
for (var i=0; i < keys.length; i++) {
if (this._attributes[keys[i]] === undefined) {
this._attributes[keys[i]] = this._inFlightAttributes[keys[i]];
}
}
this._inFlightAttributes = new EmptyObject();
},
/**
Ember Data has 3 buckets for storing the value of an attribute on an internalModel.
`_data` holds all of the attributes that have been acknowledged by
a backend via the adapter. When rollbackAttributes is called on a model all
attributes will revert to the record's state in `_data`.
`_attributes` holds any change the user has made to an attribute
that has not been acknowledged by the adapter. Any values in
`_attributes` are have priority over values in `_data`.
`_inFlightAttributes`. When a record is being synced with the
backend the values in `_attributes` are copied to
`_inFlightAttributes`. This way if the backend acknowledges the
save but does not return the new state Ember Data can copy the
values from `_inFlightAttributes` to `_data`. Without having to
worry about changes made to `_attributes` while the save was
happenign.
Changed keys builds a list of all of the values that may have been
changed by the backend after a successful save.
It does this by iterating over each key, value pair in the payload
returned from the server after a save. If the `key` is found in
`_attributes` then the user has a local changed to the attribute
that has not been synced with the server and the key is not
included in the list of changed keys.
If the value, for a key differs from the value in what Ember Data
believes to be the truth about the backend state (A merger of the
`_data` and `_inFlightAttributes` objects where
`_inFlightAttributes` has priority) then that means the backend
has updated the value and the key is added to the list of changed
keys.
@method _changedKeys
@private
*/
_changedKeys: function(updates) {
var changedKeys = [];
if (updates) {
var original, i, value, key;
var keys = Object.keys(updates);
var length = keys.length;
original = merge(new EmptyObject(), this._data);
original = merge(original, this._inFlightAttributes);
for (i = 0; i < length; i++) {
key = keys[i];
value = updates[key];
// A value in _attributes means the user has a local change to
// this attributes. We never override this value when merging
// updates from the backend so we should not sent a change
// notification if the server value differs from the original.
if (this._attributes[key] !== undefined) {
continue;
}
if (!Ember.isEqual(original[key], value)) {
changedKeys.push(key);
}
}
}
return changedKeys;
},
toString: function() {
if (this.record) {
return this.record.toString();
} else {
return `<${this.modelName}:${this.id}>`;
}
}
};
| Kuzirashi/data | packages/ember-data/lib/system/model/internal-model.js | JavaScript | mit | 20,528 |
import { sendMail } from '../functions/sendMail';
import { unsubscribe } from '../functions/unsubscribe';
export const Mailer = {
sendMail,
unsubscribe,
};
| pkgodara/Rocket.Chat | packages/rocketchat-mail-messages/server/lib/Mailer.js | JavaScript | mit | 159 |
/* flatpickr v4.2.1, @license MIT */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.sv = {})));
}(this, (function (exports) { 'use strict';
var fp = typeof window !== "undefined" && window.flatpickr !== undefined
? window.flatpickr
: {
l10ns: {},
};
var Swedish = {
firstDayOfWeek: 1,
weekAbbreviation: "v",
weekdays: {
shorthand: ["Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"],
longhand: [
"Söndag",
"Måndag",
"Tisdag",
"Onsdag",
"Torsdag",
"Fredag",
"Lördag",
],
},
months: {
shorthand: [
"Jan",
"Feb",
"Mar",
"Apr",
"Maj",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dec",
],
longhand: [
"Januari",
"Februari",
"Mars",
"April",
"Maj",
"Juni",
"Juli",
"Augusti",
"September",
"Oktober",
"November",
"December",
],
},
ordinal: function () {
return ".";
},
};
fp.l10ns.sv = Swedish;
var sv = fp.l10ns;
exports.Swedish = Swedish;
exports['default'] = sv;
Object.defineProperty(exports, '__esModule', { value: true });
})));
| extend1994/cdnjs | ajax/libs/flatpickr/4.2.1/l10n/sv.js | JavaScript | mit | 1,639 |
// version 1.0 - original version
jQuery(document).ready(function () {
var version = jQuery.fn.jquery.split('.');
if (parseFloat(version[1]) < 7) {
// use .live as we are on jQuery prior to 1.7
jQuery('.colorpickerField').live('click', function () {
if (jQuery(this).attr('id').search("__i__") === -1) {
var picker,
field = jQuery(this).attr('id').substr(0, 20);
jQuery('.s2_colorpicker').hide();
jQuery('.s2_colorpicker').each(function () {
if (jQuery(this).attr('id').search(field) !== -1) {
picker = jQuery(this).attr('id');
}
});
jQuery.farbtastic('#' + picker).linkTo(this);
jQuery('#' + picker).slideDown();
}
});
} else {
// use .on as we are using jQuery 1.7 and up where .live is deprecated
jQuery(document).on('focus', '.colorpickerField', function () {
if (jQuery(this).is('.s2_initialised') || this.id.search('__i__') !== -1) {
return; // exit early, already initialized or not activated
}
jQuery(this).addClass('s2_initialised');
var picker,
field = jQuery(this).attr('id').substr(0, 20);
jQuery('.s2_colorpicker').each(function () {
if (jQuery(this).attr('id').search(field) !== -1) {
picker = jQuery(this).attr('id');
return false; // stop looping
}
});
jQuery(this).on('focusin', function (event) {
jQuery('.s2_colorpicker').hide();
jQuery.farbtastic('#' + picker).linkTo(this);
jQuery('#' + picker).slideDown();
});
jQuery(this).on('focusout', function (event) {
jQuery('#' + picker).slideUp();
});
jQuery(this).trigger('focus'); // retrigger focus event for plugin to work
});
}
});
| Melanie27/2014 | wp-content/plugins/subscribe2/include/s2_colorpicker.js | JavaScript | gpl-2.0 | 1,643 |
var toArray = require('./toArray');
var find = require('../array/find');
/**
* Return first non void argument
*/
function defaults(var_args){
return find(toArray(arguments), nonVoid);
}
function nonVoid(val){
return val != null;
}
module.exports = defaults;
| sanwalkailash/DotFresh | node_modules/grunt-bower-installer/node_modules/bower/node_modules/mout/lang/defaults.js | JavaScript | gpl-3.0 | 330 |
YUI.add('moodle-core-blocks', function (Y, NAME) {
/**
* Provides drag and drop functionality for blocks.
*
* @module moodle-core-blockdraganddrop
*/
var AJAXURL = '/lib/ajax/blocks.php',
CSS = {
BLOCK : 'block',
BLOCKREGION : 'block-region',
BLOCKADMINBLOCK : 'block_adminblock',
EDITINGMOVE : 'editing_move',
HEADER : 'header',
LIGHTBOX : 'lightbox',
REGIONCONTENT : 'region-content',
SKIPBLOCK : 'skip-block',
SKIPBLOCKTO : 'skip-block-to',
MYINDEX : 'page-my-index',
REGIONMAIN : 'region-main'
};
/**
* Legacy drag and drop manager.
* This drag and drop manager is specifically designed for themes using side-pre and side-post
* that do not make use of the block output methods introduced by MDL-39824.
*
* @namespace M.core.blockdraganddrop
* @class LegacyManager
* @constructor
* @extends M.core.dragdrop
*/
var DRAGBLOCK = function() {
DRAGBLOCK.superclass.constructor.apply(this, arguments);
};
Y.extend(DRAGBLOCK, M.core.dragdrop, {
skipnodetop : null,
skipnodebottom : null,
dragsourceregion : null,
initializer : function() {
// Set group for parent class
this.groups = ['block'];
this.samenodeclass = CSS.BLOCK;
this.parentnodeclass = CSS.REGIONCONTENT;
// Add relevant classes and ID to 'content' block region on My Home page.
var myhomecontent = Y.Node.all('body#'+CSS.MYINDEX+' #'+CSS.REGIONMAIN+' > .'+CSS.REGIONCONTENT);
if (myhomecontent.size() > 0) {
var contentregion = myhomecontent.item(0);
contentregion.addClass(CSS.BLOCKREGION);
contentregion.set('id', CSS.REGIONCONTENT);
contentregion.one('div').addClass(CSS.REGIONCONTENT);
}
// Initialise blocks dragging
// Find all block regions on the page
var blockregionlist = Y.Node.all('div.'+CSS.BLOCKREGION);
if (blockregionlist.size() === 0) {
return false;
}
// See if we are missing either of block regions,
// if yes we need to add an empty one to use as target
if (blockregionlist.size() !== this.get('regions').length) {
var blockregion = Y.Node.create('<div></div>')
.addClass(CSS.BLOCKREGION);
var regioncontent = Y.Node.create('<div></div>')
.addClass(CSS.REGIONCONTENT);
blockregion.appendChild(regioncontent);
var pre = blockregionlist.filter('#region-pre');
var post = blockregionlist.filter('#region-post');
if (pre.size() === 0 && post.size() === 1) {
// pre block is missing, instert it before post
blockregion.setAttrs({id : 'region-pre'});
post.item(0).insert(blockregion, 'before');
blockregionlist.unshift(blockregion);
} else if (post.size() === 0 && pre.size() === 1) {
// post block is missing, instert it after pre
blockregion.setAttrs({id : 'region-post'});
pre.item(0).insert(blockregion, 'after');
blockregionlist.push(blockregion);
}
}
blockregionlist.each(function(blockregionnode) {
// Setting blockregion as droptarget (the case when it is empty)
// The region-post (the right one)
// is very narrow, so add extra padding on the left to drop block on it.
new Y.DD.Drop({
node: blockregionnode.one('div.'+CSS.REGIONCONTENT),
groups: this.groups,
padding: '40 240 40 240'
});
// Make each div element in the list of blocks draggable
var del = new Y.DD.Delegate({
container: blockregionnode,
nodes: '.'+CSS.BLOCK,
target: true,
handles: ['.'+CSS.HEADER],
invalid: '.block-hider-hide, .block-hider-show, .moveto',
dragConfig: {groups: this.groups}
});
del.dd.plug(Y.Plugin.DDProxy, {
// Don't move the node at the end of the drag
moveOnEnd: false
});
del.dd.plug(Y.Plugin.DDWinScroll);
var blocklist = blockregionnode.all('.'+CSS.BLOCK);
blocklist.each(function(blocknode) {
var move = blocknode.one('a.'+CSS.EDITINGMOVE);
if (move) {
move.remove();
blocknode.one('.'+CSS.HEADER).setStyle('cursor', 'move');
}
}, this);
}, this);
},
get_block_id : function(node) {
return Number(node.get('id').replace(/inst/i, ''));
},
get_block_region : function(node) {
var region = node.ancestor('div.'+CSS.BLOCKREGION).get('id').replace(/region-/i, '');
if (Y.Array.indexOf(this.get('regions'), region) === -1) {
// Must be standard side-X
if (right_to_left()) {
if (region === 'post') {
region = 'pre';
} else if (region === 'pre') {
region = 'post';
}
}
return 'side-' + region;
}
// Perhaps custom region
return region;
},
get_region_id : function(node) {
return node.get('id').replace(/region-/i, '');
},
drag_start : function(e) {
// Get our drag object
var drag = e.target;
// Store the parent node of original drag node (block)
// we will need it later for show/hide empty regions
this.dragsourceregion = drag.get('node').ancestor('div.'+CSS.BLOCKREGION);
// Determine skipnodes and store them
if (drag.get('node').previous() && drag.get('node').previous().hasClass(CSS.SKIPBLOCK)) {
this.skipnodetop = drag.get('node').previous();
}
if (drag.get('node').next() && drag.get('node').next().hasClass(CSS.SKIPBLOCKTO)) {
this.skipnodebottom = drag.get('node').next();
}
},
drop_over : function(e) {
// Get a reference to our drag and drop nodes
var drag = e.drag.get('node');
var drop = e.drop.get('node');
// We need to fix the case when parent drop over event has determined
// 'goingup' and appended the drag node after admin-block.
if (drop.hasClass(this.parentnodeclass) && drop.one('.'+CSS.BLOCKADMINBLOCK) && drop.one('.'+CSS.BLOCKADMINBLOCK).next('.'+CSS.BLOCK)) {
drop.prepend(drag);
}
// Block is moved within the same region
// stop here, no need to modify anything.
if (this.dragsourceregion.contains(drop)) {
return false;
}
// TODO: Hiding-displaying block region only works for base theme blocks
// (region-pre, region-post) at the moment. It should be improved
// to work with custom block regions as well.
// TODO: Fix this for the case when user drag block towards empty section,
// then the section appears, then user chnages his mind and moving back to
// original section. The opposite section remains opened and empty.
var documentbody = Y.one('body');
// Moving block towards hidden region-content, display it
var regionname = this.get_region_id(this.dragsourceregion);
if (documentbody.hasClass('side-'+regionname+'-only')) {
documentbody.removeClass('side-'+regionname+'-only');
}
// Moving from empty region-content towards the opposite one,
// hide empty one (only for region-pre, region-post areas at the moment).
regionname = this.get_region_id(drop.ancestor('div.'+CSS.BLOCKREGION));
if (this.dragsourceregion.all('.'+CSS.BLOCK).size() === 0 && this.dragsourceregion.get('id').match(/(region-pre|region-post)/i)) {
if (!documentbody.hasClass('side-'+regionname+'-only')) {
documentbody.addClass('side-'+regionname+'-only');
}
}
},
drop_end : function() {
// clear variables
this.skipnodetop = null;
this.skipnodebottom = null;
this.dragsourceregion = null;
},
drag_dropmiss : function(e) {
// Missed the target, but we assume the user intended to drop it
// on the last last ghost node location, e.drag and e.drop should be
// prepared by global_drag_dropmiss parent so simulate drop_hit(e).
this.drop_hit(e);
},
drop_hit : function(e) {
var drag = e.drag;
// Get a reference to our drag node
var dragnode = drag.get('node');
var dropnode = e.drop.get('node');
// Amend existing skipnodes
if (dragnode.previous() && dragnode.previous().hasClass(CSS.SKIPBLOCK)) {
// the one that belongs to block below move below
dragnode.insert(dragnode.previous(), 'after');
}
// Move original skipnodes
if (this.skipnodetop) {
dragnode.insert(this.skipnodetop, 'before');
}
if (this.skipnodebottom) {
dragnode.insert(this.skipnodebottom, 'after');
}
// Add lightbox if it not there
var lightbox = M.util.add_lightbox(Y, dragnode);
// Prepare request parameters
var params = {
sesskey : M.cfg.sesskey,
courseid : this.get('courseid'),
pagelayout : this.get('pagelayout'),
pagetype : this.get('pagetype'),
subpage : this.get('subpage'),
contextid : this.get('contextid'),
action : 'move',
bui_moveid : this.get_block_id(dragnode),
bui_newregion : this.get_block_region(dropnode)
};
if (this.get('cmid')) {
params.cmid = this.get('cmid');
}
if (dragnode.next('.'+this.samenodeclass) && !dragnode.next('.'+this.samenodeclass).hasClass(CSS.BLOCKADMINBLOCK)) {
params.bui_beforeid = this.get_block_id(dragnode.next('.'+this.samenodeclass));
}
// Do AJAX request
Y.io(M.cfg.wwwroot+AJAXURL, {
method: 'POST',
data: params,
on: {
start : function() {
lightbox.show();
},
success: function(tid, response) {
window.setTimeout(function() {
lightbox.hide();
}, 250);
try {
var responsetext = Y.JSON.parse(response.responseText);
if (responsetext.error) {
new M.core.ajaxException(responsetext);
}
} catch (e) {}
},
failure: function(tid, response) {
this.ajax_failure(response);
lightbox.hide();
}
},
context:this
});
}
}, {
NAME : 'core-blocks-dragdrop',
ATTRS : {
courseid : {
value : null
},
cmid : {
value : null
},
contextid : {
value : null
},
pagelayout : {
value : null
},
pagetype : {
value : null
},
subpage : {
value : null
},
regions : {
value : null
}
}
});
/**
* Core namespace.
* @static
* @class core
*/
M.core = M.core || {};
/**
* Block drag and drop static class.
* @namespace M.core
* @class blockdraganddrop
* @static
*/
M.core.blockdraganddrop = M.core.blockdraganddrop || {};
/**
* True if the page is using the new blocks methods.
* @private
* @static
* @property _isusingnewblocksmethod
* @type Boolean
* @default null
*/
M.core.blockdraganddrop._isusingnewblocksmethod = null;
/**
* Returns true if the page is using the new blocks methods.
* @static
* @method is_using_blocks_render_method
* @return Boolean
*/
M.core.blockdraganddrop.is_using_blocks_render_method = function() {
if (this._isusingnewblocksmethod === null) {
var goodregions = Y.all('.block-region[data-blockregion]').size();
var allregions = Y.all('.block-region').size();
this._isusingnewblocksmethod = (allregions === goodregions);
}
return this._isusingnewblocksmethod;
};
/**
* Initialises a drag and drop manager.
* This should only ever be called once for a page.
* @static
* @method init
* @param {Object} params
* @return Manager
*/
M.core.blockdraganddrop.init = function(params) {
if (this.is_using_blocks_render_method()) {
new MANAGER(params);
} else {
new DRAGBLOCK(params);
}
};
/**
* Legacy code to keep things working.
*/
M.core_blocks = M.core_blocks || {};
M.core_blocks.init_dragdrop = function(params) {
M.core.blockdraganddrop.init(params);
};
/**
* This file contains the drag and drop manager class.
*
* Provides drag and drop functionality for blocks.
*
* @module moodle-core-blockdraganddrop
*/
/**
* Constructs a new Block drag and drop manager.
*
* @namespace M.core.blockdraganddrop
* @class Manager
* @constructor
* @extends M.core.dragdrop
*/
var MANAGER = function() {
MANAGER.superclass.constructor.apply(this, arguments);
};
MANAGER.prototype = {
/**
* The skip block link from above the block being dragged while a drag is in progress.
* Required by the M.core.dragdrop from whom this class extends.
* @private
* @property skipnodetop
* @type Node
* @default null
*/
skipnodetop : null,
/**
* The skip block link from below the block being dragged while a drag is in progress.
* Required by the M.core.dragdrop from whom this class extends.
* @private
* @property skipnodebottom
* @type Node
* @default null
*/
skipnodebottom : null,
/**
* An associative object of regions and the
* @property regionobjects
* @type {Object} Primitive object mocking an associative array.
* @type {BLOCKREGION} [regionname]* Each item uses the region name as the key with the value being
* an instance of the BLOCKREGION class.
*/
regionobjects : {},
/**
* Called during the initialisation process of the object.
* @method initializer
*/
initializer : function() {
Y.log('Initialising drag and drop for blocks.', 'info');
var regionnames = this.get('regions'),
i = 0,
region,
regionname,
droptarget,
dragdelegation;
// Evil required by M.core.dragdrop.
this.groups = ['block'];
this.samenodeclass = CSS.BLOCK;
this.parentnodeclass = CSS.BLOCKREGION;
// Add relevant classes and ID to 'content' block region on My Home page.
var myhomecontent = Y.Node.all('body#'+CSS.MYINDEX+' #'+CSS.REGIONMAIN+' > .'+CSS.REGIONCONTENT);
if (myhomecontent.size() > 0) {
var contentregion = myhomecontent.item(0);
contentregion.addClass(CSS.BLOCKREGION);
contentregion.set('id', CSS.REGIONCONTENT);
contentregion.one('div').addClass(CSS.REGIONCONTENT);
}
for (i in regionnames) {
regionname = regionnames[i];
region = new BLOCKREGION({
manager : this,
region : regionname,
node : Y.one('#block-region-'+regionname)
});
this.regionobjects[regionname] = region;
// Setting blockregion as droptarget (the case when it is empty)
// The region-post (the right one)
// is very narrow, so add extra padding on the left to drop block on it.
droptarget = new Y.DD.Drop({
node: region.get_droptarget(),
groups: this.groups,
padding: '40 240 40 240'
});
// Make each div element in the list of blocks draggable
dragdelegation = new Y.DD.Delegate({
container: region.get_droptarget(),
nodes: '.'+CSS.BLOCK,
target: true,
handles: ['.'+CSS.HEADER],
invalid: '.block-hider-hide, .block-hider-show, .moveto',
dragConfig: {groups: this.groups}
});
dragdelegation.dd.plug(Y.Plugin.DDProxy, {
// Don't move the node at the end of the drag
moveOnEnd: false
});
dragdelegation.dd.plug(Y.Plugin.DDWinScroll);
// On the mouse down event we will enable all block regions so that they can be dragged to.
// This is VERY important as without it dnd won't work for empty block regions.
dragdelegation.on('drag:mouseDown', this.enable_all_regions, this);
region.remove_block_move_icons();
}
Y.log('Initialisation of drag and drop for blocks complete.', 'info');
},
/**
* Returns the ID of the block the given node represents.
* @method get_block_id
* @param {Node} node
* @returns {int} The blocks ID in the database.
*/
get_block_id : function(node) {
return Number(node.get('id').replace(/inst/i, ''));
},
/**
* Returns the block region that the node is part of or belonging to.
* @method get_block_region
* @param {Y.Node} node
* @returns {string} The region name.
*/
get_block_region : function(node) {
if (!node.test('[data-blockregion]')) {
node = node.ancestor('[data-blockregion]');
}
return node.getData('blockregion');
},
/**
* Returns the BLOCKREGION instance that represents the block region the given node is part of.
* @method get_region_object
* @param {Y.Node} node
* @returns {BLOCKREGION}
*/
get_region_object : function(node) {
return this.regionobjects[this.get_block_region(node)];
},
/**
* Enables all fo the regions so that they are all visible while dragging is occuring.
* @method enable_all_regions
* @returns {undefined}
*/
enable_all_regions : function() {
var i = 0;
for (i in this.regionobjects) {
this.regionobjects[i].enable();
}
},
/**
* Disables enabled regions if they contain no blocks.
* @method disable_regions_if_required
* @returns {undefined}
*/
disable_regions_if_required : function() {
var i = 0;
for (i in this.regionobjects) {
this.regionobjects[i].disable_if_required();
}
},
/**
* Called by M.core.dragdrop.global_drag_start when dragging starts.
* @method drag_start
* @param {Event} e
* @returns {undefined}
*/
drag_start : function(e) {
// Get our drag object
var drag = e.target;
// Store the parent node of original drag node (block)
// we will need it later for show/hide empty regions
// Determine skipnodes and store them
if (drag.get('node').previous() && drag.get('node').previous().hasClass(CSS.SKIPBLOCK)) {
this.skipnodetop = drag.get('node').previous();
}
if (drag.get('node').next() && drag.get('node').next().hasClass(CSS.SKIPBLOCKTO)) {
this.skipnodebottom = drag.get('node').next();
}
},
/**
* Called by M.core.dragdrop.global_drop_over when something is dragged over a drop target.
* @method drop_over
* @param {Event} e
* @returns {undefined}
*/
drop_over : function(e) {
// Get a reference to our drag and drop nodes
var drag = e.drag.get('node');
var drop = e.drop.get('node');
// We need to fix the case when parent drop over event has determined
// 'goingup' and appended the drag node after admin-block.
if (drop.hasClass(CSS.REGIONCONTENT) && drop.one('.'+CSS.BLOCKADMINBLOCK) && drop.one('.'+CSS.BLOCKADMINBLOCK).next('.'+CSS.BLOCK)) {
drop.prepend(drag);
}
},
/**
* Called by M.core.dragdrop.global_drop_end when a drop has been completed.
* @method drop_end
* @returns {undefined}
*/
drop_end : function() {
// Clear variables.
this.skipnodetop = null;
this.skipnodebottom = null;
this.disable_regions_if_required();
},
/**
* Called by M.core.dragdrop.global_drag_dropmiss when something has been dropped on a node that isn't contained by a drop target.
* @method drag_dropmiss
* @param {Event} e
* @returns {undefined}
*/
drag_dropmiss : function(e) {
// Missed the target, but we assume the user intended to drop it
// on the last ghost node location, e.drag and e.drop should be
// prepared by global_drag_dropmiss parent so simulate drop_hit(e).
this.drop_hit(e);
},
/**
* Called by M.core.dragdrop.global_drag_hit when something has been dropped on a drop target.
* @method drop_hit
* @param {Event} e
* @returns {undefined}
*/
drop_hit : function(e) {
// Get a reference to our drag node
var dragnode = e.drag.get('node');
var dropnode = e.drop.get('node');
// Amend existing skipnodes
if (dragnode.previous() && dragnode.previous().hasClass(CSS.SKIPBLOCK)) {
// the one that belongs to block below move below
dragnode.insert(dragnode.previous(), 'after');
}
// Move original skipnodes
if (this.skipnodetop) {
dragnode.insert(this.skipnodetop, 'before');
}
if (this.skipnodebottom) {
dragnode.insert(this.skipnodebottom, 'after');
}
// Add lightbox if it not there
var lightbox = M.util.add_lightbox(Y, dragnode);
// Prepare request parameters
var params = {
sesskey : M.cfg.sesskey,
courseid : this.get('courseid'),
pagelayout : this.get('pagelayout'),
pagetype : this.get('pagetype'),
subpage : this.get('subpage'),
contextid : this.get('contextid'),
action : 'move',
bui_moveid : this.get_block_id(dragnode),
bui_newregion : this.get_block_region(dropnode)
};
if (this.get('cmid')) {
params.cmid = this.get('cmid');
}
if (dragnode.next('.'+CSS.BLOCK) && !dragnode.next('.'+CSS.BLOCK).hasClass(CSS.BLOCKADMINBLOCK)) {
params.bui_beforeid = this.get_block_id(dragnode.next('.'+CSS.BLOCK));
}
// Do AJAX request
Y.io(M.cfg.wwwroot+AJAXURL, {
method: 'POST',
data: params,
on: {
start : function() {
lightbox.show();
},
success: function(tid, response) {
window.setTimeout(function() {
lightbox.hide();
}, 250);
try {
var responsetext = Y.JSON.parse(response.responseText);
if (responsetext.error) {
new M.core.ajaxException(responsetext);
}
} catch (e) {}
},
failure: function(tid, response) {
this.ajax_failure(response);
lightbox.hide();
},
complete : function() {
this.disable_regions_if_required();
}
},
context:this
});
}
};
Y.extend(MANAGER, M.core.dragdrop, MANAGER.prototype, {
NAME : 'core-blocks-dragdrop-manager',
ATTRS : {
/**
* The Course ID if there is one.
* @attribute courseid
* @type int|null
* @default null
*/
courseid : {
value : null
},
/**
* The Course Module ID if there is one.
* @attribute cmid
* @type int|null
* @default null
*/
cmid : {
value : null
},
/**
* The Context ID.
* @attribute contextid
* @type int|null
* @default null
*/
contextid : {
value : null
},
/**
* The current page layout.
* @attribute pagelayout
* @type string|null
* @default null
*/
pagelayout : {
value : null
},
/**
* The page type string, should be used as the id for the body tag in the theme.
* @attribute pagetype
* @type string|null
* @default null
*/
pagetype : {
value : null
},
/**
* The subpage identifier, if any.
* @attribute subpage
* @type string|null
* @default null
*/
subpage : {
value : null
},
/**
* An array of block regions that are present on the page.
* @attribute regions
* @type array|null
* @default Array[]
*/
regions : {
value : []
}
}
});/**
* This file contains the Block Region class used by the drag and drop manager.
*
* Provides drag and drop functionality for blocks.
*
* @module moodle-core-blockdraganddrop
*/
/**
* Constructs a new block region object.
*
* @namespace M.core.blockdraganddrop
* @class BlockRegion
* @constructor
* @extends Y.Base
*/
var BLOCKREGION = function() {
BLOCKREGION.superclass.constructor.apply(this, arguments);
};
BLOCKREGION.prototype = {
/**
* Called during the initialisation process of the object.
* @method initializer
*/
initializer : function() {
var node = this.get('node');
Y.log('Block region `'+this.get('region')+'` initialising', 'info');
if (!node) {
Y.log('block region known about but no HTML structure found for it. Guessing structure.', 'warn');
node = this.create_and_add_node();
}
var body = Y.one('body'),
hasblocks = node.all('.'+CSS.BLOCK).size() > 0,
hasregionclass = this.get_has_region_class();
this.set('hasblocks', hasblocks);
if (!body.hasClass(hasregionclass)) {
body.addClass(hasregionclass);
}
body.addClass((hasblocks) ? this.get_used_region_class() : this.get_empty_region_class());
body.removeClass((hasblocks) ? this.get_empty_region_class() : this.get_used_region_class());
},
/**
* Creates a generic block region node and adds it to the DOM at the best guess location.
* Any calling of this method is an unfortunate circumstance.
* @method create_and_add_node
* @return Node The newly created Node
*/
create_and_add_node : function() {
var c = Y.Node.create,
region = this.get('region'),
node = c('<div id="block-region-'+region+'" data-droptarget="1"></div>')
.addClass(CSS.BLOCKREGION)
.setData('blockregion', region),
regions = this.get('manager').get('regions'),
i,
haspre = false,
haspost = false,
added = false,
pre,
post;
for (i in regions) {
if (regions[i].match(/(pre|left)/)) {
haspre = regions[i];
} else if (regions[i].match(/(post|right)/)) {
haspost = regions[i];
}
}
if (haspre !== false && haspost !== false) {
if (region === haspre) {
post = Y.one('#block-region-'+haspost);
if (post) {
post.insert(node, 'before');
added = true;
}
} else {
pre = Y.one('#block-region-'+haspre);
if (pre) {
pre.insert(node, 'after');
added = true;
}
}
}
if (added === false) {
Y.one('body').append(node);
}
this.set('node', node);
return node;
},
/**
* Removes the move icons and changes the cursor to a move icon when over the header.
* @method remove_block_move_icons
*/
remove_block_move_icons : function() {
this.get('node').all('.'+CSS.BLOCK+' a.'+CSS.EDITINGMOVE).each(function(moveicon){
moveicon.ancestor('.'+CSS.BLOCK).one('.'+CSS.HEADER).setStyle('cursor', 'move');
moveicon.remove();
});
},
/**
* Returns the class name on the body that signifies the document knows about this region.
* @method get_has_region_class
* @return String
*/
get_has_region_class : function() {
return 'has-region-'+this.get('region');
},
/**
* Returns the class name to use on the body if the region contains no blocks.
* @method get_empty_region_class
* @return String
*/
get_empty_region_class : function() {
return 'empty-region-'+this.get('region');
},
/**
* Returns the class name to use on the body if the region contains blocks.
* @method get_used_region_class
* @return String
*/
get_used_region_class : function() {
return 'used-region-'+this.get('region');
},
/**
* Returns the node to use as the drop target for this region.
* @method get_droptarget
* @return Node
*/
get_droptarget : function() {
var node = this.get('node');
if (node.test('[data-droptarget="1"]')) {
return node;
}
return node.one('[data-droptarget="1"]');
},
/**
* Enables the block region so that we can be sure the user can see it.
* This is done even if it is empty.
* @method enable
*/
enable : function() {
Y.one('body').addClass(this.get_used_region_class()).removeClass(this.get_empty_region_class());
},
/**
* Disables the region if it contains no blocks, essentially hiding it from the user.
* @method disable_if_required
*/
disable_if_required : function() {
if (this.get('node').all('.'+CSS.BLOCK).size() === 0) {
Y.one('body').addClass(this.get_empty_region_class()).removeClass(this.get_used_region_class());
}
}
};
Y.extend(BLOCKREGION, Y.Base, BLOCKREGION.prototype, {
NAME : 'core-blocks-dragdrop-blockregion',
ATTRS : {
/**
* The drag and drop manager that created this block region instance.
* @attribute manager
* @type M.core.blockdraganddrop.Manager
* @writeOnce
*/
manager : {
// Can only be set during initialisation and must be set then.
writeOnce : 'initOnly',
validator : function (value) {
return Y.Lang.isObject(value) && value instanceof MANAGER;
}
},
/**
* The name of the block region this object represents.
* @attribute region
* @type String
* @writeOnce
*/
region : {
// Can only be set during initialisation and must be set then.
writeOnce : 'initOnly',
validator : function (value) {
return Y.Lang.isString(value);
}
},
/**
* The node the block region HTML starts at.s
* @attribute region
* @type Y.Node
*/
node : {
validator : function (value) {
return Y.Lang.isObject(value) || Y.Lang.isNull(value);
}
},
/**
* True if the block region currently contains blocks.
* @attribute hasblocks
* @type Boolean
* @default false
*/
hasblocks : {
value : false,
validator : function (value) {
return Y.Lang.isBoolean(value);
}
}
}
});
}, '@VERSION@', {
"requires": [
"base",
"node",
"io",
"dom",
"dd",
"dd-scroll",
"moodle-core-dragdrop",
"moodle-core-notification"
]
});
| hdomos/moodlehd | lib/yui/build/moodle-core-blocks/moodle-core-blocks-debug.js | JavaScript | gpl-3.0 | 32,521 |
/**
* Copyright 2017 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
IframeTransport,
getIframeTransportScriptUrl,
} from '../iframe-transport';
import {addParamsToUrl} from '../../../../src/url';
import {expectPostMessage} from '../../../../testing/iframe.js';
import {urls} from '../../../../src/config';
import {user} from '../../../../src/log';
describes.realWin('amp-analytics.iframe-transport', {amp: true}, env => {
let sandbox;
let iframeTransport;
const frameUrl = 'http://example.com';
beforeEach(() => {
sandbox = env.sandbox;
iframeTransport = new IframeTransport(
env.ampdoc.win,
'some_vendor_type',
{iframe: frameUrl},
frameUrl + '-1'
);
});
afterEach(() => {
IframeTransport.resetCrossDomainIframes();
});
function expectAllUnique(numArray) {
if (!numArray) {
return;
}
expect(numArray).to.have.lengthOf(new Set(numArray).size);
}
it('creates one frame per vendor type', () => {
const createCrossDomainIframeSpy = sandbox.spy(
iframeTransport,
'createCrossDomainIframe'
);
expect(createCrossDomainIframeSpy).to.not.be.called;
expect(IframeTransport.hasCrossDomainIframe(iframeTransport.getType())).to
.be.true;
iframeTransport.processCrossDomainIframe();
expect(createCrossDomainIframeSpy).to.not.be.called;
});
it('enqueues event messages correctly', () => {
const url = 'https://example.com/test';
const config = {iframe: url};
iframeTransport.sendRequest('hello, world!', config);
const {queue} = IframeTransport.getFrameData(iframeTransport.getType());
expect(queue.queueSize()).to.equal(1);
iframeTransport.sendRequest('hello again, world!', config);
expect(queue.queueSize()).to.equal(2);
});
it('does not cause sentinel collisions', () => {
const iframeTransport2 = new IframeTransport(
env.ampdoc.win,
'some_other_vendor_type',
{iframe: 'https://example.com/test2'},
'https://example.com/test2-2'
);
const frame1 = IframeTransport.getFrameData(iframeTransport.getType());
const frame2 = IframeTransport.getFrameData(iframeTransport2.getType());
expectAllUnique([
iframeTransport.getCreativeId(),
iframeTransport2.getCreativeId(),
frame1.frame.sentinel,
frame2.frame.sentinel,
]);
});
it('correctly tracks usageCount and destroys iframes', () => {
const frameUrl2 = 'https://example.com/test2';
const iframeTransport2 = new IframeTransport(
env.ampdoc.win,
'some_other_vendor_type',
{iframe: frameUrl2},
frameUrl2 + '-3'
);
const frame1 = IframeTransport.getFrameData(iframeTransport.getType());
const frame2 = IframeTransport.getFrameData(iframeTransport2.getType());
expect(frame1.usageCount).to.equal(1);
expect(frame2.usageCount).to.equal(1);
expect(env.win.document.getElementsByTagName('IFRAME')).to.have.lengthOf(2);
// Mark the iframes as used multiple times each.
iframeTransport.processCrossDomainIframe();
iframeTransport.processCrossDomainIframe();
iframeTransport2.processCrossDomainIframe();
iframeTransport2.processCrossDomainIframe();
iframeTransport2.processCrossDomainIframe();
expect(frame1.usageCount).to.equal(3);
expect(frame2.usageCount).to.equal(4);
// Stop using the iframes, make sure usage counts go to zero and they are
// removed from the DOM.
IframeTransport.markCrossDomainIframeAsDone(
env.win.document,
iframeTransport.getType()
);
expect(frame1.usageCount).to.equal(2);
IframeTransport.markCrossDomainIframeAsDone(
env.win.document,
iframeTransport.getType()
);
IframeTransport.markCrossDomainIframeAsDone(
env.win.document,
iframeTransport.getType()
);
expect(frame1.usageCount).to.equal(0);
expect(frame2.usageCount).to.equal(4); // (Still)
expect(env.win.document.getElementsByTagName('IFRAME')).to.have.lengthOf(1);
IframeTransport.markCrossDomainIframeAsDone(
env.win.document,
iframeTransport2.getType()
);
IframeTransport.markCrossDomainIframeAsDone(
env.win.document,
iframeTransport2.getType()
);
IframeTransport.markCrossDomainIframeAsDone(
env.win.document,
iframeTransport2.getType()
);
IframeTransport.markCrossDomainIframeAsDone(
env.win.document,
iframeTransport2.getType()
);
expect(frame2.usageCount).to.equal(0);
expect(env.win.document.getElementsByTagName('IFRAME')).to.have.lengthOf(0);
});
it('creates one PerformanceObserver per vendor type', () => {
const createPerformanceObserverSpy = sandbox.spy(
IframeTransport.prototype,
'createPerformanceObserver_'
);
expect(createPerformanceObserverSpy).to.not.be.called;
iframeTransport.processCrossDomainIframe(); // Create 2nd frame for 1st vendor
expect(createPerformanceObserverSpy).to.not.be.called;
// Create frame for a new vendor
const frameUrl2 = 'https://example.com/test2';
new IframeTransport(
env.ampdoc.win,
'some_other_vendor_type',
{iframe: frameUrl2},
frameUrl2 + '-3'
);
expect(createPerformanceObserverSpy).to.be.called;
});
it('gets correct client lib URL in local/test mode', () => {
const url = getIframeTransportScriptUrl(env.ampdoc.win);
expect(url).to.contain(env.win.location.host);
expect(url).to.contain('/dist/iframe-transport-client-lib.js');
});
it('gets correct client lib URL in prod mode', () => {
const url = getIframeTransportScriptUrl(env.ampdoc.win, true);
expect(url).to.contain(urls.thirdParty);
expect(url).to.contain('/iframe-transport-client-v0.js');
expect(url).to.equal(
'https://3p.ampproject.net/$internalRuntimeVersion$/' +
'iframe-transport-client-v0.js'
);
});
});
describes.realWin(
'amp-analytics.iframe-transport',
{amp: true, allowExternalResources: true},
env => {
it('logs poor performance of vendor iframe', () => {
const body =
'<html><head><script>' +
'function busyWait(count, duration, cb) {\n' +
' if (count) {\n' +
' var d = new Date();\n' +
' var d2 = null;\n' +
' do {\n' +
' d2 = new Date();\n' +
' } while (d2-d < duration);\n' + // Note the semicolon!
' setTimeout(function() { ' +
' busyWait(count-1, duration, cb);' +
' },0);\n' +
' } else {\n' +
' cb();\n' +
' }\n' +
'}\n' +
'function begin() {\n' +
' busyWait(5, 200, function() {\n' +
' window.parent.postMessage("doneSleeping", "*");\n' +
' });\n' +
'}' +
'</script></head>' +
'<body onload="javascript:begin()">' +
'Non-Performant Fake Iframe' +
'</body>' +
'</html>';
const frameUrl2 = addParamsToUrl(
'http://ads.localhost:' +
document.location.port +
'/amp4test/compose-doc',
{body}
);
sandbox.stub(env.ampdoc.win.document.body, 'appendChild');
new IframeTransport(
env.ampdoc.win,
'some_other_vendor_type',
{iframe: frameUrl2},
frameUrl2 + '-3'
);
sandbox.restore();
const errorSpy = sandbox.spy(user(), 'error');
const {frame} = IframeTransport.getFrameData('some_other_vendor_type');
frame.setAttribute('style', '');
env.ampdoc.win.document.body.appendChild(frame);
return new Promise((resolve, unused) => {
expectPostMessage(
frame.contentWindow,
env.ampdoc.win,
'doneSleeping'
).then(() => {
expect(errorSpy).to.be.called;
expect(errorSpy.args[0][1]).to.match(
/Long Task: Vendor: "some_other_vendor_type"/
);
resolve();
});
});
}).timeout(10000);
}
);
| dotandads/amphtml | extensions/amp-analytics/0.1/test/test-iframe-transport.js | JavaScript | apache-2.0 | 8,537 |
L.Map.include({
addControl: function (control) {
control.addTo(this);
return this;
},
removeControl: function (control) {
control.removeFrom(this);
return this;
},
_initControlPos: function () {
var corners = this._controlCorners = {},
l = 'leaflet-',
container = this._controlContainer =
L.DomUtil.create('div', l + 'control-container', this._container);
function createCorner(vSide, hSide) {
var className = l + vSide + ' ' + l + hSide;
corners[vSide + hSide] =
L.DomUtil.create('div', className, container);
}
createCorner('top', 'left');
createCorner('top', 'right');
createCorner('bottom', 'left');
createCorner('bottom', 'right');
}
});
| scottBrimberry/Leaflet-Smart-Package | src/map/ext/Map.Control.js | JavaScript | bsd-2-clause | 703 |
// ------------------------------------
// #POSTCSS - LOAD OPTIONS - OPTIONS
// ------------------------------------
'use strict'
/**
*
* @method options
*
* @param {Object} options PostCSS Config
*
* @return {Object} options PostCSS Options
*/
module.exports = function options (options) {
if (options.parser) {
options.parser = require(options.parser)
}
if (options.syntax) {
options.syntax = require(options.syntax)
}
if (options.stringifier) {
options.stringifier = require(options.stringifier)
}
if (options.plugins) {
delete options.plugins
}
return options
}
| thethirdwheel/reasonabledisagreement | node_modules/react-scripts/node_modules/postcss-load-options/lib/options.js | JavaScript | mit | 614 |
/**************************************
{
x:0, y:0, width:433,
min:1, max:25, step:1,
message: "rules/turns"
}
**************************************/
function Slider(config){
var self = this;
self.id = config.id;
// Create DOM
var dom = document.createElement("div");
dom.className = "slider";
dom.style.left = config.x+"px";
dom.style.top = config.y+"px";
dom.style.width = config.width+"px";
self.dom = dom;
// Background
var bg = document.createElement("div");
bg.className = "slider_bg";
dom.appendChild(bg);
// Knob
var knob = document.createElement("div");
knob.className = "slider_knob";
dom.appendChild(knob);
// Set value
self.value = 0;
var _paramToValue = function(param){
var value = config.min + (config.max-config.min)*param;
value = Math.round(value/config.step)*config.step;
return value;
};
var _valueToParam = function(value){
var param = (value-config.min)/(config.max-config.min); // to (0-1)
return param;
};
self.setParam = function(param){
// Bounds
var value = config.min + (config.max-config.min)*param;
value = Math.round(value/config.step)*config.step;
self.value = value;
// DOM
knob.style.left = self.value*config.width-15;
};
self.setValue = function(value){
// Set
self.value = value;
// DOM with param
var param = _valueToParam(self.value);
knob.style.left = param*(config.width-30);
};
if(config.message) listen(self, config.message, self.setValue);
// Mouse events
var _isDragging = false;
var _offsetX = 0;
var _mouseToParam = function(event){
// Mouse to Param to Value
var param = (event.clientX - _offsetX - dom.getBoundingClientRect().left - 8)/(config.width-30);
if(param<0) param=0;
if(param>1) param=1;
var value = _paramToValue(param);
// Publish these changes! (only if ACTUALLY changed)
if(self.value != value){
if(config.message) publish(config.message, [value]);
if(config.onchange) config.onchange(value);
}
};
var _onDomMouseDown = function(event){
if(config.onselect) config.onselect();
_mouseToParam(event);
_isDragging = true;
_offsetX = 0;
};
var _onKnobMouseDown = function(event){
_isDragging = true;
if(config.onselect) config.onselect();
_offsetX = event.clientX - knob.getBoundingClientRect().left;
};
var _onWindowMouseMove = function(event){
if(_isDragging) _mouseToParam(event);
};
var _onWindowMouseUp = function(){
_isDragging = false;
};
dom.addEventListener("mousedown",_onDomMouseDown,false);
knob.addEventListener("mousedown",_onKnobMouseDown,false);
window.addEventListener("mousemove",_onWindowMouseMove,false);
window.addEventListener("mouseup",_onWindowMouseUp,false);
// FOR TOUCH
var _fakeEventWrapper = function(event){
var fake = {};
fake.clientX = event.changedTouches[0].clientX;
fake.clientY = event.changedTouches[0].clientY;
return fake;
};
dom.addEventListener("touchstart",function(event){
event = _fakeEventWrapper(event);
_onDomMouseDown(event);
},false);
knob.addEventListener("touchstart",function(event){
event = _fakeEventWrapper(event);
_onKnobMouseDown(event);
},false);
window.addEventListener("touchmove",function(event){
event = _fakeEventWrapper(event);
_onWindowMouseMove(event);
},false);
window.addEventListener("touchend",_onWindowMouseUp,false);
////////////////////////////////////////
// Add...
self.add = function(){
_add(self);
};
// Remove...
self.remove = function(){
unlisten(self);
_remove(self);
};
}
| maeriens/trust | js/core/Slider.js | JavaScript | cc0-1.0 | 3,494 |
/**
* # Hooks & Filters
*
* This file contains all of the form functions of the main _inbound object.
* Filters and actions are described below
*
* Forked from https://github.com/carldanley/WP-JS-Hooks/blob/master/src/event-manager.js
*
* @author David Wells <[email protected]>
* @version 0.0.1
*/
var _inboundHooks = (function (_inbound) {
/**
* # EventManager
*
* Actions and filters List
* addAction( 'namespace.identifier', callback, priority )
* addFilter( 'namespace.identifier', callback, priority )
* removeAction( 'namespace.identifier' )
* removeFilter( 'namespace.identifier' )
* doAction( 'namespace.identifier', arg1, arg2, moreArgs, finalArg )
* applyFilters( 'namespace.identifier', content )
* @return {[type]} [description]
*/
/**
* Handles managing all events for whatever you plug it into. Priorities for hooks are based on lowest to highest in
* that, lowest priority hooks are fired first.
*/
var EventManager = function() {
/**
* Maintain a reference to the object scope so our public methods never get confusing.
*/
var MethodsAvailable = {
removeFilter : removeFilter,
applyFilters : applyFilters,
addFilter : addFilter,
removeAction : removeAction,
doAction : doAction,
addAction : addAction
};
/**
* Contains the hooks that get registered with this EventManager. The array for storage utilizes a "flat"
* object literal such that looking up the hook utilizes the native object literal hash.
*/
var STORAGE = {
actions : {},
filters : {}
};
/**
* Adds an action to the event manager.
*
* @param action Must contain namespace.identifier
* @param callback Must be a valid callback function before this action is added
* @param [priority=10] Used to control when the function is executed in relation to other callbacks bound to the same hook
* @param [context] Supply a value to be used for this
*/
function addAction( action, callback, priority, context ) {
if( typeof action === 'string' && typeof callback === 'function' ) {
priority = parseInt( ( priority || 10 ), 10 );
_addHook( 'actions', action, callback, priority, context );
}
return MethodsAvailable;
}
/**
* Performs an action if it exists. You can pass as many arguments as you want to this function; the only rule is
* that the first argument must always be the action.
*/
function doAction( /* action, arg1, arg2, ... */ ) {
var args = Array.prototype.slice.call( arguments );
var action = args.shift();
if( typeof action === 'string' ) {
_runHook( 'actions', action, args );
}
return MethodsAvailable;
}
/**
* Removes the specified action if it contains a namespace.identifier & exists.
*
* @param action The action to remove
* @param [callback] Callback function to remove
*/
function removeAction( action, callback ) {
if( typeof action === 'string' ) {
_removeHook( 'actions', action, callback );
}
return MethodsAvailable;
}
/**
* Adds a filter to the event manager.
*
* @param filter Must contain namespace.identifier
* @param callback Must be a valid callback function before this action is added
* @param [priority=10] Used to control when the function is executed in relation to other callbacks bound to the same hook
* @param [context] Supply a value to be used for this
*/
function addFilter( filter, callback, priority, context ) {
if( typeof filter === 'string' && typeof callback === 'function' ) {
//console.log('add filter', filter);
priority = parseInt( ( priority || 10 ), 10 );
_addHook( 'filters', filter, callback, priority );
}
return MethodsAvailable;
}
/**
* Performs a filter if it exists. You should only ever pass 1 argument to be filtered. The only rule is that
* the first argument must always be the filter.
*/
function applyFilters( /* filter, filtered arg, arg2, ... */ ) {
var args = Array.prototype.slice.call( arguments );
var filter = args.shift();
if( typeof filter === 'string' ) {
return _runHook( 'filters', filter, args );
}
return MethodsAvailable;
}
/**
* Removes the specified filter if it contains a namespace.identifier & exists.
*
* @param filter The action to remove
* @param [callback] Callback function to remove
*/
function removeFilter( filter, callback ) {
if( typeof filter === 'string') {
_removeHook( 'filters', filter, callback );
}
return MethodsAvailable;
}
/**
* Removes the specified hook by resetting the value of it.
*
* @param type Type of hook, either 'actions' or 'filters'
* @param hook The hook (namespace.identifier) to remove
* @private
*/
function _removeHook( type, hook, callback, context ) {
if ( !STORAGE[ type ][ hook ] ) {
return;
}
if ( !callback ) {
STORAGE[ type ][ hook ] = [];
} else {
var handlers = STORAGE[ type ][ hook ];
var i;
if ( !context ) {
for ( i = handlers.length; i--; ) {
if ( handlers[i].callback === callback ) {
handlers.splice( i, 1 );
}
}
}
else {
for ( i = handlers.length; i--; ) {
var handler = handlers[i];
if ( handler.callback === callback && handler.context === context) {
handlers.splice( i, 1 );
}
}
}
}
}
/**
* Adds the hook to the appropriate storage container
*
* @param type 'actions' or 'filters'
* @param hook The hook (namespace.identifier) to add to our event manager
* @param callback The function that will be called when the hook is executed.
* @param priority The priority of this hook. Must be an integer.
* @param [context] A value to be used for this
* @private
*/
function _addHook( type, hook, callback, priority, context ) {
var hookObject = {
callback : callback,
priority : priority,
context : context
};
// Utilize 'prop itself' : http://jsperf.com/hasownproperty-vs-in-vs-undefined/19
var hooks = STORAGE[ type ][ hook ];
if( hooks ) {
hooks.push( hookObject );
hooks = _hookInsertSort( hooks );
}
else {
hooks = [ hookObject ];
}
STORAGE[ type ][ hook ] = hooks;
}
/**
* Use an insert sort for keeping our hooks organized based on priority. This function is ridiculously faster
* than bubble sort, etc: http://jsperf.com/javascript-sort
*
* @param hooks The custom array containing all of the appropriate hooks to perform an insert sort on.
* @private
*/
function _hookInsertSort( hooks ) {
var tmpHook, j, prevHook;
for( var i = 1, len = hooks.length; i < len; i++ ) {
tmpHook = hooks[ i ];
j = i;
while( ( prevHook = hooks[ j - 1 ] ) && prevHook.priority > tmpHook.priority ) {
hooks[ j ] = hooks[ j - 1 ];
--j;
}
hooks[ j ] = tmpHook;
}
return hooks;
}
/**
* Runs the specified hook. If it is an action, the value is not modified but if it is a filter, it is.
*
* @param type 'actions' or 'filters'
* @param hook The hook ( namespace.identifier ) to be ran.
* @param args Arguments to pass to the action/filter. If it's a filter, args is actually a single parameter.
* @private
*/
function _runHook( type, hook, args ) {
var handlers = STORAGE[ type ][ hook ];
if ( !handlers ) {
return (type === 'filters') ? args[0] : false;
}
var i = 0, len = handlers.length;
if ( type === 'filters' ) {
for ( ; i < len; i++ ) {
args[ 0 ] = handlers[ i ].callback.apply( handlers[ i ].context, args );
}
} else {
for ( ; i < len; i++ ) {
handlers[ i ].callback.apply( handlers[ i ].context, args );
}
}
return ( type === 'filters' ) ? args[ 0 ] : true;
}
// return all of the publicly available methods
return MethodsAvailable;
};
_inbound.hooks = new EventManager();
/**
* Event Hooks and Filters public methods
*/
/*
* add_action
*
* This function uses _inbound.hooks to mimics WP add_action
*
* ```js
* function Inbound_Add_Action_Example(data) {
* // Do stuff here.
* };
* // Add action to the hook
* _inbound.add_action( 'name_of_action', Inbound_Add_Action_Example, 10 );
* ```
*/
_inbound.add_action = function() {
// allow multiple action parameters such as 'ready append'
var actions = arguments[0].split(' ');
for( k in actions ) {
// prefix action
arguments[0] = 'inbound.' + actions[ k ];
_inbound.hooks.addAction.apply(this, arguments);
}
return this;
};
/*
* remove_action
*
* This function uses _inbound.hooks to mimics WP remove_action
*
* ```js
* // Add remove action 'name_of_action'
* _inbound.remove_action( 'name_of_action');
* ```
*
*/
_inbound.remove_action = function() {
// prefix action
arguments[0] = 'inbound.' + arguments[0];
_inbound.hooks.removeAction.apply(this, arguments);
return this;
};
/*
* do_action
*
* This function uses _inbound.hooks to mimics WP do_action
* This is used if you want to allow for third party JS plugins to act on your functions
*
*/
_inbound.do_action = function() {
// prefix action
arguments[0] = 'inbound.' + arguments[0];
_inbound.hooks.doAction.apply(this, arguments);
return this;
};
/*
* add_filter
*
* This function uses _inbound.hooks to mimics WP add_filter
*
* ```js
* _inbound.add_filter( 'urlParamFilter', URL_Param_Filter, 10 );
* function URL_Param_Filter(urlParams) {
*
* var params = urlParams || {};
* // check for item in object
* if(params.utm_source !== "undefined"){
* //alert('url param "utm_source" is here');
* }
*
* // delete item from object
* delete params.utm_source;
*
* return params;
*
* }
* ```
*/
_inbound.add_filter = function() {
// prefix action
arguments[0] = 'inbound.' + arguments[0];
_inbound.hooks.addFilter.apply(this, arguments);
return this;
};
/*
* remove_filter
*
* This function uses _inbound.hooks to mimics WP remove_filter
*
* ```js
* // Add remove filter 'urlParamFilter'
* _inbound.remove_action( 'urlParamFilter');
* ```
*
*/
_inbound.remove_filter = function() {
// prefix action
arguments[0] = 'inbound.' + arguments[0];
_inbound.hooks.removeFilter.apply(this, arguments);
return this;
};
/*
* apply_filters
*
* This function uses _inbound.hooks to mimics WP apply_filters
*
*/
_inbound.apply_filters = function() {
//console.log('Filter:' + arguments[0] + " ran on ->", arguments[1]);
// prefix action
arguments[0] = 'inbound.' + arguments[0];
return _inbound.hooks.applyFilters.apply(this, arguments);
};
return _inbound;
})(_inbound || {}); | cheayeam/wordpress | wp-content/plugins/leads/shared/assets/js/frontend/analytics-src/analytics.hooks.js | JavaScript | gpl-2.0 | 11,257 |
/**@license boxplus image transition engine
* @author Levente Hunyadi
* @version 1.4.2
* @remarks Copyright (C) 2009-2010 Levente Hunyadi
* @remarks Licensed under GNU/GPLv3, see http://www.gnu.org/licenses/gpl-3.0.html
* @see http://hunyadi.info.hu/projects/boxplus
**/
/*
* boxplus: a lightweight pop-up window engine shipped with sigplus
* Copyright 2009-2010 Levente Hunyadi
*
* boxplus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* boxplus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with boxplus. If not, see <http://www.gnu.org/licenses/>.
*/
if (typeof(__jQuery__) == 'undefined') {
var __jQuery__ = jQuery;
}
(function ($) {
var CLASS_DISABLED = 'boxplus-disabled';
var max = Math.max;
var floor = Math.floor;
var ceil = Math.ceil;
/**
* Maximum computed width of matched elements including margin, border and padding.
*/
$.fn.maxWidth = function () {
var width = 0;
this.each( function(index, el) {
width = max(width, $(el).safeWidth());
});
return width;
}
/**
* Maximum computed height of matched elements including margin, border and padding.
*/
$.fn.maxHeight = function () {
var height = 0;
this.each( function(index, el) {
height = max(height, $(el).safeHeight());
});
return height;
}
/**
* "Safe" dimension of an element.
* Some browsers give invalid values with .width() but others give the meaningless,
* value "auto" with .css('width'), this function bridges the differences.
*/
function _safeDimension(obj, dim) {
var cssvalue = parseInt(obj.css(dim));
return isNaN(cssvalue) ? obj[dim]() : cssvalue;
}
$.fn.safeWidth = function () {
return _safeDimension(this, 'width');
}
$.fn.safeHeight = function () {
return _safeDimension(this, 'height');
}
/**
* Creates a new image slider from a collection of images.
* The method should be called on a ul or ol element that wraps a set of li elements.
*/
$.fn.boxplusTransition = function (settings) {
// default configuration properties
var defaults = {
navigation: 'horizontal', // orientation of navigation buttons, or do not show navigation buttons at all ['horizontal'|'vertical'|false]
loop: true, // whether the image sequence loops such that the first image follows the last [true|false]
contextmenu: true, // whether the context menu appears when right-clicking an image [true|false]
orientation: 'vertical', // alignment of bars used in transition ['vertical'|'horizontal']
slices: 15, // number of bars to use in transition animation
effect: 'fade', // image transition effect ['fade'|'bars'|'bars+fade'|'shutter'|'shutter+fade']
easing: 'swing',
duration: 500, // duration for transition animation [ms]
delay: 4000 // delay between successive animation steps [ms]
};
settings = $.extend(defaults, settings);
var lists = this.filter('ul, ol'); // filter elements that are not lists
// iterate over elements if invoked on an element collection
lists.each(function () {
// short-hand access to settings
var isNavigationVertical = settings.navigation == 'vertical';
var isOrientationHorizontal = settings.orientation == 'horizontal';
var sliceCount = settings.slices;
var duration = settings.duration;
var delay = settings.delay;
// status information
var sliderIndexPosition = 0; // index of item currently shown
var animation = false; // true if an animation is in progress
// DOM elements
var list = $(this).wrap('<div />').before('<div />').addClass('boxplus-hidden');
var wrapper = list.parent().addClass('boxplus-wrapper');
var items = $('li', list).css({
position: 'absolute',
left: 0,
top: 0
}).find('img:first');
// forces following an anchor (in a cancellable way) even when click event is triggered with jQuery
items.parent('a').click(function (event) {
if (!event.isDefaultPrevented()) {
location.href = this.href;
}
});
var container = list.prev().addClass('boxplus-transition').addClass(CLASS_DISABLED).click(function () {
items.eq(sliderIndexPosition).parent('a').click(); // when an image is clicked, the anchor wrapping the original image (if any) should be followed
});
// get maximum width and height of image slider items
var itemCount = items.length;
var itemWidth = items.maxWidth();
var itemHeight = items.maxHeight();
// set width and height of image container
wrapper.add(container).css({
width: itemWidth,
height: itemHeight
});
switch (settings.navigation) {
case 'horizontal': case 'vertical':
var cls = 'boxplus-' + settings.navigation;
container.addClass(cls);
// setup overlay navigation controls
function _addButton(cls) {
return '<div class="boxplus-' + cls + '" />';
}
container.prepend(
$(_addButton('prev') + _addButton('next')).addClass(cls).addClass(
(isNavigationVertical ? itemWidth : itemHeight) < 120 ? 'boxplus-small' : 'boxplus-large'
)
);
// bind events for navigation controls
$('.boxplus-prev', container).click(scrollPrevious);
$('.boxplus-next', container).click(scrollNext);
}
if (!settings.contextmenu) {
$(document).bind('contextmenu', function (event) { // subscribe to right-click event
return !container.children().add(container).filter(event.target).size(); // prevent right-click on image
});
}
// add bars to container for animation
var sliceDim = (isOrientationHorizontal ? itemHeight : itemWidth) / sliceCount;
for (var sliceIndex = 0; sliceIndex < sliceCount; sliceIndex++) {
var sliceOffset = floor(sliceIndex*sliceDim);
$('<div class="boxplus-transition-bars" />').css({
left: isOrientationHorizontal ? 0 : sliceOffset,
top: isOrientationHorizontal ? sliceOffset : 0,
height: isOrientationHorizontal ? sliceDim : itemHeight,
width: isOrientationHorizontal ? itemWidth : sliceDim,
visibility: 'hidden'
}).appendTo(container);
}
// update visibility of navigation controls
_updatePaging();
container.removeClass(CLASS_DISABLED);
scrollFirst();
// slider animation
if (delay > 0) {
delay = max(delay, duration + 500);
var intervalID = window.setInterval(scrollNext, delay);
// stop animation when mouse moves over an image
container.mouseover(function () {
window.clearInterval(intervalID);
}).mouseout(function () {
intervalID = window.setInterval(scrollNext, delay);
});
}
//
// Callback functions
//
function scrollFirst() {
return scroll('first');
}
function scrollPrevious() {
return scroll('prev');
}
function scrollNext() {
return scroll('next');
}
function scrollLast() {
return scroll('last');
}
/**
* Sets the image shown as the background image of elements.
* @param elem The element whose background-image property to set.
*/
function _setImage(e, x, y) {
var item = items.eq(sliderIndexPosition); // item to be shown
e.css({
backgroundImage: 'url("' + item.attr('src') + '")',
backgroundPosition: ((itemWidth - item.safeWidth()) / 2 - x) + 'px ' + ((itemHeight - item.safeHeight()) / 2 - y) + 'px'
});
}
/**
* Preloads an image for later display.
* @param item The element to use to acquire the URL of the image.
*/
function _preloadImage(item) {
var longdesc = item.attr('longdesc');
if (longdesc) { // higher-resolution image is available
item.attr('src', longdesc).attr('longdesc', '');
}
}
function _preloadImages() {
_preloadImage(items.eq(sliderIndexPosition));
_preloadImage(items.eq((sliderIndexPosition - 1) % itemCount));
_preloadImage(items.eq((sliderIndexPosition + 1) % itemCount));
}
/**
* Execute image transition.
*/
function scroll(dir) {
var bars = $('.boxplus-transition-bars', container);
if (animation) { // clear ongoing transitions
_setImage(container, 0, 0);
bars.clearQueue().stop().css('visibility', 'hidden');
}
animation = true; // indicate an ongoing transition
switch (dir) {
case 'first':
sliderIndexPosition = 0; break;
case 'prev':
sliderIndexPosition = (sliderIndexPosition - 1) % itemCount; break;
case 'next':
sliderIndexPosition = (sliderIndexPosition + 1) % itemCount; break;
case 'last':
sliderIndexPosition = itemCount - 1; break;
default:
return;
};
_updatePaging();
_preloadImages();
bars.css({ // reset bars background image, height, width, opacity, etc.
opacity: 1
}).each(function (index) { // set the image shown as the background image of bars with computing offset position
var bar = $(this);
var dim = ceil(index*sliceDim+sliceDim) - floor(index*sliceDim);
bar.css({
height: isOrientationHorizontal ? dim : itemHeight,
width: isOrientationHorizontal ? itemWidth : dim
});
var position = bar.position();
_setImage(bar, position.left, position.top);
});
function _transitionFade() {
bars.css('opacity', 0).show();
return {opacity: 1};
}
function _transitionBars() {
bars.css(isOrientationHorizontal ? 'width' : 'height', 0);
if (isOrientationHorizontal) {
return {width: itemWidth};
} else {
return {height: itemHeight};
}
}
function _transitionShutter() {
bars.css(isOrientationHorizontal ? 'height' : 'width', 0);
if (isOrientationHorizontal) {
return {height: ceil(sliceDim)};
} else {
return {width: ceil(sliceDim)};
}
}
var target;
switch (settings.effect) {
case 'fade':
target = _transitionFade(); break;
case 'bars':
target = _transitionBars(); break;
case 'bars+fade':
target = $.extend(_transitionBars(), _transitionFade()); break;
case 'shutter':
target = _transitionShutter(); break;
case 'shutter+fade':
target = $.extend(_transitionShutter(), _transitionFade()); break;
}
bars.css('visibility', 'visible');
// function to arrange bars in a specific order
var ordfun = function (index) { return index; };
switch (dir) {
case 'first': case 'prev':
ordfun = function (index) { return sliceCount-1-index; }; break;
}
// register animation events for bars
bars.each(function (index) {
var k = ordfun(index);
var options = {
duration: 500,
easing: settings.easing
};
if (k == sliceCount-1) {
$.extend(options, {
complete: function () {
animation = false;
_setImage(container, 0, 0);
bars.css('visibility', 'hidden');
}
});
}
// fire animation after an initial delay
$(this).delay(k * duration / sliceCount).animate(target, options);
});
return false; // prevent event propagation
}
/**
* Update which navigation links are enabled.
*/
function _updatePaging() {
if (!settings.loop) {
$('.boxplus-prev', container).toggleClass(CLASS_DISABLED, sliderIndexPosition <= 0);
$('.boxplus-next', container).toggleClass(CLASS_DISABLED, sliderIndexPosition >= itemCount-1);
}
}
});
return this; // support chaining
}
})(__jQuery__); | zincheto/Joomla-Online-Store | plugins/content/sigplus/engines/boxplus/slider/js/boxplus.transition.js | JavaScript | gpl-2.0 | 11,823 |
M.tool_assignmentupgrade = {
init_upgrade_table: function(Y) {
Y.use('node', function(Y) {
checkboxes = Y.all('td.c0 input');
checkboxes.each(function(node) {
node.on('change', function(e) {
rowelement = e.currentTarget.get('parentNode').get('parentNode');
if (e.currentTarget.get('checked')) {
rowelement.setAttribute('class', 'selectedrow');
} else {
rowelement.setAttribute('class', 'unselectedrow');
}
});
rowelement = node.get('parentNode').get('parentNode');
if (node.get('checked')) {
rowelement.setAttribute('class', 'selectedrow');
} else {
rowelement.setAttribute('class', 'unselectedrow');
}
});
});
var selectall = Y.one('th.c0 input');
selectall.on('change', function(e) {
if (e.currentTarget.get('checked')) {
checkboxes = Y.all('td.c0 input');
checkboxes.each(function(node) {
rowelement = node.get('parentNode').get('parentNode');
node.set('checked', true);
rowelement.setAttribute('class', 'selectedrow');
});
} else {
checkboxes = Y.all('td.c0 input');
checkboxes.each(function(node) {
rowelement = node.get('parentNode').get('parentNode');
node.set('checked', false);
rowelement.setAttribute('class', 'unselectedrow');
});
}
});
var batchform = Y.one('.tool_assignmentupgrade_batchform form');
batchform.on('submit', function(e) {
checkboxes = Y.all('td.c0 input');
var selectedassignments = [];
checkboxes.each(function(node) {
if (node.get('checked')) {
selectedassignments[selectedassignments.length] = node.get('value');
}
});
operation = Y.one('#id_operation');
assignmentsinput = Y.one('input.selectedassignments');
assignmentsinput.set('value', selectedassignments.join(','));
if (selectedassignments.length == 0) {
alert(M.str.assign.noassignmentsselected);
e.preventDefault();
}
});
var perpage = Y.one('#id_perpage');
perpage.on('change', function(e) {
window.onbeforeunload = null;
Y.one('.tool_assignmentupgrade_paginationform form').submit();
});
}
}
| bhaumik25php/ready2study | admin/tool/assignmentupgrade/module.js | JavaScript | gpl-3.0 | 2,755 |
// --
// Core.Agent.TableFilters.js - provides the special module functions for the dashboard
// Copyright (C) 2001-2011 OTRS AG, http://otrs.org/
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --
"use strict";
var Core = Core || {};
Core.Agent = Core.Agent || {};
/**
* @namespace
* @exports TargetNS as Core.Agent.TableFilters
* @description
* This namespace contains the special module functions for the Dashboard.
*/
Core.Agent.TableFilters = (function (TargetNS) {
/*
* check dependencies first
*/
if (!Core.Debug.CheckDependency('Core.Agent.TableFilters', 'Core.UI.AllocationList', 'Core.UI.AllocationList')) {
return;
}
/**
* @function
* @param {jQueryObject} $Input Input element to add auto complete to
* @return nothing
*/
TargetNS.InitCustomerIDAutocomplete = function ($Input) {
$Input.autocomplete({
minLength: Core.Config.Get('CustomerAutocomplete.MinQueryLength'),
delay: Core.Config.Get('CustomerAutocomplete.QueryDelay'),
open: function() {
// force a higher z-index than the overlay/dialog
$(this).autocomplete('widget').addClass('ui-overlay-autocomplete');
return false;
},
source: function (Request, Response) {
var URL = Core.Config.Get('Baselink'), Data = {
Action: 'AgentCustomerInformationCenterSearch',
Subaction: 'SearchCustomerID',
Term: Request.term,
MaxResults: Core.Config.Get('CustomerAutocomplete.MaxResultsDisplayed')
};
// if an old ajax request is already running, stop the old request and start the new one
if ($Input.data('AutoCompleteXHR')) {
$Input.data('AutoCompleteXHR').abort();
$Input.removeData('AutoCompleteXHR');
// run the response function to hide the request animation
Response({});
}
$Input.data('AutoCompleteXHR', Core.AJAX.FunctionCall(URL, Data, function (Result) {
var Data = [];
$Input.removeData('AutoCompleteXHR');
$.each(Result, function () {
Data.push({
label: this.Label + ' (' + this.Value + ')',
value: this.Value
});
});
Response(Data);
}));
},
select: function (Event, UI) {
$(Event.target)
.parent()
.find('select')
.append('<option value="' + UI.item.value + '">SelectedItem</option>')
.val(UI.item.value)
.trigger('change');
}
});
};
/**
* @function
* @param {jQueryObject} $Input Input element to add auto complete to
* @param {String} Subaction Subaction to execute, "SearchCustomerID" or "SearchCustomerUser"
* @return nothing
*/
TargetNS.InitCustomerUserAutocomplete = function ($Input) {
$Input.autocomplete({
minLength: Core.Config.Get('CustomerUserAutocomplete.MinQueryLength'),
delay: Core.Config.Get('CustomerUserAutocomplete.QueryDelay'),
open: function() {
// force a higher z-index than the overlay/dialog
$(this).autocomplete('widget').addClass('ui-overlay-autocomplete');
return false;
},
source: function (Request, Response) {
var URL = Core.Config.Get('Baselink'), Data = {
Action: 'AgentCustomerSearch',
Term: Request.term,
MaxResults: Core.Config.Get('CustomerUserAutocomplete.MaxResultsDisplayed')
};
// if an old ajax request is already running, stop the old request and start the new one
if ($Input.data('AutoCompleteXHR')) {
$Input.data('AutoCompleteXHR').abort();
$Input.removeData('AutoCompleteXHR');
// run the response function to hide the request animation
Response({});
}
$Input.data('AutoCompleteXHR', Core.AJAX.FunctionCall(URL, Data, function (Result) {
var Data = [];
$Input.removeData('AutoCompleteXHR');
$.each(Result, function () {
Data.push({
label: this.CustomerValue + " (" + this.CustomerKey + ")",
value: this.CustomerValue,
key: this.CustomerKey
});
});
Response(Data);
}));
},
select: function (Event, UI) {
$(Event.target)
.parent()
.find('select')
.append('<option value="' + UI.item.key + '">SelectedItem</option>')
.val(UI.item.key)
.trigger('change');
}
});
};
/**
* @function
* @param {jQueryObject} $Input Input element to add auto complete to
* @param {String} Subaction Subaction to execute, "SearchCustomerID" or "SearchCustomerUser"
* @return nothing
*/
TargetNS.InitUserAutocomplete = function ($Input, Subaction) {
$Input.autocomplete({
minLength: Core.Config.Get('UserAutocomplete.MinQueryLength'),
delay: Core.Config.Get('UserAutocomplete.QueryDelay'),
open: function() {
// force a higher z-index than the overlay/dialog
$(this).autocomplete('widget').addClass('ui-overlay-autocomplete');
return false;
},
source: function (Request, Response) {
var URL = Core.Config.Get('Baselink'), Data = {
Action: 'AgentUserSearch',
Subaction: Subaction,
Term: Request.term,
MaxResults: Core.Config.Get('UserAutocomplete.MaxResultsDisplayed')
};
// if an old ajax request is already running, stop the old request and start the new one
if ($Input.data('AutoCompleteXHR')) {
$Input.data('AutoCompleteXHR').abort();
$Input.removeData('AutoCompleteXHR');
// run the response function to hide the request animation
Response({});
}
$Input.data('AutoCompleteXHR', Core.AJAX.FunctionCall(URL, Data, function (Result) {
var Data = [];
$Input.removeData('AutoCompleteXHR');
$.each(Result, function () {
Data.push({
label: this.UserValue + " (" + this.UserKey + ")",
value: this.UserValue,
key: this.UserKey
});
});
Response(Data);
}));
},
select: function (Event, UI) {
$(Event.target)
.parent()
.find('select')
.append('<option value="' + UI.item.key + '">SelectedItem</option>')
.val(UI.item.key)
.trigger('change');
}
});
};
/**
* @function
* @return nothing
* This function initializes the special module functions
*/
TargetNS.Init = function () {
// Initiate allocation list
TargetNS.SetAllocationList();
};
/**
* @function
* @private
* @param {string} FieldID Id of the field which is updated via ajax
* @param {string} Show Show or hide the AJAX loader image
* @description Shows and hides an ajax loader for every element which is updates via ajax
*/
function UpdateAllocationList(Event, UI) {
var $ContainerObj = $(UI.sender).closest('.AllocationListContainer'),
Data = {},
FieldName;
if (Event.type === 'sortstop') {
$ContainerObj = $(UI.item).closest('.AllocationListContainer');
}
Data.Columns = {};
Data.Order = [];
$ContainerObj.find('.AvailableFields').find('li').each(function() {
FieldName = $(this).attr('data-fieldname');
Data.Columns[FieldName] = 0;
});
$ContainerObj.find('.AssignedFields').find('li').each(function() {
FieldName = $(this).attr('data-fieldname');
Data.Columns[FieldName] = 1;
Data.Order.push(FieldName);
});
$ContainerObj.closest('form').find('.ColumnsJSON').val(Core.JSON.Stringify(Data));
}
/**
* @function
* @return nothing
* This function binds a click event on an html element to update the preferences of the given dahsboard widget
* @param {jQueryObject} $ClickedElement The jQuery object of the element(s) that get the event listener
* @param {string} ElementID The ID of the element whose content should be updated with the server answer
* @param {jQueryObject} $Form The jQuery object of the form with the data for the server request
*/
TargetNS.SetAllocationList = function (Event, UI) {
$('.AllocationListContainer').each(function() {
var $ContainerObj = $(this),
DataEnabledJSON = $ContainerObj.closest('form.WidgetSettingsForm').find('input.ColumnsEnabledJSON').val(),
DataAvailableJSON = $ContainerObj.closest('form.WidgetSettingsForm').find('input.ColumnsAvailableJSON').val(),
DataEnabled,
DataAvailable,
Translation,
$FieldObj,
IDString = '#' + $ContainerObj.find('.AssignedFields').attr('id') + ', #' + $ContainerObj.find('.AvailableFields').attr('id');
if (DataEnabledJSON) {
DataEnabled = Core.JSON.Parse(DataEnabledJSON);
}
if (DataAvailableJSON) {
DataAvailable = Core.JSON.Parse(DataAvailableJSON);
}
$.each(DataEnabled, function(Index, Field) {
// get field translation
Translation = Core.Config.Get('Column' + Field) || Field;
$FieldObj = $('<li />').attr('title', Field).attr('data-fieldname', Field).text(Translation);
$ContainerObj.find('.AssignedFields').append($FieldObj);
});
$.each(DataAvailable, function(Index, Field) {
// get field translation
Translation = Core.Config.Get('Column' + Field) || Field;
$FieldObj = $('<li />').attr('title', Field).attr('data-fieldname', Field).text(Translation);
$ContainerObj.find('.AvailableFields').append($FieldObj);
});
Core.UI.AllocationList.Init(IDString, $ContainerObj.find('.AllocationList'), 'UpdateAllocationList', '', UpdateAllocationList);
Core.UI.Table.InitTableFilter($ContainerObj.find('.FilterAvailableFields'), $ContainerObj.find('.AvailableFields'));
});
};
/**
* @function
* @return nothing
* This function binds a click event on an html element to update the preferences of the given dahsboard widget
* @param {jQueryObject} $ClickedElement The jQuery object of the element(s) that get the event listener
* @param {string} ElementID The ID of the element whose content should be updated with the server answer
* @param {jQueryObject} $Form The jQuery object of the form with the data for the server request
*/
TargetNS.RegisterUpdatePreferences = function ($ClickedElement, ElementID, $Form) {
if (isJQueryObject($ClickedElement) && $ClickedElement.length) {
$ClickedElement.click(function () {
var URL = Core.Config.Get('Baselink') + Core.AJAX.SerializeForm($Form);
Core.AJAX.ContentUpdate($('#' + ElementID), URL, function () {
Core.UI.ToggleTwoContainer($('#' + ElementID + '-setting'), $('#' + ElementID));
Core.UI.Table.InitCSSPseudoClasses();
});
return false;
});
}
};
return TargetNS;
}(Core.Agent.TableFilters || {}));
| noritnk/otrs | var/httpd/htdocs/js/Core.Agent.TableFilters.js | JavaScript | agpl-3.0 | 12,857 |
/**
* slider - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: [email protected]
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
* Dependencies:
* draggable
*
*/
(function($){
function init(target){
var slider = $('<div class="slider">' +
'<div class="slider-inner">' +
'<a href="javascript:void(0)" class="slider-handle"></a>' +
'<span class="slider-tip"></span>' +
'</div>' +
'<div class="slider-rule"></div>' +
'<div class="slider-rulelabel"></div>' +
'<div style="clear:both"></div>' +
'<input type="hidden" class="slider-value">' +
'</div>').insertAfter(target);
var t = $(target);
t.addClass('slider-f').hide();
var name = t.attr('name');
if (name){
slider.find('input.slider-value').attr('name', name);
t.removeAttr('name').attr('sliderName', name);
}
return slider;
}
/**
* set the slider size, for vertical slider, the height property is required
*/
function setSize(target, param){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.slider;
if (param){
if (param.width) opts.width = param.width;
if (param.height) opts.height = param.height;
}
if (opts.mode == 'h'){
slider.css('height', '');
slider.children('div').css('height', '');
if (!isNaN(opts.width)){
slider.width(opts.width);
}
} else {
slider.css('width', '');
slider.children('div').css('width', '');
if (!isNaN(opts.height)){
slider.height(opts.height);
slider.find('div.slider-rule').height(opts.height);
slider.find('div.slider-rulelabel').height(opts.height);
slider.find('div.slider-inner')._outerHeight(opts.height);
}
}
initValue(target);
}
/**
* show slider rule if needed
*/
function showRule(target){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.slider;
var aa = opts.mode == 'h' ? opts.rule : opts.rule.slice(0).reverse();
if (opts.reversed){
aa = aa.slice(0).reverse();
}
_build(aa);
function _build(aa){
var rule = slider.find('div.slider-rule');
var label = slider.find('div.slider-rulelabel');
rule.empty();
label.empty();
for(var i=0; i<aa.length; i++){
var distance = i*100/(aa.length-1)+'%';
var span = $('<span></span>').appendTo(rule);
span.css((opts.mode=='h'?'left':'top'), distance);
// show the labels
if (aa[i] != '|'){
span = $('<span></span>').appendTo(label);
span.html(aa[i]);
if (opts.mode == 'h'){
span.css({
left: distance,
marginLeft: -Math.round(span.outerWidth()/2)
});
} else {
span.css({
top: distance,
marginTop: -Math.round(span.outerHeight()/2)
});
}
}
}
}
}
/**
* build the slider and set some properties
*/
function buildSlider(target){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.slider;
slider.removeClass('slider-h slider-v slider-disabled');
slider.addClass(opts.mode == 'h' ? 'slider-h' : 'slider-v');
slider.addClass(opts.disabled ? 'slider-disabled' : '');
slider.find('a.slider-handle').draggable({
axis:opts.mode,
cursor:'pointer',
disabled: opts.disabled,
onDrag:function(e){
var left = e.data.left;
var width = slider.width();
if (opts.mode!='h'){
left = e.data.top;
width = slider.height();
}
if (left < 0 || left > width) {
return false;
} else {
var value = pos2value(target, left);
adjustValue(value);
return false;
}
},
onBeforeDrag:function(){
state.isDragging = true;
},
onStartDrag:function(){
opts.onSlideStart.call(target, opts.value);
},
onStopDrag:function(e){
var value = pos2value(target, (opts.mode=='h'?e.data.left:e.data.top));
adjustValue(value);
opts.onSlideEnd.call(target, opts.value);
opts.onComplete.call(target, opts.value);
state.isDragging = false;
}
});
slider.find('div.slider-inner').unbind('.slider').bind('mousedown.slider', function(e){
if (state.isDragging){return}
var pos = $(this).offset();
var value = pos2value(target, (opts.mode=='h'?(e.pageX-pos.left):(e.pageY-pos.top)));
adjustValue(value);
opts.onComplete.call(target, opts.value);
});
function adjustValue(value){
var s = Math.abs(value % opts.step);
if (s < opts.step/2){
value -= s;
} else {
value = value - s + opts.step;
}
setValue(target, value);
}
}
/**
* set a specified value to slider
*/
function setValue(target, value){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.slider;
var oldValue = opts.value;
if (value < opts.min) value = opts.min;
if (value > opts.max) value = opts.max;
opts.value = value;
$(target).val(value);
slider.find('input.slider-value').val(value);
var pos = value2pos(target, value);
var tip = slider.find('.slider-tip');
if (opts.showTip){
tip.show();
tip.html(opts.tipFormatter.call(target, opts.value));
} else {
tip.hide();
}
if (opts.mode == 'h'){
var style = 'left:'+pos+'px;';
slider.find('.slider-handle').attr('style', style);
tip.attr('style', style + 'margin-left:' + (-Math.round(tip.outerWidth()/2)) + 'px');
} else {
var style = 'top:' + pos + 'px;';
slider.find('.slider-handle').attr('style', style);
tip.attr('style', style + 'margin-left:' + (-Math.round(tip.outerWidth())) + 'px');
}
if (oldValue != value){
opts.onChange.call(target, value, oldValue);
}
}
function initValue(target){
var opts = $.data(target, 'slider').options;
var fn = opts.onChange;
opts.onChange = function(){};
setValue(target, opts.value);
opts.onChange = fn;
}
/**
* translate value to slider position
*/
function value2pos(target, value){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.slider;
if (opts.mode == 'h'){
var pos = (value-opts.min)/(opts.max-opts.min)*slider.width();
if (opts.reversed){
pos = slider.width() - pos;
}
} else {
var pos = slider.height() - (value-opts.min)/(opts.max-opts.min)*slider.height();
if (opts.reversed){
pos = slider.height() - pos;
}
}
return pos.toFixed(0);
}
/**
* translate slider position to value
*/
function pos2value(target, pos){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.slider;
if (opts.mode == 'h'){
var value = opts.min + (opts.max-opts.min)*(pos/slider.width());
} else {
var value = opts.min + (opts.max-opts.min)*((slider.height()-pos)/slider.height());
}
return opts.reversed ? opts.max - value.toFixed(0) : value.toFixed(0);
}
$.fn.slider = function(options, param){
if (typeof options == 'string'){
return $.fn.slider.methods[options](this, param);
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'slider');
if (state){
$.extend(state.options, options);
} else {
state = $.data(this, 'slider', {
options: $.extend({}, $.fn.slider.defaults, $.fn.slider.parseOptions(this), options),
slider: init(this)
});
$(this).removeAttr('disabled');
}
var opts = state.options;
opts.min = parseFloat(opts.min);
opts.max = parseFloat(opts.max);
opts.value = parseFloat(opts.value);
opts.step = parseFloat(opts.step);
opts.originalValue = opts.value;
buildSlider(this);
showRule(this);
setSize(this);
});
};
$.fn.slider.methods = {
options: function(jq){
return $.data(jq[0], 'slider').options;
},
destroy: function(jq){
return jq.each(function(){
$.data(this, 'slider').slider.remove();
$(this).remove();
});
},
resize: function(jq, param){
return jq.each(function(){
setSize(this, param);
});
},
getValue: function(jq){
return jq.slider('options').value;
},
setValue: function(jq, value){
return jq.each(function(){
setValue(this, value);
});
},
clear: function(jq){
return jq.each(function(){
var opts = $(this).slider('options');
setValue(this, opts.min);
});
},
reset: function(jq){
return jq.each(function(){
var opts = $(this).slider('options');
setValue(this, opts.originalValue);
});
},
enable: function(jq){
return jq.each(function(){
$.data(this, 'slider').options.disabled = false;
buildSlider(this);
});
},
disable: function(jq){
return jq.each(function(){
$.data(this, 'slider').options.disabled = true;
buildSlider(this);
});
}
};
$.fn.slider.parseOptions = function(target){
var t = $(target);
return $.extend({}, $.parser.parseOptions(target, [
'width','height','mode',{reversed:'boolean',showTip:'boolean',min:'number',max:'number',step:'number'}
]), {
value: (t.val() || undefined),
disabled: (t.attr('disabled') ? true : undefined),
rule: (t.attr('rule') ? eval(t.attr('rule')) : undefined)
});
};
$.fn.slider.defaults = {
width: 'auto',
height: 'auto',
mode: 'h', // 'h'(horizontal) or 'v'(vertical)
reversed: false,
showTip: false,
disabled: false,
value: 0,
min: 0,
max: 100,
step: 1,
rule: [], // [0,'|',100]
tipFormatter: function(value){return value},
onChange: function(value, oldValue){},
onSlideStart: function(value){},
onSlideEnd: function(value){},
onComplete: function(value){}
};
})(jQuery);
| OneFlying/searchweb | webapp/static/lib/jquery-easyui-1.3.5/src/jquery.slider.js | JavaScript | apache-2.0 | 9,989 |
(function () {
// Append the bind() polyfill
var scriptElem = document.createElement('script');
scriptElem.setAttribute('src', 'scripts/android2.3-jscompat.js');
if (document.body) {
document.body.appendChild(scriptElem);
} else {
document.head.appendChild(scriptElem);
}
}()); | SimonidaPesic/VodicZaKupovinu | platforms/android/assets/www/scripts/platformOverrides.js | JavaScript | apache-2.0 | 329 |
/*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is goverened by a BSD-style
* license that can be found in the LICENSE file.
*/
suite('ChildNodeInterface', function() {
function getTree() {
var tree = {};
var div = tree.div = document.createElement('div');
div.innerHTML = 'a<b></b>c<d></d>e';
var a = tree.a = div.firstChild;
var b = tree.b = a.nextSibling;
var c = tree.c = b.nextSibling;
var d = tree.d = c.nextSibling;
var e = tree.e = d.nextSibling;
var sr = tree.sr = div.createShadowRoot();
sr.innerHTML = 'f<g></g>h<content></content>i<j></j>k';
var f = tree.f = sr.firstChild;
var g = tree.g = f.nextSibling;
var h = tree.h = g.nextSibling;
var content = tree.content = h.nextSibling;
var i = tree.i = content.nextSibling;
var j = tree.j = i.nextSibling;
var k = tree.k = j.nextSibling;
div.offsetHeight; // trigger rendering
return tree;
}
test('nextElementSibling', function() {
var tree = getTree();
assert.equal(tree.b.nextElementSibling, tree.d);
assert.equal(tree.d.nextElementSibling, null);
assert.equal(tree.g.nextElementSibling, tree.content);
assert.equal(tree.content.nextElementSibling, tree.j);
assert.equal(tree.j.nextElementSibling, null);
});
test('previousElementSibling', function() {
var tree = getTree();
assert.equal(tree.b.previousElementSibling, null);
assert.equal(tree.d.previousElementSibling, tree.b);
assert.equal(tree.g.previousElementSibling, null);
assert.equal(tree.content.previousElementSibling, tree.g);
assert.equal(tree.j.previousElementSibling, tree.content);
});
test('remove', function() {
var div = document.createElement('div');
div.innerHTML = '<a></a>';
var a = div.firstChild;
a.remove();
assert.equal(div.firstChild, null);
assert.equal(a.parentNode, null);
// no op.
div.remove();
});
});
| modulexcite/ShadowDOM | test/js/ChildNodeInterface.js | JavaScript | bsd-3-clause | 1,975 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Command = require('../ember-cli/lib/models/command');
const test_1 = require("../tasks/test");
const config_1 = require("../models/config");
const common_tags_1 = require("common-tags");
const config = config_1.CliConfig.fromProject() || config_1.CliConfig.fromGlobal();
const testConfigDefaults = config.getPaths('defaults.build', [
'progress', 'poll'
]);
const TestCommand = Command.extend({
name: 'test',
aliases: ['t'],
description: 'Run unit tests in existing project.',
works: 'insideProject',
availableOptions: [
{
name: 'watch',
type: Boolean,
aliases: ['w'],
description: 'Run build when files change.'
},
{
name: 'code-coverage',
type: Boolean,
default: false,
aliases: ['cc'],
description: 'Coverage report will be in the coverage/ directory.'
},
{
name: 'config',
type: String,
aliases: ['c'],
description: common_tags_1.oneLine `Use a specific config file.
Defaults to the karma config file in .angular-cli.json.`
},
{
name: 'single-run',
type: Boolean,
aliases: ['sr'],
description: 'Run tests a single time.'
},
{
name: 'progress',
type: Boolean,
default: testConfigDefaults['progress'],
description: 'Log progress to the console while in progress.'
},
{
name: 'browsers',
type: String,
description: 'Override which browsers tests are run against.'
},
{
name: 'colors',
type: Boolean,
description: 'Enable or disable colors in the output (reporters and logs).'
},
{
name: 'log-level',
type: String,
description: 'Level of logging.'
},
{
name: 'port',
type: Number,
description: 'Port where the web server will be listening.'
},
{
name: 'reporters',
type: String,
description: 'List of reporters to use.'
},
{
name: 'sourcemaps',
type: Boolean,
default: true,
aliases: ['sm', 'sourcemap'],
description: 'Output sourcemaps.'
},
{
name: 'poll',
type: Number,
default: testConfigDefaults['poll'],
description: 'Enable and define the file watching poll time period (milliseconds).'
},
{
name: 'environment',
type: String,
aliases: ['e'],
description: 'Defines the build environment.'
},
{
name: 'app',
type: String,
aliases: ['a'],
description: 'Specifies app name to use.'
}
],
run: function (commandOptions) {
const testTask = new test_1.default({
ui: this.ui,
project: this.project
});
if (commandOptions.watch !== undefined && !commandOptions.watch) {
// if not watching ensure karma is doing a single run
commandOptions.singleRun = true;
}
return testTask.run(commandOptions);
}
});
TestCommand.overrideCore = true;
exports.default = TestCommand;
//# sourceMappingURL=/users/hansl/sources/angular-cli/commands/test.js.map | RakaChoudhury/systemintegration | node_modules/@angular/cli/commands/test.js | JavaScript | mit | 3,611 |
import Ember from "ember-metal/core";
import EmberObject from "ember-runtime/system/object";
import TargetActionSupport from "ember-runtime/mixins/target_action_support";
var originalLookup;
QUnit.module("TargetActionSupport", {
setup() {
originalLookup = Ember.lookup;
},
teardown() {
Ember.lookup = originalLookup;
}
});
QUnit.test("it should return false if no target or action are specified", function() {
expect(1);
var obj = EmberObject.createWithMixins(TargetActionSupport);
ok(false === obj.triggerAction(), "no target or action was specified");
});
QUnit.test("it should support actions specified as strings", function() {
expect(2);
var obj = EmberObject.createWithMixins(TargetActionSupport, {
target: EmberObject.create({
anEvent() {
ok(true, "anEvent method was called");
}
}),
action: 'anEvent'
});
ok(true === obj.triggerAction(), "a valid target and action were specified");
});
QUnit.test("it should invoke the send() method on objects that implement it", function() {
expect(3);
var obj = EmberObject.createWithMixins(TargetActionSupport, {
target: EmberObject.create({
send(evt, context) {
equal(evt, 'anEvent', "send() method was invoked with correct event name");
equal(context, obj, "send() method was invoked with correct context");
}
}),
action: 'anEvent'
});
ok(true === obj.triggerAction(), "a valid target and action were specified");
});
QUnit.test("it should find targets specified using a property path", function() {
expect(2);
var Test = {};
Ember.lookup = { Test: Test };
Test.targetObj = EmberObject.create({
anEvent() {
ok(true, "anEvent method was called on global object");
}
});
var myObj = EmberObject.createWithMixins(TargetActionSupport, {
target: 'Test.targetObj',
action: 'anEvent'
});
ok(true === myObj.triggerAction(), "a valid target and action were specified");
});
QUnit.test("it should use an actionContext object specified as a property on the object", function() {
expect(2);
var obj = EmberObject.createWithMixins(TargetActionSupport, {
action: 'anEvent',
actionContext: {},
target: EmberObject.create({
anEvent(ctx) {
ok(obj.actionContext === ctx, "anEvent method was called with the expected context");
}
})
});
ok(true === obj.triggerAction(), "a valid target and action were specified");
});
QUnit.test("it should find an actionContext specified as a property path", function() {
expect(2);
var Test = {};
Ember.lookup = { Test: Test };
Test.aContext = {};
var obj = EmberObject.createWithMixins(TargetActionSupport, {
action: 'anEvent',
actionContext: 'Test.aContext',
target: EmberObject.create({
anEvent(ctx) {
ok(Test.aContext === ctx, "anEvent method was called with the expected context");
}
})
});
ok(true === obj.triggerAction(), "a valid target and action were specified");
});
QUnit.test("it should use the target specified in the argument", function() {
expect(2);
var targetObj = EmberObject.create({
anEvent() {
ok(true, "anEvent method was called");
}
});
var obj = EmberObject.createWithMixins(TargetActionSupport, {
action: 'anEvent'
});
ok(true === obj.triggerAction({ target: targetObj }), "a valid target and action were specified");
});
QUnit.test("it should use the action specified in the argument", function() {
expect(2);
var obj = EmberObject.createWithMixins(TargetActionSupport, {
target: EmberObject.create({
anEvent() {
ok(true, "anEvent method was called");
}
})
});
ok(true === obj.triggerAction({ action: 'anEvent' }), "a valid target and action were specified");
});
QUnit.test("it should use the actionContext specified in the argument", function() {
expect(2);
var context = {};
var obj = EmberObject.createWithMixins(TargetActionSupport, {
target: EmberObject.create({
anEvent(ctx) {
ok(context === ctx, "anEvent method was called with the expected context");
}
}),
action: 'anEvent'
});
ok(true === obj.triggerAction({ actionContext: context }), "a valid target and action were specified");
});
QUnit.test("it should allow multiple arguments from actionContext", function() {
expect(3);
var param1 = 'someParam';
var param2 = 'someOtherParam';
var obj = EmberObject.createWithMixins(TargetActionSupport, {
target: EmberObject.create({
anEvent(first, second) {
ok(first === param1, "anEvent method was called with the expected first argument");
ok(second === param2, "anEvent method was called with the expected second argument");
}
}),
action: 'anEvent'
});
ok(true === obj.triggerAction({ actionContext: [param1, param2] }), "a valid target and action were specified");
});
QUnit.test("it should use a null value specified in the actionContext argument", function() {
expect(2);
var obj = EmberObject.createWithMixins(TargetActionSupport, {
target: EmberObject.create({
anEvent(ctx) {
ok(null === ctx, "anEvent method was called with the expected context (null)");
}
}),
action: 'anEvent'
});
ok(true === obj.triggerAction({ actionContext: null }), "a valid target and action were specified");
});
| dgeb/ember.js | packages/ember-runtime/tests/mixins/target_action_support_test.js | JavaScript | mit | 5,453 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.