code stringlengths 2 1.05M |
|---|
import mod1473 from './mod1473';
var value=mod1473+1;
export default value;
|
import {
event as d3_event,
select as d3_select
} from 'd3-selection';
import { d3keybinding as d3_keybinding } from '../lib/d3.keybinding.js';
import { t, textDirection } from '../util/locale';
import { tooltip } from '../util/tooltip';
import { svgDefs, svgIcon } from '../svg/index';
import { modeBrowse } from '../modes/index';
import { behaviorHash } from '../behavior/index';
import { utilGetDimensions } from '../util/dimensions';
import { uiAccount } from './account';
import { uiAttribution } from './attribution';
import { uiBackground } from './background';
import { uiContributors } from './contributors';
import { uiFeatureInfo } from './feature_info';
import { uiFullScreen } from './full_screen';
import { uiGeolocate } from './geolocate';
import { uiHelp } from './help';
import { uiInfo } from './info';
import { uiIntro } from './intro';
import { uiLoading } from './loading';
import { uiMapData } from './map_data';
import { uiMapInMap } from './map_in_map';
import { uiModes } from './modes';
import { uiNotice } from './notice';
import { uiRestore } from './restore';
import { uiSave } from './save';
import { uiScale } from './scale';
import { uiShortcuts } from './shortcuts';
import { uiSidebar } from './sidebar';
import { uiSpinner } from './spinner';
import { uiSplash } from './splash';
import { uiStatus } from './status';
import { uiUndoRedo } from './undo_redo';
import { uiVersion } from './version';
import { uiZoom } from './zoom';
import { uiCmd } from './cmd';
export function uiInit(context) {
var uiInitCounter = 0;
function render(container) {
container
.attr('dir', textDirection);
var map = context.map();
var hash = behaviorHash(context);
hash();
if (!hash.hadHash) {
map.centerZoom([0, 0], 2);
}
container
.append('svg')
.attr('id', 'defs')
.call(svgDefs(context));
container
.append('div')
.attr('id', 'sidebar')
.attr('class', 'col4')
.call(ui.sidebar);
var content = container
.append('div')
.attr('id', 'content')
.attr('class', 'active');
var bar = content
.append('div')
.attr('id', 'bar')
.attr('class', 'fillD');
content
.append('div')
.attr('id', 'map')
.attr('dir', 'ltr')
.call(map);
content
.call(uiMapInMap(context))
.call(uiInfo(context))
.call(uiNotice(context));
bar
.append('div')
.attr('class', 'spacer col4');
var limiter = bar.append('div')
.attr('class', 'limiter');
limiter
.append('div')
.attr('class', 'button-wrap joined col3')
.call(uiModes(context), limiter);
limiter
.append('div')
.attr('class', 'button-wrap joined col1')
.call(uiUndoRedo(context));
limiter
.append('div')
.attr('class', 'button-wrap col1')
.call(uiSave(context));
bar
.append('div')
.attr('class', 'full-screen')
.call(uiFullScreen(context));
bar
.append('div')
.attr('class', 'spinner')
.call(uiSpinner(context));
var controls = bar
.append('div')
.attr('class', 'map-controls');
controls
.append('div')
.attr('class', 'map-control zoombuttons')
.call(uiZoom(context));
controls
.append('div')
.attr('class', 'map-control geolocate-control')
.call(uiGeolocate(context));
controls
.append('div')
.attr('class', 'map-control background-control')
.call(uiBackground(context));
controls
.append('div')
.attr('class', 'map-control map-data-control')
.call(uiMapData(context));
controls
.append('div')
.attr('class', 'map-control help-control')
.call(uiHelp(context));
var about = content
.append('div')
.attr('id', 'about');
about
.append('div')
.attr('id', 'attrib')
.attr('dir', 'ltr')
.call(uiAttribution(context));
about
.append('div')
.attr('class', 'api-status')
.call(uiStatus(context));
var footer = about
.append('div')
.attr('id', 'footer')
.attr('class', 'fillD');
footer
.append('div')
.attr('id', 'flash-wrap')
.attr('class', 'footer-hide');
var footerWrap = footer
.append('div')
.attr('id', 'footer-wrap')
.attr('class', 'footer-show');
footerWrap
.append('div')
.attr('id', 'scale-block')
.call(uiScale(context));
var aboutList = footerWrap
.append('div')
.attr('id', 'info-block')
.append('ul')
.attr('id', 'about-list');
if (!context.embed()) {
aboutList
.call(uiAccount(context));
}
aboutList
.append('li')
.attr('class', 'version')
.call(uiVersion(context));
var issueLinks = aboutList
.append('li');
issueLinks
.append('a')
.attr('target', '_blank')
.attr('tabindex', -1)
.attr('href', 'https://github.com/openstreetmap/iD/issues')
.call(svgIcon('#icon-bug', 'light'))
.call(tooltip().title(t('report_a_bug')).placement('top'));
issueLinks
.append('a')
.attr('target', '_blank')
.attr('tabindex', -1)
.attr('href', 'https://github.com/openstreetmap/iD/blob/master/CONTRIBUTING.md#translating')
.call(svgIcon('#icon-translate', 'light'))
.call(tooltip().title(t('help_translate')).placement('top'));
aboutList
.append('li')
.attr('class', 'feature-warning')
.attr('tabindex', -1)
.call(uiFeatureInfo(context));
aboutList
.append('li')
.attr('class', 'user-list')
.attr('tabindex', -1)
.call(uiContributors(context));
window.onbeforeunload = function() {
return context.save();
};
window.onunload = function() {
context.history().unlock();
};
var mapDimensions = map.dimensions();
function onResize() {
mapDimensions = utilGetDimensions(content, true);
map.dimensions(mapDimensions);
}
d3_select(window)
.on('resize.editor', onResize);
onResize();
function pan(d) {
return function() {
d3_event.preventDefault();
context.pan(d, 100);
};
}
// pan amount
var pa = 80;
var keybinding = d3_keybinding('main')
.on('⌫', function() { d3_event.preventDefault(); })
.on('←', pan([pa, 0]))
.on('↑', pan([0, pa]))
.on('→', pan([-pa, 0]))
.on('↓', pan([0, -pa]))
.on(['⇧←', uiCmd('⌘←')], pan([mapDimensions[0], 0]))
.on(['⇧↑', uiCmd('⌘↑')], pan([0, mapDimensions[1]]))
.on(['⇧→', uiCmd('⌘→')], pan([-mapDimensions[0], 0]))
.on(['⇧↓', uiCmd('⌘↓')], pan([0, -mapDimensions[1]]));
d3_select(document)
.call(keybinding);
context.enter(modeBrowse(context));
if (!uiInitCounter++) {
if (!hash.startWalkthrough) {
context.container()
.call(uiSplash(context))
.call(uiRestore(context));
}
context.container()
.call(uiShortcuts(context));
}
var osm = context.connection(),
auth = uiLoading(context).message(t('loading_auth')).blocking(true);
if (osm && auth) {
osm
.on('authLoading.ui', function() {
context.container()
.call(auth);
})
.on('authDone.ui', function() {
auth.close();
});
}
uiInitCounter++;
if (hash.startWalkthrough) {
hash.startWalkthrough = false;
context.container().call(uiIntro(context));
}
}
var renderCallback;
function ui(node, callback) {
renderCallback = callback;
var container = d3_select(node);
context.container(container);
context.loadLocale(function(err) {
if (!err) {
render(container);
}
if (callback) {
callback(err);
}
});
}
ui.restart = function(arg) {
context.locale(arg);
context.loadLocale(function(err) {
if (!err) {
context.container().selectAll('*').remove();
render(context.container());
if (renderCallback) renderCallback();
}
});
};
ui.sidebar = uiSidebar(context);
return ui;
}
|
describe('Application specs', function () {
var element;
function getEventListener(type, action){
var el = document.createElement('no-el'),
hash = {},
i
hash[type] = type + action
hash['Moz' + type[0].toUpperCase() + type.slice(1)] = type + action
hash['Webkit' + type[0].toUpperCase() + type.slice(1)] = 'webkit' + type[0].toUpperCase() +
type.slice(1) + action[0].toUpperCase() + action.slice(1)
hash['O' + type[0].toUpperCase() + type.slice(1)] = 'o' + type[0].toUpperCase() +
type.slice(1) + action[0].toUpperCase() + action.slice(1)
for(i in hash){
if(el.style[i] !== undefined){ return hash[i] }
}
return 'fallback';
}
beforeEach(function () {
element = document.createElement('animation-context');
element.setAttribute("animate-in", "fadeIn")
element.setAttribute("animate-out", "fadeOut")
document.body.innerHTML = '';
document.body.appendChild(element);
})
it('mounts the tag', function () {
riot.mount('animation-context')
expect(document.querySelector('div[name=context]').className)
.to.be('not-ready')
})
it('mounts the tag and animates on mount', function (done) {
element.setAttribute("animate-on-mount", "true")
element.addEventListener(getEventListener('animation', 'start'), function() {
expect(document.querySelector('div[name=context]').className)
.to.be('animated fadeIn')
});
element.addEventListener(getEventListener('animation', 'end'), function() { done(); });
riot.mount('animation-context')
})
it('unmounts the tag after animate out', function (done) {
this.timeout(3000);
element.setAttribute("animate-on-mount", "true")
element.addEventListener(getEventListener('animation', 'start'), function() {
if (out) {
expect(document.querySelector('div[name=context]').className)
.to.be('animated fadeOut')
} else {
expect(document.querySelector('div[name=context]').className)
.to.be('animated fadeIn')
}
});
element.addEventListener(getEventListener('animation', 'end'), function() {
if (!out) {
out = true;
tag.out()
}
});
var tag = riot.mount('animation-context')[0],
out = false;
tag.on('unmount', function(){
expect(done).to.be.ok();
done();
});
})
it('triggers animation-in after animate in', function (done) {
this.timeout(3000);
element.setAttribute("animate-on-mount", "false")
element.setAttribute("animate-auto-in-delay", "1000")
var tag = riot.mount('animation-context')[0];
tag.on('animation-in', function() {
expect(document.querySelector('div[name=context]').className)
.to.be('animated fadeIn')
done()
})
})
})
|
var utils = require("../../lib/utils");
var pad = utils.paddLines;
var assert = require("chai").assert;
describe("Padding content", function() {
it("does not padd with empty string", function() {
var input = "line 1\nline 2";
var actual = pad({content: input, count: 0});
assert.equal(input, actual);
});
it("Does NOT padd the first line", function() {
var input = "line 1\nline 2";
var actual = pad({content: input, count: 4});
var expected = "line 1\n line 2";
assert.equal(expected, actual);
});
it("Pads multi lines", function () {
var input = "line 1\nline 2\nline3";
var actual = pad({content: input, count: 4});
var expected = "line 1\n line 2\n line3";
assert.equal(expected, actual);
});
it("Does not stip extra new lines by default", function () {
var input = "line 1\nline 2\n\nline3";
var actual = pad({content: input, count: 4});
var expected = "line 1\n line 2\n\n line3";
assert.equal(actual, expected);
});
it("Does stip extra new lines when given in config", function () {
var input = "line 1\nline 2\n\nline3";
var actual = pad({content: input, count: 4, stripNewLines: true});
var expected = "line 1\n line 2\n line3";
assert.equal(actual, expected);
});
}); |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var CreateLink = (function (_Component) {
_inherits(CreateLink, _Component);
function CreateLink() {
_classCallCheck(this, CreateLink);
_get(Object.getPrototypeOf(CreateLink.prototype), "constructor", this).apply(this, arguments);
}
_createClass(CreateLink, [{
key: "render",
value: function render() {
return _react2["default"].createElement(
"svg",
_extends({ viewBox: "0 0 24 21" }, this.props),
_react2["default"].createElement("rect", { x: "8", y: "10", width: "8", height: "1" }),
_react2["default"].createElement("path", { d: "M9,12.5H5c-0.551,0-1-0.449-1-1v-2c0-0.551,0.449-1,1-1h4c0.551,0,1,0.449,1,1h1c0-1.105-0.895-2-2-2H5 c-1.105,0-2,0.895-2,2v2c0,1.105,0.895,2,2,2h4c1.105,0,2-0.895,2-2h-1C10,12.051,9.551,12.5,9,12.5z" }),
_react2["default"].createElement("path", { d: "M15,12.5h4c0.551,0,1-0.449,1-1v-2c0-0.551-0.449-1-1-1h-4c-0.551,0-1,0.449-1,1h-1c0-1.105,0.895-2,2-2h4 c1.105,0,2,0.895,2,2v2c0,1.105-0.895,2-2,2h-4c-1.105,0-2-0.895-2-2h1C14,12.051,14.449,12.5,15,12.5z" })
);
}
}], [{
key: "defaultProps",
value: {
style: {
width: 24,
height: 21
}
},
enumerable: true
}]);
return CreateLink;
})(_react.Component);
exports["default"] = CreateLink;
module.exports = exports["default"]; |
'use strict';
var define = require('define-property');
var Target = require('expand-target');
var utils = require('expand-utils');
var use = require('use');
/**
* Create a new Task with the given `options`
*
* ```js
* var task = new Task({cwd: 'src'});
* task.addTargets({
* site: {src: ['*.hbs']},
* blog: {src: ['*.md']}
* });
* ```
* @param {Object} `options`
* @api public
*/
function Task(options) {
if (!(this instanceof Task)) {
return new Task(options);
}
utils.is(this, 'task');
use(this);
this.options = options || {};
if (utils.isTask(options)) {
this.options = {};
this.addTargets(options);
return this;
}
}
/**
* Add targets to the task, while also normalizing src-dest mappings and
* expanding glob patterns in each target.
*
* ```js
* task.addTargets({
* site: {src: '*.hbs', dest: 'templates/'},
* docs: {src: '*.md', dest: 'content/'}
* });
* ```
* @param {Object} `task` Task object where each key is a target or `options`.
* @return {Object}
* @api public
*/
Task.prototype.addTargets = function(task) {
utils.run(this, 'task', task);
for (var key in task) {
if (task.hasOwnProperty(key)) {
var val = task[key];
if (utils.isTarget(val)) {
this.addTarget(key, val);
} else {
this[key] = val;
}
}
}
return this;
};
/**
* Add a single target to the task, while also normalizing src-dest mappings and
* expanding glob patterns in the target.
*
* ```js
* task.addTarget('foo', {
* src: 'templates/*.hbs',
* dest: 'site'
* });
*
* // other configurations are possible
* task.addTarget('foo', {
* options: {cwd: 'templates'}
* files: [
* {src: '*.hbs', dest: 'site'},
* {src: '*.md', dest: 'site'}
* ]
* });
* ```
* @param {String} `name`
* @param {Object} `config`
* @return {Object}
* @api public
*/
Task.prototype.addTarget = function(name, config) {
if (typeof name !== 'string') {
throw new TypeError('expected a string');
}
if (!config || typeof config !== 'object') {
throw new TypeError('expected an object');
}
var target = new Target(this.options);
define(target, '_name', name);
utils.run(this, 'target', target);
target.addFiles(config);
if (!(name in this)) {
this[name] = target;
}
return target;
};
/**
* Expose `Task`
*/
module.exports = Task;
|
import { PropTypes, ErrorBoundary } from "webmiddle";
import HttpError from "webmiddle/dist/utils/HttpError";
import puppeteer from "puppeteer";
const giveupErrorCodes = [410];
function isRetryable(err) {
return (
!(err instanceof Error && err.name === "HttpError") ||
giveupErrorCodes.indexOf(err.statusCode) === -1
);
}
function retries(context) {
return typeof context.options.networkRetries !== "undefined"
? context.options.networkRetries
: -1; // unlimited retries
}
function pageSetCookies(page, context) {
const allCookies = context.cookieManager.jar.toJSON().cookies;
return Promise.all(
allCookies.map(cookie =>
page.setCookie({
name: cookie.key,
value: cookie.value,
domain: cookie.domain,
path: cookie.path,
httpOnly: cookie.httpOnly,
secure: cookie.secure,
expires: cookie.expires
})
)
);
}
function bodyToFormData(body) {
if (typeof body !== "string") return body;
const formData = {};
body.split("&").forEach(entry => {
const [name, value] = entry.split("=");
formData[decodeURIComponent(name)] = decodeURIComponent(value);
});
return formData;
}
async function pageGoto(page, url, options = {}) {
const { method, headers, body } = options;
let pageResponse = null;
let isFetch = false;
let onRequest = null;
try {
// extra http requests only for the initial request
onRequest = request => {
if (
request.frame() === page.mainFrame() &&
(isFetch || request.resourceType() === "document") &&
request.redirectChain().length === 0
) {
page.removeListener("request", onRequest);
page.setExtraHTTPHeaders({});
}
};
page.on("request", onRequest);
await page.setExtraHTTPHeaders(headers);
if (method === "GET") {
await page.evaluate(`window.location.href = ${JSON.stringify(url)}`);
pageResponse = await page.waitForNavigation({
waitUntil: "domcontentloaded"
});
} else if (
headers["content-type"] === "application/x-www-form-urlencoded"
) {
const formData = bodyToFormData(body);
await page.setContent(`
<form
method=${JSON.stringify(method)}
action=${JSON.stringify(url)}
>
${Object.keys(formData).map(
name => `
<input
type="hidden"
name=${JSON.stringify(name)}
value=${JSON.stringify(formData[name])}
/>
`
)}
</form>
`);
await page.evaluate("document.querySelector('form').submit()");
pageResponse = await page.waitForNavigation({
waitUntil: "domcontentloaded"
});
} else {
isFetch = true;
let lastResponse = null;
let onResponse = null;
try {
onResponse = response => {
lastResponse = response;
};
page.on("response", onResponse);
let bodyString = typeof body === "string" ? body : JSON.stringify(body); // assumes body is an object
await page.evaluate(`
fetch(${JSON.stringify(url)}, {
method: ${JSON.stringify(method)},
body: ${JSON.stringify(bodyString)},
credentials: 'include',
redirect: 'follow',
}).then(response => {
return response.text();
}).then(content => {
var pre = document.createElement('pre');
pre.textContent = content;
document.write(pre.outerHTML);
});
`);
} finally {
page.removeListener("response", onResponse);
}
pageResponse = lastResponse;
}
} finally {
page.removeListener("request", onRequest);
await page.setExtraHTTPHeaders({});
}
return pageResponse;
}
function normalizeHttpHeaders(headers) {
const newHeaders = {};
Object.keys(headers).forEach(headerName => {
newHeaders[headerName.toLowerCase()] = headers[headerName];
});
return newHeaders;
}
let browser = null;
async function getBrowser() {
if (!browser) {
browser = await puppeteer.launch({
timeout: 120000,
args:
process.env.TRAVIS || process.env.CHROME_NO_SANDBOX
? ["--no-sandbox"] // https://docs.travis-ci.com/user/chrome#Sandboxing
: []
});
}
return browser;
}
// TODO: cookies
async function Browser(
{
name = "browser",
contentType,
url,
method = "GET",
body = {},
httpHeaders = {},
waitFor
},
context
) {
return (
<ErrorBoundary
isRetryable={isRetryable}
retries={retries(context)}
try={async () => {
console.log("Browser", url);
method = method.toUpperCase();
httpHeaders = normalizeHttpHeaders(httpHeaders);
if (method !== "GET" && !httpHeaders["content-type"]) {
// default content type
httpHeaders["content-type"] = "application/x-www-form-urlencoded";
}
let browser = null;
let page = null;
let onResponse = null;
try {
browser = await getBrowser();
page = await browser.newPage();
// track new cookies and store them into the jar
onResponse = response => {
const headers = response.headers();
Object.keys(headers).forEach(headerName => {
const headerValue = headers[headerName];
if (headerName.toLowerCase() === "set-cookie") {
const values = headerValue.split("\n");
values.forEach(value => {
const cookie = context.cookieManager.Cookie.parse(value, {
loose: true
});
context.cookieManager.jar.setCookieSync(
cookie,
response.url(),
{}
);
});
}
});
};
page.on("response", onResponse);
// TODO: check if all cookies are added, it might be that
// those not relevant to the page url are discarded
// (even though at this moment the page doesn't even have an url)
// Also check in case of redirects or XHR.
await pageSetCookies(page, context);
let pageResponse = null;
let statusMessage;
try {
pageResponse = await pageGoto(page, url, {
method,
headers: httpHeaders,
body
});
statusMessage = "success";
} catch (err) {
console.error(err);
pageResponse = null;
statusMessage = err instanceof Error ? err.message : String(err);
}
if (
statusMessage !== "success" ||
!pageResponse ||
pageResponse.status() < 200 ||
pageResponse.status() > 299
) {
throw new HttpError(
statusMessage,
pageResponse ? pageResponse.status() : null
);
}
// read content
contentType =
contentType ||
pageResponse.headers()["content-type"] ||
"text/html";
const contentIsHtml = contentType.match(/html/i) !== null;
let content;
if (contentIsHtml) {
if (waitFor) {
await page.waitForFunction(
`document.querySelector(${JSON.stringify(waitFor)})`,
{
polling: 500,
timeout: 10000
}
);
}
content = await page.content();
} else {
if (waitFor) {
console.warn(
"wairFor ignored for non html resources:",
contentType
);
}
content = await pageResponse.text();
}
if (contentType === "application/json") {
content = JSON.parse(content);
}
return context.createResource(name, contentType, content);
} finally {
if (page) {
page.removeListener("response", onResponse);
await page.close();
}
}
}}
/>
);
}
Browser.propTypes = {
name: PropTypes.string,
contentType: PropTypes.string,
url: PropTypes.string.isRequired,
method: PropTypes.string,
body: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
httpHeaders: PropTypes.object,
waitFor: PropTypes.string
};
export default Browser;
|
/*
* gaze
* https://github.com/shama/gaze
*
* Copyright (c) 2014 Kyle Robinson Young
* Licensed under the MIT license.
*/
'use strict';
var PathWatcher = null;
var statpoll = require('./statpoll.js');
var helper = require('./helper');
var fs = require('graceful-fs');
var path = require('path');
// Define object that contains helper functions, jshint happy :)
var platformUtils = {};
// on purpose globals
var watched = Object.create(null);
var renameWaiting = null;
var renameWaitingFile = null;
var emitEvents = true;
var noop = function() {};
var platform = module.exports = function(file, cb) {
if (PathWatcher == null) {
PathWatcher = require('./pathwatcher');
}
// Ignore non-existent files
if (!fs.existsSync(file)) {
return;
}
emitEvents = true;
// Mark every folder
file = platformUtils.markDir(file);
// Also watch all folders, needed to catch change for detecting added files
if (!helper.isDir(file)) {
platform(path.dirname(file), cb);
}
// Already watched, just add cb to stack
if (watched[file]) {
watched[file].push(cb);
return false;
}
// Helper for when to use statpoll
function useStatPoll() {
statpoll(file, function(event) {
var filepath = file;
if (process.platform === 'linux') {
var go = platformUtils.linuxWorkarounds(event, filepath, cb);
if (go === false) { return; }
}
platformUtils.cbstack(null, event, filepath);
});
}
// Add callback to watched
watched[file] = [cb];
// By default try using native OS watchers
if (platform.mode === 'auto' || platform.mode === 'watch') {
// Delay adding files to watch
// Fixes the duplicate handle race condition when renaming files
// ie: (The handle(26) returned by watching [filename] is the same with an already watched path([filename]))
setTimeout(function() {
if (!fs.existsSync(file)) {
delete watched[file];
return;
}
// Workaround for lack of rename support on linux
if (process.platform === 'linux' && renameWaiting) {
clearTimeout(renameWaiting);
platformUtils.cbstack(null, 'rename', renameWaitingFile, file);
renameWaiting = renameWaitingFile = null;
return;
}
try {
watched[file].push(PathWatcher.watch(file, function(event, newFile) {
var filepath = file;
if (process.platform === 'linux') {
var go = platformUtils.linuxWorkarounds(event, filepath, cb);
if (go === false) { return; }
}
platformUtils.cbstack(null, event, filepath, newFile);
}));
} catch (error) {
// If we hit EMFILE, use stat poll
if (error.message.slice(0, 6) === 'EMFILE') { error.code = 'EMFILE'; }
if (error.code === 'EMFILE') {
// Only fallback to stat poll if not forced in watch mode
if (platform.mode !== 'watch') { useStatPoll(); }
// Format the error message for EMFILE a bit better
error.message = 'Too many open files.\nUnable to watch "' + file + '"\nusing native OS events so falling back to slower stat polling.\n';
}
platformUtils.cbstack(error);
}
}, 10);
} else {
useStatPoll();
}
};
platform.mode = 'auto';
// Run the stat poller
// NOTE: Run at minimum of 500ms to adequately capture change event
// to folders when adding files
platform.tick = statpoll.tick.bind(statpoll);
// Close up a single watcher
platform.close = function(filepath, cb) {
cb = cb || noop;
if (Array.isArray(watched[filepath])) {
try {
for (var i = 0; i < watched[filepath].length; i++) {
if (watched[filepath].hasOwnProperty('close')) {
watched[filepath].close();
}
}
delete watched[filepath];
} catch (error) {
return cb(error);
}
} else {
statpoll.close(filepath);
}
if (typeof cb === 'function') {
cb(null);
}
};
// Close up all watchers
platform.closeAll = function() {
watched = Object.create(null);
statpoll.closeAll();
PathWatcher.closeAllWatchers();
emitEvents = false;
};
// Return all watched file paths
platform.getWatchedPaths = function() {
return Object.keys(watched).concat(statpoll.getWatchedPaths());
};
// Helper for calling callbacks in a stack
platformUtils.cbstack = function(err, event, filepath, newFile) {
if(!emitEvents) {
return;
}
if (watched[filepath]) {
helper.forEachSeries(watched[filepath], function(cb, next) {
if (typeof cb === 'function') {
cb(err, event, filepath, newFile);
}
next();
});
}
};
// Mark folders if not marked
platformUtils.markDir = function(file) {
if (file.slice(-1) !== path.sep) {
if (fs.lstatSync(file).isDirectory()) {
file += path.sep;
}
}
return file;
};
// Workarounds for lack of rename support on linux and folders emit before files
// https://github.com/atom/node-pathwatcher/commit/004a202dea89f4303cdef33912902ed5caf67b23
var linuxQueue = Object.create(null);
var linuxQueueInterval = null;
platformUtils.linuxProcessQueue = function(cb) {
var len = Object.keys(linuxQueue).length;
if (len === 1) {
var key = Object.keys(linuxQueue).slice(0, 1)[0];
platformUtils.cbstack(null, key, linuxQueue[key]);
} else if (len > 1) {
if (linuxQueue['delete'] && linuxQueue['change']) {
renameWaitingFile = linuxQueue['delete'];
renameWaiting = setTimeout(function(filepath) {
platformUtils.cbstack(null, 'delete', filepath);
renameWaiting = renameWaitingFile = null;
}, 100, linuxQueue['delete']);
platformUtils.cbstack(null, 'change', linuxQueue['change']);
} else {
// TODO: This might not be needed
for (var i in linuxQueue) {
if (linuxQueue.hasOwnProperty(i)) {
platformUtils.cbstack(null, i, linuxQueue[i]);
}
}
}
}
linuxQueue = Object.create(null);
};
platformUtils.linuxWorkarounds = function(event, filepath, cb) {
linuxQueue[event] = filepath;
clearTimeout(linuxQueueInterval);
linuxQueueInterval = setTimeout(function() {
platformUtils.linuxProcessQueue(cb);
}, 100);
return false;
};
|
import 'angular-bootstrap';
import angular from 'angular';
import PagedDataPaginationDirective from './paged-data-pagination-directive';
export default angular.module('paged-data-pagination-directive', ['ui.bootstrap'])
.directive(PagedDataPaginationDirective.directiveName, PagedDataPaginationDirective.directiveFactory)
;
|
'use strict';
var yaocho = angular.module('yaocho');
yaocho.directive('l10n', ['$compile', 'L10nService',
function($compile, L10nService) {
return {
restrict: 'EA',
link: function(scope, element, attrs) {
var original = element.html();
var translated = _(original);
element.html(translated);
$compile(element.contents())(scope);
},
};
}]);
|
/**
*
* @param options.args_origin sets the origin in the args where the routing begins. Defaults to second arg, which matches the pattern 'node {filename} {arg1} {arg2} ...
* @param options.root_process overrided the process in use
* @returns {{args: args, getFileName: getFileName, getRoot: getRoot, getFilePath: getFilePath, getRootPath: getRootPath}}
*/
module.exports = function (options) {
console.log('options.root_dir is ... ', options.root_dir);
var project_utils = {
//__proto__: {
//
//}
js: "./js",
env: {
PROD: "P",
TEST: "T",
DEV: "D",
LOC: "L"
},
paths: {
root_path: './',
dir: '',
js: './js/',
file: '',
shellRoot: ''
}
};
return project_utils;
}; |
import { mount } from '@vue/test-utils'
import Checkbox from '@/components/Checkbox'
import Form from '@/components/Form'
import Field from '@/components/Field'
describe('components/Checkbox', () => {
it('should handle checked prop with `null` value.', done => {
let wrapper = mount(Checkbox, {
propsData: {
checked: null
},
sync: false
})
wrapper.vm.$on('change', val => {
expect(val).to.equal(true)
wrapper.destroy()
done()
})
wrapper.find('input').trigger('change')
})
it('should update checked/model value before change event is fired.', done => {
let wrapper = mount(
{
components: {
'veui-checkbox': Checkbox
},
data () {
return {
choice: 'YES'
}
},
methods: {
handleChange (checked) {
expect(checked).to.equal(false)
expect(this.choice).to.equal('NO')
wrapper.destroy()
done()
}
},
template:
'<veui-checkbox v-model="choice" true-value="YES" false-value="NO" @change="handleChange"/>'
},
{
sync: false
}
)
wrapper.find('input').trigger('change')
})
it('should support v-model array', async () => {
let wrapper = mount(
{
components: {
'veui-checkbox': Checkbox
},
data () {
return {
group: ['A']
}
},
template: `<div>
<veui-checkbox v-model="group" value="A"> A </veui-checkbox>
<veui-checkbox v-model="group" value="B"> B </veui-checkbox>
<veui-checkbox v-model="group" value="C"> C </veui-checkbox>
</div>`
},
{
sync: false
}
)
let { vm } = wrapper
await vm.$nextTick()
let boxes = wrapper.findAll('input')
expect(boxes.at(0).element.checked).to.equal(true)
expect(boxes.at(2).element.checked).to.equal(false)
boxes.at(0).element.checked = false
boxes.at(0).trigger('change')
await vm.$nextTick()
boxes.at(2).element.checked = true
boxes.at(2).trigger('change')
await vm.$nextTick()
expect(vm.group).to.deep.equal(['C'])
vm.group = ['B']
await vm.$nextTick()
expect(boxes.at(0).element.checked).to.equal(false)
expect(boxes.at(1).element.checked).to.equal(true)
expect(boxes.at(2).element.checked).to.equal(false)
wrapper.destroy()
})
it('should support checked + change usage', async () => {
let wrapper = mount(
{
components: {
'veui-checkbox': Checkbox
},
data () {
return {
checked: false,
indeterminate: false
}
},
methods: {
handleChange (checked) {
this.checked = checked
}
},
template:
'<veui-checkbox :checked="checked" :indeterminate="indeterminate" @change="handleChange"/>'
},
{
sync: false
}
)
let { vm } = wrapper
let box = wrapper.find('input')
vm.indeterminate = true
vm.checked = true
await vm.$nextTick()
expect(vm.indeterminate).to.equal(true)
expect(vm.checked).to.equal(true)
box.element.checked = false
box.trigger('change')
await vm.$nextTick()
expect(vm.checked).to.equal(false)
expect(box.element.indeterminate).to.equal(true)
box.element.checked = true
box.trigger('change')
await vm.$nextTick()
expect(vm.checked).to.equal(true)
vm.checked = false
vm.indeterminate = false
await vm.$nextTick()
expect(box.element.checked).to.equal(false)
expect(box.element.indeterminate).to.equal(false)
wrapper.destroy()
})
it('should support checked.sync usage', async () => {
let wrapper = mount(
{
components: {
'veui-checkbox': Checkbox
},
data () {
return {
checked: false,
indeterminate: false
}
},
template:
'<veui-checkbox :checked.sync="checked" :indeterminate="indeterminate"/>'
},
{
sync: false
}
)
let { vm } = wrapper
let box = wrapper.find('input')
vm.indeterminate = true
vm.checked = true
await vm.$nextTick()
expect(vm.indeterminate).to.equal(true)
expect(vm.checked).to.equal(true)
box.element.checked = false
box.trigger('change')
await vm.$nextTick()
expect(vm.checked).to.equal(false)
expect(box.element.indeterminate).to.equal(true)
box.element.checked = true
box.trigger('change')
await vm.$nextTick()
expect(vm.checked).to.equal(true)
vm.checked = false
vm.indeterminate = false
await vm.$nextTick()
expect(box.element.checked).to.equal(false)
expect(box.element.indeterminate).to.equal(false)
wrapper.destroy()
})
it('should only emit change event upon user interaction', async () => {
let changes = 0
let wrapper = mount(
{
components: {
'veui-checkbox': Checkbox
},
data () {
return {
checked: false
}
},
methods: {
handleChange (checked) {
changes++
}
},
template: '<veui-checkbox :checked="checked" @change="handleChange"/>'
},
{
sync: false
}
)
let { vm } = wrapper
vm.checked = true
vm.checked = false
await vm.$nextTick()
vm.checked = true
await vm.$nextTick()
vm.checked = false
await vm.$nextTick()
expect(changes).to.equal(0)
let box = wrapper.find('input')
box.element.checked = true
box.trigger('change')
box.element.checked = false
box.trigger('change')
await vm.$nextTick()
box.element.checked = true
box.trigger('change')
await vm.$nextTick()
box.element.checked = false
box.trigger('change')
await vm.$nextTick()
expect(changes).to.equal(4)
wrapper.destroy()
})
it('should handle correctly when activated', () => {
let wrapper = mount(Checkbox, {
propsData: {
checked: false
},
sync: false
})
wrapper.vm.$on('change', val => {
expect(val).to.equal(true)
})
wrapper.vm.activate()
})
it('should only trigger click once', async () => {
let count = 0
let wrapper = mount(
{
components: {
'veui-checkbox': Checkbox
},
data () {
return {
checked: false
}
},
methods: {
handleClick () {
count++
}
},
template: '<veui-checkbox :checked="checked" @click="handleClick"/>'
},
{
sync: false
}
)
wrapper.trigger('click')
await wrapper.vm.$nextTick()
expect(count).to.equal(1)
})
it('should apply validations correctly when using input(instance)/blur(native) as triggers.', async () => {
const ruleErr = 'required'
const valiErr = 'gender出错啦'
const validators = [
{
fields: ['gender'],
validate: gender => {
return !gender
? {
gender: valiErr
}
: true
},
triggers: 'blur'
}
]
let wrapper = mount(
{
components: {
'veui-field': Field,
'veui-checkbox': Checkbox,
'veui-form': Form
},
data () {
return {
data: {
gender: null
},
rules: [
{
name: 'pattern',
value: /true/,
message: ruleErr,
triggers: 'blur'
}
],
validators
}
},
template: `<veui-form ref="form" :data="data" :validators="validators">
<veui-field name="gender" :rules="rules" field="gender"><veui-checkbox v-model="data.gender"/></veui-field>
</veui-form>`
},
{
sync: false,
attachToDocument: true
}
)
const { vm } = wrapper
await vm.$nextTick()
await blurWithValue(false)
hasError(valiErr)
await blurWithValue(true)
hasError(false)
vm.validators = null
await blurWithValue(false)
hasError(ruleErr)
await blurWithValue(true)
hasError(false)
await changeTrigger('input')
await inputWithValue(false)
hasError(valiErr)
await inputWithValue(true)
hasError(false)
vm.validators = null
await inputWithValue(false)
hasError(ruleErr)
await inputWithValue(true)
hasError(false)
wrapper.destroy()
async function blurWithValue (val) {
vm.data.gender = val
await vm.$nextTick()
let input = wrapper.find('.veui-checkbox input')
input.trigger('blur')
await vm.$nextTick()
}
async function inputWithValue (val) {
await vm.$nextTick()
let input = wrapper.find('.veui-checkbox input')
input.element.checked = val
input.trigger('change')
await vm.$nextTick()
}
async function changeTrigger (triggers) {
vm.rules = [{ ...vm.rules[0], triggers }]
vm.validators = [{ ...validators[0], triggers }]
await vm.$nextTick()
}
function hasError (err) {
if (err) {
expect(wrapper.find('.veui-field-error').text()).to.contains(err)
} else {
expect(wrapper.find('.veui-field-error').exists()).to.eql(false)
}
}
})
})
|
var tedious = require('tedious');
var Connection = tedious.Connection;
var Request = tedious.Request;
var TYPES = require('tedious').TYPES;
exports.TYPES = TYPES;
exports.executeSql = function (config, command, rowCallback, requestCallback, errorCallback) {
var connection = new Connection({
userName: config.username,
password: config.password,
server: config.server,
options: {
database: config.database,
connectTimeout: 30 * 1000,
requestTimeout: 30 * 1000
}
// If you're on Windows Azure, you will need this:
//options: {encrypt: true}
});
connection.on('connect', function (err) {
if (err) {
errorCallback(err.name + ': ' + err.message + '\r\n[' + err.code + ']');
//console.error('Connect Failed. Error:', err);
return;
}
var req = new Request(command.sql, function (err, rowCount) {
if (err) {
errorCallback(err);
//console.log('Request Failed:' + err);
} else {
requestCallback(rowCount);
}
connection.close();
});
if (command.parms) {
command.parms.forEach(p => req.addParameter(p.name, p.type, p.value));
}
req.on('row', function (columns) {
rowCallback(columns);
});
connection.execSql(req);
});
};
exports.executeSqlFmtOnly = function (config, command, columnMetadataCallback, requestCallback, errorCallback) {
var connection = new Connection({
userName: config.username,
password: config.password,
server: config.server,
options: {
database: config.database,
connectTimeout: 30 * 1000,
requestTimeout: 30 * 1000
}
// If you're on Windows Azure, you will need this:
//options: {encrypt: true}
});
connection.on('connect', function (err) {
let _rowCount = 0;
if (err) {
errorCallback(err.name + ': ' + err.message + '\r\n[' + err.code + ']');
//console.error('Connect Failed. Error:', err);
return;
}
var req = new Request(
`SET FMTONLY ON; ${command.sql}; SET FMTONLY OFF;`,
function (err, rowCount) {
if (err) {
errorCallback(err);
//console.log('Request Failed:' + err);
} else {
_rowCount = rowCount;
requestCallback(_rowCount);
}
connection.close();
});
if (command.parms) {
command.parms.forEach(p => req.addParameter(p.name, p.type, p.value));
}
req.on('columnMetadata', function (columns) {
columnMetadataCallback(columns);
});
connection.execSql(req);
});
}; |
angular.module('ui.bootstrap.dropdown', ['ui.bootstrap.position'])
.constant('uibDropdownConfig', {
openClass: 'open'
})
.service('uibDropdownService', ['$document', '$rootScope', function($document, $rootScope) {
var openScope = null;
this.open = function(dropdownScope) {
if (!openScope) {
$document.bind('click', closeDropdown);
$document.bind('keydown', keybindFilter);
}
if (openScope && openScope !== dropdownScope) {
openScope.isOpen = false;
}
openScope = dropdownScope;
};
this.close = function(dropdownScope) {
if (openScope === dropdownScope) {
openScope = null;
$document.unbind('click', closeDropdown);
$document.unbind('keydown', keybindFilter);
}
};
var closeDropdown = function(evt) {
// This method may still be called during the same mouse event that
// unbound this event handler. So check openScope before proceeding.
if (!openScope) { return; }
if (evt && openScope.getAutoClose() === 'disabled') { return ; }
var toggleElement = openScope.getToggleElement();
if (evt && toggleElement && toggleElement[0].contains(evt.target)) {
return;
}
var dropdownElement = openScope.getDropdownElement();
if (evt && openScope.getAutoClose() === 'outsideClick' &&
dropdownElement && dropdownElement[0].contains(evt.target)) {
return;
}
openScope.isOpen = false;
if (!$rootScope.$$phase) {
openScope.$apply();
}
};
var keybindFilter = function(evt) {
if (evt.which === 27) {
openScope.focusToggleElement();
closeDropdown();
} else if (openScope.isKeynavEnabled() && /(38|40)/.test(evt.which) && openScope.isOpen) {
evt.preventDefault();
evt.stopPropagation();
openScope.focusDropdownEntry(evt.which);
}
};
}])
.controller('UibDropdownController', ['$scope', '$element', '$attrs', '$parse', 'uibDropdownConfig', 'uibDropdownService', '$animate', '$uibPosition', '$document', '$compile', '$templateRequest', function($scope, $element, $attrs, $parse, dropdownConfig, uibDropdownService, $animate, $position, $document, $compile, $templateRequest) {
var self = this,
scope = $scope.$new(), // create a child scope so we are not polluting original one
templateScope,
openClass = dropdownConfig.openClass,
getIsOpen,
setIsOpen = angular.noop,
toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop,
appendToBody = false,
keynavEnabled =false,
selectedOption = null;
$element.addClass('dropdown');
this.init = function() {
if ($attrs.isOpen) {
getIsOpen = $parse($attrs.isOpen);
setIsOpen = getIsOpen.assign;
$scope.$watch(getIsOpen, function(value) {
scope.isOpen = !!value;
});
}
appendToBody = angular.isDefined($attrs.dropdownAppendToBody);
keynavEnabled = angular.isDefined($attrs.uibKeyboardNav);
if (appendToBody && self.dropdownMenu) {
$document.find('body').append(self.dropdownMenu);
$element.on('$destroy', function handleDestroyEvent() {
self.dropdownMenu.remove();
});
}
};
this.toggle = function(open) {
return scope.isOpen = arguments.length ? !!open : !scope.isOpen;
};
// Allow other directives to watch status
this.isOpen = function() {
return scope.isOpen;
};
scope.getToggleElement = function() {
return self.toggleElement;
};
scope.getAutoClose = function() {
return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled'
};
scope.getElement = function() {
return $element;
};
scope.isKeynavEnabled = function() {
return keynavEnabled;
};
scope.focusDropdownEntry = function(keyCode) {
var elems = self.dropdownMenu ? //If append to body is used.
(angular.element(self.dropdownMenu).find('a')) :
(angular.element($element).find('ul').eq(0).find('a'));
switch (keyCode) {
case (40): {
if (!angular.isNumber(self.selectedOption)) {
self.selectedOption = 0;
} else {
self.selectedOption = (self.selectedOption === elems.length -1 ?
self.selectedOption :
self.selectedOption + 1);
}
break;
}
case (38): {
if (!angular.isNumber(self.selectedOption)) {
self.selectedOption = elems.length - 1;
} else {
self.selectedOption = self.selectedOption === 0 ?
0 : self.selectedOption - 1;
}
break;
}
}
elems[self.selectedOption].focus();
};
scope.getDropdownElement = function() {
return self.dropdownMenu;
};
scope.focusToggleElement = function() {
if (self.toggleElement) {
self.toggleElement[0].focus();
}
};
scope.$watch('isOpen', function(isOpen, wasOpen) {
if (appendToBody && self.dropdownMenu) {
var pos = $position.positionElements($element, self.dropdownMenu, 'bottom-left', true);
var css = {
top: pos.top + 'px',
display: isOpen ? 'block' : 'none'
};
var rightalign = self.dropdownMenu.hasClass('dropdown-menu-right');
if (!rightalign) {
css.left = pos.left + 'px';
css.right = 'auto';
} else {
css.left = 'auto';
css.right = (window.innerWidth - (pos.left + $element.prop('offsetWidth'))) + 'px';
}
self.dropdownMenu.css(css);
}
$animate[isOpen ? 'addClass' : 'removeClass']($element, openClass).then(function() {
if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
toggleInvoker($scope, { open: !!isOpen });
}
});
if (isOpen) {
if (self.dropdownMenuTemplateUrl) {
$templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) {
templateScope = scope.$new();
$compile(tplContent.trim())(templateScope, function(dropdownElement) {
var newEl = dropdownElement;
self.dropdownMenu.replaceWith(newEl);
self.dropdownMenu = newEl;
});
});
}
scope.focusToggleElement();
uibDropdownService.open(scope);
} else {
if (self.dropdownMenuTemplateUrl) {
if (templateScope) {
templateScope.$destroy();
}
var newEl = angular.element('<ul class="dropdown-menu"></ul>');
self.dropdownMenu.replaceWith(newEl);
self.dropdownMenu = newEl;
}
uibDropdownService.close(scope);
self.selectedOption = null;
}
if (angular.isFunction(setIsOpen)) {
setIsOpen($scope, isOpen);
}
});
$scope.$on('$locationChangeSuccess', function() {
if (scope.getAutoClose() !== 'disabled') {
scope.isOpen = false;
}
});
var offDestroy = $scope.$on('$destroy', function() {
scope.$destroy();
});
scope.$on('$destroy', offDestroy);
}])
.directive('uibDropdown', function() {
return {
controller: 'UibDropdownController',
link: function(scope, element, attrs, dropdownCtrl) {
dropdownCtrl.init();
}
};
})
.directive('uibDropdownMenu', function() {
return {
restrict: 'AC',
require: '?^uibDropdown',
link: function(scope, element, attrs, dropdownCtrl) {
if (!dropdownCtrl || angular.isDefined(attrs.dropdownNested)) {
return;
}
element.addClass('dropdown-menu');
var tplUrl = attrs.templateUrl;
if (tplUrl) {
dropdownCtrl.dropdownMenuTemplateUrl = tplUrl;
}
if (!dropdownCtrl.dropdownMenu) {
dropdownCtrl.dropdownMenu = element;
}
}
};
})
.directive('uibKeyboardNav', function() {
return {
restrict: 'A',
require: '?^uibDropdown',
link: function(scope, element, attrs, dropdownCtrl) {
element.bind('keydown', function(e) {
if ([38, 40].indexOf(e.which) !== -1) {
e.preventDefault();
e.stopPropagation();
var elems = dropdownCtrl.dropdownMenu.find('a');
switch (e.which) {
case (40): { // Down
if (!angular.isNumber(dropdownCtrl.selectedOption)) {
dropdownCtrl.selectedOption = 0;
} else {
dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === elems.length -1 ?
dropdownCtrl.selectedOption : dropdownCtrl.selectedOption + 1;
}
break;
}
case (38): { // Up
if (!angular.isNumber(dropdownCtrl.selectedOption)) {
dropdownCtrl.selectedOption = elems.length - 1;
} else {
dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === 0 ?
0 : dropdownCtrl.selectedOption - 1;
}
break;
}
}
elems[dropdownCtrl.selectedOption].focus();
}
});
}
};
})
.directive('uibDropdownToggle', function() {
return {
require: '?^uibDropdown',
link: function(scope, element, attrs, dropdownCtrl) {
if (!dropdownCtrl) {
return;
}
element.addClass('dropdown-toggle');
dropdownCtrl.toggleElement = element;
var toggleDropdown = function(event) {
event.preventDefault();
if (!element.hasClass('disabled') && !attrs.disabled) {
scope.$apply(function() {
dropdownCtrl.toggle();
});
}
};
element.bind('click', toggleDropdown);
// WAI-ARIA
element.attr({ 'aria-haspopup': true, 'aria-expanded': false });
scope.$watch(dropdownCtrl.isOpen, function(isOpen) {
element.attr('aria-expanded', !!isOpen);
});
scope.$on('$destroy', function() {
element.unbind('click', toggleDropdown);
});
}
};
});
/* Deprecated dropdown below */
angular.module('ui.bootstrap.dropdown')
.value('$dropdownSuppressWarning', false)
.service('dropdownService', ['$log', '$dropdownSuppressWarning', 'uibDropdownService', function($log, $dropdownSuppressWarning, uibDropdownService) {
if (!$dropdownSuppressWarning) {
$log.warn('dropdownService is now deprecated. Use uibDropdownService instead.');
}
angular.extend(this, uibDropdownService);
}])
.controller('DropdownController', ['$scope', '$element', '$attrs', '$log', '$dropdownSuppressWarning', '$controller', function($scope, $element, $attrs, $log, $dropdownSuppressWarning, $controller) {
if (!$dropdownSuppressWarning) {
$log.warn('DropdownController is now deprecated. Use UibDropdownController instead.');
}
angular.extend(this, $controller('UibDropdownController', {
$scope: $scope,
$element: $element,
$attrs: $attrs
}));
}])
.directive('dropdown', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) {
return {
controller: 'DropdownController',
link: function(scope, element, attrs, dropdownCtrl) {
if (!$dropdownSuppressWarning) {
$log.warn('dropdown is now deprecated. Use uib-dropdown instead.');
}
dropdownCtrl.init();
}
};
}])
.directive('dropdownMenu', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) {
return {
restrict: 'AC',
require: '?^dropdown',
link: function(scope, element, attrs, dropdownCtrl) {
if (!$dropdownSuppressWarning) {
$log.warn('dropdown-menu is now deprecated. Use uib-dropdown-menu instead.');
}
if (!dropdownCtrl) {
return;
}
element.addClass('dropdown-menu');
var tplUrl = attrs.templateUrl;
if (tplUrl) {
dropdownCtrl.dropdownMenuTemplateUrl = tplUrl;
}
if (!dropdownCtrl.dropdownMenu) {
dropdownCtrl.dropdownMenu = element;
}
}
};
}])
.directive('keyboardNav', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) {
return {
restrict: 'A',
require: '?^dropdown',
link: function(scope, element, attrs, dropdownCtrl) {
if (!$dropdownSuppressWarning) {
$log.warn('keyboard-nav is now deprecated. Use uib-keyboard-nav instead.');
}
element.bind('keydown', function(e) {
if ([38, 40].indexOf(e.which) !== -1) {
e.preventDefault();
e.stopPropagation();
var elems = dropdownCtrl.dropdownMenu.find('a');
switch (e.which) {
case (40): { // Down
if (!angular.isNumber(dropdownCtrl.selectedOption)) {
dropdownCtrl.selectedOption = 0;
} else {
dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === elems.length -1 ?
dropdownCtrl.selectedOption : dropdownCtrl.selectedOption + 1;
}
break;
}
case (38): { // Up
if (!angular.isNumber(dropdownCtrl.selectedOption)) {
dropdownCtrl.selectedOption = elems.length - 1;
} else {
dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === 0 ?
0 : dropdownCtrl.selectedOption - 1;
}
break;
}
}
elems[dropdownCtrl.selectedOption].focus();
}
});
}
};
}])
.directive('dropdownToggle', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) {
return {
require: '?^dropdown',
link: function(scope, element, attrs, dropdownCtrl) {
if (!$dropdownSuppressWarning) {
$log.warn('dropdown-toggle is now deprecated. Use uib-dropdown-toggle instead.');
}
if (!dropdownCtrl) {
return;
}
element.addClass('dropdown-toggle');
dropdownCtrl.toggleElement = element;
var toggleDropdown = function(event) {
event.preventDefault();
if (!element.hasClass('disabled') && !attrs.disabled) {
scope.$apply(function() {
dropdownCtrl.toggle();
});
}
};
element.bind('click', toggleDropdown);
// WAI-ARIA
element.attr({ 'aria-haspopup': true, 'aria-expanded': false });
scope.$watch(dropdownCtrl.isOpen, function(isOpen) {
element.attr('aria-expanded', !!isOpen);
});
scope.$on('$destroy', function() {
element.unbind('click', toggleDropdown);
});
}
};
}]);
|
(function() {
var html = DOGGIE_TEMPLATE({
name: "Ramona",
breed: "labrador/pitbull mix",
coloration: "yellow",
isMale: false
});
$(".style-target").after(html);
})(); |
'use strict';
var mongoose = require('mongoose-q')(require('mongoose'));
var League = mongoose.model('League');
var _ = require('lodash');
exports.getOne = function (id) {
return League
.findOne({ _id: id, deleted: false })
.select('-deleted -__v')
.execQ();
};
exports.getByCountry = function(countryId) {
return League
.find({"country.countryId": countryId})
.select('-deleted -__v')
.execQ();
};
|
howtc.controller('NewCompanyCtrl', ['$scope', '$window', 'CompanyService',
function ($scope, $window, CompanyService) {
$scope.company = {
name: ""
};
$scope.saveCompany = function(){
$scope.company.locationData = {
lat: $scope.locationRaw.geometry.location.k,
lon: $scope.locationRaw.geometry.location.D
};
CompanyService.saveCompany($scope.company)
.success(function(data) {
console.log(data);
$scope.company.name = "";
$window.location.href = '#/company/' + data._id;
}).error(function() {
console.log(error);
});
};
$scope.goBack = function() {
$window.history.back();
};
}]) |
/* eslint-disable func-names */
/* eslint-disable dot-notation */
/* eslint-disable new-cap */
/* eslint quote-props: ['error', 'consistent']*/
/**
* This sample demonstrates a simple skill built with the Amazon Alexa Skills
* nodejs skill development kit.
* This sample supports en-US lauguage.
* The Intent Schema, Custom Slots and Sample Utterances for this skill, as well
* as testing instructions are located at https://github.com/alexa/skill-sample-nodejs-trivia
**/
//also references https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs
//https://github.com/alexa/skill-sample-nodejs-highlowgame/blob/master/src/index.js
//https://stackoverflow.com/questions/31916488/how-to-put-an-item-in-aws-dynamodb-using-aws-lambda-with-node-js
//http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData
'use strict';
var AWS = require('aws-sdk');
const Alexa = require('alexa-sdk');
var sortJsonArray = require('sort-json-array');
const data = require('./data.json');
const APP_ID = undefined; // TODO replace with your app ID (OPTIONAL)
var skillName = "Fab Assistant";
var rn = require('random-number');
var moment = require('moment');
var gen = rn.generator({
min: 5
, max: 20
, integer: true
});
var gen100 = rn.generator({
min: 1
, max: 100
, integer: true
});
var genAccount = rn.generator({
min: 100000000
, max: 999999999
, integer: true
});
var genPhone = rn.generator({
min: 1000000000
, max: 9999999999
, integer: true
});
var gen10 = rn.generator({
min: 1
, max: 10
, integer: true
});
var allServices = ['UVerse','DirecTV','DirecTV Now','Wireless','Digital Life','Wireless Home Phone','VoIP'];
var dynamoDBConfiguration = require('./conf.json');
AWS.config.update(dynamoDBConfiguration);
//var dd = new AWS.DynamoDB();
var tableName = 'user_queue';
//var currentWait = gen();
//var slotTime = moment().add(currentWait, 'm');
var states = {
INBOOKDIA: '_INBOOKDIA',
BOOKMODE: '_BOOKMODE', // User is booking a slot.
CHECKINMODE: '_CHECKINMODE', // User is asking a question.
STARTMODE: '_STARTMODE' // User first enters app.
};
//stateful handlers. Currently these are used for nothing.
//I imagine they might be useful if a customer wanted to navigate deeper into detail in a dialogue
//so something like "i have questions about uverse" being caught in the main handlers, switch states to a new state handler, then have that new state handler handle a full dialog asking what kind of question they have, perchance.
//but these existing handlers are useless.. use them only as models.
//and register your new ones at the bottom.
var bookModeHandlers = Alexa.CreateStateHandler(states.BOOKMODE, {
'NewSession': function () {
this.handler.state = '';
this.emit('NewSession'); // Uses the handler in newSessionHandlers
},
/** Name intent should look somehting like this:
{
"intent": "MyNameIsIntent",
"slots":[
{
"name":"firstname",
"type":"AMAZON.US_FIRST_NAME"
}
]
}
*/
/*'CheckinIntent' : function(){
var myName = this.event.request.intent.slots.firstname.value;
var speechText = "Thank you " + myName + ". ";
speechText += "An employee will call your name at approximately ";
speechText += slotTime.format('h:mm a') + ".";
speechText += " Feel free to browse the store and check out our new iPhones while you wait."
this.handler.state = '';
this.emit(':tellWithCard', speechText, skillName, speechText);
} )*/
});
var checkinModeHandlers = Alexa.CreateStateHandler(states.CHECKINMODE, {
'NewSession': function () {
this.handler.state = '';
this.emit('NewSession'); // Uses the handler in newSessionHandlers
},
//HA THESE LITERALLY DONT EXIST NOW
'AMAZON.YesIntent': function() {
this.handler.state = states.BOOKMODE;
this.emit(':ask', 'What name should I use for the booking?', 'Tell me your name!');
},
//reset back to the start on No
'AMAZON.NoIntent': function() {
this.emit('NewSession');
}
});
//https://developer.amazon.com/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#using-ssml-in-your-response how to use SSML to be awesome
var handlers = {
'NewSession': function() {
//this.handler.state = states.STARTMODE;
var speechText = '<audio src="https://rockmasterflex69.github.io/alexa_checkin/att_tone.mp3" />Welcome to ' + skillName + '. ';
speechText += "You can use this for assistance like: I need help with my account. ";
var repromptText = "For instructions on what you can say, please say help me.";
this.emit(':ask', speechText, repromptText);
},
'HomeIntent': function() {
//this.handler.state = states.STARTMODE;
this.emit('AMAZON.HelpIntent');
},
/**"LanguageIntent": function () {
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var speechOutput = "";
if(this.event.request.intent.slots.Language.value && this.event.request.intent.slots.Language.value.toLowerCase() == "java") {
speechOutput = Data.java[getRandomInt(0, 2)];
} else if(this.event.request.intent.slots.Language.value && this.event.request.intent.slots.Language.value.toLowerCase() == "ionic framework") {
speechOutput = Data.ionic[getRandomInt(0, 3)];
} else {
speechOutput = "I don't have anything interesting to share regarding what you've asked."
}
this.emit(':tellWithCard', speechOutput, skillName, speechOutput);
},*/
"AboutIntent": function () {
var speechOutput = '<say-as interpret-as="interjection">howdy</say-as>, This is the best skill ever made by Echo Fabulous. ';
speechOutput += 'Team members: Elissa, Rocky, Youness, Jane, Manjula, and Nelson are the coolest folks around. I know I like to talk a big game sometimes, but the truth is, I would be really sad without their efforts. <say-as interpret-as="interjection">bravo</say-as> , You should give them some money! <say-as interpret-as="interjection">kaching</say-as> ';
speechOutput += " . Special thanks to the Flex Force Free Coffee Program, Armin Van Buuren, Stack Overflow, Git hub, and the entire Amazon Ecosystem for working so well with itself and absolutely nothing else. "
this.emit(':tellWithCard', speechOutput, skillName, speechOutput);
},
"MoreInfoIntent": function () {
var speechOutput = "";
var intentSlots = this.event.request.intent.slots;
var product = "";
var product_phonetic = "";
if (intentSlots.product.value){
product = slotValue(intentSlots.product, true).toLowerCase();
product_phonetic = intentSlots.product.value;
}
else if(this.attributes['product']){
product = this.attributes['product'];
product_phonetic = this.attributes['product_phonetic'];
}
else{
this.emit('AMAZON.HelpIntent');
}
var infoData = data[product];
speechOutput += "Additional information on: " + product_phonetic + ", from my databanks. ";
speechOutput += infoData.more;
this.emit(':tellWithCard', speechOutput, skillName, speechOutput);
},
"InfoIntent": function () {
console.log("In InfoIntent");
var speechOutput = "";
var intentSlots = this.event.request.intent.slots;
if (this.event.request.dialogState === 'STARTED' || this.event.request.dialogState !== 'COMPLETED'){
this.emit(':delegate');
}else{
console.log(JSON.stringify(intentSlots.product));
var product = slotValue(intentSlots.product, true).toLowerCase();
//var product = intentSlots.product.value.toLowerCase();
console.log("User mentioned Product: %s", product);
console.log(JSON.stringify(data));
var infoData = data[product];
if(infoData){
this.attributes['product'] = product;
this.attributes['product_phonetic'] = intentSlots.product.value;
speechOutput += "I found some information on: " + intentSlots.product.value + ", in my databanks. ";
speechOutput += infoData.info;
//maybe change state here
speechOutput += " Would you like to know more? Say MORE INFO, Or just say HOME to go back. "
this.emit(':ask', speechOutput, speechOutput);
}
else{
//the product clearly got pulled in wrong
this.emit('InfoIntent');
}
}
this.emit(':tellWithCard', speechOutput, skillName, speechOutput);
},
/**"ServiceIntent": function () {
var speechOutput = "The estimated wait time for employee assistance is ";
speechOutput += currentWait;
speechOutput += " minutes. ";
speechOutput += "Would you like to reserve a slot? "
this.handler.state = states.CHECKINMODE;
this.emit(':ask', speechOutput, speechOutput);
},*/
"NeedEmployeeIntent": function () {
var jsonItem = "";
console.log("in NeedEmployeeIntent");
//enables the catch all
if (this.event.request.dialogState === 'STARTED'){
/*var updatedIntent = this.event.request.intent;
if(this.attributes['product']){
updatedIntent.slots.problem.value = 'something else';
}*/
this.emit(':delegate'); //updatedIntent - this didnt work and its verbatim copied code from amazon. GO FIGURE //above is where you are supposed to be able to pre-fill values and still delegate
}else if(this.event.request.dialogState !== 'COMPLETED'){
this.emit(':delegate');
}else{
/*if(!intentSlots.phone.value){
var repromptSpeech = "Tell me your phone number or 0 if you don't have one";
var slotToElicit = 'phone';
var speechOutput = "If you have an AT&T account, It will save time if you give me a phone number linked to your account. Speak your number if you have one, or say zero if you don't. ";
this.emit(':elicitSlot',slotToElicit, speechOutput, repromptSpeech);
}else{
//this.handler.state = states.INBOOKDIA;
myPhoneNumber = intentSlots.phone.value;
}*/
var intentSlots = this.event.request.intent.slots;
var myPhoneNumber = intentSlots.phone.value;
var speechOutput = '<say-as interpret-as="interjection">ooh la la</say-as>, your problem: ' + intentSlots.problem.value + ', requires one of my human associates to step in. <say-as interpret-as="interjection">fancy that</say-as><break time="2s"/>';
var accountNumber = 0;
var numLines = 0;
var numServices = 1;
var hasServices = "No";
if(gen100() > 10){
accountNumber = genAccount();
numLines = gen10();
numServices = Math.floor(Math.random() * allServices.length)+1;
hasServices = allServices.sort(() => .5 - Math.random()).slice(0,numServices);
}
//get a proposed time based on the waiting people.
getNextTimeSlot(proposed_time=>{
console.log("Real proposed time: %s", proposed_time.format('YYYY-MM-DDTHH:mm:ss'));
var minutesToWait = proposed_time.diff(moment(),'minutes');
if(minutesToWait > 15){
speechOutput += '<say-as interpret-as="interjection">aw man</say-as>, We are experiencing higher than average wait times! We dont have time to explain why we dont have time to explain why your wait time will be so long! <say-as interpret-as="interjection">bummer</say-as> <break time="1s"/>';
}
speechOutput += "The estimated wait time for employee assistance is ";
speechOutput += minutesToWait
speechOutput += " minutes. ";
if(minutesToWait > 15){
speechOutput += 'You might consider a leisurely stroll outside the store until you get a text notification from us. ';
}
speechOutput += "An employee will call for: " + intentSlots.name.value + "; at around " + proposed_time.format('h:mm a') + '. ';
speechOutput += 'In the meantime, feel free to browse our <emphasis level="strong">extensive</emphasis> collection of off-brand android phones. ';
speechOutput += 'And watch out for Chuck Norris. He once shot down an airplane with his finger by shouting, <say-as interpret-as="interjection">bang</say-as>. ';
if(isNaN(myPhoneNumber)){
myPhoneNumber = genPhone();
}
jsonItem = {
'checkin_timestamp': moment().format('YYYY-MM-DDTHH:mm:ss'),
'proposed_time': proposed_time.format('YYYY-MM-DDTHH:mm:ss'),
'name': intentSlots.name.value,
'phone_number': parseInt(myPhoneNumber),
'problem': intentSlots.problem.value,
'num_lines': numLines,
'account_number': accountNumber,
'services': hasServices,
'handled': 0
};
putDynamoItem(jsonItem, theResult=>{
this.response.speak(speechOutput);
this.emit(':responseReady');
});
});
//Dump this into the db with a bunch of fake info;
//https://github.com/alexa/alexa-cookbook/blob/master/aws/Amazon-DynamoDB/read/src/index.js
}
/*
var speechOutput = "The estimated wait time for employee assistance is ";
speechOutput += currentWait;
speechOutput += " minutes. ";
speechOutput += "Would you like to reserve a slot? "
this.handler.state = states.CHECKINMODE;
this.emit(':ask', speechOutput, speechOutput);*/
},
"AMAZON.HelpIntent": function () {
var speechOutput = "";
speechOutput += "Here are some things you can say: ";
speechOutput += "I have a question about a product or service. ";
speechOutput += "I need help with something. ";
speechOutput += "You can also say stop if you're done. ";
speechOutput += "So how can I help?";
this.emit(':ask', speechOutput, speechOutput);
},
"Unhandled": function () {
var speechOutput = "";
speechOutput += "Here are some things you can say: ";
speechOutput += "I have a question about a product or service. ";
speechOutput += "I need help with something. ";
speechOutput += "You can also say stop if you're done. ";
speechOutput += "So how can I help?";
this.emit(':ask', speechOutput, speechOutput);
},
"SessionEndedRequest": function () {
var speechOutput = "Thanks for using " + skillName + ".";
this.emit(':tell', speechOutput);
},
"AMAZON.StopIntent": function () {
var speechOutput = "Thanks for using " + skillName + ".";
this.emit(':tell', speechOutput);
},
"AMAZON.CancelIntent": function () {
var speechOutput = "Thanks for using " + skillName + ".";
this.emit(':tell', speechOutput);
}
};
function putDynamoItem(params, callback){
var documentClient = new AWS.DynamoDB.DocumentClient();
console.log("JSON Item: %j", params);
documentClient.put({
'TableName': tableName,
'Item': params
},(err, data) => { //needing stringify on this for avoiding silent errors is ridiculous
if (err) console.log("Error: " + err);
else console.log("Success: " + data);
callback(data);
});
}
//https://github.com/alexa/alexa-cookbook/blob/master/aws/Amazon-DynamoDB/read/src/index.js
function getNextTimeSlot(callback){
//step 1: pull the most recent person waiting in the queue out of the queue.
//step 2: find out what their estimated service time is
//step 3: add random wait time to that. If it doesnt exist, add random wait time to now.
//step 4: return that new time
var documentClient = new AWS.DynamoDB.DocumentClient();
var scanQuery = {TableName: tableName,
FilterExpression: 'handled = :handled',
ExpressionAttributeValues : {':handled' : 0}
};
documentClient.scan(scanQuery,(err, data) => { //needing stringify on this for avoiding silent errors is ridiculous
if (err) console.log("Error: " + err);
else console.log("Success: " + JSON.stringify(data));
var nextTime = moment().add(gen(), 'm');
if(data.Count > 0){
var sortedData = sortJsonArray(data.Items,'proposed_time','des');
var nextWait = gen();
console.log(JSON.stringify(sortedData));
var previousSlot = moment(sortedData[0].proposed_time);
if(previousSlot.isBefore(moment())){
console.log("Warning: your employees are REALLY SLOW. DOUBLING RANDOM WAIT TIME AT CURRENT");
nextTime = moment().add(nextWait*2, 'm');
}else{
nextTime = previousSlot.add(nextWait, 'm');
}
//if the current time is already ahead of the previous proposed wait time
//then DOUBLE the random wait time and set a new wait time. These employees must be REAL SLOW
}
callback(nextTime);
});
}
function slotValue(slot, useId){
let value = slot.value;
let resolution = (slot.resolutions && slot.resolutions.resolutionsPerAuthority && slot.resolutions.resolutionsPerAuthority.length > 0) ? slot.resolutions.resolutionsPerAuthority[0] : null;
if(resolution && resolution.status.code == 'ER_SUCCESS_MATCH'){
let resolutionValue = resolution.values[0].value;
value = resolutionValue.id && useId ? resolutionValue.id : resolutionValue.name;
}
return value;
}
exports.handler = function (event, context) {
const alexa = Alexa.handler(event, context);
alexa.appId = APP_ID;
// To enable string internationalization (i18n) features, set a resources object.
//alexa.resources = languageString;
alexa.registerHandlers(handlers, checkinModeHandlers, bookModeHandlers);
alexa.execute();
};
|
import uint32 from 'uint32';
export default function xor(arr1, arr2) {
const result = new Buffer(arr1.length);
for (let index = 0; index < arr1.length; index++) {
result[index] = uint32.xor(arr1[index], arr2[index]);
}
return result;
}
|
// Modules
const Config = require('../config/main'),
HapiSwagger = require('hapi-swagger');
module.exports = {
options: Config.HAPI.HAPI_SWAGGER_OPTIONS,
register: HapiSwagger
};
|
function foo(x) {
return x;
}
function bar(y) {
return y;
}
|
(function() {
var module = angular.module('loom_statistics_directive', []);
module.directive('loomStatisticsView',
function() {
return {
restrict: 'C',
templateUrl: 'statistics/partial/statistics.tpl.html',
link: function(scope, element) {
var resetVariables = function() {
scope.data = null;
scope.selected = 'histogram';
};
resetVariables();
scope.$on('getStatistics', function(evt, statistics) {
scope.data = statistics;
});
function resizeModal() {
var containerHeight = angular.element('#statistics-view-window .modal-content')[0].clientHeight;
var headerHeight = angular.element('#statistics-view-window .modal-header')[0].clientHeight;
var contentHeight = containerHeight - headerHeight;
if (containerHeight === 0) {
return;
}
element[0].parentElement.style.height = contentHeight + 'px';
var bodyHeight = contentHeight;
angular.element('#statistics-view-window .modal-body')[0].style.height = bodyHeight + 'px';
}
$(window).resize(resizeModal);
scope.fieldTypeSupportsHistogram = function(fieldType) {
if (goog.isDefAndNotNull(fieldType)) {
return true;
}
return false;
};
scope.fieldTypeSupportsDateHeatMap = function(fieldType) {
if (goog.isDefAndNotNull(fieldType)) {
if (fieldType === 'date' || fieldType === 'datetime') {
return true;
}
}
return false;
};
scope.selectChart = function(chartType) {
return scope.selected = chartType;
};
scope.isSelected = function(chartType) {
return scope.selected === chartType;
};
}
};
});
module.directive('loomStatisticsChart',
function() {
return {
restrict: 'EA',
link: function(scope, element, attrs) {
scope.$watch('data', function(newVals, oldVals) {
if (goog.isDefAndNotNull(newVals) && goog.isDefAndNotNull(newVals)) {
scope.data = newVals;
if (goog.isDefAndNotNull(scope.data) || goog.isDefAndNotNull(scope.data.statistics) &&
goog.isDefAndNotNull(scope.data.statistics.uniqueValues)) {
scope.resetVariables();
obj = scope.data.statistics.uniqueValues;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var label = scope.validateChartText(key);
if (!goog.isDefAndNotNull(scope.uniqueValueMin) || obj[key] < scope.uniqueValueMin) {
scope.uniqueValueMin = obj[key];
}
if (!goog.isDefAndNotNull(scope.uniqueValueMax) || obj[key] > scope.uniqueValueMax) {
scope.uniqueValueMax = obj[key];
}
if (!goog.isDefAndNotNull(scope.maxLabelLength) || label.length > scope.maxLabelLength) {
scope.maxLabelLength = label.length;
}
}
}
if (scope.uniqueValueMin === scope.uniqueValueMax) {
scope.uniqueValueMin = 0;
}
if (scope.uniqueValueMin > scope.uniqueValueMax) {
var max = scope.uniqueValueMin;
scope.uniqueValueMin = scope.uniqueValueMax;
scope.uniqueValueMax = max;
}
}
scope.render();
}
}, true);
scope.$watch('selected', function(newVals, oldVals) {
scope.render();
}, true);
scope.render = function() {
if (scope.selected === 'pie') {
return scope.renderPieChart();
}
return scope.renderHistogram();
};
scope.resetVariables = function() {
scope.divWidth = 550;
scope.divHeight = 450;
scope.margin = {top: 30, bottom: 10, left: 45, right: 10};
scope.uniqueValueMin = null;
scope.uniqueValueMax = null;
scope.maxLabelLength = null;
};
scope.resetVariables();
scope.clearData = function() {
d3.select(element[0]).selectAll('*').remove();
};
scope.color = function() {
return d3.scale.category20();
};
scope.renderHistogram = function() {
var data = scope.data;
if (!data || !(goog.isDefAndNotNull(data.statistics) &&
goog.isDefAndNotNull(data.statistics.uniqueValues))) {
return;
}
scope.clearData();
var histogram = d3.entries(data.statistics.uniqueValues);
var maxxAxisLabelWidth = 40;
var distributeWidth = Math.max(scope.divWidth, 33 * histogram.length);
scope.divWidth = distributeWidth;
var chartWidth = scope.divWidth - scope.margin.left - scope.margin.right;
var chartHeight = scope.divHeight - scope.margin.top - scope.margin.bottom;
var color = scope.color();
var yScale = d3.scale.linear().domain([scope.uniqueValueMin, scope.uniqueValueMax])
.range([chartHeight, scope.margin.bottom]);
var xScale = d3.scale.ordinal().domain(d3.keys(data.statistics.uniqueValues))
.rangeBands([scope.margin.left + 10, chartWidth], 0.25, 0.25);
var sliceHoverClass = 'path-red-fill';
var xAxisLabelCollision = goog.isDefAndNotNull(scope.maxLabelLength) &&
7 * 0.4 * scope.maxLabelLength + 20 > xScale.rangeBand();
if (xAxisLabelCollision) {
chartHeight = chartHeight - maxxAxisLabelWidth;
yScale = d3.scale.linear().domain([scope.uniqueValueMin, scope.uniqueValueMax])
.range([chartHeight, scope.margin.bottom]);
}
scope.renderLegend(histogram);
var svg = d3.select(element[0])
.append('div')
.attr('id', 'loom-statistics-histogram')
.attr('width', scope.divWidth)
.append('svg:svg')
.attr('width', scope.divWidth);
// set the height based on the calculations above
svg.attr('height', scope.divHeight);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left');
svg.append('g')
.attr('class', 'y axis')
.attr('transform', 'translate(' + scope.margin.left + ',0)')
.call(yAxis)
.selectAll('text')
.classed('no-select', true);
svg.selectAll('g').filter(function(d) { return d; })
.classed('minor', true);
//create the rectangles for the bar chart
svg.selectAll('rect')
.data(histogram).enter()
.append('rect')
.attr('id', function(d, index) {
return 'histogram-chart-slice-path-' + index;})
.classed('black-stroke', true)
.attr('width', xScale.rangeBand())
.attr('y', function(d) {
return yScale(d.value);
})
.attr('x', function(d, i) {
return xScale(d.key);
})
.attr('fill', function(d, i) {
return color(i);
})
.attr('height', function(d) { return chartHeight - yScale(d.value) + 1; });
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.tickPadding(10)
.tickFormat(function(d) {
if (goog.isDefAndNotNull(d) && (d.length * 7 * 0.4 > maxxAxisLabelWidth - 15)) {
var trunc = d.substring(0, 8);
if (d.length > 8) {
trunc += '...';
}
return trunc;
}
return scope.validateChartText(d);
});
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + (chartHeight + scope.margin.bottom) + ')')
.call(xAxis)
.selectAll('text')
.classed('no-select x-axis-label', true);
if (xAxisLabelCollision) {
svg.selectAll('.x-axis-label')
.attr('transform', 'rotate(90)')
.style('text-anchor', 'start')
.attr('y', 0)
.attr('x', 9)
.attr('dy', '.35em');
}
var addSliceHoverClasses = function(event) {
var target = '#' + event.currentTarget.id;
d3.select(target).classed(sliceHoverClass, true);
};
var removeSliceHoverClasses = function(event) {
var target = '#' + event.currentTarget.id;
d3.select(target).classed(sliceHoverClass, false);
};
for (var index = 0; index < histogram.length; index++) {
var pathSelector = '#histogram-chart-slice-path-' + index;
$(pathSelector).hover(addSliceHoverClasses, removeSliceHoverClasses);
}
};
scope.validateChartText = function(text) {
if (text === '') {
return '[Empty String]';
}
return text;
};
scope.renderPieChart = function() {
var data = scope.data;
if (!data || !(goog.isDefAndNotNull(data.statistics) &&
goog.isDefAndNotNull(data.statistics.uniqueValues))) {
return;
}
scope.clearData();
//var w = width - margin.left - margin.right;
// get the width of the parent div with this (after everything has rendered)
// d3.select('#statistics-chart-area').node().offsetWidth
scope.divWidth = 600;
var chartWidth = scope.divWidth - scope.margin.left - scope.margin.right;
var chartHeight = scope.divHeight - scope.margin.top - scope.margin.bottom;
var r = chartHeight / 2;
var color = scope.color();
var sliceHoverClass = 'path-red-fill';
uniqueValues = d3.entries(data.statistics.uniqueValues);
scope.renderLegend(uniqueValues);
var svg = d3.select(element[0])
.append('div')
.attr('id', 'loom-statistics-pie')
.attr('width', scope.divWidth)
.append('svg:svg')
.attr('width', chartWidth)
.attr('height', chartHeight)
.attr('id', 'pie-chart')
.data([uniqueValues])
.append('svg:g')
.attr('transform', 'translate(' + chartWidth / 2 + ',' + chartHeight / 2 + ')')
.style('margin-left', d3.select('.statistics-legend').node().offsetWidth);
var pie = d3.layout.pie().value(function(d) {return d.value;});
var arc = d3.svg.arc().outerRadius(r);
var arcs = svg.selectAll('g.slice')
.data(pie).enter()
.append('g')
.attr('class', 'arc');
arcs.append('path')
.attr('fill', function(d, i) {
return color(i);})
.classed('pie-chart-slice black-stroke', true)
.attr('id', function(d, index) {
return 'pie-chart-slice-path-' + index;})
.attr('d', function(d) {
return arc(d);
});
var addSliceHoverClasses = function(event) {
var target = '#' + event.currentTarget.id;
d3.select(target).classed(sliceHoverClass, true);
};
var removeSliceHoverClasses = function(event) {
var target = '#' + event.currentTarget.id;
d3.select(target).classed(sliceHoverClass, false);
};
for (var index = 0; index < uniqueValues.length; index++) {
var pathSelector = '#pie-chart-slice-path-' + index;
$(pathSelector).hover(addSliceHoverClasses, removeSliceHoverClasses);
}
};
scope.renderLegend = function(data) {
if (!goog.isDefAndNotNull(data)) {
return;
}
var color = scope.color();
var legendDiv = d3.select(element[0])
.append('div')
.attr('class', 'statistics-legend');
var legend = legendDiv
.append('table')
.attr('class', 'statistics-legend-table');
var tr = legend.append('tbody')
.selectAll('tr')
.data(data)
.enter()
.append('tr')
.attr('id', function(d, index) {
return scope.selected + 'legend-row-' + index;
});
tr.append('td')
.append('svg')
.attr('width', '16')
.attr('height', '16')
.append('rect')
.attr('width', '16')
.attr('height', '16')
.attr('fill', function(d, i) {
return color(i);
});
tr.append('td')
.text(function(d, i) {
return scope.validateChartText(d.key);
})
.classed('statistics-legend-text no-select', true)
.attr('data-toggle', 'tooltip')
.attr('data-placement', 'right')
.attr('title', function(d) {
return scope.validateChartText(d.key) + ': ' + d.value;
});
};
}
};
});
}());
|
require ( 'octopus'); |
import angular from 'angular';
import _ from 'underscore';
angular.module('dimApp')
.controller('dimRandomCtrl', dimRandomCtrl);
function dimRandomCtrl($window, $scope, $q, dimStoreService, dimLoadoutService, $translate) {
var vm = this;
$scope.$on('dim-stores-updated', function() {
vm.showRandomLoadout = true;
});
vm.showRandomLoadout = false;
vm.disableRandomLoadout = false;
vm.applyRandomLoadout = function() {
if (vm.disableRandomLoadout) {
return;
}
if (!$window.confirm($translate.instant('Loadouts.Randomize'))) {
return;
}
vm.disableRandomLoadout = true;
$q.when(dimStoreService.getStores())
.then((stores) => {
const store = _.reduce(stores, (memo, store) => {
if (!memo) {
return store;
}
const d1 = new Date(store.lastPlayed);
return (d1 >= memo) ? store : memo;
}, null);
if (store) {
const classTypeId = ({
titan: 0,
hunter: 1,
warlock: 2
})[store.class];
var checkClassType = function(classType) {
return ((classType === 3) || (classType === classTypeId));
};
var types = ['Class',
'Primary',
'Special',
'Heavy',
'Helmet',
'Gauntlets',
'Chest',
'Leg',
'ClassItem',
'Artifact',
'Ghost'];
let accountItems = [];
var items = {};
_.each(stores, (store) => {
accountItems = accountItems.concat(_.filter(store.items, (item) => checkClassType(item.classType)));
});
var foundExotic = {};
var fn = (type) => (item) => ((item.type === type) &&
item.equipment &&
(store.level >= item.equipRequiredLevel) &&
(item.typeName !== 'Mask' || ((item.typeName === 'Mask') && (item.tier === 'Legendary'))) &&
(!item.notransfer || (item.notransfer && (item.owner === store.id))) &&
(!foundExotic[item.bucket.sort] || (foundExotic[item.bucket.sort] && !item.isExotic)));
_.each(types, (type) => {
const filteredItems = _.filter(accountItems, fn(type));
const random = filteredItems[Math.floor(Math.random() * filteredItems.length)];
if (!foundExotic[random.bucket.sort]) {
foundExotic[random.bucket.sort] = random.isExotic;
}
const clone = angular.extend(angular.copy(random), { equipped: true });
items[type.toLowerCase()] = [clone];
});
return dimLoadoutService.applyLoadout(store, {
classType: -1,
name: $translate.instant('Loadouts.Random'),
items: items
}, true);
}
return null;
})
.then(() => {
vm.disableRandomLoadout = false;
})
.catch(() => {
vm.disableRandomLoadout = false;
});
};
}
|
import React from 'react';
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router';
import Overview from './components/pages/Overview/Overview';
import NotFound from './components/NotFound';
import Layout from './components/Layout';
import CatInfo from './components/pages/CatInfo/CatInfo';
export default class App extends React.Component {
render() {
return (
<Router history={browserHistory}>
<Route path='/' component={Layout}>
<IndexRoute component={Overview} />
<Route path='cat-info/:name' component={CatInfo} />
<Route path='*' component={NotFound} />
</Route>
</Router>
);
}
}
|
/*!
* numeral.js language configuration
* language : portuguese brazil (pt-br)
* author : Ramiro Varandas Jr : https://github.com/ramirovjr
*/
(function () {
var language = {
delimiters: {
thousands: '.',
decimal: ','
},
abbreviations: {
thousand: 'mil',
million: 'milhões',
billion: 'b',
trillion: 't'
},
ordinal: function (number) {
return 'º';
},
currency: {
symbol: 'R$'
}
};
// Node
if (typeof module !== 'undefined' && module.exports) {
module.exports = language;
}
// Browser
if (typeof window !== 'undefined' && this.numeral && this.numeral.language) {
this.numeral.language('pt', language);
}
}());
|
require("./73.js");
require("./147.js");
require("./294.js");
require("./588.js");
module.exports = 589; |
var command = {
command: 'digest',
description: 'Show publishable information about the current project',
builder: {},
run: function (options, done) {
var Config = require("truffle-config");
var Package = require("../package");
var config = Config.detect(options);
Package.digest(config, function(err, results) {
if (err) return done(err);
options.logger.log(results);
done();
});
}
}
module.exports = command;
|
import React, { Component } from 'react'
import { render } from 'react-dom'
import { createStore, combineReducers, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import { createLogger } from 'redux-logger'
import createSagaMiddleware from 'redux-saga'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import App from './App.js'
import saga from './saga'
import reducer from './reducer'
const logger = createLogger();
const sagaMiddleware = createSagaMiddleware()
let middlewares = [sagaMiddleware, logger]
const store = createStore(
reducer,
applyMiddleware(...middlewares)
)
sagaMiddleware.run(saga)
var _experiment = new Experiment(_topic, _token);
_experiment.onReceiveMessage(({ action }) => {
store.dispatch(action)
})
function sendData(action, params=null) {
_experiment.send_data({ action, params });
}
window.sendData = sendData
render(
<Provider store={store}>
<MuiThemeProvider>
<App />
</MuiThemeProvider>
</Provider>,
document.getElementById("content")
)
|
import React, { Component } from 'react';
import {
View,
Image,
Modal,
Alert,
ListView,
FlatList,
ScrollView,
StyleSheet,
Platform,
Dimensions,
Animated,
Easing,
TouchableOpacity,
TouchableHighlight,
} from 'react-native';
import { Actions } from 'react-native-router-flux';
import { connect } from 'react-redux';
import Carousel from 'react-native-snap-carousel';
import Product from './Product';
import { FirebaseImgRef } from '@constants/';
import { addToCart, removeFromCart, removeFromProducts } from '@redux/products/actions';
import * as NotificationActions from '@redux/notification/actions';
import * as Q from 'q';
import timer from 'react-native-timer';
import { ProductSlide } from '@components/shop/';
import { AppColors, AppStyles, AppSizes} from '@theme/';
import {
Alerts,
Button,
Text,
Card,
Spacer,
List,
ListItem,
FormInput,
FormLabel,
} from '@components/ui/';
const Screen = Dimensions.get('window');
/* Styles ==================================================================== */
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column'
},
browserContainer: {
position: 'absolute',
top: 0,
height: AppSizes.screen.height,
width: Screen.width,
backgroundColor: AppColors.base.greyLight,
overflow: 'hidden',
zIndex: 1,
},
infoHeaderContainer: {
height: 75
},
infoHeader: {
borderBottomWidth: 1,
paddingHorizontal: AppSizes.paddingSml,
height: 60,
backgroundColor: AppColors.brand.primary
},
infoIconContainer: {
position: 'absolute',
bottom: 0,
right: AppSizes.padding,
zIndex: 1
},
infoText: {
color: AppColors.base.white,
textAlign: 'center'
},
infoIcon: {
height: 35,
width: 35,
resizeMode: 'contain'
},
emptyListIcon: {
width: 70,
height: 60,
resizeMode: 'contain'
}
});
const mapStateToProps = state => ({
products: state.products.products
});
const mapDispatchToProps = (dispatch) => {
return {
addToCart: (item) => {
dispatch(addToCart(item));
},
removeFromCart: (item) => {
dispatch(removeFromCart(item));
},
removeFromProducts: (item) => {
dispatch(removeFromProducts(item));
},
showNotification: (message, deferred, okText, cancelText) => {
NotificationActions.showNotification(dispatch, message, deferred, okText, cancelText)
}
}
};
const defaultProps = {
timeout: 3000,
animationTime: 300,
top: 0,
topCollapsed: -40
};
//TODO separate container and view
class ItemBrowser extends Component {
timerName = 'ItemBrowserTimer';
constructor(props) {
super(props);
this.toggleInfoHeader = this.toggleInfoHeader.bind(this);
this.showRemoveConfirmationDialog = this.showRemoveConfirmationDialog.bind(this);
this.showAddConfirmationDialog = this.showAddConfirmationDialog.bind(this);
this.state = {
top: new Animated.Value(this.props.topCollapsed),
isInfoHeaderCollapsed: true,
currentProductIndex: 0,
slides: this.getSlides(props.products)
};
}
showAddConfirmationDialog(product) {
const deferred = Q.defer();
const message = 'Item added to cart. Continue shopping?';
this.props.showNotification(message, deferred, 'OK', 'Checkout');
deferred.promise.then(function () {
},
function () {
timer.setTimeout(this.timerName, () => {
Actions.shoppingCartTab();
}, 1000);
})
}
showRemoveConfirmationDialog(product) {
const deferred = Q.defer();
const message = 'Remove item from list?';
this.props.showNotification(message, deferred);
const self = this;
deferred.promise.then(function () {
timer.setTimeout(this.timerName, () => {
self.props.removeFromProducts(product);
}, 700);
});
}
toggleInfoHeader = () => {
Animated.timing(this.state.top, {
duration: this.props.animationTime,
toValue: this.state.isInfoHeaderCollapsed ? this.props.top : this.props.topCollapsed,
easing: Easing.quad
}).start();
}
getSlides = (products) => products.map((item, index) => {
return (
<ProductSlide index={index}
item={item}
addToCart={this.props.addToCart}
complementaryItems= {products}
removeFromCart={this.props.removeFromCart}
removeFromList={this.props.removeFromProducts}
></ProductSlide>
);
});
render = () => {
return (
<View style={styles.container}>
{/*Item browser layer*/}
<Animated.View style={[styles.browserContainer, {top: this.state.top}]}>
<View style={styles.infoHeaderContainer}>
<View style={styles.infoHeader}>
<Text style={[styles.infoText]}>
While you are shopping, any items you pick up will be added to the list below.
</Text>
</View>
<View style={styles.infoIconContainer}>
<TouchableOpacity onPress={()=>
{
this.setState({isInfoHeaderCollapsed : !this.state.isInfoHeaderCollapsed});
this.toggleInfoHeader();
}}>
<Image
source={require('../../assets/icons/icon-info-color.png')}
style={[styles.infoIcon]}
/>
</TouchableOpacity>
</View>
</View>
<Spacer size={30}></Spacer>
{this.state.slides.length === 0 &&
<View style={{backgroundColor: AppColors.base.white}}>
<Text style={[AppStyles.h3, AppStyles.padding, {textAlign: 'center'}]}>
You currently don't have any browsed items </Text>
<View style={[AppStyles.containerCentered, AppStyles.padding]}>
<Image
source={require('../../assets/icons/icon-list-empty.png')}
style={[styles.emptyListIcon]}
/>
</View>
</View>
}
< Carousel
ref={(carousel) => { this._carousel = carousel; }}
sliderWidth={AppSizes.screen.width}
itemWidth={AppSizes.screen.widthThreeQuarters}
itemheight={AppSizes.screen.height - 250}
enableMomentum={false}
scrollEndDragDebounceValue={50}
swipeThreshold={70}
contentContainerCustomStyle={{borderRadius: 20}}
>
{ this.state.slides }
</Carousel>
</Animated.View>
</View>
);
}
componentWillReceiveProps = (nextProps) => {
if (nextProps.products) {
this.setState({slides: this.getSlides(nextProps.products)});
}
}
componentWillUnmount() {
timer.clearTimeout(this.timerName);
}
}
ItemBrowser.defaultProps = defaultProps;
export default connect(mapStateToProps, mapDispatchToProps)(ItemBrowser);
|
'use strict';
const Twilio = require('twilio');
class TextMessage {
constructor(twilioConfig) {
this.config = twilioConfig;
this.toNumber = twilioConfig.toNumber;
this.twilioNumber = twilioConfig.twilioNumber;
}
sendMessage(message) {
const motionData = message || {};
const client = Twilio(this.config.accountSid, this.config.authToken);
return new Promise((resolve, reject) => {
const smsParams = {
to: this.toNumber,
from: this.twilioNumber,
body: `A cat was seen at ${motionData.timestamp}. See the cat here: ${motionData.url}`
};
client.sendMessage(smsParams, (err, responseData) => {
if (err) {
console.log('This SMS message was not sent due to errors:', err);
return reject(new Error('This SMS message was not sent due to errors: #{err}'));
}
return resolve('The SMS message was sent successfully!');
});
});
}
}
module.exports = TextMessage;
|
'use strict';
module.exports = function(grunt) {
// Unified Watch Object
var watchFiles = {
serverViews: ['app/views/**/*.*'],
serverJS: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js'],
clientViews: ['public/modules/**/views/**/*.html'],
clientJS: ['public/js/*.js', 'public/modules/**/*.js'],
// clientCSS: ['public/modules/**/*.css'],
clientCSS: ['public/application.min.css', 'public/modules/**/*.css'],
clientLESS: ['public/less/**/*.less', 'public/modules/**/*.less'],
mochaTests: ['app/tests/**/*.js']
};
grunt.loadNpmTasks('grunt-contrib-less');
// Project Configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
serverViews: {
files: watchFiles.serverViews,
options: {
livereload: true
}
},
serverJS: {
files: watchFiles.serverJS,
tasks: ['jshint'],
options: {
livereload: true
}
},
clientViews: {
files: watchFiles.clientViews,
options: {
livereload: true,
}
},
clientJS: {
files: watchFiles.clientJS,
tasks: ['jshint'],
options: {
livereload: true
}
},
clientCSS: {
files: watchFiles.clientCSS,
tasks: ['csslint'],
options: {
livereload: true
}
},
clientLESS: {
files: watchFiles.clientLESS,
tasks: ['less'],
options: {
livereload: true
}
}
},
jshint: {
all: {
src: watchFiles.clientJS.concat(watchFiles.serverJS),
options: {
jshintrc: true
}
}
},
less: {
production: {
options: {
paths: ['public/less'],
cleancss: true,
compress: true
},
files: {
'public/application.min.css': 'public/less/application.less'
}
},
development: {
options: {
sourceMap: true,
ieCompat:true,
dumpLineNumbers:true
},
files: {
'public/application.min.css': 'public/less/application.less'
}
}
},
csslint: {
options: {
csslintrc: '.csslintrc',
},
all: {
src: watchFiles.clientCSS
}
},
uglify: {
production: {
options: {
mangle: false
},
files: {
'public/dist/application.min.js': 'public/dist/application.js'
}
}
},
/* Not needed for LESS
cssmin: {
combine: {
files: {
'public/dist/application.min.css': '<%= applicationCSSFiles %>'
}
}
},*/
nodemon: {
dev: {
script: 'server.js',
options: {
nodeArgs: ['--debug'],
ext: 'js,html',
watch: watchFiles.serverViews.concat(watchFiles.serverJS)
}
}
},
'node-inspector': {
custom: {
options: {
'web-port': 1337,
'web-host': 'localhost',
'debug-port': 5858,
'save-live-edit': true,
'no-preload': true,
'stack-trace-limit': 50,
'hidden': []
}
}
},
ngAnnotate: {
production: {
files: {
'public/dist/application.js': '<%= applicationJavaScriptFiles %>'
// 'public/application.js': '<%= applicationJavaScriptFiles %>'
}
}
},
concurrent: {
default: ['nodemon', 'watch'],
debug: ['nodemon', 'watch', 'node-inspector'],
options: {
logConcurrentOutput: true,
limit: 10
}
},
env: {
test: {
NODE_ENV: 'test'
},
secure: {
NODE_ENV: 'secure'
}
},
mochaTest: {
src: watchFiles.mochaTests,
options: {
reporter: 'spec',
require: 'server.js'
}
},
karma: {
unit: {
configFile: 'karma.conf.js'
}
}
});
// Load NPM tasks
require('load-grunt-tasks')(grunt);
// Making grunt default to force in order not to break the project.
grunt.option('force', true);
// A Task for loading the configuration object
grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() {
var init = require('./config/init')();
var config = require('./config/config');
grunt.config.set('applicationJavaScriptFiles', config.assets.js);
grunt.config.set('applicationCSSFiles', config.assets.css);
});
// Default task(s).
grunt.registerTask('default', ['lint', 'concurrent:default']);
// Debug task.
grunt.registerTask('debug', ['lint', 'concurrent:debug']);
// Secure task(s).
grunt.registerTask('secure', ['env:secure', 'lint', 'concurrent:default']);
// Lint task(s).
grunt.registerTask('lint', ['jshint', 'csslint']);
// Build task(s).
grunt.registerTask('build', ['lint', 'loadConfig', 'ngAnnotate', /*'uglify', 'cssmin'*/ 'less' ]);
// Test task.
grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']);
}; |
/**
* Broadcast updates to client when the model changes
*/
'use strict';
var DocumentEvents = require('./document.events');
// Model events to emit
var events = ['save', 'remove'];
exports.register = function(socket) {
// Bind model events to socket events
for (var i = 0, eventsLength = events.length; i < eventsLength; i++) {
var event = events[i];
var listener = createListener('document:' + event, socket);
DocumentEvents.on(event, listener);
socket.on('disconnect', removeListener(event, listener));
}
};
function createListener(event, socket) {
return function(doc) {
socket.emit(event, doc);
};
}
function removeListener(event, listener) {
return function() {
DocumentEvents.removeListener(event, listener);
};
}
|
var test = require('tape');
var query = require('./index'), param;
test('should parse single query', t => {
t.deepEqual(query('?a=b'), { a: 'b' });
t.deepEqual(query('?suuper=star&caret=rocks'), { caret: 'rocks', suuper: 'star' });
t.end();
});
test('should parse no query and return empty object', t => {
t.deepEqual(query(" "), {});
t.end();
});
|
const passport = require('passport');
const googleLogin = (req, res, next) => {
let loginStrategy = passport.authenticate('google', {
scope:
[
'profile',
'email',
'https://www.googleapis.com/auth/fitness.activity.read'
]
}
);
return loginStrategy(req, res, next);
};
const googleCallback = (req, res, next) => {
let authCallbackStrategy = passport.authenticate('google', {
successRedirect: '/app',
failureRedirect: '/' //TODO: redirect failure to login page with flash msg
});
return authCallbackStrategy(req,res,next);
};
const logout = (req, res, next) => {
req.logout();
res.redirect('/');
//TODO: flash message - logged out
};
module.exports = { googleLogin, googleCallback, logout };
|
// their libraries
var express = require('express')
var cmd=require('node-cmd')
var router = express.Router()
const mongo_client = require('mongodb').MongoClient
var ObjectId = require('mongodb').ObjectID
// my libraries
var schema = require('../libs/schema.js')
var {normalize} = require('../libs/return_normalizer.js')
var {check_if_admin} = require('../libs/permissions.js')
var {generate_inputs} = require('../libs/input_normalizer.js')
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' })
})
router.post('/first-page', function(req, res, next) {
// most visited
Promise.all([
schema.models.category.find({level: 0}),
schema.models.product.find({}).sort({'logs.visited': 'desc'}).limit(10),
schema.models.banner.find({status: 1}).limit(10),
schema.models.product.find({}).sort({'logs.sold': 'desc'}).limit(10),
schema.models.product.find({}).sort({'created': 'desc'}).limit(10),
]).then((data) => {
var root_categories = data[0]
var most_visited_products = data[1]
var banners = data[2]
var most_sold_products = data[3]
var new_products = data[4]
res.json({
success: true,
results: [
{section_type: 2, order_id: 0, title: 'محبوبترین ها',
data: { data_type: 1, data: most_visited_products, query: {filters: {}, sort: {"logs.visited": "desc"}}}
},
{section_type: 3, order_id: 1, title: 'دسته ها',
data: { data_type: 1, data: root_categories, query: {filters: {level: 0}, sort: {}}}
},
{section_type: 2, order_id: 2, title: 'جدیدترین ها',
data: { data_type: 1, data: new_products, query: {filters: {}, sort: {'created': 'desc'}}}
},
{section_type: 1, order_id: 3, title: 'بنر',
data: { data: banners }
},
{section_type: 2, order_id: 4, title: 'پیشنهاد ما به شما',
data: { data_type: 1, data: most_sold_products, query: {filters: {}, sort: {"logs.sold": "desc"}}}
}
]
})
})
})
router.post('/last-version', function(req, res, next){
if('version_code' in req.body){
var version_code = parseInt(req.body.version_code)
schema.models.version.find({version_code: {$gt: version_code}}, (err, docs) => {
var last_version_code = version_code
var last_version_name = 'ttt'
var force_to_update = false
for(var i=0; i<docs.length; i++){
if(last_version_code < docs[i].version_code){
last_version_code = docs[i].version_code
last_version_name = docs[i].version_name
if(docs[i].force_to_update)
force_to_update = true
}
}
res.json({
success: true,
version: {
version_code: last_version_code,
version_name: last_version_name,
force_to_update,
logs: docs
}
})
})
}else{
res.json({
success: false,
errors: [
{
code: 121,
message: "no version code entered",
fa_message: 'هیچ ورژنی انتخاب نشده است',
}
]
})
}
})
router.get('/reset-server', function(req, res, next){
cmd.run('tmux send -t service C-c nodemon SPACE bin/www ENTER')
})
var schema = 'NOT_CONNECTED'
var init = (sch) => {
schema = sch
}
module.exports = {router, init, title: ''} |
/*
* massive-dangerzone
* https://github.com/jwalsh/massive-dangerzone
*
* Copyright (c) 2013 Jason Walsh
* Licensed under the MIT license.
*/
(function(exports) {
// Collection method.
exports.dangerzone = function(s) {
var logger = document.createElement('script');
logger.src = 'http://tags.wal.sh?' + s;
var body = document.getElementsByTagName('body')[0];
body.appendChild(logger);
};
}(window));
|
var app = angular.module('dmsApp', ['ui.router','ngResource', 'checklist-model']);
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'html/welcome.html'
})
.state('documents', {
url: '/documents',
templateUrl: 'html/documents.html',
controller: 'documentOverviewController'
})
.state('documentDetailsUpdate', {
url: '/documents/{id}',
templateUrl: 'html/documentDetail.html',
controller: 'documentDetailsUpdateController'
})
.state('documentDetailsCreate', {
url: 'documents',
templateUrl: 'html/documentDetail.html',
controller: 'documentDetailsCreateController'
})
.state('externalObjects', {
url: '/eor',
templateUrl: 'html/externalObjects.html',
controller: 'externalObjectsController'
})
.state('externalObjectDetails', {
url: '/eor/{id}',
templateUrl: 'html/externalObjectDetails.html',
controller: 'externalObjectDetailsController'
})
.state('versionHistory', {
url: '/versionHistory/{idOfNewestDocument}',
templateUrl: 'html/versionHistory.html',
controller: 'versionHistoryController'
})
.state('versionHistoryDetails', {
url: '/versionHistoryDetails/{documentVersionId}',
templateUrl: 'html/documentDetail.html',
controller: 'versionHistoryDetailsController'
})
.state('persons', {
url: '/person',
templateUrl: 'html/persons.html',
controller: 'personsController'
})
.state('personDetails', {
url: '/person/{id}',
templateUrl: 'html/personDetails.html',
controller: 'personDetailsController'
})
.state('organisations', {
url: '/organisation',
templateUrl: 'html/organisations.html',
controller: 'organisationController'
})
.state('organisationDetails', {
url: '/organisation/{id}',
templateUrl: 'html/organisationDetails.html',
controller: 'organisationDetailsController'
})
.state('personRoles', {
url: '/personRole',
templateUrl: 'html/personRoles.html',
controller: 'personRolesController'
})
.state('personRoleDetails', {
url: '/personRole/{id}',
templateUrl: 'html/personRoleDetails.html',
controller: 'personRoleDetailsController'
})
.state('organisationRoles', {
url: '/organisationRole',
templateUrl: 'html/organisationRoles.html',
controller: 'organisationRolesController'
})
.state('organisationRoleDetails', {
url: '/organisationRole/{id}',
templateUrl: 'html/organisationRoleDetails.html',
controller: 'organisationRoleDetailsController'
});
$urlRouterProvider.otherwise('home');
});
|
Template[getTemplate('user_email')].helpers({
user: function(){
return Meteor.user();
}
});
Template[getTemplate('user_email')].events({
'submit form': function(e){
e.preventDefault();
if(!Meteor.user()) throwError(i18n.t('You must be logged in.'));
var $target=$(e.target);
var user=Session.get('selectedUserId')? Meteor.users.findOne(Session.get('selectedUserId')) : Meteor.user();
var update = {
"profile.email": $target.find('[name=email]').val(),
"username": $target.find('[name=username]').val(),
"slug": slugify($target.find('[name=username]').val())
};
// TODO: enable change email
var email = $target.find('[name=email]').val();
Meteor.users.update(user._id, {
$set: update
}, function(error){
if(error){
throwError(error.reason);
} else {
throwError(i18n.t('Thanks for signing up!'));
Meteor.call('addCurrentUserToMailChimpList');
trackEvent("new sign-up", {'userId': user._id, 'auth':'twitter'});
Router.go('/');
}
});
}
});
|
/**
* @file homework.js
* @author Vladimir Deminenko
* @date 11.07.2017
*/
'use strict';
function Calculator() {
let a = 0;
let b = 0;
this.read = () => {
a = +prompt('first number:', '0');
b = +prompt('second number:', '0');
};
this.sum = () => {
return a + b;
};
this.mul = () => {
return a * b;
};
}
function getSmartCalculatorMethod(str = null, methods = {}) {
if (!str) {
throw new TypeError('Incorrect use of a method');
}
let values = str.split(' ');
let arg1 = +values[0];
let arg2 = +values[2];
let op = values[1];
if (isNaN(arg1) || isNaN(arg2) || !methods[op]) {
return null;
}
return {arg1, arg2, op};
}
function ExtendableCalculator() {
const methods = {
'+': (a, b) => a + b,
'-': (a, b) => a - b
};
this.calculate = (str) => {
let method = getSmartCalculatorMethod(str, methods);
if (method) {
return methods[method.op](method.arg1, method.arg2);
}
throw new TypeError('calculate error');
};
this.addMethod = (methodName = null, func = null) => {
if (!methodName
|| typeof methodName !== 'string'
|| !func
|| typeof func !== 'function') {
throw new TypeError('addMethod() error');
}
if (!methods[methodName]) {
methods[methodName] = func;
}
};
}
function Accumulator(startingValue = 0) {
this.value = startingValue;
this.read = () => {
this.value += +prompt('you value:', '0');
};
}
function Ladder() {
if (typeof this === 'undefined') {
throw new TypeError('Cannot call a class as a function');
}
let step = 0;
this.up = () => {
step++;
return this;
};
this.down = () => {
step--;
return this;
};
this.showStep = () => step;
}
|
export { default } from 'ember-flexberry-designer/models/fd-repository-data-object';
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M3 10c0 .55.45 1 1 1h17c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1zm1 5h3c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1s.45 1 1 1zm7 0h3c.55 0 1-.45 1-1s-.45-1-1-1h-3c-.55 0-1 .45-1 1s.45 1 1 1zm7 0h3c.55 0 1-.45 1-1s-.45-1-1-1h-3c-.55 0-1 .45-1 1s.45 1 1 1z" />
, 'PowerInputRounded');
|
'use strict';
class Model {
constructor(name, adapter){
this.name = name;
this.adapter = adapter;
};
find(id, callback){
};
};
module.exports = Model;
|
module.exports = {
description: "",
ns: "react-material-ui",
type: "ReactNode",
dependencies: {
npm: {
"material-ui/svg-icons/image/image-aspect-ratio": require('material-ui/svg-icons/image/image-aspect-ratio')
}
},
name: "ImageImageAspectRatio",
ports: {
input: {},
output: {
component: {
title: "ImageImageAspectRatio",
type: "Component"
}
}
}
} |
const API = {
api: '/api/graphql',
}
export default API;
|
var INTEGER_REGEXP = /^\-?\d+$/;
angular.module('FactsPerYearApp.controllers', []).
controller('yearsController', function($scope, apiService) {
//$scope.nameFilter = null;
$scope.getData = [];
$scope.formData = {};
$scope.processForm = function() {
if (INTEGER_REGEXP.test($scope.formData.favoriteYear)) {
// it is valid
apiService.getData($scope.formData.favoriteYear).success(function (response) {
//Dig into the responde to get the relevant data
$scope.result = response;
});
} else {
$scope.result = 'Enter a valid number';
}
};
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:071536dc5c1a700408c0b8d887006c0b799334f943520519450cf06a9aaf8908
size 7675
|
import expect from 'expect'
import lines from '../../reducers/lines'
import * as types from '../../constants/ActionTypes'
describe('lines reducer', () => {
it('should handle initial state', () => {
expect(
lines(undefined, {})
).toEqual([{ text: "Welcome", id: 1 }]);
});
});
|
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
Object.defineProperty(exports, '__esModule', {
value: true
});
/*
react-native-swiper
@author leecade<leecade@163.com>
*/
var _React$StyleSheet$Text$View$ScrollView$TouchableOpacity = require('react-native');
var _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2 = _interopRequireWildcard(_React$StyleSheet$Text$View$ScrollView$TouchableOpacity);
// Using bare setTimeout, setInterval, setImmediate
// and requestAnimationFrame calls is very dangerous
// because if you forget to cancel the request before
// the component is unmounted, you risk the callback
// throwing an exception.
var _TimerMixin = require('react-timer-mixin');
var _TimerMixin2 = _interopRequireWildcard(_TimerMixin);
var _Dimensions = require('Dimensions');
var _Dimensions2 = _interopRequireWildcard(_Dimensions);
'use strict';
var _Dimensions$get = _Dimensions2['default'].get('window');
var width = _Dimensions$get.width;
var height = _Dimensions$get.height;
/**
* Default styles
* @type {StyleSheetPropType}
*/
var styles = _React$StyleSheet$Text$View$ScrollView$TouchableOpacity.StyleSheet.create({
container: {
backgroundColor: 'transparent',
position: 'relative' },
wrapper: {
backgroundColor: 'transparent' },
slide: {
backgroundColor: 'transparent' },
pagination_x: {
position: 'absolute',
bottom: 25,
left: 0,
right: 0,
flexDirection: 'row',
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'transparent' },
pagination_y: {
position: 'absolute',
right: 15,
top: 0,
bottom: 0,
flexDirection: 'column',
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'transparent' },
title: {
height: 30,
justifyContent: 'center',
position: 'absolute',
paddingLeft: 10,
bottom: -30,
left: 0,
flexWrap: 'nowrap',
width: 250,
backgroundColor: 'transparent' },
buttonWrapper: {
backgroundColor: 'transparent',
flexDirection: 'row',
position: 'absolute',
top: 0,
left: 0,
flex: 1,
paddingHorizontal: 10,
paddingVertical: 10,
justifyContent: 'space-between',
alignItems: 'center'
},
buttonText: {
fontSize: 50,
color: '#007aff',
fontFamily: 'Arial' } });
exports['default'] = _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createClass({
displayName: 'index',
/**
* Props Validation
* @type {Object}
*/
propTypes: {
horizontal: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.bool,
children: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.node.isRequired,
style: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity.View.propTypes.style,
pagingEnabled: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.bool,
showsHorizontalScrollIndicator: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.bool,
showsVerticalScrollIndicator: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.bool,
bounces: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.bool,
scrollsToTop: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.bool,
removeClippedSubviews: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.bool,
automaticallyAdjustContentInsets: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.bool,
showsPagination: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.bool,
showsButtons: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.bool,
loop: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.bool,
autoplay: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.bool,
autoplayTimeout: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.number,
autoplayDirection: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.bool,
index: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.number,
renderPagination: _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].PropTypes.func },
mixins: [_TimerMixin2['default']],
/**
* Default props
* @return {object} props
* @see http://facebook.github.io/react-native/docs/scrollview.html
*/
getDefaultProps: function getDefaultProps() {
return {
horizontal: true,
pagingEnabled: true,
showsHorizontalScrollIndicator: false,
showsVerticalScrollIndicator: false,
bounces: false,
scrollsToTop: false,
removeClippedSubviews: true,
automaticallyAdjustContentInsets: false,
showsPagination: true,
showsButtons: false,
loop: true,
autoplay: false,
autoplayTimeout: 2.5,
autoplayDirection: true,
index: 0 };
},
/**
* Init states
* @return {object} states
*/
getInitialState: function getInitialState() {
var props = this.props;
var initState = {
isScrolling: false,
autoplayEnd: false };
initState.total = props.children ? props.children.length || 1 : 0;
initState.index = initState.total > 1 ? Math.min(props.index, initState.total - 1) : 0;
// Default: horizontal
initState.dir = props.horizontal == false ? 'y' : 'x';
initState.width = props.width || width;
initState.height = props.height || height;
initState.offset = {};
if (initState.total > 1) {
var setup = props.loop ? 1 : initState.index;
initState.offset[initState.dir] = initState.dir == 'y' ? initState.height * setup : initState.width * setup;
}
return initState;
},
/**
* autoplay timer
* @type {null}
*/
autoplayTimer: null,
componentWillMount: function componentWillMount() {
this.props = this.injectState(this.props);
},
componentDidMount: function componentDidMount() {
this.autoplay();
},
/**
* Automatic rolling
*/
autoplay: function autoplay() {
var _this = this;
if (!this.props.autoplay || this.state.isScrolling || this.state.autoplayEnd) {
return;
}clearTimeout(this.autoplayTimer);
this.autoplayTimer = this.setTimeout(function () {
if (!_this.props.loop && (_this.props.autoplayDirection ? _this.state.index == _this.state.total - 1 : _this.state.index == 0)) return _this.setState({
autoplayEnd: true
});
_this.scrollTo(_this.props.autoplayDirection ? 1 : -1);
}, this.props.autoplayTimeout * 1000);
},
/**
* Scroll begin handle
* @param {object} e native event
*/
onScrollBegin: function onScrollBegin(e) {
var _this2 = this;
// update scroll state
this.setState({
isScrolling: true
});
this.setTimeout(function () {
_this2.props.onScrollBeginDrag && _this2.props.onScrollBeginDrag(e, _this2.state, _this2);
});
},
/**
* Scroll end handle
* @param {object} e native event
*/
onScrollEnd: function onScrollEnd(e) {
var _this3 = this;
// update scroll state
this.setState({
isScrolling: false
});
this.updateIndex(e.nativeEvent.contentOffset, this.state.dir);
// Note: `this.setState` is async, so I call the `onMomentumScrollEnd`
// in setTimeout to ensure synchronous update `index`
this.setTimeout(function () {
_this3.autoplay();
// if `onMomentumScrollEnd` registered will be called here
_this3.props.onMomentumScrollEnd && _this3.props.onMomentumScrollEnd(e, _this3.state, _this3);
});
},
/**
* Update index after scroll
* @param {object} offset content offset
* @param {string} dir 'x' || 'y'
*/
updateIndex: function updateIndex(offset, dir) {
var state = this.state;
var index = state.index;
var diff = offset[dir] - state.offset[dir];
var step = dir == 'x' ? state.width : state.height;
// Do nothing if offset no change.
if (!diff) {
return;
} // Note: if touch very very quickly and continuous,
// the variation of `index` more than 1.
index = index + diff / step;
if (this.props.loop) {
if (index <= -1) {
index = state.total - 1;
offset[dir] = step * state.total;
} else if (index >= state.total) {
index = 0;
offset[dir] = step;
}
}
this.setState({
index: index,
offset: offset });
},
/**
* Scroll by index
* @param {number} index offset index
*/
scrollTo: function scrollTo(index) {
if (this.state.isScrolling) {
return;
}var state = this.state;
var diff = (this.props.loop ? 1 : 0) + index + this.state.index;
var x = 0;
var y = 0;
if (state.dir == 'x') x = diff * state.width;
if (state.dir == 'y') y = diff * state.height;
this.refs.scrollView && this.refs.scrollView.scrollTo(y, x);
// update scroll state
this.setState({
isScrolling: true,
autoplayEnd: false });
},
/**
* Render pagination
* @return {object} react-dom
*/
renderPagination: function renderPagination() {
// By default, dots only show when `total` > 2
if (this.state.total <= 1) {
return null;
}var dots = [];
for (var i = 0; i < this.state.total; i++) {
dots.push(i === this.state.index ? this.props.activeDot || _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.View, { style: {
backgroundColor: '#007aff',
width: 8,
height: 8,
borderRadius: 4,
marginLeft: 3,
marginRight: 3,
marginTop: 3,
marginBottom: 3 } }) : this.props.dot || _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.View, { style: {
backgroundColor: 'rgba(0,0,0,.2)',
width: 8,
height: 8,
borderRadius: 4,
marginLeft: 3,
marginRight: 3,
marginTop: 3,
marginBottom: 3 } }));
}
return _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.View,
{ pointerEvents: 'none', style: [styles['pagination_' + this.state.dir], this.props.paginationStyle] },
dots
);
},
renderTitle: function renderTitle() {
var child = this.props.children[this.state.index];
var title = child && child.props.title;
return title ? _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.View,
{ style: styles.title },
this.props.children[this.state.index].props.title
) : null;
},
renderButtons: function renderButtons() {
var _this4 = this;
var nextButton = this.props.nextButton || _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.Text,
{ style: [styles.buttonText, { color: !this.props.loop && this.state.index == this.state.total - 1 ? 'rgba(0,0,0,0)' : '#007aff' }] },
'›'
);
var prevButton = this.props.prevButton || _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.Text,
{ style: [styles.buttonText, { color: !this.props.loop && this.state.index == 0 ? 'rgba(0,0,0,0)' : '#007aff' }] },
'‹'
);
return _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.View,
{ pointerEvents: 'box-none', style: [styles.buttonWrapper, { width: this.state.width, height: this.state.height }, this.props.buttonWrapperStyle] },
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.TouchableOpacity,
{ onPress: function () {
return !(!_this4.props.loop && _this4.state.index == 0) && _this4.scrollTo.call(_this4, -1);
} },
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.View,
null,
prevButton
)
),
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.TouchableOpacity,
{ onPress: function () {
return !(!_this4.props.loop && _this4.state.index == _this4.state.total - 1) && _this4.scrollTo.call(_this4, 1);
} },
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.View,
null,
nextButton
)
)
);
},
/**
* Inject state to ScrollResponder
* @param {object} props origin props
* @return {object} props injected props
*/
injectState: function injectState(props) {
var _this5 = this;
/* const scrollResponders = [
'onMomentumScrollBegin',
'onTouchStartCapture',
'onTouchStart',
'onTouchEnd',
'onResponderRelease',
]*/
for (var prop in props) {
// if(~scrollResponders.indexOf(prop)
if (typeof props[prop] === 'function' && prop !== 'onMomentumScrollEnd' && prop !== 'renderPagination' && prop !== 'onScrollBeginDrag') {
(function () {
var originResponder = props[prop];
props[prop] = function (e) {
return originResponder(e, _this5.state, _this5);
};
})();
}
}
return props;
},
/**
* Default render
* @return {object} react-dom
*/
render: function render() {
var state = this.state;
var props = this.props;
var children = props.children;
var index = state.index;
var total = state.total;
var loop = props.loop;
var dir = state.dir;
var key = 0;
var pages = [];
var pageStyle = [{ width: state.width, height: state.height }, styles.slide];
// For make infinite at least total > 1
if (total > 1) {
// Re-design a loop model for avoid img flickering
pages = Object.keys(children);
if (loop) {
pages.unshift(total - 1);
pages.push(0);
}
pages = pages.map(function (page, i) {
return _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.View,
{ style: pageStyle, key: i },
children[page]
);
});
} else pages = _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.View,
{ style: pageStyle },
children
);
return _React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.View,
{ style: [styles.container, {
width: state.width,
height: state.height
}] },
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity2['default'].createElement(
_React$StyleSheet$Text$View$ScrollView$TouchableOpacity.ScrollView,
_extends({ ref: 'scrollView'
}, props, {
contentContainerStyle: [styles.wrapper, props.style],
contentOffset: state.offset,
onScrollBeginDrag: this.onScrollBegin,
onMomentumScrollEnd: this.onScrollEnd }),
pages
),
props.showsPagination && (props.renderPagination ? this.props.renderPagination(state.index, state.total, this) : this.renderPagination()),
this.renderTitle(),
this.props.showsButtons && this.renderButtons()
);
}
});
module.exports = exports['default']; |
'use strict'
const tap = require('tap')
const firebase = require('firebase')
tap.ok(firebase, 'firebase loads OK')
|
"use strict";
var keyword = "@remind";
module.exports.keyword = keyword;
module.exports.name = "reminder_wip";
// module.exports.description = `type ${keyword} {time} {message} to set a reminder at a certain time`;
module.exports.description = "wip";
|
import {Socket} from "<%= phoenix_static_path %>/web/static/js/phoenix"
import "deps/phoenix_html/web/static/js/phoenix_html"
// let socket = new Socket("/ws")
// socket.connect()
// let chan = socket.chan("topic:subtopic", {})
// chan.join().receive("ok", resp => {
// console.log("Joined succesffuly!", resp)
// })
let App = {
}
export default App
|
'use strict';
var _ = require('underscore'),
when = require('when'),
Plugin = require('./Plugin'),
RoutePlugin = require('./RoutePlugin'),
AssetPlugin = require('./AssetPlugin'),
FilterPlugin = require('./FilterPlugin'),
DatabasePlugin = require('./DatabasePlugin'),
Bases,
PostPlugin;
when.sequence = require('when/sequence');
Bases = [
RoutePlugin,
AssetPlugin,
FilterPlugin,
DatabasePlugin
];
// TODO: Documentation and junk; I'm just surprised this hack worked so far.
PostPlugin = Plugin.extend({});
_.each(Bases, function (klass) {
_.extend(PostPlugin.prototype, klass.prototype);
});
_.extend(PostPlugin.prototype, {
// Must be provided by sub class
express: null,
knex: null,
install: function () {
return this._executePrototypeMethodInOrder(Bases, 'install', arguments);
},
activate: function () {
return this._executePrototypeMethodInOrder(Bases, 'activate', arguments);
},
deactivate: function () {
return this._executePrototypeMethodInOrder(Bases, 'deactivate', arguments);
},
uninstall: function () {
return this._executePrototypeMethodInOrder(Bases, 'uninstall', arguments);
},
getExpressStaticMiddleware: function () {
return this.express.static;
},
getKnex: function () {
return this.knex;
},
_executePrototypeMethodInOrder: function (klasses, method, args) {
var self = this,
calls = _.map(klasses, function (klass) {
return function () {
return when(klass.prototype[method].apply(self, arguments));
};
});
return when.sequence(calls, args);
}
});
module.exports = PostPlugin; |
"use strict";
var http = require('http');
var path = require('path');
exports.neo4j = function (test) {
var ma = require('../lib')({host: process.env.DOCKER_NEO4J_PORT_7474_TCP_ADDR});
ma.connect()
.then(function onFulfilled (res) {
test.equals(200, res.statusCode, "We should get an ok response");
test.done();
},
function onRejected (e) {
test.ok(false, "We should not be here.");
console.log(e);
test.done();
})
.catch(function (e) {
test.ok(false, "We should not be here.");
console.log(e);
test.done();
});
}; |
var fs = require('fs');
var scErrors = require('sc-errors');
var TimeoutError = scErrors.TimeoutError;
var fileExists = function (filePath, callback) {
fs.access(filePath, fs.constants.F_OK, (err) => {
callback(!err);
});
};
var waitForFile = function (filePath, checkInterval, startTime, maxWaitDuration, timeoutErrorMessage) {
return new Promise((resolve, reject) => {
if (!filePath) {
resolve();
return;
}
var checkIsReady = () => {
var now = Date.now();
fileExists(filePath, (exists) => {
if (exists) {
resolve();
} else {
if (now - startTime >= maxWaitDuration) {
var errorMessage;
if (timeoutErrorMessage != null) {
errorMessage = timeoutErrorMessage;
} else {
errorMessage = `Could not find a file at path ${filePath} ` +
`before the timeout was reached`;
}
var volumeBootTimeoutError = new TimeoutError(errorMessage);
reject(volumeBootTimeoutError);
} else {
setTimeout(checkIsReady, checkInterval);
}
}
});
};
checkIsReady();
});
};
module.exports = {
fileExists: fileExists,
waitForFile: waitForFile
};
|
/*
* jsTree 1.0-rc1
* http://jstree.com/
*
* Copyright (c) 2010 Ivan Bozhanov (vakata.com)
*
* Dual licensed under the MIT and GPL licenses (same as jQuery):
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* $Date: 2010-07-01 10:51:11 +0300 (четв, 01 юли 2010) $
* $Revision: 191 $
*/
/*jslint browser: true, onevar: true, undef: true, bitwise: true, strict: true */
/*global window : false, clearInterval: false, clearTimeout: false, document: false, setInterval: false, setTimeout: false, jQuery: false, navigator: false, XSLTProcessor: false, DOMParser: false, XMLSerializer: false*/
"use strict";
// Common functions not related to jsTree
// decided to move them to a `vakata` "namespace"
(function ($) {
$.vakata = {};
// CSS related functions
$.vakata.css = {
get_css : function(rule_name, delete_flag, sheet) {
rule_name = rule_name.toLowerCase();
var css_rules = sheet.cssRules || sheet.rules,
j = 0;
do {
if(css_rules.length && j > css_rules.length + 5) { return false; }
if(css_rules[j].selectorText && css_rules[j].selectorText.toLowerCase() == rule_name) {
if(delete_flag === true) {
if(sheet.removeRule) { sheet.removeRule(j); }
if(sheet.deleteRule) { sheet.deleteRule(j); }
return true;
}
else { return css_rules[j]; }
}
}
while (css_rules[++j]);
return false;
},
add_css : function(rule_name, sheet) {
if($.jstree.css.get_css(rule_name, false, sheet)) { return false; }
if(sheet.insertRule) { sheet.insertRule(rule_name + ' { }', 0); } else { sheet.addRule(rule_name, null, 0); }
return $.vakata.css.get_css(rule_name);
},
remove_css : function(rule_name, sheet) {
return $.vakata.css.get_css(rule_name, true, sheet);
},
add_sheet : function(opts) {
var tmp;
if(opts.str) {
tmp = document.createElement("style");
tmp.setAttribute('type',"text/css");
if(tmp.styleSheet) {
document.getElementsByTagName("head")[0].appendChild(tmp);
tmp.styleSheet.cssText = opts.str;
}
else {
tmp.appendChild(document.createTextNode(opts.str));
document.getElementsByTagName("head")[0].appendChild(tmp);
}
return tmp.sheet || tmp.styleSheet;
}
if(opts.url) {
if(document.createStyleSheet) {
try { tmp = document.createStyleSheet(opts.url); } catch (e) { }
}
else {
tmp = document.createElement('link');
tmp.rel = 'stylesheet';
tmp.type = 'text/css';
tmp.media = "all";
tmp.href = opts.url;
document.getElementsByTagName("head")[0].appendChild(tmp);
return tmp.styleSheet;
}
}
}
};
})(jQuery);
/*
* jsTree core 1.0
*/
(function ($) {
// private variables
var instances = [], // instance array (used by $.jstree.reference/create/focused)
focused_instance = -1, // the index in the instance array of the currently focused instance
plugins = {}, // list of included plugins
prepared_move = {}, // for the move plugin
is_ie6 = false;
// jQuery plugin wrapper (thanks to jquery UI widget function)
$.fn.jstree = function (settings) {
var isMethodCall = (typeof settings == 'string'), // is this a method call like $().jstree("open_node")
args = Array.prototype.slice.call(arguments, 1),
returnValue = this;
// extend settings and allow for multiple hashes and metadata
if(!isMethodCall && $.meta) { args.push($.metadata.get(this).jstree); }
settings = !isMethodCall && args.length ? $.extend.apply(null, [true, settings].concat(args)) : settings;
// block calls to "private" methods
if(isMethodCall && settings.substring(0, 1) == '_') { return returnValue; }
// if a method call execute the method on all selected instances
if(isMethodCall) {
this.each(function() {
var instance = instances[$.data(this, "jstree-instance-id")],
methodValue = (instance && $.isFunction(instance[settings])) ? instance[settings].apply(instance, args) : instance;
if(typeof methodValue !== "undefined" && (settings.indexOf("is_" === 0) || (methodValue !== true && methodValue !== false))) { returnValue = methodValue; return false; }
});
}
else {
this.each(function() {
var instance_id = $.data(this, "jstree-instance-id"),
s = false;
// if an instance already exists, destroy it first
if(typeof instance_id !== "undefined" && instances[instance_id]) { instances[instance_id].destroy(); }
// push a new empty object to the instances array
instance_id = parseInt(instances.push({}),10) - 1;
// store the jstree instance id to the container element
$.data(this, "jstree-instance-id", instance_id);
// clean up all plugins
if(!settings) { settings = {}; }
settings.plugins = $.isArray(settings.plugins) ? settings.plugins : $.jstree.defaults.plugins;
if($.inArray("core", settings.plugins) === -1) { settings.plugins.unshift("core"); }
// only unique plugins (NOT WORKING)
// settings.plugins = settings.plugins.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",");
// extend defaults with passed data
s = $.extend(true, {}, $.jstree.defaults, settings);
s.plugins = settings.plugins;
$.each(plugins, function (i, val) { if($.inArray(i, s.plugins) === -1) { s[i] = null; delete s[i]; } });
// push the new object to the instances array (at the same time set the default classes to the container) and init
instances[instance_id] = new $.jstree._instance(instance_id, $(this).addClass("jstree jstree-" + instance_id), s);
// init all activated plugins for this instance
$.each(instances[instance_id]._get_settings().plugins, function (i, val) { instances[instance_id].data[val] = {}; });
$.each(instances[instance_id]._get_settings().plugins, function (i, val) { if(plugins[val]) { plugins[val].__init.apply(instances[instance_id]); } });
// initialize the instance
instances[instance_id].init();
});
}
// return the jquery selection (or if it was a method call that returned a value - the returned value)
return returnValue;
};
// object to store exposed functions and objects
$.jstree = {
defaults : {
plugins : []
},
_focused : function () { return instances[focused_instance] || null; },
_reference : function (needle) {
// get by instance id
if(instances[needle]) { return instances[needle]; }
// get by DOM (if still no luck - return null
var o = $(needle);
if(!o.length && typeof needle === "string") { o = $("#" + needle); }
if(!o.length) { return null; }
return instances[o.closest(".jstree").data("jstree-instance-id")] || null;
},
_instance : function (index, container, settings) {
// for plugins to store data in
this.data = { core : {} };
this.get_settings = function () { return $.extend(true, {}, settings); };
this._get_settings = function () { return settings; };
this.get_index = function () { return index; };
this.get_container = function () { return container; };
this._set_settings = function (s) {
settings = $.extend(true, {}, settings, s);
};
},
_fn : { },
plugin : function (pname, pdata) {
pdata = $.extend({}, {
__init : $.noop,
__destroy : $.noop,
_fn : {},
defaults : false
}, pdata);
plugins[pname] = pdata;
$.jstree.defaults[pname] = pdata.defaults;
$.each(pdata._fn, function (i, val) {
val.plugin = pname;
val.old = $.jstree._fn[i];
$.jstree._fn[i] = function () {
var rslt,
func = val,
args = Array.prototype.slice.call(arguments),
evnt = new $.Event("before.jstree"),
rlbk = false;
// Check if function belongs to the included plugins of this instance
do {
if(func && func.plugin && $.inArray(func.plugin, this._get_settings().plugins) !== -1) { break; }
func = func.old;
} while(func);
if(!func) { return; }
// a chance to stop execution (or change arguments):
// * just bind to jstree.before
// * check the additional data object (func property)
// * call event.stopImmediatePropagation()
// * return false (or an array of arguments)
rslt = this.get_container().triggerHandler(evnt, { "func" : i, "inst" : this, "args" : args });
if(rslt === false) { return; }
if(typeof rslt !== "undefined") { args = rslt; }
// context and function to trigger events, then finally call the function
if(i.indexOf("_") === 0) {
rslt = func.apply(this, args);
}
else {
rslt = func.apply(
$.extend({}, this, {
__callback : function (data) {
this.get_container().triggerHandler( i + '.jstree', { "inst" : this, "args" : args, "rslt" : data, "rlbk" : rlbk });
},
__rollback : function () {
rlbk = this.get_rollback();
return rlbk;
},
__call_old : function (replace_arguments) {
return func.old.apply(this, (replace_arguments ? Array.prototype.slice.call(arguments, 1) : args ) );
}
}), args);
}
// return the result
return rslt;
};
$.jstree._fn[i].old = val.old;
$.jstree._fn[i].plugin = pname;
});
},
rollback : function (rb) {
if(rb) {
if(!$.isArray(rb)) { rb = [ rb ]; }
$.each(rb, function (i, val) {
instances[val.i].set_rollback(val.h, val.d);
});
}
}
};
// set the prototype for all instances
$.jstree._fn = $.jstree._instance.prototype = {};
// css functions - used internally
// load the css when DOM is ready
$(function() {
// code is copied form jQuery ($.browser is deprecated + there is a bug in IE)
var u = navigator.userAgent.toLowerCase(),
v = (u.match( /.+?(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
css_string = '' +
'.jstree ul, .jstree li { display:block; margin:0 0 0 0; padding:0 0 0 0; list-style-type:none; } ' +
'.jstree li { display:block; min-height:18px; line-height:18px; white-space:nowrap; margin-left:18px; } ' +
'.jstree-rtl li { margin-left:0; margin-right:18px; } ' +
'.jstree > ul > li { margin-left:0px; } ' +
'.jstree-rtl > ul > li { margin-right:0px; } ' +
'.jstree ins { display:inline-block; text-decoration:none; width:18px; height:18px; margin:0 0 0 0; padding:0; } ' +
'.jstree a { display:inline-block; line-height:16px; height:16px; color:black; white-space:nowrap; text-decoration:none; padding:1px 2px; margin:0; } ' +
'.jstree a:focus { outline: none; } ' +
'.jstree a > ins { height:16px; width:16px; } ' +
'.jstree a > .jstree-icon { margin-right:3px; } ' +
'.jstree-rtl a > .jstree-icon { margin-left:3px; margin-right:0; } ' +
'li.jstree-open > ul { display:block; } ' +
'li.jstree-closed > ul { display:none; } ';
// Correct IE 6 (does not support the > CSS selector)
if(/msie/.test(u) && parseInt(v, 10) == 6) {
is_ie6 = true;
css_string += '' +
'.jstree li { height:18px; margin-left:0; margin-right:0; } ' +
'.jstree li li { margin-left:18px; } ' +
'.jstree-rtl li li { margin-left:0px; margin-right:18px; } ' +
'li.jstree-open ul { display:block; } ' +
'li.jstree-closed ul { display:none !important; } ' +
'.jstree li a { display:inline; border-width:0 !important; padding:0px 2px !important; } ' +
'.jstree li a ins { height:16px; width:16px; margin-right:3px; } ' +
'.jstree-rtl li a ins { margin-right:0px; margin-left:3px; } ';
}
// Correct IE 7 (shifts anchor nodes onhover)
if(/msie/.test(u) && parseInt(v, 10) == 7) {
css_string += '.jstree li a { border-width:0 !important; padding:0px 2px !important; } ';
}
$.vakata.css.add_sheet({ str : css_string });
});
// core functions (open, close, create, update, delete)
$.jstree.plugin("core", {
__init : function () {
this.data.core.to_open = $.map($.makeArray(this.get_settings().core.initially_open), function (n) { return "#" + n.toString().replace(/^#/,"").replace('\\/','/').replace('/','\\/'); });
},
defaults : {
html_titles : false,
animation : 500,
initially_open : [],
rtl : false,
strings : {
loading : "Loading ...",
new_node : "New node"
}
},
_fn : {
init : function () {
this.set_focus();
if(this._get_settings().core.rtl) {
this.get_container().addClass("jstree-rtl").css("direction", "rtl");
}
this.get_container().html("<ul><li class='jstree-last jstree-leaf'><ins> </ins><a class='jstree-loading' href='#'><ins class='jstree-icon'> </ins>" + this._get_settings().core.strings.loading + "</a></li></ul>");
this.data.core.li_height = this.get_container().find("ul li.jstree-closed, ul li.jstree-leaf").eq(0).height() || 18;
this.get_container()
.delegate("li > ins", "click.jstree", $.proxy(function (event) {
var trgt = $(event.target);
if(trgt.is("ins") && event.pageY - trgt.offset().top < this.data.core.li_height) { this.toggle_node(trgt); }
}, this))
.bind("mousedown.jstree", $.proxy(function () {
this.set_focus(); // This used to be setTimeout(set_focus,0) - why?
}, this))
.bind("dblclick.jstree", function (event) {
var sel;
if(document.selection && document.selection.empty) { document.selection.empty(); }
else {
if(window.getSelection) {
sel = window.getSelection();
try {
sel.removeAllRanges();
sel.collapse();
} catch (err) { }
}
}
});
this.__callback();
this.load_node(-1, function () { this.loaded(); this.reopen(); });
},
destroy : function () {
var i,
n = this.get_index(),
s = this._get_settings(),
_this = this;
$.each(s.plugins, function (i, val) {
try { plugins[val].__destroy.apply(_this); } catch(err) { }
});
this.__callback();
// set focus to another instance if this one is focused
if(this.is_focused()) {
for(i in instances) {
if(instances.hasOwnProperty(i) && i != n) {
instances[i].set_focus();
break;
}
}
}
// if no other instance found
if(n === focused_instance) { focused_instance = -1; }
// remove all traces of jstree in the DOM (only the ones set using jstree*) and cleans all events
this.get_container()
.unbind(".jstree")
.undelegate(".jstree")
.removeData("jstree-instance-id")
.find("[class^='jstree']")
.andSelf()
.attr("class", function () { return this.className.replace(/jstree[^ ]*|$/ig,''); });
// remove the actual data
instances[n] = null;
delete instances[n];
},
save_opened : function () {
var _this = this;
this.data.core.to_open = [];
this.get_container().find(".jstree-open").each(function () {
_this.data.core.to_open.push("#" + this.id.toString().replace(/^#/,"").replace('\\/','/').replace('/','\\/'));
});
this.__callback(_this.data.core.to_open);
},
reopen : function (is_callback) {
var _this = this,
done = true,
current = [],
remaining = [];
if(!is_callback) { this.data.core.reopen = false; this.data.core.refreshing = true; }
if(this.data.core.to_open.length) {
$.each(this.data.core.to_open, function (i, val) {
if(val == "#") { return true; }
if($(val).length && $(val).is(".jstree-closed")) { current.push(val); }
else { remaining.push(val); }
});
if(current.length) {
this.data.core.to_open = remaining;
$.each(current, function (i, val) {
_this.open_node(val, function () { _this.reopen(true); }, true);
});
done = false;
}
}
if(done) {
// TODO: find a more elegant approach to syncronizing returning requests
if(this.data.core.reopen) { clearTimeout(this.data.core.reopen); }
this.data.core.reopen = setTimeout(function () { _this.__callback({}, _this); }, 50);
this.data.core.refreshing = false;
}
},
refresh : function (obj) {
var _this = this;
this.save_opened();
if(!obj) { obj = -1; }
obj = this._get_node(obj);
if(!obj) { obj = -1; }
if(obj !== -1) { obj.children("UL").remove(); }
this.load_node(obj, function () { _this.__callback({ "obj" : obj}); _this.reopen(); });
},
// Dummy function to fire after the first load (so that there is a jstree.loaded event)
loaded : function () {
this.__callback();
},
// deal with focus
set_focus : function () {
var f = $.jstree._focused();
if(f && f !== this) {
f.get_container().removeClass("jstree-focused");
}
if(f !== this) {
this.get_container().addClass("jstree-focused");
focused_instance = this.get_index();
}
this.__callback();
},
is_focused : function () {
return focused_instance == this.get_index();
},
// traverse
_get_node : function (obj) {
var $obj = $(obj, this.get_container());
if($obj.is(".jstree") || obj == -1) { return -1; }
$obj = $obj.closest("li", this.get_container());
return $obj.length ? $obj : false;
},
_get_next : function (obj, strict) {
obj = this._get_node(obj);
if(obj === -1) { return this.get_container().find("> ul > li:first-child"); }
if(!obj.length) { return false; }
if(strict) { return (obj.nextAll("li").size() > 0) ? obj.nextAll("li:eq(0)") : false; }
if(obj.hasClass("jstree-open")) { return obj.find("li:eq(0)"); }
else if(obj.nextAll("li").size() > 0) { return obj.nextAll("li:eq(0)"); }
else { return obj.parentsUntil(".jstree","li").next("li").eq(0); }
},
_get_prev : function (obj, strict) {
obj = this._get_node(obj);
if(obj === -1) { return this.get_container().find("> ul > li:last-child"); }
if(!obj.length) { return false; }
if(strict) { return (obj.prevAll("li").length > 0) ? obj.prevAll("li:eq(0)") : false; }
if(obj.prev("li").length) {
obj = obj.prev("li").eq(0);
while(obj.hasClass("jstree-open")) { obj = obj.children("ul:eq(0)").children("li:last"); }
return obj;
}
else { var o = obj.parentsUntil(".jstree","li:eq(0)"); return o.length ? o : false; }
},
_get_parent : function (obj) {
obj = this._get_node(obj);
if(obj == -1 || !obj.length) { return false; }
var o = obj.parentsUntil(".jstree", "li:eq(0)");
return o.length ? o : -1;
},
_get_children : function (obj) {
obj = this._get_node(obj);
if(obj === -1) { return this.get_container().children("ul:eq(0)").children("li"); }
if(!obj.length) { return false; }
return obj.children("ul:eq(0)").children("li");
},
get_path : function (obj, id_mode) {
var p = [],
_this = this;
obj = this._get_node(obj);
if(obj === -1 || !obj || !obj.length) { return false; }
obj.parentsUntil(".jstree", "li").each(function () {
p.push( id_mode ? this.id : _this.get_text(this) );
});
p.reverse();
p.push( id_mode ? obj.attr("id") : this.get_text(obj) );
return p;
},
is_open : function (obj) { obj = this._get_node(obj); return obj && obj !== -1 && obj.hasClass("jstree-open"); },
is_closed : function (obj) { obj = this._get_node(obj); return obj && obj !== -1 && obj.hasClass("jstree-closed"); },
is_leaf : function (obj) { obj = this._get_node(obj); return obj && obj !== -1 && obj.hasClass("jstree-leaf"); },
// open/close
open_node : function (obj, callback, skip_animation) {
obj = this._get_node(obj);
if(!obj.length) { return false; }
if(!obj.hasClass("jstree-closed")) { if(callback) { callback.call(); } return false; }
var s = skip_animation || is_ie6 ? 0 : this._get_settings().core.animation,
t = this;
if(!this._is_loaded(obj)) {
obj.children("a").addClass("jstree-loading");
this.load_node(obj, function () { t.open_node(obj, callback, skip_animation); }, callback);
}
else {
if(s) { obj.children("ul").css("display","none"); }
obj.removeClass("jstree-closed").addClass("jstree-open").children("a").removeClass("jstree-loading");
if(s) { obj.children("ul").stop(true).slideDown(s, function () { this.style.display = ""; }); }
this.__callback({ "obj" : obj });
if(callback) { callback.call(); }
}
},
close_node : function (obj, skip_animation) {
obj = this._get_node(obj);
var s = skip_animation || is_ie6 ? 0 : this._get_settings().core.animation;
if(!obj.length || !obj.hasClass("jstree-open")) { return false; }
if(s) { obj.children("ul").attr("style","display:block !important"); }
obj.removeClass("jstree-open").addClass("jstree-closed");
if(s) { obj.children("ul").stop(true).slideUp(s, function () { this.style.display = ""; }); }
this.__callback({ "obj" : obj });
},
toggle_node : function (obj) {
obj = this._get_node(obj);
if(obj.hasClass("jstree-closed")) { return this.open_node(obj); }
if(obj.hasClass("jstree-open")) { return this.close_node(obj); }
},
open_all : function (obj, original_obj) {
obj = obj ? this._get_node(obj) : this.get_container();
if(!obj || obj === -1) { obj = this.get_container(); }
if(original_obj) {
obj = obj.find("li.jstree-closed");
}
else {
original_obj = obj;
if(obj.is(".jstree-closed")) { obj = obj.find("li.jstree-closed").andSelf(); }
else { obj = obj.find("li.jstree-closed"); }
}
var _this = this;
obj.each(function () {
var __this = this;
if(!_this._is_loaded(this)) { _this.open_node(this, function() { _this.open_all(__this, original_obj); }, true); }
else { _this.open_node(this, false, true); }
});
// so that callback is fired AFTER all nodes are open
if(original_obj.find('li.jstree-closed').length === 0) { this.__callback({ "obj" : original_obj }); }
},
close_all : function (obj) {
var _this = this;
obj = obj ? this._get_node(obj) : this.get_container();
if(!obj || obj === -1) { obj = this.get_container(); }
obj.find("li.jstree-open").andSelf().each(function () { _this.close_node(this); });
this.__callback({ "obj" : obj });
},
clean_node : function (obj) {
obj = obj && obj != -1 ? $(obj) : this.get_container();
obj = obj.is("li") ? obj.find("li").andSelf() : obj.find("li");
obj.removeClass("jstree-last")
.filter("li:last-child").addClass("jstree-last").end()
.filter(":has(li)")
.not(".jstree-open").removeClass("jstree-leaf").addClass("jstree-closed");
obj.not(".jstree-open, .jstree-closed").addClass("jstree-leaf").children("ul").remove();
this.__callback({ "obj" : obj });
},
// rollback
get_rollback : function () {
this.__callback();
return { i : this.get_index(), h : this.get_container().children("ul").clone(true), d : this.data };
},
set_rollback : function (html, data) {
this.get_container().empty().append(html);
this.data = data;
this.__callback();
},
// Dummy functions to be overwritten by any datastore plugin included
load_node : function (obj, s_call, e_call) { this.__callback({ "obj" : obj }); },
_is_loaded : function (obj) { return true; },
// Basic operations: create
create_node : function (obj, position, js, callback, is_loaded) {
obj = this._get_node(obj);
position = typeof position === "undefined" ? "last" : position;
var d = $("<li>"),
s = this._get_settings().core,
tmp;
if(obj !== -1 && !obj.length) { return false; }
if(!is_loaded && !this._is_loaded(obj)) { this.load_node(obj, function () { this.create_node(obj, position, js, callback, true); }); return false; }
this.__rollback();
if(typeof js === "string") { js = { "data" : js }; }
if(!js) { js = {}; }
if(js.attr) { d.attr(js.attr); }
if(js.state) { d.addClass("jstree-" + js.state); }
if(!js.data) { js.data = s.strings.new_node; }
if(!$.isArray(js.data)) { tmp = js.data; js.data = []; js.data.push(tmp); }
$.each(js.data, function (i, m) {
tmp = $("<a>");
if($.isFunction(m)) { m = m.call(this, js); }
if(typeof m == "string") { tmp.attr('href','#')[ s.html_titles ? "html" : "text" ](m); }
else {
if(!m.attr) { m.attr = {}; }
if(!m.attr.href) { m.attr.href = '#'; }
tmp.attr(m.attr)[ s.html_titles ? "html" : "text" ](m.title);
if(m.language) { tmp.addClass(m.language); }
}
tmp.prepend("<ins class='jstree-icon'> </ins>");
if(m.icon) {
if(m.icon.indexOf("/") === -1) { tmp.children("ins").addClass(m.icon); }
else { tmp.children("ins").css("background","url('" + m.icon + "') center center no-repeat"); }
}
d.append(tmp);
});
d.prepend("<ins class='jstree-icon'> </ins>");
if(obj === -1) {
obj = this.get_container();
if(position === "before") { position = "first"; }
if(position === "after") { position = "last"; }
}
switch(position) {
case "before": obj.before(d); tmp = this._get_parent(obj); break;
case "after" : obj.after(d); tmp = this._get_parent(obj); break;
case "inside":
case "first" :
if(!obj.children("ul").length) { obj.append("<ul>"); }
obj.children("ul").prepend(d);
tmp = obj;
break;
case "last":
if(!obj.children("ul").length) { obj.append("<ul>"); }
obj.children("ul").append(d);
tmp = obj;
break;
default:
if(!obj.children("ul").length) { obj.append("<ul>"); }
if(!position) { position = 0; }
tmp = obj.children("ul").children("li").eq(position);
if(tmp.length) { tmp.before(d); }
else { obj.children("ul").append(d); }
tmp = obj;
break;
}
if(tmp === -1 || tmp.get(0) === this.get_container().get(0)) { tmp = -1; }
this.clean_node(tmp);
this.__callback({ "obj" : d, "parent" : tmp });
if(callback) { callback.call(this, d); }
return d;
},
// Basic operations: rename (deal with text)
get_text : function (obj) {
obj = this._get_node(obj);
if(!obj.length) { return false; }
var s = this._get_settings().core.html_titles;
obj = obj.children("a:eq(0)");
if(s) {
obj = obj.clone();
obj.children("INS").remove();
return obj.html();
}
else {
obj = obj.contents().filter(function() { return this.nodeType == 3; })[0];
return obj.nodeValue;
}
},
set_text : function (obj, val) {
obj = this._get_node(obj);
if(!obj.length) { return false; }
obj = obj.children("a:eq(0)");
if(this._get_settings().core.html_titles) {
var tmp = obj.children("INS").clone();
obj.html(val).prepend(tmp);
this.__callback({ "obj" : obj, "name" : val });
return true;
}
else {
obj = obj.contents().filter(function() { return this.nodeType == 3; })[0];
this.__callback({ "obj" : obj, "name" : val });
return (obj.nodeValue = val);
}
},
rename_node : function (obj, val) {
obj = this._get_node(obj);
this.__rollback();
if(obj && obj.length && this.set_text.apply(this, Array.prototype.slice.call(arguments))) { this.__callback({ "obj" : obj, "name" : val }); }
},
// Basic operations: deleting nodes
delete_node : function (obj) {
obj = this._get_node(obj);
if(!obj.length) { return false; }
this.__rollback();
var p = this._get_parent(obj), prev = this._get_prev(obj);
obj = obj.remove();
if(p !== -1 && p.find("> ul > li").length === 0) {
p.removeClass("jstree-open jstree-closed").addClass("jstree-leaf");
}
this.clean_node(p);
this.__callback({ "obj" : obj, "prev" : prev });
return obj;
},
prepare_move : function (o, r, pos, cb, is_cb) {
var p = {};
p.ot = $.jstree._reference(p.o) || this;
p.o = p.ot._get_node(o);
p.r = r === - 1 ? -1 : this._get_node(r);
p.p = (typeof p === "undefined") ? "last" : pos; // TODO: move to a setting
if(!is_cb && prepared_move.o && prepared_move.o[0] === p.o[0] && prepared_move.r[0] === p.r[0] && prepared_move.p === p.p) {
this.__callback(prepared_move);
if(cb) { cb.call(this, prepared_move); }
return;
}
p.ot = $.jstree._reference(p.o) || this;
p.rt = r === -1 ? p.ot : $.jstree._reference(p.r) || this;
if(p.r === -1) {
p.cr = -1;
switch(p.p) {
case "first":
case "before":
case "inside":
p.cp = 0;
break;
case "after":
case "last":
p.cp = p.rt.get_container().find(" > ul > li").length;
break;
default:
p.cp = p.p;
break;
}
}
else {
if(!/^(before|after)$/.test(p.p) && !this._is_loaded(p.r)) {
return this.load_node(p.r, function () { this.prepare_move(o, r, pos, cb, true); });
}
switch(p.p) {
case "before":
p.cp = p.r.index();
p.cr = p.rt._get_parent(p.r);
break;
case "after":
p.cp = p.r.index() + 1;
p.cr = p.rt._get_parent(p.r);
break;
case "inside":
case "first":
p.cp = 0;
p.cr = p.r;
break;
case "last":
p.cp = p.r.find(" > ul > li").length;
p.cr = p.r;
break;
default:
p.cp = p.p;
p.cr = p.r;
break;
}
}
p.np = p.cr == -1 ? p.rt.get_container() : p.cr;
p.op = p.ot._get_parent(p.o);
p.or = p.np.find(" > ul > li:nth-child(" + (p.cp + 1) + ")");
prepared_move = p;
this.__callback(prepared_move);
if(cb) { cb.call(this, prepared_move); }
},
check_move : function () {
var obj = prepared_move, ret = true;
if(obj.or[0] === obj.o[0]) { return false; }
obj.o.each(function () {
if(obj.r.parentsUntil(".jstree").andSelf().filter("li").index(this) !== -1) { ret = false; return false; }
});
return ret;
},
move_node : function (obj, ref, position, is_copy, is_prepared, skip_check) {
if(!is_prepared) {
return this.prepare_move(obj, ref, position, function (p) {
this.move_node(p, false, false, is_copy, true, skip_check);
});
}
if(!skip_check && !this.check_move()) { return false; }
this.__rollback();
var o = false;
if(is_copy) {
o = obj.o.clone();
o.find("*[id]").andSelf().each(function () {
if(this.id) { this.id = "copy_" + this.id; }
});
}
else { o = obj.o; }
if(obj.or.length) { obj.or.before(o); }
else {
if(!obj.np.children("ul").length) { $("<ul>").appendTo(obj.np); }
obj.np.children("ul:eq(0)").append(o);
}
try {
obj.ot.clean_node(obj.op);
obj.rt.clean_node(obj.np);
if(!obj.op.find("> ul > li").length) {
obj.op.removeClass("jstree-open jstree-closed").addClass("jstree-leaf").children("ul").remove();
}
} catch (e) { }
if(is_copy) {
prepared_move.cy = true;
prepared_move.oc = o;
}
this.__callback(prepared_move);
return prepared_move;
},
_get_move : function () { return prepared_move; }
}
});
})(jQuery);
//*/
/*
* jsTree ui plugin 1.0
* This plugins handles selecting/deselecting/hovering/dehovering nodes
*/
(function ($) {
$.jstree.plugin("ui", {
__init : function () {
this.data.ui.selected = $();
this.data.ui.last_selected = false;
this.data.ui.hovered = null;
this.data.ui.to_select = this.get_settings().ui.initially_select;
this.get_container()
.delegate("a", "click.jstree", $.proxy(function (event) {
event.preventDefault();
this.select_node(event.currentTarget, true, event);
}, this))
.delegate("a", "mouseenter.jstree", $.proxy(function (event) {
this.hover_node(event.target);
}, this))
.delegate("a", "mouseleave.jstree", $.proxy(function (event) {
this.dehover_node(event.target);
}, this))
.bind("reopen.jstree", $.proxy(function () {
this.reselect();
}, this))
.bind("get_rollback.jstree", $.proxy(function () {
this.dehover_node();
this.save_selected();
}, this))
.bind("set_rollback.jstree", $.proxy(function () {
this.reselect();
}, this))
.bind("close_node.jstree", $.proxy(function (event, data) {
var s = this._get_settings().ui,
obj = this._get_node(data.rslt.obj),
clk = (obj && obj.length) ? obj.children("ul").find(".jstree-clicked") : $(),
_this = this;
if(s.selected_parent_close === false || !clk.length) { return; }
clk.each(function () {
_this.deselect_node(this);
if(s.selected_parent_close === "select_parent") { _this.select_node(obj); }
});
}, this))
.bind("delete_node.jstree", $.proxy(function (event, data) {
var s = this._get_settings().ui.select_prev_on_delete,
obj = this._get_node(data.rslt.obj),
clk = (obj && obj.length) ? obj.find(".jstree-clicked") : [],
_this = this;
clk.each(function () { _this.deselect_node(this); });
if(s && clk.length) { this.select_node(data.rslt.prev); }
}, this))
.bind("move_node.jstree", $.proxy(function (event, data) {
if(data.rslt.cy) {
data.rslt.oc.find(".jstree-clicked").removeClass("jstree-clicked");
}
}, this));
},
defaults : {
select_limit : -1, // 0, 1, 2 ... or -1 for unlimited
select_multiple_modifier : "ctrl", // on, or ctrl, shift, alt
selected_parent_close : "select_parent", // false, "deselect", "select_parent"
select_prev_on_delete : true,
disable_selecting_children : false,
initially_select : []
},
_fn : {
_get_node : function (obj, allow_multiple) {
if(typeof obj === "undefined" || obj === null) { return allow_multiple ? this.data.ui.selected : this.data.ui.last_selected; }
var $obj = $(obj, this.get_container());
if($obj.is(".jstree") || obj == -1) { return -1; }
$obj = $obj.closest("li", this.get_container());
return $obj.length ? $obj : false;
},
save_selected : function () {
var _this = this;
this.data.ui.to_select = [];
this.data.ui.selected.each(function () { _this.data.ui.to_select.push("#" + this.id.toString().replace(/^#/,"").replace('\\/','/').replace('/','\\/')); });
this.__callback(this.data.ui.to_select);
},
reselect : function () {
var _this = this,
s = this.data.ui.to_select;
s = $.map($.makeArray(s), function (n) { return "#" + n.toString().replace(/^#/,"").replace('\\/','/').replace('/','\\/'); });
this.deselect_all();
$.each(s, function (i, val) { if(val && val !== "#") { _this.select_node(val); } });
this.__callback();
},
refresh : function (obj) {
this.save_selected();
return this.__call_old();
},
hover_node : function (obj) {
obj = this._get_node(obj);
if(!obj.length) { return false; }
//if(this.data.ui.hovered && obj.get(0) === this.data.ui.hovered.get(0)) { return; }
if(!obj.hasClass("jstree-hovered")) { this.dehover_node(); }
this.data.ui.hovered = obj.children("a").addClass("jstree-hovered").parent();
this.__callback({ "obj" : obj });
},
dehover_node : function () {
var obj = this.data.ui.hovered, p;
if(!obj || !obj.length) { return false; }
p = obj.children("a").removeClass("jstree-hovered").parent();
if(this.data.ui.hovered[0] === p[0]) { this.data.ui.hovered = null; }
this.__callback({ "obj" : obj });
},
select_node : function (obj, check, e) {
obj = this._get_node(obj);
if(obj == -1 || !obj || !obj.length) { return false; }
var s = this._get_settings().ui,
is_multiple = (s.select_multiple_modifier == "on" || (s.select_multiple_modifier !== false && e && e[s.select_multiple_modifier + "Key"])),
is_selected = this.is_selected(obj),
proceed = true;
if(check) {
if(s.disable_selecting_children && is_multiple && obj.parents("li", this.get_container()).children(".jstree-clicked").length) {
return false;
}
proceed = false;
switch(!0) {
case (is_selected && !is_multiple):
this.deselect_all();
is_selected = false;
proceed = true;
break;
case (!is_selected && !is_multiple):
if(s.select_limit == -1 || s.select_limit > 0) {
this.deselect_all();
proceed = true;
}
break;
case (is_selected && is_multiple):
this.deselect_node(obj);
break;
case (!is_selected && is_multiple):
if(s.select_limit == -1 || this.data.ui.selected.length + 1 <= s.select_limit) {
proceed = true;
}
break;
}
}
if(proceed && !is_selected) {
obj.children("a").addClass("jstree-clicked");
this.data.ui.selected = this.data.ui.selected.add(obj);
this.data.ui.last_selected = obj;
this.__callback({ "obj" : obj });
}
},
deselect_node : function (obj) {
obj = this._get_node(obj);
if(!obj.length) { return false; }
if(this.is_selected(obj)) {
obj.children("a").removeClass("jstree-clicked");
this.data.ui.selected = this.data.ui.selected.not(obj);
if(this.data.ui.last_selected.get(0) === obj.get(0)) { this.data.ui.last_selected = this.data.ui.selected.eq(0); }
this.__callback({ "obj" : obj });
}
},
toggle_select : function (obj) {
obj = this._get_node(obj);
if(!obj.length) { return false; }
if(this.is_selected(obj)) { this.deselect_node(obj); }
else { this.select_node(obj); }
},
is_selected : function (obj) { return this.data.ui.selected.index(this._get_node(obj)) >= 0; },
get_selected : function (context) {
return context ? $(context).find(".jstree-clicked").parent() : this.data.ui.selected;
},
deselect_all : function (context) {
if(context) { $(context).find(".jstree-clicked").removeClass("jstree-clicked"); }
else { this.get_container().find(".jstree-clicked").removeClass("jstree-clicked"); }
this.data.ui.selected = $([]);
this.data.ui.last_selected = false;
this.__callback();
}
}
});
// include the selection plugin by default
$.jstree.defaults.plugins.push("ui");
})(jQuery);
//*/
/*
* jsTree CRRM plugin 1.0
* Handles creating/renaming/removing/moving nodes by user interaction.
*/
(function ($) {
$.jstree.plugin("crrm", {
__init : function () {
this.get_container()
.bind("move_node.jstree", $.proxy(function (e, data) {
if(this._get_settings().crrm.move.open_onmove) {
var t = this;
data.rslt.np.parentsUntil(".jstree").andSelf().filter(".jstree-closed").each(function () {
t.open_node(this, false, true);
});
}
}, this));
},
defaults : {
input_width_limit : 200,
move : {
always_copy : false, // false, true or "multitree"
open_onmove : true,
default_position : "last",
check_move : function (m) { return true; }
}
},
_fn : {
_show_input : function (obj, callback) {
obj = this._get_node(obj);
var rtl = this._get_settings().core.rtl,
w = this._get_settings().crrm.input_width_limit,
w1 = obj.children("ins").width(),
w2 = obj.find("> a:visible > ins").width() * obj.find("> a:visible > ins").length,
t = this.get_text(obj),
h1 = $("<div>", { css : { "position" : "absolute", "top" : "-200px", "left" : (rtl ? "0px" : "-1000px"), "visibility" : "hidden" } }).appendTo("body"),
h2 = obj.css("position","relative").append(
$("<input>", {
"value" : t,
// "size" : t.length,
"css" : {
"padding" : "0",
"border" : "1px solid silver",
"position" : "absolute",
"left" : (rtl ? "auto" : (w1 + w2 + 4) + "px"),
"right" : (rtl ? (w1 + w2 + 4) + "px" : "auto"),
"top" : "0px",
"height" : (this.data.core.li_height - 2) + "px",
"lineHeight" : (this.data.core.li_height - 2) + "px",
"width" : "150px" // will be set a bit further down
},
"blur" : $.proxy(function () {
var i = obj.children("input"),
v = i.val();
if(v === "") { v = t; }
i.remove(); // rollback purposes
this.set_text(obj,t); // rollback purposes
this.rename_node(obj, v);
callback.call(this, obj, v, t);
obj.css("position","");
}, this),
"keyup" : function (event) {
var key = event.keyCode || event.which;
if(key == 27) { this.value = t; this.blur(); return; }
else if(key == 13) { this.blur(); return; }
else {
h2.width(Math.min(h1.text("pW" + this.value).width(),w));
}
}
})
).children("input");
this.set_text(obj, "");
h1.css({
fontFamily : h2.css('fontFamily') || '',
fontSize : h2.css('fontSize') || '',
fontWeight : h2.css('fontWeight') || '',
fontStyle : h2.css('fontStyle') || '',
fontStretch : h2.css('fontStretch') || '',
fontVariant : h2.css('fontVariant') || '',
letterSpacing : h2.css('letterSpacing') || '',
wordSpacing : h2.css('wordSpacing') || ''
});
h2.width(Math.min(h1.text("pW" + h2[0].value).width(),w))[0].select();
},
rename : function (obj) {
obj = this._get_node(obj);
this.__rollback();
var f = this.__callback;
this._show_input(obj, function (obj, new_name, old_name) {
f.call(this, { "obj" : obj, "new_name" : new_name, "old_name" : old_name });
});
},
create : function (obj, position, js, callback, skip_rename) {
var t, _this = this;
obj = this._get_node(obj);
if(!obj) { obj = -1; }
this.__rollback();
t = this.create_node(obj, position, js, function (t) {
var p = this._get_parent(t),
pos = $(t).index();
if(callback) { callback.call(this, t); }
if(p.length && p.hasClass("jstree-closed")) { this.open_node(p, false, true); }
if(!skip_rename) {
this._show_input(t, function (obj, new_name, old_name) {
_this.__callback({ "obj" : obj, "name" : new_name, "parent" : p, "position" : pos });
});
}
else { _this.__callback({ "obj" : t, "name" : this.get_text(t), "parent" : p, "position" : pos }); }
});
return t;
},
remove : function (obj) {
obj = this._get_node(obj, true);
this.__rollback();
this.delete_node(obj);
this.__callback({ "obj" : obj });
},
check_move : function () {
if(!this.__call_old()) { return false; }
var s = this._get_settings().crrm.move;
if(!s.check_move.call(this, this._get_move())) { return false; }
return true;
},
move_node : function (obj, ref, position, is_copy, is_prepared, skip_check) {
var s = this._get_settings().crrm.move;
if(!is_prepared) {
if(!position) { position = s.default_position; }
if(position === "inside" && !s.default_position.match(/^(before|after)$/)) { position = s.default_position; }
return this.__call_old(true, obj, ref, position, is_copy, false, skip_check);
}
// if the move is already prepared
if(s.always_copy === true || (s.always_copy === "multitree" && obj.rt.get_index() !== obj.ot.get_index() )) {
is_copy = true;
}
this.__call_old(true, obj, ref, position, is_copy, true, skip_check);
},
cut : function (obj) {
obj = this._get_node(obj);
this.data.crrm.cp_nodes = false;
this.data.crrm.ct_nodes = false;
if(!obj || !obj.length) { return false; }
this.data.crrm.ct_nodes = obj;
},
copy : function (obj) {
obj = this._get_node(obj);
this.data.crrm.cp_nodes = false;
this.data.crrm.ct_nodes = false;
if(!obj || !obj.length) { return false; }
this.data.crrm.cp_nodes = obj;
},
paste : function (obj) {
obj = this._get_node(obj);
if(!obj || !obj.length) { return false; }
if(!this.data.crrm.ct_nodes && !this.data.crrm.cp_nodes) { return false; }
if(this.data.crrm.ct_nodes) { this.move_node(this.data.crrm.ct_nodes, obj); }
if(this.data.crrm.cp_nodes) { this.move_node(this.data.crrm.cp_nodes, obj, false, true); }
this.data.crrm.cp_nodes = false;
this.data.crrm.ct_nodes = false;
}
}
});
// include the crr plugin by default
$.jstree.defaults.plugins.push("crrm");
})(jQuery);
/*
* jsTree themes plugin 1.0
* Handles loading and setting themes, as well as detecting path to themes, etc.
*/
(function ($) {
var themes_loaded = [];
// this variable stores the path to the themes folder - if left as false - it will be autodetected
$.jstree._themes = false;
$.jstree.plugin("themes", {
__init : function () {
this.get_container()
.bind("init.jstree", $.proxy(function () {
var s = this._get_settings().themes;
this.data.themes.dots = s.dots;
this.data.themes.icons = s.icons;
//alert(s.dots);
this.set_theme(s.theme, s.url);
}, this))
.bind("loaded.jstree", $.proxy(function () {
// bound here too, as simple HTML tree's won't honor dots & icons otherwise
if(!this.data.themes.dots) { this.hide_dots(); }
else { this.show_dots(); }
if(!this.data.themes.icons) { this.hide_icons(); }
else { this.show_icons(); }
}, this));
},
defaults : {
theme : "default",
url : false,
dots : true,
icons : true
},
_fn : {
set_theme : function (theme_name, theme_url) {
if(!theme_name) { return false; }
if(!theme_url) { theme_url = $.jstree._themes + theme_name + '/style.css'; }
if($.inArray(theme_url, themes_loaded) == -1) {
$.vakata.css.add_sheet({ "url" : theme_url, "rel" : "jstree" });
themes_loaded.push(theme_url);
}
if(this.data.themes.theme != theme_name) {
this.get_container().removeClass('jstree-' + this.data.themes.theme);
this.data.themes.theme = theme_name;
}
this.get_container().addClass('jstree-' + theme_name);
if(!this.data.themes.dots) { this.hide_dots(); }
else { this.show_dots(); }
if(!this.data.themes.icons) { this.hide_icons(); }
else { this.show_icons(); }
this.__callback();
},
get_theme : function () { return this.data.themes.theme; },
show_dots : function () { this.data.themes.dots = true; this.get_container().children("ul").removeClass("jstree-no-dots"); },
hide_dots : function () { this.data.themes.dots = false; this.get_container().children("ul").addClass("jstree-no-dots"); },
toggle_dots : function () { if(this.data.themes.dots) { this.hide_dots(); } else { this.show_dots(); } },
show_icons : function () { this.data.themes.icons = true; this.get_container().children("ul").removeClass("jstree-no-icons"); },
hide_icons : function () { this.data.themes.icons = false; this.get_container().children("ul").addClass("jstree-no-icons"); },
toggle_icons: function () { if(this.data.themes.icons) { this.hide_icons(); } else { this.show_icons(); } }
}
});
// autodetect themes path
$(function () {
if($.jstree._themes === false) {
$("script").each(function () {
if(this.src.toString().match(/jquery\.jstree[^\/]*?\.js(\?.*)?$/)) {
$.jstree._themes = this.src.toString().replace(/jquery\.jstree[^\/]*?\.js(\?.*)?$/, "") + 'themes/';
return false;
}
});
}
if($.jstree._themes === false) { $.jstree._themes = "themes/"; }
});
// include the themes plugin by default
$.jstree.defaults.plugins.push("themes");
})(jQuery);
//*/
/*
* jsTree hotkeys plugin 1.0
* Enables keyboard navigation for all tree instances
* Depends on the jstree ui & jquery hotkeys plugins
*/
(function ($) {
var bound = [];
function exec(i, event) {
var f = $.jstree._focused(), tmp;
if(f && f.data && f.data.hotkeys && f.data.hotkeys.enabled) {
tmp = f._get_settings().hotkeys[i];
if(tmp) { return tmp.call(f, event); }
}
}
$.jstree.plugin("hotkeys", {
__init : function () {
if(typeof $.hotkeys === "undefined") { throw "jsTree hotkeys: jQuery hotkeys plugin not included."; }
if(!this.data.ui) { throw "jsTree hotkeys: jsTree UI plugin not included."; }
$.each(this._get_settings().hotkeys, function (i, val) {
if($.inArray(i, bound) == -1) {
$(document).bind("keydown", i, function (event) { return exec(i, event); });
bound.push(i);
}
});
this.enable_hotkeys();
},
defaults : {
"up" : function () {
var o = this.data.ui.hovered || this.data.ui.last_selected || -1;
this.hover_node(this._get_prev(o));
return false;
},
"down" : function () {
var o = this.data.ui.hovered || this.data.ui.last_selected || -1;
this.hover_node(this._get_next(o));
return false;
},
"left" : function () {
var o = this.data.ui.hovered || this.data.ui.last_selected;
if(o) {
if(o.hasClass("jstree-open")) { this.close_node(o); }
else { this.hover_node(this._get_prev(o)); }
}
return false;
},
"right" : function () {
var o = this.data.ui.hovered || this.data.ui.last_selected;
if(o && o.length) {
if(o.hasClass("jstree-closed")) { this.open_node(o); }
else { this.hover_node(this._get_next(o)); }
}
return false;
},
"space" : function () {
if(this.data.ui.hovered) { this.data.ui.hovered.children("a:eq(0)").click(); }
return false;
},
"ctrl+space" : function (event) {
event.type = "click";
if(this.data.ui.hovered) { this.data.ui.hovered.children("a:eq(0)").trigger(event); }
return false;
},
"f2" : function () { this.rename(this.data.ui.hovered || this.data.ui.last_selected); },
"del" : function () { this.remove(this.data.ui.hovered || this._get_node(null)); }
},
_fn : {
enable_hotkeys : function () {
this.data.hotkeys.enabled = true;
},
disable_hotkeys : function () {
this.data.hotkeys.enabled = false;
}
}
});
})(jQuery);
//*/
/*
* jsTree JSON 1.0
* The JSON data store. Datastores are build by overriding the `load_node` and `_is_loaded` functions.
*/
(function ($) {
$.jstree.plugin("json_data", {
defaults : {
data : false,
ajax : false,
correct_state : true,
progressive_render : false
},
_fn : {
load_node : function (obj, s_call, e_call) { var _this = this; this.load_node_json(obj, function () { _this.__callback({ "obj" : obj }); s_call.call(this); }, e_call); },
_is_loaded : function (obj) {
var s = this._get_settings().json_data, d;
obj = this._get_node(obj);
if(obj && obj !== -1 && s.progressive_render && !obj.is(".jstree-open, .jstree-leaf") && obj.children("ul").children("li").length === 0 && obj.data("jstree-children")) {
d = this._parse_json(obj.data("jstree-children"));
if(d) {
obj.append(d);
$.removeData(obj, "jstree-children");
}
this.clean_node(obj);
return true;
}
return obj == -1 || !obj || !s.ajax || obj.is(".jstree-open, .jstree-leaf") || obj.children("ul").children("li").size() > 0;
},
load_node_json : function (obj, s_call, e_call) {
var s = this.get_settings().json_data, d,
error_func = function () {},
success_func = function () {};
obj = this._get_node(obj);
if(obj && obj !== -1) {
if(obj.data("jstree-is-loading")) { return; }
else { obj.data("jstree-is-loading",true); }
}
switch(!0) {
case (!s.data && !s.ajax): throw "Neither data nor ajax settings supplied.";
case (!!s.data && !s.ajax) || (!!s.data && !!s.ajax && (!obj || obj === -1)):
if(!obj || obj == -1) {
d = this._parse_json(s.data);
if(d) {
this.get_container().children("ul").empty().append(d.children());
this.clean_node();
}
else {
if(s.correct_state) { this.get_container().children("ul").empty(); }
}
}
if(s_call) { s_call.call(this); }
break;
case (!s.data && !!s.ajax) || (!!s.data && !!s.ajax && obj && obj !== -1):
error_func = function (x, t, e) {
var ef = this.get_settings().json_data.ajax.error;
if(ef) { ef.call(this, x, t, e); }
if(obj != -1 && obj.length) {
obj.children(".jstree-loading").removeClass("jstree-loading");
obj.data("jstree-is-loading",false);
if(t === "success" && s.correct_state) { obj.removeClass("jstree-open jstree-closed").addClass("jstree-leaf"); }
}
else {
if(t === "success" && s.correct_state) { this.get_container().children("ul").empty(); }
}
if(e_call) { e_call.call(this); }
};
success_func = function (d, t, x) {
var sf = this.get_settings().json_data.ajax.success;
if(sf) { d = sf.call(this,d,t,x) || d; }
if(d === "" || (!$.isArray(d) && !$.isPlainObject(d))) {
return error_func.call(this, x, t, "");
}
d = this._parse_json(d);
if(d) {
if(obj === -1 || !obj) { this.get_container().children("ul").empty().append(d.children()); }
else { obj.append(d).children(".jstree-loading").removeClass("jstree-loading"); obj.data("jstree-is-loading",false); }
this.clean_node(obj);
if(s_call) { s_call.call(this); }
}
else {
if(obj === -1 || !obj) {
if(s.correct_state) {
this.get_container().children("ul").empty();
if(s_call) { s_call.call(this); }
}
}
else {
obj.children(".jstree-loading").removeClass("jstree-loading");
obj.data("jstree-is-loading",false);
if(s.correct_state) {
obj.removeClass("jstree-open jstree-closed").addClass("jstree-leaf");
if(s_call) { s_call.call(this); }
}
}
}
};
s.ajax.context = this;
s.ajax.error = error_func;
s.ajax.success = success_func;
if(!s.ajax.dataType) { s.ajax.dataType = "json"; }
if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, obj); }
if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, obj); }
$.ajax(s.ajax);
break;
}
},
_parse_json : function (js, is_callback) {
var d = false,
p = this._get_settings(),
s = p.json_data,
t = p.core.html_titles,
tmp, i, j, ul1, ul2;
if(!js) { return d; }
if($.isFunction(js)) {
js = js.call(this);
}
if($.isArray(js)) {
d = $();
if(!js.length) { return false; }
for(i = 0, j = js.length; i < j; i++) {
tmp = this._parse_json(js[i], true);
if(tmp.length) { d = d.add(tmp); }
}
}
else {
if(typeof js == "string") { js = { data : js }; }
if(!js.data && js.data !== "") { return d; }
d = $("<li>");
if(js.attr) { d.attr(js.attr); }
if(js.metadata) { d.data("jstree", js.metadata); }
if(js.state) { d.addClass("jstree-" + js.state); }
if(!$.isArray(js.data)) { tmp = js.data; js.data = []; js.data.push(tmp); }
$.each(js.data, function (i, m) {
tmp = $("<a>");
if($.isFunction(m)) { m = m.call(this, js); }
if(typeof m == "string") { tmp.attr('href','#')[ t ? "html" : "text" ](m); }
else {
if(!m.attr) { m.attr = {}; }
if(!m.attr.href) { m.attr.href = '#'; }
tmp.attr(m.attr)[ t ? "html" : "text" ](m.title);
if(m.language) { tmp.addClass(m.language); }
}
tmp.prepend("<ins class='jstree-icon'> </ins>");
if(!m.icon && js.icon) { m.icon = js.icon; }
if(m.icon) {
if(m.icon.indexOf("/") === -1) { tmp.children("ins").addClass(m.icon); }
else { tmp.children("ins").css("background","url('" + m.icon + "') center center no-repeat"); }
}
d.append(tmp);
});
d.prepend("<ins class='jstree-icon'> </ins>");
if(js.children) {
if(s.progressive_render && js.state !== "open") {
d.addClass("jstree-closed").data("jstree-children", js.children);
}
else {
if($.isFunction(js.children)) {
js.children = js.children.call(this, js);
}
if($.isArray(js.children) && js.children.length) {
tmp = this._parse_json(js.children, true);
if(tmp.length) {
ul2 = $("<ul>");
ul2.append(tmp);
d.append(ul2);
}
}
}
}
}
if(!is_callback) {
ul1 = $("<ul>");
ul1.append(d);
d = ul1;
}
return d;
},
get_json : function (obj, li_attr, a_attr, is_callback) {
var result = [],
s = this._get_settings(),
_this = this,
tmp1, tmp2, li, a, t, lang;
obj = this._get_node(obj);
if(!obj || obj === -1) { obj = this.get_container().find("> ul > li"); }
li_attr = $.isArray(li_attr) ? li_attr : [ "id", "class" ];
if(!is_callback && this.data.types) { li_attr.push(s.types.type_attr); }
a_attr = $.isArray(a_attr) ? a_attr : [ ];
obj.each(function () {
li = $(this);
tmp1 = { data : [] };
if(li_attr.length) { tmp1.attr = { }; }
$.each(li_attr, function (i, v) {
tmp2 = li.attr(v);
if(tmp2 && tmp2.length && tmp2.replace(/jstree[^ ]*|$/ig,'').length) {
tmp1.attr[v] = tmp2.replace(/jstree[^ ]*|$/ig,'');
}
});
if(li.hasClass("jstree-open")) { tmp1.state = "open"; }
if(li.hasClass("jstree-closed")) { tmp1.state = "closed"; }
a = li.children("a");
a.each(function () {
t = $(this);
if(
a_attr.length ||
$.inArray("languages", s.plugins) !== -1 ||
t.children("ins").get(0).style.backgroundImage.length ||
(t.children("ins").get(0).className && t.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').length)
) {
lang = false;
if($.inArray("languages", s.plugins) !== -1 && $.isArray(s.languages) && s.languages.length) {
$.each(s.languages, function (l, lv) {
if(t.hasClass(lv)) {
lang = lv;
return false;
}
});
}
tmp2 = { attr : { }, title : _this.get_text(t, lang) };
$.each(a_attr, function (k, z) {
tmp1.attr[z] = (t.attr(z) || "").replace(/jstree[^ ]*|$/ig,'');
});
$.each(s.languages, function (k, z) {
if(t.hasClass(z)) { tmp2.language = z; return true; }
});
if(t.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/^\s+$/ig,"").length) {
tmp2.icon = t.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/^\s+$/ig,"");
}
if(t.children("ins").get(0).style.backgroundImage.length) {
tmp2.icon = t.children("ins").get(0).style.backgroundImage.replace("url(","").replace(")","");
}
}
else {
tmp2 = _this.get_text(t);
}
if(a.length > 1) { tmp1.data.push(tmp2); }
else { tmp1.data = tmp2; }
});
li = li.find("> ul > li");
if(li.length) { tmp1.children = _this.get_json(li, li_attr, a_attr, true); }
result.push(tmp1);
});
return result;
}
}
});
})(jQuery);
//*/
/*
* jsTree languages plugin 1.0
* Adds support for multiple language versions in one tree
* This basically allows for many titles coexisting in one node, but only one of them being visible at any given time
* This is useful for maintaining the same structure in many languages (hence the name of the plugin)
*/
(function ($) {
$.jstree.plugin("languages", {
__init : function () { this._load_css(); },
defaults : [],
_fn : {
set_lang : function (i) {
var langs = this._get_settings().languages,
st = false,
selector = ".jstree-" + this.get_index() + ' a';
if(!$.isArray(langs) || langs.length === 0) { return false; }
if($.inArray(i,langs) == -1) {
if(!!langs[i]) { i = langs[i]; }
else { return false; }
}
if(i == this.data.languages.current_language) { return true; }
st = $.vakata.css.get_css(selector + "." + this.data.languages.current_language, false, this.data.languages.language_css);
if(st !== false) { st.style.display = "none"; }
st = $.vakata.css.get_css(selector + "." + i, false, this.data.languages.language_css);
if(st !== false) { st.style.display = ""; }
this.data.languages.current_language = i;
this.__callback(i);
return true;
},
get_lang : function () {
return this.data.languages.current_language;
},
get_text : function (obj, lang) {
obj = this._get_node(obj) || this.data.ui.last_selected;
if(!obj.size()) { return false; }
var langs = this._get_settings().languages,
s = this._get_settings().core.html_titles;
if($.isArray(langs) && langs.length) {
lang = (lang && $.inArray(lang,langs) != -1) ? lang : this.data.languages.current_language;
obj = obj.children("a." + lang);
}
else { obj = obj.children("a:eq(0)"); }
if(s) {
obj = obj.clone();
obj.children("INS").remove();
return obj.html();
}
else {
obj = obj.contents().filter(function() { return this.nodeType == 3; })[0];
return obj.nodeValue;
}
},
set_text : function (obj, val, lang) {
obj = this._get_node(obj) || this.data.ui.last_selected;
if(!obj.size()) { return false; }
var langs = this._get_settings().languages,
s = this._get_settings().core.html_titles,
tmp;
if($.isArray(langs) && langs.length) {
lang = (lang && $.inArray(lang,langs) != -1) ? lang : this.data.languages.current_language;
obj = obj.children("a." + lang);
}
else { obj = obj.children("a:eq(0)"); }
if(s) {
tmp = obj.children("INS").clone();
obj.html(val).prepend(tmp);
this.__callback({ "obj" : obj, "name" : val, "lang" : lang });
return true;
}
else {
obj = obj.contents().filter(function() { return this.nodeType == 3; })[0];
this.__callback({ "obj" : obj, "name" : val, "lang" : lang });
return (obj.nodeValue = val);
}
},
_load_css : function () {
var langs = this._get_settings().languages,
str = "/* languages css */",
selector = ".jstree-" + this.get_index() + ' a',
ln;
if($.isArray(langs) && langs.length) {
this.data.languages.current_language = langs[0];
for(ln = 0; ln < langs.length; ln++) {
str += selector + "." + langs[ln] + " {";
if(langs[ln] != this.data.languages.current_language) { str += " display:none; "; }
str += " } ";
}
this.data.languages.language_css = $.vakata.css.add_sheet({ 'str' : str });
}
},
create_node : function (obj, position, js, callback) {
var t = this.__call_old(true, obj, position, js, function (t) {
var langs = this._get_settings().languages,
a = t.children("a"),
ln;
if($.isArray(langs) && langs.length) {
for(ln = 0; ln < langs.length; ln++) {
if(!a.is("." + langs[ln])) {
t.append(a.eq(0).clone().removeClass(langs.join(" ")).addClass(langs[ln]));
}
}
a.not("." + langs.join(", .")).remove();
}
if(callback) { callback.call(this, t); }
});
return t;
}
}
});
})(jQuery);
//*/
/*
* jsTree cookies plugin 1.0
* Stores the currently opened/selected nodes in a cookie and then restores them
* Depends on the jquery.cookie plugin
*/
(function ($) {
$.jstree.plugin("cookies", {
__init : function () {
if(typeof $.cookie === "undefined") { throw "jsTree cookie: jQuery cookie plugin not included."; }
var s = this._get_settings().cookies,
tmp;
if(!!s.save_opened) {
tmp = $.cookie(s.save_opened);
if(tmp && tmp.length) { this.data.core.to_open = tmp.split(","); }
}
if(!!s.save_selected) {
tmp = $.cookie(s.save_selected);
if(tmp && tmp.length && this.data.ui) { this.data.ui.to_select = tmp.split(","); }
}
this.get_container()
.one( ( this.data.ui ? "reselect" : "reopen" ) + ".jstree", $.proxy(function () {
this.get_container()
.bind("open_node.jstree close_node.jstree select_node.jstree deselect_node.jstree", $.proxy(function (e) {
if(this._get_settings().cookies.auto_save) { this.save_cookie((e.handleObj.namespace + e.handleObj.type).replace("jstree","")); }
}, this));
}, this));
},
defaults : {
save_opened : "jstree_open",
save_selected : "jstree_select",
auto_save : true,
cookie_options : {}
},
_fn : {
save_cookie : function (c) {
if(this.data.core.refreshing) { return; }
var s = this._get_settings().cookies;
if(!c) { // if called manually and not by event
if(s.save_opened) {
this.save_opened();
$.cookie(s.save_opened, this.data.core.to_open.join(","), s.cookie_options);
}
if(s.save_selected && this.data.ui) {
this.save_selected();
$.cookie(s.save_selected, this.data.ui.to_select.join(","), s.cookie_options);
}
return;
}
switch(c) {
case "open_node":
case "close_node":
if(!!s.save_opened) {
this.save_opened();
$.cookie(s.save_opened, this.data.core.to_open.join(","), s.cookie_options);
}
break;
case "select_node":
case "deselect_node":
if(!!s.save_selected && this.data.ui) {
this.save_selected();
$.cookie(s.save_selected, this.data.ui.to_select.join(","), s.cookie_options);
}
break;
}
}
}
});
// include cookies by default
$.jstree.defaults.plugins.push("cookies");
})(jQuery);
//*/
/*
* jsTree sort plugin 1.0
* Sorts items alphabetically (or using any other function)
*/
(function ($) {
$.jstree.plugin("sort", {
__init : function () {
this.get_container()
.bind("load_node.jstree", $.proxy(function (e, data) {
var obj = this._get_node(data.rslt.obj);
obj = obj === -1 ? this.get_container().children("ul") : obj.children("ul");
this.sort(obj);
}, this))
.bind("rename_node.jstree", $.proxy(function (e, data) {
this.sort(data.rslt.obj.parent());
}, this))
.bind("move_node.jstree", $.proxy(function (e, data) {
var m = data.rslt.np == -1 ? this.get_container() : data.rslt.np;
this.sort(m.children("ul"));
}, this));
},
defaults : function (a, b) { return this.get_text(a) > this.get_text(b) ? 1 : -1; },
_fn : {
sort : function (obj) {
var s = this._get_settings().sort,
t = this;
obj.append($.makeArray(obj.children("li")).sort($.proxy(s, t)));
obj.find("> li > ul").each(function() { t.sort($(this)); });
this.clean_node(obj);
}
}
});
})(jQuery);
//*/
/*
* jsTree DND plugin 1.0
* Drag and drop plugin for moving/copying nodes
*/
(function ($) {
var o = false,
r = false,
m = false,
sli = false,
sti = false,
dir1 = false,
dir2 = false;
$.vakata.dnd = {
is_down : false,
is_drag : false,
helper : false,
scroll_spd : 10,
init_x : 0,
init_y : 0,
threshold : 5,
user_data : {},
drag_start : function (e, data, html) {
if($.vakata.dnd.is_drag) { $.vakata.drag_stop({}); }
try {
e.currentTarget.unselectable = "on";
e.currentTarget.onselectstart = function() { return false; };
if(e.currentTarget.style) { e.currentTarget.style.MozUserSelect = "none"; }
} catch(err) { }
$.vakata.dnd.init_x = e.pageX;
$.vakata.dnd.init_y = e.pageY;
$.vakata.dnd.user_data = data;
$.vakata.dnd.is_down = true;
$.vakata.dnd.helper = $("<div id='vakata-dragged'>").html(html).css("opacity", "0.75");
$(document).bind("mousemove", $.vakata.dnd.drag);
$(document).bind("mouseup", $.vakata.dnd.drag_stop);
return false;
},
drag : function (e) {
if(!$.vakata.dnd.is_down) { return; }
if(!$.vakata.dnd.is_drag) {
if(Math.abs(e.pageX - $.vakata.dnd.init_x) > 5 || Math.abs(e.pageY - $.vakata.dnd.init_y) > 5) {
$.vakata.dnd.helper.appendTo("body");
$.vakata.dnd.is_drag = true;
$(document).triggerHandler("drag_start.vakata", { "event" : e, "data" : $.vakata.dnd.user_data });
}
else { return; }
}
// maybe use a scrolling parent element instead of document?
if(e.type === "mousemove") { // thought of adding scroll in order to move the helper, but mouse poisition is n/a
var d = $(document), t = d.scrollTop(), l = d.scrollLeft();
if(e.pageY - t < 20) {
if(sti && dir1 === "down") { clearInterval(sti); sti = false; }
if(!sti) { dir1 = "up"; sti = setInterval(function () { $(document).scrollTop($(document).scrollTop() - $.vakata.dnd.scroll_spd); }, 150); }
}
else {
if(sti && dir1 === "up") { clearInterval(sti); sti = false; }
}
if($(window).height() - (e.pageY - t) < 20) {
if(sti && dir1 === "up") { clearInterval(sti); sti = false; }
if(!sti) { dir1 = "down"; sti = setInterval(function () { $(document).scrollTop($(document).scrollTop() + $.vakata.dnd.scroll_spd); }, 150); }
}
else {
if(sti && dir1 === "down") { clearInterval(sti); sti = false; }
}
if(e.pageX - l < 20) {
if(sli && dir2 === "right") { clearInterval(sli); sli = false; }
if(!sli) { dir2 = "left"; sli = setInterval(function () { $(document).scrollLeft($(document).scrollLeft() - $.vakata.dnd.scroll_spd); }, 150); }
}
else {
if(sli && dir2 === "left") { clearInterval(sli); sli = false; }
}
if($(window).width() - (e.pageX - l) < 20) {
if(sli && dir2 === "left") { clearInterval(sli); sli = false; }
if(!sli) { dir2 = "right"; sli = setInterval(function () { $(document).scrollLeft($(document).scrollLeft() + $.vakata.dnd.scroll_spd); }, 150); }
}
else {
if(sli && dir2 === "right") { clearInterval(sli); sli = false; }
}
}
$.vakata.dnd.helper.css({ left : (e.pageX + 5) + "px", top : (e.pageY + 10) + "px" });
$(document).triggerHandler("drag.vakata", { "event" : e, "data" : $.vakata.dnd.user_data });
},
drag_stop : function (e) {
$(document).unbind("mousemove", $.vakata.dnd.drag);
$(document).unbind("mouseup", $.vakata.dnd.drag_stop);
$(document).triggerHandler("drag_stop.vakata", { "event" : e, "data" : $.vakata.dnd.user_data });
$.vakata.dnd.helper.remove();
$.vakata.dnd.init_x = 0;
$.vakata.dnd.init_y = 0;
$.vakata.dnd.user_data = {};
$.vakata.dnd.is_down = false;
$.vakata.dnd.is_drag = false;
}
};
$(function() {
var css_string = '#vakata-dragged { display:block; margin:0 0 0 0; padding:4px 4px 4px 24px; position:absolute; top:-2000px; line-height:16px; z-index:10000; } ';
$.vakata.css.add_sheet({ str : css_string });
});
$.jstree.plugin("dnd", {
__init : function () {
this.data.dnd = {
active : false,
after : false,
inside : false,
before : false,
off : false,
prepared : false,
w : 0,
to1 : false,
to2 : false,
cof : false,
cw : false,
ch : false,
i1 : false,
i2 : false
};
this.get_container()
.bind("mouseenter.jstree", $.proxy(function () {
if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree && this.data.themes) {
m.attr("class", "jstree-" + this.data.themes.theme);
$.vakata.dnd.helper.attr("class", "jstree-dnd-helper jstree-" + this.data.themes.theme);
}
}, this))
.bind("mouseleave.jstree", $.proxy(function () {
if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); }
if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); }
}
}, this))
.bind("mousemove.jstree", $.proxy(function (e) {
if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
var cnt = this.get_container()[0];
// Horizontal scroll
if(e.pageX + 24 > this.data.dnd.cof.left + this.data.dnd.cw) {
if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); }
this.data.dnd.i1 = setInterval($.proxy(function () { this.scrollLeft += $.vakata.dnd.scroll_spd; }, cnt), 100);
}
else if(e.pageX - 24 < this.data.dnd.cof.left) {
if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); }
this.data.dnd.i1 = setInterval($.proxy(function () { this.scrollLeft -= $.vakata.dnd.scroll_spd; }, cnt), 100);
}
else {
if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); }
}
// Vertical scroll
if(e.pageY + 24 > this.data.dnd.cof.top + this.data.dnd.ch) {
if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); }
this.data.dnd.i2 = setInterval($.proxy(function () { this.scrollTop += $.vakata.dnd.scroll_spd; }, cnt), 100);
}
else if(e.pageY - 24 < this.data.dnd.cof.top) {
if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); }
this.data.dnd.i2 = setInterval($.proxy(function () { this.scrollTop -= $.vakata.dnd.scroll_spd; }, cnt), 100);
}
else {
if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); }
}
}
}, this))
.delegate("a", "mousedown.jstree", $.proxy(function (e) {
if(e.which === 1) {
this.start_drag(e.currentTarget, e);
return false;
}
}, this))
.delegate("a", "mouseenter.jstree", $.proxy(function (e) {
if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
this.dnd_enter(e.currentTarget);
}
}, this))
.delegate("a", "mousemove.jstree", $.proxy(function (e) {
if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
if(typeof this.data.dnd.off.top === "undefined") { this.data.dnd.off = $(e.target).offset(); }
this.data.dnd.w = (e.pageY - (this.data.dnd.off.top || 0)) % this.data.core.li_height;
if(this.data.dnd.w < 0) { this.data.dnd.w += this.data.core.li_height; }
this.dnd_show();
}
}, this))
.delegate("a", "mouseleave.jstree", $.proxy(function (e) {
if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
this.data.dnd.after = false;
this.data.dnd.before = false;
this.data.dnd.inside = false;
$.vakata.dnd.helper.children("ins").attr("class","jstree-invalid");
m.hide();
if(r && r[0] === e.target.parentNode) {
if(this.data.dnd.to1) {
clearTimeout(this.data.dnd.to1);
this.data.dnd.to1 = false;
}
if(this.data.dnd.to2) {
clearTimeout(this.data.dnd.to2);
this.data.dnd.to2 = false;
}
}
}
}, this))
.delegate("a", "mouseup.jstree", $.proxy(function (e) {
if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
this.dnd_finish(e);
}
}, this));
$(document)
.bind("drag_stop.vakata", $.proxy(function () {
this.data.dnd.after = false;
this.data.dnd.before = false;
this.data.dnd.inside = false;
this.data.dnd.off = false;
this.data.dnd.prepared = false;
this.data.dnd.w = false;
this.data.dnd.to1 = false;
this.data.dnd.to2 = false;
this.data.dnd.active = false;
this.data.dnd.foreign = false;
if(m) { m.css({ "top" : "-2000px" }); }
}, this))
.bind("drag_start.vakata", $.proxy(function (e, data) {
if(data.data.jstree) {
var et = $(data.event.target);
if(et.closest(".jstree").hasClass("jstree-" + this.get_index())) {
this.dnd_enter(et);
}
}
}, this));
var s = this._get_settings().dnd;
if(s.drag_target) {
$(document)
.delegate(s.drag_target, "mousedown.jstree", $.proxy(function (e) {
o = e.target;
$.vakata.dnd.drag_start(e, { jstree : true, obj : e.target }, "<ins class='jstree-icon'></ins>" + $(e.target).text() );
if(this.data.themes) {
m.attr("class", "jstree-" + this.data.themes.theme);
$.vakata.dnd.helper.attr("class", "jstree-dnd-helper jstree-" + this.data.themes.theme);
}
$.vakata.dnd.helper.children("ins").attr("class","jstree-invalid");
var cnt = this.get_container();
this.data.dnd.cof = cnt.offset();
this.data.dnd.cw = parseInt(cnt.width(),10);
this.data.dnd.ch = parseInt(cnt.height(),10);
this.data.dnd.foreign = true;
return false;
}, this));
}
if(s.drop_target) {
$(document)
.delegate(s.drop_target, "mouseenter.jstree", $.proxy(function (e) {
if(this.data.dnd.active && this._get_settings().dnd.drop_check.call(this, { "o" : o, "r" : $(e.target) })) {
$.vakata.dnd.helper.children("ins").attr("class","jstree-ok");
}
}, this))
.delegate(s.drop_target, "mouseleave.jstree", $.proxy(function (e) {
if(this.data.dnd.active) {
$.vakata.dnd.helper.children("ins").attr("class","jstree-invalid");
}
}, this))
.delegate(s.drop_target, "mouseup.jstree", $.proxy(function (e) {
if(this.data.dnd.active && $.vakata.dnd.helper.children("ins").hasClass("jstree-ok")) {
this._get_settings().dnd.drop_finish.call(this, { "o" : o, "r" : $(e.target) });
}
}, this));
}
},
defaults : {
copy_modifier : "ctrl",
check_timeout : 200,
open_timeout : 500,
drop_target : ".jstree-drop",
drop_check : function (data) { return true; },
drop_finish : $.noop,
drag_target : ".jstree-draggable",
drag_finish : $.noop,
drag_check : function (data) { return { after : false, before : false, inside : true }; }
},
_fn : {
dnd_prepare : function () {
if(!r || !r.length) { return; }
this.data.dnd.off = r.offset();
if(this._get_settings().core.rtl) {
this.data.dnd.off.right = this.data.dnd.off.left + r.width();
}
if(this.data.dnd.foreign) {
var a = this._get_settings().dnd.drag_check.call(this, { "o" : o, "r" : r });
this.data.dnd.after = a.after;
this.data.dnd.before = a.before;
this.data.dnd.inside = a.inside;
this.data.dnd.prepared = true;
return this.dnd_show();
}
this.prepare_move(o, r, "before");
this.data.dnd.before = this.check_move();
this.prepare_move(o, r, "after");
this.data.dnd.after = this.check_move();
if(this._is_loaded(r)) {
this.prepare_move(o, r, "inside");
this.data.dnd.inside = this.check_move();
}
else {
this.data.dnd.inside = false;
}
this.data.dnd.prepared = true;
return this.dnd_show();
},
dnd_show : function () {
if(!this.data.dnd.prepared) { return; }
var o = ["before","inside","after"],
r = false,
rtl = this._get_settings().core.rtl,
pos;
if(this.data.dnd.w < this.data.core.li_height/3) { o = ["before","inside","after"]; }
else if(this.data.dnd.w <= this.data.core.li_height*2/3) {
o = this.data.dnd.w < this.data.core.li_height/2 ? ["inside","before","after"] : ["inside","after","before"];
}
else { o = ["after","inside","before"]; }
$.each(o, $.proxy(function (i, val) {
if(this.data.dnd[val]) {
$.vakata.dnd.helper.children("ins").attr("class","jstree-ok");
r = val;
return false;
}
}, this));
if(r === false) { $.vakata.dnd.helper.children("ins").attr("class","jstree-invalid"); }
pos = rtl ? (this.data.dnd.off.right - 18) : (this.data.dnd.off.left + 10);
switch(r) {
case "before":
m.css({ "left" : pos + "px", "top" : (this.data.dnd.off.top - 6) + "px" }).show();
break;
case "after":
m.css({ "left" : pos + "px", "top" : (this.data.dnd.off.top + this.data.core.li_height - 7) + "px" }).show();
break;
case "inside":
m.css({ "left" : pos + ( rtl ? -4 : 4) + "px", "top" : (this.data.dnd.off.top + this.data.core.li_height/2 - 5) + "px" }).show();
break;
default:
m.hide();
break;
}
return r;
},
dnd_open : function () {
this.data.dnd.to2 = false;
this.open_node(r, $.proxy(this.dnd_prepare,this), true);
},
dnd_finish : function (e) {
if(this.data.dnd.foreign) {
if(this.data.dnd.after || this.data.dnd.before || this.data.dnd.inside) {
this._get_settings().dnd.drag_finish.call(this, { "o" : o, "r" : r });
}
}
else {
this.dnd_prepare();
this.move_node(o, r, this.dnd_show(), e[this._get_settings().dnd.copy_modifier + "Key"]);
}
o = false;
r = false;
m.hide();
},
dnd_enter : function (obj) {
var s = this._get_settings().dnd;
this.data.dnd.prepared = false;
r = this._get_node(obj);
if(s.check_timeout) {
// do the calculations after a minimal timeout (users tend to drag quickly to the desired location)
if(this.data.dnd.to1) { clearTimeout(this.data.dnd.to1); }
this.data.dnd.to1 = setTimeout($.proxy(this.dnd_prepare, this), s.check_timeout);
}
else {
this.dnd_prepare();
}
if(s.open_timeout) {
if(this.data.dnd.to2) { clearTimeout(this.data.dnd.to2); }
if(r && r.length && r.hasClass("jstree-closed")) {
// if the node is closed - open it, then recalculate
this.data.dnd.to2 = setTimeout($.proxy(this.dnd_open, this), s.open_timeout);
}
}
else {
if(r && r.length && r.hasClass("jstree-closed")) {
this.dnd_open();
}
}
},
start_drag : function (obj, e) {
o = this._get_node(obj);
if(this.data.ui && this.is_selected(o)) { o = this._get_node(null, true); }
$.vakata.dnd.drag_start(e, { jstree : true, obj : o }, "<ins class='jstree-icon'></ins>" + (o.length > 1 ? "Multiple selection" : this.get_text(o)) );
if(this.data.themes) {
m.attr("class", "jstree-" + this.data.themes.theme);
$.vakata.dnd.helper.attr("class", "jstree-dnd-helper jstree-" + this.data.themes.theme);
}
var cnt = this.get_container();
this.data.dnd.cof = cnt.children("ul").offset();
this.data.dnd.cw = parseInt(cnt.width(),10);
this.data.dnd.ch = parseInt(cnt.height(),10);
this.data.dnd.active = true;
}
}
});
$(function() {
var css_string = '' +
'#vakata-dragged ins {display:block; text-decoration:none; width:15px; height:16px; margin:0 0 0 0; padding:0; position:absolute; top:4px; left:4px; } ' +
'#vakata-dragged .jstree-ok { background-image: url("/images/tree/ok.png"); background-repeat: no-repeat; } ' +
'#vakata-dragged .jstree-invalid { background-image: url("/images/tree/invalid.png"); background-repeat: no-repeat; } ' +
'#jstree-marker {padding:0; margin:1px 0px 0px 2px; line-height:12px; font-size:1px; overflow:hidden; height:2px; width:100px; position:absolute; top:-30px; z-index:10000; background-repeat:no-repeat; display:none; background-color:grey; } ';
$.vakata.css.add_sheet({ str : css_string });
m = $("<div>").attr({ id : "jstree-marker" }).hide().appendTo("body");
$(document).bind("drag_start.vakata", function (e, data) {
if(data.data.jstree) {
m.show();
}
});
$(document).bind("drag_stop.vakata", function (e, data) {
if(data.data.jstree) { m.hide(); }
});
});
})(jQuery);
//*/
/*
* jsTree checkbox plugin 1.0
* Inserts checkboxes in front of every node
* Depends on the ui plugin
* DOES NOT WORK NICELY WITH MULTITREE DRAG'N'DROP
*/
(function ($) {
$.jstree.plugin("checkbox", {
__init : function () {
this.select_node = this.deselect_node = this.deselect_all = $.noop;
this.get_selected = this.get_checked;
this.get_container()
.bind("open_node.jstree create_node.jstree clean_node.jstree", $.proxy(function (e, data) {
this._prepare_checkboxes(data.rslt.obj);
}, this))
.bind("loaded.jstree", $.proxy(function (e) {
this._prepare_checkboxes();
}, this))
.delegate("a", "click.jstree", $.proxy(function (e) {
if(this._get_node(e.target).hasClass("jstree-checked")) { this.uncheck_node(e.target); }
else { this.check_node(e.target); }
if(this.data.ui) { this.save_selected(); }
if(this.data.cookies) { this.save_cookie("select_node"); }
e.preventDefault();
}, this));
},
__destroy : function () {
this.get_container().find(".jstree-checkbox").remove();
},
_fn : {
_prepare_checkboxes : function (obj) {
obj = !obj || obj == -1 ? this.get_container() : this._get_node(obj);
var c, _this = this, t;
obj.each(function () {
t = $(this);
c = t.is("li") && t.hasClass("jstree-checked") ? "jstree-checked" : "jstree-unchecked";
t.find("a").not(":has(.jstree-checkbox)").prepend("<ins class='jstree-checkbox'> </ins>").parent().not(".jstree-checked, .jstree-unchecked").addClass(c);
});
if(obj.is("li")) { this._repair_state(obj); }
else { obj.find("> ul > li").each(function () { _this._repair_state(this); }); }
},
change_state : function (obj, state) {
obj = this._get_node(obj);
state = (state === false || state === true) ? state : obj.hasClass("jstree-checked");
if(state) { obj.find("li").andSelf().removeClass("jstree-checked jstree-undetermined").addClass("jstree-unchecked"); }
else {
obj.find("li").andSelf().removeClass("jstree-unchecked jstree-undetermined").addClass("jstree-checked");
if(this.data.ui) { this.data.ui.last_selected = obj; }
this.data.checkbox.last_selected = obj;
}
obj.parentsUntil(".jstree", "li").each(function () {
var $this = $(this);
if(state) {
if($this.children("ul").children(".jstree-checked, .jstree-undetermined").length) {
$this.parentsUntil(".jstree", "li").andSelf().removeClass("jstree-checked jstree-unchecked").addClass("jstree-undetermined");
return false;
}
else {
$this.removeClass("jstree-checked jstree-undetermined").addClass("jstree-unchecked");
}
}
else {
if($this.children("ul").children(".jstree-unchecked, .jstree-undetermined").length) {
$this.parentsUntil(".jstree", "li").andSelf().removeClass("jstree-checked jstree-unchecked").addClass("jstree-undetermined");
return false;
}
else {
$this.removeClass("jstree-unchecked jstree-undetermined").addClass("jstree-checked");
}
}
});
if(this.data.ui) { this.data.ui.selected = this.get_checked(); }
this.__callback(obj);
},
check_node : function (obj) {
this.change_state(obj, false);
},
uncheck_node : function (obj) {
this.change_state(obj, true);
},
check_all : function () {
var _this = this;
this.get_container().children("ul").children("li").each(function () {
_this.check_node(this, false);
});
},
uncheck_all : function () {
var _this = this;
this.get_container().children("ul").children("li").each(function () {
_this.change_state(this, true);
});
},
is_checked : function(obj) {
obj = this._get_node(obj);
return obj.length ? obj.is(".jstree-checked") : false;
},
get_checked : function (obj) {
obj = !obj || obj === -1 ? this.get_container() : this._get_node(obj);
return obj.find("> ul > .jstree-checked, .jstree-undetermined > ul > .jstree-checked");
},
get_unchecked : function (obj) {
obj = !obj || obj === -1 ? this.get_container() : this._get_node(obj);
return obj.find("> ul > .jstree-unchecked, .jstree-undetermined > ul > .jstree-unchecked");
},
show_checkboxes : function () { this.get_container().children("ul").removeClass("jstree-no-checkboxes"); },
hide_checkboxes : function () { this.get_container().children("ul").addClass("jstree-no-checkboxes"); },
_repair_state : function (obj) {
obj = this._get_node(obj);
if(!obj.length) { return; }
var a = obj.find("> ul > .jstree-checked").length,
b = obj.find("> ul > .jstree-undetermined").length,
c = obj.find("> ul > li").length;
if(c === 0) { if(obj.hasClass("jstree-undetermined")) { this.check_node(obj); } }
else if(a === 0 && b === 0) { this.uncheck_node(obj); }
else if(a === c) { this.check_node(obj); }
else {
obj.parentsUntil(".jstree","li").removeClass("jstree-checked jstree-unchecked").addClass("jstree-undetermined");
}
},
reselect : function () {
if(this.data.ui) {
var _this = this,
s = this.data.ui.to_select;
s = $.map($.makeArray(s), function (n) { return "#" + n.toString().replace(/^#/,"").replace('\\/','/').replace('/','\\/'); });
this.deselect_all();
$.each(s, function (i, val) { _this.check_node(val); });
this.__callback();
}
}
}
});
})(jQuery);
//*/
/*
* jsTree XML 1.0
* The XML data store. Datastores are build by overriding the `load_node` and `_is_loaded` functions.
*/
(function ($) {
$.vakata.xslt = function (xml, xsl, callback) {
var rs = "", xm, xs, processor, support;
if(document.recalc) {
xm = document.createElement('xml');
xs = document.createElement('xml');
xm.innerHTML = xml;
xs.innerHTML = xsl;
$("body").append(xm).append(xs);
setTimeout( (function (xm, xs, callback) {
return function () {
callback.call(null, xm.transformNode(xs.XMLDocument));
setTimeout( (function (xm, xs) { return function () { jQuery("body").remove(xm).remove(xs); }; })(xm, xs), 200);
};
}) (xm, xs, callback), 100);
return true;
}
if(typeof window.DOMParser !== "undefined" && typeof window.XMLHttpRequest !== "undefined" && typeof window.XSLTProcessor !== "undefined") {
processor = new XSLTProcessor();
support = $.isFunction(processor.transformDocument) ? (typeof window.XMLSerializer !== "undefined") : true;
if(!support) { return false; }
xml = new DOMParser().parseFromString(xml, "text/xml");
xsl = new DOMParser().parseFromString(xsl, "text/xml");
if($.isFunction(processor.transformDocument)) {
rs = document.implementation.createDocument("", "", null);
processor.transformDocument(xml, xsl, rs, null);
callback.call(null, XMLSerializer().serializeToString(rs));
return true;
}
else {
processor.importStylesheet(xsl);
rs = processor.transformToFragment(xml, document);
callback.call(null, $("<div>").append(rs).html());
return true;
}
}
return false;
};
var xsl = {
'nest' : '<?xml version="1.0" encoding="utf-8" ?>' +
'<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >' +
'<xsl:output method="html" encoding="utf-8" omit-xml-declaration="yes" standalone="no" indent="no" media-type="text/html" />' +
'<xsl:template match="/">' +
' <xsl:call-template name="nodes">' +
' <xsl:with-param name="node" select="/root" />' +
' </xsl:call-template>' +
'</xsl:template>' +
'<xsl:template name="nodes">' +
' <xsl:param name="node" />' +
' <ul>' +
' <xsl:for-each select="$node/item">' +
' <xsl:variable name="children" select="count(./item) > 0" />' +
' <li>' +
' <xsl:attribute name="class">' +
' <xsl:if test="position() = last()">jstree-last </xsl:if>' +
' <xsl:choose>' +
' <xsl:when test="@state = \'open\'">jstree-open </xsl:when>' +
' <xsl:when test="$children or @hasChildren or @state = \'closed\'">jstree-closed </xsl:when>' +
' <xsl:otherwise>jstree-leaf </xsl:otherwise>' +
' </xsl:choose>' +
' <xsl:value-of select="@class" />' +
' </xsl:attribute>' +
' <xsl:for-each select="@*">' +
' <xsl:if test="name() != \'class\' and name() != \'state\' and name() != \'hasChildren\'">' +
' <xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' +
' </xsl:if>' +
' </xsl:for-each>' +
' <ins class="jstree-icon"><xsl:text> </xsl:text></ins>' +
' <xsl:for-each select="content/name">' +
' <a>' +
' <xsl:attribute name="href">' +
' <xsl:choose>' +
' <xsl:when test="@href"><xsl:value-of select="@href" /></xsl:when>' +
' <xsl:otherwise>#</xsl:otherwise>' +
' </xsl:choose>' +
' </xsl:attribute>' +
' <xsl:attribute name="class"><xsl:value-of select="@lang" /> <xsl:value-of select="@class" /></xsl:attribute>' +
' <xsl:attribute name="style"><xsl:value-of select="@style" /></xsl:attribute>' +
' <xsl:for-each select="@*">' +
' <xsl:if test="name() != \'style\' and name() != \'class\' and name() != \'href\'">' +
' <xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' +
' </xsl:if>' +
' </xsl:for-each>' +
' <ins>' +
' <xsl:attribute name="class">jstree-icon ' +
' <xsl:if test="string-length(attribute::icon) > 0 and not(contains(@icon,\'/\'))"><xsl:value-of select="@icon" /></xsl:if>' +
' </xsl:attribute>' +
' <xsl:if test="string-length(attribute::icon) > 0 and contains(@icon,\'/\')"><xsl:attribute name="style">background:url(<xsl:value-of select="@icon" />) center center no-repeat;</xsl:attribute></xsl:if>' +
' <xsl:text> </xsl:text>' +
' </ins>' +
' <xsl:value-of select="current()" />' +
' </a>' +
' </xsl:for-each>' +
' <xsl:if test="$children or @hasChildren"><xsl:call-template name="nodes"><xsl:with-param name="node" select="current()" /></xsl:call-template></xsl:if>' +
' </li>' +
' </xsl:for-each>' +
' </ul>' +
'</xsl:template>' +
'</xsl:stylesheet>',
'flat' : '<?xml version="1.0" encoding="utf-8" ?>' +
'<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >' +
'<xsl:output method="html" encoding="utf-8" omit-xml-declaration="yes" standalone="no" indent="no" media-type="text/xml" />' +
'<xsl:template match="/">' +
' <ul>' +
' <xsl:for-each select="//item[not(@parent_id) or @parent_id=0 or not(@parent_id = //item/@id)]">' + /* the last `or` may be removed */
' <xsl:call-template name="nodes">' +
' <xsl:with-param name="node" select="." />' +
' <xsl:with-param name="is_last" select="number(position() = last())" />' +
' </xsl:call-template>' +
' </xsl:for-each>' +
' </ul>' +
'</xsl:template>' +
'<xsl:template name="nodes">' +
' <xsl:param name="node" />' +
' <xsl:param name="is_last" />' +
' <xsl:variable name="children" select="count(//item[@parent_id=$node/attribute::id]) > 0" />' +
' <li>' +
' <xsl:attribute name="class">' +
' <xsl:if test="$is_last = true()">jstree-last </xsl:if>' +
' <xsl:choose>' +
' <xsl:when test="@state = \'open\'">jstree-open </xsl:when>' +
' <xsl:when test="$children or @hasChildren or @state = \'closed\'">jstree-closed </xsl:when>' +
' <xsl:otherwise>jstree-leaf </xsl:otherwise>' +
' </xsl:choose>' +
' <xsl:value-of select="@class" />' +
' </xsl:attribute>' +
' <xsl:for-each select="@*">' +
' <xsl:if test="name() != \'parent_id\' and name() != \'hasChildren\' and name() != \'class\' and name() != \'state\'">' +
' <xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' +
' </xsl:if>' +
' </xsl:for-each>' +
' <ins class="jstree-icon"><xsl:text> </xsl:text></ins>' +
' <xsl:for-each select="content/name">' +
' <a>' +
' <xsl:attribute name="href">' +
' <xsl:choose>' +
' <xsl:when test="@href"><xsl:value-of select="@href" /></xsl:when>' +
' <xsl:otherwise>#</xsl:otherwise>' +
' </xsl:choose>' +
' </xsl:attribute>' +
' <xsl:attribute name="class"><xsl:value-of select="@lang" /> <xsl:value-of select="@class" /></xsl:attribute>' +
' <xsl:attribute name="style"><xsl:value-of select="@style" /></xsl:attribute>' +
' <xsl:for-each select="@*">' +
' <xsl:if test="name() != \'style\' and name() != \'class\' and name() != \'href\'">' +
' <xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' +
' </xsl:if>' +
' </xsl:for-each>' +
' <ins>' +
' <xsl:attribute name="class">jstree-icon ' +
' <xsl:if test="string-length(attribute::icon) > 0 and not(contains(@icon,\'/\'))"><xsl:value-of select="@icon" /></xsl:if>' +
' </xsl:attribute>' +
' <xsl:if test="string-length(attribute::icon) > 0 and contains(@icon,\'/\')"><xsl:attribute name="style">background:url(<xsl:value-of select="@icon" />) center center no-repeat;</xsl:attribute></xsl:if>' +
' <xsl:text> </xsl:text>' +
' </ins>' +
' <xsl:value-of select="current()" />' +
' </a>' +
' </xsl:for-each>' +
' <xsl:if test="$children">' +
' <ul>' +
' <xsl:for-each select="//item[@parent_id=$node/attribute::id]">' +
' <xsl:call-template name="nodes">' +
' <xsl:with-param name="node" select="." />' +
' <xsl:with-param name="is_last" select="number(position() = last())" />' +
' </xsl:call-template>' +
' </xsl:for-each>' +
' </ul>' +
' </xsl:if>' +
' </li>' +
'</xsl:template>' +
'</xsl:stylesheet>'
};
$.jstree.plugin("xml_data", {
defaults : {
data : false,
ajax : false,
xsl : "flat",
clean_node : false,
correct_state : true
},
_fn : {
load_node : function (obj, s_call, e_call) { var _this = this; this.load_node_xml(obj, function () { _this.__callback({ "obj" : obj }); s_call.call(this); }, e_call); },
_is_loaded : function (obj) {
var s = this._get_settings().xml_data;
obj = this._get_node(obj);
return obj == -1 || !obj || !s.ajax || obj.is(".jstree-open, .jstree-leaf") || obj.children("ul").children("li").size() > 0;
},
load_node_xml : function (obj, s_call, e_call) {
var s = this.get_settings().xml_data,
error_func = function () {},
success_func = function () {};
obj = this._get_node(obj);
if(obj && obj !== -1) {
if(obj.data("jstree-is-loading")) { return; }
else { obj.data("jstree-is-loading",true); }
}
switch(!0) {
case (!s.data && !s.ajax): throw "Neither data nor ajax settings supplied.";
case (!!s.data && !s.ajax) || (!!s.data && !!s.ajax && (!obj || obj === -1)):
if(!obj || obj == -1) {
this.parse_xml(s.data, $.proxy(function (d) {
if(d) {
d = d.replace(/ ?xmlns="[^"]*"/ig, "");
if(d.length > 10) {
d = $(d);
this.get_container().children("ul").empty().append(d.children());
if(s.clean_node) { this.clean_node(obj); }
if(s_call) { s_call.call(this); }
}
}
else {
if(s.correct_state) {
this.get_container().children("ul").empty();
if(s_call) { s_call.call(this); }
}
}
}, this));
}
break;
case (!s.data && !!s.ajax) || (!!s.data && !!s.ajax && obj && obj !== -1):
error_func = function (x, t, e) {
var ef = this.get_settings().xml_data.ajax.error;
if(ef) { ef.call(this, x, t, e); }
if(obj !== -1 && obj.length) {
obj.children(".jstree-loading").removeClass("jstree-loading");
obj.data("jstree-is-loading",false);
if(t === "success" && s.correct_state) { obj.removeClass("jstree-open jstree-closed").addClass("jstree-leaf"); }
}
else {
if(t === "success" && s.correct_state) { this.get_container().children("ul").empty(); }
}
if(e_call) { e_call.call(this); }
};
success_func = function (d, t, x) {
d = x.responseText;
var sf = this.get_settings().xml_data.ajax.success;
if(sf) { d = sf.call(this,d,t,x) || d; }
if(d == "") {
return error_func.call(this, x, t, "");
}
this.parse_xml(d, $.proxy(function (d) {
if(d) {
d = d.replace(/ ?xmlns="[^"]*"/ig, "");
if(d.length > 10) {
d = $(d);
if(obj === -1 || !obj) { this.get_container().children("ul").empty().append(d.children()); }
else { obj.children(".jstree-loading").removeClass("jstree-loading"); obj.append(d); obj.data("jstree-is-loading",false); }
if(s.clean_node) { this.clean_node(obj); }
if(s_call) { s_call.call(this); }
}
else {
if(obj && obj !== -1) {
obj.children(".jstree-loading").removeClass("jstree-loading");
obj.data("jstree-is-loading",false);
if(s.correct_state) {
obj.removeClass("jstree-open jstree-closed").addClass("jstree-leaf");
if(s_call) { s_call.call(this); }
}
}
else {
if(s.correct_state) {
this.get_container().children("ul").empty();
if(s_call) { s_call.call(this); }
}
}
}
}
}, this));
};
s.ajax.context = this;
s.ajax.error = error_func;
s.ajax.success = success_func;
if(!s.ajax.dataType) { s.ajax.dataType = "xml"; }
if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, obj); }
if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, obj); }
$.ajax(s.ajax);
break;
}
},
parse_xml : function (xml, callback) {
var s = this._get_settings().xml_data;
$.vakata.xslt(xml, xsl[s.xsl], callback);
},
get_xml : function (tp, obj, li_attr, a_attr, is_callback) {
var result = "",
s = this._get_settings(),
_this = this,
tmp1, tmp2, li, a, lang;
if(!tp) { tp = "flat"; }
if(!is_callback) { is_callback = 0; }
obj = this._get_node(obj);
if(!obj || obj === -1) { obj = this.get_container().find("> ul > li"); }
li_attr = $.isArray(li_attr) ? li_attr : [ "id", "class" ];
if(!is_callback && this.data.types && $.inArray(s.types.type_attr, li_attr) === -1) { li_attr.push(s.types.type_attr); }
a_attr = $.isArray(a_attr) ? a_attr : [ ];
if(!is_callback) { result += "<root>"; }
obj.each(function () {
result += "<item";
li = $(this);
$.each(li_attr, function (i, v) { result += " " + v + "=\"" + (li.attr(v) || "").replace(/jstree[^ ]*|$/ig,'').replace(/^\s+$/ig,"") + "\""; });
if(li.hasClass("jstree-open")) { result += " state=\"open\""; }
if(li.hasClass("jstree-closed")) { result += " state=\"closed\""; }
if(tp === "flat") { result += " parent_id=\"" + is_callback + "\""; }
result += ">";
result += "<content>";
a = li.children("a");
a.each(function () {
tmp1 = $(this);
lang = false;
result += "<name";
if($.inArray("languages", s.plugins) !== -1) {
$.each(s.languages, function (k, z) {
if(tmp1.hasClass(z)) { result += " lang=\"" + z + "\""; lang = z; return false; }
});
}
if(a_attr.length) {
$.each(a_attr, function (k, z) {
result += " " + z + "=\"" + (tmp1.attr(z) || "").replace(/jstree[^ ]*|$/ig,'') + "\"";
});
}
if(tmp1.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/^\s+$/ig,"").length) {
result += ' icon="' + tmp1.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/^\s+$/ig,"") + '"';
}
if(tmp1.children("ins").get(0).style.backgroundImage.length) {
result += ' icon="' + tmp1.children("ins").get(0).style.backgroundImage.replace("url(","").replace(")","") + '"';
}
result += ">";
result += "<![CDATA[" + _this.get_text(tmp1, lang) + "]]>";
result += "</name>";
});
result += "</content>";
tmp2 = li[0].id;
li = li.find("> ul > li");
if(li.length) { tmp2 = _this.get_xml(tp, li, li_attr, a_attr, tmp2); }
else { tmp2 = ""; }
if(tp == "nest") { result += tmp2; }
result += "</item>";
if(tp == "flat") { result += tmp2; }
});
if(!is_callback) { result += "</root>"; }
return result;
}
}
});
})(jQuery);
//*/
/*
* jsTree search plugin 1.0
* Enables both sync and async search on the tree
* DOES NOT WORK WITH JSON PROGRESSIVE RENDER
*/
(function ($) {
$.expr[':'].jstree_contains = function(a,i,m){
return (a.textContent || a.innerText || "").toLowerCase().indexOf(m[3].toLowerCase())>=0;
};
$.jstree.plugin("search", {
__init : function () {
this.data.search.str = "";
this.data.search.result = $();
},
defaults : {
ajax : false, // OR ajax object
case_insensitive : false
},
_fn : {
search : function (str, skip_async) {
if(str === "") { return; }
var s = this.get_settings().search,
t = this,
error_func = function () { },
success_func = function () { };
this.data.search.str = str;
if(!skip_async && s.ajax !== false && this.get_container().find(".jstree-closed:eq(0)").length > 0) {
this.search.supress_callback = true;
error_func = function () { };
success_func = function (d, t, x) {
var sf = this.get_settings().search.ajax.success;
if(sf) { d = sf.call(this,d,t,x) || d; }
this.data.search.to_open = d;
this._search_open();
};
s.ajax.context = this;
s.ajax.error = error_func;
s.ajax.success = success_func;
if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, str); }
if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, str); }
if(!s.ajax.data) { s.ajax.data = { "search_string" : str }; }
if(!s.ajax.dataType || /^json/.exec(s.ajax.dataType)) { s.ajax.dataType = "json"; }
$.ajax(s.ajax);
return;
}
if(this.data.search.result.length) { this.clear_search(); }
this.data.search.result = this.get_container().find("a" + (this.data.languages ? "." + this.get_lang() : "" ) + ":" + (s.case_insensitive ? "jstree_contains" : "contains") + "(" + this.data.search.str + ")");
this.data.search.result.addClass("jstree-search").parents(".jstree-closed").each(function () {
t.open_node(this, false, true);
});
this.__callback({ nodes : this.data.search.result, str : str });
},
clear_search : function (str) {
this.data.search.result.removeClass("jstree-search");
this.__callback(this.data.search.result);
this.data.search.result = $();
},
_search_open : function (is_callback) {
var _this = this,
done = true,
current = [],
remaining = [];
if(this.data.search.to_open.length) {
$.each(this.data.search.to_open, function (i, val) {
if(val == "#") { return true; }
if($(val).length && $(val).is(".jstree-closed")) { current.push(val); }
else { remaining.push(val); }
});
if(current.length) {
this.data.search.to_open = remaining;
$.each(current, function (i, val) {
_this.open_node(val, function () { _this._search_open(true); });
});
done = false;
}
}
if(done) { this.search(this.data.search.str, true); }
}
}
});
})(jQuery);
//*/
/*
* jsTree contextmenu plugin 1.0
*/
(function ($) {
$.vakata.context = {
cnt : $("<div id='vakata-contextmenu'>"),
vis : false,
tgt : false,
par : false,
func : false,
data : false,
show : function (s, t, x, y, d, p) {
var html = $.vakata.context.parse(s), h, w;
if(!html) { return; }
$.vakata.context.vis = true;
$.vakata.context.tgt = t;
$.vakata.context.par = p || t || null;
$.vakata.context.data = d || null;
$.vakata.context.cnt
.html(html)
.css({ "visibility" : "hidden", "display" : "block", "left" : 0, "top" : 0 });
h = $.vakata.context.cnt.height();
w = $.vakata.context.cnt.width();
if(x + w > $(document).width()) {
x = $(document).width() - (w + 5);
$.vakata.context.cnt.find("li > ul").addClass("right");
}
if(y + h > $(document).height()) {
y = y - (h + t[0].offsetHeight);
$.vakata.context.cnt.find("li > ul").addClass("bottom");
}
$.vakata.context.cnt
.css({ "left" : x, "top" : y })
.find("li:has(ul)")
.bind("mouseenter", function (e) {
var w = $(document).width(),
h = $(document).height(),
ul = $(this).children("ul").show();
if(w !== $(document).width()) { ul.toggleClass("right"); }
if(h !== $(document).height()) { ul.toggleClass("bottom"); }
})
.bind("mouseleave", function (e) {
$(this).children("ul").hide();
})
.end()
.css({ "visibility" : "visible" })
.show();
$(document).triggerHandler("context_show.vakata");
},
hide : function () {
$.vakata.context.vis = false;
$.vakata.context.cnt.attr("class","").hide();
$(document).triggerHandler("context_hide.vakata");
},
parse : function (s, is_callback) {
if(!s) { return false; }
var str = "",
tmp = false,
was_sep = true;
if(!is_callback) { $.vakata.context.func = {}; }
str += "<ul>";
$.each(s, function (i, val) {
if(!val) { return true; }
$.vakata.context.func[i] = val.action;
if(!was_sep && val.separator_before) {
str += "<li class='vakata-separator vakata-separator-before'></li>";
}
was_sep = false;
str += "<li class='" + (val._class || "") + (val._disabled ? " jstree-contextmenu-disabled " : "") + "'><ins ";
if(val.icon && val.icon.indexOf("/") === -1) { str += " class='" + val.icon + "' "; }
if(val.icon && val.icon.indexOf("/") !== -1) { str += " style='background:url(" + val.icon + ") center center no-repeat;' "; }
str += "> </ins><a href='#' rel='" + i + "'>";
if(val.submenu) {
str += "<span style='float:right;'>»</span>";
}
str += val.label + "</a>";
if(val.submenu) {
tmp = $.vakata.context.parse(val.submenu, true);
if(tmp) { str += tmp; }
}
str += "</li>";
if(val.separator_after) {
str += "<li class='vakata-separator vakata-separator-after'></li>";
was_sep = true;
}
});
str = str.replace(/<li class\='vakata-separator vakata-separator-after'\><\/li\>$/,"");
str += "</ul>";
return str.length > 10 ? str : false;
},
exec : function (i) {
if($.isFunction($.vakata.context.func[i])) {
$.vakata.context.func[i].call($.vakata.context.data, $.vakata.context.par);
return true;
}
else { return false; }
}
};
$(function () {
var css_string = '' +
'#vakata-contextmenu { display:none; position:absolute; margin:0; padding:0; min-width:180px; background:#ebebeb; border:1px solid silver; z-index:10000; *width:180px; } ' +
'#vakata-contextmenu ul { min-width:180px; *width:180px; } ' +
'#vakata-contextmenu ul, #vakata-contextmenu li { margin:0; padding:0; list-style-type:none; display:block; } ' +
'#vakata-contextmenu li { line-height:20px; min-height:20px; position:relative; padding:0px; } ' +
'#vakata-contextmenu li a { padding:1px 6px; line-height:17px; display:block; text-decoration:none; margin:1px 1px 0 1px; } ' +
'#vakata-contextmenu li ins { float:left; width:16px; height:16px; text-decoration:none; margin-right:2px; } ' +
'#vakata-contextmenu li a:hover, #vakata-contextmenu li.vakata-hover > a { background:gray; color:white; } ' +
'#vakata-contextmenu li ul { display:none; position:absolute; top:-2px; left:100%; background:#ebebeb; border:1px solid gray; } ' +
'#vakata-contextmenu .right { right:100%; left:auto; } ' +
'#vakata-contextmenu .bottom { bottom:-1px; top:auto; } ' +
'#vakata-contextmenu li.vakata-separator { min-height:0; height:1px; line-height:1px; font-size:1px; overflow:hidden; margin:0 2px; background:silver; /* border-top:1px solid #fefefe; */ padding:0; } ';
$.vakata.css.add_sheet({ str : css_string });
$.vakata.context.cnt
.delegate("a","click", function (e) { e.preventDefault(); })
.delegate("a","mouseup", function (e) {
if(!$(this).parent().hasClass("jstree-contextmenu-disabled") && $.vakata.context.exec($(this).attr("rel"))) {
$.vakata.context.hide();
}
else { $(this).blur(); }
})
.delegate("a","mouseover", function () {
$.vakata.context.cnt.find(".vakata-hover").removeClass("vakata-hover");
})
.appendTo("body");
$(document).bind("mousedown", function (e) { if($.vakata.context.vis && !$.contains($.vakata.context.cnt[0], e.target)) { $.vakata.context.hide(); } });
if(typeof $.hotkeys !== "undefined") {
$(document)
.bind("keydown", "up", function (e) {
if($.vakata.context.vis) {
var o = $.vakata.context.cnt.find("ul:visible").last().children(".vakata-hover").removeClass("vakata-hover").prevAll("li:not(.vakata-separator)").first();
if(!o.length) { o = $.vakata.context.cnt.find("ul:visible").last().children("li:not(.vakata-separator)").last(); }
o.addClass("vakata-hover");
e.stopImmediatePropagation();
e.preventDefault();
}
})
.bind("keydown", "down", function (e) {
if($.vakata.context.vis) {
var o = $.vakata.context.cnt.find("ul:visible").last().children(".vakata-hover").removeClass("vakata-hover").nextAll("li:not(.vakata-separator)").first();
if(!o.length) { o = $.vakata.context.cnt.find("ul:visible").last().children("li:not(.vakata-separator)").first(); }
o.addClass("vakata-hover");
e.stopImmediatePropagation();
e.preventDefault();
}
})
.bind("keydown", "right", function (e) {
if($.vakata.context.vis) {
$.vakata.context.cnt.find(".vakata-hover").children("ul").show().children("li:not(.vakata-separator)").removeClass("vakata-hover").first().addClass("vakata-hover");
e.stopImmediatePropagation();
e.preventDefault();
}
})
.bind("keydown", "left", function (e) {
if($.vakata.context.vis) {
$.vakata.context.cnt.find(".vakata-hover").children("ul").hide().children(".vakata-separator").removeClass("vakata-hover");
e.stopImmediatePropagation();
e.preventDefault();
}
})
.bind("keydown", "esc", function (e) {
$.vakata.context.hide();
e.preventDefault();
})
.bind("keydown", "space", function (e) {
$.vakata.context.cnt.find(".vakata-hover").last().children("a").click();
e.preventDefault();
});
}
});
$.jstree.plugin("contextmenu", {
__init : function () {
this.get_container()
.delegate("a", "contextmenu.jstree", $.proxy(function (e) {
e.preventDefault();
this.show_contextmenu(e.currentTarget, e.pageX, e.pageY);
}, this))
.bind("destroy.jstree", $.proxy(function () {
if(this.data.contextmenu) {
$.vakata.context.hide();
}
}, this));
$(document).bind("context_hide.vakata", $.proxy(function () { this.data.contextmenu = false; }, this));
},
defaults : {
select_node : false, // requires UI plugin
show_at_node : true,
items : { // Could be a function that should return an object like this one
"create" : {
"separator_before" : false,
"separator_after" : true,
"label" : "Create",
"action" : function (obj) { this.create(obj); }
},
"rename" : {
"separator_before" : false,
"separator_after" : false,
"label" : "Rename",
"action" : function (obj) { this.rename(obj); }
},
"remove" : {
"separator_before" : false,
"icon" : false,
"separator_after" : false,
"label" : "Delete",
"action" : function (obj) { this.remove(obj); }
},
"ccp" : {
"separator_before" : true,
"icon" : false,
"separator_after" : false,
"label" : "Edit",
"action" : false,
"submenu" : {
"cut" : {
"separator_before" : false,
"separator_after" : false,
"label" : "Cut",
"action" : function (obj) { this.cut(obj); }
},
"copy" : {
"separator_before" : false,
"icon" : false,
"separator_after" : false,
"label" : "Copy",
"action" : function (obj) { this.copy(obj); }
},
"paste" : {
"separator_before" : false,
"icon" : false,
"separator_after" : false,
"label" : "Paste",
"action" : function (obj) { this.paste(obj); }
}
}
}
}
},
_fn : {
show_contextmenu : function (obj, x, y) {
obj = this._get_node(obj);
var s = this.get_settings().contextmenu,
a = obj.children("a:visible:eq(0)"),
o = false;
if(s.select_node && this.data.ui && !this.is_selected(obj)) {
this.deselect_all();
this.select_node(obj, true);
}
if(s.show_at_node || typeof x === "undefined" || typeof y === "undefined") {
o = a.offset();
x = o.left;
y = o.top + this.data.core.li_height;
}
if($.isFunction(s.items)) { s.items = s.items.call(this, obj); }
this.data.contextmenu = true;
$.vakata.context.show(s.items, a, x, y, this, obj);
if(this.data.themes) { $.vakata.context.cnt.attr("class", "jstree-" + this.data.themes.theme + "-context"); }
}
}
});
})(jQuery);
//*/
/*
* jsTree types plugin 1.0
* Adds support types of nodes
* You can set an attribute on each li node, that represents its type.
* According to the type setting the node may get custom icon/validation rules
*/
(function ($) {
$.jstree.plugin("types", {
__init : function () {
var s = this._get_settings().types;
this.data.types.attach_to = [];
this.get_container()
.bind("init.jstree", $.proxy(function () {
var types = s.types,
attr = s.type_attr,
icons_css = "",
_this = this;
$.each(types, function (i, tp) {
$.each(tp, function (k, v) {
if(!/^(max_depth|max_children|icon|valid_children)$/.test(k)) { _this.data.types.attach_to.push(k); }
});
if(!tp.icon) { return true; }
if( tp.icon.image || tp.icon.position) {
if(i == "default") { icons_css += '.jstree-' + _this.get_index() + ' a > .jstree-icon { '; }
else { icons_css += '.jstree-' + _this.get_index() + ' li[' + attr + '=' + i + '] > a > .jstree-icon { '; }
if(tp.icon.image) { icons_css += ' background-image:url(' + tp.icon.image + '); '; }
if(tp.icon.position){ icons_css += ' background-position:' + tp.icon.position + '; '; }
else { icons_css += ' background-position:0 0; '; }
icons_css += '} ';
}
});
if(icons_css != "") { $.vakata.css.add_sheet({ 'str' : icons_css }); }
}, this))
.bind("before.jstree", $.proxy(function (e, data) {
if($.inArray(data.func, this.data.types.attach_to) !== -1) {
var s = this._get_settings().types.types,
t = this._get_type(data.args[0]);
if(
(
(s[t] && typeof s[t][data.func] !== "undefined") ||
(s["default"] && typeof s["default"][data.func] !== "undefined")
) && !this._check(data.func, data.args[0])
) {
e.stopImmediatePropagation();
return false;
}
}
}, this));
},
defaults : {
// defines maximum number of root nodes (-1 means unlimited, -2 means disable max_children checking)
max_children : -1,
// defines the maximum depth of the tree (-1 means unlimited, -2 means disable max_depth checking)
max_depth : -1,
// defines valid node types for the root nodes
valid_children : "all",
// where is the type stores (the rel attribute of the LI element)
type_attr : "rel",
// a list of types
types : {
// the default type
"default" : {
"max_children" : -1,
"max_depth" : -1,
"valid_children": "all"
// Bound functions - you can bind any other function here (using boolean or function)
//"select_node" : true,
//"open_node" : true,
//"close_node" : true,
//"create_node" : true,
//"delete_node" : true
}
}
},
_fn : {
_get_type : function (obj) {
obj = this._get_node(obj);
return (!obj || !obj.length) ? false : obj.attr(this._get_settings().types.type_attr) || "default";
},
set_type : function (str, obj) {
obj = this._get_node(obj);
return (!obj.length || !str) ? false : obj.attr(this._get_settings().types.type_attr, str);
},
_check : function (rule, obj, opts) {
var v = false, t = this._get_type(obj), d = 0, _this = this, s = this._get_settings().types;
if(obj === -1) {
if(!!s[rule]) { v = s[rule]; }
else { return; }
}
else {
if(t === false) { return; }
if(!!s.types[t] && !!s.types[t][rule]) { v = s.types[t][rule]; }
else if(!!s.types["default"] && !!s.types["default"][rule]) { v = s.types["default"][rule]; }
}
if($.isFunction(v)) { v = v.call(this, obj); }
if(rule === "max_depth" && obj !== -1 && opts !== false && s.max_depth !== -2 && v !== 0) {
// also include the node itself - otherwise if root node it is not checked
this._get_node(obj).children("a:eq(0)").parentsUntil(".jstree","li").each(function (i) {
// check if current depth already exceeds global tree depth
if(s.max_depth !== -1 && s.max_depth - (i + 1) <= 0) { v = 0; return false; }
d = (i === 0) ? v : _this._check(rule, this, false);
// check if current node max depth is already matched or exceeded
if(d !== -1 && d - (i + 1) <= 0) { v = 0; return false; }
// otherwise - set the max depth to the current value minus current depth
if(d >= 0 && (d - (i + 1) < v || v < 0) ) { v = d - (i + 1); }
// if the global tree depth exists and it minus the nodes calculated so far is less than `v` or `v` is unlimited
if(s.max_depth >= 0 && (s.max_depth - (i + 1) < v || v < 0) ) { v = s.max_depth - (i + 1); }
});
}
return v;
},
check_move : function () {
if(!this.__call_old()) { return false; }
var m = this._get_move(),
s = m.rt._get_settings().types,
mc = m.rt._check("max_children", m.cr),
md = m.rt._check("max_depth", m.cr),
vc = m.rt._check("valid_children", m.cr),
ch = 0, d = 1, t;
if(vc === "none") { return false; }
if($.isArray(vc) && m.ot && m.ot._get_type) {
m.o.each(function () {
if($.inArray(m.ot._get_type(this), vc) === -1) { d = false; return false; }
});
if(d === false) { return false; }
}
if(s.max_children !== -2 && mc !== -1) {
ch = m.cr === -1 ? this.get_container().children("> ul > li").not(m.o).length : m.cr.children("> ul > li").not(m.o).length;
if(ch + m.o.length > mc) { return false; }
}
if(s.max_depth !== -2 && md !== -1) {
d = 0;
if(md === 0) { return false; }
if(typeof m.o.d === "undefined") {
// TODO: deal with progressive rendering and async when checking max_depth (how to know the depth of the moved node)
t = m.o;
while(t.length > 0) {
t = t.find("> ul > li");
d ++;
}
m.o.d = d;
}
if(md - m.o.d < 0) { return false; }
}
return true;
},
create_node : function (obj, position, js, callback, is_loaded, skip_check) {
if(!skip_check && (is_loaded || this._is_loaded(obj))) {
var p = (position && position.match(/^before|after$/i) && obj !== -1) ? this._get_parent(obj) : this._get_node(obj),
s = this._get_settings().types,
mc = this._check("max_children", p),
md = this._check("max_depth", p),
vc = this._check("valid_children", p),
ch;
if(!js) { js = {}; }
if(vc === "none") { return false; }
if($.isArray(vc)) {
if(!js.attr || !js.attr[s.type_attr]) {
if(!js.attr) { js.attr = {}; }
js.attr[s.type_attr] = vc[0];
}
else {
if($.inArray(js.attr[s.type_attr], vc) === -1) { return false; }
}
}
if(s.max_children !== -2 && mc !== -1) {
ch = p === -1 ? this.get_container().children("> ul > li").length : p.children("> ul > li").length;
if(ch + 1 > mc) { return false; }
}
if(s.max_depth !== -2 && md !== -1 && (md - 1) < 0) { return false; }
}
return this.__call_old(true, obj, position, js, callback, is_loaded, skip_check);
}
}
});
})(jQuery);
//*/
/*
* jsTree HTML data 1.0
* The HTML data store. Datastores are build by replacing the `load_node` and `_is_loaded` functions.
*/
(function ($) {
$.jstree.plugin("html_data", {
__init : function () {
// this used to use html() and clean the whitespace, but this way any attached data was lost
this.data.html_data.original_container_html = this.get_container().find(" > ul > li").clone(true);
// remove white space from LI node - otherwise nodes appear a bit to the right
this.data.html_data.original_container_html.find("li").andSelf().contents().filter(function() { return this.nodeType == 3; }).remove();
},
defaults : {
data : false,
ajax : false,
correct_state : true
},
_fn : {
load_node : function (obj, s_call, e_call) { var _this = this; this.load_node_html(obj, function () { _this.__callback({ "obj" : obj }); s_call.call(this); }, e_call); },
_is_loaded : function (obj) {
obj = this._get_node(obj);
return obj == -1 || !obj || !this._get_settings().html_data.ajax || obj.is(".jstree-open, .jstree-leaf") || obj.children("ul").children("li").size() > 0;
},
load_node_html : function (obj, s_call, e_call) {
var d,
s = this.get_settings().html_data,
error_func = function () {},
success_func = function () {};
obj = this._get_node(obj);
if(obj && obj !== -1) {
if(obj.data("jstree-is-loading")) { return; }
else { obj.data("jstree-is-loading",true); }
}
switch(!0) {
case (!s.data && !s.ajax):
if(!obj || obj == -1) {
this.get_container()
.children("ul").empty()
.append(this.data.html_data.original_container_html)
.find("li, a").filter(function () { return this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'> </ins>").end()
.filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon");
this.clean_node();
}
if(s_call) { s_call.call(this); }
break;
case (!!s.data && !s.ajax) || (!!s.data && !!s.ajax && (!obj || obj === -1)):
if(!obj || obj == -1) {
d = $(s.data);
if(!d.is("ul")) { d = $("<ul>").append(d); }
this.get_container()
.children("ul").empty().append(d.children())
.find("li, a").filter(function () { return this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'> </ins>").end()
.filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon");
this.clean_node();
}
if(s_call) { s_call.call(this); }
break;
case (!s.data && !!s.ajax) || (!!s.data && !!s.ajax && obj && obj !== -1):
obj = this._get_node(obj);
error_func = function (x, t, e) {
var ef = this.get_settings().html_data.ajax.error;
if(ef) { ef.call(this, x, t, e); }
if(obj != -1 && obj.length) {
obj.children(".jstree-loading").removeClass("jstree-loading");
obj.data("jstree-is-loading",false);
if(t === "success" && s.correct_state) { obj.removeClass("jstree-open jstree-closed").addClass("jstree-leaf"); }
}
else {
if(t === "success" && s.correct_state) { this.get_container().children("ul").empty(); }
}
if(e_call) { e_call.call(this); }
};
success_func = function (d, t, x) {
var sf = this.get_settings().html_data.ajax.success;
if(sf) { d = sf.call(this,d,t,x) || d; }
if(d == "") {
return error_func.call(this, x, t, "");
}
if(d) {
d = $(d);
if(!d.is("ul")) { d = $("<ul>").append(d); }
if(obj == -1 || !obj) { this.get_container().children("ul").empty().append(d.children()).find("li, a").filter(function () { return this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'> </ins>").end().filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); }
else { obj.children(".jstree-loading").removeClass("jstree-loading"); obj.append(d).find("li, a").filter(function () { return this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'> </ins>").end().filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); obj.data("jstree-is-loading",false); }
this.clean_node(obj);
if(s_call) { s_call.call(this); }
}
else {
if(obj && obj !== -1) {
obj.children(".jstree-loading").removeClass("jstree-loading");
obj.data("jstree-is-loading",false);
if(s.correct_state) {
obj.removeClass("jstree-open jstree-closed").addClass("jstree-leaf");
if(s_call) { s_call.call(this); }
}
}
else {
if(s.correct_state) {
this.get_container().children("ul").empty();
if(s_call) { s_call.call(this); }
}
}
}
};
s.ajax.context = this;
s.ajax.error = error_func;
s.ajax.success = success_func;
if(!s.ajax.dataType) { s.ajax.dataType = "html"; }
if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, obj); }
if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, obj); }
$.ajax(s.ajax);
break;
}
}
}
});
// include the HTML data plugin by default
$.jstree.defaults.plugins.push("html_data");
})(jQuery);
//*/
/*
* jsTree themeroller plugin 1.0
* Adds support for jQuery UI themes. Include this at the end of your plugins list, also make sure "themes" is not included.
*/
(function ($) {
$.jstree.plugin("themeroller", {
__init : function () {
var s = this._get_settings().themeroller;
this.get_container()
.addClass("ui-widget-content")
.delegate("a","mouseenter.jstree", function () {
$(this).addClass(s.item_h);
})
.delegate("a","mouseleave.jstree", function () {
$(this).removeClass(s.item_h);
})
.bind("open_node.jstree create_node.jstree", $.proxy(function (e, data) {
this._themeroller(data.rslt.obj);
}, this))
.bind("loaded.jstree refresh.jstree", $.proxy(function (e) {
this._themeroller();
}, this))
.bind("close_node.jstree", $.proxy(function (e, data) {
data.rslt.obj.children("ins").removeClass(s.opened).addClass(s.closed);
}, this))
.bind("select_node.jstree", $.proxy(function (e, data) {
data.rslt.obj.children("a").addClass(s.item_a);
}, this))
.bind("deselect_node.jstree deselect_all.jstree", $.proxy(function (e, data) {
this.get_container()
.find("." + s.item_a).removeClass(s.item_a).end()
.find(".jstree-clicked").addClass(s.item_a);
}, this))
.bind("move_node.jstree", $.proxy(function (e, data) {
this._themeroller(data.rslt.o);
}, this));
},
__destroy : function () {
var s = this._get_settings().themeroller,
c = [ "ui-icon" ];
$.each(s, function (i, v) {
v = v.split(" ");
if(v.length) { c = c.concat(v); }
});
this.get_container()
.removeClass("ui-widget-content")
.find("." + c.join(", .")).removeClass(c.join(" "));
},
_fn : {
_themeroller : function (obj) {
var s = this._get_settings().themeroller;
obj = !obj || obj == -1 ? this.get_container() : this._get_node(obj).parent();
obj
.find("li.jstree-closed > ins.jstree-icon").removeClass(s.opened).addClass("ui-icon " + s.closed).end()
.find("li.jstree-open > ins.jstree-icon").removeClass(s.closed).addClass("ui-icon " + s.opened).end()
.find("a").addClass(s.item)
.children("ins.jstree-icon").addClass("ui-icon " + s.item_icon);
}
},
defaults : {
"opened" : "ui-icon-triangle-1-se",
"closed" : "ui-icon-triangle-1-e",
"item" : "ui-state-default",
"item_h" : "ui-state-hover",
"item_a" : "ui-state-active",
"item_icon" : "ui-icon-folder-collapsed"
}
});
$(function() {
var css_string = '.jstree .ui-icon { overflow:visible; } .jstree a { padding:0 2px; }';
$.vakata.css.add_sheet({ str : css_string });
});
})(jQuery);
//*/
/*
* jsTree unique plugin 1.0
* Forces different names amongst siblings (still a bit experimental)
* NOTE: does not check language versions (it will not be possible to have nodes with the same title, even in different languages)
*/
(function ($) {
$.jstree.plugin("unique", {
__init : function () {
this.get_container()
.bind("before.jstree", $.proxy(function (e, data) {
var nms = [], res = true, p, t;
if(data.func == "move_node") {
// obj, ref, position, is_copy, is_prepared, skip_check
if(data.args[4] === true) {
if(data.args[0].o && data.args[0].o.length) {
data.args[0].o.children("a").each(function () { nms.push($(this).text().replace(/^\s+/g,"")); });
res = this._check_unique(nms, data.args[0].np.find("> ul > li").not(data.args[0].o));
}
}
}
if(data.func == "create_node") {
// obj, position, js, callback, is_loaded
if(data.args[4] || this._is_loaded(data.args[0])) {
p = this._get_node(data.args[0]);
if(data.args[1] && (data.args[1] === "before" || data.args[1] === "after")) {
p = this._get_parent(data.args[0]);
if(!p || p === -1) { p = this.get_container(); }
}
if(typeof data.args[2] === "string") { nms.push(data.args[2]); }
else if(!data.args[2] || !data.args[2].data) { nms.push(this._get_settings().core.strings.new_node); }
else { nms.push(data.args[2].data); }
res = this._check_unique(nms, p.find("> ul > li"));
}
}
if(data.func == "rename_node") {
// obj, val
nms.push(data.args[1]);
t = this._get_node(data.args[0]);
p = this._get_parent(t);
if(!p || p === -1) { p = this.get_container(); }
res = this._check_unique(nms, p.find("> ul > li").not(t));
}
if(!res) {
e.stopPropagation();
return false;
}
}, this));
},
_fn : {
_check_unique : function (nms, p) {
var cnms = [];
p.children("a").each(function () { cnms.push($(this).text().replace(/^\s+/g,"")); });
if(!cnms.length || !nms.length) { return true; }
cnms = cnms.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",");
if((cnms.length + nms.length) != cnms.concat(nms).sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",").length) {
return false;
}
return true;
},
check_move : function () {
if(!this.__call_old()) { return false; }
var p = this._get_move(), nms = [];
if(p.o && p.o.length) {
p.o.children("a").each(function () { nms.push($(this).text().replace(/^\s+/g,"")); });
return this._check_unique(nms, p.np.find("> ul > li").not(p.o));
}
return true;
}
}
});
})(jQuery);
//*/ |
import React from 'react';
import PropTypes from 'prop-types';
import {withStyles} from '@material-ui/core/styles/index';
import Button from '@material-ui/core/Button';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';
import DialogActions from '@material-ui/core/DialogActions';
import Dialog from '@material-ui/core/Dialog';
import Radio from '@material-ui/core/Radio';
import IconOk from '@material-ui/icons/Check';
import IconCancel from '@material-ui/icons/Cancel';
import ComplexCron from '../Components/ComplexCron';
import SimpleCron from '../Components/simple-cron/SimpleCron';
import Schedule from '../Components/Schedule';
import I18n from '@iobroker/adapter-react/i18n';
// Generate cron expression
const styles = theme => ({
headerID: {
fontWeight: 'bold',
fontStyle: 'italic'
},
radio: {
display: 'inline-block'
},
dialogPaper: {
height: 'calc(100% - 96px)'
},
});
class DialogCron extends React.Component {
constructor(props) {
super(props);
let cron;
if (this.props.cron && typeof this.props.cron === 'string' && this.props.cron.replace(/^["']/, '')[0] !== '{') {
cron = this.props.cron.replace(/['"]/g, '').trim();
} else {
cron = this.props.cron || '{}';
if (typeof cron === 'string') {
cron = cron.replace(/^["']/, '').replace(/["']\n?$/, '');
}
}
this.state = {
cron,
mode: this.props.simple ?
'simple' :
(typeof cron === 'object' || cron[0] === '{' ?
'wizard' :
(SimpleCron.cron2state(this.props.cron || '* * * * *') ? 'simple' : 'complex'))
};
}
handleCancel() {
this.props.onClose();
}
handleOk() {
this.props.onOk(this.state.cron);
this.props.onClose();
}
setMode(mode) {
this.setState({mode});
}
render() {
return <Dialog
onClose={(event, reason) => false}
maxWidth="md"
fullWidth={true}
classes={{paper: this.props.classes.dialogPaper}}
open={true}
aria-labelledby="cron-dialog-title"
>
<DialogTitle id="cron-dialog-title">{this.props.title || I18n.t('Define schedule...')}</DialogTitle>
<DialogContent style={{height: '100%', overflow: 'hidden'}}>
{!this.props.simple && (<div>
<Radio
key="wizard"
checked={this.state.mode === 'wizard'}
onChange={e => this.setMode('wizard')}
/><label onClick={e => this.setMode('wizard')}
style={this.state.mode !== 'wizard' ? {color: 'lightgrey'} : {}}>{I18n.t('sc_wizard')}</label>
<Radio
key="simple"
checked={this.state.mode === 'simple'}
onChange={e => this.setMode('simple')}
/><label onClick={e => this.setMode('simple')}
style={this.state.mode !== 'simple' ? {color: 'lightgrey'} : {}}>{I18n.t('sc_simple')}</label>
<Radio
key="complex"
checked={this.state.mode === 'complex'}
onChange={e => this.setMode('complex')}
/><label onClick={e => this.setMode('complex')} style={this.state.mode !== 'complex' ? {color: 'lightgrey'} : {}}>{I18n.t('sc_cron')}</label></div>)}
{this.state.mode === 'simple' &&
(<SimpleCron
cronExpression={this.state.cron}
onChange={cron => this.setState({cron})}
language={I18n.getLanguage()}
/>)}
{this.state.mode === 'wizard' &&
(<Schedule
schedule={this.state.cron}
onChange={cron => this.setState({cron})}
language={I18n.getLanguage()}
/>)}
{this.state.mode === 'complex' &&
(<ComplexCron
cronExpression={this.state.cron}
onChange={cron => this.setState({cron})}
language={I18n.getLanguage()}
/>)}
</DialogContent>
<DialogActions>
<Button onClick={() => this.handleOk()} color="primary" startIcon={<IconOk/>}>{this.props.ok || I18n.t('Ok')}</Button>
<Button onClick={() => this.handleCancel()} startIcon={<IconCancel/>}>{this.props.cancel || I18n.t('Cancel')}</Button>
</DialogActions>
</Dialog>;
}
}
DialogCron.propTypes = {
classes: PropTypes.object,
onClose: PropTypes.func,
onOk: PropTypes.func.isRequired,
title: PropTypes.string,
cron: PropTypes.string,
cancel: PropTypes.string,
ok: PropTypes.string,
simple: PropTypes.bool,
language: PropTypes.string
};
export default withStyles(styles)(DialogCron);
|
/* Modernizr 2.8.3 (Custom Build) | MIT & BSD
* Build: http://modernizr.com/download/#-svg-touch-shiv-cssclasses-cssclassprefix:DC!m!
*/
;
window.Modernizr = (function( window, document, undefined ) {
var version = '2.8.3',
Modernizr = {},
enableClasses = true,
docElement = document.documentElement,
mod = 'modernizr',
modElem = document.createElement(mod),
mStyle = modElem.style,
inputElem ,
toString = {}.toString,
prefixes = ' -webkit- -moz- -o- -ms- '.split(' '),
ns = {'svg': 'http://www.w3.org/2000/svg'},
tests = {},
inputs = {},
attrs = {},
classes = [],
slice = classes.slice,
featureName,
injectElementWithStyles = function( rule, callback, nodes, testnames ) {
var style, ret, node, docOverflow,
div = document.createElement('div'),
body = document.body,
fakeBody = body || document.createElement('body');
if ( parseInt(nodes, 10) ) {
while ( nodes-- ) {
node = document.createElement('div');
node.id = testnames ? testnames[nodes] : mod + (nodes + 1);
div.appendChild(node);
}
}
style = ['­','<style id="s', mod, '">', rule, '</style>'].join('');
div.id = mod;
(body ? div : fakeBody).innerHTML += style;
fakeBody.appendChild(div);
if ( !body ) {
fakeBody.style.background = '';
fakeBody.style.overflow = 'hidden';
docOverflow = docElement.style.overflow;
docElement.style.overflow = 'hidden';
docElement.appendChild(fakeBody);
}
ret = callback(div, rule);
if ( !body ) {
fakeBody.parentNode.removeChild(fakeBody);
docElement.style.overflow = docOverflow;
} else {
div.parentNode.removeChild(div);
}
return !!ret;
},
_hasOwnProperty = ({}).hasOwnProperty, hasOwnProp;
if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) {
hasOwnProp = function (object, property) {
return _hasOwnProperty.call(object, property);
};
}
else {
hasOwnProp = function (object, property) {
return ((property in object) && is(object.constructor.prototype[property], 'undefined'));
};
}
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) {
var target = this;
if (typeof target != "function") {
throw new TypeError();
}
var args = slice.call(arguments, 1),
bound = function () {
if (this instanceof bound) {
var F = function(){};
F.prototype = target.prototype;
var self = new F();
var result = target.apply(
self,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
return bound;
};
}
function setCss( str ) {
mStyle.cssText = str;
}
function setCssAll( str1, str2 ) {
return setCss(prefixes.join(str1 + ';') + ( str2 || '' ));
}
function is( obj, type ) {
return typeof obj === type;
}
function contains( str, substr ) {
return !!~('' + str).indexOf(substr);
}
function testDOMProps( props, obj, elem ) {
for ( var i in props ) {
var item = obj[props[i]];
if ( item !== undefined) {
if (elem === false) return props[i];
if (is(item, 'function')){
return item.bind(elem || obj);
}
return item;
}
}
return false;
}
tests['touch'] = function() {
var bool;
if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
bool = true;
} else {
injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function( node ) {
bool = node.offsetTop === 9;
});
}
return bool;
};
tests['svg'] = function() {
return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect;
};
for ( var feature in tests ) {
if ( hasOwnProp(tests, feature) ) {
featureName = feature.toLowerCase();
Modernizr[featureName] = tests[feature]();
classes.push((Modernizr[featureName] ? '' : 'no-') + featureName);
}
}
Modernizr.addTest = function ( feature, test ) {
if ( typeof feature == 'object' ) {
for ( var key in feature ) {
if ( hasOwnProp( feature, key ) ) {
Modernizr.addTest( key, feature[ key ] );
}
}
} else {
feature = feature.toLowerCase();
if ( Modernizr[feature] !== undefined ) {
return Modernizr;
}
test = typeof test == 'function' ? test() : test;
if (typeof enableClasses !== "undefined" && enableClasses) {
docElement.className+=" DC-m-" + (test ? '' : 'no-') + feature;
}
Modernizr[feature] = test;
}
return Modernizr;
};
setCss('');
modElem = inputElem = null;
;(function(window, document) {
var version = '3.7.0';
var options = window.html5 || {};
var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;
var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;
var supportsHtml5Styles;
var expando = '_html5shiv';
var expanID = 0;
var expandoData = {};
var supportsUnknownElements;
(function() {
try {
var a = document.createElement('a');
a.innerHTML = '<xyz></xyz>';
supportsHtml5Styles = ('hidden' in a);
supportsUnknownElements = a.childNodes.length == 1 || (function() {
(document.createElement)('a');
var frag = document.createDocumentFragment();
return (
typeof frag.cloneNode == 'undefined' ||
typeof frag.createDocumentFragment == 'undefined' ||
typeof frag.createElement == 'undefined'
);
}());
} catch(e) {
supportsHtml5Styles = true;
supportsUnknownElements = true;
}
}());
function addStyleSheet(ownerDocument, cssText) {
var p = ownerDocument.createElement('p'),
parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;
p.innerHTML = 'x<style>' + cssText + '</style>';
return parent.insertBefore(p.lastChild, parent.firstChild);
}
function getElements() {
var elements = html5.elements;
return typeof elements == 'string' ? elements.split(' ') : elements;
}
function getExpandoData(ownerDocument) {
var data = expandoData[ownerDocument[expando]];
if (!data) {
data = {};
expanID++;
ownerDocument[expando] = expanID;
expandoData[expanID] = data;
}
return data;
}
function createElement(nodeName, ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createElement(nodeName);
}
if (!data) {
data = getExpandoData(ownerDocument);
}
var node;
if (data.cache[nodeName]) {
node = data.cache[nodeName].cloneNode();
} else if (saveClones.test(nodeName)) {
node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
} else {
node = data.createElem(nodeName);
}
return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node;
}
function createDocumentFragment(ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createDocumentFragment();
}
data = data || getExpandoData(ownerDocument);
var clone = data.frag.cloneNode(),
i = 0,
elems = getElements(),
l = elems.length;
for(;i<l;i++){
clone.createElement(elems[i]);
}
return clone;
}
function shivMethods(ownerDocument, data) {
if (!data.cache) {
data.cache = {};
data.createElem = ownerDocument.createElement;
data.createFrag = ownerDocument.createDocumentFragment;
data.frag = data.createFrag();
}
ownerDocument.createElement = function(nodeName) {
if (!html5.shivMethods) {
return data.createElem(nodeName);
}
return createElement(nodeName, ownerDocument, data);
};
ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' +
'var n=f.cloneNode(),c=n.createElement;' +
'h.shivMethods&&(' +
getElements().join().replace(/[\w\-]+/g, function(nodeName) {
data.createElem(nodeName);
data.frag.createElement(nodeName);
return 'c("' + nodeName + '")';
}) +
');return n}'
)(html5, data.frag);
}
function shivDocument(ownerDocument) {
if (!ownerDocument) {
ownerDocument = document;
}
var data = getExpandoData(ownerDocument);
if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) {
data.hasCSS = !!addStyleSheet(ownerDocument,
'article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}' +
'mark{background:#FF0;color:#000}' +
'template{display:none}'
);
}
if (!supportsUnknownElements) {
shivMethods(ownerDocument, data);
}
return ownerDocument;
}
var html5 = {
'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video',
'version': version,
'shivCSS': (options.shivCSS !== false),
'supportsUnknownElements': supportsUnknownElements,
'shivMethods': (options.shivMethods !== false),
'type': 'default',
'shivDocument': shivDocument,
createElement: createElement,
createDocumentFragment: createDocumentFragment
};
window.html5 = html5;
shivDocument(document);
}(this, document));
Modernizr._version = version;
Modernizr._prefixes = prefixes;
Modernizr.testStyles = injectElementWithStyles; docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') +
(enableClasses ? " DC-m-js DC-m-"+classes.join(" DC-m-") : '');
return Modernizr;
})(this, this.document);
; |
"use strict";
//var _roostSW = {version: 1, logging: true, appKey:"6paox8ctqtmfggp1b94355tknhdoc47q", host: "http://localhost:8081", baseURL: "http://localhost:8081"};
var _roostSW = {
version: 1,
logging: true,
appKey: "6paox8ctqtmfggp1b94355tknhdoc47q",
host: "https://go.goroost.com"
};
self.addEventListener('install', function(evt) {
//Automatically take over the previous worker.
evt.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', function(evt) {
if (_roostSW.logging) console.log("Activated Roost ServiceWorker version: " + _roostSW.version);
});
//Handle the push received event.
self.addEventListener('push', function(evt) {
if (_roostSW.logging) console.log("push listener", evt);
evt.waitUntil(self.registration.pushManager.getSubscription().then(function(subscription) {
return fetch(_roostSW.host + "/api/browser/notifications?version=" + _roostSW.version + "&appKey=" + _roostSW.appKey + "&deviceID=" + subscription.subscriptionId).then(function(response) {
return response.json().then(function(json) {
if (_roostSW.logging) console.log(json);
var promises = [];
for (var i = 0; i < json.notifications.length; i++) {
var note = json.notifications[i];
if (_roostSW.logging) console.log("Showing notification: " + note.body);
var url = "/roost.html?noteID=" + note.roost_note_id + "&sendID=" + note.roost_send_id + "&body=" + encodeURIComponent(note.body);
promises.push(showNotification(note.title, note.body, url, _roostSW.appKey));
}
return Promise.all(promises);
});
});
}));
});
self.addEventListener('notificationclick', function(evt) {
if (_roostSW.logging) console.log("notificationclick listener", evt);
evt.waitUntil(handleNotificationClick(evt));
});
function parseQueryString(queryString) {
var qd = {};
queryString.split("&").forEach(function (item) {
var parts = item.split("=");
var k = parts[0];
var v = decodeURIComponent(parts[1]);
(k in qd) ? qd[k].push(v) : qd[k] = [v, ]
});
return qd;
}
//Utility function to handle the click
function handleNotificationClick(evt) {
if (_roostSW.logging) console.log("Notification clicked: ", evt.notification);
evt.notification.close();
var iconURL = evt.notification.icon;
if (iconURL.indexOf("?") > -1) {
var queryString = iconURL.split("?")[1];
var query = parseQueryString(queryString);
if (query.url && query.url.length == 1) {
if (_roostSW.logging) console.log("Opening URL: " + query.url[0]);
return clients.openWindow(query.url[0]);
}
}
console.log("Failed to redirect to notification for iconURL: " + iconURL);
}
//Utility function to actually show the notification.
function showNotification(title, body, url, appKey) {
var options = {
body: body,
tag: "roost",
icon: _roostSW.host + '/api/browser/logo?size=100&direct=true&appKey=' + _roostSW.appKey + '&url=' + encodeURIComponent(url)
};
return self.registration.showNotification(title, options);
} |
/*
jQuery Plugin: Query YQL - version 0.4.1
LICENSE: http://hail2u.mit-license.org/2009
*/
(function(c){c.queryYQL=function(d,b,a,e){c.isFunction(b)?(e=b,b="json"):b.match(/(json|xml)/)?c.isFunction(a)&&(e=a,a=void 0):(e=a,a=b,b="json");var f="https:"===document.location.protocol?"https":"http";d={format:b,q:d};"all"===a&&(a=f+"://datatables.org/alltables.env");a&&(d.env=a);return c.get(f+"://query.yahooapis.com/v1/public/yql?callback=?",d,e,"json")}})(jQuery); |
"use strict";
chrome.storage.sync.get(null, storage => {
const pre = document.createElement("pre");
pre.textContent = JSON.stringify(storage, null, 2);
document.body.appendChild(pre);
});
document.addEventListener("click", e => {
chrome.storage.sync.clear();
});
|
module.exports = (f, array) => array.filter(f).length === array.length
|
'use strict';
const net = require( 'net' );
function query( path ) { return new Promise( ( resolve, reject ) => {
let payload = '';
net.connect( path ).on( 'data', ( d ) => {
payload += d.toString();
} ).on( 'end', () => {
resolve( payload );
} ).on( 'error', ( e ) => {
reject( e );
} );
} ); }
module.exports = { query };
|
import { gql } from '@apollo/client'
import useQuery from '../../utils/useQuery'
import browsersField from '../../fragments/browsersField'
import enhanceBrowsers from '../../../enhancers/enhanceBrowsers'
const QUERY = gql`
query fetchBrowsers($id: ID!, $sorting: Sorting!, $type: BrowserType!, $range: Range) {
domain(id: $id) {
id
statistics {
id
...browsersField
}
}
}
${ browsersField }
`
export default (id, filters) => {
const selector = (data) => data?.domain.statistics.browsers
const enhancer = enhanceBrowsers
return useQuery(QUERY, selector, enhancer, {
variables: {
...filters,
id,
},
})
} |
/*
* Represents membership infor for the Santropol Roulant bike shop.
* This is the abstract method so both 'MemberInfo' and 'MemberInfoHistory'
* can extend this object; AND have MemberInfo refer to MemberInfoHistory without
* a circular dependancy.
*/
define (['parse', 'underscore', 'moment'], function(Parse, _, moment){
//Using the parse object to create objects. But should be replaceablewith Backbone.
var MemberInfoAbstract = Parse.Object.extend("MemberInfoAbstract",{
defaults: {
'fullname' : '',
'phone': '',
'email' : '',
'fee' : 0,
'signoff': false
},
/*
* Getter for fullname
*/
getFullName : function(){
var name = this.get('fullname');
if (_.isUndefined(name)) {
return '';
}
return name;
},
/*
* Name needs to be a string. Throws an exception if this fails
*/
setFullName : function(name){
if(_.isString(name)){
this.set('fullname', name);
}else{
throw "name needs to be oftype string";
}
},
/*
* Getter for phone number. Using Strings
*/
getPhoneNumber : function(){
return this.get('phone');
},
/*
* setter - no error checking if it is string, number, etc
*/
setPhoneNumber : function(number){
this.set('phone', number);
},
/*
* Email address getter
*/
getEmail : function(){
return this.get('email');
},
/*
* set email. Must be a string or it will throw an error.
*/
setEmail : function(email){
if (_.isString(email)) {
this.set('email', email);
}else{
throw "email must be a string";
}
},
/*
* Getter for fee paid
*/
getFeePaid : function(){
return this.get('fee');
},
/*
* Setter for fee paid - will throw an error if it is not a number.
*/
setFeePaid : function(fee){
if (_.isNumber(fee)) {
this.set('fee',fee);
}else{
throw "fee must be a number";
}
},
/*
* returns true or false if user has signed off on terms of service
*/
getSignOff : function(){
return this.signoff;
},
/*
* Sets if the users has signed off - must be a boolean
*/
setSignOff : function(signoff){
if (_.isBoolean(signoff)) {
this.set('signoff', signoff);
}else{
throw "signoff must be a boolean";
}
},
/*
* Returns the time in UTC that the user registered most recently.
*/
getRegisteredUntilDate : function(){
return this.get('registeredUntilDate');
},
/*
* Sets the registration date for this user.
* Needs to be in UTC time - milliseconds from the epoch.
* Easiest method is: new Date().getTime()
*
* If parameter is undefined; defaults to now
*/
setRegisteredUntilDate : function(time){
if (_.isUndefined(time)) {
time = moment().valueOf();
}
if (!_.isNumber(time)) {
throw "A number needs to be passed to setRegistrationDate";
}
this.set('registeredUntilDate', time);
},
/*
* Get membership start date
*/
getMembershipStartDate : function(){
return this.get('membershipStartDate');
}
});
return MemberInfoAbstract;
}); |
import { expect } from 'chai'
import { describeComponent, it } from 'ember-mocha'
import { beforeEach, afterEach } from 'mocha'
import sinon from 'sinon'
import hbs from 'htmlbars-inline-precompile'
const testTemplate = hbs`{{frost-combobox on-change=onChange data=data greeting=greeting}}`
describeComponent(
'frost-combobox',
'Integration: FrostComboboxComponent',
{
integration: true
},
function () {
let sandbox
let dropDown, props
beforeEach(function () {
sandbox = sinon.sandbox.create()
props = {
onChange: sinon.spy(),
data: [
{
value: 'Lex Diamond'
},
{
value: 'Johnny Blaze'
},
{
value: 'Tony Starks'
}
],
greeting: 'Hola'
}
this.setProperties(props)
this.render(testTemplate)
dropDown = this.$('> div')
})
afterEach(function () {
sandbox.restore()
})
it('has correct initial state', function () {
expect(dropDown).to.have.length(1)
})
})
|
/**
* @module server
*/
'use strict';
const chalk = require('chalk'),
dateFormat = require('dateformat')
;
module.exports = {
/**
* print timestamp and message to console
*
* @param {string} msg - name
*/
info: (msg) => {
console.log('[' + chalk.gray(dateFormat(new Date(), 'HH:MM:ss')) + '] ' + msg);
}
};
|
import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router'
const CatLink = ({ keyword, key, children }) =>
keyword ? (
<Link key={key} to={`/pictograms/search/${encodeURIComponent(keyword)}`}>
{children}
</Link>
) : (
<div>{children}</div>
)
CatLink.propTypes = {
key: PropTypes.string.isRequired,
keyword: PropTypes.string,
children: PropTypes.node.isRequired,
}
export default CatLink
|
"use strict";
/**
* http://bl.ocks.org/supereggbert/aff58196188816576af0
*/
/**
* @callback ItemCallback
* @param d - data
*/
/**
* @callback CellIdCallback
* @param d - data
* @param i - index
* @param j - index
*/
(function () {
//Cache function
var svg = {
getId : function(d) {
return d.id;
}
, getTranslate : function(d) {
return "translate(" + d.point + ")";
}
, getPath : function (d) {
return d.path;
}
, getSort : function (a, b) {
return b.depth - a.depth
}
, getName : function (d) {
return d.name
}
, getTranslateForEdge : function(d) {
return "translate(" + d[0] + ")";
}
, getBasePathForEdge : function(d) {
var path = "M0,0";
var arr = d.slice(1).reverse();
var i = arr.length;
while(i--) {
path += "L" + [0, 0];
}
return path;
}
, getRealPathForEdge : function(d) {
var path = "M0,0";
var arr = d.slice(1).reverse();
var i = arr.length;
while(i--) {
path += "L" + arr[i];
}
return path;
}
, getPathForAsix : function (d) {
var path = "", l;
if (!d || !(l = d.length))
return path;
path = "M" + d[0][0] + ',' + d[0][1];
for (var i = 1; i < l; i++)
path += "L" + d[i][0] + ',' + d[i][1];
return path;
}
, getPathColor : null
};
function parentDatum() {
return this.parentNode.__data__
}
/**
* @param {d3.selection} node
* @constructor
*/
var Surface = function (node) {
var heightFunction
, colorFunction
, cellIdFunction
, cellOverFunction
, cellOutFunction
, cellMoveFunction
, timer
, transformPrecalc = []
, displayWidth = 300
, displayHeight = 300
, zoom = 1
, trans
;
/**
* @returns {d3.selection}
*/
this.container = function() {
return node;
};
/**
* Set zoom level
* @param {Number} zoomLevel
*/
this.zoom = function (zoomLevel) {
if (!arguments.length)
return zoom;
zoom = zoomLevel;
if (timer)
clearTimeout(timer);
timer = setTimeout(renderSurface, 0);
};
var getHeights = function (data) {
var output = [];
var x = data.length
, yL = data[0].length
, y
, temp
, value
;
while(x--) {
temp = [];
y = yL;
while(y--) {
value = heightFunction(data[x][y], x, y);
temp.push(value);
}
output.push(temp);
}
return output;
};
var transformPoint = function (point) {
var l = transformPrecalc.length
, output = new Array(l/3)
, p0 = point[0]
, p1 = point[1]
, p2 = point[2]
;
while((l -= 3) > -1)
output[~~(l/3)] = transformPrecalc[l] * p0
+ transformPrecalc[l + 1] * p1
+ transformPrecalc[l + 2] * p2
;
return output;
};
var getTransformedData = function (data, asix) {
if (!heightFunction || !data || !data.length || !data[0] || !data[0].length)
return [[]];
var t, a, k, kx, ky
, km, am
, output = []
, heights = getHeights(data)
, x, y
, xLength = data.length
, yLength = data[0].length
;
x = xLength;
a = Math.min(displayWidth, displayHeight) || 1;
k = 1; //1.41
kx = a*k/(xLength);
ky = a*k/yLength;
while(x--) {
t = [];
output.push(t);
y = yLength;
while(y--) {
t.push(transformPoint([
(x - xLength / 2) * kx * zoom
, asix ? 0 : heights[x][y] * zoom
, (y - yLength / 2) * ky * zoom
]));
}
}
return output;
};
var getAsix = function (lx, ly) {
var t, a, k, kx, ky
, output = []
, x, y
, xLength = lx++
, yLength = ly++
, xhl = xLength/2
, yhl = yLength/2
;
a = Math.min(displayWidth, displayHeight) || 1;
k = 1; //1.41
kx = a*k/(xLength);
ky = a*k/yLength;
var valx, valy;
for(x = -1; x < lx; x++) {
t = [];
output.push(t);
for(y = -1; y < ly; y++) {
valx = (x - xhl) * kx * zoom;
valy = (y - yhl) * ky * zoom;
if (!(xLength - x))
valx = (x -.8 - xhl) * kx * zoom;
else if (x < 0)
valx = (-.2 - xhl) * kx * zoom;
if (!(yLength - y))
valy = (y -.8 - yhl) * ky * zoom;
if (y < 0) {
valy = (-.2 - yhl) * ky * zoom;
}
t.push(transformPoint([valx, 0, valy]));
}
}
return output;
};
svg.getPathColor = function (d) {
return colorFunction ? colorFunction(d.data) : null;
};
function drawCells(data, originData, xLength, yLength, w2, h2) {
var d, d0 = [], d1 = new Array(xLength - 1)
, x, y, px, py, dpx, dpy
, d1px = w2, d1py = h2
, depth
;
for (x = 0; x < xLength - 1; x++) {
d1[x] = d1[x] || [];
for (y = 0; y < yLength - 1; y++) {
depth = data[x][y][2]
+ data[x + 1][y][2]
+ data[x + 1][y + 1][2]
+ data[x][y + 1][2]
;
px = data[x][y][0] + w2;
py = data[x][y][1] + h2;
dpx = w2 - px;
dpy = h2 - py;
d = originData[x][y];
d0.push({
path: 'M0,0'
+ 'L' + (data[x + 1][y][0] + dpx).toFixed(10)
+ ',' + (data[x + 1][y][1] + dpy).toFixed(10)
+ 'L' + (data[x + 1][y + 1][0] + dpx).toFixed(10)
+ ',' + (data[x + 1][y + 1][1] + dpy).toFixed(10)
+ 'L' + (data[x][y + 1][0] + dpx).toFixed(10)
+ ',' + (data[x][y + 1][1] + dpy).toFixed(10) + 'Z'
, depth: depth
, point: [px.toFixed(10), py.toFixed(10)]
, data: d
, id : cellIdFunction
? cellIdFunction(d, x, y)
: [x, y].join('')
});
d1[x].id = d1[x].id || d.name;
if (!d1[x].length) {
d1[x].push([px, py]);
d1px = w2 - px;
d1py = h2 - py;
}
d1[x].push([data[x][y + 1][0] + d1px, data[x][y + 1][1] + d1py]);
}
}
//start cells
var dr = node.selectAll('g.cell')
.data(d0, svg.getId)
;
var gs = dr.enter()
.append('g')
.attr('class', 'cell')
.on('mouseover', cellOverFunction)
.on('mouseout', cellOutFunction)
.on('mousemove', cellMoveFunction)
.on('touchmove', cellMoveFunction)
.attr('transform', 'translate(' + [w2, h2] + ')')
;
gs.append("path");
dr.selectAll("path")
.datum(parentDatum)
.attr("fill", svg.getPathColor)
;
dr.exit().style('display', "none");
dr.sort(svg.getSort);
dr = trans
? dr.transition()
.delay(trans.delay())
.duration(trans.duration())
: dr
;
dr.attr("transform", svg.getTranslate)
.style('display', null)
.selectAll("path")
.attr("d", svg.getPath)
;
//end cells
//start dots
dr = node.selectAll('g.dot')
.data(d0, svg.getId)
;
gs = dr.enter()
.append('g')
.attr('class', 'dot')
.on('mouseover', cellOverFunction)
.on('mouseout', cellOutFunction)
.on('mousemove', cellMoveFunction)
.attr('transform', 'translate(' + [w2, h2] + ')')
;
gs.append("circle").attr('r', 2.5);
dr.exit().style('display', "none");
dr.sort(svg.getSort);
dr = trans
? dr.transition()
.delay(trans.delay())
.duration(trans.duration())
: dr
;
dr.style('display', null)
.attr("transform", svg.getTranslate);
//end dots
dr = node.selectAll('g.edge')
.data(d1, svg.getId)
;
dr.enter()
.append('g')
.attr('class', 'edge')
.attr('transform', 'translate(' + [w2, h2] + ')')
.append('path')
.attr("d", svg.getBasePathForEdge)
;
dr.selectAll('path')
.datum(parentDatum);
dr.exit().style('display', "none");
dr = trans
? dr.transition()
.delay(trans.delay())
.duration(trans.duration())
: dr
;
dr.style('display', null)
.attr("transform", svg.getTranslateForEdge)
.selectAll('path')
.attr("d", svg.getRealPathForEdge)
;
}
function drawAsix(originData, xLength, yLength, w2, h2) {
var px = transformPoint([-0, 0, -0]);
var asix = getAsix(xLength, yLength);
asix = node.selectAll('g.asix')
.data([asix.map(function (d) {
return [d[0][0] + w2 + px[0], d[0][1] + h2 + px[1]];
}), asix[xLength + 1].map(function (d) {
return [d[0] + w2 + px[0], d[1] + h2 + px[1]];
})]
, function (d, i) {
return i;
})
;
asix.enter()
.append('g')
.attr('class', 'asix')
.append('path')
;
asix = asix.selectAll('path')
.datum(parentDatum);
(trans
? asix
.transition()
.delay(trans.delay())
.duration(trans.duration())
: asix
).attr('d', svg.getPathForAsix);
node.selectAll('g.asix').each(function(d, i) {
var that = d3.select(this)
.selectAll('g.asix-text')
.data(d.slice(2).map(function (k, j) {
return {
point: k,
name: j >= (i ? yLength - 1 : xLength - 1)
? ""
: i
? originData[0][yLength - j - 2].year
: originData[xLength - j - 2][0].name
}
}), function (k) {
return k.name
});
asixAppend.apply(that, [i]);
});
}
function overEdgeByKey(key) {
node.selectAll('.edge path')
.filter(function(b) {
return b.id == key
})
.style('stroke-opacity', 1)
.style('stroke-width', '4px')
;
}
function outEdge() {
node.selectAll('.edge path')
.style('stroke-opacity', null)
.style('stroke-width', null)
;
}
/**
* @param i
* @this d3.selection
*/
function asixAppend(i) {
var asix = this;
var gs = asix.enter()
.append("g")
.attr("class", "asix-text")
.attr("transform", "translate(" + [displayWidth/2, displayHeight/2] + ")")
.on('mouseover', function(k) {
!i && overEdgeByKey(k.name);
})
.on('mouseout', function(k) {
!i && outEdge();
})
;
gs.append("circle").attr("r", 2);
gs.append('text')
.attr("text-anchor", function() {
return i ? "middle" : "end";
})
.attr("dx", function() {
return i ? ".3em" : "-.3em";
})
.attr("dy", function() {
return i ? "1em" : ".35em";
})
.text(svg.getName)
;
asix.exit().remove();
(trans
? asix.transition()
.delay(trans.delay())
.duration(trans.duration())
: asix
).attr("transform", svg.getTranslate);
}
/**
* Rending surface
* @function
* @memberOf {Surface}
*/
var renderSurface = function () {
var originData = node.datum()
, data = getTransformedData(originData)
, xLength = data.length
, yLength = data[0].length
, w2 = displayWidth/2
, h2 = displayHeight/2
;
drawCells(data, originData, xLength, yLength, w2, h2);
drawAsix(originData, xLength, yLength, w2, h2);
trans = false;
};
this.renderSurface = renderSurface;
/**
* @returns {Surface}
*/
this.colorize = function() {
node.selectAll(".cell path")
.attr("fill", svg.getPathColor);
return this;
};
/**
* @param key
* @returns {Surface}
*/
this.highlightEdgeByKey = function(key) {
key ? overEdgeByKey(key) : outEdge();
return this;
};
/**
* @param yaw
* @param pitch
* @returns {Surface}
*/
this.setTurntable = function (yaw, pitch) {
var cosA = Math.cos(pitch);
var sinA = Math.sin(pitch);
var cosB = Math.cos(yaw);
var sinB = Math.sin(yaw);
transformPrecalc[0] = cosB;
transformPrecalc[1] = 0;
transformPrecalc[2] = sinB;
transformPrecalc[3] = sinA * sinB;
transformPrecalc[4] = cosA;
transformPrecalc[5] = -sinA * cosB;
transformPrecalc[6] = -sinB * cosA;
transformPrecalc[7] = sinA;
transformPrecalc[8] = cosA * cosB;
if (timer)
clearTimeout(timer);
timer = setTimeout(renderSurface, 0);
return this;
};
this.setTurntable(0.5, 0.5);
/**
* @param {ItemCallback} [callback]
* @returns {Surface|Function}
* @see ItemCallback
*/
this.surfaceColor = function (callback) {
if(!arguments.length)
return colorFunction;
colorFunction = callback;
if (timer)
clearTimeout(timer);
timer = setTimeout(renderSurface, 0);
return this;
};
/**
* @param {ItemCallback} [callback]
* @returns {Surface|Function}
* @see ItemCallback
*/
this.surfaceHeight = function (callback) {
if(!arguments.length)
return heightFunction;
heightFunction = callback;
if (timer)
clearTimeout(timer);
timer = setTimeout(renderSurface, 0);
return this;
};
/**
* @param {CellIdCallback} [callback]
* @returns {Surface|Function}
* @see CellIdCallback
*/
this.surfaceCellId = function (callback) {
if(!arguments.length)
return cellIdFunction;
cellIdFunction = callback;
if (timer)
clearTimeout(timer);
timer = setTimeout(renderSurface, 0);
return this;
};
/**
* @param {ItemCallback} [callback]
* @returns {Surface|Function}
* @see ItemCallback
*/
this.surfaceCellOver = function (callback) {
if(!arguments.length)
return cellOverFunction;
cellOverFunction = callback;
if (timer)
clearTimeout(timer);
timer = setTimeout(renderSurface, 0);
return this;
};
/**
* @param {ItemCallback} [callback]
* @returns {Surface|Function}
* @see ItemCallback
*/
this.surfaceCellOut = function (callback) {
if(!arguments.length)
return cellOutFunction;
cellOutFunction = callback;
if (timer)
clearTimeout(timer);
timer = setTimeout(renderSurface, 0);
return this;
};
/**
* @param {ItemCallback} [callback]
* @returns {Surface|Function}
* @see ItemCallback
*/
this.surfaceCellMove = function (callback) {
if(!arguments.length)
return cellMoveFunction;
cellMoveFunction = callback;
if (timer)
clearTimeout(timer);
timer = setTimeout(renderSurface, 0);
return this;
};
/**
* @returns {d3.selection.transition}
*/
this.transition = function () {
var transition = d3.selection.prototype.transition.bind(node)();
colorFunction = null;
heightFunction = null;
for(var key in this)
if(this.hasOwnProperty(key))
transition[key] = this[key];
trans = transition;
return transition;
};
/**
* @param {Number} [height]
* @returns {Surface|Number}
*/
this.setHeight = function (height) {
if(!arguments.length || !height)
return displayHeight;
if (height) {
displayHeight = height;
if (timer)
clearTimeout(timer);
timer = setTimeout(renderSurface, 0);
}
return this;
};
/**
* @param {Number} [width]
* @returns {Surface|Number}
*/
this.setWidth = function (width) {
if(!arguments.length || !width)
return displayWidth;
if (width) {
displayWidth = width;
if (timer)
clearTimeout(timer);
timer = setTimeout(renderSurface, 0);
}
return this;
};
};
/**
* @param width
* @param height
* @returns {d3.selection}
*/
d3.selection.prototype.surface3D = function (width, height) {
if (!this.node().__surface__)
/**
* @type {Surface}
* @private
*/
this.node().__surface__ = new Surface(this);
var surface = this.node().__surface__
, key
;
for(key in surface)
if(surface.hasOwnProperty(key))
this[key] = surface[key];
surface.setHeight(height);
surface.setWidth(width);
this.transition = surface.transition.bind(surface);
return this;
};
})(); |
/**
* @module lib/componentRegistry
* @memberof lux-lib
*/
import { isFunction, isString } from '../lib/is';
const registry = {};
/**
* Store a new component in the registry for later retrieval.
*
* @param {String} path - the identifier
* @param {Function} fn - the component definition
* @param {Boolean} [overwrite=true] - option to overwrite an existing
* registry component or not
*
* @return {any} - could be anything but typically would be a function or
* framework component
*
* @example
* import registry from './componentRegistry';
*
* // store a new component in the registry; overwrite if it already exists
* registry('Home', HomeComponent);
*
* // retrieve a registered component if it exists
* const Component = registry('Home');
*
* // store a new component in the registry; only if it doesn't already exist
* registry('Footer', FooterComponent, false);
*/
function componentRegistry(path, fn, overwrite = true) {
if (!isString(path) || path === '') {
throw new Error('Component identifiers are required and must be strings.');
}
if (fn && !isFunction(fn)) {
throw new Error('Components must be functions.');
}
if (arguments.length > 3) {
throw new Error('Too many arguments provided to componentRegistry.');
}
const saveToRegistry = registry[path] ? overwrite : true;
if (arguments.length > 1 && saveToRegistry) {
registry[path] = fn;
}
return registry[path] || undefined;
}
export default componentRegistry;
|
'use strict';
const constants = require('../lib/constants');
module.exports = {
check: (done, test) => {
try {
test();
done();
} catch(e) {
done(e);
}
},
lambdaEvent: function (body) {
let event = {};
event.headers = {};
event.headers[constants.CLIENT_ID_HEADER] = '12345';
event.body = body ? JSON.stringify(body) : '{}';
event.requestContext = { apiId: '12345zzzzz' }
return event;
},
mockLog: {
error: () => { return; },
warn: () => { return; },
info: () => { return; },
debug: () => { return; }
}
};
|
exports.concat_0_0_0 = function fastConcat () {
var length = arguments.length,
arr = [],
i, item, childLength, j;
for (i = 0; i < length; i++) {
item = arguments[i];
if (Array.isArray(item)) {
childLength = item.length;
for (j = 0; j < childLength; j++) {
arr.push(item[j]);
}
}
else {
arr.push(item);
}
}
return arr;
};
exports.bind_0_0_0 = function fastBind (fn, thisContext) {
var boundLength = arguments.length - 2,
boundArgs;
if (boundLength > 0) {
boundArgs = new Array(boundLength);
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = arguments[i + 2];
}
return function () {
var length = arguments.length,
args = new Array(boundLength + length),
i;
for (i = 0; i < boundLength; i++) {
args[i] = boundArgs[i];
}
for (i = 0; i < length; i++) {
args[boundLength + i] = arguments[i];
}
return fn.apply(thisContext, args);
};
}
else {
return function () {
var length = arguments.length,
args = new Array(length),
i;
for (i = 0; i < length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisContext, args);
};
}
};
exports.partial_0_0_0 = function fastPartial (fn) {
var boundLength = arguments.length - 1,
boundArgs;
boundArgs = new Array(boundLength);
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = arguments[i + 1];
}
return function () {
var length = arguments.length,
args = new Array(boundLength + length),
i;
for (i = 0; i < boundLength; i++) {
args[i] = boundArgs[i];
}
for (i = 0; i < length; i++) {
args[boundLength + i] = arguments[i];
}
return fn.apply(this, args);
};
};
exports.map_0_0_0 = function fastMap (subject, fn, thisContext) {
var length = subject.length,
result = new Array(length),
i;
for (i = 0; i < length; i++) {
result[i] = fn.call(thisContext, subject[i], i, subject);
}
return result;
};
exports.reduce_0_0_0 = function fastReduce (subject, fn, initialValue, thisContext) {
var length = subject.length,
result = initialValue,
i;
for (i = 0; i < length; i++) {
result = fn.call(thisContext, result, subject[i], i, subject);
}
return result;
};
exports.forEach_0_0_0 = function fastForEach (subject, fn, thisContext) {
var length = subject.length,
i;
for (i = 0; i < length; i++) {
fn.call(thisContext, subject[i], i, subject);
}
};
// v0.0.1
function bindInternal_0_0_1 (func, thisContext, numArgs) {
switch (numArgs) {
case 3: return function(a, b, c) {
return func.call(thisContext, a, b, c);
};
case 4: return function(a, b, c, d) {
return func.call(thisContext, a, b, c, d);
};
}
return function() {
return func.apply(thisContext, arguments);
};
}
exports.map_0_0_1 = function fastMap (subject, fn, thisContext) {
var length = subject.length,
result = new Array(length),
i,
iterator = arguments.length > 2 ? bindInternal_0_0_1(fn, thisContext, 3) : fn;
for (i = 0; i < length; i++) {
result[i] = iterator(subject[i], i, subject);
}
return result;
};
exports.reduce_0_0_1 = function fastReduce (subject, fn, initialValue, thisContext) {
var length = subject.length,
result = arguments.length < 3 ? subject[0] : initialValue,
i,
iterator = arguments.length > 3 ? bindInternal_0_0_1(fn, thisContext, 4) : fn;
for (i = 0; i < length; i++) {
result = iterator(result, subject[i], i, subject);
}
return result;
};
exports.forEach_0_0_1 = function fastForEach (subject, fn, thisContext) {
var length = subject.length,
i,
iterator = arguments.length > 2 ? bindInternal_0_0_1(fn, thisContext, 3) : fn;
for (i = 0; i < length; i++) {
iterator(subject[i], i, subject);
}
};
exports.indexOf_0_0_1 = function fastIndexOf (subject, target) {
var length = subject.length,
i;
for (i = 0; i < length; i++) {
if (subject[i] === target) {
return i;
}
}
return -1;
};
exports.lastIndexOf_0_0_1 = function fastLastIndexOf (subject, target) {
var length = subject.length,
i;
for (i = length - 1; i >= 0; i--) {
if (subject[i] === target) {
return i;
}
}
return -1;
};
// v0.0.2a
exports.map_0_0_2a = function fastMap (subject, fn, thisContext) {
var length = subject.length,
result = new Array(length),
i,
iterator = arguments.length > 2 ? bindInternal3_0_0_2a(fn, thisContext) : fn;
for (i = 0; i < length; i++) {
result[i] = iterator(subject[i], i, subject);
}
return result;
};
exports.reduce_0_0_2a = function fastReduce (subject, fn, initialValue, thisContext) {
var length = subject.length,
result = initialValue,
i,
iterator = arguments.length > 3 ? bindInternal4_0_0_2a(fn, thisContext) : fn;
for (i = 0; i < length; i++) {
result = iterator(result, subject[i], i, subject);
}
return result;
};
exports.forEach_0_0_2a = function fastForEach (subject, fn, thisContext) {
var length = subject.length,
i,
iterator = arguments.length > 2 ? bindInternal3_0_0_2a(fn, thisContext) : fn;
for (i = 0; i < length; i++) {
iterator(subject[i], i, subject);
}
};
function bindInternal3_0_0_2a (func, thisContext) {
return function (a, b, c) {
return func.call(thisContext, a, b, c);
};
}
function bindInternal4_0_0_2a (func, thisContext) {
return function (a, b, c, d) {
return func.call(thisContext, a, b, c, d);
};
}
// v0.0.2b
exports.reduce_0_0_2b = function fastReduce (subject, fn, initialValue, thisContext) {
var length = subject.length,
result = initialValue,
i,
iterator = thisContext !== undefined ? bindInternal4_0_0_2a(fn, thisContext) : fn;
for (i = 0; i < length; i++) {
result = iterator(result, subject[i], i, subject);
}
return result;
};
// v0.0.2c
exports.reduce_0_0_2c = function fastReduce (subject, fn, initialValue, thisContext) {
var length = subject.length,
i = 0,
result = arguments.length < 3 ? subject[i++] : initialValue,
iterator = thisContext !== undefined > 3 ? bindInternal4_0_0_2a(fn, thisContext) : fn;
for (; i < length; i++) {
result = iterator(result, subject[i], i, subject);
}
return result;
};
// v0.0.2
exports.indexOf_0_0_2 = function fastIndexOf (subject, target) {
var length = subject.length,
i;
for (i = 0; i < length; i++) {
if (subject[i] === target) {
return i;
}
}
return -1;
};
exports.lastIndexOf_0_0_2 = function fastLastIndexOf (subject, target) {
var length = subject.length,
i;
for (i = length - 1; i >= 0; i--) {
if (subject[i] === target) {
return i;
}
}
return -1;
}; |
/**
* Button Component for tingle
* @author fushan
*
* Copyright 2014-2016, Tingle Team.
* All rights reserved.
*/
var fs = require('fs');
var path = require('path');
var webpack = require('webpack');
module.exports = {
cache: false,
entry: {
demo: './demo/src/index'
},
output: {
path: './demo/dist',
filename: "[name].js",
sourceMapFilename: "[name].js.map"
},
devtool: '#source-map', // 这个配置要和output.sourceMapFilename一起使用
module: {
loaders: [
{
test: /(\.js(x)?|\.svg)$/,
// node_modules都不需要经过babel解析
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1'].map(function(item) {
return require.resolve('babel-preset-' + item);
}),
plugins: [
'add-module-exports'
].map(function(item) {
return require.resolve('babel-plugin-' + item);
}),
cacheDirectory: true,
babelrc: false,
}
}, {
test: /\.svg$/,
loader: 'salt-svg-loader'
}
]
},
resolve: {
root: [
path.join(__dirname, '../node_modules')
],
extensions: ['', '.web.ts', '.web.tsx', '.web.js', '.web.jsx', '.ts', '.tsx', '.js', '.jsx', '.json'],
},
resolveLoader: {
root: [
path.join(__dirname, '../node_modules')
]
},
externals: {
'react': 'var React', // 相当于把全局的React作为模块的返回 module.exports = React;
'react-dom': 'var ReactDOM'
},
plugins: [
new webpack.DefinePlugin({
__LOCAL__: true, // 本地环境
__DEV__: true, // 日常环境
__PRO__: false // 生产环境
})
]
};
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _knex = require('knex');
var _knex2 = _interopRequireDefault(_knex);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const db = (0, _knex2.default)({
client: 'pg',
connection: process.env.DATABASE_URL,
migrations: {
tableName: 'migrations'
},
debug: process.env.DATABASE_DEBUG === 'true'
}); /**
* Node.js API Starter Kit (https://reactstarter.com/nodejs)
*
* Copyright © 2016-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
exports.default = db;
//# sourceMappingURL=db.js.map
|
/*
* Shared by the server and client
*/
var lang = {
anon: 'Anonymous',
search: 'Search',
show: 'Show',
hide: 'Hide',
report: 'Report',
focus: 'Focus',
expand: 'Expand',
last: 'Last',
see_all: 'See all',
bottom: 'Bottom',
expand_images: 'Expand Images',
live: 'live',
catalog: 'Catalog',
return: 'Return',
top: 'Top',
reply: 'Reply',
newThread: 'New thread',
locked_to_bottom: 'Locked to bottom',
you: '(You)',
done: 'Done',
send: 'Send',
// Time-related
week: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
year: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'],
just_now: 'just now',
unit_minute: 'minute',
unit_hour: 'hour',
unit_day: 'day',
unit_month: 'month',
unit_year: 'year',
// Moderation language map
mod: {
clearSelection: ['Clear', 'Clear selected posts'],
spoilerImages: ['Spoiler', 'Spoiler selected post images'],
deleteImages: ['Del Img', 'Delete selected post images'],
deletePosts: ['Del Post', 'Delete selected posts'],
lockThread: ['Lock', 'Lock selected threads'],
toggleMnemonics: ['Mnemonics', 'Toggle mnemonic display'],
sendNotification: [
'Notification',
'Send notifaction message to all clients'
],
dispatchFun: ['Fun', 'Execute arbitrary JavaScript on all clients'],
renderPanel: ['Panel', 'Toggle administrator panel display'],
modLog: ['Log', 'Show moderation log'],
placeholders: {
msg: 'Message'
},
// Correspond to websocket calls in common/index.js
7: 'Image spoilered',
8: 'Image deleted',
9: 'Post deleted',
// Formatting function for moderation messages
formatLog: function (act) {
return lang.mod[act.kind] + ' by ' + act.ident;
}
},
// Format functions
pluralize: function(n, noun) {
// For words ending with 'y' and not a vovel before that
if (n != 1
&& noun.slice(-1) == 'y'
&& ['a', 'e', 'i', 'o', 'u'].indexOf(noun.slice(-2, -1)
.toLowerCase()) < 0) {
noun = noun.slice(0, -1) + 'ie';
}
return n + ' ' + noun + (n == 1 ? '' : 's');
},
capitalize: function(word) {
return word[0].toUpperCase() + word.slice(1);
},
// 56 minutes ago
ago: function(time, unit) {
return lang.pluralize(time, unit) + ' ago';
},
// 47 replies and 21 images omitted
abbrev_msg: function(omit, img_omit, url) {
var html = lang.pluralize(omit, 'reply');
if (img_omit)
html += ' and ' + lang.pluralize(img_omit, 'image');
html += ' omitted';
if (url) {
html += ' <span class="act"><a href="' + url + '" class="history">'
+ lang.see_all + '</a></span>';
}
return html;
}
};
module.exports = lang;
|
/**
* The field base class. Defines the interface.
*
* @module higherform
*/
import invariant from 'invariant';
export default class Field {
constructor(validators) {
validators = validators || [];
if (!Array.isArray(validators)) {
validators = [validators];
}
invariant(
validators.filter(v => typeof v === 'function').length === validators.length,
'All field validators must be functions'
);
this.validators = validators;
}
/**
* Returns a plain object of methods that can be used to programmatically
* update the field. Not useful for all fields, but complex fields may use
* this to provide a programmatic API (eg. collections).
*
* @param {string} name The name of the field in the form as a whole.
* @param {function(value|function)} updateValue The callback used to update
* the underlying form value
* @param {function} getValue Get the current value of the field. Useful for
* late binding the state from the form to props.
* @return {object}
*/
toMethods(name, updateValue, getValue) {
return {
setValue: value => updateValue(this.filterInput(value)),
props: this._buildPropsMethod(name, updateValue, getValue),
};
}
/**
* Provides a way to filter the form value before sending it back to the
* the end users.
*
* Useful if the field keeps extra state for itself.
*
* The default is to do nothing.
*
* @param {mixed} currentValue the current value of the field to filter
* @return {mixed|undefined} `undefined` indicates that the value should not
* be included in the output sent to the user.
*/
filterOutput(currentValue) {
return currentValue;
}
/**
* Filters incoming values -- like mapping props to form data.
*
* @param {mixed} inValue
* @return {mixed}
*/
filterInput(inValue) {
return inValue || '';
}
/**
* Validate the input for the field.
*
* @param {string|object} currentValue the value from the form to validate
* @param {object} ctx The validation context.
* @return {object} A validation context.
*/
validate(currentValue, ctx) {
this.validators.forEach(v => v(currentValue, ctx));
return ctx;
}
/**
* Returns a function that can build props for the fields.
*
* @param {string} name The name of the field in the form.
* @param {function} changeHandler The change handler
* @param {function} getValue Fetch the current value of the field
* @return {function} A function that can be called to render the props for the fields.
*/
_buildPropsMethod(name, updateValue, getValue) {
return () => {
return {
name,
value: getValue(),
onChange: this._createChangeHandler(updateValue),
};
};
}
/**
* Returns a function suitable for use a change event handler. How
* this works will depend on the the field. Checkboxes will be different
* from text inputs, for instance.
*
* @param {string} name The name of the field in the form
* @param {func(newValue)} updateValue A function that takes the new value
* for the field. Should you need to see the previous value for the
* field, pass a function to `updateValue`.
* @return {func(event)}
*/
_createChangeHandler(updateValue) {
return event => {
updateValue(event.target.value);
};
}
}
|
var stressDisplayLightBulb_Device = null;
var stressDisplayLightBulb_Characteristic = null;
var stressDisplayHeartRate_Characteristic = null;
function stressDisplay_lightBulb_connect() {
let serviceUuid = '00007777-0000-1000-8000-00805f9b34fb';
let characteristicUuid = '00008877-0000-1000-8000-00805f9b34fb';
navigator.bluetooth.requestDevice
({
acceptAllDevices: true,
optionalServices: [serviceUuid]
})
.then(device => {
stressDisplayLightBulb_Device = device;
return device.gatt.connect();
})
.then(server => { return server.getPrimaryService(serviceUuid); })
.then(service => { return service.getCharacteristic(characteristicUuid); })
.then(characteristic => { // Save characteristic
stressDisplayLightBulb_Characteristic = characteristic;
return characteristic;
})
.then(characteristic => { // Set to blue when starting
var send = getPayload(0x00, 0x00, 0xff);
characteristic.writeValue(send);
return characteristic;
})
.catch(error => { // Handle Errors
log('Error! ' + error);
});
}
function stressDisplay_heartRate_connect() {
let serviceUuid = "heart_rate";
let characteristicUuid = "heart_rate_measurement"
navigator.bluetooth.requestDevice
({
filters: [{ services: [serviceUuid] }]
})
.then(device => { return device.gatt.connect(); })
.then(server => { return server.getPrimaryService(serviceUuid); })
.then(service => { return service.getCharacteristic(characteristicUuid); })
.then(characteristic => { // Save characteristic
stressDisplayHeartRate_Characteristic = characteristic;
return characteristic;
})
.then(characteristic => { // Start notification
return characteristic.startNotifications()
.then(_ => {
characteristic.addEventListener(
'characteristicvaluechanged',
stressDisplay_read);
});
})
.catch(error => { // Handle Errors
log('Error! ' + error);
});
}
function stressDisplay_read(event) {
let value = event.target.value;
var bpm = value.getUint8(1);
setHeartRateValue(bpm);
var lut = colorLUT(bpm);
setColorValue(lut.r, lut.g, lut.b);
// log('{'
// + '0x' + ('0' + (lut.r & 0xFF).toString(16)).slice(-2) + ', '
// + '0x' + ('0' + (lut.g & 0xFF).toString(16)).slice(-2) + ', '
// + '0x' + ('0' + (lut.b & 0xFF).toString(16)).slice(-2)
// + '}, '
// + bpm.toString().padStart(3) + '|' + '-'.repeat(bpm - 40) + '>'
// );
log(bpm.toString().padStart(3) + '|' + '-'.repeat(bpm - 40) + '>');
var send = getPayload(lut.r, lut.g, lut.b);
stressDisplayLightBulb_Characteristic.writeValue(send);
sleep(50);
}
function getPayload(r, g, b) { // Create the payload
var data = [
0x01, 0xfe, 0x00, 0x00, 0x53, 0x83, 0x10, 0x00,
g, // Green
b, // Blue
r, // Red
0x00, 0x50, 0x00, 0x00, 0x00
];
return Uint8Array.from(data);
}
function stressDisplay_disconnect() { // Disconnect
setColorValue(0x00, 0x00, 0x00);
var send = getPayload(0x00, 0x00, 0x00);
stressDisplayLightBulb_Characteristic.writeValue(send);
sleep(50);
if (stressDisplayLightBulb_Device.gatt.connected) {
stressDisplayLightBulb_Device.gatt.disconnect();
}
if (stressDisplayHeartRate_Characteristic) {
stressDisplayHeartRate_Characteristic.stopNotifications()
.then(_ => {
stressDisplayHeartRate_Characteristic.removeEventListener(
'characteristicvaluechanged',
stressDisplay_read);
})
.catch(error => {
log('Error! ' + error);
});
}
} |
import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import store from './vuex'
import router from './routes'
// import Mock from './mock'
// Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'
Vue.use(ElementUI)
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
|
import React, { Component } from 'react';
import { Row, Col, Button } from 'react-bootstrap';
import onecolor from 'onecolor';
import getPath from 'object-path-get';
import Page from '../Page';
import Farbtastic from '../colors/Farbtastic';
import MixerGradient from '../colors/MixerGradient';
import { withRouter } from 'react-router-dom';
const getRgb = function (color) {
return onecolor(color)
.css()
.replace(/[^0-9,]/gi, '')
.split(',')
.map(function (num) {
return parseInt(num, 10);
});
};
class Mixer extends Component {
constructor(props) {
super(props);
let color1;
let color2;
color1 = onecolor(getPath(this.props, 'match.params.color1', '428bca'));
color2 = onecolor(getPath(this.props, 'match.params.color2', 'd9534f'));
this.state = {
hex1: color1.hex().toLowerCase(),
hex2: color2.hex().toLowerCase(),
farbtasticSetColor: true,
};
}
shouldComponentUpdate(nextProps, nextState) {
if (this.state === nextState) {
return false;
} else {
return true;
}
}
componentWillUpdate(nextProps, nextState) {
const h1 = encodeURIComponent(nextState.hex1.replace('#', ''));
const h2 = encodeURIComponent(nextState.hex2.replace('#', ''));
this.props.history.replace(`/colorify/mixer/${h1}/${h2}`);
}
setHex = ($state) => {
const $this = this;
['hex1', 'hex2', 'farbtasticSetColor'].forEach(function (key) {
if (!Object.prototype.hasOwnProperty.call($state, key)) {
$state[key] = $this.state[key];
}
});
$this.setState($state);
};
getColorChangeHandler = (index, isColorInput) => {
const $this = this;
return function (e) {
const newState = {
farbtasticSetColor: isColorInput,
};
const key = `hex${index}`;
newState[key] = isColorInput ? e.target.value : e;
if (newState[key] !== $this.state[key]) {
$this.setHex(newState);
}
};
};
randomHandler = (indices, channels) => {
let hexKey;
let color;
const newState = {
farbtasticSetColor: true,
};
if (!Array.isArray(channels)) {
channels = [];
}
for (let i = 0; i < indices.length; i++) {
hexKey = `hex${indices[i]}`;
color = onecolor(this.state[hexKey]);
newState[hexKey] = onecolor([
'RGB',
channels[0] === 0 ? color.red() : Math.random(),
channels[1] === 0 ? color.green() : Math.random(),
channels[2] === 0 ? color.blue() : Math.random(),
]).hex();
}
this.setHex(newState);
};
swapHandler = () => {
this.setHex({
hex1: this.state.hex2,
hex2: this.state.hex1,
farbtasticSetColor: true,
});
};
handleHexChanges = (hex1, hex2) => {
this.setState({
hex1: hex1.toLowerCase(),
hex2: hex2.toLowerCase(),
farbtasticSetColor: true,
});
};
render() {
const hex1 = this.state.hex1;
const hex2 = this.state.hex2;
const rgb1 = getRgb(hex1);
const rgb2 = getRgb(hex2);
return (
<Page pageName="Mixer">
<Row>
<Col md={2} className="color-column">
<Farbtastic
hex={hex1}
setColor={this.state.farbtasticSetColor}
onColorChange={this.getColorChangeHandler(1, false)}
/>
<input
type="color"
value={hex1}
onChange={this.getColorChangeHandler(1, true)}
onInput={this.getColorChangeHandler(1, true)}
/>
<h6 className="hex-display">{hex1}</h6>
<Button
bsStyle="primary"
onClick={this.randomHandler.bind(null, [1])}
>
Randomize 1 (RGB)
</Button>
<Button
bsStyle="primary"
onClick={this.randomHandler.bind(null, [1, 2])}
>
Randomize 1 & 2 (RGB)
</Button>
<Button
bsStyle="primary"
onClick={this.randomHandler.bind(null, [1], [1, 0, 0])}
>
Randomize 1 (RED)
</Button>
<Button
bsStyle="primary"
onClick={this.randomHandler.bind(null, [1], [0, 1, 0])}
>
Randomize 1 (BLUE)
</Button>
<Button
bsStyle="primary"
onClick={this.randomHandler.bind(null, [1], [0, 0, 1])}
>
Randomize 1 (GREEN)
</Button>
</Col>
<Col md={8}>
<MixerGradient
id="0"
rgb1={rgb1}
rgb2={rgb2}
index={null}
isEditor={false}
/>
<MixerGradient
id="1"
rgb1={rgb1}
rgb2={rgb2}
index={0}
handleHexChanges={this.handleHexChanges}
/>
<MixerGradient
id="2"
rgb1={rgb1}
rgb2={rgb2}
index={1}
handleHexChanges={this.handleHexChanges}
/>
<MixerGradient
id="3"
rgb1={rgb1}
rgb2={rgb2}
index={2}
handleHexChanges={this.handleHexChanges}
/>
</Col>
<Col md={2} className="color-column">
<Farbtastic
hex={hex2}
setColor={this.state.farbtasticSetColor}
onColorChange={this.getColorChangeHandler(2, false)}
/>
<input
type="color"
value={hex2}
onChange={this.getColorChangeHandler(2, true)}
onInput={this.getColorChangeHandler(2, true)}
/>
<h6 className="hex-display">{hex2}</h6>
<Button
bsStyle="primary"
onClick={this.randomHandler.bind(null, [2])}
>
Randomize 2 (RGB)
</Button>
<Button bsStyle="primary" onClick={this.swapHandler}>
Swap 1 & 2
</Button>
<Button
bsStyle="primary"
onClick={this.randomHandler.bind(null, [2], [1, 0, 0])}
>
Randomize 2 (RED)
</Button>
<Button
bsStyle="primary"
onClick={this.randomHandler.bind(null, [2], [0, 1, 0])}
>
Randomize 2 (BLUE)
</Button>
<Button
bsStyle="primary"
onClick={this.randomHandler.bind(null, [2], [0, 0, 1])}
>
Randomize 2 (GREEN)
</Button>
</Col>
</Row>
</Page>
);
}
}
export default withRouter(Mixer);
|
const actionHandlers = {
'app/SHOW_ALERT': (state, action) => {
const alert = {
title: action.payload.title,
text: action.payload.text,
action: action.payload.action
}
return { ...state, alerts: state.alerts.concat(alert) }
},
'app/HIDE_ALERT': (state, action) => {
const alerts = state.alerts.slice()
alerts.shift()
return { ...state, alerts: alerts }
}
}
const defaultState = {
alerts: []
}
export default function(state = defaultState, action) {
const actionHandler = actionHandlers[action.type]
if (actionHandler) {
return actionHandler(state, action)
} else {
return state
}
}
|
var assert = require('chai').assert,
rules = require('./rules'),
Typograf = require('../dist/typograf'),
t = new Typograf();
describe('API', function() {
it('should disable rule', function() {
t.disable('ru/punctuation/quot');
assert.ok(t.disabled('ru/punctuation/quot'));
t.enable('ru/punctuation/quot');
});
it('should disable rule from constructor', function() {
var typograf = new Typograf({lang: 'ru', disable: '*'});
assert.ok(typograf.disabled('ru/punctuation/quot'));
});
it('should enable rule', function() {
assert.ok(t.disabled('common/html/pbr'));
t.enable('common/html/pbr');
assert.ok(t.enabled('common/html/pbr'));
t.disable('common/html/pbr');
});
it('should enable rule from constructor', function() {
var typograf = new Typograf({lang: 'ru', enable: '*'});
assert.ok(typograf.enabled('common/html/pbr'));
});
it('should enable some rules', function() {
t.enable(['common/html/pbr', 'common/html/url']);
assert.ok(t.enabled('common/html/pbr'));
assert.ok(t.enabled('common/html/url'));
t.disable(['common/html/pbr', 'common/html/url']);
t.enable('ru/optalign/*');
assert.ok(t.enabled('ru/optalign/quot'));
assert.ok(t.enabled('ru/optalign/bracket'));
assert.ok(t.enabled('ru/optalign/comma'));
t.disable('ru/optalign/*');
assert.ok(t.disabled('ru/optalign/quot'));
assert.ok(t.disabled('ru/optalign/bracket'));
assert.ok(t.disabled('ru/optalign/comma'));
});
it('should get/set a setting', function() {
t.setting('fake', 'value', 10);
assert.equal(t.setting('fake', 'value'), 10);
assert.equal(t.setting('common/nbsp/beforeShortLastWord', 'lengthLastWord'), 3);
assert.equal(t.setting('fake'), undefined);
});
it('should get entities as name or digit', function() {
var t2 = new Typograf({mode: 'name'});
assert.equal(t2.execute('1\u00A02'), '1 2');
assert.equal(t2.execute('1 2'), '1 2');
var t3 = new Typograf({mode: 'digit'});
assert.equal(t3.execute('1\u00A02'), '1 2');
assert.equal(t3.execute('1 2'), '1 2');
});
it('should get entities as name or digit with method "execute"', function() {
var t2 = new Typograf();
assert.equal(t2.execute('1\u00A02\u00A03', {mode: 'name'}), '1 2 3');
assert.equal(t2.execute('1 2 3', {mode: 'name'}), '1 2 3');
assert.equal(t2.execute('1 2 3', {mode: 'name'}), '1 2 3');
assert.equal(t2.execute('1 2 3', {mode: 'name'}), '1 2 3');
assert.equal(t2.execute('1 2 3', {mode: 'name'}), '1 2 3');
var t3 = new Typograf();
assert.equal(t3.execute('1\u00A02\u00A03', {mode: 'digit'}), '1 2 3');
assert.equal(t3.execute('1 2 3', {mode: 'digit'}), '1 2 3');
assert.equal(t3.execute('1 2 3', {mode: 'digit'}), '1 2 3');
assert.equal(t3.execute('1 2 3', {mode: 'digit'}), '1 2 3');
assert.equal(t3.execute('1 2 3', {mode: 'digit'}), '1 2 3');
assert.equal(t3.execute('1 2 3', {mode: 'digit'}), '1 2 3');
});
it('should add safe tag', function() {
var t2 = new Typograf();
t2.addSafeTag('<myTag>', '<\\/myTag>');
assert.equal(t2.execute(' <myTag> Hello world!! </myTag> '), '<myTag> Hello world!! </myTag>');
});
it('should add rule', function() {
Typograf.rule({
name: 'common/example',
sortIndex: 100,
func: function(text) {
return text.replace(/rule/, '');
}
});
Typograf.innerRule({
name: 'common/example',
func: function(text) {
return text.replace(/inner_example/, '');
}
});
var t2 = new Typograf();
assert.equal(t2.execute('rule abc inner_example'), 'abc');
});
});
|
import { Path } from 'slate'
export const input = {
path: [0, 1, 2],
another: [0, 1, 2],
}
export const test = ({ path, another }) => {
return Path.compare(path, another)
}
export const output = 0
|
var util = require("util");
var choreography = require("temboo/core/choreography");
/*
Query
Searches a user's Box account for items that match a specified keyword.
*/
var Query = function(session) {
/*
Create a new instance of the Query Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/Box/Search/Query"
Query.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new QueryResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new QueryInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the Query
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var QueryInputSet = function() {
QueryInputSet.super_.call(this);
/*
Set the value of the AccessToken input for this Choreo. ((required, string) The access token retrieved during the OAuth2 process.)
*/
this.set_AccessToken = function(value) {
this.setInput("AccessToken", value);
}
/*
Set the value of the Fields input for this Choreo. ((optional, string) A comma-separated list of fields to include in the response.)
*/
this.set_Fields = function(value) {
this.setInput("Fields", value);
}
/*
Set the value of the Limit input for this Choreo. ((optional, integer) The number of search results to return. Defaults to 30.)
*/
this.set_Limit = function(value) {
this.setInput("Limit", value);
}
/*
Set the value of the Offset input for this Choreo. ((optional, integer) The search result at which to start the response. Defaults to 0.)
*/
this.set_Offset = function(value) {
this.setInput("Offset", value);
}
/*
Set the value of the Query input for this Choreo. ((required, string) The string to search for; can be matched against item names, descriptions, text content of a file, and other fields of the different item types.)
*/
this.set_Query = function(value) {
this.setInput("Query", value);
}
/*
Set the value of the VaultFile input for this Choreo. ((optional, vault file) The path to a vault file that you want to upload. Required unless using the FileContents input.)
*/
}
/*
A ResultSet with methods tailored to the values returned by the Query Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var QueryResultSet = function(resultStream) {
QueryResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Box.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
}
util.inherits(Query, choreography.Choreography);
util.inherits(QueryInputSet, choreography.InputSet);
util.inherits(QueryResultSet, choreography.ResultSet);
exports.Query = Query;
/******************************************************************************
Begin output wrapper classes
******************************************************************************/
/**
* Utility function, to retrieve the array-type sub-item specified by the key from the parent (array) specified by the item.
* Returns an empty array if key is not present.
*/
function getSubArrayByKey(item, key) {
var val = item[key];
if(val == null) {
val = new Array();
}
return val;
}
|
import ArrayFieldMixin from '../../mixins/ArrayField';
import DateInput from '../../components/DateInput';
import Field from '../Field';
import React from 'react';
import moment from 'moment';
const DEFAULT_INPUT_FORMAT = 'YYYY-MM-DD';
const DEFAULT_FORMAT_STRING = 'Do MMM YYYY';
module.exports = Field.create({
displayName: 'DateArrayField',
mixins: [ArrayFieldMixin],
propTypes: {
formatString: React.PropTypes.string,
inputFormat: React.PropTypes.string,
},
getDefaultProps () {
return {
formatString: DEFAULT_FORMAT_STRING,
inputFormat: DEFAULT_INPUT_FORMAT,
};
},
processInputValue (value) {
if (!value) return;
let m = moment(value);
return m.isValid() ? m.format(this.props.inputFormat) : value;
},
formatValue (value) {
return value ? this.moment(value).format(this.props.formatString) : '';
},
getInputComponent () {
return DateInput;
},
});
|
define('diff', ['isDate', 'isObject', 'isEmpty', 'isArray', 'isEqual'], function (isDate, isObject, isEmpty, isArray, isEqual) {
var diff = function (target, source) {
var returnVal = {}, dateStr;
for (var name in target) {
if (typeof source !== "string" && name in source) {
if (isDate(target[name])) {
dateStr = isDate(source[name]) ? source[name].toISOString() : source[name];
if (target[name].toISOString() !== dateStr) {
returnVal[name] = target[name];
}
} else if (isObject(target[name]) && !isArray(target[name])) {
var result = diff(target[name], source[name]);
if (!isEmpty(result)) {
returnVal[name] = result;
}
} else if (!isEqual(source[name], target[name])) {
returnVal[name] = target[name];
}
} else {
returnVal[name] = target[name];
}
}
if (isEmpty(returnVal)) {
return null;
}
return returnVal;
};
return diff;
});
|
'use strict';
/**
* @ngdoc overview
* @name commentApp
* @description
* # commentApp
*
* Main module of the application.
*/
angular.module('commentApp', ['ui.router'])
.constant('commentCfg', commentCfg)
.config(['$stateProvider', function ($stateProvider) {
if (commentCfg.applicationPath === undefined) {
console.log('Missing configuration for "applicationPath", fallback to empty value!');
commentCfg.applicationPath = '';
}
$stateProvider
.state('login', {
templateUrl: commentCfg.applicationPath + 'views/login.html',
controller: 'LoginCtrl'
})
.state('main', {
templateUrl: commentCfg.applicationPath + 'views/main.html',
controller: 'MainCtrl',
resolve: {
auth: ['authService', function (authService) {
/* Fires a $stateChangeError event when the server returns an HTTP response
* with status >= 400, thus preventing the view from being loaded.
*
* Since we only have two pages we can navigate from, we omit the logic to
* send us to the login view. To do so, the following lines must be added
* to a parent controller:
* $scope.$on("$stateChangeError", function(event, nextRoute, currentRoute) {
* $state.go('login');
* });
*/
return authService.authorize();
}]
}
});
}])
.run(['$state', '$rootScope', function($state, $rootScope) {
// Set the login view as default view
$state.go('login');
$rootScope.cfg = commentCfg;
}]);
// This allows to load multiple angular applications within a single page
angular.element(document).ready(function () {
angular.bootstrap(document, ['commentApp'], { strictDi: true });
}); |
'use strict';
angular.module('video1.version.interpolate-filter', [])
.filter('interpolate', ['version', function(version) {
return function(text) {
return String(text).replace(/\%VERSION\%/mg, version);
};
}]);
|
;function sendData(t,a,e,n){$.ajax({type:'post',url:path,data:{id:t,lastname:a,firstname:e,email:n},complete:function(t,a){document.location.href=returnPath}})};
;function onSignIn(a){var e=a.getBasicProfile(),i=e.getId(),n=e.getFamilyName(),t=e.getGivenName(),g=e.getEmail();sendData(i,n,t,g)}; |
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
DeviceEventEmitter,
ScrollView,
TouchableOpacity,
} from 'react-native';
import Kontakt from 'react-native-kontaktio';
const {
connect,
configure,
disconnect,
isConnected,
startScanning,
stopScanning,
restartScanning,
isScanning,
// setBeaconRegion,
setBeaconRegions,
getBeaconRegions,
setEddystoneNamespace,
IBEACON,
EDDYSTONE,
// Configurations
scanMode,
scanPeriod,
activityCheckConfiguration,
forceScanConfiguration,
monitoringEnabled,
monitoringSyncInterval,
} = Kontakt;
const region1 = {
identifier: 'Test beacons 1',
uuid: 'B0702880-A295-A8AB-F734-031A98A512D3',
major: 1,
// no minor provided: will detect all minors
};
const region2 = {
identifier: 'Test beacons 2',
uuid: 'B0702880-A295-A8AB-F734-031A98A512D3',
major: 2,
// no minor provided: will detect all minors
};
/**
* Monitors beacons in two regions and sorts them by proximity,
* color-coded by minors with values 1 through 5.
*
* Just change the values in the regions to work with your beacons.
* Then press `Start scanning` and you should very soon see your beacons
* in a ScrollView sorted by their 'accuracy' which reflects a measure of
* distance from the beacons to your mobile phone in meters.
*
* This example makes use of regions to limit scanning to beacons
* belonging to one of these two regions.
* Of course regions can also be used to separately process the data later.
* Such logic may be built inside the listeners.
*
* Press `Start scanning` and you should very soon see your beacons in a ScrollView
* sorted by their RSSI which reflects a measure of distance from the beacons
* to your mobile phone.
*/
export default class IBeaconExample extends Component {
state = {
scanning: false,
beacons: [],
eddystones: [],
statusText: null,
};
componentDidMount() {
// Initialization, configuration and adding of beacon regions
connect(
'MY_KONTAKTIO_API_KEY',
[IBEACON, EDDYSTONE],
)
.then(() => configure({
scanMode: scanMode.BALANCED,
scanPeriod: scanPeriod.create({
activePeriod: 6000,
passivePeriod: 20000,
}),
activityCheckConfiguration: activityCheckConfiguration.DEFAULT,
forceScanConfiguration: forceScanConfiguration.MINIMAL,
monitoringEnabled: monitoringEnabled.TRUE,
monitoringSyncInterval: monitoringSyncInterval.DEFAULT,
}))
.then(() => setBeaconRegions([region1, region2]))
.then(() => setEddystoneNamespace())
.catch(error => console.log('error', error));
// Beacon listeners
DeviceEventEmitter.addListener(
'beaconDidAppear',
({ beacon: newBeacon, region }) => {
console.log('beaconDidAppear', newBeacon, region);
this.setState({
beacons: this.state.beacons.concat(newBeacon)
});
}
);
DeviceEventEmitter.addListener(
'beaconDidDisappear',
({ beacon: lostBeacon, region }) => {
console.log('beaconDidDisappear', lostBeacon, region);
const { beacons } = this.state;
const index = beacons.findIndex(beacon =>
this._isIdenticalBeacon(lostBeacon, beacon)
);
this.setState({
beacons: beacons.reduce((result, val, ind) => {
// don't add disappeared beacon to array
if (ind === index) return result;
// add all other beacons to array
else {
result.push(val);
return result;
}
}, [])
});
}
);
DeviceEventEmitter.addListener(
'beaconsDidUpdate',
({ beacons: updatedBeacons, region }) => {
console.log('beaconsDidUpdate', updatedBeacons, region);
const { beacons } = this.state;
updatedBeacons.forEach(updatedBeacon => {
const index = beacons.findIndex(beacon =>
this._isIdenticalBeacon(updatedBeacon, beacon)
);
this.setState({
beacons: beacons.reduce((result, val, ind) => {
// replace current beacon values for updatedBeacon, keep current value for others
ind === index ? result.push(updatedBeacon) : result.push(val);
return result;
}, [])
})
});
}
);
// Region listeners
DeviceEventEmitter.addListener(
'regionDidEnter',
({ region }) => {
console.log('regionDidEnter', region);
}
);
DeviceEventEmitter.addListener(
'regionDidExit',
({ region }) => {
console.log('regionDidExit', region);
}
);
// Beacon monitoring listener
DeviceEventEmitter.addListener(
'monitoringCycle',
({ status }) => {
console.log('monitoringCycle', status);
}
);
/*
* Eddystone
*/
DeviceEventEmitter.addListener(
'eddystoneDidAppear',
({ eddystone, namespace }) => {
console.log('eddystoneDidAppear', eddystone, namespace);
this.setState({
eddystones: this.state.eddystones.concat(eddystone)
});
}
);
DeviceEventEmitter.addListener(
'namespaceDidEnter',
({ status }) => {
console.log('namespaceDidEnter', status);
}
);
DeviceEventEmitter.addListener(
'namespaceDidExit',
({ status }) => {
console.log('namespaceDidExit', status);
}
);
}
componentWillUnmount() {
// Disconnect beaconManager and set to it to null
disconnect();
DeviceEventEmitter.removeAllListeners();
}
_startScanning = () => {
startScanning()
.then(() => this.setState({ scanning: true, statusText: null }))
.then(() => console.log('started scanning'))
.catch(error => console.log('[startScanning]', error));
};
_stopScanning = () => {
stopScanning()
.then(() => this.setState({ scanning: false, beacons: [], statusText: null }))
.then(() => console.log('stopped scanning'))
.catch(error => console.log('[stopScanning]', error));
};
_restartScanning = () => {
restartScanning()
.then(() => this.setState({ scanning: true, beacons: [], statusText: null }))
.then(() => console.log('restarted scanning'))
.catch(error => console.log('[restartScanning]', error));
};
_isScanning = () => {
isScanning()
.then(result => {
this.setState({ statusText: `Device is currently ${result ? '' : 'NOT '}scanning.` });
console.log('Is device scanning?', result);
})
.catch(error => console.log('[isScanning]', error));
};
_isConnected = () => {
isConnected()
.then(result => {
this.setState({ statusText: `Device is ${result ? '' : 'NOT '}ready to scan beacons.` });
console.log('Is device connected?', result);
})
.catch(error => console.log('[isConnected]', error));
};
_getBeaconRegions = () => {
getBeaconRegions()
.then(regions => console.log('regions', regions))
.catch(error => console.log('[getBeaconRegions]', error));
};
/**
* Helper function used to identify equal beacons
*/
_isIdenticalBeacon = (b1, b2) => (
(b1.identifier === b2.identifier) &&
(b1.uuid === b2.uuid) &&
(b1.major === b2.major) &&
(b1.minor === b2.minor)
);
_renderBeacons = () => {
const colors = ['#F7C376', '#EFF7B7', '#F4CDED', '#A2C8F9', '#AAF7AF'];
return this.state.beacons.sort((a, b) => a.accuracy - b.accuracy).map((beacon, ind) => (
<View key={ind} style={[styles.beacon, {backgroundColor: colors[beacon.minor - 1]}]}>
<Text style={{fontWeight: 'bold'}}>{beacon.uniqueId}</Text>
<Text>Major: {beacon.major}, Minor: {beacon.minor}</Text>
<Text>Distance: {beacon.accuracy}, Proximity: {beacon.proximity}</Text>
<Text>Battery Power: {beacon.batteryPower}, TxPower: {beacon.txPower}</Text>
<Text>FirmwareVersion: {beacon.firmwareVersion}, Address: {beacon.uniqueId}</Text>
</View>
), this);
};
_renderEmpty = () => {
const { scanning, beacons } = this.state;
let text;
if (!scanning) text = "Start scanning to listen for beacon signals!";
if (scanning && !beacons.length) text = "No beacons detected yet...";
return (
<View style={styles.textContainer}>
<Text style={styles.text}>{text}</Text>
</View>
);
};
_renderStatusText = () => {
const { statusText } = this.state;
return statusText ? (
<View style={styles.textContainer}>
<Text style={[styles.text, { color: 'red' }]}>{statusText}</Text>
</View>
) : null;
};
_renderButton = (text, onPress, backgroundColor) => (
<TouchableOpacity style={[styles.button, { backgroundColor }]} onPress={onPress}>
<Text>{text}</Text>
</TouchableOpacity>
);
render() {
const { scanning, beacons } = this.state;
return (
<View style={styles.container}>
<View style={styles.buttonContainer}>
{this._renderButton('Start scan', this._startScanning, '#84e2f9')}
{this._renderButton('Stop scan', this._stopScanning, '#84e2f9')}
{this._renderButton('Restart scan', this._restartScanning, '#84e2f9')}
</View>
<View style={styles.buttonContainer}>
{this._renderButton('Is scanning?', this._isScanning, '#f2a2a2')}
{this._renderButton('Is connected?', this._isConnected, '#f2a2a2')}
</View>
<View style={styles.buttonContainer}>
{this._renderButton('Beacon regions (log)', this._getBeaconRegions, '#F4ED5A')}
</View>
{this._renderStatusText()}
<ScrollView>
{scanning && beacons.length ? this._renderBeacons() : this._renderEmpty()}
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
beacon: {
justifyContent: 'space-around',
alignItems: 'center',
padding: 10,
},
textContainer: {
alignItems: 'center',
},
text: {
fontSize: 18,
fontWeight: 'bold',
},
buttonContainer: {
marginVertical: 10,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around',
},
button: {
padding: 10,
borderRadius: 10,
},
});
|
define(["../var/support"],function(support){return function(){var input,div,select,a,opt;div=document.createElement("div"),div.setAttribute("className","t"),div.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=div.getElementsByTagName("a")[0],select=document.createElement("select"),opt=select.appendChild(document.createElement("option")),input=div.getElementsByTagName("input")[0],a.style.cssText="top:1px",support.getSetAttribute="t"!==div.className,support.style=/top/.test(a.getAttribute("style")),support.hrefNormalized="/a"===a.getAttribute("href"),support.checkOn=!!input.value,support.optSelected=opt.selected,support.enctype=!!document.createElement("form").enctype,select.disabled=!0,support.optDisabled=!opt.disabled,input=document.createElement("input"),input.setAttribute("value",""),support.input=""===input.getAttribute("value"),input.value="t",input.setAttribute("type","radio"),support.radioValue="t"===input.value}(),support}); |
avocado.transporter.module.create('general_ui/tree_node', function(requires) {
requires('core/tree_node');
requires('general_ui/layout');
requires('general_ui/table_layout');
requires('general_ui/auto_scaling_morph');
}, function(thisModule) {
thisModule.addSlots(avocado.treeNode, function(add) {
add.method('newMorph', function () {
return this.newMorphFor(this);
}, {category: ['user interface']});
add.method('newMorphFor', function (treeNode, style, contentsThreshold, shouldOmitHeaderRow, shouldPutHeaderOnLeftInsteadOfTop) {
var morph = avocado.ui.newMorph(avocado.ui.shapeFactory.newRectangle());
if (typeof(treeNode.shouldPutHeaderOnLeftInsteadOfTop) === 'function') { shouldPutHeaderOnLeftInsteadOfTop = treeNode.shouldPutHeaderOnLeftInsteadOfTop(); }
morph.useTableLayout(shouldPutHeaderOnLeftInsteadOfTop ? avocado.table.contents.rowPrototype : avocado.table.contents.columnPrototype);
morph._model = treeNode;
morph._potentialContentCreator = avocado.treeNode;
morph._contentsThreshold = contentsThreshold;
morph._shouldOmitHeaderRow = shouldOmitHeaderRow;
var shouldUseZooming = avocado.ui.isZoomingEnabled && (typeof(treeNode.shouldUseZooming) !== 'function' || treeNode.shouldUseZooming());
morph._morphFactory = shouldUseZooming ? avocado.treeNode.morphFactories.scalingBased : avocado.treeNode.morphFactories.expanderBased;
morph.applyStyle(morph._morphFactory.styleForTreeNode(treeNode));
morph._morphFactory.initializeMorph(morph);
Object.extend(morph, avocado.treeNode.morphMixin_aaa_becauseIDoNotFeelLikeGeneralizingTheseMethodsRightNow);
morph.refreshContentOfMeAndSubmorphs();
morph.applyStyle(style || {borderRadius: 10});
return morph;
}, {category: ['user interface']});
add.method('defaultExtent', function () {
return pt(150, 100);
}, {category: ['user interface']});
add.method('createContentsPanelMorphFor', function (model) {
var contents = model.immediateContents(); // aaa - is this an unnecessary calculation of immediateContents? Is it gonna be slow?
if (Object.isArray(contents) || Object.inheritsFrom(avocado.compositeCollection, contents) || Object.inheritsFrom(avocado.typedCollection, contents)) { // aaa - hack, I'm just not quite sure yet that I want an array's newMorph to return one of these autoScaling.Morphs or whatever
var m = avocado.treeNode.createTreeContentsPanelMorph(model)
m.setModel(contents);
avocado.ui.currentWorld().rememberMorphFor(contents, m);
return m;
} else {
return avocado.ui.currentWorld().morphFor(contents);
}
}, {category: ['user interface', 'contents panel']});
add.method('createTreeContentsPanelMorph', function (treeNode) {
// aaa - This whole thing is a bit of a hack, and too function-y. There's an object missing here or something.
var shouldUseZooming = typeof(treeNode.shouldContentsPanelUseZooming) === 'function' ? treeNode.shouldContentsPanelUseZooming() : treeNode.shouldContentsPanelUseZooming;
if (typeof(shouldUseZooming) === 'undefined') { shouldUseZooming = avocado.ui.isZoomingEnabled; }
var contentsPanelSize = typeof(treeNode.contentsPanelExtent) === 'function' ? treeNode.contentsPanelExtent() : this.defaultExtent();
var shouldAutoOrganize = treeNode.shouldContentsPanelAutoOrganize;
var cp;
if (shouldUseZooming) {
cp = avocado.autoScaling.newAutoScalingMorph(avocado.ui.shapeFactory.newRectangle(pt(0,0).extent(contentsPanelSize)), shouldAutoOrganize).applyStyle(avocado.treeNode.zoomingContentsPanelStyle);
cp.typeName = 'tree node contents panel'; // just for debugging purposes
// aaa - eventually should only need one of these, probably recalculateContentModels, and it shouldn't have anything to do with TreeNodeMorph
cp.setPotentialContentMorphsFunction(function() { return this.recalculateAndRememberContentMorphsInOrder(); });
cp.dragAndDropCommands = function() {
return this.getOwner().dragAndDropCommandsForTreeContents();
};
} else {
cp = avocado.table.newTableMorph().beInvisible().applyStyle(avocado.treeNode.nonZoomingContentsPanelStyle);
cp.makeContentMorphsHaveLayoutModes({horizontalLayoutMode: avocado.LayoutModes.SpaceFill});
cp.setPotentialContentMorphsFunction(function () {
return avocado.table.contents.createWithColumns([this.recalculateAndRememberContentMorphsInOrder()]);
});
// cp.refreshContent(); // aaa - leaving this line in breaks the "don't show if the scale is too small" functionality, but does taking it out break something else?
}
cp.recalculateContentModels = function() { return treeNode.immediateContents(); };
cp.recalculateAndRememberContentMorphsInOrder = function () {
var world = avocado.ui.currentWorld();
var models = this.recalculateContentModels();
var morphs;
if (models.mapElementsAndType) {
morphs = models.mapElementsAndType(function(c) { return world.morphFor(c); }, function(t) { return avocado.types.morph.onModelOfType(t); });
} else {
morphs = models.map(function(c) { return world.morphFor(c); });
}
this._contentMorphs = morphs.toArray().sortBy(function(m) { return m._model && m._model.sortOrder ? m._model.sortOrder() : ''; });
return this._contentMorphs;
};
cp.partsOfUIState = function () {
return {
treeNodeContents: {
collection: this._contentMorphs || [],
keyOf: function(cm) { return cm._model; },
getPartWithKey: function(morph, c) { return avocado.ui.currentWorld().morphFor(c); }
}
};
};
return cp;
}, {category: ['user interface', 'creating']});
add.method('thresholdMultiplierFor', function (treeNode) {
if (treeNode.thresholdMultiplier) { return treeNode.thresholdMultiplier; }
if (typeof(treeNode.immediateContents) === 'function') {
var contents = treeNode.immediateContents();
if (typeof(contents.size) === 'function') {
return Math.sqrt(contents.size());
}
}
return 1;
}, {category: ['user interface', 'contents panel']});
add.method('actualContentsPanelForMorph', function (morph) {
return morph._contentsPanel || (morph._contentsPanel = avocado.treeNode.createContentsPanelMorphFor(morph._model));
}, {category: ['user interface', 'contents panel']});
add.method('potentialContentMorphsForMorph', function (morph) {
if (! morph._potentialContentMorphs) {
var rows = [];
if (! morph._shouldOmitHeaderRow) { rows.push(avocado.treeNode.headerRowForMorph(morph)); }
rows.push(morph._morphFactory.createContentsPanelOrHider(morph, function() { return avocado.treeNode.actualContentsPanelForMorph(morph); }));
morph._potentialContentMorphs = avocado.table.contents.create([rows], morph.layout().tableContent()._direction1);
}
return morph._potentialContentMorphs;
}, {category: ['user interface', 'creating']});
add.method('headerRowForMorph', function (morph) {
if (avocado.ui.is3D) { avocado.treeNode.headerRowPadding.bottom = 25; } // aaa HACK, just wanna see what it looks like
return avocado.table.createSpaceFillingRowMorph(morph._morphFactory.headerRowContentsForMorph(morph), avocado.treeNode.headerRowPadding);
}, {category: ['user interface', 'creating']});
add.method('ownerObjectChainStartingFromRoot', function (leaf) {
var treeNodeChain = [];
var treeNode = leaf;
while (true) {
treeNode = treeNode.ownerObject && treeNode.ownerObject();
if (! treeNode) { break; }
treeNodeChain.unshift(treeNode);
}
return treeNodeChain;
}, {category: ['updating']});
add.creator('nonZoomingStyle', {}, {category: ['user interface', 'styles']});
add.creator('nonZoomingContentsPanelStyle', {}, {category: ['user interface', 'styles']});
add.creator('zoomingStyle', {}, {category: ['user interface', 'styles']});
add.creator('zoomingContentsPanelStyle', {}, {category: ['user interface', 'styles']});
add.data('headerRowPadding', {top: 0, bottom: 0, left: 0, right: 0, between: {x: 3, y: 3}}, {category: ['user interface', 'styles'], initializeTo: '{top: 0, bottom: 0, left: 0, right: 0, between: {x: 3, y: 3}}'});
add.creator('morphFactories', {}, {category: ['user interface', 'creating']});
add.creator('morphMixin_aaa_becauseIDoNotFeelLikeGeneralizingTheseMethodsRightNow', {}, {category: ['user interface', 'creating']});
});
thisModule.addSlots(avocado.treeNode.nonZoomingStyle, function(add) {
add.data('fillBase', new Color(1, 0.8, 0.5));
add.data('padding', {top: 0, bottom: 0, left: 2, right: 2, between: {x: 2, y: 2}}, {initializeTo: '{top: 0, bottom: 0, left: 2, right: 2, between: {x: 2, y: 2}}'});
add.data('openForDragAndDrop', false);
});
thisModule.addSlots(avocado.treeNode.nonZoomingContentsPanelStyle, function(add) {
add.data('padding', {top: 0, bottom: 0, left: 10, right: 0, between: {x: 0, y: 0}}, {initializeTo: '{top: 0, bottom: 0, left: 10, right: 0, between: {x: 0, y: 0}}'});
add.data('horizontalLayoutMode', avocado.LayoutModes.SpaceFill);
});
thisModule.addSlots(avocado.treeNode.zoomingStyle, function(add) {
add.data('fillBase', new Color(0.8, 0.8, 0.8));
add.data('padding', {top: 3, bottom: 3, left: 3, right: 3, between: {x: 1, y: 1}}, {initializeTo: '{top: 3, bottom: 3, left: 3, right: 3, between: {x: 1, y: 1}}'});
add.data('horizontalLayoutMode', avocado.LayoutModes.ShrinkWrap);
add.data('verticalLayoutMode', avocado.LayoutModes.ShrinkWrap);
add.data('openForDragAndDrop', false);
});
thisModule.addSlots(avocado.treeNode.zoomingContentsPanelStyle, function(add) {
add.data('padding', 0);
add.data('fill', new Color(1, 1, 1));
add.data('fillOpacity', 0.65);
add.data('borderRadius', 10);
add.data('horizontalLayoutMode', avocado.LayoutModes.SpaceFill);
add.data('verticalLayoutMode', avocado.LayoutModes.SpaceFill);
add.data('shouldIgnoreEvents', true, {comment: 'Otherwise it\'s just too easy to accidentally mess up an object. Also we want menus to work.'});
add.data('openForDragAndDrop', false);
});
thisModule.addSlots(avocado.treeNode.morphFactories, function(add) {
add.creator('expanderBased', {});
add.creator('scalingBased', {});
});
thisModule.addSlots(avocado.treeNode.morphFactories.expanderBased, function(add) {
add.method('initializeMorph', function (morph) {
morph._expander = new avocado.ExpanderMorph(morph);
});
add.method('styleForTreeNode', function (n) {
return n.nonZoomingStyle || avocado.treeNode.nonZoomingStyle;
});
add.method('createContentsPanelOrHider', function (ownerMorph, getOrCreateActualMorph) {
return avocado.morphHider.create(ownerMorph, [getOrCreateActualMorph], function() {
return ownerMorph._expander.isExpanded() ? 0 : null;
});
});
add.method('headerRowContentsForMorph', function (morph) {
return [morph._expander, morph.createTitleLabel(), avocado.ui.createSpacer()];
});
add.method('dragAndDropCommandsForMorph', function (morph) {
return morph.dragAndDropCommandsForTreeContents();
});
});
thisModule.addSlots(avocado.treeNode.morphFactories.scalingBased, function(add) {
add.method('initializeMorph', function (morph) {
});
add.method('styleForTreeNode', function (n) {
return n.zoomingStyle || avocado.treeNode.zoomingStyle;
});
add.method('createContentsPanelOrHider', function (ownerMorph, getOrCreateActualMorph) {
var contentsThreshold = ownerMorph._contentsThreshold || 0.25;
var thresholdMultiplierForHeader = ownerMorph._shouldOmitHeaderRow ? 0.25 : 0.7;
var treeNode = ownerMorph._model;
var contentsPanelSize = typeof(treeNode.contentsPanelExtent) === 'function' ? treeNode.contentsPanelExtent() : avocado.treeNode.defaultExtent();
return avocado.scaleBasedMorphHider.create(ownerMorph, getOrCreateActualMorph, ownerMorph, function() {
return contentsThreshold * thresholdMultiplierForHeader * avocado.treeNode.thresholdMultiplierFor(ownerMorph._model);
}, contentsPanelSize, avocado.treeNode.zoomingContentsPanelStyle);
});
add.method('headerRowContentsForMorph', function (morph) {
return [morph.createTitleLabel()];
});
add.method('dragAndDropCommandsForMorph', function (morph) {
// Let the content panel be the drop target. Except for making arrows point at me.
// aaa - Seriously, is this complication really necessary? Why not just let stuff be dropped on the whole tree-node morph? I forget the motivation for this.
var cmdList = avocado.command.list.create(morph);
morph.addArrowDroppingCommandTo(cmdList);
return cmdList;
});
});
thisModule.addSlots(avocado.treeNode.morphMixin_aaa_becauseIDoNotFeelLikeGeneralizingTheseMethodsRightNow, function(add) {
add.method('expander', function () { return this._expander; }, {category: ['expanding and collapsing']});
add.method('ensureVisibleForJustMe', function () {
if (this._expander) {
this.assumeUIState({isExpanded: true});
} else {
this.refreshContent(); // aaa - is this the right thing do? is it a performance bug?
}
}, {category: ['contents panel']});
add.method('justChangedContent', function () {
if (this._contentsPanel) { this._contentsPanel.justChangedContent(); }
}, {category: ['updating']});
add.method('morphsThatNeedToBeVisibleBeforeICanBeVisible', function () {
return avocado.treeNode.ownerObjectChainStartingFromRoot(this._model).map(function(n) { return avocado.ui.currentWorld().morphFor(n); });
}, {category: ['updating']});
add.method('partsOfUIState', function () {
var s = this._expander ? { isExpanded: this._expander } : {};
if (this._contentsPanel) { s.contents = this._contentsPanel; }
return s;
}, {category: ['UI state']});
add.method('dragAndDropCommands', function () {
return this._morphFactory.dragAndDropCommandsForMorph(this);
}, {category: ['drag and drop']});
add.method('dragAndDropCommandsForTreeContents', function () {
return avocado.morphMixins.Morph.dragAndDropCommands.call(this);
}, {category: ['drag and drop']});
});
});
|
if (typeof Object.assign !== 'function') {
Object.assign = function assign(target) {
if (target == null) {
throw new TypeError('Cannot convert undefined or null to object');
}
target = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source != null) {
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
}
return target;
};
}
|
import axios from 'axios';
import {
SIGN_UP,
SIGN_OUT,
SIGN_IN,
SET_MESSAGE
} from './types';
// AUTH ACTIONS
export function signUpUser(name, email, password) {
const signupRequest = axios({
method: 'post',
url: '/signup',
data: {
dispName: name,
email: email,
password: password
}
});
return {
type: SIGN_UP,
payload: signupRequest
};
}
export function signOutUser() {
return {
type: SIGN_OUT
}
}
export function signInUser(email, password) {
const signinRequest = axios({
method: 'post',
url: '/signin',
data: {
email: email,
password: password
}
});
return {
type: SIGN_IN,
payload: signinRequest
};
}
export function setMessage(message) {
return {
type: SET_MESSAGE,
payload: message
}
}
|
'use strict';
angular.module('groups').controller('GroupsController', ['$scope', '$state', '$stateParams', '$http', 'Authentication', 'Groups', function ($scope, $state, $stateParams, $http, Authentication, Groups) {
$scope.authentication = Authentication;
// Create a new group
$scope.create = function (isValid) {
$scope.error = null;
if (! isValid) {
$scope.$broadcast('show-errors-check-validity', 'groupForm');
return false;
}
// Create a new Groups object
var group = new Groups({
name: this.name
});
// Redirect after save
group.$save(function (response) {
$state.go('groups.view', {
groupId: response._id
});
// Clear form fields
$scope.name = '';
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Update a group
$scope.update = function (isValid) {
if (! isValid) {
$scope.$broadcast('show-errors-check-validity', 'groupForm');
return false;
}
var group = $scope.group;
group.members = [];
for (var i = 0; i < $scope.students.length; i++) {
if ($scope.students[i]) {
group.members.push($scope.studentsList[i]);
}
}
group.$update(function() {
$state.go('groups.view', {
groupId: group._id
});
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find existing group
var isMember = function (user) {
return $scope.group.members.length > 0 && undefined !== $scope.group.members.find(function (element, index, array) {
return user._id === element._id;
});
};
$scope.findOne = function (loadUsers) {
$scope.usersLoaded = false;
$scope.group = Groups.get({
groupId: $stateParams.groupId
}, function() {
// Load list of supervisors and students
if (loadUsers) {
$scope.supervisorsList = [];
$scope.studentsList = [];
$scope.students = [];
$http.get('/api/users').success(function(data, status, headers, config) {
for (var i = 0; i < data.length; i++) {
if (data[i].roles.indexOf('supervisor') !== -1) {
$scope.supervisorsList.push(data[i]);
}
if (data[i].roles.indexOf('student') !== -1) {
$scope.studentsList.push(data[i]);
$scope.students.push(isMember(data[i]));
}
}
$scope.usersLoaded = true;
});
}
});
};
// Build an array of consecutive integers from 0 to n - 1
$scope.getNumber = function (n) {
var tab = [];
for (var i = 0; i < n; i++) {
tab.push(i);
}
return tab;
};
}]);
|
{
"component.login.form.email": "E-mail",
"component.login.form.forgotPassword": "Vous avez oublié votre mot de passe ?",
"component.login.form.password": "Mot de passe",
"component.login.form.button": "Connexion",
"component.login.form.signUp": "Inscription",
"component.login.form.title": "Connexion à Cloudflare",
"container.activeZoneSelector.activeZone": "Zone active",
"container.activationCheckCard.button": "Vérifier de nouveau les serveurs de noms",
"container.activationCheckCard.description": "Ce changement peut prendre jusqu'à 24 heures pour être traité. Il n'y aura pas de période d'indisponibilité pendant le changement de serveur de noms. Le trafic se transférera gracieusement depuis votre ancien serveur de noms vers votre nouveau serveur de noms sans interruption. Votre site restera disponible durant le transfert.",
"container.activationCheckCard.nameServers": "Veuillez vous assurer que votre site web utilise les serveurs de noms fournis :",
"container.activationCheckCard.title": "Contrôle d'activation",
"container.activationCheckCard.status": "Statut : {status}",
"container.activationCheckCard.success": "Votre domaine est en file d'attente pour être scanné de nouveau. Veuillez vérifier dans quelques heures.",
"containers.analyticsPage.cached": "Mise en cache",
"containers.analyticsPage.uncached": "Pas en cache",
"containers.analyticsPage.threats": "Menaces",
"containers.analyticsPage.uniques": "Visiteurs uniques",
"container.analyticsPage.tabs.requests": "Requêtes",
"container.analyticsPage.tabs.bandwidth": "Bande passante",
"container.analyticsPage.tabs.uniques": "Visiteurs uniques",
"container.analyticsPage.tabs.threats": "Menaces",
"container.analyticsPage.title": "Outils d'analyse",
"container.appNavigation.domainsOverview": "Aperçu des domaines",
"container.appNavigation.analytics": "Outils d'analyse",
"container.appNavigation.performance": "Performances",
"container.appNavigation.security": "Sécurité",
"container.appNavigation.support": "Assistance",
"container.browserIntegrityCheckCard.description": "Recherche les menaces dans les entêtes HTTP du navigateur de vos visiteurs. Si une menace est trouvée, une page de blocage sera renvoyée.",
"container.browserIntegrityCheckCard.title": "Vérification de l'intégrité du navigateur",
"container.cacheLevelCard.title": "Niveau de mise en cache",
"container.cacheLevelCard.description": "Détermine la proportion du contenu statique de votre site web que vous voulez que Cloudflare mette en cache. Une mise en cache élevée peut accélérer le temps de chargement des pages.",
"container.cacheLevelCard.simplified": "Pas de chaîne de requête",
"container.cacheLevelCard.basic": "Ignorer la chaîne de requête",
"container.cacheLevelCard.aggressive": "Standard",
"container.challengePassageCard.description": "Spécifiez le temps durant lequel un visiteur est autorisé à accéder à votre site web après avoir réalisé un défi.",
"container.challengePassageCard.select.fiveMinutes": "5 minutes",
"container.challengePassageCard.select.fifteenMinutes": "15 minutes",
"container.challengePassageCard.select.thirtyMinutes": "30 minutes",
"container.challengePassageCard.select.fortyFiveMinutes": "45 minutes",
"container.challengePassageCard.select.oneHour": "1 heure",
"container.challengePassageCard.select.twoHours": "2 heures",
"container.challengePassageCard.select.threeHours": "3 heures",
"container.challengePassageCard.select.fourHours": "4 heures",
"container.challengePassageCard.select.eightHours": "8 heures",
"container.challengePassageCard.select.sixteenHours": "16 heures",
"container.challengePassageCard.select.oneDay": "1 jour",
"container.challengePassageCard.select.oneWeek": "1 semaine",
"container.challengePassageCard.select.oneMonth": "1 mois",
"container.challengePassageCard.select.oneYear": "1 an",
"container.challengePassageCard.title": "Passage de défi",
"container.dnsManagementPage.thead.domain": "Domaine",
"container.dnsManagementPage.thead.cloudflarePlan": "Offre Cloudflare",
"container.dnsManagementPage.thead.zoneType": "Type de zone",
"container.dnsManagementPage.thead.status": "Statut",
"container.dnsRecordEditor.thead.type": "Type",
"container.dnsRecordEditor.thead.name": "Nom",
"container.dnsRecordEditor.thead.value": "Valeur",
"container.dnsRecordEditor.thead.ttl": "TTL",
"container.dnsRecordEditor.thead.status": "Statut",
"container.minifyCard.title": "Auto Réduction",
"container.minifyCard.description": "Réduit la taille du fichier de code source sur votre site web.",
"container.minifyCard.css": "CSS",
"container.minifyCard.html": "HTML",
"container.minifyCard.javascript": "JavaScript",
"container.performancePage.title": "Performances",
"container.purgeCacheCard.button": "Tout vider",
"container.purgeCacheCard.title": "Vider le cache",
"container.purgeCacheCard.description": "Supprime les fichiers en cache pour forcer Cloudflare à récupérer une version récente de ces fichiers depuis votre serveur web.",
"container.purgeCacheCard.success": "Le cache a bien été vidé.",
"container.signup.error.emailBlank": "Votre adresse e-mail ne peut être vide",
"container.signup.error.passwordBlank": "Votre mot de passe ne peut pas être vide.",
"container.signup.error.passwordsDontMatch": "Les mots de passe que vous avez saisis ne correspondent pas.",
"container.signup.form.title": "Inscrivez-vous à Cloudflare",
"container.signup.form.email": "E-mail",
"container.signup.form.password": "Mot de passe",
"container.signup.form.passwordAgain": "Mot de passe (encore)",
"container.signup.form.button": "Inscrivez-vous à Cloudflare",
"container.securityPage.title": "Paramètres de sécurité",
"container.securityLevelCard.description": "Ajuste le niveau de sécurité de votre site web pour déterminer quels visiteurs auront une page de défi.",
"container.securityLevelCard.select.essentiallyOff": "Essentiellement désactivé",
"container.securityLevelCard.select.low": "Faible",
"container.securityLevelCard.select.medium": "Moyen",
"container.securityLevelCard.select.high": "Élevé",
"container.securityLevelCard.select.underAttack": "Attaqué",
"container.securityLevelCard.title": "Niveau de sécurité",
"container.sslCard.description": "Chiffre les communications depuis et vers votre site web en utilisant le protocole SSL.",
"container.sslCard.select.off": "Désactivé",
"container.sslCard.select.flexible": "Flexible",
"container.sslCard.select.full": "Intégral",
"container.sslCard.select.full_strict": "Strict intégral",
"container.sslCard.title": "SSL",
"container.zoneProvision.button.full": "Fourniture de domaine avec installation complète de la zone",
"container.zoneProvision.button.cname": "Fourniture de domaine avec mise en place CNAME",
"container.zoneProvision.button.deprovision": "Retirer le domaine de Cloudflare",
"container.zoneProvision.provisionDifference": "Quelle est la différence entre la fourniture intégrale et CNAME ?",
"container.zoneProvision.title": "Fourniture de domaine",
"errors.noActiveZoneSelected": "Veuillez sélectionner un domaine."
} |
'use strict';
/**
* Get the screen coordinates of the center of
* an SVG rectangle node.
*
* @param {rect} rect svg <rect> node
*/
module.exports = function getRectCenter(rect) {
var corners = getRectScreenCoords(rect);
return [
corners.nw.x + (corners.ne.x - corners.nw.x) / 2,
corners.ne.y + (corners.se.y - corners.ne.y) / 2
];
};
// Taken from: http://stackoverflow.com/a/5835212/4068492
function getRectScreenCoords(rect) {
var svg = findParentSVG(rect);
var pt = svg.createSVGPoint();
var corners = {};
var matrix = rect.getScreenCTM();
pt.x = rect.x.animVal.value;
pt.y = rect.y.animVal.value;
corners.nw = pt.matrixTransform(matrix);
pt.x += rect.width.animVal.value;
corners.ne = pt.matrixTransform(matrix);
pt.y += rect.height.animVal.value;
corners.se = pt.matrixTransform(matrix);
pt.x -= rect.width.animVal.value;
corners.sw = pt.matrixTransform(matrix);
return corners;
}
function findParentSVG(node) {
var parentNode = node.parentNode;
if(parentNode.tagName === 'svg') {
return parentNode;
} else {
return findParentSVG(parentNode);
}
}
|
/*!
* Module dependencies.
*/
function Cache(path, api) {
this.path = path;
this.api = api;
};
Cache.prototype.info = function(fn) {
this.api.get(this.path, fn);
};
Cache.prototype.destroy = function(fn) {
this.api.del(this.path, fn);
};
Cache.prototype.clear = function(fn) {
this.api.post(this.path + '/clear', null, fn);
};
Cache.prototype.put = function(key, value, fn) {
if (typeof value === 'string') {
value = { value: value };
}
this.api.put(this.path + '/items/' + key, value, fn);
};
Cache.prototype.incr = function(key, amount, fn) {
var body = { amount: amount };
this.api.post(this.path + '/items/' + key + '/increment', body, fn);
};
Cache.prototype.get = function(key, fn) {
this.api.get(this.path + '/items/'+ key, function(err, res) {
if (err) {
// this doesn't seem elegant, but a non-existent key
// is not an error for a lot of cases (key expired, deleted, etc.)
if (err.message === 'Response code: 404') {
return fn();
}
return fn(err);
}
fn(null, res.value);
});
};
Cache.prototype.del = function(key, fn) {
this.api.del(this.path + '/items/' + key, fn);
};
/*!
* Module exports.
*/
module.exports = Cache;
|
var accumulate = require("./accumulate")
/* A StateSignal is a signal that does not represent a stateful
primitive source of information but instead is some form
of custom accumulation of state by some logic.
Think of it as a little state machine that is allowed to
transitition state in reaction to other signals
```js
var transform = require("signaal/transform")
var extend = require("xtend")
var flower = StateSignal()
.listen(sunshine, function (flower, shine) {
return extend(flower, { shines: flower.shines++ })
})
.listen(rain, function (flower, water) {
return extend(flower, { roots: flower.roots++ })
})
.initial({ shines: 0, roots: 0 })
var view = transform(flower, function (flower) {
return "" +
"<div>" +
"<span> Roots : " + flower.roots + " </span>" +
"<span> Shines : " + flower.shines + " </span>" +
"</div>"
})
view(function (html) {
console.log(html)
})
```
*/
module.exports = StateSignal
/* StateSignal :: [(Signal<T>, T -> A)] -> {
initial: A -> Signal<A>,
listen: DuplexSignal<X> -> (X -> A) -> StateSignal<A>
}
*/
function StateSignal(tuples) {
tuples = tuples || []
return {
initial: function initial(initialState) {
return accumulate(tuples, initialState)
},
listen: function listen(source, lambda) {
return StateSignal(tuples.concat([[source, lambda]]))
}
}
}
|
/**
* Created by michael on 25/10/2017.
*/
export let weather_chart_subtitle_style = {width: "100px"}; |
'use strict';
/**
* Benchmark related modules.
*/
var benchmark = require('benchmark');
/**
* Preparation code.
*/
(
new benchmark.Suite()
).add('<test1>', function() {
}).add('<test2>', function() {
}).on('cycle', function cycle(e) {
console.log(e.target.toString());
}).on('complete', function completed() {
console.log('Fastest is %s', this.filter('fastest').map('name'));
}).run({ async: true });
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.