code stringlengths 2 1.05M |
|---|
let objectify = require('./objectifier')
module.exports = function processResult (result) {
if (console && console.warn) {
result.warnings().forEach(warn => {
let source = warn.plugin || 'PostCSS'
console.warn(source + ': ' + warn.text)
})
}
return objectify(result.root)
}
|
"use strict";
var Client = require("./../lib/index");
var testAuth = require("./../testAuth.json");
var github = new Client({
debug: true,
headers: {
"Accept": "application/vnd.github.loki-preview+json"
}
});
github.authenticate({
type: "oauth",
token: testAuth["token"]
});
github.repos.updateBranchProtection({
user: "kaizensoze",
repo: "test2",
branch: "a",
required_status_checks: null,
restrictions: null
}, function(err, res) {
console.log(err, res);
});
|
/**
* A selection model that renders a column of checkboxes that can be toggled to
* select or deselect rows. The default mode for this selection model is MULTI.
*
* @example
* var store = Ext.create('Ext.data.Store', {
* fields: ['name', 'email', 'phone'],
* data: [{
* name: 'Lisa',
* email: 'lisa@simpsons.com',
* phone: '555-111-1224'
* }, {
* name: 'Bart',
* email: 'bart@simpsons.com',
* phone: '555-222-1234'
* }, {
* name: 'Homer',
* email: 'homer@simpsons.com',
* phone: '555-222-1244'
* }, {
* name: 'Marge',
* email: 'marge@simpsons.com',
* phone: '555-222-1254'
* }]
* });
*
* Ext.create('Ext.grid.Panel', {
* title: 'Simpsons',
* store: store,
* columns: [{
* text: 'Name',
* dataIndex: 'name'
* }, {
* text: 'Email',
* dataIndex: 'email',
* flex: 1
* }, {
* text: 'Phone',
* dataIndex: 'phone'
* }],
* height: 200,
* width: 400,
* renderTo: Ext.getBody(),
* selModel: {
* selType: 'checkboxmodel'
* }
* });
*
* The selection model will inject a header for the checkboxes in the first view
* and according to the {@link #injectCheckbox} configuration.
*/
Ext.define('Ext.selection.CheckboxModel', {
alias: 'selection.checkboxmodel',
extend: 'Ext.selection.RowModel',
/**
* @cfg {"SINGLE"/"SIMPLE"/"MULTI"} mode
* Modes of selection.
* Valid values are `"SINGLE"`, `"SIMPLE"`, and `"MULTI"`.
*/
mode: 'MULTI',
/**
* @cfg {Number/String} [injectCheckbox=0]
* The index at which to insert the checkbox column.
* Supported values are a numeric index, and the strings 'first' and 'last'.
*/
injectCheckbox: 0,
/**
* @cfg {Boolean} checkOnly
* True if rows can only be selected by clicking on the checkbox column, not by clicking
* on the row itself. Note that this only refers to selection via the UI, programmatic
* selection will still occur regardless.
*/
checkOnly: false,
/**
* @cfg {Boolean} showHeaderCheckbox
* Configure as `false` to not display the header checkbox at the top of the column.
* When the store is a {@link Ext.data.BufferedStore BufferedStore}, this configuration will
* not be available because the buffered data set does not always contain all data.
*/
showHeaderCheckbox: undefined,
/**
* @cfg {String} [checkSelector="x-grid-row-checker"]
* The selector for determining whether the checkbox element is clicked. This may be changed to
* allow for a wider area to be clicked, for example, the whole cell for the selector.
*/
checkSelector: '.' + Ext.baseCSSPrefix + 'grid-row-checker',
allowDeselect: true,
headerWidth: 24,
// private
checkerOnCls: Ext.baseCSSPrefix + 'grid-hd-checker-on',
tdCls: Ext.baseCSSPrefix + 'grid-cell-special ' + Ext.baseCSSPrefix + 'grid-cell-row-checker',
constructor: function() {
var me = this;
me.callParent(arguments);
// If mode is single and showHeaderCheck isn't explicity set to
// true, hide it.
if (me.mode === 'SINGLE') {
//<debug>
if (me.showHeaderCheckbox) {
Ext.Error.raise('The header checkbox is not supported for SINGLE mode selection models.');
}
//</debug>
me.showHeaderCheckbox = false;
}
},
beforeViewRender: function(view) {
var me = this,
owner,
ownerLockable = view.grid.ownerLockable;
me.callParent(arguments);
// Preserve behaviour of false, but not clear why that would ever be done.
if (me.injectCheckbox !== false) {
// The check column gravitates to the locked side unless
// the locked side is emptied, in which case it migrates to the normal side.
if (ownerLockable && !me.lockListeners) {
me.lockListeners = ownerLockable.mon(ownerLockable, {
lockcolumn: me.onColumnLock,
unlockcolumn: me.onColumnUnlock,
scope: me,
destroyable: true
});
}
// If the controlling grid is NOT lockable, there's only one chance to add the column, so add it.
// If the view is the locked one and there are locked headers, add the column.
// If the view is the normal one and we have not already added the column, add it.
if (!ownerLockable || (view.isLockedView && me.hasLockedHeader()) || (view.isNormalView && !me.column)) {
me.addCheckbox(view, true);
owner = view.ownerCt;
// Listen to the outermost reconfigure event
if (view.headerCt.lockedCt) {
owner = owner.ownerCt;
}
// Listen for reconfigure of outermost grid panel.
me.mon(view.ownerGrid, {
beforereconfigure: me.onBeforeReconfigure,
reconfigure: me.onReconfigure,
scope: me
});
}
}
},
onColumnUnlock: function(lockable, column) {
var me = this,
checkbox = me.injectCheckbox,
lockedColumns = lockable.lockedGrid.visibleColumnManager.getColumns();
// User has unlocked all columns and left only the expander column in the locked side.
if (lockedColumns.length === 1 && lockedColumns[0] === me.column) {
if (checkbox === 'first') {
checkbox = 0;
} else if (checkbox === 'last') {
checkbox = lockable.normalGrid.visibleColumnManager.getColumns().length;
}
lockable.unlock(me.column, checkbox);
}
},
onColumnLock: function(lockable, column) {
var me = this,
checkbox = me.injectCheckbox,
lockedColumns = lockable.lockedGrid.visibleColumnManager.getColumns();
// User has begun filling the empty locked side - migrate to the locked side..
if (lockedColumns.length === 1) {
if (checkbox === 'first') {
checkbox = 0;
} else if (checkbox === 'last') {
checkbox = lockable.lockedGrid.visibleColumnManager.getColumns().length;
}
lockable.lock(me.column, checkbox);
}
},
bindComponent: function(view) {
this.sortable = false;
this.callParent(arguments);
},
hasLockedHeader: function(){
var columns = this.view.ownerGrid.getVisibleColumnManager().getColumns(),
len = columns.length, i;
for (i = 0; i < len; i++) {
if (columns[i].locked) {
return true;
}
}
return false;
},
/**
* Add the header checkbox to the header row
* @private
*/
addCheckbox: function(view){
var me = this,
checkbox = me.injectCheckbox,
headerCt = view.headerCt;
// Preserve behaviour of false, but not clear why that would ever be done.
if (checkbox !== false) {
if (checkbox === 'first') {
checkbox = 0;
} else if (checkbox === 'last') {
checkbox = headerCt.getColumnCount();
}
Ext.suspendLayouts();
if (view.getStore().isBufferedStore) {
me.showHeaderCheckbox = false;
}
me.column = headerCt.add(checkbox, me.column || me.getHeaderConfig());
Ext.resumeLayouts();
}
},
/**
* Handles the grid's beforereconfigure event. Removes the checkbox header if the columns are being reconfigured.
* @private
*/
onBeforeReconfigure: function(grid, store, columns, oldStore, oldColumns) {
var column = this.column,
headerCt = column.ownerCt;
// Save out check column from destruction.
// addCheckbox will reuse it instead of creation a new one.
if (columns && headerCt) {
headerCt.remove(column, false);
}
},
/**
* Handles the grid's reconfigure event. Adds the checkbox header if the columns have been reconfigured.
* @private
* @param {Ext.panel.Table} grid
* @param {Ext.data.Store} store
* @param {Object[]} columns
*/
onReconfigure: function(grid, store, columns) {
var me = this;
if (columns) {
// If it's a lockable assembly, add the column to the correct side
if (grid.lockable) {
if (grid.lockedGrid.isVisible()) {
grid.lock(me.column, 0);
} else {
grid.unlock(me.column, 0);
}
} else {
me.addCheckbox(me.view);
}
grid.view.refreshView();
}
},
/**
* Toggle the ui header between checked and unchecked state.
* @param {Boolean} isChecked
* @private
*/
toggleUiHeader: function(isChecked) {
var view = this.views[0],
headerCt = view.headerCt,
checkHd = headerCt.child('gridcolumn[isCheckerHd]'),
cls = this.checkerOnCls;
if (checkHd) {
if (isChecked) {
checkHd.addCls(cls);
} else {
checkHd.removeCls(cls);
}
}
},
/**
* Toggle between selecting all and deselecting all when clicking on
* a checkbox header.
*/
onHeaderClick: function(headerCt, header, e) {
var me = this,
store = me.store,
isChecked, records, i, len,
selections, selection;
if (me.showHeaderCheckbox !== false && header === me.column && me.mode !== 'SINGLE') {
e.stopEvent();
isChecked = header.el.hasCls(Ext.baseCSSPrefix + 'grid-hd-checker-on');
// selectAll will only select the contents of the store, whereas deselectAll
// will remove all the current selections. In this case we only want to
// deselect whatever is available in the view.
if (isChecked) {
records = [];
selections = this.getSelection();
for (i = 0, len = selections.length; i < len; ++i) {
selection = selections[i];
if (store.indexOf(selection) > -1) {
records.push(selection);
}
}
if (records.length > 0) {
me.deselect(records);
}
} else {
me.selectAll();
}
}
},
/**
* Retrieve a configuration to be used in a HeaderContainer.
* This should be used when injectCheckbox is set to false.
*/
getHeaderConfig: function() {
var me = this,
showCheck = me.showHeaderCheckbox !== false;
return {
xtype: 'gridcolumn',
isCheckerHd: showCheck,
text : ' ',
clickTargetName: 'el',
width: me.headerWidth,
sortable: false,
draggable: false,
resizable: false,
hideable: false,
menuDisabled: true,
dataIndex: '',
tdCls: me.tdCls,
cls: showCheck ? Ext.baseCSSPrefix + 'column-header-checkbox ' : '',
defaultRenderer: me.renderer.bind(me),
editRenderer: me.editRenderer || me.renderEmpty,
locked: me.hasLockedHeader()
};
},
renderEmpty: function() {
return ' ';
},
// After refresh, ensure that the header checkbox state matches
refresh: function() {
this.callParent(arguments);
this.updateHeaderState();
},
/**
* Generates the HTML to be rendered in the injected checkbox column for each row.
* Creates the standard checkbox markup by default; can be overridden to provide custom rendering.
* See {@link Ext.grid.column.Column#renderer} for description of allowed parameters.
*/
renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {
return '<div class="' + Ext.baseCSSPrefix + 'grid-row-checker" role="presentation"> </div>';
},
selectByPosition: function (position, keepExisting) {
if (!position.isCellContext) {
position = new Ext.grid.CellContext(this.view).setPosition(position.row, position.column);
}
// Do not select if checkOnly, and the requested position is not the check column
if (!this.checkOnly || position.column === this.column) {
this.callParent([position, keepExisting]);
}
},
/**
* Synchronize header checker value as selection changes.
* @private
*/
onSelectChange: function() {
this.callParent(arguments);
if (!this.suspendChange) {
this.updateHeaderState();
}
},
/**
* @private
*/
onStoreLoad: function() {
this.callParent(arguments);
this.updateHeaderState();
},
onStoreAdd: function() {
this.callParent(arguments);
this.updateHeaderState();
},
onStoreRemove: function() {
this.callParent(arguments);
this.updateHeaderState();
},
onStoreRefresh: function(){
this.callParent(arguments);
this.updateHeaderState();
},
maybeFireSelectionChange: function(fireEvent) {
if (fireEvent && !this.suspendChange) {
this.updateHeaderState();
}
this.callParent(arguments);
},
resumeChanges: function(){
this.callParent();
if (!this.suspendChange) {
this.updateHeaderState();
}
},
/**
* @private
*/
updateHeaderState: function() {
// check to see if all records are selected
var me = this,
store = me.store,
storeCount = store.getCount(),
views = me.views,
hdSelectStatus = false,
selectedCount = 0,
selected, len, i;
if (!store.isBufferedStore && storeCount > 0) {
selected = me.selected;
hdSelectStatus = true;
for (i = 0, len = selected.getCount(); i < len; ++i) {
if (store.indexOfId(selected.getAt(i).id) > -1) {
++selectedCount;
}
}
hdSelectStatus = storeCount === selectedCount;
}
if (views && views.length) {
me.toggleUiHeader(hdSelectStatus);
}
},
vetoSelection: function(e) {
var me = this,
column = me.column,
veto, isClick, isSpace;
if (me.checkOnly) {
isClick = e.type === 'click' && e.getTarget(me.checkSelector);
isSpace = e.getKey() === e.SPACE && e.position.column === column;
veto = !(isClick || isSpace);
}
return veto || me.callParent([e]);
},
destroy: function() {
this.column = null;
this.callParent();
},
privates: {
onBeforeNavigate: function(metaEvent) {
var e = metaEvent.keyEvent;
if (this.selectionMode !== 'SINGLE') {
metaEvent.ctrlKey = metaEvent.ctrlKey || e.ctrlKey || (e.type === 'click' && !e.shiftKey) || e.getKey() === e.SPACE;
}
},
selectWithEventMulti: function(record, e, isSelected) {
var me = this;
if (!e.shiftKey && !e.ctrlKey && e.getTarget(me.checkSelector)) {
if (isSelected) {
me.doDeselect(record);
} else {
me.doSelect(record, true);
}
} else {
me.callParent([record, e, isSelected]);
}
}
}
});
|
var gulp = require('gulp');
// Finds index.js file
var gae = require('../');
var path = require('path');
if (argv.clear_datastore) {
params.clear_datastore = true;
}
if (argv.enable_sendmail) {
params.enable_sendmail = argv.enable_sendmail;
}
gulp.task('gulp-serve', function() {
gulp.src('app/app.yaml')
.pipe(gae('dev_appserver.py', [], {
admin_host: '0.0.0.0',
admin_port: 8000,
host: '0.0.0.0',
port: 8181
}));
});
// Not sure if we can use this
gulp.task('gulp-deploy', function() {
gulp.src('app/app.yaml')
.pipe(gae('appcfg.py', ['update'], {
// For value-less parameters
oauth2: undefined,
version: 'dev'
}));
});
gulp.task('default', ['gulp-serve']);
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M14 1H4c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 19H4V4h10v16zM20.63 8.26c-.26-.32-.74-.36-1.04-.06l-.03.03c-.25.25-.26.65-.05.93 1.26 1.64 1.25 3.87-.02 5.57-.21.28-.19.67.05.92l.05.05c.29.29.76.26 1.03-.05 1.8-2.13 1.8-5.19.01-7.39zM17.42 10.37l-.06.06c-.2.2-.26.5-.15.76.21.49.21 1.03 0 1.52-.11.26-.05.56.15.76l.08.08c.32.32.87.25 1.09-.15.49-.89.49-1.94-.01-2.86a.687.687 0 0 0-1.1-.17z" /></g></React.Fragment>
, 'PhonelinkRingRounded');
|
version https://git-lfs.github.com/spec/v1
oid sha256:f3786d388e21669dd8a7c421ec384b38e0cf895226c2d892476caf2671a0a80a
size 549
|
/**
* Test injectors
*/
import { memoryHistory } from 'react-router-dom';
import { put } from 'redux-saga/effects';
import { shallow } from 'enzyme';
import React from 'react';
import configureStore from '../../configureStore';
import injectSaga from '../injectSaga';
import * as sagaInjectors from '../sagaInjectors';
// Fixtures
const Component = () => null;
function* testSaga() {
yield put({ type: 'TEST', payload: 'yup' });
}
describe('injectSaga decorator', () => {
let store;
let injectors;
let ComponentWithSaga;
beforeAll(() => {
sagaInjectors.default = jest.fn().mockImplementation(() => injectors);
});
beforeEach(() => {
store = configureStore({}, memoryHistory);
injectors = {
injectSaga: jest.fn(),
ejectSaga: jest.fn(),
};
ComponentWithSaga = injectSaga({
key: 'test',
saga: testSaga,
mode: 'testMode',
})(Component);
sagaInjectors.default.mockClear();
});
it('should inject given saga, mode, and props', () => {
const props = { test: 'test' };
shallow(<ComponentWithSaga {...props} />, { context: { store } });
expect(injectors.injectSaga).toHaveBeenCalledTimes(1);
expect(injectors.injectSaga).toHaveBeenCalledWith(
'test',
{ saga: testSaga, mode: 'testMode' },
props,
);
});
it('should eject on unmount with a correct saga key', () => {
const props = { test: 'test' };
const renderedComponent = shallow(<ComponentWithSaga {...props} />, {
context: { store },
});
renderedComponent.unmount();
expect(injectors.ejectSaga).toHaveBeenCalledTimes(1);
expect(injectors.ejectSaga).toHaveBeenCalledWith('test');
});
it('should set a correct display name', () => {
expect(ComponentWithSaga.displayName).toBe('withSaga(Component)');
expect(
injectSaga({ key: 'test', saga: testSaga })(() => null).displayName,
).toBe('withSaga(Component)');
});
it('should propagate props', () => {
const props = { testProp: 'test' };
const renderedComponent = shallow(<ComponentWithSaga {...props} />, {
context: { store },
});
expect(renderedComponent.prop('testProp')).toBe('test');
});
});
|
import nanoid from 'nanoid';
import format from 'nanoid/format';
import generate from 'nanoid/generate';
import url from 'nanoid/url';
const id1: string = nanoid();
// $FlowExpectedError
const id2: number = nanoid();
nanoid(10)
// $FlowExpectedError
nanoid('10')
const random = () => [''];
const f1: string = format(random, '', 10);
// $FlowExpectedError
const f2: number = format(random, '', 10);
// $FlowExpectedError
format(10, '', 10);
// $FlowExpectedError
format(random, 10, 10);
// $FlowExpectedError
format(random, '', '');
const g1: string = generate('', 10);
// $FlowExpectedError
const g2: number = generate('', 10);
// $FlowExpectedError
generate(10, 10);
// $FlowExpectedError
generate('', '');
const url1: string = url;
// $FlowExpectedError
const url2: number = url;
|
(function () {
'use strict';
angular
.module('professions')
.controller('ProfessionsListController', ProfessionsListController);
ProfessionsListController.$inject = ['ProfessionsService'];
function ProfessionsListController(ProfessionsService) {
var vm = this;
vm.professions = ProfessionsService.query();
}
})();
|
var intervalId,
handleReceptacle = {},
observerIds = [],
// This is the same value as server.get.js
sampleUri = "/a/iotivity-node-observe-sample",
iotivity = require( "iotivity-node/lowlevel" );
// Start iotivity and set up the processing loop
iotivity.OCInit( null, 0, iotivity.OCMode.OC_SERVER );
iotivity.OCSetDeviceInfo( { deviceName: "server.observable" } );
iotivity.OCSetPlatformInfo( {
platformID: "server.observe.sample",
manufacturerName: "iotivity-node"
} );
intervalId = setInterval( function() {
iotivity.OCProcess();
}, 1000 );
require( "./mock-sensor" )().on( "change", function( data ) {
console.log( "Sensor data has changed. " +
( observerIds.length > 0 ?
"Notifying " + observerIds.length + " observers." :
"No observers in list." ) );
if ( observerIds.length > 0 ) {
iotivity.OCNotifyListOfObservers(
handleReceptacle.handle,
observerIds,
{
type: iotivity.OCPayloadType.PAYLOAD_TYPE_REPRESENTATION,
values: data
},
iotivity.OCQualityOfService.OC_HIGH_QOS );
}
} );
// Create a new resource
iotivity.OCCreateResource(
// The bindings fill in this object
handleReceptacle,
"core.fan",
iotivity.OC_RSRVD_INTERFACE_DEFAULT,
sampleUri,
function( flag, request ) {
var observerIdIndex;
console.log( "Entity handler called with flag = " + flag + " and the following request:" );
console.log( JSON.stringify( request, null, 4 ) );
if ( flag & iotivity.OCEntityHandlerFlag.OC_OBSERVE_FLAG ) {
if ( request.obsInfo.obsId !== 0 ) {
if ( request.obsInfo.action === iotivity.OCObserveAction.OC_OBSERVE_REGISTER ) {
// Add new observer to list.
observerIds.push( request.obsInfo.obsId );
} else if ( request.obsInfo.action ===
iotivity.OCObserveAction.OC_OBSERVE_DEREGISTER ) {
// Remove requested observer from list.
observerIdIndex = observerIds.indexOf( request.obsInfo.obsId );
if ( observerIdIndex >= 0 ) {
observerIds.splice( observerIdIndex, 1 );
}
}
}
iotivity.OCDoResponse( {
requestHandle: request.requestHandle,
resourceHandle: request.resource,
ehResult: iotivity.OCEntityHandlerResult.OC_EH_OK,
payload: null,
resourceUri: sampleUri,
sendVendorSpecificHeaderOptions: []
} );
}
return iotivity.OCEntityHandlerResult.OC_EH_OK;
},
iotivity.OCResourceProperty.OC_DISCOVERABLE |
iotivity.OCResourceProperty.OC_OBSERVABLE );
// Exit gracefully when interrupted
process.on( "SIGINT", function() {
console.log( "SIGINT: Quitting..." );
// Tear down the processing loop and stop iotivity
clearInterval( intervalId );
iotivity.OCDeleteResource( handleReceptacle.handle );
iotivity.OCStop();
// Exit
process.exit( 0 );
} );
|
import React from 'react';
import { shallow } from 'enzyme';
import { Auth } from 'containers/Auth';
describe('user toggle the authType', () => {
let wrapper;
it('should be LoginForm initially', () => {
wrapper = shallow(<Auth authType="Login" dispatch={jest.fn()} />);
expect(wrapper.name()).toBe('LoginForm');
});
it('user toggle the authType', () => {
wrapper.instance().toggleAuthType();
expect(wrapper.name()).toBe('SignUpForm');
});
it('user toggle the authType again', () => {
wrapper.instance().toggleAuthType();
expect(wrapper.name()).toBe('LoginForm');
});
});
|
/*
* /MathJax/jax/output/HTML-CSS/fonts/STIX/General/Bold/MiscTechnical.js
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["STIXGeneral-bold"],{8962:[774,0,926,55,871],8968:[731,193,469,164,459],8969:[731,193,469,10,305],8970:[732,193,469,164,459],8971:[732,193,469,10,305],8976:[399,-108,750,65,685],8985:[399,-108,750,65,685],8994:[378,-129,1026,37,990],8995:[378,-129,1026,37,990],9001:[732,193,445,69,399],9002:[732,193,445,46,376],9014:[751,156,926,85,841],9021:[694,190,924,80,844],9023:[732,200,728,55,673],9135:[297,-209,315,0,315]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/General/Bold/MiscTechnical.js");
|
'use strict';
exports.__esModule = true;
exports.noop = noop;
exports.hasOwn = hasOwn;
exports.toObject = toObject;
exports.getPropByPath = getPropByPath;
var hasOwnProperty = Object.prototype.hasOwnProperty;
function noop() {};
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
};
function extend(to, _from) {
for (var key in _from) {
to[key] = _from[key];
}
return to;
};
function toObject(arr) {
var res = {};
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i]);
}
}
return res;
};
var getValueByPath = exports.getValueByPath = function getValueByPath(object, prop) {
prop = prop || '';
var paths = prop.split('.');
var current = object;
var result = null;
for (var i = 0, j = paths.length; i < j; i++) {
var path = paths[i];
if (!current) break;
if (i === j - 1) {
result = current[path];
break;
}
current = current[path];
}
return result;
};
function getPropByPath(obj, path, strict) {
var tempObj = obj;
path = path.replace(/\[(\w+)\]/g, '.$1');
path = path.replace(/^\./, '');
var keyArr = path.split('.');
var i = 0;
for (var len = keyArr.length; i < len - 1; ++i) {
if (!tempObj && !strict) break;
var key = keyArr[i];
if (key in tempObj) {
tempObj = tempObj[key];
} else {
if (strict) {
throw new Error('please transfer a valid prop path to form item!');
}
break;
}
}
return {
o: tempObj,
k: keyArr[i],
v: tempObj ? tempObj[keyArr[i]] : null
};
};
var generateId = exports.generateId = function generateId() {
return Math.floor(Math.random() * 10000);
};
var valueEquals = exports.valueEquals = function valueEquals(a, b) {
// see: https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript
if (a === b) return true;
if (!(a instanceof Array)) return false;
if (!(b instanceof Array)) return false;
if (a.length !== b.length) return false;
for (var i = 0; i !== a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}; |
import DropdownMenu from 'src/modules/Dropdown/DropdownMenu'
import * as common from 'test/specs/commonTests'
describe('DropdownMenu', () => {
common.isConformant(DropdownMenu)
common.rendersChildren(DropdownMenu)
})
|
describe('StarterCtrl', function() {
it('should pass a test', function() {
expect(true).to.equal(true);
});
});
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var Class = require('../../utils/Class');
var GameEvents = require('../../core/events');
/**
* @classdesc
* A Bitmap Mask combines the alpha (opacity) of a masked pixel with the alpha of another pixel.
* Unlike the Geometry Mask, which is a clipping path, a Bitmap Mask behaves like an alpha mask,
* not a clipping path. It is only available when using the WebGL Renderer.
*
* A Bitmap Mask can use any Game Object to determine the alpha of each pixel of the masked Game Object(s).
* For any given point of a masked Game Object's texture, the pixel's alpha will be multiplied by the alpha
* of the pixel at the same position in the Bitmap Mask's Game Object. The color of the pixel from the
* Bitmap Mask doesn't matter.
*
* For example, if a pure blue pixel with an alpha of 0.95 is masked with a pure red pixel with an
* alpha of 0.5, the resulting pixel will be pure blue with an alpha of 0.475. Naturally, this means
* that a pixel in the mask with an alpha of 0 will hide the corresponding pixel in all masked Game Objects
* A pixel with an alpha of 1 in the masked Game Object will receive the same alpha as the
* corresponding pixel in the mask.
*
* The Bitmap Mask's location matches the location of its Game Object, not the location of the
* masked objects. Moving or transforming the underlying Game Object will change the mask
* (and affect the visibility of any masked objects), whereas moving or transforming a masked object
* will not affect the mask.
*
* The Bitmap Mask will not render its Game Object by itself. If the Game Object is not in a
* Scene's display list, it will only be used for the mask and its full texture will not be directly
* visible. Adding the underlying Game Object to a Scene will not cause any problems - it will
* render as a normal Game Object and will also serve as a mask.
*
* @class BitmapMask
* @memberof Phaser.Display.Masks
* @constructor
* @since 3.0.0
*
* @param {Phaser.Scene} scene - The Scene which this Bitmap Mask will be used in.
* @param {Phaser.GameObjects.GameObject} renderable - A renderable Game Object that uses a texture, such as a Sprite.
*/
var BitmapMask = new Class({
initialize:
function BitmapMask (scene, renderable)
{
var renderer = scene.sys.game.renderer;
/**
* A reference to either the Canvas or WebGL Renderer that this Mask is using.
*
* @name Phaser.Display.Masks.BitmapMask#renderer
* @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)}
* @since 3.11.0
*/
this.renderer = renderer;
/**
* A renderable Game Object that uses a texture, such as a Sprite.
*
* @name Phaser.Display.Masks.BitmapMask#bitmapMask
* @type {Phaser.GameObjects.GameObject}
* @since 3.0.0
*/
this.bitmapMask = renderable;
/**
* The texture used for the mask's framebuffer.
*
* @name Phaser.Display.Masks.BitmapMask#maskTexture
* @type {WebGLTexture}
* @default null
* @since 3.0.0
*/
this.maskTexture = null;
/**
* The texture used for the main framebuffer.
*
* @name Phaser.Display.Masks.BitmapMask#mainTexture
* @type {WebGLTexture}
* @default null
* @since 3.0.0
*/
this.mainTexture = null;
/**
* Whether the Bitmap Mask is dirty and needs to be updated.
*
* @name Phaser.Display.Masks.BitmapMask#dirty
* @type {boolean}
* @default true
* @since 3.0.0
*/
this.dirty = true;
/**
* The framebuffer to which a masked Game Object is rendered.
*
* @name Phaser.Display.Masks.BitmapMask#mainFramebuffer
* @type {WebGLFramebuffer}
* @since 3.0.0
*/
this.mainFramebuffer = null;
/**
* The framebuffer to which the Bitmap Mask's masking Game Object is rendered.
*
* @name Phaser.Display.Masks.BitmapMask#maskFramebuffer
* @type {WebGLFramebuffer}
* @since 3.0.0
*/
this.maskFramebuffer = null;
/**
* The previous framebuffer set in the renderer before this one was enabled.
*
* @name Phaser.Display.Masks.BitmapMask#prevFramebuffer
* @type {WebGLFramebuffer}
* @since 3.17.0
*/
this.prevFramebuffer = null;
/**
* Whether to invert the masks alpha.
*
* If `true`, the alpha of the masking pixel will be inverted before it's multiplied with the masked pixel. Essentially, this means that a masked area will be visible only if the corresponding area in the mask is invisible.
*
* @name Phaser.Display.Masks.BitmapMask#invertAlpha
* @type {boolean}
* @since 3.1.2
*/
this.invertAlpha = false;
/**
* Is this mask a stencil mask?
*
* @name Phaser.Display.Masks.BitmapMask#isStencil
* @type {boolean}
* @readonly
* @since 3.17.0
*/
this.isStencil = false;
if (renderer && renderer.gl)
{
var width = renderer.width;
var height = renderer.height;
var pot = ((width & (width - 1)) === 0 && (height & (height - 1)) === 0);
var gl = renderer.gl;
var wrap = pot ? gl.REPEAT : gl.CLAMP_TO_EDGE;
var filter = gl.LINEAR;
this.mainTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height);
this.maskTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height);
this.mainFramebuffer = renderer.createFramebuffer(width, height, this.mainTexture, true);
this.maskFramebuffer = renderer.createFramebuffer(width, height, this.maskTexture, true);
scene.sys.game.events.on(GameEvents.CONTEXT_RESTORED, function (renderer)
{
var width = renderer.width;
var height = renderer.height;
var pot = ((width & (width - 1)) === 0 && (height & (height - 1)) === 0);
var gl = renderer.gl;
var wrap = pot ? gl.REPEAT : gl.CLAMP_TO_EDGE;
var filter = gl.LINEAR;
this.mainTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height);
this.maskTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height);
this.mainFramebuffer = renderer.createFramebuffer(width, height, this.mainTexture, true);
this.maskFramebuffer = renderer.createFramebuffer(width, height, this.maskTexture, true);
}, this);
}
},
/**
* Sets a new masking Game Object for the Bitmap Mask.
*
* @method Phaser.Display.Masks.BitmapMask#setBitmap
* @since 3.0.0
*
* @param {Phaser.GameObjects.GameObject} renderable - A renderable Game Object that uses a texture, such as a Sprite.
*/
setBitmap: function (renderable)
{
this.bitmapMask = renderable;
},
/**
* Prepares the WebGL Renderer to render a Game Object with this mask applied.
*
* This renders the masking Game Object to the mask framebuffer and switches to the main framebuffer so that the masked Game Object will be rendered to it instead of being rendered directly to the frame.
*
* @method Phaser.Display.Masks.BitmapMask#preRenderWebGL
* @since 3.0.0
*
* @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The WebGL Renderer to prepare.
* @param {Phaser.GameObjects.GameObject} maskedObject - The masked Game Object which will be drawn.
* @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to render to.
*/
preRenderWebGL: function (renderer, maskedObject, camera)
{
renderer.pipelines.BitmapMaskPipeline.beginMask(this, maskedObject, camera);
},
/**
* Finalizes rendering of a masked Game Object.
*
* This resets the previously bound framebuffer and switches the WebGL Renderer to the Bitmap Mask Pipeline, which uses a special fragment shader to apply the masking effect.
*
* @method Phaser.Display.Masks.BitmapMask#postRenderWebGL
* @since 3.0.0
*
* @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The WebGL Renderer to clean up.
*/
postRenderWebGL: function (renderer, camera)
{
renderer.pipelines.BitmapMaskPipeline.endMask(this, camera);
},
/**
* This is a NOOP method. Bitmap Masks are not supported by the Canvas Renderer.
*
* @method Phaser.Display.Masks.BitmapMask#preRenderCanvas
* @since 3.0.0
*
* @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The Canvas Renderer which would be rendered to.
* @param {Phaser.GameObjects.GameObject} mask - The masked Game Object which would be rendered.
* @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to render to.
*/
preRenderCanvas: function ()
{
// NOOP
},
/**
* This is a NOOP method. Bitmap Masks are not supported by the Canvas Renderer.
*
* @method Phaser.Display.Masks.BitmapMask#postRenderCanvas
* @since 3.0.0
*
* @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The Canvas Renderer which would be rendered to.
*/
postRenderCanvas: function ()
{
// NOOP
},
/**
* Destroys this BitmapMask and nulls any references it holds.
*
* Note that if a Game Object is currently using this mask it will _not_ automatically detect you have destroyed it,
* so be sure to call `clearMask` on any Game Object using it, before destroying it.
*
* @method Phaser.Display.Masks.BitmapMask#destroy
* @since 3.7.0
*/
destroy: function ()
{
this.bitmapMask = null;
var renderer = this.renderer;
if (renderer && renderer.gl)
{
renderer.deleteTexture(this.mainTexture);
renderer.deleteTexture(this.maskTexture);
renderer.deleteFramebuffer(this.mainFramebuffer);
renderer.deleteFramebuffer(this.maskFramebuffer);
}
this.mainTexture = null;
this.maskTexture = null;
this.mainFramebuffer = null;
this.maskFramebuffer = null;
this.prevFramebuffer = null;
this.renderer = null;
}
});
module.exports = BitmapMask;
|
define(['./_arrayFilter', './_baseFilter', './_baseIteratee', './isArray', './negate'], function(arrayFilter, baseFilter, baseIteratee, isArray, negate) {
/**
* The opposite of `_.filter`; this method returns the elements of `collection`
* that `predicate` does **not** return truthy for.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.filter
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true }
* ];
*
* _.reject(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.reject(users, { 'age': 40, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.reject(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.reject(users, 'active');
* // => objects for ['barney']
*/
function reject(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, negate(baseIteratee(predicate, 3)));
}
return reject;
});
|
/**
* @author mrdoob / http://mrdoob.com/
* @author zz85 / http://joshuakoo.com/
* @author yomboprime / https://yombo.org
*/
import {
BufferGeometry,
Color,
FileLoader,
Float32BufferAttribute,
Loader,
Matrix3,
Path,
ShapePath,
Vector2,
Vector3
} from "../../../build/three.module.js";
var SVGLoader = function ( manager ) {
Loader.call( this, manager );
};
SVGLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: SVGLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var loader = new FileLoader( scope.manager );
loader.setPath( scope.path );
loader.load( url, function ( text ) {
onLoad( scope.parse( text ) );
}, onProgress, onError );
},
parse: function ( text ) {
function parseNode( node, style ) {
if ( node.nodeType !== 1 ) return;
var transform = getNodeTransform( node );
var path = null;
switch ( node.nodeName ) {
case 'svg':
break;
case 'g':
style = parseStyle( node, style );
break;
case 'path':
style = parseStyle( node, style );
if ( node.hasAttribute( 'd' ) ) path = parsePathNode( node );
break;
case 'rect':
style = parseStyle( node, style );
path = parseRectNode( node );
break;
case 'polygon':
style = parseStyle( node, style );
path = parsePolygonNode( node );
break;
case 'polyline':
style = parseStyle( node, style );
path = parsePolylineNode( node );
break;
case 'circle':
style = parseStyle( node, style );
path = parseCircleNode( node );
break;
case 'ellipse':
style = parseStyle( node, style );
path = parseEllipseNode( node );
break;
case 'line':
style = parseStyle( node, style );
path = parseLineNode( node );
break;
default:
console.log( node );
}
if ( path ) {
if ( style.fill !== undefined && style.fill !== 'none' ) {
path.color.setStyle( style.fill );
}
transformPath( path, currentTransform );
paths.push( path );
path.userData = { node: node, style: style };
}
var nodes = node.childNodes;
for ( var i = 0; i < nodes.length; i ++ ) {
parseNode( nodes[ i ], style );
}
if ( transform ) {
transformStack.pop();
if ( transformStack.length > 0 ) {
currentTransform.copy( transformStack[ transformStack.length - 1 ] );
} else {
currentTransform.identity();
}
}
}
function parsePathNode( node ) {
var path = new ShapePath();
var point = new Vector2();
var control = new Vector2();
var firstPoint = new Vector2();
var isFirstPoint = true;
var doSetFirstPoint = false;
var d = node.getAttribute( 'd' );
// console.log( d );
var commands = d.match( /[a-df-z][^a-df-z]*/ig );
for ( var i = 0, l = commands.length; i < l; i ++ ) {
var command = commands[ i ];
var type = command.charAt( 0 );
var data = command.substr( 1 ).trim();
if ( isFirstPoint === true ) {
doSetFirstPoint = true;
isFirstPoint = false;
}
switch ( type ) {
case 'M':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) {
point.x = numbers[ j + 0 ];
point.y = numbers[ j + 1 ];
control.x = point.x;
control.y = point.y;
if ( j === 0 ) {
path.moveTo( point.x, point.y );
} else {
path.lineTo( point.x, point.y );
}
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'H':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j ++ ) {
point.x = numbers[ j ];
control.x = point.x;
control.y = point.y;
path.lineTo( point.x, point.y );
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'V':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j ++ ) {
point.y = numbers[ j ];
control.x = point.x;
control.y = point.y;
path.lineTo( point.x, point.y );
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'L':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) {
point.x = numbers[ j + 0 ];
point.y = numbers[ j + 1 ];
control.x = point.x;
control.y = point.y;
path.lineTo( point.x, point.y );
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'C':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j += 6 ) {
path.bezierCurveTo(
numbers[ j + 0 ],
numbers[ j + 1 ],
numbers[ j + 2 ],
numbers[ j + 3 ],
numbers[ j + 4 ],
numbers[ j + 5 ]
);
control.x = numbers[ j + 2 ];
control.y = numbers[ j + 3 ];
point.x = numbers[ j + 4 ];
point.y = numbers[ j + 5 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'S':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) {
path.bezierCurveTo(
getReflection( point.x, control.x ),
getReflection( point.y, control.y ),
numbers[ j + 0 ],
numbers[ j + 1 ],
numbers[ j + 2 ],
numbers[ j + 3 ]
);
control.x = numbers[ j + 0 ];
control.y = numbers[ j + 1 ];
point.x = numbers[ j + 2 ];
point.y = numbers[ j + 3 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'Q':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) {
path.quadraticCurveTo(
numbers[ j + 0 ],
numbers[ j + 1 ],
numbers[ j + 2 ],
numbers[ j + 3 ]
);
control.x = numbers[ j + 0 ];
control.y = numbers[ j + 1 ];
point.x = numbers[ j + 2 ];
point.y = numbers[ j + 3 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'T':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) {
var rx = getReflection( point.x, control.x );
var ry = getReflection( point.y, control.y );
path.quadraticCurveTo(
rx,
ry,
numbers[ j + 0 ],
numbers[ j + 1 ]
);
control.x = rx;
control.y = ry;
point.x = numbers[ j + 0 ];
point.y = numbers[ j + 1 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'A':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j += 7 ) {
var start = point.clone();
point.x = numbers[ j + 5 ];
point.y = numbers[ j + 6 ];
control.x = point.x;
control.y = point.y;
parseArcCommand(
path, numbers[ j ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], start, point
);
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'm':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) {
point.x += numbers[ j + 0 ];
point.y += numbers[ j + 1 ];
control.x = point.x;
control.y = point.y;
if ( j === 0 ) {
path.moveTo( point.x, point.y );
} else {
path.lineTo( point.x, point.y );
}
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'h':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j ++ ) {
point.x += numbers[ j ];
control.x = point.x;
control.y = point.y;
path.lineTo( point.x, point.y );
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'v':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j ++ ) {
point.y += numbers[ j ];
control.x = point.x;
control.y = point.y;
path.lineTo( point.x, point.y );
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'l':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) {
point.x += numbers[ j + 0 ];
point.y += numbers[ j + 1 ];
control.x = point.x;
control.y = point.y;
path.lineTo( point.x, point.y );
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'c':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j += 6 ) {
path.bezierCurveTo(
point.x + numbers[ j + 0 ],
point.y + numbers[ j + 1 ],
point.x + numbers[ j + 2 ],
point.y + numbers[ j + 3 ],
point.x + numbers[ j + 4 ],
point.y + numbers[ j + 5 ]
);
control.x = point.x + numbers[ j + 2 ];
control.y = point.y + numbers[ j + 3 ];
point.x += numbers[ j + 4 ];
point.y += numbers[ j + 5 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 's':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) {
path.bezierCurveTo(
getReflection( point.x, control.x ),
getReflection( point.y, control.y ),
point.x + numbers[ j + 0 ],
point.y + numbers[ j + 1 ],
point.x + numbers[ j + 2 ],
point.y + numbers[ j + 3 ]
);
control.x = point.x + numbers[ j + 0 ];
control.y = point.y + numbers[ j + 1 ];
point.x += numbers[ j + 2 ];
point.y += numbers[ j + 3 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'q':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) {
path.quadraticCurveTo(
point.x + numbers[ j + 0 ],
point.y + numbers[ j + 1 ],
point.x + numbers[ j + 2 ],
point.y + numbers[ j + 3 ]
);
control.x = point.x + numbers[ j + 0 ];
control.y = point.y + numbers[ j + 1 ];
point.x += numbers[ j + 2 ];
point.y += numbers[ j + 3 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 't':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) {
var rx = getReflection( point.x, control.x );
var ry = getReflection( point.y, control.y );
path.quadraticCurveTo(
rx,
ry,
point.x + numbers[ j + 0 ],
point.y + numbers[ j + 1 ]
);
control.x = rx;
control.y = ry;
point.x = point.x + numbers[ j + 0 ];
point.y = point.y + numbers[ j + 1 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'a':
var numbers = parseFloats( data );
for ( var j = 0, jl = numbers.length; j < jl; j += 7 ) {
var start = point.clone();
point.x += numbers[ j + 5 ];
point.y += numbers[ j + 6 ];
control.x = point.x;
control.y = point.y;
parseArcCommand(
path, numbers[ j ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], start, point
);
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'Z':
case 'z':
path.currentPath.autoClose = true;
if ( path.currentPath.curves.length > 0 ) {
// Reset point to beginning of Path
point.copy( firstPoint );
path.currentPath.currentPoint.copy( point );
isFirstPoint = true;
}
break;
default:
console.warn( command );
}
// console.log( type, parseFloats( data ), parseFloats( data ).length )
doSetFirstPoint = false;
}
return path;
}
/**
* https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
* https://mortoray.com/2017/02/16/rendering-an-svg-elliptical-arc-as-bezier-curves/ Appendix: Endpoint to center arc conversion
* From
* rx ry x-axis-rotation large-arc-flag sweep-flag x y
* To
* aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation
*/
function parseArcCommand( path, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, start, end ) {
x_axis_rotation = x_axis_rotation * Math.PI / 180;
// Ensure radii are positive
rx = Math.abs( rx );
ry = Math.abs( ry );
// Compute (x1โฒ, y1โฒ)
var dx2 = ( start.x - end.x ) / 2.0;
var dy2 = ( start.y - end.y ) / 2.0;
var x1p = Math.cos( x_axis_rotation ) * dx2 + Math.sin( x_axis_rotation ) * dy2;
var y1p = - Math.sin( x_axis_rotation ) * dx2 + Math.cos( x_axis_rotation ) * dy2;
// Compute (cxโฒ, cyโฒ)
var rxs = rx * rx;
var rys = ry * ry;
var x1ps = x1p * x1p;
var y1ps = y1p * y1p;
// Ensure radii are large enough
var cr = x1ps / rxs + y1ps / rys;
if ( cr > 1 ) {
// scale up rx,ry equally so cr == 1
var s = Math.sqrt( cr );
rx = s * rx;
ry = s * ry;
rxs = rx * rx;
rys = ry * ry;
}
var dq = ( rxs * y1ps + rys * x1ps );
var pq = ( rxs * rys - dq ) / dq;
var q = Math.sqrt( Math.max( 0, pq ) );
if ( large_arc_flag === sweep_flag ) q = - q;
var cxp = q * rx * y1p / ry;
var cyp = - q * ry * x1p / rx;
// Step 3: Compute (cx, cy) from (cxโฒ, cyโฒ)
var cx = Math.cos( x_axis_rotation ) * cxp - Math.sin( x_axis_rotation ) * cyp + ( start.x + end.x ) / 2;
var cy = Math.sin( x_axis_rotation ) * cxp + Math.cos( x_axis_rotation ) * cyp + ( start.y + end.y ) / 2;
// Step 4: Compute ฮธ1 and ฮฮธ
var theta = svgAngle( 1, 0, ( x1p - cxp ) / rx, ( y1p - cyp ) / ry );
var delta = svgAngle( ( x1p - cxp ) / rx, ( y1p - cyp ) / ry, ( - x1p - cxp ) / rx, ( - y1p - cyp ) / ry ) % ( Math.PI * 2 );
path.currentPath.absellipse( cx, cy, rx, ry, theta, theta + delta, sweep_flag === 0, x_axis_rotation );
}
function svgAngle( ux, uy, vx, vy ) {
var dot = ux * vx + uy * vy;
var len = Math.sqrt( ux * ux + uy * uy ) * Math.sqrt( vx * vx + vy * vy );
var ang = Math.acos( Math.max( - 1, Math.min( 1, dot / len ) ) ); // floating point precision, slightly over values appear
if ( ( ux * vy - uy * vx ) < 0 ) ang = - ang;
return ang;
}
/*
* According to https://www.w3.org/TR/SVG/shapes.html#RectElementRXAttribute
* rounded corner should be rendered to elliptical arc, but bezier curve does the job well enough
*/
function parseRectNode( node ) {
var x = parseFloat( node.getAttribute( 'x' ) || 0 );
var y = parseFloat( node.getAttribute( 'y' ) || 0 );
var rx = parseFloat( node.getAttribute( 'rx' ) || 0 );
var ry = parseFloat( node.getAttribute( 'ry' ) || 0 );
var w = parseFloat( node.getAttribute( 'width' ) );
var h = parseFloat( node.getAttribute( 'height' ) );
var path = new ShapePath();
path.moveTo( x + 2 * rx, y );
path.lineTo( x + w - 2 * rx, y );
if ( rx !== 0 || ry !== 0 ) path.bezierCurveTo( x + w, y, x + w, y, x + w, y + 2 * ry );
path.lineTo( x + w, y + h - 2 * ry );
if ( rx !== 0 || ry !== 0 ) path.bezierCurveTo( x + w, y + h, x + w, y + h, x + w - 2 * rx, y + h );
path.lineTo( x + 2 * rx, y + h );
if ( rx !== 0 || ry !== 0 ) {
path.bezierCurveTo( x, y + h, x, y + h, x, y + h - 2 * ry );
}
path.lineTo( x, y + 2 * ry );
if ( rx !== 0 || ry !== 0 ) {
path.bezierCurveTo( x, y, x, y, x + 2 * rx, y );
}
return path;
}
function parsePolygonNode( node ) {
function iterator( match, a, b ) {
var x = parseFloat( a );
var y = parseFloat( b );
if ( index === 0 ) {
path.moveTo( x, y );
} else {
path.lineTo( x, y );
}
index ++;
}
var regex = /(-?[\d\.?]+)[,|\s](-?[\d\.?]+)/g;
var path = new ShapePath();
var index = 0;
node.getAttribute( 'points' ).replace( regex, iterator );
path.currentPath.autoClose = true;
return path;
}
function parsePolylineNode( node ) {
function iterator( match, a, b ) {
var x = parseFloat( a );
var y = parseFloat( b );
if ( index === 0 ) {
path.moveTo( x, y );
} else {
path.lineTo( x, y );
}
index ++;
}
var regex = /(-?[\d\.?]+)[,|\s](-?[\d\.?]+)/g;
var path = new ShapePath();
var index = 0;
node.getAttribute( 'points' ).replace( regex, iterator );
path.currentPath.autoClose = false;
return path;
}
function parseCircleNode( node ) {
var x = parseFloat( node.getAttribute( 'cx' ) );
var y = parseFloat( node.getAttribute( 'cy' ) );
var r = parseFloat( node.getAttribute( 'r' ) );
var subpath = new Path();
subpath.absarc( x, y, r, 0, Math.PI * 2 );
var path = new ShapePath();
path.subPaths.push( subpath );
return path;
}
function parseEllipseNode( node ) {
var x = parseFloat( node.getAttribute( 'cx' ) );
var y = parseFloat( node.getAttribute( 'cy' ) );
var rx = parseFloat( node.getAttribute( 'rx' ) );
var ry = parseFloat( node.getAttribute( 'ry' ) );
var subpath = new Path();
subpath.absellipse( x, y, rx, ry, 0, Math.PI * 2 );
var path = new ShapePath();
path.subPaths.push( subpath );
return path;
}
function parseLineNode( node ) {
var x1 = parseFloat( node.getAttribute( 'x1' ) );
var y1 = parseFloat( node.getAttribute( 'y1' ) );
var x2 = parseFloat( node.getAttribute( 'x2' ) );
var y2 = parseFloat( node.getAttribute( 'y2' ) );
var path = new ShapePath();
path.moveTo( x1, y1 );
path.lineTo( x2, y2 );
path.currentPath.autoClose = false;
return path;
}
//
function parseStyle( node, style ) {
style = Object.assign( {}, style ); // clone style
function addStyle( svgName, jsName, adjustFunction ) {
if ( adjustFunction === undefined ) adjustFunction = function copy( v ) {
return v;
};
if ( node.hasAttribute( svgName ) ) style[ jsName ] = adjustFunction( node.getAttribute( svgName ) );
if ( node.style[ svgName ] !== '' ) style[ jsName ] = adjustFunction( node.style[ svgName ] );
}
function clamp( v ) {
return Math.max( 0, Math.min( 1, parseFloat( v ) ) );
}
function positive( v ) {
return Math.max( 0, parseFloat( v ) );
}
addStyle( 'fill', 'fill' );
addStyle( 'fill-opacity', 'fillOpacity', clamp );
addStyle( 'stroke', 'stroke' );
addStyle( 'stroke-opacity', 'strokeOpacity', clamp );
addStyle( 'stroke-width', 'strokeWidth', positive );
addStyle( 'stroke-linejoin', 'strokeLineJoin' );
addStyle( 'stroke-linecap', 'strokeLineCap' );
addStyle( 'stroke-miterlimit', 'strokeMiterLimit', positive );
return style;
}
// http://www.w3.org/TR/SVG11/implnote.html#PathElementImplementationNotes
function getReflection( a, b ) {
return a - ( b - a );
}
function parseFloats( string ) {
var array = string.split( /[\s,]+|(?=\s?[+\-])/ );
for ( var i = 0; i < array.length; i ++ ) {
var number = array[ i ];
// Handle values like 48.6037.7.8
// TODO Find a regex for this
if ( number.indexOf( '.' ) !== number.lastIndexOf( '.' ) ) {
var split = number.split( '.' );
for ( var s = 2; s < split.length; s ++ ) {
array.splice( i + s - 1, 0, '0.' + split[ s ] );
}
}
array[ i ] = parseFloat( number );
}
return array;
}
function getNodeTransform( node ) {
if ( ! node.hasAttribute( 'transform' ) ) {
return null;
}
var transform = parseNodeTransform( node );
if ( transformStack.length > 0 ) {
transform.premultiply( transformStack[ transformStack.length - 1 ] );
}
currentTransform.copy( transform );
transformStack.push( transform );
return transform;
}
function parseNodeTransform( node ) {
var transform = new Matrix3();
var currentTransform = tempTransform0;
var transformsTexts = node.getAttribute( 'transform' ).split( ')' );
for ( var tIndex = transformsTexts.length - 1; tIndex >= 0; tIndex -- ) {
var transformText = transformsTexts[ tIndex ].trim();
if ( transformText === '' ) continue;
var openParPos = transformText.indexOf( '(' );
var closeParPos = transformText.length;
if ( openParPos > 0 && openParPos < closeParPos ) {
var transformType = transformText.substr( 0, openParPos );
var array = parseFloats( transformText.substr( openParPos + 1, closeParPos - openParPos - 1 ) );
currentTransform.identity();
switch ( transformType ) {
case "translate":
if ( array.length >= 1 ) {
var tx = array[ 0 ];
var ty = tx;
if ( array.length >= 2 ) {
ty = array[ 1 ];
}
currentTransform.translate( tx, ty );
}
break;
case "rotate":
if ( array.length >= 1 ) {
var angle = 0;
var cx = 0;
var cy = 0;
// Angle
angle = - array[ 0 ] * Math.PI / 180;
if ( array.length >= 3 ) {
// Center x, y
cx = array[ 1 ];
cy = array[ 2 ];
}
// Rotate around center (cx, cy)
tempTransform1.identity().translate( - cx, - cy );
tempTransform2.identity().rotate( angle );
tempTransform3.multiplyMatrices( tempTransform2, tempTransform1 );
tempTransform1.identity().translate( cx, cy );
currentTransform.multiplyMatrices( tempTransform1, tempTransform3 );
}
break;
case "scale":
if ( array.length >= 1 ) {
var scaleX = array[ 0 ];
var scaleY = scaleX;
if ( array.length >= 2 ) {
scaleY = array[ 1 ];
}
currentTransform.scale( scaleX, scaleY );
}
break;
case "skewX":
if ( array.length === 1 ) {
currentTransform.set(
1, Math.tan( array[ 0 ] * Math.PI / 180 ), 0,
0, 1, 0,
0, 0, 1
);
}
break;
case "skewY":
if ( array.length === 1 ) {
currentTransform.set(
1, 0, 0,
Math.tan( array[ 0 ] * Math.PI / 180 ), 1, 0,
0, 0, 1
);
}
break;
case "matrix":
if ( array.length === 6 ) {
currentTransform.set(
array[ 0 ], array[ 2 ], array[ 4 ],
array[ 1 ], array[ 3 ], array[ 5 ],
0, 0, 1
);
}
break;
}
}
transform.premultiply( currentTransform );
}
return transform;
}
function transformPath( path, m ) {
function transfVec2( v2 ) {
tempV3.set( v2.x, v2.y, 1 ).applyMatrix3( m );
v2.set( tempV3.x, tempV3.y );
}
var isRotated = isTransformRotated( m );
var subPaths = path.subPaths;
for ( var i = 0, n = subPaths.length; i < n; i ++ ) {
var subPath = subPaths[ i ];
var curves = subPath.curves;
for ( var j = 0; j < curves.length; j ++ ) {
var curve = curves[ j ];
if ( curve.isLineCurve ) {
transfVec2( curve.v1 );
transfVec2( curve.v2 );
} else if ( curve.isCubicBezierCurve ) {
transfVec2( curve.v0 );
transfVec2( curve.v1 );
transfVec2( curve.v2 );
transfVec2( curve.v3 );
} else if ( curve.isQuadraticBezierCurve ) {
transfVec2( curve.v0 );
transfVec2( curve.v1 );
transfVec2( curve.v2 );
} else if ( curve.isEllipseCurve ) {
if ( isRotated ) {
console.warn( "SVGLoader: Elliptic arc or ellipse rotation or skewing is not implemented." );
}
tempV2.set( curve.aX, curve.aY );
transfVec2( tempV2 );
curve.aX = tempV2.x;
curve.aY = tempV2.y;
curve.xRadius *= getTransformScaleX( m );
curve.yRadius *= getTransformScaleY( m );
}
}
}
}
function isTransformRotated( m ) {
return m.elements[ 1 ] !== 0 || m.elements[ 3 ] !== 0;
}
function getTransformScaleX( m ) {
var te = m.elements;
return Math.sqrt( te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] );
}
function getTransformScaleY( m ) {
var te = m.elements;
return Math.sqrt( te[ 3 ] * te[ 3 ] + te[ 4 ] * te[ 4 ] );
}
//
console.log( 'THREE.SVGLoader' );
var paths = [];
var transformStack = [];
var tempTransform0 = new Matrix3();
var tempTransform1 = new Matrix3();
var tempTransform2 = new Matrix3();
var tempTransform3 = new Matrix3();
var tempV2 = new Vector2();
var tempV3 = new Vector3();
var currentTransform = new Matrix3();
console.time( 'THREE.SVGLoader: DOMParser' );
var xml = new DOMParser().parseFromString( text, 'image/svg+xml' ); // application/xml
console.timeEnd( 'THREE.SVGLoader: DOMParser' );
console.time( 'THREE.SVGLoader: Parse' );
parseNode( xml.documentElement, {
fill: '#000',
fillOpacity: 1,
strokeOpacity: 1,
strokeWidth: 1,
strokeLineJoin: 'miter',
strokeLineCap: 'butt',
strokeMiterLimit: 4
} );
var data = { paths: paths, xml: xml.documentElement };
// console.log( paths );
console.timeEnd( 'THREE.SVGLoader: Parse' );
return data;
}
} );
SVGLoader.getStrokeStyle = function ( width, color, lineJoin, lineCap, miterLimit ) {
// Param width: Stroke width
// Param color: As returned by Color.getStyle()
// Param lineJoin: One of "round", "bevel", "miter" or "miter-limit"
// Param lineCap: One of "round", "square" or "butt"
// Param miterLimit: Maximum join length, in multiples of the "width" parameter (join is truncated if it exceeds that distance)
// Returns style object
width = width !== undefined ? width : 1;
color = color !== undefined ? color : '#000';
lineJoin = lineJoin !== undefined ? lineJoin : 'miter';
lineCap = lineCap !== undefined ? lineCap : 'butt';
miterLimit = miterLimit !== undefined ? miterLimit : 4;
return {
strokeColor: color,
strokeWidth: width,
strokeLineJoin: lineJoin,
strokeLineCap: lineCap,
strokeMiterLimit: miterLimit
};
};
SVGLoader.pointsToStroke = function ( points, style, arcDivisions, minDistance ) {
// Generates a stroke with some witdh around the given path.
// The path can be open or closed (last point equals to first point)
// Param points: Array of Vector2D (the path). Minimum 2 points.
// Param style: Object with SVG properties as returned by SVGLoader.getStrokeStyle(), or SVGLoader.parse() in the path.userData.style object
// Params arcDivisions: Arc divisions for round joins and endcaps. (Optional)
// Param minDistance: Points closer to this distance will be merged. (Optional)
// Returns BufferGeometry with stroke triangles (In plane z = 0). UV coordinates are generated ('u' along path. 'v' across it, from left to right)
var vertices = [];
var normals = [];
var uvs = [];
if ( SVGLoader.pointsToStrokeWithBuffers( points, style, arcDivisions, minDistance, vertices, normals, uvs ) === 0 ) {
return null;
}
var geometry = new BufferGeometry();
geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
geometry.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
geometry.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
return geometry;
};
SVGLoader.pointsToStrokeWithBuffers = function () {
var tempV2_1 = new Vector2();
var tempV2_2 = new Vector2();
var tempV2_3 = new Vector2();
var tempV2_4 = new Vector2();
var tempV2_5 = new Vector2();
var tempV2_6 = new Vector2();
var tempV2_7 = new Vector2();
var lastPointL = new Vector2();
var lastPointR = new Vector2();
var point0L = new Vector2();
var point0R = new Vector2();
var currentPointL = new Vector2();
var currentPointR = new Vector2();
var nextPointL = new Vector2();
var nextPointR = new Vector2();
var innerPoint = new Vector2();
var outerPoint = new Vector2();
return function ( points, style, arcDivisions, minDistance, vertices, normals, uvs, vertexOffset ) {
// This function can be called to update existing arrays or buffers.
// Accepts same parameters as pointsToStroke, plus the buffers and optional offset.
// Param vertexOffset: Offset vertices to start writing in the buffers (3 elements/vertex for vertices and normals, and 2 elements/vertex for uvs)
// Returns number of written vertices / normals / uvs pairs
// if 'vertices' parameter is undefined no triangles will be generated, but the returned vertices count will still be valid (useful to preallocate the buffers)
// 'normals' and 'uvs' buffers are optional
arcDivisions = arcDivisions !== undefined ? arcDivisions : 12;
minDistance = minDistance !== undefined ? minDistance : 0.001;
vertexOffset = vertexOffset !== undefined ? vertexOffset : 0;
// First ensure there are no duplicated points
points = removeDuplicatedPoints( points );
var numPoints = points.length;
if ( numPoints < 2 ) return 0;
var isClosed = points[ 0 ].equals( points[ numPoints - 1 ] );
var currentPoint;
var previousPoint = points[ 0 ];
var nextPoint;
var strokeWidth2 = style.strokeWidth / 2;
var deltaU = 1 / ( numPoints - 1 );
var u0 = 0;
var innerSideModified;
var joinIsOnLeftSide;
var isMiter;
var initialJoinIsOnLeftSide = false;
var numVertices = 0;
var currentCoordinate = vertexOffset * 3;
var currentCoordinateUV = vertexOffset * 2;
// Get initial left and right stroke points
getNormal( points[ 0 ], points[ 1 ], tempV2_1 ).multiplyScalar( strokeWidth2 );
lastPointL.copy( points[ 0 ] ).sub( tempV2_1 );
lastPointR.copy( points[ 0 ] ).add( tempV2_1 );
point0L.copy( lastPointL );
point0R.copy( lastPointR );
for ( var iPoint = 1; iPoint < numPoints; iPoint ++ ) {
currentPoint = points[ iPoint ];
// Get next point
if ( iPoint === numPoints - 1 ) {
if ( isClosed ) {
// Skip duplicated initial point
nextPoint = points[ 1 ];
} else nextPoint = undefined;
} else {
nextPoint = points[ iPoint + 1 ];
}
// Normal of previous segment in tempV2_1
var normal1 = tempV2_1;
getNormal( previousPoint, currentPoint, normal1 );
tempV2_3.copy( normal1 ).multiplyScalar( strokeWidth2 );
currentPointL.copy( currentPoint ).sub( tempV2_3 );
currentPointR.copy( currentPoint ).add( tempV2_3 );
var u1 = u0 + deltaU;
innerSideModified = false;
if ( nextPoint !== undefined ) {
// Normal of next segment in tempV2_2
getNormal( currentPoint, nextPoint, tempV2_2 );
tempV2_3.copy( tempV2_2 ).multiplyScalar( strokeWidth2 );
nextPointL.copy( currentPoint ).sub( tempV2_3 );
nextPointR.copy( currentPoint ).add( tempV2_3 );
joinIsOnLeftSide = true;
tempV2_3.subVectors( nextPoint, previousPoint );
if ( normal1.dot( tempV2_3 ) < 0 ) {
joinIsOnLeftSide = false;
}
if ( iPoint === 1 ) initialJoinIsOnLeftSide = joinIsOnLeftSide;
tempV2_3.subVectors( nextPoint, currentPoint );
tempV2_3.normalize();
var dot = Math.abs( normal1.dot( tempV2_3 ) );
// If path is straight, don't create join
if ( dot !== 0 ) {
// Compute inner and outer segment intersections
var miterSide = strokeWidth2 / dot;
tempV2_3.multiplyScalar( - miterSide );
tempV2_4.subVectors( currentPoint, previousPoint );
tempV2_5.copy( tempV2_4 ).setLength( miterSide ).add( tempV2_3 );
innerPoint.copy( tempV2_5 ).negate();
var miterLength2 = tempV2_5.length();
var segmentLengthPrev = tempV2_4.length();
tempV2_4.divideScalar( segmentLengthPrev );
tempV2_6.subVectors( nextPoint, currentPoint );
var segmentLengthNext = tempV2_6.length();
tempV2_6.divideScalar( segmentLengthNext );
// Check that previous and next segments doesn't overlap with the innerPoint of intersection
if ( tempV2_4.dot( innerPoint ) < segmentLengthPrev && tempV2_6.dot( innerPoint ) < segmentLengthNext ) {
innerSideModified = true;
}
outerPoint.copy( tempV2_5 ).add( currentPoint );
innerPoint.add( currentPoint );
isMiter = false;
if ( innerSideModified ) {
if ( joinIsOnLeftSide ) {
nextPointR.copy( innerPoint );
currentPointR.copy( innerPoint );
} else {
nextPointL.copy( innerPoint );
currentPointL.copy( innerPoint );
}
} else {
// The segment triangles are generated here if there was overlapping
makeSegmentTriangles();
}
switch ( style.strokeLineJoin ) {
case 'bevel':
makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u1 );
break;
case 'round':
// Segment triangles
createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified );
// Join triangles
if ( joinIsOnLeftSide ) {
makeCircularSector( currentPoint, currentPointL, nextPointL, u1, 0 );
} else {
makeCircularSector( currentPoint, nextPointR, currentPointR, u1, 1 );
}
break;
case 'miter':
case 'miter-clip':
default:
var miterFraction = ( strokeWidth2 * style.strokeMiterLimit ) / miterLength2;
if ( miterFraction < 1 ) {
// The join miter length exceeds the miter limit
if ( style.strokeLineJoin !== 'miter-clip' ) {
makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u1 );
break;
} else {
// Segment triangles
createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified );
// Miter-clip join triangles
if ( joinIsOnLeftSide ) {
tempV2_6.subVectors( outerPoint, currentPointL ).multiplyScalar( miterFraction ).add( currentPointL );
tempV2_7.subVectors( outerPoint, nextPointL ).multiplyScalar( miterFraction ).add( nextPointL );
addVertex( currentPointL, u1, 0 );
addVertex( tempV2_6, u1, 0 );
addVertex( currentPoint, u1, 0.5 );
addVertex( currentPoint, u1, 0.5 );
addVertex( tempV2_6, u1, 0 );
addVertex( tempV2_7, u1, 0 );
addVertex( currentPoint, u1, 0.5 );
addVertex( tempV2_7, u1, 0 );
addVertex( nextPointL, u1, 0 );
} else {
tempV2_6.subVectors( outerPoint, currentPointR ).multiplyScalar( miterFraction ).add( currentPointR );
tempV2_7.subVectors( outerPoint, nextPointR ).multiplyScalar( miterFraction ).add( nextPointR );
addVertex( currentPointR, u1, 1 );
addVertex( tempV2_6, u1, 1 );
addVertex( currentPoint, u1, 0.5 );
addVertex( currentPoint, u1, 0.5 );
addVertex( tempV2_6, u1, 1 );
addVertex( tempV2_7, u1, 1 );
addVertex( currentPoint, u1, 0.5 );
addVertex( tempV2_7, u1, 1 );
addVertex( nextPointR, u1, 1 );
}
}
} else {
// Miter join segment triangles
if ( innerSideModified ) {
// Optimized segment + join triangles
if ( joinIsOnLeftSide ) {
addVertex( lastPointR, u0, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( outerPoint, u1, 0 );
addVertex( lastPointR, u0, 1 );
addVertex( outerPoint, u1, 0 );
addVertex( innerPoint, u1, 1 );
} else {
addVertex( lastPointR, u0, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( outerPoint, u1, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( innerPoint, u1, 0 );
addVertex( outerPoint, u1, 1 );
}
if ( joinIsOnLeftSide ) {
nextPointL.copy( outerPoint );
} else {
nextPointR.copy( outerPoint );
}
} else {
// Add extra miter join triangles
if ( joinIsOnLeftSide ) {
addVertex( currentPointL, u1, 0 );
addVertex( outerPoint, u1, 0 );
addVertex( currentPoint, u1, 0.5 );
addVertex( currentPoint, u1, 0.5 );
addVertex( outerPoint, u1, 0 );
addVertex( nextPointL, u1, 0 );
} else {
addVertex( currentPointR, u1, 1 );
addVertex( outerPoint, u1, 1 );
addVertex( currentPoint, u1, 0.5 );
addVertex( currentPoint, u1, 0.5 );
addVertex( outerPoint, u1, 1 );
addVertex( nextPointR, u1, 1 );
}
}
isMiter = true;
}
break;
}
} else {
// The segment triangles are generated here when two consecutive points are collinear
makeSegmentTriangles();
}
} else {
// The segment triangles are generated here if it is the ending segment
makeSegmentTriangles();
}
if ( ! isClosed && iPoint === numPoints - 1 ) {
// Start line endcap
addCapGeometry( points[ 0 ], point0L, point0R, joinIsOnLeftSide, true, u0 );
}
// Increment loop variables
u0 = u1;
previousPoint = currentPoint;
lastPointL.copy( nextPointL );
lastPointR.copy( nextPointR );
}
if ( ! isClosed ) {
// Ending line endcap
addCapGeometry( currentPoint, currentPointL, currentPointR, joinIsOnLeftSide, false, u1 );
} else if ( innerSideModified && vertices ) {
// Modify path first segment vertices to adjust to the segments inner and outer intersections
var lastOuter = outerPoint;
var lastInner = innerPoint;
if ( initialJoinIsOnLeftSide !== joinIsOnLeftSide ) {
lastOuter = innerPoint;
lastInner = outerPoint;
}
if ( joinIsOnLeftSide ) {
lastInner.toArray( vertices, 0 * 3 );
lastInner.toArray( vertices, 3 * 3 );
if ( isMiter ) {
lastOuter.toArray( vertices, 1 * 3 );
}
} else {
lastInner.toArray( vertices, 1 * 3 );
lastInner.toArray( vertices, 3 * 3 );
if ( isMiter ) {
lastOuter.toArray( vertices, 0 * 3 );
}
}
}
return numVertices;
// -- End of algorithm
// -- Functions
function getNormal( p1, p2, result ) {
result.subVectors( p2, p1 );
return result.set( - result.y, result.x ).normalize();
}
function addVertex( position, u, v ) {
if ( vertices ) {
vertices[ currentCoordinate ] = position.x;
vertices[ currentCoordinate + 1 ] = position.y;
vertices[ currentCoordinate + 2 ] = 0;
if ( normals ) {
normals[ currentCoordinate ] = 0;
normals[ currentCoordinate + 1 ] = 0;
normals[ currentCoordinate + 2 ] = 1;
}
currentCoordinate += 3;
if ( uvs ) {
uvs[ currentCoordinateUV ] = u;
uvs[ currentCoordinateUV + 1 ] = v;
currentCoordinateUV += 2;
}
}
numVertices += 3;
}
function makeCircularSector( center, p1, p2, u, v ) {
// param p1, p2: Points in the circle arc.
// p1 and p2 are in clockwise direction.
tempV2_1.copy( p1 ).sub( center ).normalize();
tempV2_2.copy( p2 ).sub( center ).normalize();
var angle = Math.PI;
var dot = tempV2_1.dot( tempV2_2 );
if ( Math.abs( dot ) < 1 ) angle = Math.abs( Math.acos( dot ) );
angle /= arcDivisions;
tempV2_3.copy( p1 );
for ( var i = 0, il = arcDivisions - 1; i < il; i ++ ) {
tempV2_4.copy( tempV2_3 ).rotateAround( center, angle );
addVertex( tempV2_3, u, v );
addVertex( tempV2_4, u, v );
addVertex( center, u, 0.5 );
tempV2_3.copy( tempV2_4 );
}
addVertex( tempV2_4, u, v );
addVertex( p2, u, v );
addVertex( center, u, 0.5 );
}
function makeSegmentTriangles() {
addVertex( lastPointR, u0, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( currentPointL, u1, 0 );
addVertex( lastPointR, u0, 1 );
addVertex( currentPointL, u1, 1 );
addVertex( currentPointR, u1, 0 );
}
function makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u ) {
if ( innerSideModified ) {
// Optimized segment + bevel triangles
if ( joinIsOnLeftSide ) {
// Path segments triangles
addVertex( lastPointR, u0, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( currentPointL, u1, 0 );
addVertex( lastPointR, u0, 1 );
addVertex( currentPointL, u1, 0 );
addVertex( innerPoint, u1, 1 );
// Bevel join triangle
addVertex( currentPointL, u, 0 );
addVertex( nextPointL, u, 0 );
addVertex( innerPoint, u, 0.5 );
} else {
// Path segments triangles
addVertex( lastPointR, u0, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( currentPointR, u1, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( innerPoint, u1, 0 );
addVertex( currentPointR, u1, 1 );
// Bevel join triangle
addVertex( currentPointR, u, 1 );
addVertex( nextPointR, u, 0 );
addVertex( innerPoint, u, 0.5 );
}
} else {
// Bevel join triangle. The segment triangles are done in the main loop
if ( joinIsOnLeftSide ) {
addVertex( currentPointL, u, 0 );
addVertex( nextPointL, u, 0 );
addVertex( currentPoint, u, 0.5 );
} else {
addVertex( currentPointR, u, 1 );
addVertex( nextPointR, u, 0 );
addVertex( currentPoint, u, 0.5 );
}
}
}
function createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified ) {
if ( innerSideModified ) {
if ( joinIsOnLeftSide ) {
addVertex( lastPointR, u0, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( currentPointL, u1, 0 );
addVertex( lastPointR, u0, 1 );
addVertex( currentPointL, u1, 0 );
addVertex( innerPoint, u1, 1 );
addVertex( currentPointL, u0, 0 );
addVertex( currentPoint, u1, 0.5 );
addVertex( innerPoint, u1, 1 );
addVertex( currentPoint, u1, 0.5 );
addVertex( nextPointL, u0, 0 );
addVertex( innerPoint, u1, 1 );
} else {
addVertex( lastPointR, u0, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( currentPointR, u1, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( innerPoint, u1, 0 );
addVertex( currentPointR, u1, 1 );
addVertex( currentPointR, u0, 1 );
addVertex( innerPoint, u1, 0 );
addVertex( currentPoint, u1, 0.5 );
addVertex( currentPoint, u1, 0.5 );
addVertex( innerPoint, u1, 0 );
addVertex( nextPointR, u0, 1 );
}
}
}
function addCapGeometry( center, p1, p2, joinIsOnLeftSide, start, u ) {
// param center: End point of the path
// param p1, p2: Left and right cap points
switch ( style.strokeLineCap ) {
case 'round':
if ( start ) {
makeCircularSector( center, p2, p1, u, 0.5 );
} else {
makeCircularSector( center, p1, p2, u, 0.5 );
}
break;
case 'square':
if ( start ) {
tempV2_1.subVectors( p1, center );
tempV2_2.set( tempV2_1.y, - tempV2_1.x );
tempV2_3.addVectors( tempV2_1, tempV2_2 ).add( center );
tempV2_4.subVectors( tempV2_2, tempV2_1 ).add( center );
// Modify already existing vertices
if ( joinIsOnLeftSide ) {
tempV2_3.toArray( vertices, 1 * 3 );
tempV2_4.toArray( vertices, 0 * 3 );
tempV2_4.toArray( vertices, 3 * 3 );
} else {
tempV2_3.toArray( vertices, 1 * 3 );
tempV2_3.toArray( vertices, 3 * 3 );
tempV2_4.toArray( vertices, 0 * 3 );
}
} else {
tempV2_1.subVectors( p2, center );
tempV2_2.set( tempV2_1.y, - tempV2_1.x );
tempV2_3.addVectors( tempV2_1, tempV2_2 ).add( center );
tempV2_4.subVectors( tempV2_2, tempV2_1 ).add( center );
var vl = vertices.length;
// Modify already existing vertices
if ( joinIsOnLeftSide ) {
tempV2_3.toArray( vertices, vl - 1 * 3 );
tempV2_4.toArray( vertices, vl - 2 * 3 );
tempV2_4.toArray( vertices, vl - 4 * 3 );
} else {
tempV2_3.toArray( vertices, vl - 2 * 3 );
tempV2_4.toArray( vertices, vl - 1 * 3 );
tempV2_4.toArray( vertices, vl - 4 * 3 );
}
}
break;
case 'butt':
default:
// Nothing to do here
break;
}
}
function removeDuplicatedPoints( points ) {
// Creates a new array if necessary with duplicated points removed.
// This does not remove duplicated initial and ending points of a closed path.
var dupPoints = false;
for ( var i = 1, n = points.length - 1; i < n; i ++ ) {
if ( points[ i ].distanceTo( points[ i + 1 ] ) < minDistance ) {
dupPoints = true;
break;
}
}
if ( ! dupPoints ) return points;
var newPoints = [];
newPoints.push( points[ 0 ] );
for ( var i = 1, n = points.length - 1; i < n; i ++ ) {
if ( points[ i ].distanceTo( points[ i + 1 ] ) >= minDistance ) {
newPoints.push( points[ i ] );
}
}
newPoints.push( points[ points.length - 1 ] );
return newPoints;
}
};
}();
export { SVGLoader };
|
var sendHtml = require("send-data/html")
var homePage = require("../templates/home.js")
module.exports = home
function home(req, res) {
sendHtml(req, res, homePage({ title: "Route seperation example"}))
}
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4V6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z" /></React.Fragment>
, 'StarHalfOutlined');
|
'use strict';
/**
* Module dependencies.
*/
var profiles = require('../controllers/profiles.server.controller');
module.exports = function (app) {
// Profiles collection routes
app.route('/api/profiles')
.get(profiles.list)
.post(profiles.create);
// Single profile routes
app.route('/api/profiles/:providerID/:providerKey').all(profiles.profileByProvider)
.get(profiles.read)
.put(profiles.update)
.delete(profiles.delete);
};
|
import React from 'react';
import { mount } from 'enzyme';
import { BigButton } from '../../../forms/inputs';
describe('<BigButton>', () => {
it('renders Button with overridden props', () => {
const child = <span>Click me!</span>;
const button = mount(
<BigButton
className={ `test` }
overrides={{ color: 'red' }}>{child}
</BigButton>
).find('Button');
expect(button.prop('size')).toEqual('large');
expect(button.prop('color')).toEqual('red');
expect(button.prop('className')).toEqual('big-button test');
});
it(`renders BigButton with any given props`, () => {
const child = <span>Click me!</span>;
const button = mount(
<BigButton alt={ `test` }>
{child}
</BigButton>
).find('Button');
expect(button.prop(`alt`)).toEqual(`test`);
});
});
|
var has = require("./has.js")
var isObject = require("./is-object.js")
var nativeKeys = Object.keys
module.exports = nativeKeys || keys
function keys(obj) {
if (!isObject(obj)) {
return []
}
if (nativeKeys) {
return nativeKeys(obj)
}
var k = []
for (var key in obj) {
if (has(obj, key)) {
k.push(key)
}
}
return k
}
|
Fireball.addTemplate({
name: "Well",
description: "Text well",
template: 'fireball_basic_well',
type: 'component',
settings: {
text: {
name: 'Text',
type: 'html'
}
}
}); |
function getData(...props) {
return function (req, res, next) {
if (!req.body) {
res.writeHead(400);
return res.end();
}
const data = props.concat('origin').reduce((data, prop) => {
if (!data || !req.body[prop]) {
return null;
}
return Object.assign(data, {
[prop]: req.body[prop]
});
}, {});
if (!data) {
res.writeHead(400);
return res.end(`Expected {${props.join(', ')}}`);
}
req.data = data || {};
next();
};
}
function handleError(status, res) {
return function () {
res.writeHead(status);
res.end();
};
}
module.exports = {
getData,
handleError
};
|
describe('I refresh the page', function() {
before(function() {
browser.manage().timeouts().implicitlyWait(100);
return browser.get('http://localhost:9001/');
});
describe('regex', function() {
before(function() {
stepPattern = 'I refresh the page';
});
it('should match "I refresh the page"', function() {
verifyStepMatch('I refresh the page');
});
});
describe('execution', function() {
beforeEach(function() {
sinon.stub(browser, 'refresh');
});
afterEach(function() {
browser.refresh.restore();
});
it('should refresh the page', function() {
return executeStep('I refresh the page', function() {
expect(browser.refresh).to.have.been.calledOnce;
});
});
});
});
|
// Generated by IcedCoffeeScript 1.3.1b
(function() {
var key, val, _ref;
_ref = require('./coffee-script');
for (key in _ref) {
val = _ref[key];
exports[key] = val;
}
}).call(this);
|
var markzero = require('markzero');
var abs = markzero.links.abs;
var isAbsolute = markzero.links.isAbsolute;
var isHash = markzero.links.isHash;
var anchor = markzero.links.anchor;
/**
* @func absolute(token)
*
* @api private
*
* Modifies URLs to be absolute within inline text blocks.
*
* @param The meta data.
*/
module.exports = function middleware(meta) {
if(!meta.base) {
return;
}
return function absolute(token, tokens, next) {
if(!arguments.length) {
return;
}
var types = ['paragraph', 'text'];
if(token.text && ~types.indexOf(token.type)) {
var re = /\[([^\]]+)\]\(([^)]*)\)/g, result, text, href, start, end;
while((result = re.exec(token.text))) {
text = result[1]; href = result[2];
if(!meta.hash && isHash(href)) {
continue;
}
if(isAbsolute(href)) {
continue;
}
href = abs(href, meta);
start = token.text.substr(0, result.index);
end = token.text.substr(result.index + result[0].length);
token.text = start + anchor(text, href) + end;
}
}
next();
}
}
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M17.5 10.5h2v1h-2v-1zm-13 0h2v3h-2v-3zM23 3H1v18h22V3zM8 13.5c0 .85-.65 1.5-1.5 1.5H3V9h3.5c.85 0 1.5.65 1.5 1.5v3zm4.62 1.5h-1.5L9.37 9h1.5l1 3.43 1-3.43h1.5l-1.75 6zM21 12.9h-.9L21 15h-1.5l-.85-2H17.5v2H16V9h5v3.9z" /></React.Fragment>
, 'FiberDvrSharp');
|
(function ($) {
'use strict';
// Vars
var accordion = $('.accordion'),
accordionHeader = $('.accordion__header'),
accordionContent = $('.accordion__content'),
showOneAnswerAtATime = false;
/**
* Save question focus
*/
var saveFocus = function (elem, thisAccordionHeaders) {
// Reset other tab attributes
thisAccordionHeaders.each(function () {
$(this).attr('tabindex', '-1');
$(this).attr('aria-selected', 'false');
});
// Set this tab attributes
elem.attr({
'tabindex': '0',
'aria-selected': 'true'
});
};
/**
* Show answer on click
*/
var showHeader = function (elem, thisAccordionHeaders) {
var thisFaqAnswer = elem.next();
// Save focus
saveFocus(elem, thisAccordionHeaders);
// Set this tab attributes
if (thisFaqAnswer.hasClass('accordion__content--show')) {
// Hide answer
thisFaqAnswer.removeClass('accordion__content--show');
elem.attr('aria-expanded', 'false');
thisFaqAnswer.attr('aria-hidden', 'true');
} else {
if (showOneAnswerAtATime) {
// Hide all answers
accordionContent.removeClass('accordion__content--show').attr('aria-hidden', 'true');
accordionHeader.attr('aria-expanded', 'false');
}
// Show answer
thisFaqAnswer.addClass('accordion__content--show');
elem.attr('aria-expanded', 'true');
thisFaqAnswer.attr('aria-hidden', 'false');
}
};
/**
* Keyboard interaction
*/
var keyboardInteraction = function (elem, e, thisAccordionHeaders) {
var keyCode = e.which,
nextQuestion = elem.next().next().is('dt') ? elem.next().next() : false,
previousQuestion = elem.prev().prev().is('dt') ? elem.prev().prev() : false,
firstQuestion = elem.parent().find('dt:first'),
lastQuestion = elem.parent().find('dt:last');
switch(keyCode) {
// Left/Up
case 37:
case 38:
e.preventDefault();
e.stopPropagation();
// Check for previous question
if (!previousQuestion) {
// No previous, set focus on last question
lastQuestion.focus();
} else {
// Move focus to previous question
previousQuestion.focus();
}
break;
// Right/Down
case 39:
case 40:
e.preventDefault();
e.stopPropagation();
// Check for next question
if (!nextQuestion) {
// No next, set focus on first question
firstQuestion.focus();
} else {
// Move focus to next question
nextQuestion.focus();
}
break;
// Home
case 36:
e.preventDefault();
e.stopPropagation();
// Set focus on first question
firstQuestion.focus();
break;
// End
case 35:
e.preventDefault();
e.stopPropagation();
// Set focus on last question
lastQuestion.focus();
break;
// Enter/Space
case 13:
case 32:
e.preventDefault();
e.stopPropagation();
// Show answer content
showHeader(elem, thisAccordionHeaders);
break;
}
};
/**
* On load, setup roles and initial properties
*/
// Each FAQ Question
accordionHeader.each(function (i) {
$(this).attr({
'id': 'accordion__header--' + i,
'role': 'tab',
'aria-controls': 'accordion__content--' + i,
'aria-expanded': 'false',
'aria-selected': 'false',
'tabindex': '-1'
});
});
// Each FAQ Answer
accordionContent.each(function (i) {
$(this).attr({
'id': 'accordion__content--' + i,
'role': 'tabpanel',
'aria-labelledby': 'accordion__header--' + i,
'aria-hidden': 'true'
});
});
// Each FAQ Section
accordion.each(function () {
var $this = $(this),
thisAccordionHeaders = $this.find('.accordion__header');
// Set section attributes
$this.attr({
'role': 'tablist',
'aria-multiselectable': 'true'
});
thisAccordionHeaders.each(function (i) {
var $this = $(this);
// Make first tab clickable
if (i === 0) {
$this.attr('tabindex', '0');
}
// Click event
$this.on('click', function () {
showHeader($(this), thisAccordionHeaders);
});
// Keydown event
$this.on('keydown', function (e) {
keyboardInteraction($(this), e, thisAccordionHeaders);
});
// Focus event
$this.on('focus', function () {
saveFocus($(this), thisAccordionHeaders);
});
});
});
})(jQuery);
|
var searchData=
[
['flags',['flags',['../structENetPacket.html#afe56ea0c19dcbcdb3e48361a8b9ef190',1,'ENetPacket::flags()'],['../structENetPeer.html#acaf5ebc41ab85dc406f43ffff989ea90',1,'ENetPeer::flags()']]],
['fragmentcount',['fragmentCount',['../structENetIncomingCommand.html#a045997566fdb38517b7a775355e5be95',1,'ENetIncomingCommand::fragmentCount()'],['../structENetProtocolSendFragment.html#a8b3afd14b9d2a30683ac404f533bcfa9',1,'ENetProtocolSendFragment::fragmentCount()']]],
['fragmentlength',['fragmentLength',['../structENetOutgoingCommand.html#aff231b94d1bb07bc99f43041ea63cb3c',1,'ENetOutgoingCommand']]],
['fragmentnumber',['fragmentNumber',['../structENetProtocolSendFragment.html#abff93e4f5f1f08ca1aadace7bdf5c437',1,'ENetProtocolSendFragment']]],
['fragmentoffset',['fragmentOffset',['../structENetOutgoingCommand.html#a2e4ca8e0be684aef02086d4f1a778524',1,'ENetOutgoingCommand::fragmentOffset()'],['../structENetProtocolSendFragment.html#a242d3ad63ca86988e4a698cc4bb33c7e',1,'ENetProtocolSendFragment::fragmentOffset()']]],
['fragments',['fragments',['../structENetIncomingCommand.html#ab6e89f5c93ffd70301e40920fa453ccd',1,'ENetIncomingCommand']]],
['fragmentsremaining',['fragmentsRemaining',['../structENetIncomingCommand.html#a9a81258c1c0ec7fedfdc0d4ff20807b0',1,'ENetIncomingCommand']]],
['free',['free',['../structENetCallbacks.html#a8a0467be3f7d004b24228e1a3d1d540f',1,'ENetCallbacks']]],
['freecallback',['freeCallback',['../structENetPacket.html#ad602d6b6b35ef88b2b2e080fa5c9dc3d',1,'ENetPacket']]]
];
|
version https://git-lfs.github.com/spec/v1
oid sha256:d18b16702f9f10cffff340b2eb999c417a492418987f6cc0563e9f3d158da4e5
size 8342
|
'use strict';
/**
* hojs
*
* @author Zongmin Lei <leizongmin@gmail.com>
*/
const assert = require('assert');
const Schema = require('../schema');
const { getCallerSourceLine } = require('../utils');
const debug = require('../debug').core;
module.exports = function extendRegister() {
this.api.override = {};
const removeSchemas = (key) => {
for (let i = 0; i < this.api.$schemas.length; i++) {
const s = this.api.$schemas[i];
if (s.key === key) {
this.api.$schemas.splice(i, 1);
i += 1;
}
}
};
/**
* ๆณจๅAPI
*
* @param {String} method HTTP่ฏทๆฑๆนๆณ
* @param {String} path ่ฏทๆฑ่ทฏๅพ
* @param {Boolean} strict ๆฏๅฆไธฅๆ ผๆจกๅผ๏ผไธฅๆ ผๆจกๅผไธไธๅ
่ฎธ้ๅคๆณจๅ็ธๅ็API๏ผ้ป่ฎคไธบ`true`
* @return {Object}
*/
const register = (method, path, strict = true) => {
const s = new Schema(method, path, getCallerSourceLine(this.config.get('api.path')));
const s2 = this.api.$schemaMapping[s.key];
if (strict) {
assert(!s2, `ๅฐ่ฏๆณจๅAPI๏ผ${ s.key }๏ผๆๅจๆไปถ๏ผ${ s.options.sourceFile.absolute }๏ผๅคฑ่ดฅ๏ผๅ ไธบ่ฏฅAPIๅทฒๅจๆไปถ${ s2 && s2.options.sourceFile.absolute }ไธญๆณจๅ่ฟ`);
}
if (s2) {
removeSchemas(s.key);
debug('override API: %s %s at %s', method, path, s.options.sourceFile.absolute);
}
this.api.$schemas.push(s);
this.api.$schemaMapping[s.key] = s;
return s;
};
for (const method of Schema.SUPPORT_METHOD) {
this.api[method] = (path) => {
return register(method, path, true);
};
this.api.override[method] = (path) => {
return register(method, path, false);
};
}
};
|
({
__proto__: a,
__proto__: a,
a: a = 1
})
|
import Helper from './_helper';
import { module, test } from 'qunit';
module('Integration | ORM | Has Many | Named Reflexive | new', function(hooks) {
hooks.beforeEach(function() {
this.helper = new Helper();
this.schema = this.helper.schema;
});
test('the parent accepts a saved child id', function(assert) {
let tagA = this.helper.savedChild();
let tagB = this.schema.tags.new({
labelIds: [ tagA.id ]
});
assert.deepEqual(tagB.labelIds, [ tagA.id ]);
assert.deepEqual(tagB.labels.models[0], tagA);
});
test('the parent errors if the children ids don\'t exist', function(assert) {
assert.throws(function() {
this.schema.tags.new({ labelIds: [ 2 ] });
}, /You're instantiating a tag that has a labelIds of 2, but some of those records don't exist in the database/);
});
test('the parent accepts null children foreign key', function(assert) {
let tag = this.schema.tags.new({ labelIds: null });
assert.equal(tag.labels.models.length, 0);
assert.deepEqual(tag.labelIds, []);
assert.deepEqual(tag.attrs, { labelIds: null });
});
test('the parent accepts saved children', function(assert) {
let tagA = this.helper.savedChild();
let tagB = this.schema.tags.new({ labels: [ tagA ] });
assert.deepEqual(tagB.labelIds, [ tagA.id ]);
assert.deepEqual(tagB.labels.models[0], tagA);
});
test('the parent accepts new children', function(assert) {
let tagA = this.schema.tags.new({ color: 'Red' });
let tagB = this.schema.tags.new({ labels: [ tagA ] });
assert.deepEqual(tagB.labelIds, [ undefined ]);
assert.deepEqual(tagB.labels.models[0], tagA);
});
test('the parent accepts null children', function(assert) {
let tag = this.schema.tags.new({ labels: null });
assert.equal(tag.labels.models.length, 0);
assert.deepEqual(tag.labelIds, []);
assert.deepEqual(tag.attrs, { labelIds: null });
});
test('the parent accepts children and child ids', function(assert) {
let tagA = this.helper.savedChild();
let tagB = this.schema.tags.new({ labels: [ tagA ], labelIds: [ tagA.id ] });
assert.deepEqual(tagB.labelIds, [ tagA.id ]);
assert.deepEqual(tagB.labels.models[0], tagA);
});
test('the parent accepts no reference to children or child ids as empty obj', function(assert) {
let tag = this.schema.tags.new({});
assert.deepEqual(tag.labelIds, []);
assert.deepEqual(tag.labels.models, []);
assert.deepEqual(tag.attrs, { labelIds: null });
});
test('the parent accepts no reference to children or child ids', function(assert) {
let tag = this.schema.tags.new();
assert.deepEqual(tag.labelIds, []);
assert.deepEqual(tag.labels.models, []);
assert.deepEqual(tag.attrs, { labelIds: null });
});
});
|
'use strict';
var MACROUTILS = require( 'osg/Utils' );
var BufferArray = require( 'osg/BufferArray' );
var Geometry = require( 'osg/Geometry' );
var NodeVisitor = require( 'osg/NodeVisitor' );
var PrimitiveSet = require( 'osg/PrimitiveSet' );
var Vec3 = require( 'osg/Vec3' );
var osg = MACROUTILS;
var TangentSpaceGenerator = function () {
NodeVisitor.call( this );
this._T = undefined;
this._B = undefined;
this._N = undefined;
this._texCoordUnit = 0;
};
TangentSpaceGenerator.prototype = MACROUTILS.objectInherit( NodeVisitor.prototype, {
apply: function ( node ) {
if ( node.getTypeID() === Geometry.getTypeID() )
this.generate( node, this._texCoordUnit );
else
this.traverse( node );
},
setTexCoordUnit: function ( texCoordUnit ) {
this._texCoordUnit = texCoordUnit;
},
computePrimitiveSet: function ( geometry, primitiveSet ) {
// no indices -> exit
if ( !primitiveSet.getIndices )
return;
var numIndices = primitiveSet.getNumIndices();
var vx = geometry.getAttributes().Vertex;
var nx = geometry.getAttributes().Normal;
var tx = geometry.getAttributes()[ 'TexCoord' + this._texCoordUnit ];
var i;
if ( primitiveSet.getMode() === PrimitiveSet.TRIANGLES ) {
for ( i = 0; i < numIndices; i += 3 ) {
this.compute( primitiveSet, vx, nx, tx, i, i + 1, i + 2 );
}
} else if ( primitiveSet.getMode() === PrimitiveSet.TRIANGLE_STRIP ) {
for ( i = 0; i < numIndices - 2; ++i ) {
if ( ( i % 2 ) === 0 ) {
this.compute( primitiveSet, vx, nx, tx, i, i + 1, i + 2 );
} else {
this.compute( primitiveSet, vx, nx, tx, i + 1, i, i + 2 );
}
}
}
},
generate: function ( geometry, texCoordUnit ) {
this._texCoordUnit = texCoordUnit;
if ( this._texCoordUnit === undefined )
this._texCoordUnit = 0;
var size = geometry.getAttributes().Vertex.getElements().length;
this._T = new osg.Float32Array( size );
this._B = new osg.Float32Array( size );
this._N = new osg.Float32Array( size );
geometry.getPrimitiveSetList().forEach( function ( primitiveSet ) {
this.computePrimitiveSet( geometry, primitiveSet );
}, this );
var nbElements = size / 3;
var tangents = new osg.Float32Array( nbElements * 4 );
var tmp0 = Vec3.create();
var tmp1 = Vec3.create();
var t3 = Vec3.create();
for ( var i = 0; i < nbElements; i++ ) {
var t = this._T.subarray( i * 3, i * 3 + 3 );
var n = this._N.subarray( i * 3, i * 3 + 3 );
var b = this._B.subarray( i * 3, i * 3 + 3 );
Vec3.normalize( n, n );
// Gram-Schmidt orthogonalize
// Vec3 t3 = (t - n * (n * t));
// t3.normalize();
// finalTangent = Vec4(t3, 0.0);
// Calculate handedness
// finalTangent[3] = (((n ^ t) * b) < 0.0) ? -1.0 : 1.0;
// The bitangent vector B is then given by B = (N ร T) ยท Tw
var nt = Vec3.dot( n, t );
Vec3.mult( n, nt, tmp1 );
Vec3.sub( t, tmp1, tmp0 );
Vec3.normalize( tmp0, t3 );
Vec3.cross( n, t, tmp0 );
var sign = Vec3.dot( tmp0, b );
sign = sign < 0.0 ? -1.0 : 0.0;
// TODO perf : cache index var id = i * 4;
tangents[ i * 4 ] = t3[ 0 ];
tangents[ i * 4 + 1 ] = t3[ 1 ];
tangents[ i * 4 + 2 ] = t3[ 2 ];
tangents[ i * 4 + 3 ] = sign;
}
geometry.getAttributes().Normal.setElements( this._N );
geometry.getAttributes().Tangent = new BufferArray( 'ARRAY_BUFFER', tangents, 4 );
},
compute: function ( primitiveSet, vx, nx, tx, ia, ib, ic ) {
var i0 = primitiveSet.index( ia );
var i1 = primitiveSet.index( ib );
var i2 = primitiveSet.index( ic );
// TODO perf : cache xx.getElements() but more importantly
// subarray call have very high overhead, it's super useful
// when you call it a few times for big array chunk, but for
// small array extraction (each vertex) it's better to use a temporary
// pre allocated array and simply fill it
// then, you'll have to write in the big arrays at the end
var P1 = vx.getElements().subarray( i0 * 3, i0 * 3 + 3 );
var P2 = vx.getElements().subarray( i1 * 3, i1 * 3 + 3 );
var P3 = vx.getElements().subarray( i2 * 3, i2 * 3 + 3 );
var N1 = nx.getElements().subarray( i0 * 3, i0 * 3 + 3 );
var N2 = nx.getElements().subarray( i1 * 3, i1 * 3 + 3 );
var N3 = nx.getElements().subarray( i2 * 3, i2 * 3 + 3 );
var uv1 = tx.getElements().subarray( i0 * 2, i0 * 2 + 2 );
var uv2 = tx.getElements().subarray( i1 * 2, i1 * 2 + 2 );
var uv3 = tx.getElements().subarray( i2 * 2, i2 * 2 + 2 );
var vz, vy;
// TODO perf : use temporary vec
var V = Vec3.create();
var B1 = Vec3.create();
var B2 = Vec3.create();
var B3 = Vec3.create();
var T1 = Vec3.create();
var T2 = Vec3.create();
var T3 = Vec3.create();
var v1 = Vec3.create();
var v2 = Vec3.create();
Vec3.set( P2[ 0 ] - P1[ 0 ], uv2[ 0 ] - uv1[ 0 ], uv2[ 1 ] - uv1[ 1 ], v1 );
Vec3.set( P3[ 0 ] - P1[ 0 ], uv3[ 0 ] - uv1[ 0 ], uv3[ 1 ] - uv1[ 1 ], v2 );
Vec3.cross( v1, v2, V );
if ( V[ 0 ] !== 0.0 ) {
Vec3.normalize( V, V );
vy = -V[ 1 ] / V[ 0 ];
vz = -V[ 2 ] / V[ 0 ];
T1[ 0 ] += vy;
B1[ 0 ] += vz;
T2[ 0 ] += vy;
B2[ 0 ] += vz;
T3[ 0 ] += vy;
B3[ 0 ] += vz;
}
Vec3.set( P2[ 1 ] - P1[ 1 ], uv2[ 0 ] - uv1[ 0 ], uv2[ 1 ] - uv1[ 1 ], v1 );
Vec3.set( P3[ 1 ] - P1[ 1 ], uv3[ 0 ] - uv1[ 0 ], uv3[ 1 ] - uv1[ 1 ], v2 );
Vec3.cross( v1, v2, V );
if ( V[ 0 ] !== 0.0 ) {
Vec3.normalize( V, V );
vy = -V[ 1 ] / V[ 0 ];
vz = -V[ 2 ] / V[ 0 ];
T1[ 1 ] += vy;
B1[ 1 ] += vz;
T2[ 1 ] += vy;
B2[ 1 ] += vz;
T3[ 1 ] += vy;
B3[ 1 ] += vz;
}
Vec3.set( P2[ 2 ] - P1[ 2 ], uv2[ 0 ] - uv1[ 0 ], uv2[ 1 ] - uv1[ 1 ], v1 );
Vec3.set( P3[ 2 ] - P1[ 2 ], uv3[ 0 ] - uv1[ 0 ], uv3[ 1 ] - uv1[ 1 ], v2 );
Vec3.cross( v1, v2, V );
if ( V[ 0 ] !== 0.0 ) {
Vec3.normalize( V, V );
vy = -V[ 1 ] / V[ 0 ];
vz = -V[ 2 ] / V[ 0 ];
T1[ 2 ] += vy;
B1[ 2 ] += vz;
T2[ 2 ] += vy;
B2[ 2 ] += vz;
T3[ 2 ] += vy;
B3[ 2 ] += vz;
}
var tempVec = Vec3.create();
var tempVec2 = Vec3.create();
var Tdst, Bdst, Ndst;
Vec3.cross( N1, T1, tempVec );
Vec3.cross( tempVec, N1, tempVec2 );
Tdst = this._T.subarray( i0 * 3, i0 * 3 + 3 );
Vec3.add( tempVec2, Tdst, Tdst );
Vec3.cross( B1, N1, tempVec );
Vec3.cross( N1, tempVec, tempVec2 );
Bdst = this._B.subarray( i0 * 3, i0 * 3 + 3 );
Vec3.add( tempVec2, Bdst, Bdst );
Vec3.cross( N2, T2, tempVec );
Vec3.cross( tempVec, N2, tempVec2 );
Tdst = this._T.subarray( i1 * 3, i1 * 3 + 3 );
Vec3.add( tempVec2, Tdst, Tdst );
Vec3.cross( B2, N2, tempVec );
Vec3.cross( N2, tempVec, tempVec2 );
Bdst = this._B.subarray( i1 * 3, i1 * 3 + 3 );
Vec3.add( tempVec2, Bdst, Bdst );
Vec3.cross( N3, T3, tempVec );
Vec3.cross( tempVec, N3, tempVec2 );
Tdst = this._T.subarray( i2 * 3, i2 * 3 + 3 );
Vec3.add( tempVec2, Tdst, Tdst );
Vec3.cross( B3, N3, tempVec );
Vec3.cross( N3, tempVec, tempVec2 );
Bdst = this._B.subarray( i2 * 3, i2 * 3 + 3 );
Vec3.add( tempVec2, Bdst, Bdst );
Ndst = this._N.subarray( i0 * 3, i0 * 3 + 3 );
Vec3.add( N1, Ndst, Ndst );
Ndst = this._N.subarray( i1 * 3, i1 * 3 + 3 );
Vec3.add( N2, Ndst, Ndst );
Ndst = this._N.subarray( i2 * 3, i2 * 3 + 3 );
Vec3.add( N3, Ndst, Ndst );
}
} );
module.exports = TangentSpaceGenerator;
|
import React from 'react';
import { i18n } from 'gutenberg/utils/helpers';
import isEmpty from 'lodash/isEmpty';
import { getRawContent } from 'gutenberg/utils/data';
// We should use this... but no time for now
// import { __ } from '@wordpress/i18n';
import { RawHTML } from '@wordpress/element';
import edit from './edit';
const name = 'divi/placeholder';
const tag = `wp:${name}`;
const unwrap = content => content.replace(RegExp(`<!-- /?${tag} /?-->`, 'g'), '');
const encode = content => unwrap(content).replace(/<!-- (\/)?wp:([^:]+) -->/g, '<!-- $1divi:$2 -->');
const wrap = content => `<!-- ${tag} -->${encode(content)}<!-- /${tag} -->`;
const shortcode = (content) => {
if (isEmpty(content) || content.indexOf('[et_pb_section') >= 0) {
// If content is empty or already has shortcode, do nothing
return content;
}
let modified = content;
// Add Text Module.
modified = `[et_pb_text]${modified}[/et_pb_text]`;
// Add Column.
modified = `[et_pb_column type="4_4"]${modified}[/et_pb_column]`;
// Add Row.
modified = `[et_pb_row]${modified}[/et_pb_row]`;
// Add Section.
modified = `[et_pb_section]${modified}[/et_pb_section]`;
return modified;
};
let processed = false;
const { placeholder: { block: { title, description } } } = i18n();
const icon = (
<svg
aria-hidden="true"
role="img"
focusable="false"
className="dashicon dashicons-format-image"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 16 16"
>
<path
d="M7.5,6H7v4h0.5c2.125,0,2.125-1.453,2.125-2C9.625,7.506,9.625,6,7.5,6z M8,3C5.239,3,3,5.239,3,8
c0,2.761,2.239,5,5,5s5-2.239,5-5C13,5.239,10.761,3,8,3z M7.5,11h-1C6.224,11,6,10.761,6,10.467V5.533C6,5.239,6.224,5,6.5,5
c0,0,0.758,0,1,0c1.241,0,3.125,0.51,3.125,3C10.625,10.521,8.741,11,7.5,11z"
/>
</svg>
);
export default {
name,
tag,
settings: {
title,
description,
icon,
category: 'embed',
useOnce: true,
attributes: {
content: {
type: 'string',
source: 'html',
},
builder: {
type: 'string',
source: 'meta',
meta: '_et_pb_use_builder',
},
old: {
type: 'string',
source: 'meta',
meta: '_et_pb_old_content',
},
},
supports: {
// This is needed or else GB will try to wrap the shortcode with an extra div.className
// causing a validation error
className: false,
customClassName: false,
html: false,
},
save: props => <RawHTML>{ props.attributes.content }</RawHTML>,
edit,
},
hooks: {
// Aight, all the following is needed because GB performs block validation
// which will fail if the shortcode includes invalid HTML.
// In this case, GB would show an error message instead of our custom block
// and we can't allow that to happen.
'divi.addPlaceholder': (content) => {
processed = shortcode(content);
return wrap(processed);
},
'blocks.getSaveElement': (element, blockType) => {
if (blockType.name !== name) {
return element;
}
return <RawHTML>{ encode(processed === false ? getRawContent() : processed) }</RawHTML>;
},
},
};
|
{
"name": "notification.js",
"url": "https://github.com/timseverien/notification.js.git"
}
|
'use strict';
var ShelfHelper = require('../../lib/shelf-helper.js').ShelfHelper;
var AssertsHelper = require ('../../lib/asserts-helper.js').AssertsHelper;
var EditorHelper = require ('../../lib/editor-helper.js').EditorHelper;
describe('shelf',function(){
var shelf = new ShelfHelper();
var designerAsserts = new AssertsHelper();
var editor = new EditorHelper();
var namedParameters = ['baseUriParameters', 'headers', 'queryParameters'];
describe('traits elements',function(){
it('check elements at trait level', function (){
var definition = [
'#%RAML 0.8',
'title: The API',
'traits: ',
' - trait1: ',
' '
].join('\\n');
editor.setValue(definition);
editor.setCursor(5,6);
designerAsserts.ShelfElementsByGroup(shelf.elemTraitsByGroup);
});
describe('Named Parameters', function(){
namedParameters.forEach(function(namedParameter){
it(namedParameter+'displayed on the shelf', function(){
var definition = [
'#%RAML 0.8',
'title: The API',
'traits: ',
' - trait1: ',
' '+namedParameter+': ',
' hola: ',
' '
].join('\\n');
editor.setValue(definition);
editor.setCursor(7,10);
designerAsserts.ShelfElementsByGroup(shelf.elemNamedParametersByGroups);
});
});
describe('after being selected', function(){
var options = shelf.elemNamedParametersLevel;
namedParameters.forEach(function(namedParameter){
options.forEach(function(option){
it(namedParameter+': '+option+' is no longer displayed on the shelf', function(){
shelf = new ShelfHelper();
var definition = [
'#%RAML 0.8',
'title: The API',
'traits: ',
' - trait1: ',
' '+namedParameter+': ',
' hola:',
' '+option+':',
' '
].join('\\n');
editor.setValue(definition);
editor.setCursor(8,10);
designerAsserts.shelfElementsNotDisplayed([option], shelf.elemNamedParametersLevel);
});
});
});
}); // Not displayed after being selected
}); //NAmed Parameter
describe('response', function(){
it('displayed on the shelf', function(){
var definition = [
'#%RAML 0.8',
'title: The API',
'traits: ',
' - trait1: ',
' responses: ',
' 200: ',
' '
].join('\\n');
editor.setValue(definition);
editor.setCursor(7,10);
designerAsserts.ShelfElementsByGroup(shelf.elemResponsesByGroup);
});
describe('after being selected', function(){
it('displayName is no longer displayed on the shelf', function(){
shelf = new ShelfHelper();
var definition = [
'#%RAML 0.8',
'title: The API',
'traits: ',
' - trait1: ',
' responses: ',
' 200: ',
' description: ',
' '
].join('\\n');
editor.setValue(definition);
editor.setCursor(8,10);
var list2 =['description'];
designerAsserts.shelfElementsNotDisplayed(list2, shelf.elemResponsesLevel);
});
it('displayName is no longer displayed on the shelf', function(){
shelf = new ShelfHelper();
var definition = [
'#%RAML 0.8',
'title: The API',
'traits: ',
' - trait1: ',
' responses: ',
' 200: ',
' body: ',
' '
].join('\\n');
editor.setValue(definition);
editor.setCursor(8,10);
var list2 =['body'];
designerAsserts.shelfElementsNotDisplayed(list2, shelf.elemResponsesLevel);
});
}); // Not displayed after select
}); //response
describe('body', function(){
}); //body
describe('after being selected', function(){
var options = shelf.elemTraitsLevel;
options.forEach(function(option){
it(option+': property is no longer displayed on the shelf', function(){
shelf = new ShelfHelper();
var definition = [
'#%RAML 0.8',
'title: The API',
'traits: ',
' - trait1: ',
' '+option+': ',
' '
].join('\\n');
editor.setValue(definition);
editor.setCursor(6,6);
var list2 =[option];
designerAsserts.shelfElementsNotDisplayed(list2, shelf.elemTraitsLevel);
});
});
});// Don't displayed after select
});//traits elements
}); // shelf
|
/**
* Download vendor deps
*/
'use strict';
// Intrinsic mods
var path = require('path');
var https = require('https');
// Npm mods
var _ = require('lodash');
var fs = require('fs-extra');
// Pkg.json
var pkgJson = require('./../package.json');
// Files we need and the projects from whence they came.
// @todo: check whether this actually is set?
var assets = pkgJson.postInstallAssets;
/*
* Get the minor version of the current project
*/
var getMinorVersion = function() {
// Should already be loaded but just in case
if (!pkgJson) {
pkgJson = require('./../package.json');
}
// Split the version and send back the minor part
var parts = pkgJson.version.split('.');
return parts[1];
};
/*
* Simple function to make a github api request
*/
var request = function(options, callback) {
// Request object
var req = https.request(options, function(res) {
// Need a string not a buffer
res.setEncoding('utf8');
// Collector
var responseString = '';
// Collect the stream
res.on('data', function(data) {
responseString += data;
});
// Return the JSON parsed stream
res.on('end', function() {
callback(JSON.parse(responseString));
});
});
// Handle errors
req.on('error', function(err) {
console.error(err);
});
// End request
req.end();
};
/*
* We can't rely on Kalabox stuff in this file so we need to do this
* to get the users home dir
*/
var getHomeDir = function() {
// Check the env for the home path
var platformIsWindows = process.platform === 'win32';
var envKey = platformIsWindows ? 'USERPROFILE' : 'HOME';
// Homeward bound
return process.env[envKey];
};
/*
* We can't rely on Kalabox stuff in this file so we need to do this
* to get dev mod
*/
var getDevMode = function() {
// Set for usage later
var devMode;
// If the environment is a no go try to load from custom kalabox.json
if (process.env.KALABOX_DEV === undefined) {
// Construct kbox.json path
var kboxJsonFile = path.join(getHomeDir(), '.kalabox', 'kalabox.json');
// Check it kbox json exists
if (fs.existsSync(kboxJsonFile)) {
// Load it
var kboxJson = require(kboxJsonFile);
// Use its dev mode if its set
devMode = (kboxJson.devMode) ? kboxJson.devMode : false;
}
}
// Use the envvar if its set
else {
// Set it
devMode = (process.env.KALABOX_DEV) ? process.env.KALABOX_DEV : false;
}
// Return something
return devMode;
};
/*
* Get the project tag/branch we should be pulling from
*/
var getProjectVersion = function(project, callback) {
// If we are in dev mode this is trivial
if (getDevMode() === true || getDevMode() === 'true') {
callback('v' + ['0', getMinorVersion()].join('.'));
}
// If not we need to do some exploration on the github API
else {
// Request opts to find the github tags for a project
var options = {
hostname: 'api.github.com',
port: 443,
path: '/repos/kalabox/' + project + '/tags',
method: 'GET',
json: true,
headers: {'User-Agent': 'Kalabox'}
};
// Make teh request
request(options, function(data) {
// Get the minor version of the current project
var projectVer = getMinorVersion();
// Grab the first tag that shares the minor version
// we assume this lists the most recent tags first
var minorVersion = _.result(_.find(data, function(release) {
if (release.name) {
var minorVersionParts = release.name.split('.');
return projectVer.toString() === minorVersionParts[1];
}
// @todo: What happens if we have no project releases for this version?
}), 'name');
callback(minorVersion);
});
}
};
/*
* Get the minor version for a kalabox github project based on the
* minor version of this project
*/
var writeInternetFile = function(project, location, callback) {
// Get version we are going to use before we start
getProjectVersion(project, function(version) {
// This protects against the use case where you aren't in dev mode
// but you also have no published packages for the minor version
if (version === undefined) {
callback(false);
}
else {
// this should be the github path
var urlPath = ['kalabox', project, version, location].join('/');
// Request opts for RAW github content
var options = {
hostname: 'raw.githubusercontent.com',
port: 443,
path: '/' + urlPath,
method: 'GET',
headers: {'User-Agent': 'Kalabox'}
};
// Create our vendor dirs if needed
var filePath = path.join('vendor', project, path.dirname(location));
fs.mkdirsSync(filePath);
// Construct the file object
var fileName = path.basename(location);
var file = fs.createWriteStream(path.join(filePath, fileName));
// Make the request and write the stream to file
var req = https.request(options, function(res) {
// Wrtie stream to disk
res.on('data', function(d) {
file.write(d);
});
// Return some stuff
res.on('end', function() {
callback(urlPath, filePath);
});
});
// Fin
req.end();
// Errors
req.on('error', function(err) {
console.error(err);
});
}
});
};
// Downlaod our files and put them in their place
_.forEach(assets, function(files, project) {
_.forEach(files, function(file, purpose) {
var options = {
hostname: 'api.github.com',
port: 443,
path: '/repos/kalabox/' + project + '/tags',
method: 'GET',
json: true,
headers: {'User-Agent': 'Kalabox'}
};
writeInternetFile(project, file, function(url, loc) {
var msg;
if (url === false) {
msg = 'No latest package for this version. Try running in devMode';
}
else {
msg = 'Grabbed a file from ' + url + ' doth put it hither: ' + loc;
}
console.log(msg);
});
});
});
|
var config = require( './config' );
var Winston = require( 'winston' );
// Build new Winston logger and return
module.exports = new (Winston.Logger)({
transports: [
new (Winston.transports.Console)({
colorize: true,
timestamp: true
}),
new (Winston.transports.File)({
filename: config.basePath + 'logs/' + 'app.log',
maxsize: 100 * 1024 * 1024,
maxFiles: 5
})
]
});
|
(function() {
'use strict';
angular
.module('echarliApp')
.factory('DateUtils', DateUtils);
DateUtils.$inject = ['$filter'];
function DateUtils ($filter) {
var service = {
convertDateTimeFromServer : convertDateTimeFromServer,
convertLocalDateFromServer : convertLocalDateFromServer,
convertLocalDateToServer : convertLocalDateToServer,
dateformat : dateformat
};
return service;
function convertDateTimeFromServer (date) {
if (date) {
return new Date(date);
} else {
return null;
}
}
function convertLocalDateFromServer (date) {
if (date) {
var dateString = date.split('-');
return new Date(dateString[0], dateString[1] - 1, dateString[2]);
}
return null;
}
function convertLocalDateToServer (date) {
if (date) {
return $filter('date')(date, 'yyyy-MM-dd');
} else {
return null;
}
}
function dateformat () {
return 'yyyy-MM-dd';
}
}
})();
|
$(document).ready(function() {
window.TABLE = $('#references-table').DataTable({
"iDisplayLength": 25,
fixedHeader: {headerOffset: 50},
responsive: true,
"order": [[2, "asc"]],
"aoColumnDefs": [
{
"className": "dt-center",
"bSortable": false,
"width": '5%',
"targets": [0, 1]
},
{
'className': 'none',
"targets": [5]
}
]
});
});
|
define(['./_baseGet', './_baseSlice'], function(baseGet, baseSlice) {
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
}
return parent;
});
|
export default /* glsl */`
void normalOffsetPointShadow(vec4 shadowParams) {
float distScale = length(dLightDirW);
vec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0) * distScale; //0.02
vec3 dir = wPos - dLightPosW;
dLightDirW = dir;
}
`;
|
var gridOptions = {
columnDefs: [
{ field: 'country', rowGroup: true, hide: true },
{ field: 'year', rowGroup: true, hide: true },
{ field: 'sport', minWidth: 200 },
{ field: 'gold' },
{ field: 'silver' },
{ field: 'bronze' },
{ field: 'total' },
{ field: 'age' },
{ field: 'date', minWidth: 140 },
],
defaultColDef: {
flex: 1,
minWidth: 100,
filter: true,
sortable: true,
resizable: true,
},
autoGroupColumnDef: {
headerName: 'Group',
field: 'athlete',
minWidth: 250,
},
enableRangeSelection: true,
animateRows: true,
};
// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
agGrid.simpleHttpRequest({ url: 'https://www.ag-grid.com/example-assets/olympic-winners.json' })
.then(function(data) {
gridOptions.api.setRowData(data);
});
});
|
/*eslint no-console: 0*/
'use strict';
var Core = require('../core/core');
var Track = require('../core/track');
var f = require('util').format;
var uniqueId = require('unique-id');
function noop() {
return this.name;
}
function pad(s, n) {
s = String(s);
while (s.length < n) {
s = '0' + s;
}
return s;
}
function consoleLog() {
// console.log.apply(console, arguments);
}
function buildDeps(unitsCount, onInit) {
var app = new Core({
logging: {
logLevel: 'SILENT'
}
});
var deps;
var currentDepsCount = 1;
var n = String(unitsCount).length;
var unitName = f('u%s', pad(currentDepsCount, n));
var i;
unitsCount = Math.ceil(unitsCount / 2);
while (unitsCount >= currentDepsCount) {
deps = [];
for (i = 0; i < currentDepsCount; i += 1) {
deps[deps.length] = f('u%s', pad(currentDepsCount + i + 1, n));
}
consoleLog('%s (%s)', f('u%s', pad(currentDepsCount, n)), deps.join(', '));
app.unit({
base: 0,
name: f('u%s', pad(currentDepsCount, n)),
deps: deps,
main: noop
});
currentDepsCount += 1;
}
for (i = 0; i < deps.length; i += 1) {
consoleLog('%s ()', deps[i]);
app.unit({
base: 0,
name: deps[i],
deps: [],
main: noop
});
}
app.ready().done(function () {
onInit(function run(done) {
var logger = app.logger.bind(uniqueId());
var track = new Track(app, logger);
var unit = app.getUnit(unitName);
unit.run(track, null, function () {
done();
});
});
});
}
module.exports = buildDeps;
|
import test from 'ava';
import resolveData from '../lib/data';
test('w/o options', t => resolveData('test/fixtures/duplicate-1.jpg')
.then((resolvedDataUrl) => {
t.is(resolvedDataUrl.slice(0, 32), 'data:image/jpeg;base64,/9j/4AAQS');
t.is(resolvedDataUrl.slice(-32), 'GWbO3rSpUIsvhA1vsPh/WlSpVprP/9k=');
}));
test('basePath + loadPaths', t => resolveData('picture.png', {
basePath: 'test/fixtures',
loadPaths: ['fonts', 'images'],
})
.then((resolvedDataUrl) => {
t.is(resolvedDataUrl.slice(0, 32), 'data:image/png;base64,iVBORw0KGg');
t.is(resolvedDataUrl.slice(-32), '+BPCufaJraBKlQAAAABJRU5ErkJggg==');
}));
test('discard query + preserve hash', t => resolveData('test/fixtures/duplicate-1.jpg?foo=bar#hash')
.then((resolvedDataUrl) => {
t.is(resolvedDataUrl.slice(0, 32), 'data:image/jpeg;base64,/9j/4AAQS');
t.is(resolvedDataUrl.slice(-32), 'rSpUIsvhA1vsPh/WlSpVprP/9k=#hash');
}));
test('svg', t => resolveData('test/fixtures/images/vector.svg')
.then((resolvedDataUrl) => {
t.is(resolvedDataUrl.slice(0, 32), 'data:image/svg+xml;charset=utf-8');
t.is(resolvedDataUrl.slice(-32), '0h80z%22%2F%3E%0D%0A%3C%2Fsvg%3E');
}));
test('non-existing file', t => resolveData('non-existing.gif')
.then(t.fail, (err) => {
t.true(err instanceof Error);
t.is(err.message, 'Asset not found or unreadable: non-existing.gif');
}));
test.cb('node-style callback w/o options', (t) => {
resolveData('test/fixtures/duplicate-1.jpg', (err, resolvedDataUrl) => {
t.is(err, null);
t.is(resolvedDataUrl.slice(0, 32), 'data:image/jpeg;base64,/9j/4AAQS');
t.end();
});
});
test.cb('node-style callback w/ options', (t) => {
resolveData('picture.png', {
basePath: 'test/fixtures',
loadPaths: ['fonts', 'images'],
}, (err, resolvedDataUrl) => {
t.is(err, null);
t.is(resolvedDataUrl.slice(0, 32), 'data:image/png;base64,iVBORw0KGg');
t.end();
});
});
test.cb('node-style callback + non-existing file', (t) => {
resolveData('non-existing.gif', (err, resolvedDataUrl) => {
t.true(err instanceof Error);
t.is(err.message, 'Asset not found or unreadable: non-existing.gif');
t.is(resolvedDataUrl, undefined);
t.end();
});
});
|
import _defineProperty from"@babel/runtime/helpers/esm/defineProperty";export function alignProperty(r){var e=r.size,n=r.grid,t=e-e%n,o=t+n;return e-t<o-e?t:o};export function fontGrid(r){var e=r.lineHeight;return r.pixels/(e*r.htmlFontSize)};export function responsiveProperty(r){var e=r.cssProperty,n=r.min,t=r.max,o=r.unit,i=void 0===o?"rem":o,a=r.breakpoints,c=void 0===a?[600,960,1280]:a,p=r.transform,d=void 0===p?null:p,f=_defineProperty({},e,"".concat(n).concat(i)),u=(t-n)/c[c.length-1];return c.forEach(function(r){var t=n+u*r;null!==d&&(t=d(t)),f["@media (min-width:".concat(r,"px)")]=_defineProperty({},e,"".concat(Math.round(1e4*t)/1e4).concat(i))}),f}; |
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import { deepmerge } from '@material-ui/utils';
import formControlState from '../FormControl/formControlState';
import useFormControl from '../FormControl/useFormControl';
import experimentalStyled from '../styles/experimentalStyled';
import capitalize from '../utils/capitalize';
import formHelperTextClasses, { getFormHelperTextUtilityClasses } from './formHelperTextClasses';
import useThemeProps from '../styles/useThemeProps';
import { jsx as _jsx } from "react/jsx-runtime";
const overridesResolver = (props, styles) => {
const {
styleProps
} = props;
return deepmerge(_extends({}, styleProps.size && styles[`size${capitalize(styleProps.size)}`], styleProps.contained && styles.contained, styleProps.filled && styles.filled), styles.root || {});
};
const useUtilityClasses = styleProps => {
const {
classes,
contained,
size,
disabled,
error,
filled,
focused,
required
} = styleProps;
const slots = {
root: ['root', disabled && 'disabled', error && 'error', size && `size${capitalize(size)}`, contained && 'contained', focused && 'focused', filled && 'filled', required && 'required']
};
return composeClasses(slots, getFormHelperTextUtilityClasses, classes);
};
const FormHelperTextRoot = experimentalStyled('p', {}, {
name: 'MuiFormHelperText',
slot: 'Root',
overridesResolver
})(({
theme,
styleProps
}) => _extends({
color: theme.palette.text.secondary
}, theme.typography.caption, {
textAlign: 'left',
marginTop: 3,
marginRight: 0,
marginBottom: 0,
marginLeft: 0,
[`&.${formHelperTextClasses.disabled}`]: {
color: theme.palette.text.disabled
},
[`&.${formHelperTextClasses.error}`]: {
color: theme.palette.error.main
}
}, styleProps.size === 'small' && {
marginTop: 4
}, styleProps.contained && {
marginLeft: 14,
marginRight: 14
}));
const FormHelperText = /*#__PURE__*/React.forwardRef(function FormHelperText(inProps, ref) {
const props = useThemeProps({
props: inProps,
name: 'MuiFormHelperText'
});
const {
children,
className,
component = 'p'
} = props,
other = _objectWithoutPropertiesLoose(props, ["children", "className", "component", "disabled", "error", "filled", "focused", "margin", "required", "variant"]);
const muiFormControl = useFormControl();
const fcs = formControlState({
props,
muiFormControl,
states: ['variant', 'size', 'disabled', 'error', 'filled', 'focused', 'required']
});
const styleProps = _extends({}, props, {
component,
contained: fcs.variant === 'filled' || fcs.variant === 'outlined',
variant: fcs.variant,
size: fcs.size,
disabled: fcs.disabled,
error: fcs.error,
filled: fcs.filled,
focused: fcs.focused,
required: fcs.required
});
const classes = useUtilityClasses(styleProps);
return /*#__PURE__*/_jsx(FormHelperTextRoot, _extends({
as: component,
styleProps: styleProps,
className: clsx(classes.root, className),
ref: ref
}, other, {
children: children === ' ' ?
/*#__PURE__*/
// notranslate needed while Google Translate will not fix zero-width space issue
// eslint-disable-next-line react/no-danger
_jsx("span", {
className: "notranslate",
dangerouslySetInnerHTML: {
__html: '​'
}
}) : children
}));
});
process.env.NODE_ENV !== "production" ? FormHelperText.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content of the component.
*
* If `' '` is provided, the component reserves one line height for displaying a future message.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: PropTypes.elementType,
/**
* If `true`, the helper text should be displayed in a disabled state.
*/
disabled: PropTypes.bool,
/**
* If `true`, helper text should be displayed in an error state.
*/
error: PropTypes.bool,
/**
* If `true`, the helper text should use filled classes key.
*/
filled: PropTypes.bool,
/**
* If `true`, the helper text should use focused classes key.
*/
focused: PropTypes.bool,
/**
* If `dense`, will adjust vertical spacing. This is normally obtained via context from
* FormControl.
*/
margin: PropTypes.oneOf(['dense']),
/**
* If `true`, the helper text should use required classes key.
*/
required: PropTypes.bool,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])
} : void 0;
export default FormHelperText; |
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { DomHandler, classNames, ObjectUtils, IconUtils } from 'primereact/utils';
import { Dialog } from 'primereact/dialog';
import { Button } from 'primereact/button';
import { localeOption } from 'primereact/api';
import { Portal } from 'primereact/portal';
function _extends() {
_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;
};
return _extends.apply(this, arguments);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function confirmDialog(props) {
var appendTo = props.appendTo || document.body;
var confirmDialogWrapper = document.createDocumentFragment();
DomHandler.appendChild(confirmDialogWrapper, appendTo);
props = _objectSpread(_objectSpread({}, props), {
visible: props.visible === undefined ? true : props.visible
});
var confirmDialogEl = /*#__PURE__*/React.createElement(ConfirmDialog, props);
ReactDOM.render(confirmDialogEl, confirmDialogWrapper);
var updateConfirmDialog = function updateConfirmDialog(newProps) {
props = _objectSpread(_objectSpread({}, props), newProps);
ReactDOM.render( /*#__PURE__*/React.cloneElement(confirmDialogEl, props), confirmDialogWrapper);
};
return {
_destroy: function _destroy() {
ReactDOM.unmountComponentAtNode(confirmDialogWrapper);
},
show: function show() {
updateConfirmDialog({
visible: true,
onHide: function onHide() {
updateConfirmDialog({
visible: false
}); // reset
}
});
},
hide: function hide() {
updateConfirmDialog({
visible: false
});
},
update: function update(newProps) {
updateConfirmDialog(newProps);
}
};
}
var ConfirmDialog = /*#__PURE__*/function (_Component) {
_inherits(ConfirmDialog, _Component);
var _super = _createSuper(ConfirmDialog);
function ConfirmDialog(props) {
var _this;
_classCallCheck(this, ConfirmDialog);
_this = _super.call(this, props);
_this.state = {
visible: props.visible
};
_this.reject = _this.reject.bind(_assertThisInitialized(_this));
_this.accept = _this.accept.bind(_assertThisInitialized(_this));
_this.hide = _this.hide.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(ConfirmDialog, [{
key: "acceptLabel",
value: function acceptLabel() {
return this.props.acceptLabel || localeOption('accept');
}
}, {
key: "rejectLabel",
value: function rejectLabel() {
return this.props.rejectLabel || localeOption('reject');
}
}, {
key: "accept",
value: function accept() {
if (this.props.accept) {
this.props.accept();
}
this.hide('accept');
}
}, {
key: "reject",
value: function reject() {
if (this.props.reject) {
this.props.reject();
}
this.hide('reject');
}
}, {
key: "show",
value: function show() {
this.setState({
visible: true
});
}
}, {
key: "hide",
value: function hide(result) {
var _this2 = this;
this.setState({
visible: false
}, function () {
if (_this2.props.onHide) {
_this2.props.onHide(result);
}
});
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.visible !== this.props.visible) {
this.setState({
visible: this.props.visible
});
}
}
}, {
key: "renderFooter",
value: function renderFooter() {
var acceptClassName = classNames('p-confirm-dialog-accept', this.props.acceptClassName);
var rejectClassName = classNames('p-confirm-dialog-reject', {
'p-button-text': !this.props.rejectClassName
}, this.props.rejectClassName);
var content = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Button, {
label: this.rejectLabel(),
icon: this.props.rejectIcon,
className: rejectClassName,
onClick: this.reject
}), /*#__PURE__*/React.createElement(Button, {
label: this.acceptLabel(),
icon: this.props.acceptIcon,
className: acceptClassName,
onClick: this.accept,
autoFocus: true
}));
if (this.props.footer) {
var defaultContentOptions = {
accept: this.accept,
reject: this.reject,
acceptClassName: acceptClassName,
rejectClassName: rejectClassName,
acceptLabel: this.acceptLabel(),
rejectLabel: this.rejectLabel(),
element: content,
props: this.props
};
return ObjectUtils.getJSXElement(this.props.footer, defaultContentOptions);
}
return content;
}
}, {
key: "renderElement",
value: function renderElement() {
var className = classNames('p-confirm-dialog', this.props.className);
var dialogProps = ObjectUtils.findDiffKeys(this.props, ConfirmDialog.defaultProps);
var message = ObjectUtils.getJSXElement(this.props.message, this.props);
var footer = this.renderFooter();
return /*#__PURE__*/React.createElement(Dialog, _extends({
visible: this.state.visible
}, dialogProps, {
className: className,
footer: footer,
onHide: this.hide,
breakpoints: this.props.breakpoints
}), IconUtils.getJSXIcon(this.props.icon, {
className: 'p-confirm-dialog-icon'
}, {
props: this.props
}), /*#__PURE__*/React.createElement("span", {
className: "p-confirm-dialog-message"
}, message));
}
}, {
key: "render",
value: function render() {
var element = this.renderElement();
return /*#__PURE__*/React.createElement(Portal, {
element: element,
appendTo: this.props.appendTo
});
}
}]);
return ConfirmDialog;
}(Component);
_defineProperty(ConfirmDialog, "defaultProps", {
visible: false,
message: null,
rejectLabel: null,
acceptLabel: null,
icon: null,
rejectIcon: null,
acceptIcon: null,
rejectClassName: null,
acceptClassName: null,
className: null,
appendTo: null,
footer: null,
breakpoints: null,
onHide: null,
accept: null,
reject: null
});
export { ConfirmDialog, confirmDialog };
|
var Code = require('code'),
Lab = require('lab'),
lab = exports.lab = Lab.script(),
describe = lab.experiment,
before = lab.before,
after = lab.after,
it = lab.test,
expect = Code.expect,
nock = require("nock"),
users = require('../../fixtures').users;
var MockTransport = require('nodemailer-mock-transport');
var sendEmail = require('../../../adapters/send-email');
var requireInject = require('require-inject');
var redisMock = require('redis-mock');
var client = redisMock.createClient();
var server;
var emailMock;
before(function(done) {
requireInject.installGlobally('../../mocks/server', {
redis: redisMock
})(function(obj) {
server = obj;
sendEmail.mailConfig.mailTransportModule = new MockTransport();
emailMock = sendEmail.mailConfig.mailTransportModule;
done();
});
});
after(function(done) {
server.stop(done);
});
function assertEmail() {
var expectedName = 'bob';
var expectedEmail = 'bob@boom.me';
var expectedTo = '"' + expectedName + '" <' + expectedEmail + '>';
var expectedFrom = '"npm, Inc." <website@npmjs.com>';
var expectedSupportEmail = 'support@npmjs.com';
var msg = emailMock.sentMail[0];
expect(msg.data.to).to.equal(expectedTo);
expect(msg.message._headers.find(function(header) {
return header.key === 'To';
}).value).to.equal(expectedTo);
expect(msg.data.from).to.equal(expectedFrom);
expect(msg.message._headers.find(function(header) {
return header.key === 'From';
}).value).to.equal(expectedFrom);
expect(msg.data.name).to.equal(expectedName);
expect(msg.data.support_email).to.equal(expectedSupportEmail);
expect(msg.message.content).to.match(new RegExp(expectedName));
expect(msg.message.content).to.match(new RegExp(expectedSupportEmail));
}
describe('Request to resend confirmation email', function() {
it('redirects to login if user is not already logged in', function(done) {
var opts = {
url: '/resend-email-confirmation'
};
server.inject(opts, function(resp) {
expect(resp.statusCode).to.equal(302);
expect(resp.headers.location).to.equal('/login');
done();
});
});
it('sends an email & takes the user to the /profile-edit page without any errors', function(done) {
var userMock = nock("https://user-api-example.com")
.get("/user/bob")
.reply(200, users.bob);
var licenseMock = nock("https://license-api-example.com")
.get("/customer/bob/stripe")
.reply(404);
var opts = {
url: '/resend-email-confirmation',
credentials: users.bob
};
server.inject(opts, function(resp) {
userMock.done();
licenseMock.done();
expect(resp.statusCode).to.equal(302);
expect(resp.headers.location).to.equal('/profile-edit?verification-email-sent=true');
assertEmail();
done();
});
});
it('renders an error if we were unable to send the email', function(done) {
var userMock = nock("https://user-api-example.com")
.get("/user/" + users.bad_email.name)
.reply(200, users.bad_email);
var licenseMock = nock("https://license-api-example.com")
.get("/customer/" + users.bad_email.name + "/stripe")
.reply(404);
var opts = {
url: '/resend-email-confirmation',
credentials: users.bad_email
};
server.inject(opts, function(resp) {
userMock.done();
licenseMock.done();
expect(resp.statusCode).to.equal(500);
var source = resp.request.response.source;
expect(source.template).to.equal('errors/internal');
done();
});
});
});
|
module.exports = require('./build/index.js'); |
// Copyright 2021 Mathias Bynens. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
author: Mathias Bynens
description: >
Unicode property escapes for `Script=Meroitic_Cursive`
info: |
Generated by https://github.com/mathiasbynens/unicode-property-escapes-tests
Unicode v14.0.0
esid: sec-static-semantics-unicodematchproperty-p
features: [regexp-unicode-property-escapes]
includes: [regExpUtils.js]
---*/
const matchSymbols = buildString({
loneCodePoints: [],
ranges: [
[0x0109A0, 0x0109B7],
[0x0109BC, 0x0109CF],
[0x0109D2, 0x0109FF]
]
});
testPropertyEscapes(
/^\p{Script=Meroitic_Cursive}+$/u,
matchSymbols,
"\\p{Script=Meroitic_Cursive}"
);
testPropertyEscapes(
/^\p{Script=Merc}+$/u,
matchSymbols,
"\\p{Script=Merc}"
);
testPropertyEscapes(
/^\p{sc=Meroitic_Cursive}+$/u,
matchSymbols,
"\\p{sc=Meroitic_Cursive}"
);
testPropertyEscapes(
/^\p{sc=Merc}+$/u,
matchSymbols,
"\\p{sc=Merc}"
);
const nonMatchSymbols = buildString({
loneCodePoints: [],
ranges: [
[0x00DC00, 0x00DFFF],
[0x000000, 0x00DBFF],
[0x00E000, 0x01099F],
[0x0109B8, 0x0109BB],
[0x0109D0, 0x0109D1],
[0x010A00, 0x10FFFF]
]
});
testPropertyEscapes(
/^\P{Script=Meroitic_Cursive}+$/u,
nonMatchSymbols,
"\\P{Script=Meroitic_Cursive}"
);
testPropertyEscapes(
/^\P{Script=Merc}+$/u,
nonMatchSymbols,
"\\P{Script=Merc}"
);
testPropertyEscapes(
/^\P{sc=Meroitic_Cursive}+$/u,
nonMatchSymbols,
"\\P{sc=Meroitic_Cursive}"
);
testPropertyEscapes(
/^\P{sc=Merc}+$/u,
nonMatchSymbols,
"\\P{sc=Merc}"
);
|
/*! jQuery UI - v1.10.4 - 2014-06-07
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(t){t.datepicker.regional.de={closeText:"Schlieรen",prevText:"<Zurรผck",nextText:"Vor>",currentText:"Heute",monthNames:["Januar","Februar","Mรคrz","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],monthNamesShort:["Jan","Feb","Mรคr","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"],dayNames:["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"],dayNamesShort:["So","Mo","Di","Mi","Do","Fr","Sa"],dayNamesMin:["So","Mo","Di","Mi","Do","Fr","Sa"],weekHeader:"KW",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.de)}); |
// Copyright 2021 Mathias Bynens. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
author: Mathias Bynens
description: >
Unicode property escapes for `Script=Meetei_Mayek`
info: |
Generated by https://github.com/mathiasbynens/unicode-property-escapes-tests
Unicode v14.0.0
esid: sec-static-semantics-unicodematchproperty-p
features: [regexp-unicode-property-escapes]
includes: [regExpUtils.js]
---*/
const matchSymbols = buildString({
loneCodePoints: [],
ranges: [
[0x00AAE0, 0x00AAF6],
[0x00ABC0, 0x00ABED],
[0x00ABF0, 0x00ABF9]
]
});
testPropertyEscapes(
/^\p{Script=Meetei_Mayek}+$/u,
matchSymbols,
"\\p{Script=Meetei_Mayek}"
);
testPropertyEscapes(
/^\p{Script=Mtei}+$/u,
matchSymbols,
"\\p{Script=Mtei}"
);
testPropertyEscapes(
/^\p{sc=Meetei_Mayek}+$/u,
matchSymbols,
"\\p{sc=Meetei_Mayek}"
);
testPropertyEscapes(
/^\p{sc=Mtei}+$/u,
matchSymbols,
"\\p{sc=Mtei}"
);
const nonMatchSymbols = buildString({
loneCodePoints: [],
ranges: [
[0x00DC00, 0x00DFFF],
[0x000000, 0x00AADF],
[0x00AAF7, 0x00ABBF],
[0x00ABEE, 0x00ABEF],
[0x00ABFA, 0x00DBFF],
[0x00E000, 0x10FFFF]
]
});
testPropertyEscapes(
/^\P{Script=Meetei_Mayek}+$/u,
nonMatchSymbols,
"\\P{Script=Meetei_Mayek}"
);
testPropertyEscapes(
/^\P{Script=Mtei}+$/u,
nonMatchSymbols,
"\\P{Script=Mtei}"
);
testPropertyEscapes(
/^\P{sc=Meetei_Mayek}+$/u,
nonMatchSymbols,
"\\P{sc=Meetei_Mayek}"
);
testPropertyEscapes(
/^\P{sc=Mtei}+$/u,
nonMatchSymbols,
"\\P{sc=Mtei}"
);
|
import { test } from 'tap';
import { ensureBoolean, ensureNumber, ensureString } from '../src/server/lib/ensure-type';
test('ensureBoolean', (t) => {
t.equal(ensureBoolean({}), true);
t.equal(ensureBoolean(true), true);
t.equal(ensureBoolean(false), false);
t.equal(ensureBoolean(0), false);
t.equal(ensureBoolean(1), true);
t.equal(ensureBoolean(Infinity), true);
t.equal(ensureBoolean(-Infinity), true);
t.equal(ensureBoolean(NaN), false);
t.equal(ensureBoolean(undefined), false);
t.equal(ensureBoolean(null), false);
t.equal(ensureBoolean(''), false);
t.equal(ensureBoolean(' '), true);
t.equal(ensureBoolean('foo'), true);
t.end();
});
test('ensureNumber', (t) => {
t.ok(Number.isNaN(ensureNumber({})));
t.equal(ensureNumber(true), 1);
t.equal(ensureNumber(false), 0);
t.equal(ensureNumber(0), 0);
t.equal(ensureNumber(1), 1);
t.equal(ensureNumber(Infinity), Infinity);
t.equal(ensureNumber(-Infinity), -Infinity);
t.ok(Number.isNaN(ensureNumber(NaN)));
t.equal(ensureNumber(undefined), 0);
t.equal(ensureNumber(null), 0);
t.equal(ensureNumber(''), 0);
t.equal(ensureNumber(' '), 0);
t.ok(Number.isNaN(ensureNumber('foo')));
t.end();
});
test('ensureString', (t) => {
t.equal(ensureString({}), ({}).toString());
t.equal(ensureString(true), 'true');
t.equal(ensureString(false), 'false');
t.equal(ensureString(0), '0');
t.equal(ensureString(1), '1');
t.equal(ensureString(Infinity), 'Infinity');
t.equal(ensureString(-Infinity), '-Infinity');
t.equal(ensureString(NaN), 'NaN');
t.equal(ensureString(undefined), '');
t.equal(ensureString(null), '');
t.equal(ensureString(''), '');
t.equal(ensureString(' '), ' ');
t.equal(ensureString('foo'), 'foo');
t.end();
});
|
YUI.add('jsonp-tests', function(Y) {
var suite = new Y.Test.Suite("JSONP"),
// For the tests, replace Y.Get.js with an object that calls the
// appropriate callback based on the url and sets a _getConfig property
// on the test object for inspection. This test suite is not testing
// the Get module. Asynchronicity is removed from the operations as well,
// but maybe it should be reinserted.
setup = function () {
var test = this;
this._GetJS = Y.Get.js;
Y.Get.js = function (url, config) {
test._getConfig = config;
return {
execute: function () {
var proxy = url.match(/YUI\.Env\.JSONP\.(\w+)/)[1],
callback;
test._proxyName = proxy;
if (url.indexOf('404') > -1) {
callback = config.onFailure;
// for the timeout + success test, where one request should
// timeout and others succeed
} else if (url.indexOf('wait=') > -1
&& (test._remainingTimeouts === undefined
|| test._remainingTimeouts--)) {
callback = config.onTimeout;
} else {
callback = YUI.Env.JSONP[proxy];
}
// Support async simulation by setting the test's _asyncGet
if (test._asyncGet) {
setTimeout(function () {
callback({ url: url, callback: proxy });
}, 0);
} else {
callback({ url: url, callback: proxy });
}
}
};
};
},
teardown = function () {
Y.Get.js = this._GetJS;
};
suite.add(new Y.Test.Case({
name: "send",
setUp : setup,
tearDown: teardown,
_should: {
ignore: {
"config charset should be set via Y.Get.js": 'Not testing Get behavior'
}
},
"config charset should be set via Y.Get.js": function () {
Y.jsonp("echo/jsonp?callback={callback}", {
on: { success: function () {} }
});
Y.Assert.areSame('utf-8', this._getConfig.charset);
Y.jsonp("echo/jsonp?callback={callback}", {
on: { success: function () {} },
charset: "GBK"
});
Y.Assert.areSame('GBK', this._getConfig.charset);
},
"config attributes should be set via Y.Get.js": function () {
Y.jsonp("echo/jsonp?callback={callback}", {
on: { success: function () {} },
attributes: {
// passing an attribute that is less likely to be skipped over
// by browser whitelisting (if they do that now or will later)
language: "javascript"
}
});
Y.Assert.isObject(this._getConfig.attributes);
Y.Assert.areSame("javascript", this._getConfig.attributes.language);
},
"async config should be set via Y.Get.js": function () {
Y.jsonp("echo/jsonp?callback={callback}", {
on: { success: function () {} },
async: true
});
Y.Assert.isTrue(this._getConfig.async);
}
}));
suite.add(new Y.Test.Case({
name : "callbacks",
setUp : setup,
tearDown: teardown,
"callback function as second arg should be success handler": function () {
Y.jsonp("echo/jsonp?&callback={callback}", function (json) {
Y.Assert.isObject(json);
});
},
"success handler in callback object should execute": function () {
Y.jsonp("echo/jsonp?&callback={callback}", {
on: {
success: function (json) {
Y.Assert.isObject(json);
}
}
});
},
"failure handler in callback object should execute": function () {
Y.jsonp("status/404?callback={callback}", {
on: {
success: function (json) {
Y.Assert.fail("Success handler called from 404 response");
},
failure: function () {
Y.Assert.isTrue(true);
}
}
});
},
"failure handler in callback object should not execute for successful io": function () {
Y.jsonp("echo/jsonp?&callback={callback}", {
on: {
success: function (json) {
Y.Assert.isTrue(true);
},
failure: function () {
Y.Assert.fail("Failure handler called after successful response");
}
}
});
},
"test multiple send() from an instance of Y.JSONPRequest": function () {
var count = 0,
service;
service = new Y.JSONPRequest("echo/jsonp?callback={callback}", {
on: {
success: function (json) {
count++;
}
}
});
service.send().send().send();
Y.Assert.areSame(count, 3);
},
"test otherparam={callback}": function () {
var url, called;
Y.jsonp("echo/jsonp?foo={callback}", function (data) {
called = true;
url = data.url;
});
Y.Assert.isTrue(called);
Y.Assert.areSame(-1, url.indexOf('callback'));
}
// failure for bogus response data (not yet implemented)
// missing {callback} (not sure how to test. No callback would be attached.
// Maybe have the service create a property on YUI and have the test
// look for that after a time?)
// missing success handler (logs a warning)
// JSONPRequest + send
// JSONPRequest + send with config overrides (not yet implemented)
}));
suite.add(new Y.Test.Case({
name : "allowCache",
setUp : setup,
tearDown: teardown,
"allowCache should preserve the same callback": function () {
var test = this,
callback = [],
jsonp;
jsonp = new Y.JSONPRequest('echo/jsonp?&callback={callback}', {
allowCache: true,
on: {
success: function (data) {
callback.push(data.callback);
}
}
});
jsonp.send().send();
Y.Assert.areSame(2, callback.length);
Y.Assert.isString(callback[0]);
Y.Assert.areSame(callback[0], callback[1]);
},
"allowCache should not clear proxy if another send() is pending response": function () {
var test = this,
callbacks = [],
jsonp;
// Make the Y.Get.js shim execute asynchronously
test._asyncGet = true;
jsonp = new Y.JSONPRequest('echo/jsonp?&callback={callback}', {
allowCache: true,
on: {
success: function (data) {
callbacks.push(data.callback);
if (callbacks.length > 2) {
test.resume(function () {
Y.Assert.areSame(callbacks[0], callbacks[1]);
Y.Assert.areSame(callbacks[1], callbacks[2]);
Y.Assert.isUndefined(YUI.Env.JSONP[callbacks[0]]);
});
} else if (!YUI.Env.JSONP[data.callback]) {
test.resume(function () {
Y.Assert.fail("proxy cleared prematurely");
});
}
}
}
});
jsonp.send().send().send();
this.wait();
}
}));
suite.add(new Y.Test.Case({
name : "timeout",
setUp : setup,
tearDown: teardown,
"timeout should not flush the global proxy": function () {
var timeoutCalled = false,
jsonp;
jsonp = new Y.JSONPRequest('echo/jsonp?&wait=2&callback={callback}', {
timeout: 1000,
on: {
success: function (data) {
Y.Assert.fail("Success callback executed after timeout");
},
timeout: function () {
timeoutCalled = true;
}
}
});
jsonp.send();
Y.Assert.isTrue(timeoutCalled);
Y.Assert.isFunction(YUI.Env.JSONP[this._proxyName]);
},
"timeout should not flush the global proxy across multiple send calls": function () {
var test = this,
callbacks = [],
timeoutCalled = false,
jsonp;
test._remainingTimeouts = 1;
jsonp = new Y.JSONPRequest('echo/jsonp?wait=2&callback={callback}', {
allowCache: true,
timeout: 1000,
on: {
success: function (data) {
callbacks.push(data.callback);
},
timeout: function () {
callbacks.push(test._proxyName);
timeoutCalled = true;
}
}
});
jsonp.send().send();
Y.Assert.isTrue(timeoutCalled);
Y.Assert.areSame(2, callbacks.length);
Y.Assert.areSame(callbacks[0], callbacks[1]);
Y.Assert.isFunction(YUI.Env.JSONP[callbacks[0]]);
}
}));
suite.add(new Y.Test.Case({
name : "Should not have TypeError when both `timeout` and `failure` handlers are set.",
"Having timeout and failure handles should not cause a TypeError": function () {
var error = false,
windowOnError = window.onerror,
jsonp;
window.onerror = function(e) {
error = e;
};
jsonp = new Y.JSONPRequest('echo/jsonp?wait=2&callback={callback}', {
timeout: 1,
on: {
success: function (data) {
//success logic
},
timeout: function () {
//timeout logic
},
failure: function() {
//failure logic
}
}
});
jsonp.send();
this.wait(function() {
window.onerror = windowOnError;
if(error) {
Y.Assert.fail(error);
} else {
Y.Assert.isTrue(true);
}
}, 3000);
}
}));
Y.Test.Runner.add(suite);
}, '@VERSION@' ,{requires:['jsonp', 'test'] });
|
'use strict';
var parts = ['Apps', 'Users', 'Keys', 'Tokens', 'Snapshots', 'Databases', 'Logs', 'Client'];
parts.forEach(function forEach(k) {
exports[k] = require('./client/' + k.toLowerCase())[k];
});
//
// ### function createClient(options)
// #### @options {Object} options for the clients
// Generates a new API client.
//
exports.createClient = function createClient(options) {
var client = {};
parts.forEach(function generate(k) {
var endpoint = k.toLowerCase();
client[endpoint] = new exports[k](options);
if (options.debug) {
client[endpoint].on('debug::request', debug);
client[endpoint].on('debug::response', debug);
}
});
function debug(args) {
console.log(args);
}
return client;
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:70aef9ee46cfbf27bbb9ab240880aae6629ce0ec00251489518fd537c49f1615
size 41919
|
StartTest(function (t) {
t.expectGlobals('0', '1')
var innerWin, innerExt;
t.getHarness([
{
preload : [
'../../../extjs-4.2.1/resources/css/ext-all.css',
'../../../extjs-4.2.1/ext-all.js'
],
url : 'testfiles/604_extjs_components.t.js'
}
]);
function assertSize(cmp) {
var highlighterEl = Ext.getBody().down('.cmp-inspector-box');
t.isApprox(highlighterEl.getWidth(), cmp.getWidth() + 5, 3);
t.isApprox(highlighterEl.getHeight(), cmp.getHeight() + 5, 3);
}
t.chain(
{ waitFor : 'harnessReady' },
function (next) {
t.waitForHarnessEvent('testsuiteend', next)
t.runFirstTest();
},
function (next) {
t.cq1('resultpanel').onRecorderClick();
var recorderPanel = t.cq1('recorderpanel');
recorderPanel.highlightTarget('>>button[text=Foo]');
next()
},
{ waitFor : 1000 },
function (next) {
innerWin = t.getActiveTestWindow();
innerExt = innerWin.Ext;
var recorderPanel = t.cq1('recorderpanel');
assertSize(innerExt.ComponentQuery.query('button[text=Foo]')[0]);
recorderPanel.highlightTarget('>>button[')
next()
},
{ waitFor : 1000 },
function (next) {
var recorderPanel = t.cq1('recorderpanel');
// Should keep size if resolving fails
assertSize(innerExt.ComponentQuery.query('button[text=Foo]')[0]);
recorderPanel.highlightTarget('button[text=Foo] => span');
next()
},
{ waitFor : 1000 },
function (next) {
assertSize(innerExt.ComponentQuery.query('button[text=Foo]')[0].el.down('span'));
}
);
}) |
'use strict';
angular.module('copayApp.controllers').controller('addressesController', function($scope, $log, $stateParams, $state, $timeout, $ionicHistory, $ionicScrollDelegate, configService, popupService, gettextCatalog, ongoingProcess, lodash, profileService, walletService, bwcError, platformInfo, appConfigService) {
var UNUSED_ADDRESS_LIMIT = 5;
var BALANCE_ADDRESS_LIMIT = 5;
var config = configService.getSync().wallet.settings;
var unitName = config.unitName;
var unitToSatoshi = config.unitToSatoshi;
var satToUnit = 1 / unitToSatoshi;
var unitDecimals = config.unitDecimals;
var withBalance, cachedWallet;
$scope.isCordova = platformInfo.isCordova;
$scope.wallet = profileService.getWallet($stateParams.walletId);
function resetValues() {
$scope.loading = false;
$scope.showInfo = false;
$scope.showMore = false;
$scope.allAddressesView = false;
$scope.latestUnused = $scope.latestWithBalance = null;
$scope.viewAll = {
value: false
};
};
$scope.init = function() {
resetValues();
$scope.loading = true;
walletService.getMainAddresses($scope.wallet, {}, function(err, addresses) {
if (err) {
$scope.loading = false;
return popupService.showAlert(bwcError.msg(err, gettextCatalog.getString('Could not update wallet')));
}
var allAddresses = addresses;
walletService.getBalance($scope.wallet, {}, function(err, resp) {
$scope.loading = false;
if (err) {
return popupService.showAlert(bwcError.msg(err, gettextCatalog.getString('Could not update wallet')));
}
withBalance = resp.byAddress;
var idx = lodash.indexBy(withBalance, 'address');
$scope.noBalance = lodash.reject(allAddresses, function(x) {
return idx[x.address];
});
processPaths($scope.noBalance);
processPaths(withBalance);
$scope.latestUnused = lodash.slice($scope.noBalance, 0, UNUSED_ADDRESS_LIMIT);
$scope.latestWithBalance = lodash.slice(withBalance, 0, BALANCE_ADDRESS_LIMIT);
lodash.each(withBalance, function(a) {
a.balanceStr = (a.amount * satToUnit).toFixed(unitDecimals) + ' ' + unitName;
});
$scope.viewAll = {
value: $scope.noBalance.length > UNUSED_ADDRESS_LIMIT || withBalance.length > BALANCE_ADDRESS_LIMIT
};
$scope.allAddresses = $scope.noBalance.concat(withBalance);
cachedWallet = $scope.wallet.id;
$log.debug('Addresses cached for Wallet:', cachedWallet);
$ionicScrollDelegate.resize();
$scope.$digest();
});
});
};
function processPaths(list) {
lodash.each(list, function(n) {
n.path = n.path.replace(/^m/g, 'xpub');
});
};
$scope.newAddress = function() {
if ($scope.gapReached) return;
ongoingProcess.set('generatingNewAddress', true);
walletService.getAddress($scope.wallet, true, function(err, addr) {
if (err) {
ongoingProcess.set('generatingNewAddress', false);
$scope.gapReached = true;
$timeout(function() {
$scope.$digest();
});
return;
}
walletService.getMainAddresses($scope.wallet, {
limit: 1
}, function(err, _addr) {
ongoingProcess.set('generatingNewAddress', false);
if (err) return popupService.showAlert(gettextCatalog.getString('Error'), err);
if (addr != _addr[0].address) return popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('New address could not be generated. Please try again.'));
$scope.noBalance = [_addr[0]].concat($scope.noBalance);
$scope.latestUnused = lodash.slice($scope.noBalance, 0, UNUSED_ADDRESS_LIMIT);
$scope.viewAll = {
value: $scope.noBalance.length > UNUSED_ADDRESS_LIMIT
};
$scope.$digest();
});
});
};
$scope.viewAllAddresses = function() {
$state.go('tabs.receive.allAddresses', {
walletId: $scope.wallet.id
});
};
$scope.requestSpecificAmount = function() {
$state.go('tabs.receive.amount', {
customAmount: true,
toAddress: $stateParams.toAddress
});
}
$scope.showInformation = function() {
$timeout(function() {
$scope.showInfo = !$scope.showInfo;
$ionicScrollDelegate.resize();
}, 10);
};
$scope.readMore = function() {
$timeout(function() {
$scope.showMore = !$scope.showMore;
$ionicScrollDelegate.resize();
}, 10);
};
$scope.scan = function() {
walletService.startScan($scope.wallet);
$ionicHistory.clearHistory();
$state.go('tabs.home');
};
$scope.sendByEmail = function() {
function formatDate(ts) {
var dateObj = new Date(ts * 1000);
if (!dateObj) {
$log.debug('Error formating a date');
return 'DateError';
}
if (!dateObj.toJSON()) {
return '';
}
return dateObj.toJSON();
};
ongoingProcess.set('sendingByEmail', true);
$timeout(function() {
var appName = appConfigService.nameCase;
var body = appName + ' Wallet "' + $scope.wallet.name + '" Addresses\n Only Main Addresses are shown.\n\n';
body += "\n";
body += $scope.allAddresses.map(function(v) {
return ('* ' + v.address + ' xpub' + v.path.substring(1) + ' ' + formatDate(v.createdOn));
}).join("\n");
ongoingProcess.set('sendingByEmail', false);
window.plugins.socialsharing.shareViaEmail(
body,
appName + ' Addresses',
null, // TO: must be null or an array
null, // CC: must be null or an array
null, // BCC: must be null or an array
null, // FILES: can be null, a string, or an array
function() {},
function() {}
);
});
};
function isCachedWallet(walletId) {
if (cachedWallet && cachedWallet == walletId) return true;
else return false;
};
$scope.$on("$ionicView.afterEnter", function(event, data) {
$scope.allAddressesView = data.stateName == 'tabs.receive.allAddresses' ? true : false;
if (!isCachedWallet($stateParams.walletId)) $scope.init();
else $log.debug('Addresses cached for Wallet:', $stateParams.walletId);
});
});
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
global.ng.common.locales['en-dk'] = [
'en-DK',
[['a', 'p'], ['am', 'pm'], u],
[['am', 'pm'], u, u],
[
['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
[
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'
]
],
u,
[['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']],
1,
[6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'],
['HH.mm', 'HH.mm.ss', 'HH.mm.ss z', 'HH.mm.ss zzzz'],
['{1}, {0}', u, '{1} \'at\' {0}', u],
[',', '.', ';', '%', '+', '-', 'E', 'ยท', 'โฐ', 'โ', 'NaN', '.'],
['#,##0.###', '#,##0ย %', '#,##0.00ย ยค', '#E0'],
'DKK',
'kr.',
'Danish Krone',
{'DKK': ['kr.', 'kr'], 'JPY': ['JPยฅ', 'ยฅ'], 'USD': ['US$', '$']},
'ltr',
plural,
[
[
['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'],
['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u
],
[['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u],
[
'00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'],
['21:00', '06:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
|
/*
original script from: https://github.com/ocangelo/roll20
*/
/*jshint -W069 */
/*jshint -W014 */
/*jshint -W083 */
const WS_API = {
NAME : "WildShape",
VERSION : "1.3.1",
REQUIRED_HELPER_VERSION: "1.3.1",
STATENAME : "WILDSHAPE",
DEBUG : false,
// storage in the state
DATA_CONFIG : "config",
DATA_SHIFTERS : "shifters",
// general info
SETTINGS : {
BASE_SHAPE : "base",
SHIFTER_SIZE : "normal",
SHAPE_SIZE : "auto",
SHAPE_SIZES : [
"auto",
"normal",
"large",
"huge",
"gargantuan",
],
STATS: {
NAMES: ["strength", "dexterity", "constitution", "intelligence", "wisdom", "charisma"],
SHORT_NAMES: ["str", "dex", "con", "int", "wis", "cha"],
SKILLS: {
"strength" : [ "athletics"],
"dexterity" : [ "acrobatics", "sleight_of_hand", "stealth"],
"constitution" : [],
"intelligence" : ["arcana", "history", "investigation", "nature", "religion"],
"wisdom" : ["animal_handling", "insight", "medicine", "perception", "survival"],
"charisma" : ["deception", "intimidation", "performance", "persuasion"]
},
PROF: "pb",
PREFIX: {
NPC: "npc_",
},
SUFFIX: {
BASE: "_base",
MOD: "_mod",
BONUS: "_bonus",
SAVE: "_save",
SAVE_BONUS: "_save_bonus",
PROF: "_prof",
FLAG: "_flag",
},
DRUID_COPY_ATTR: ["intelligence", "wisdom", "charisma"],
},
},
DEFAULT_CONFIG : {
SEP: "###", // separator used in commands
DRUID_WS_RES : "",
MUTE_SHIFT: false,
PC_DATA : {
HP: "hp",
AC: "ac",
SPEED: "speed",
},
NPC_DATA : {
HP_CACHE: "npcCachedHp",
HP: "hp",
AC: "npc_ac",
SPEED: "npc_speed",
SENSES: "npc_senses",
},
TOKEN_DATA : {
HP: "bar1", // HP can never be empty, we are caching current value from bars on transforming
AC: "bar2",
SPEED: "bar3",
EMPTYBAR: "none",
},
SENSES: {
OVERRIDE_SENSES: true,
light_radius: 5,
light_dimradius: -5,
light_otherplayers: false,
light_hassight: true,
light_angle: 360,
light_losangle: 360,
light_multiplier: 1,
},
},
// available commands
CMD : {
ROOT : "!ws",
USAGE : "Please select a token then run: !ws",
HELP : "help",
CONFIG : "config",
ADD : "add",
REMOVE : "remove",
EDIT : "edit",
RESET : "reset",
IMPORT : "import",
EXPORT : "export",
SHIFT : "shift",
SHOW_SHIFTERS : "showshifters",
},
// fields that can be referenced by commands
FIELDS : {
SEP: "sep",
TOGGLE: "toggle",
// target of a command
TARGET : {
CONFIG: "config",
SHIFTER : "shifter",
SHAPE : "shape",
SHAPEFOLDER : "shapefolder",
},
SETTINGS: "settings",
SHAPES: "shapes",
ID: "ID",
NAME: "name",
CHARACTER: "character",
SIZE: "size",
ISDRUID: "isdruid",
MAKEROLLPUBLIC: "makerollpublic",
ISNPC: "isnpc",
CURRENT_SHAPE: "currshape",
ISDUPLICATE: "isDuplicate",
DRUID_WS_RES: "DRUID_WS_RES",
MUTE_SHIFT: "MUTE_SHIFT",
STATS_CACHE: {
ROOT: "stats_cache",
STATS: "stats",
MODS: "modifiers",
SAVES: "saves",
SKILLS: "skills",
},
TOKEN_DATA : {
ROOT: "TOKEN_DATA",
HP: "HP",
AC: "AC",
SPEED: "SPEED",
},
NPC_DATA : {
ROOT: "NPC_DATA",
HP: "HP",
AC: "AC",
SPEED: "SPEED",
SENSES: "SENSES",
EMPTYBAR: "EMPTYBAR",
HP_CACHE: "HP_CACHE",
},
PC_DATA : {
ROOT: "PC_DATA",
HP: "HP",
AC: "AC",
SPEED: "SPEED",
},
SENSES: {
ROOT: "SENSES",
OVERRIDE: "OVERRIDE_SENSES",
LIGHT_ATTRS: [
"light_radius",
"light_dimradius",
"light_otherplayers",
"light_hassight",
"light_angle",
"light_losangle",
"light_multiplier"],
},
},
// major changes
CHANGELOG : {
"1.3" : "automatically duplicate/delete characters when adding/removing new shapes",
"1.2.6" : "added setting to mute players chat messages",
"1.2.5" : "Wild Shape Resource added to config, automatically check and decrease when Druids transform",
"1.2" : "automatically add corrected saving throws and proficiencies for druids",
"1.1" : "automatically shapeshift tokens to the last shape when copied/dropped from the journal",
"1.0.7" : "added senses attribute setting in NPC Data",
"1.0.6" : "added automatic senses setup for NPCs (e.g. vision, light) and senses overrides for shifters and single shapes",
"1.0.5" : "changed default separator to minimize collisions",
"1.0.4" : "added override roll settings (default true on PCs) to automatically set target shapes to never whisper, toggle advantage",
"1.0.2" : "restructured pc/npc data",
}
};
// ========================================= MENU HANDLING =========================================
class WildShapeMenu extends WildMenu
{
constructor() {
super();
}
updateConfig()
{
this.SEP = state[WS_API.STATENAME][WS_API.DATA_CONFIG].SEP;
this.CMD = {};
this.CMD.ROOT = WS_API.CMD.ROOT + this.SEP;
this.CMD.CONFIG = this.CMD.ROOT + WS_API.CMD.CONFIG;
this.CMD.CONFIG_ADD = this.CMD.CONFIG + this.SEP + WS_API.CMD.ADD + this.SEP;
this.CMD.CONFIG_REMOVE = this.CMD.CONFIG + this.SEP + WS_API.CMD.REMOVE + this.SEP;
this.CMD.CONFIG_EDIT = this.CMD.CONFIG + this.SEP + WS_API.CMD.EDIT + this.SEP;
this.CMD.CONFIG_RESET = this.CMD.CONFIG + this.SEP + WS_API.CMD.RESET;
this.UTILS = new WildUtils(WS_API.NAME, WS_API.DEBUG);
this.SHAPE_SIZES = WS_API.SETTINGS.SHAPE_SIZES.join("|");
}
showEditSenses(shifterId = null, shapeId = null) {
const config = state[WS_API.STATENAME][WS_API.DATA_CONFIG];
let settings;
let cmdEdit;
let cmdBack;
let cmdBackName;
let overrideName;
let menuTitle;
// check what are editing senses on
if (shifterId)
{
menuTitle = WS_API.NAME + ": " + shifterId;
const shifter = state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterId];
if (shapeId)
{
settings = shifter[WS_API.FIELDS.SHAPES][shapeId];
cmdEdit = this.CMD.CONFIG_EDIT + WS_API.FIELDS.TARGET.SHAPE + this.SEP + shifterId + this.SEP + shapeId + this.SEP;
cmdBack = this.CMD.CONFIG_EDIT + WS_API.FIELDS.TARGET.SHAPE + this.SEP + shifterId + this.SEP + shapeId;
cmdBackName = "Edit Shape: " + shapeId;
menuTitle = menuTitle + " - " + shapeId;
}
else
{
settings = shifter[WS_API.FIELDS.SETTINGS];
cmdEdit = this.CMD.CONFIG_EDIT + WS_API.FIELDS.TARGET.SHIFTER + this.SEP + shifterId + this.SEP;
cmdBack = this.CMD.CONFIG_EDIT + WS_API.FIELDS.TARGET.SHIFTER + this.SEP + shifterId;
cmdBackName = "Edit Shifter: " + shifterId;
}
menuTitle = menuTitle + " - Senses";
overrideName = "Force Senses";
}
else
{
settings = config;
cmdEdit = this.CMD.CONFIG_EDIT + WS_API.FIELDS.TARGET.CONFIG + this.SEP;
cmdBack = this.CMD.CONFIG;
cmdBackName = "Main Menu";
menuTitle = "Default Senses";
overrideName = "Write Senses";
}
cmdEdit = cmdEdit + WS_API.FIELDS.SENSES.ROOT + this.SEP;
let sensesDataList = [
this.makeLabelValue(overrideName, settings[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE], 'false') + this.makeRightButton("Toggle", cmdEdit + WS_API.FIELDS.SENSES.OVERRIDE)
];
if (shifterId && !config[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE])
{
sensesDataList.push(this.makeLabel("NOTE: Current Config Write Senses value is set to false, senses won't be applied", "font-size: 80%; padding-left: 10px; padding-bottom: 10px"));
}
// senses settings
_.each(WS_API.FIELDS.SENSES.LIGHT_ATTRS, (attr) => {
const currAttr = settings[WS_API.FIELDS.SENSES.ROOT][attr];
let attrField = this.makeLabelValue(attr, currAttr);
if (currAttr === false || currAttr === true)
attrField = attrField + this.makeRightButton("Toggle", cmdEdit + attr + this.SEP + WS_API.FIELDS.TOGGLE);
else
attrField = attrField + this.makeRightButton("Edit", cmdEdit + attr + this.SEP + "?{Attribute|" + currAttr + "}");
sensesDataList.push(attrField);
});
let contents = this.makeList(sensesDataList)
+ "<hr>" + this.makeButton(cmdBackName, cmdBack, ' width: 100%');
this.showMenu(WS_API.NAME, contents, WS_API.NAME + ': ' + menuTitle);
}
showEditShape(shifterId, shapeId) {
const cmdShapeEdit = this.CMD.CONFIG_EDIT + WS_API.FIELDS.TARGET.SHAPE + this.SEP + shifterId + this.SEP + shapeId + this.SEP;
const cmdRemove = this.CMD.CONFIG_REMOVE;
const cmdShifterEdit = this.CMD.CONFIG_EDIT + WS_API.FIELDS.TARGET.SHIFTER + this.SEP + shifterId;
const shifter = state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterId];
let npcs = this.UTILS.getNPCNames().sort().join('|');
let obj = shifter[WS_API.FIELDS.SHAPES][shapeId];
if(!obj)
{
UTILS.chatError("cannot find shape " + shapeId + " when trying to create EditShape menu");
return;
}
let listItems = [
this.makeLabelValue("Character", obj[WS_API.FIELDS.CHARACTER]),
this.makeLabelValue("Name", shapeId) + this.makeRightButton("Edit", cmdShapeEdit + WS_API.FIELDS.NAME + this.SEP + "?{Edit Name|" + shapeId + "}"),
this.makeLabelValue("Size", obj[WS_API.FIELDS.SIZE]) + this.makeRightButton("Edit", cmdShapeEdit + WS_API.FIELDS.SIZE + this.SEP + "?{Edit Size|" + this["SHAPE_SIZES"] + "}"),
this.makeLabelValue("Force Senses", obj[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE], 'false') + this.makeRightButton("Edit Senses", cmdShapeEdit + WS_API.FIELDS.SENSES.ROOT),
this.makeLabel("Override the auto/default senses applied", "font-size: 80%"),
];
const deleteShapeButton = this.makeButton("Delete Shape", cmdRemove + "?{Are you sure you want to delete " + shapeId + "?|no|yes}" + this.SEP + WS_API.FIELDS.TARGET.SHAPE + this.SEP + shifterId + this.SEP + shapeId, ' width: 100%');
const editShifterButton = this.makeButton("Edit Shifter: " + shifterId, cmdShifterEdit, ' width: 100%');
let contents = this.makeList(listItems) + '<hr>' + deleteShapeButton + '<hr>' + editShifterButton;
this.showMenu(WS_API.NAME, contents, WS_API.NAME + ': ' + shifterId + " - " + shapeId);
}
showEditShifter(shifterId) {
const cmdShapeEdit = this.CMD.CONFIG_EDIT + WS_API.FIELDS.TARGET.SHAPE + this.SEP;
const cmdShapeAdd = this.CMD.CONFIG_ADD + WS_API.FIELDS.TARGET.SHAPE + this.SEP;
const cmdShifterEdit = this.CMD.CONFIG_EDIT + WS_API.FIELDS.TARGET.SHIFTER + this.SEP + shifterId + this.SEP ;
const cmdRemove = this.CMD.CONFIG_REMOVE;
const cmdImport = this.CMD.CONFIG + this.SEP + WS_API.CMD.IMPORT + this.SEP;
const cmdExport = this.CMD.CONFIG + this.SEP + WS_API.CMD.EXPORT + this.SEP;
const shifter = state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterId];
const shifterSettings = shifter[WS_API.FIELDS.SETTINGS];
const shifterShapes = shifter[WS_API.FIELDS.SHAPES];
// get list of pcs and npcs
const isNpc = shifterSettings[WS_API.FIELDS.ISNPC];
const npcs = this.UTILS.getNPCNames().sort().join('|');
const pcs = this.UTILS.getPCNames().sort().join('|');
let shifterPcs = isNpc ? npcs : pcs;
let pcTag = shifterSettings[WS_API.FIELDS.ISNPC] ? "<i>(NPC)</i>" : " <i>(PC)</i>";
// settings section
let listItems = [];
let settingsDataList = [
this.makeLabel("<p style='font-size: 120%'><b>Settings " + pcTag) + ":</b></p>",
this.makeLabelValue("Token Name", shifterId) + this.makeRightButton("Edit", cmdShifterEdit + WS_API.FIELDS.NAME + this.SEP + "@{target|token_name}"),
this.makeLabel("Token name needs to match to be able to shapeshift", "font-size: 80%; padding-left: 10px; padding-bottom: 10px"),
this.makeLabelValue(pcTag + " Character", shifterSettings[WS_API.FIELDS.CHARACTER]) + this.makeRightButton("Edit", cmdShifterEdit + WS_API.FIELDS.CHARACTER + this.SEP + "?{Edit Character|" + shifterPcs + "}"),
this.makeLabelValue("Size", shifterSettings[WS_API.FIELDS.SIZE]) + this.makeRightButton("Edit", cmdShifterEdit + WS_API.FIELDS.SIZE + this.SEP + "?{Edit Size|" + this["SHAPE_SIZES"] + "}"),
this.makeLabelValue("Is Druid", shifterSettings[WS_API.FIELDS.ISDRUID], 'false') + this.makeRightButton("Toggle", cmdShifterEdit + WS_API.FIELDS.ISDRUID),
this.makeLabel("Is Druid automatically copies over INT/WIS/CHA attributes", "font-size: 80%"),
this.makeLabelValue("Override Roll Settings", shifterSettings[WS_API.FIELDS.MAKEROLLPUBLIC], 'false') + this.makeRightButton("Toggle", cmdShifterEdit + WS_API.FIELDS.MAKEROLLPUBLIC),
this.makeLabel("Automatically set to never whisper, toggle advantage", "font-size: 80%"),
this.makeLabelValue("Force Senses", shifterSettings[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE], 'false') + this.makeRightButton("Edit Senses", cmdShifterEdit + WS_API.FIELDS.SENSES.ROOT),
this.makeLabel("Override the auto/default senses applied", "font-size: 80%"),
];
//listItems.push(this.makeList(settingsDataList, " padding-left: 10px"));
// shapes section
let shapesDataList = [
this.makeLabel("<p style='font-size: 120%'><b>Shapes:</b></p>"),
];
_.each(shifterShapes, (value, shapeId) =>
{
shapesDataList.push(this.makeLabel(shapeId) + this.makeRightButton("Del", cmdRemove + "?{Are you sure you want to delete " + shapeId + "?|no|yes}" + this.SEP + WS_API.FIELDS.TARGET.SHAPE + this.SEP + shifterId + this.SEP + shapeId) + this.makeRightButton("Edit", cmdShapeEdit + shifterId + this.SEP + shapeId));
});
//listItems.push(this.makeList(shapesDataList, " padding-left: 10px"));
// bottom buttons
const shapeButtons =
"<table style='width: 100%'><tr><td>" + this.makeButton("Add NPC", cmdShapeAdd + shifterId + this.SEP + "?{Target Shape|" + npcs + "}", 'width: 100%') + "<td>" + this.makeButton("Add PC", cmdShapeAdd + shifterId + this.SEP + "?{Target Shape|" + pcs + "}", 'width: 100%') + "</table>"
+ this.makeButton("Import Shapes from Folder", cmdImport + WS_API.FIELDS.TARGET.SHAPEFOLDER + this.SEP + shifterId + this.SEP + "?{Folder Name}" + this.SEP + "?{Find in Subfolders?|no|yes}" + this.SEP + "?{Remove Prefix (optional)}", ' width: 100%')
+ this.makeLabelComment("Adding a single shape may take a several seconds (around 4s), importing several shapes from a folder may take a while (e.g. 15 shapes should take around 1 minute); please wait until you see the results in the chat");
const deleteShapesButton = this.makeButton("Delete All Shapes", cmdRemove + "?{Are you sure you want to delete all shapes?|no|yes}" + this.SEP + WS_API.FIELDS.TARGET.SHAPE + this.SEP + shifterId, ' width: 100%');
//const importShapesButton = this.makeButton("Import Shapes", cmdImport + WS_API.FIELDS.TARGET.SHAPE + this.SEP + "?{Shapes Data}", ' width: 100%');
//const exportShapesButton = this.makeButton("Export Shapes", cmdExport + WS_API.FIELDS.TARGET.SHAPE, ' width: 100%');
//const exportShifterButton = this.makeButton("Export Shifter", cmdExport + WS_API.FIELDS.TARGET.SHIFTER, ' width: 100%');
const deleteShifterButton = this.makeButton("Delete Shifter: " + shifterId, cmdRemove + "?{Are you sure you want to delete the shifter?|no|yes}" + this.SEP + WS_API.FIELDS.TARGET.SHIFTER + this.SEP + shifterId, ' width: 100%');
const showShiftersButton = this.makeButton("Show ShapeShifters", this.CMD.ROOT + WS_API.CMD.SHOW_SHIFTERS, ' width: 100%');
//let contents = this.makeList(listItems) + importShapesFromFolderButton /*+ importShapesButton + exportShapesButton + exportShifterButton*/ + '<hr>' + deleteShifterButton + '<hr>' + showShiftersButton;
let contents = this.makeList(settingsDataList)
+ '<hr>' + this.makeList(shapesDataList) + shapeButtons /*+ importShapesButton + exportShapesButton + exportShifterButton*/
+ '<hr>' + deleteShapesButton + deleteShifterButton
+ '<hr>' + showShiftersButton;
this.showMenu(WS_API.NAME, contents, WS_API.NAME + ': ' + shifterId);
}
showShifters() {
const cmdShifterAdd = this.CMD.CONFIG_ADD + WS_API.FIELDS.TARGET.SHIFTER + this.SEP;
const cmdShifterEdit = this.CMD.CONFIG_EDIT + WS_API.FIELDS.TARGET.SHIFTER + this.SEP;
const cmdRemove = this.CMD.CONFIG_REMOVE;
const cmdImport = this.CMD.CONFIG + this.SEP + WS_API.CMD.IMPORT + this.SEP;
let listItems = [];
_.each(state[WS_API.STATENAME][WS_API.DATA_SHIFTERS], (value, shifterId) => {
const shifterSettings = state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterId][WS_API.FIELDS.SETTINGS];
listItems.push(this.makeLabel(shifterId + (shifterSettings[WS_API.FIELDS.ISNPC] ? " <i>(NPC)</i>" : " <i>(PC)</i>")) + this.makeRightButton("Del", cmdRemove + "?{Are you sure you want to delete " + shifterId + "?|no|yes}" + this.SEP + WS_API.FIELDS.TARGET.SHIFTER + this.SEP + shifterId)+ this.makeRightButton("Edit", cmdShifterEdit + shifterId));
});
let pcs = this.UTILS.getPCNames().sort().join('|');
let npcs = this.UTILS.getNPCNames().sort().join('|');
const addShifterButton = this.makeButton("Add ShapeShifter", cmdShifterAdd + "@{target|token_id}", ' width: 100%');
//const importShifterButton = this.makeButton("Import Shifter", cmdImport + WS_API.FIELDS.TARGET.SHIFTER + this.SEP + "?{Shifter Data}", ' width: 100%');
const configButton = this.makeButton("Main Menu", this.CMD.CONFIG, ' width: 100%');
let contents = this.makeList(listItems) + addShifterButton /*+ importShifterButton*/ + '<hr>' + configButton;
this.showMenu(WS_API.NAME, contents, WS_API.NAME + ': ShapeShifters');
}
showConfigMenu(newVersion) {
const config = state[WS_API.STATENAME][WS_API.DATA_CONFIG];
const apiCmdBase = this.CMD.ROOT;
const cmdConfigEdit = this.CMD.CONFIG_EDIT + WS_API.FIELDS.TARGET.CONFIG + this.SEP;
const showShiftersButton = this.makeButton("Edit ShapeShifters", apiCmdBase + WS_API.CMD.SHOW_SHIFTERS, ' width: 100%');
let otherSettingsList = [
this.makeLabel("<p style='font-size: 120%'><b>Config:</b></p>"),
this.makeLabelValue("Commands Separator", this.SEP) + this.makeRightButton("Edit", cmdConfigEdit + WS_API.FIELDS.SEP + this.SEP + "?{New Separator}"),
this.makeLabel("Please make sure your names/strings don't include the separator used by the API", "font-size: 80%"),
this.makeLabelValue("<br>WildShape Resource", config[WS_API.FIELDS.DRUID_WS_RES]) + this.makeRightButton("Edit", cmdConfigEdit + WS_API.FIELDS.DRUID_WS_RES + this.SEP + "?{Edit|" + config[WS_API.FIELDS.DRUID_WS_RES] + "}"),
this.makeLabel("Automatically check and decrease resource for Druids (case insensitive)", "font-size: 80%"),
this.makeLabelValue("Mute Shift Messages", config[WS_API.FIELDS.MUTE_SHIFT], 'false') + this.makeRightButton("Toggle", cmdConfigEdit + WS_API.FIELDS.MUTE_SHIFT),
this.makeLabel("Mute messages sent to players when shapeshifting", "font-size: 80%"),
];
// token settings
let tokenDataList = [
this.makeLabel("<p style='font-size: 120%'><b>Token Data:</b></p>"),
this.makeLabel("Automatically assign values to bars (HP needs to be assigned to one)", "font-size: 80%; padding-left: 10px; padding-bottom: 10px"),
this.makeList(
[
this.makeLabelValue("HP", config[WS_API.FIELDS.TOKEN_DATA.ROOT][WS_API.FIELDS.TOKEN_DATA.HP]) + this.makeRightButton("Edit", cmdConfigEdit + WS_API.FIELDS.TOKEN_DATA.ROOT + this.SEP + WS_API.FIELDS.TOKEN_DATA.HP + this.SEP + "?{Select a Bar|bar1|bar2|bar3}"),
this.makeLabelValue("AC", config[WS_API.FIELDS.TOKEN_DATA.ROOT][WS_API.FIELDS.TOKEN_DATA.AC]) + this.makeRightButton("Edit", cmdConfigEdit + WS_API.FIELDS.TOKEN_DATA.ROOT + this.SEP + WS_API.FIELDS.TOKEN_DATA.AC + this.SEP + "?{Select a Bar|none|bar1|bar2|bar3}"),
this.makeLabelValue("SPEED", config[WS_API.FIELDS.TOKEN_DATA.ROOT][WS_API.FIELDS.TOKEN_DATA.SPEED]) + this.makeRightButton("Edit", cmdConfigEdit + WS_API.FIELDS.TOKEN_DATA.ROOT + this.SEP + WS_API.FIELDS.TOKEN_DATA.SPEED + this.SEP + "?{Select a Bar|none|bar1|bar2|bar3}"),
], " padding-left: 10px"),
];
// PC settings
let pcDataList = [
this.makeLabel("<p style='font-size: 120%'><b>PC Data:</b></p>"),
this.makeLabel("Attributes on sheets used to link to the data", "font-size: 80%; padding-left: 10px; padding-bottom: 10px"),
this.makeList(
[
this.makeLabelValue("HP", config[WS_API.FIELDS.PC_DATA.ROOT][WS_API.FIELDS.PC_DATA.HP]) + this.makeRightButton("Edit", cmdConfigEdit + WS_API.FIELDS.PC_DATA.ROOT + this.SEP + WS_API.FIELDS.PC_DATA.HP + this.SEP + "?{Attribute|" + config[WS_API.FIELDS.PC_DATA.ROOT][WS_API.FIELDS.PC_DATA.HP] + "}"),
this.makeLabelValue("AC", config[WS_API.FIELDS.PC_DATA.ROOT][WS_API.FIELDS.PC_DATA.AC]) + this.makeRightButton("Edit", cmdConfigEdit + WS_API.FIELDS.PC_DATA.ROOT + this.SEP + WS_API.FIELDS.PC_DATA.AC + this.SEP + "?{Attribute|" + config[WS_API.FIELDS.PC_DATA.ROOT][WS_API.FIELDS.PC_DATA.AC] + "}"),
this.makeLabelValue("SPEED", config[WS_API.FIELDS.PC_DATA.ROOT][WS_API.FIELDS.PC_DATA.SPEED]) + this.makeRightButton("Edit", cmdConfigEdit + WS_API.FIELDS.PC_DATA.ROOT + this.SEP + WS_API.FIELDS.PC_DATA.SPEED + this.SEP + "?{Attribute|" + config[WS_API.FIELDS.PC_DATA.ROOT][WS_API.FIELDS.PC_DATA.SPEED] + "}"),
], " padding-left: 10px"),
];
// NPC settings
let npcDataList = [
this.makeLabel("<p style='font-size: 120%'><b>NPC Data:</b></p>"),
this.makeLabel("Attributes on sheets used to link to the data", "font-size: 80%; padding-left: 10px; padding-bottom: 10px"),
this.makeList(
[
this.makeLabelValue("HP", config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.HP]) + this.makeRightButton("Edit", cmdConfigEdit + WS_API.FIELDS.NPC_DATA.ROOT + this.SEP + WS_API.FIELDS.NPC_DATA.HP + this.SEP + "?{Attribute|" + config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.HP] + "}"),
this.makeLabelValue("AC", config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.AC]) + this.makeRightButton("Edit", cmdConfigEdit + WS_API.FIELDS.NPC_DATA.ROOT + this.SEP + WS_API.FIELDS.NPC_DATA.AC + this.SEP + "?{Attribute|" + config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.AC] + "}"),
this.makeLabelValue("SPEED", config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.SPEED]) + this.makeRightButton("Edit", cmdConfigEdit + WS_API.FIELDS.NPC_DATA.ROOT + this.SEP + WS_API.FIELDS.NPC_DATA.SPEED + this.SEP + "?{Attribute|" + config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.SPEED] + "}"),
this.makeLabelValue("SENSES", config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.SENSES]) + this.makeRightButton("Edit", cmdConfigEdit + WS_API.FIELDS.NPC_DATA.ROOT + this.SEP + WS_API.FIELDS.NPC_DATA.SENSES + this.SEP + "?{Attribute|" + config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.SENSES] + "}"),
], " padding-left: 10px"),
];
// senses settings
let sensesDataList = [
this.makeLabel("<p style='font-size: 120%'><b>Default Senses:</b></p>"),
this.makeLabel("Write senses to token, defaults if data cannot be found", "font-size: 80%; padding-left: 10px; padding-bottom: 10px"),
this.makeLabelValue("Write Senses", config[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE], 'false') + this.makeRightButton("Edit", cmdConfigEdit + WS_API.FIELDS.SENSES.ROOT)
];
// finalization
const resetButton = this.makeButton('Reset', this.CMD.CONFIG_RESET + this.SEP + "?{Are you sure you want to reset all configs?|no|yes}", ' width: 100%');
let title_text = WS_API.NAME + " v" + WS_API.VERSION + ((newVersion) ? ': New Version Setup' : ': Config');
let contents = showShiftersButton + '<hr>'
+ this.makeList(otherSettingsList)
+ this.makeList(tokenDataList)
+ this.makeList(pcDataList)
+ this.makeList(npcDataList)
+ this.makeList(sensesDataList)
+ '<hr>' + resetButton;
this.showMenu(WS_API.NAME, contents, title_text);
}
showShapeShiftMenu(who, playerid, shifterId, shapes) {
const cmdShapeShift = this.CMD.ROOT + WS_API.CMD.SHIFT + this.SEP;
let contents = '';
if (playerIsGM(playerid))
{
const cmdShifterEdit = this.CMD.CONFIG_EDIT + WS_API.FIELDS.TARGET.SHIFTER + this.SEP;
contents += this.makeButton("Edit", cmdShifterEdit + shifterId, ' width: 100%') + "<hr>";
}
contents += this.makeButton(shifterId, cmdShapeShift + WS_API.SETTINGS.BASE_SHAPE, ' width: 100%') + "<hr>";
_.each(shapes, (value, key) => {
contents += this.makeButton(key, cmdShapeShift + key, ' width: 100%');
});
this.showMenu(WS_API.NAME, contents, WS_API.NAME + ': ' + shifterId + ' ShapeShift', {whisper: who});
}
}
// ========================================= WILD SHAPE =========================================
var WildShape = WildShape || (function() {
'use strict';
let MENU = new WildShapeMenu();
let UTILS = new WildUtils(WS_API.NAME, WS_API.DEBUG);
const sortShifters = () => {
// order shifters
state[WS_API.STATENAME][WS_API.DATA_SHIFTERS] = UTILS.sortByKey(state[WS_API.STATENAME][WS_API.DATA_SHIFTERS]);
};
const sortShapes = (shifter) => {
// order shapes
shifter[WS_API.FIELDS.SHAPES] = UTILS.sortByKey(shifter[WS_API.FIELDS.SHAPES]);
};
const copySenses = (from, to) =>
{
const fromSenses = from[WS_API.FIELDS.SENSES.ROOT];
let toSenses = {};
_.each(WS_API.FIELDS.SENSES.LIGHT_ATTRS, function (attr)
{
toSenses[attr] = fromSenses[attr];
});
toSenses[WS_API.FIELDS.SENSES.OVERRIDE] = fromSenses[WS_API.FIELDS.SENSES.OVERRIDE];
to[WS_API.FIELDS.SENSES.ROOT] = toSenses;
};
// cache basic stats and modifiers
const cacheCharacterData = (target) => {
const targetId = target[WS_API.FIELDS.ID];
const isNpc = (getAttrByName(targetId, 'npc', 'current') == 1);
const STATS = WS_API.SETTINGS.STATS;
const PREFIX = isNpc ? STATS.PREFIX.NPC : "";
const SUFFIX_MOD = STATS.SUFFIX.MOD;
const SUFFIX_SAVE = STATS.SUFFIX.SAVE;
const SUFFIX_PROF = STATS.SUFFIX.PROF;
let stats = {};
let mods = {};
let saves = {};
let skills = {};
for (let statIndex = 0; statIndex < 6; ++statIndex) {
const statName = STATS.NAMES[statIndex];
const shortStatName = STATS.SHORT_NAMES[statIndex];
// copy stat
let attr = findObjs({_type: "attribute", name: statName, _characterid: targetId})[0];
stats[statName] = attr ? Number(attr.get("current")) : 0;
// copy modifier
attr = findObjs({_type: "attribute", name: statName + SUFFIX_MOD, _characterid: targetId})[0];
let mod = attr ? Number(attr.get("current")) : 0;
mods[statName] = mod;
// copy save
attr = findObjs({_type: "attribute", name: PREFIX + (isNpc ? shortStatName : statName) + SUFFIX_SAVE, _characterid: targetId})[0];
saves[statName] = attr && attr.get("current") != "" ? Number(attr.get("current")) : mod;
// copy skills
_.each(STATS.SKILLS[statName], (skillName) => {
attr = findObjs({_type: "attribute", name: PREFIX + skillName, _characterid: targetId})[0];
skills[skillName] = attr && attr.get("current") != "" ? Number(attr.get("current")) : mod;
});
}
let statsCache = {};
statsCache[WS_API.FIELDS.STATS_CACHE.STATS] = stats;
statsCache[WS_API.FIELDS.STATS_CACHE.MODS] = mods;
statsCache[WS_API.FIELDS.STATS_CACHE.SAVES] = saves;
statsCache[WS_API.FIELDS.STATS_CACHE.SKILLS] = skills;
target[WS_API.FIELDS.STATS_CACHE.ROOT] = statsCache;
};
const getCreatureSize = (targetSize) => {
return targetSize ? Math.max(_.indexOf(WS_API.SETTINGS.SHAPE_SIZES, targetSize.toLowerCase()), 0) : 0;
};
const findShifterData = (tokenObj, silent = false) => {
//let tokenObj = getObj(selectedToken._type, selectedToken._id);
//const id = tokenObj.get("represents");
//const targetId = _.findKey(state[WS_API.STATENAME][WS_API.DATA_SHIFTERS], function(s) { return s[WS_API.FIELDS.SETTINGS][WS_API.FIELDS.ID] == id; });
//if (targetKey)
const targetId = tokenObj.get("name");
const target = state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][targetId];
if(target)
{
const targetCharacterId = target[WS_API.FIELDS.SETTINGS][WS_API.FIELDS.ID];
const targetCharacter = findObjs({ type: 'character', id: targetCharacterId })[0];
if(targetCharacter)
{
return {
token: tokenObj,
shifterId: targetId,
shifter: target,
shifterCharacterId: targetCharacterId,
shifterCharacter: targetCharacter,
shifterControlledby: targetCharacter.get("controlledby")
};
}
else if (!silent)
UTILS.chatError("Cannot find ShapeShifter: " + targetId + ", character id: " + target[WS_API.FIELDS.SETTINGS][WS_API.FIELDS.ID]);
}
else if (!silent)
UTILS.chatError("Cannot find ShapeShifter: " + targetId);
return null;
};
async function getTargetCharacterData(shiftData, isTargetNpc, isTargetDefault) {
const config = state[WS_API.STATENAME][WS_API.DATA_CONFIG];
const shifterSettings = shiftData.shifter[WS_API.FIELDS.SETTINGS];
const targetData = shiftData.targetShape ? shiftData.targetShape : shifterSettings;
let data = {};
let targetSize = 1;
let hpName;
let acName;
let speedName;
let senses = null;
// setup token data
if(isTargetNpc)
{
hpName = config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.HP];
acName = config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.AC];
speedName = config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.SPEED];
// get token size
targetSize = getCreatureSize(targetData[WS_API.FIELDS.SIZE]);
if (targetSize === 0)
{
targetSize = getAttrByName(shiftData.targetCharacterId, "token_size");
if(!targetSize)
targetSize = 1;
}
}
else
{
hpName = config[WS_API.FIELDS.PC_DATA.ROOT][WS_API.FIELDS.PC_DATA.HP];
acName = config[WS_API.FIELDS.PC_DATA.ROOT][WS_API.FIELDS.PC_DATA.AC];
speedName = config[WS_API.FIELDS.PC_DATA.ROOT][WS_API.FIELDS.PC_DATA.SPEED];
// get token size
targetSize = getCreatureSize(shifterSettings[WS_API.FIELDS.SIZE]);
// auto defaults to normal on PCs
if (targetSize == 0)
targetSize = 1;
}
// the get on _defaulttoken is async, need to wait on it
let targetImg = null;
await UTILS.getDefaultTokenImage(shiftData.targetCharacter).then((img) => {
targetImg = img;
if (!targetImg || targetImg.trim() == "")
{
UTILS.debugChat("cannot find default token image, getting avatar image");
targetImg = UTILS.getCleanImgsrc(shiftData.targetCharacter.get('avatar'));
if (!targetImg || targetImg.trim() == "")
{
UTILS.chatErrorToPlayer(shiftData.who, "cannot use image with marketplace link, the image needs to be re-uploaded into the library and set on the target character as either token or avatar image; character id = " + shiftData.targetCharacterId);
targetImg = null;
}
}
});
if (!targetImg)
return null;
// setup other output data
{
data.imgsrc = targetImg;
data.characterId = shiftData.targetCharacterId;
data.controlledby = shiftData.shifterControlledby;
data.tokenSize = targetSize;
}
// setup hp/ac/speed on token bars
function setTokenBarValue(fieldId, attrName)
{
let obj = findObjs({type: "attribute", characterid: shiftData.targetCharacterId, name: attrName})[0];
if(obj)
{
data[fieldId] = {};
data[fieldId].current = obj.get('current');
data[fieldId].max = obj.get('max');
data[fieldId].id = obj.id;
return true;
}
else
{
UTILS.chatErrorToPlayer(shiftData.who, "cannot find attribute [" + attrName + "] on character: " + shiftData.targetCharacterId);
return false;
}
}
if (!setTokenBarValue("hp", hpName)) return false;
if (!setTokenBarValue("ac", acName)) return false;
if (!setTokenBarValue("speed", speedName)) return false;
// setup senses
if (config[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE])
{
let senses = {};
if (targetData[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE])
{
_.each(WS_API.FIELDS.SENSES.LIGHT_ATTRS, (attr) => {
senses[attr] = targetData[WS_API.FIELDS.SENSES.ROOT][attr];
});
}
else
{
// copy the defaults
_.each(WS_API.FIELDS.SENSES.LIGHT_ATTRS, (attr) => {
senses[attr] = config[WS_API.FIELDS.SENSES.ROOT][attr];
});
if (isTargetNpc)
{
// get npc senses
let targetSenses = getAttrByName(shiftData.targetCharacterId, config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.SENSES]);
if (targetSenses)
{
// set radius to darkvision
let visionSense = targetSenses.match(/darkvision\s([0-9]+)/);
let hasDarkvision = visionSense && visionSense.length >= 2;
if (hasDarkvision)
senses.light_radius = visionSense[1];
visionSense = targetSenses.match(/blindsight\s([0-9]+)/);
if (visionSense && visionSense.length >= 2)
{
// set end of bright radius to blindsight
senses.light_dimradius = visionSense[1];
if (!hasDarkvision)
senses.light_radius = senses.light_dimradius;
}
}
}
}
data.senses = senses;
}
// special handling of NPC ShapeShifter to restore hp when going back to original form, as they don't store the current in hp
if(shifterSettings[WS_API.FIELDS.ISNPC])
{
if (isTargetDefault)
{
if (shifterSettings[WS_API.FIELDS.CURRENT_SHAPE] != WS_API.SETTINGS.BASE_SHAPE)
{
data.hp.current = shifterSettings[config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.HP_CACHE]];
}
else
return null;
}
else if (shifterSettings[WS_API.FIELDS.CURRENT_SHAPE] == WS_API.SETTINGS.BASE_SHAPE)
{
// cache current npc hp value
shifterSettings[config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.HP_CACHE]] = shiftData.token.get(config[WS_API.FIELDS.TOKEN_DATA.ROOT][WS_API.FIELDS.TOKEN_DATA.HP] + "_value");
}
}
return data;
}
const copyDruidProficiency = (profData) => {
/*
You also retain all of your skill and saving throw Proficiencies, in addition to gaining those of the creature.
If the creature has the same proficiency as you and the bonus in its stat block is higher than yours, use the creatureโs bonus instead of yours.
*/
let shapeStatAttr = findObjs({_type: "attribute", name: profData.shapeStatName, _characterid: profData.shapeId})[0];
if (shapeStatAttr)
{
// target could have proficiency in a stat we don't, default to that proficiency bonus
let statPb = profData.shapeStatValue - profData.shapeStatMod;
const isProficient = UTILS.isProficient(profData.druidId, profData.druidStatName + WS_API.SETTINGS.STATS.SUFFIX.PROF);
UTILS.debugChat("-- stat " + profData.shapeStatName + ": " + profData.shapeStatValue.toString() + ", npc pb: " + statPb + ", npc mod " + profData.shapeStatMod + ", druid pb: " + (isProficient ? profData.druidPb : 0), false);
// check which proficiency bonus we should use
if (isProficient && profData.druidPb > statPb)
{
statPb = profData.druidPb;
}
// update stat value based on current modifier and best proficiency
const newShapeStatValue = profData.statMod + statPb;
const oldShapeStatValue = Number(shapeStatAttr.get("current"));
if (newShapeStatValue !== oldShapeStatValue || shapeStatAttr.get("current") == "")
{
shapeStatAttr.set("current", newShapeStatValue);
UTILS.debugChat("-- CHANGING -- " + profData.shapeStatName + " from " + oldShapeStatValue + " to: " + newShapeStatValue.toString(), false);
// also set _base value
shapeStatAttr = findObjs({_type: "attribute", name: profData.shapeStatName + WS_API.SETTINGS.STATS.SUFFIX.BASE, _characterid: profData.shapeId})[0];
if (shapeStatAttr)
{
shapeStatAttr.set("current", (newShapeStatValue > 0 ? "+" : "") + newShapeStatValue.toString());
}
}
// set _flag value so that stats are forced to be displayed on NPCs
shapeStatAttr = findObjs({_type: "attribute", name: profData.shapeStatName + WS_API.SETTINGS.STATS.SUFFIX.FLAG, _characterid: profData.shapeId})[0];
if (shapeStatAttr)
{
shapeStatAttr.set("current", 1);
}
}
else
{
UTILS.chatError("cannot find attribute " + profData.shapeStatName + " on shape " + profData.shapeId);
}
};
const copyDruidData = (shiftData) => {
const STATS = WS_API.SETTINGS.STATS;
const targetStatsCache = shiftData.targetShape[WS_API.FIELDS.STATS_CACHE.ROOT];
const statsCache = targetStatsCache[WS_API.FIELDS.STATS_CACHE.STATS];
const modsCache = targetStatsCache[WS_API.FIELDS.STATS_CACHE.MODS];
const savesCache = targetStatsCache[WS_API.FIELDS.STATS_CACHE.SAVES];
const skillsCache = targetStatsCache[WS_API.FIELDS.STATS_CACHE.SKILLS];
let druidCharacterId = shiftData.shifter[WS_API.FIELDS.SETTINGS][WS_API.FIELDS.ID];
let targetCharacterId = shiftData.targetCharacterId;
let targetCharacter = shiftData.targetCharacter;
let targetShape = shiftData.targetShape;
// copy attributes
UTILS.debugChat("copying druid attributes");
_.each(STATS.DRUID_COPY_ATTR, function (attrName) {
UTILS.copyAttribute(druidCharacterId, attrName, targetCharacterId, attrName, false);
UTILS.copyAttribute(druidCharacterId, attrName + STATS.SUFFIX.BASE, targetCharacterId, attrName + STATS.SUFFIX.BASE, false);
UTILS.copyAttribute(druidCharacterId, attrName + STATS.SUFFIX.MOD, targetCharacterId, attrName + STATS.SUFFIX.MOD, false);
});
// copy proficiencies
let profData = {};
profData.druidId = druidCharacterId;
profData.shapeId = targetCharacterId;
let druidPb = findObjs({_type: "attribute", name: STATS.PROF, _characterid: druidCharacterId})[0];
profData.druidPb = druidPb ? Number(druidPb.get("current")) : 0;
UTILS.debugChat("druid pb: " + profData.druidPb, false);
for (let statIndex = 0; statIndex < 6; ++statIndex)
{
const statName = STATS.NAMES[statIndex];
const shortStatName = STATS.SHORT_NAMES[statIndex];
// original stat modifier on target
let statMod = findObjs({_type: "attribute", name: statName + WS_API.SETTINGS.STATS.SUFFIX.MOD, _characterid: targetCharacterId})[0];
profData.statMod = statMod ? Number(statMod.get("current")) : 0;
profData.shapeStatMod = modsCache[statName];
// copy save proficiency
profData.druidStatName = statName + STATS.SUFFIX.SAVE;
profData.shapeStatName = STATS.PREFIX.NPC + shortStatName + STATS.SUFFIX.SAVE;
profData.shapeStatValue = savesCache[statName];
copyDruidProficiency(profData);
// copy skill proficiency for all skills associated with this stat
_.each(STATS.SKILLS[statName], (skillName) => {
profData.druidStatName = skillName;
profData.shapeStatName = STATS.PREFIX.NPC + skillName;
profData.shapeStatValue = skillsCache[skillName];
copyDruidProficiency(profData);
});
}
UTILS.debugFlush("copying druid proficiencies");
// npc saving/skills flag
let npc_attr_flag = findObjs({_type: "attribute", name: "npc_saving_flag", _characterid: targetCharacterId})[0];
if (npc_attr_flag)
{
npc_attr_flag.set("current", 1);
}
npc_attr_flag = findObjs({_type: "attribute", name: "npc_skills_flag", _characterid: targetCharacterId})[0];
if (npc_attr_flag)
{
npc_attr_flag.set("current", 1);
}
};
async function doShapeShift(shiftData) {
const config = state[WS_API.STATENAME][WS_API.DATA_CONFIG];
const shifterSettings = shiftData.shifter[WS_API.FIELDS.SETTINGS];
let isTargetNpc = true;
let isTargetDefault = false;
let wildShapeResource = null;
if(shiftData.targetShape)
{
// if it's a druid shapeshifting check that we have enough uses of the wildshape resource left
if(shifterSettings[WS_API.FIELDS.ISDRUID] && !shiftData.ignoreDruidResource)
{
const wsResName = config[WS_API.FIELDS.DRUID_WS_RES];
if(wsResName && wsResName.length > 0)
{
wildShapeResource = UTILS.getResourceAttribute(shifterSettings[WS_API.FIELDS.ID], wsResName, false);
if (wildShapeResource)
{
if (wildShapeResource.get("current") <= 0)
{
if (shiftData.isGM)
{
wildShapeResource = null;
UTILS.chat("GM OVERRIDE - You have NO WildShape usage left for the day! resource name: " + wsResName);
}
else
{
UTILS.chatErrorToPlayer(shiftData.who, "You have NO WildShape usage left for the day! resource name: " + wsResName);
return false;
}
}
}
else
{
UTILS.chatErrorToPlayer(shiftData.who, "Cannot find wildshape resource attribute on character sheet = " + wsResName);
return false;
}
}
}
shiftData.targetCharacterId = shiftData.targetShape[WS_API.FIELDS.ID];
shiftData.targetCharacter = findObjs({ type: 'character', id: shiftData.targetCharacterId })[0];
if (!shiftData.targetCharacter)
{
UTILS.chatErrorToPlayer(shiftData.who, "Cannot find target character = " + shiftData.targetShape[WS_API.FIELDS.CHARACTER] + " with id = " + shiftData.targetCharacterId);
return false;
}
isTargetNpc = (getAttrByName(shiftData.targetCharacterId, 'npc', 'current') == 1);
}
else
{
// transform back into default shifter character
shiftData.targetCharacterId = shiftData.shifterCharacterId;
shiftData.targetCharacter = shiftData.shifterCharacter;
isTargetNpc = shifterSettings[WS_API.FIELDS.ISNPC];
isTargetDefault = true;
}
let targetData = null;
await getTargetCharacterData(shiftData, isTargetNpc, isTargetDefault).then((ret) => { targetData = ret; });
if (!targetData)
return false;
if (WS_API.DEBUG)
{
let debugStats = ""
+ ("====== TARGET STATS ======")
+ ("<br>token_size = " + targetData.tokenSize)
+ ("<br>controlledby = " + targetData.controlledby)
+ ("<br>avatar = " + targetData.imgsrc)
+ ("<br>hp = " + (targetData.hp ? targetData.hp.current : "invalid"))
+ ("<br>ac = " + (targetData.ac ? targetData.ac.current : "invalid"))
+ ("<br>npc speed = " + (targetData.speed ? targetData.speed.current : "invalid"));
UTILS.debugChat(debugStats);
}
const tokenFields = WS_API.FIELDS.TOKEN_DATA;
if (isTargetNpc)
{
// copy over druid attributes
if (shifterSettings[WS_API.FIELDS.ISDRUID])
{
copyDruidData(shiftData);
}
if (targetData.ac && config[tokenFields.ROOT][tokenFields.AC] != config[tokenFields.ROOT][tokenFields.EMPTYBAR])
{
shiftData.token.set(config[tokenFields.ROOT][tokenFields.AC] + "_link", 'None');
shiftData.token.set(config[tokenFields.ROOT][tokenFields.AC] + "_value", targetData.ac.current);
}
if (targetData.speed && config[tokenFields.ROOT][tokenFields.SPEED] != config[tokenFields.ROOT][tokenFields.EMPTYBAR])
{
shiftData.token.set(config[tokenFields.ROOT][tokenFields.SPEED] + "_link", 'None');
shiftData.token.set(config[tokenFields.ROOT][tokenFields.SPEED] + "_value", ((!_.isNumber(targetData.speed.current)) && targetData.speed.current.indexOf(' ')) > 0 ? targetData.speed.current.split(' ')[0] : targetData.speed.current);
}
// set HP last in case we need to override another value because of wrong data
if (targetData.hp)
{
shiftData.token.set(config[tokenFields.ROOT][tokenFields.HP] + "_link", 'None');
shiftData.token.set(config[tokenFields.ROOT][tokenFields.HP] + "_value", isTargetDefault ? targetData.hp.current : targetData.hp.max);
shiftData.token.set(config[tokenFields.ROOT][tokenFields.HP] + "_max", targetData.hp.max);
}
}
else
{
if (targetData.ac && config[tokenFields.ROOT][tokenFields.AC] != config[tokenFields.ROOT][tokenFields.EMPTYBAR])
{
shiftData.token.set(config[tokenFields.ROOT][tokenFields.AC] + "_link", isTargetDefault ? targetData.ac.id : 'None');
shiftData.token.set(config[tokenFields.ROOT][tokenFields.AC] + "_value", targetData.ac.current);
}
if (targetData.speed && config[tokenFields.ROOT][tokenFields.SPEED] != config[tokenFields.ROOT][tokenFields.EMPTYBAR])
{
shiftData.token.set(config[tokenFields.ROOT][tokenFields.SPEED] + "_link", targetData.speed.id);
shiftData.token.set(config[tokenFields.ROOT][tokenFields.SPEED] + "_value", targetData.speed.current);
}
// set HP last in case we need to override another value because of wrong data
if (targetData.hp)
{
shiftData.token.set(config[tokenFields.ROOT][tokenFields.HP] + "_link", isTargetDefault ? targetData.hp.id : 'None');
shiftData.token.set(config[tokenFields.ROOT][tokenFields.HP] + "_value", isTargetDefault ? targetData.hp.current : targetData.hp.max);
shiftData.token.set(config[tokenFields.ROOT][tokenFields.HP] + "_max", targetData.hp.max);
}
}
// override default rolltype, whisper and autoroll damage settings to: toggle, visible to everyone and don't auto roll damage
// sometimes as a default values these attributes don't exist at all so we need to create them
if (shifterSettings[WS_API.FIELDS.MAKEROLLPUBLIC])
{
UTILS.setAttribute(shiftData.targetCharacterId, "rtype", "@{advantagetoggle}", true);
UTILS.setAttribute(shiftData.targetCharacterId, "advantagetoggle", "{{query=1}} {{normal=1}} {{r2=[[0d20", true);
UTILS.setAttribute(shiftData.targetCharacterId, "wtype", "", true);
UTILS.setAttribute(shiftData.targetCharacterId, "dtype", "pick", true);
}
// we need to turn bar visibility on if the target is controlled by a player
if (targetData.controlledby.length > 0)
{
if (config[tokenFields.ROOT][tokenFields.AC] !== config[tokenFields.ROOT][tokenFields.EMPTYBAR])
{
shiftData.token.set("showplayers_" + config[tokenFields.ROOT][tokenFields.AC], false);
shiftData.token.set("playersedit_" + config[tokenFields.ROOT][tokenFields.AC], true);
}
if (config[tokenFields.ROOT][tokenFields.SPEED] !== config[tokenFields.ROOT][tokenFields.EMPTYBAR])
{
shiftData.token.set("showplayers_" + config[tokenFields.ROOT][tokenFields.SPEED], false);
shiftData.token.set("playersedit_" + config[tokenFields.ROOT][tokenFields.SPEED], true);
}
shiftData.token.set("showplayers_" + config[tokenFields.ROOT][tokenFields.HP], false);
shiftData.token.set("playersedit_" + config[tokenFields.ROOT][tokenFields.HP], true);
}
// check if the token is on a scaled page
let tokenPageScale = 1.0;
var tokenPageData = getObj("page", shiftData.token.get("pageid"));
if (tokenPageData)
{
let snapping_increment = tokenPageData.get("snapping_increment");
if (snapping_increment && snapping_increment > 0)
tokenPageScale = snapping_increment;
}
let tokenBaseSize = 70 * tokenPageScale;
// set other token data
shiftData.token.set({
imgsrc: targetData.imgsrc,
represents: targetData.characterId,
height: tokenBaseSize * targetData.tokenSize,
width: tokenBaseSize * targetData.tokenSize,
});
// set token sense
if (targetData.senses)
{
_.each(WS_API.FIELDS.SENSES.LIGHT_ATTRS, function setLightAttr(attr) {
shiftData.token.set(attr, targetData.senses[attr]);
});
}
if (!isTargetDefault)
{
shiftData.targetCharacter.set({controlledby: targetData.controlledby, inplayerjournals: targetData.controlledby});
}
shifterSettings[WS_API.FIELDS.CURRENT_SHAPE] = shiftData.targetShapeName;
// update wildshape resource
if (wildShapeResource)
{
let wsCurrent = wildShapeResource.get("current") - 1;
wildShapeResource.set("current", wsCurrent);
if (!config[WS_API.FIELDS.MUTE_SHIFT])
{
UTILS.chatToPlayer(shiftData.who, config[WS_API.FIELDS.DRUID_WS_RES] + " left: " + wsCurrent + " / " + wildShapeResource.get("max"));
}
}
return true;
}
async function addShapeToShifter(config, shifter, shapeCharacter, newCharacterName, shapeId = null, doSort = true) {
const shapeName = shapeCharacter.get('name');
if ((!shapeId) || (typeof shapeId !== 'string') || (shapeId.length == 0))
shapeId = shapeName;
if (shifter[WS_API.FIELDS.SHAPES][shapeId])
{
UTILS.chatError("Trying to add a shape with an ID that's already used, skipping: " + shapeId);
return false;
}
UTILS.chat("adding shape " + shapeId + ", please wait...");
await UTILS.duplicateCharacter(shapeCharacter, newCharacterName)
.then(
function(newShapeCharacter) { shapeCharacter = newShapeCharacter; }
);
if(!shapeCharacter)
{
UTILS.chatError("cannot duplicate character, skipping: " + shapeId);
return false;
}
let shape = {};
shape[WS_API.FIELDS.ID] = shapeCharacter.get('_id');
shape[WS_API.FIELDS.CHARACTER] = newCharacterName;
shape[WS_API.FIELDS.SIZE] = WS_API.SETTINGS.SHAPE_SIZE;
shape[WS_API.FIELDS.ISDUPLICATE] = true;
cacheCharacterData(shape);
copySenses(config, shape);
shape[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE] = false;
shifter[WS_API.FIELDS.SHAPES][shapeId] = shape;
const shifterCharacter = findObjs({ type: 'character', id: shifter[WS_API.FIELDS.SETTINGS][WS_API.FIELDS.ID] })[0];
if (shifterCharacter)
{
const shifterControlledBy = shifterCharacter.get("controlledby");
shapeCharacter.set({controlledby: shifterControlledBy, inplayerjournals: shifterControlledBy});
}
if (doSort)
{
sortShapes(shifter);
}
return true;
}
const handleInputShift = (msg, args, config) =>
{
if(!msg.selected)
{
UTILS.chatErrorToPlayer(msg.who, "Please select a token before shapeshifting");
return;
}
const shapeName = args.shift();
const tokenObj = getObj(msg.selected[0]._type, msg.selected[0]._id);
const obj = findShifterData(tokenObj);
if(obj)
{
// check that the player sending the command can actually control the token
obj.isGM = playerIsGM(msg.playerid);
if (obj.isGM || obj.shifterControlledby.search(msg.playerid) >= 0 || obj.shifterControlledby.search("all") >= 0)
{
obj.who = msg.who;
obj.targetShapeName = shapeName;
if (obj.targetShapeName !== obj.shifter[WS_API.FIELDS.SETTINGS][WS_API.FIELDS.CURRENT_SHAPE])
{
if (obj.targetShapeName != WS_API.SETTINGS.BASE_SHAPE)
{
obj.targetShape = obj.shifter[WS_API.FIELDS.SHAPES][obj.targetShapeName];
if (!obj.targetShape)
{
UTILS.chatErrorToPlayer(msg.who, "Cannot find shape [" + obj.targetShapeName + "] for ShapeShifter: " + obj.shifterId);
return;
}
}
doShapeShift(obj).then((ret) => {
if (ret && !config[WS_API.FIELDS.MUTE_SHIFT])
{
if (obj.targetShape)
UTILS.chatAs(obj.shifterCharacter.get("id"), "Transforming into " + shapeName, null, null);
else
UTILS.chatAs(obj.shifterCharacter.get("id"), "Transforming back into " + obj.shifterId, null, null);
}
});
}
else
{
UTILS.chatErrorToPlayer(msg.who, "You are already transformed into " + shapeName);
}
}
else
{
UTILS.chatErrorToPlayer(msg.who, "Trying to shapeshift on a token you don't have control over");
}
}
else
{
UTILS.chatErrorToPlayer(msg.who, "Cannot find a ShapeShifter for the selected token");
}
};
const handleInputAddShifter = (msg, args, config) =>
{
let tokenId = args.shift();
let tokenObj = findObjs({type:'graphic', id:tokenId})[0];
const shifterKey = tokenObj ? tokenObj.get("name") : null;
if (shifterKey && shifterKey.length > 0)
{
let shifter = state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterKey];
if(!shifter)
{
const charId = tokenObj.get("represents");
let charObj = findObjs({ type: 'character', id: charId });
if(charObj && charObj.length == 1)
{
const isNpc = (getAttrByName(charId, 'npc', 'current') == 1);
shifter = {};
let shifterSettings = {};
shifterSettings[WS_API.FIELDS.ID] = charId;
shifterSettings[WS_API.FIELDS.CHARACTER] = charObj[0].get('name');
shifterSettings[WS_API.FIELDS.SIZE] = isNpc ? WS_API.SETTINGS.SHAPE_SIZE : WS_API.SETTINGS.SHIFTER_SIZE;
shifterSettings[WS_API.FIELDS.ISDRUID] = !isNpc;
shifterSettings[WS_API.FIELDS.ISNPC] = isNpc;
shifterSettings[WS_API.FIELDS.MAKEROLLPUBLIC] = !isNpc;
shifterSettings[WS_API.FIELDS.CURRENT_SHAPE] = WS_API.SETTINGS.BASE_SHAPE;
copySenses(config, shifterSettings);
shifterSettings[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE] = false;
shifter[WS_API.FIELDS.SETTINGS] = shifterSettings;
shifter[WS_API.FIELDS.SHAPES] = {};
state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterKey] = shifter;
sortShifters();
MENU.showEditShifter(shifterKey);
}
else
{
UTILS.chatError("Cannot find character with id [" + charId + "] in the journal");
}
}
else
{
UTILS.chatError("Trying to add ShapeShifter " + shifterKey + " which already exists");
}
}
else
{
UTILS.chatError("Trying to add ShapeShifter from a token without a name");
}
};
async function handleInputAddShape(msg, args, config)
{
const shifterKey = args.shift();
let shifter = state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterKey];
if (shifter)
{
const shapeName = args.shift();
let shapeObj = findObjs({ type: 'character', name: shapeName })[0];
if(shapeObj)
{
let shapeCharacterName = shifterKey + " - " + shapeName;
await addShapeToShifter(config, shifter, shapeObj, shapeCharacterName).then(
(ret) => { if (ret) { MENU.showEditShifter(shifterKey); UTILS.chat("New shape added: " + shapeName); } } );
}
else
{
UTILS.chatError("Cannot find character [" + shapeName + "] in the journal");
}
}
else
{
UTILS.chatError("Trying to add shape to ShapeShifter " + shifterKey + " which doesn't exist");
MENU.showShifters();
}
}
async function handleInputRemoveShifter(msg, args, config)
{
const shifterKey = args.shift();
if (shifterKey)
{
if(state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterKey])
{
let shifter = state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterKey];
_.each(shifter[WS_API.FIELDS.SHAPES], (shape) => {
removeShape(shape);
});
delete state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterKey];
}
else
{
UTILS.chatError("Trying to delete ShapeShifter " + shifterKey + " which doesn't exists");
}
}
else
{
UTILS.chatError("Trying to delete a ShapeShifter without providing a name");
}
MENU.showShifters();
}
const removeShape = (shape) =>
{
if (shape)
{
const shapeCharacter = findObjs({ type: 'character', id: shape[WS_API.FIELDS.ID] })[0];
if (shapeCharacter)
{
// versions earlier than 1.3 don't have the automatic duplicate, preserve characters
if(shape[WS_API.FIELDS.ISDUPLICATE])
{
shapeCharacter.remove();
}
else
{
shapeCharacter.set({controlledby: "", inplayerjournals: ""});
}
}
return true;
}
return false;
};
async function handleInputRemoveShape(msg, args, config)
{
const shifterKey = args.shift();
const shapeKey = args.shift();
let shifter = state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterKey];
if (shifter)
{
if (shapeKey)
{
let shape = shifter[WS_API.FIELDS.SHAPES][shapeKey];
if (removeShape(shape))
{
delete shifter[WS_API.FIELDS.SHAPES][shapeKey];
}
else
{
UTILS.chatError("Trying to remove shape " + shapeKey + " that doesn't exist from ShapeShifter " + shifterKey);
}
}
else
{
// delete all shapes
_.each(shifter[WS_API.FIELDS.SHAPES], (shape) => {
const shapeCharacter = findObjs({ type: 'character', id: shape[WS_API.FIELDS.ID] })[0];
if (shapeCharacter)
{
// versions earlier than 1.3 don't have the automatic duplicate, preserve characters
if(shape[WS_API.FIELDS.ISDUPLICATE])
{
shapeCharacter.remove();
}
else
{
shapeCharacter.set({controlledby: "", inplayerjournals: ""});
}
}
});
delete shifter[WS_API.FIELDS.SHAPES][shapeKey];
shifter[WS_API.FIELDS.SHAPES] = {};
}
MENU.showEditShifter(shifterKey);
}
else
{
UTILS.chatError("Trying to remove shape from ShapeShifter " + shifterKey + " which doesn't exist");
MENU.showShifters();
}
}
const handleInputEditSenses = (msg, args, config, senses) =>
{
const field = args.shift();
if (field)
{
if (field == WS_API.FIELDS.SENSES.OVERRIDE)
senses[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE] = !senses[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE];
else if (field)
{
let newValue = args.shift();
if (newValue)
{
if (newValue == WS_API.FIELDS.TOGGLE)
senses[WS_API.FIELDS.SENSES.ROOT][field] = !senses[WS_API.FIELDS.SENSES.ROOT][field];
else
senses[WS_API.FIELDS.SENSES.ROOT][field] = newValue;
}
}
}
return field;
};
const handleInputEditShifter = (msg, args, config) =>
{
let shifterKey = args.shift();
let shifter = state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterKey];
if (shifter)
{
const field = args.shift();
if (field)
{
if (field == WS_API.FIELDS.SENSES.ROOT)
{
let shifterSettings = shifter[WS_API.FIELDS.SETTINGS];
const editedSense = handleInputEditSenses(msg, args, config, shifterSettings);
// copy defaults in shifter if we are setting override to false
if(editedSense == WS_API.FIELDS.SENSES.OVERRIDE && !shifterSettings[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE])
{
copySenses(config, shifterSettings);
shifterSettings[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE] = false;
}
MENU.showEditSenses(shifterKey);
return;
}
else
{
let isValueSet = false;
let newValue = args.shift();
if(field == WS_API.FIELDS.NAME)
{
let oldShifterKey = shifterKey;
shifterKey = newValue.trim();
if (shifterKey && shifterKey.length > 0)
{
if(!state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterKey])
{
state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterKey] = shifter;
delete state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][oldShifterKey];
sortShifters();
isValueSet = true;
}
else
{
UTILS.chatError("Trying to add ShapeShifter " + shifterKey + " which already exists");
}
}
}
else if(field == WS_API.FIELDS.CHARACTER)
{
let charObj = findObjs({ type: 'character', name: newValue });
if(charObj && charObj.length == 1)
{
shifter[WS_API.FIELDS.SETTINGS][WS_API.FIELDS.ID] = charObj[0].get('id');
shifter[WS_API.FIELDS.SETTINGS][field] = newValue;
isValueSet = true;
const shifterControlledBy = charObj[0].get("controlledby");
_.each(shifter[WS_API.FIELDS.SHAPES], (shape) => {
let shapeObj = findObjs({ type: 'character', id: shape[WS_API.FIELDS.ID] });
if (shapeObj && shapeObj.length == 1)
shapeObj[0].set({controlledby: shifterControlledBy, inplayerjournals: shifterControlledBy});
});
}
else
{
UTILS.chatError("Cannot find character [" + newValue + "] in the journal");
}
}
else if(field == WS_API.FIELDS.ISDRUID)
{
shifter[WS_API.FIELDS.SETTINGS][WS_API.FIELDS.ISDRUID] = !shifter[WS_API.FIELDS.SETTINGS][WS_API.FIELDS.ISDRUID];
isValueSet = true;
}
else if(field == WS_API.FIELDS.MAKEROLLPUBLIC)
{
shifter[WS_API.FIELDS.SETTINGS][WS_API.FIELDS.MAKEROLLPUBLIC] = !shifter[WS_API.FIELDS.SETTINGS][WS_API.FIELDS.MAKEROLLPUBLIC];
isValueSet = true;
}
else
{
shifter[WS_API.FIELDS.SETTINGS][field] = newValue;
isValueSet = true;
}
if(isValueSet)
MENU.showEditShifter(shifterKey);
}
}
else
MENU.showEditShifter(shifterKey);
}
else
{
UTILS.chatError("cannot find shifter [" + shifterKey + "]");
}
};
const handleInputEditShape = (msg, args, config) =>
{
const shifterKey = args.shift();
let shifter = state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterKey];
if (shifter)
{
let shapeKey = args.shift();
let shape = shifter[WS_API.FIELDS.SHAPES][shapeKey];
if (shape)
{
let field = args.shift();
if (field)
{
if (field == WS_API.FIELDS.SENSES.ROOT)
{
const editedSense = handleInputEditSenses(msg, args, config, shape);
// copy defaults in shape if we are setting override to false
if(editedSense == WS_API.FIELDS.SENSES.OVERRIDE && !shape[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE])
{
copySenses(config, shape);
shape[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE] = false;
}
MENU.showEditSenses(shifterKey, shapeKey);
}
else
{
let newValue = args.shift();
if(field == WS_API.FIELDS.NAME)
{
let oldShapeKey = shapeKey;
shapeKey = newValue.trim();
if (shapeKey && shapeKey.length > 0)
{
if(!shifter[WS_API.FIELDS.SHAPES][shapeKey])
{
shifter[WS_API.FIELDS.SHAPES][shapeKey] = shape;
delete shifter[WS_API.FIELDS.SHAPES][oldShapeKey];
sortShapes(shifter);
MENU.showEditShape(shifterKey, shapeKey);
}
else
{
UTILS.chatError("Trying to rename shape to " + shapeKey + " which already exists");
}
}
}
else
{
shape[field] = newValue;
MENU.showEditShape(shifterKey, shapeKey);
}
}
}
else
{
MENU.showEditShape(shifterKey, shapeKey);
}
}
else
{
UTILS.chatError("cannot find shape [" + shapeKey + "]");
}
}
else
{
UTILS.chatError("cannot find shifter [" + shifterKey + "]");
}
};
const handleInputEditConfig = (msg, args, config) =>
{
switch (args.shift())
{
case WS_API.FIELDS.SEP:
{
config.SEP = args.shift();
MENU.updateConfig();
}
break;
case WS_API.FIELDS.TOKEN_DATA.ROOT:
{
const field = args.shift();
config[WS_API.FIELDS.TOKEN_DATA.ROOT][field] = args.shift();
}
break;
case WS_API.FIELDS.PC_DATA.ROOT:
{
const field = args.shift();
config[WS_API.FIELDS.PC_DATA.ROOT][field] = args.shift();
}
break;
case WS_API.FIELDS.NPC_DATA.ROOT:
{
const field = args.shift();
config[WS_API.FIELDS.NPC_DATA.ROOT][field] = args.shift();
}
break;
case WS_API.FIELDS.SENSES.ROOT:
{
const editedSense = handleInputEditSenses(msg, args, config, config);
if(editedSense && editedSense !== WS_API.FIELDS.SENSES.OVERRIDE)
{
let newSenseValue = config[WS_API.FIELDS.SENSES.ROOT][editedSense];
// update default senses on all shifters/shapes that are not overriding
_.each(state[WS_API.STATENAME][WS_API.DATA_SHIFTERS], (shifterValue, shifterId) => {
let shifterSettings = shifterValue[WS_API.FIELDS.SETTINGS];
// copy defaults in shifters
if (!shifterSettings[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE])
{
shifterSettings[WS_API.FIELDS.SENSES.ROOT][editedSense] = newSenseValue;
}
_.each(shifterValue[WS_API.FIELDS.SHAPES], (shapeValue, shapeId) => {
// copy defaults in shapes
if (!shapeValue[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE])
{
shapeValue[WS_API.FIELDS.SENSES.ROOT][editedSense] = newSenseValue;
}
});
});
}
MENU.showEditSenses();
return;
}
break;
case WS_API.FIELDS.DRUID_WS_RES:
{
config[WS_API.FIELDS.DRUID_WS_RES] = args.shift();
}
break;
case WS_API.FIELDS.MUTE_SHIFT:
{
config[WS_API.FIELDS.MUTE_SHIFT] = !config[WS_API.FIELDS.MUTE_SHIFT];
}
break;
}
MENU.showConfigMenu();
};
async function handleInputImportShapeFolder(msg, args, config)
{
const shifterKey = args.shift();
let shifter = state[WS_API.STATENAME][WS_API.DATA_SHIFTERS][shifterKey];
if (shifter)
{
const folderName = args.shift();
const searchSubfolders = args.shift() == 'yes';
let removePrefix = args.shift();
if (removePrefix == "")
removePrefix = null;
let folderShapes = UTILS.findCharactersInFolder(folderName, searchSubfolders);
if(folderShapes)
{
if (WS_API.DEBUG)
{
let debugShapeNames = "";
_.each(folderShapes, function(shape) { debugShapeNames += shape.get("name") + ", "; });
UTILS.chat("shapes found in input folder = " + debugShapeNames);
}
UTILS.chat("start importing shapes...");
let importedShapes = 0;
for (let shapeIndex = folderShapes.length - 1; shapeIndex >= 0; --shapeIndex) {
let shape = folderShapes[shapeIndex];
let shapeObj = findObjs({ type: 'character', id: shape.id })[0];
if (shapeObj)
{
let newName = shapeObj.get("name");
if (removePrefix && newName.startsWith(removePrefix))
{
newName = newName.slice(removePrefix.length);
}
const shapeId = newName;
newName = shifterKey + " - " + newName;
// add shape to shifter
await addShapeToShifter(config, shifter, shapeObj, newName, shapeId, false).then(
(ret) => { if (ret) importedShapes += 1; });
}
}
if (importedShapes > 0)
{
sortShapes(shifter);
MENU.showEditShifter(shifterKey);
UTILS.chat("Imported " + importedShapes + "/" + folderShapes.length + " Shapes from folder [" + folderName + "]");
}
if (importedShapes < folderShapes.length)
{
UTILS.chat("Not all shapes were imported, please check for errors " + (importedShapes > 0 ? "above the menu" : ""));
}
}
else
{
UTILS.chatError("Cannot find any shapes in the input folder [" + folderName + "]");
}
}
else
{
UTILS.chatError("Trying to add shape to ShapeShifter " + shifterKey + " which doesn't exist");
MENU.showShifters();
}
}
const handleInput = (msg) => {
if (msg.type === "api" && msg.content.indexOf(WS_API.CMD.ROOT) == 0)
{
let config = state[WS_API.STATENAME][WS_API.DATA_CONFIG];
const args = msg.content.split(config.SEP);
args.shift(); // remove WS_API.CMD.ROOT
if(args.length == 0)
{
if (!msg.selected)
{
if (playerIsGM(msg.playerid))
{
MENU.showConfigMenu();
}
else
{
UTILS.chatToPlayer(msg.who, WS_API.CMD.USAGE);
}
return;
}
const tokenObj = getObj(msg.selected[0]._type, msg.selected[0]._id);
const obj = findShifterData(tokenObj);
if (obj)
{
if (playerIsGM(msg.playerid) || obj.shifterControlledby.search(msg.playerid) >= 0 || obj.shifterControlledby.search("all") >= 0)
{
MENU.showShapeShiftMenu(msg.who, msg.playerid, obj.shifterId, obj.shifter[WS_API.FIELDS.SHAPES]);
}
else
{
UTILS.chatErrorToPlayer(msg.who, "Trying to shapeshift on a token you don't have control over");
}
}
else {
UTILS.chatErrorToPlayer(msg.who, "Cannot find ShapeShifter for the selected token");
}
return;
}
else
{
let cmd = args.shift();
if (cmd == WS_API.CMD.SHIFT)
{
handleInputShift(msg, args, config);
}
else if (playerIsGM(msg.playerid))
{
// GM ONLY COMMANDS
switch (cmd)
{
case WS_API.CMD.SHOW_SHIFTERS:
{
MENU.showShifters();
}
break;
case WS_API.CMD.CONFIG:
{
switch (args.shift())
{
case WS_API.CMD.ADD:
{
switch (args.shift())
{
case WS_API.FIELDS.TARGET.SHIFTER: handleInputAddShifter(msg, args, config); break;
case WS_API.FIELDS.TARGET.SHAPE: handleInputAddShape(msg, args, config); break;
}
}
break;
case WS_API.CMD.REMOVE:
{
if (args.shift() == 'no')
return;
switch (args.shift())
{
case WS_API.FIELDS.TARGET.SHIFTER: handleInputRemoveShifter(msg, args, config); break;
case WS_API.FIELDS.TARGET.SHAPE: handleInputRemoveShape(msg, args, config); break;
}
}
break;
case WS_API.CMD.EDIT:
{
switch (args.shift())
{
case WS_API.FIELDS.TARGET.SHIFTER: handleInputEditShifter(msg, args, config); break;
case WS_API.FIELDS.TARGET.SHAPE: handleInputEditShape(msg, args, config); break;
case WS_API.FIELDS.TARGET.CONFIG: handleInputEditConfig(msg, args, config); break;
}
}
break;
case WS_API.CMD.RESET:
{
if (args.shift() == 'no')
return;
setDefaults(true);
}
break;
case WS_API.CMD.IMPORT:
{
switch (args.shift())
{
case WS_API.FIELDS.TARGET.SHAPEFOLDER: handleInputImportShapeFolder(msg, args, config); break;
}
}
break;
default: MENU.showConfigMenu();
}
}
break;
case WS_API.CMD.HELP:
{
UTILS.chat(WS_API.CMD.USAGE);
}
break;
}
}
}
}
};
const handleAddToken = (token) =>
{
let obj = findShifterData(token, true);
if(obj)
{
let shifterSettings = obj.shifter[WS_API.FIELDS.SETTINGS];
obj.isGM = true;
obj.ignoreDruidResource = true;
obj.who = "gm";
obj.targetShapeName = shifterSettings[WS_API.FIELDS.CURRENT_SHAPE];
if (obj.targetShapeName != WS_API.SETTINGS.BASE_SHAPE)
{
obj.targetShape = obj.shifter[WS_API.FIELDS.SHAPES][obj.targetShapeName];
if (!obj.targetShape)
{
UTILS.chatError("Cannot find shape [" + obj.targetShapeName + "] for ShapeShifter: " + obj.shifterId);
return;
}
doShapeShift(obj).then((ret) => {
if (ret)
{
UTILS.chat("Dropping shifter token, transforming " + obj.shifterId + " into " + obj.targetShapeName);
}
else
{
UTILS.chatError("Dropping shifter token, cannot transform " + obj.shifterId + " into " + obj.targetShapeName);
}
});
}
}
};
const upgradeVersion = () => {
const apiState = state[WS_API.STATENAME];
const currentVersion = apiState[WS_API.DATA_CONFIG].VERSION;
const newConfig = WS_API.DEFAULT_CONFIG;
let config = apiState[WS_API.DATA_CONFIG];
let shifters = apiState[WS_API.DATA_SHIFTERS];
if (UTILS.compareVersion(currentVersion, "1.0.2") < 0)
{
const npcFields = WS_API.FIELDS.NPC_DATA;
config[npcFields.ROOT] = {};
config[npcFields.ROOT][npcFields.HP_CACHE] = newConfig[npcFields.ROOT][npcFields.HP_CACHE];
config[npcFields.ROOT][npcFields.HP] = newConfig[npcFields.ROOT][npcFields.HP];
config[npcFields.ROOT][npcFields.AC] = newConfig[npcFields.ROOT][npcFields.AC];
config[npcFields.ROOT][npcFields.SPEED] = newConfig[npcFields.ROOT][npcFields.SPEED];
const pcFields = WS_API.FIELDS.PC_DATA;
config[pcFields.ROOT] = {};
config[pcFields.ROOT][pcFields.HP] = newConfig[pcFields.ROOT][pcFields.HP];
config[pcFields.ROOT][pcFields.AC] = newConfig[pcFields.ROOT][pcFields.AC];
config[pcFields.ROOT][pcFields.SPEED] = newConfig[pcFields.ROOT][pcFields.SPEED];
}
if (UTILS.compareVersion(currentVersion, "1.0.4") < 0)
{
// add MAKEROLLPUBLIC field to shifters, default to true for non-npcs
_.each(shifters, (value, shifterId) => {
let shifterSettings = shifters[shifterId][WS_API.FIELDS.SETTINGS];
shifterSettings[WS_API.FIELDS.MAKEROLLPUBLIC] = !shifterSettings[WS_API.FIELDS.ISNPC];
});
}
if (UTILS.compareVersion(currentVersion, "1.0.5") < 0)
{
// updated separator to minimize collisions with names/strings
if(config.SEP == "--")
config.SEP = newConfig.SEP;
}
if (UTILS.compareVersion(currentVersion, "1.0.6") < 0)
{
// copy defaults in config
copySenses(newConfig, config);
_.each(shifters, (value, shifterId) => {
let shifterSettings = shifters[shifterId][WS_API.FIELDS.SETTINGS];
// copy defaults in all shifters
copySenses(newConfig, shifterSettings);
shifterSettings[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE] = false;
_.each(shifters[shifterId][WS_API.FIELDS.SHAPES], (shapeValue, shapeId) => {
// copy defaults in all shapes
copySenses(newConfig, shapeValue);
shapeValue[WS_API.FIELDS.SENSES.ROOT][WS_API.FIELDS.SENSES.OVERRIDE] = false;
});
});
}
if (UTILS.compareVersion(currentVersion, "1.0.7") < 0)
{
config[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.SENSES] = newConfig[WS_API.FIELDS.NPC_DATA.ROOT][WS_API.FIELDS.NPC_DATA.SENSES];
}
if (UTILS.compareVersion(currentVersion, "1.2") < 0)
{
// cache stats for all shapes
_.each(shifters, (shifterValue, shifterId) => {
_.each(shifters[shifterId][WS_API.FIELDS.SHAPES], (shapeValue, shapeId) => {
cacheCharacterData(shapeValue);
});
});
}
config.VERSION = WS_API.VERSION;
};
async function setDefaults(reset)
{
let oldVersionDetected = null;
let apiState = state[WS_API.STATENAME];
if(!apiState || typeof apiState !== 'object' || reset)
{
if(state[WS_API.STATENAME])
{
_.each(state[WS_API.STATENAME][WS_API.DATA_SHIFTERS],
(shifter) => {
_.each(shifter[WS_API.FIELDS.SHAPES], (shape) => {
removeShape(shape);
});
});
}
state[WS_API.STATENAME] = {};
apiState = state[WS_API.STATENAME];
reset = true;
}
if (!apiState[WS_API.DATA_CONFIG] || typeof apiState[WS_API.DATA_CONFIG] !== 'object' || reset)
{
apiState[WS_API.DATA_CONFIG] = WS_API.DEFAULT_CONFIG;
apiState[WS_API.DATA_CONFIG].VERSION = WS_API.VERSION;
reset = true;
}
else if (UTILS.compareVersion(apiState[WS_API.DATA_CONFIG].VERSION, WS_API.VERSION) < 0)
{
oldVersionDetected = apiState[WS_API.DATA_CONFIG].VERSION;
upgradeVersion();
}
if (!apiState[WS_API.DATA_SHIFTERS] || typeof apiState[WS_API.DATA_SHIFTERS] !== 'object' || reset)
{
apiState[WS_API.DATA_SHIFTERS] = {};
}
MENU.updateConfig();
if (reset || oldVersionDetected)
{
MENU.showConfigMenu(true);
if (oldVersionDetected)
{
_.each(WS_API.CHANGELOG, function (changes, version)
{
if (UTILS.compareVersion(oldVersionDetected, version) < 0)
UTILS.chat("Updated to " + version + ": " + changes);
});
UTILS.chat("New version detected, updated from " + oldVersionDetected + " to " + WS_API.VERSION);
}
}
}
async function start()
{
// check install
if (!UTILS.VERSION || UTILS.compareVersion(UTILS.VERSION, WS_API.REQUIRED_HELPER_VERSION) < 0)
{
UTILS.chatError("This API version " + WS_API.VERSION + " requires WildUtils version " + WS_API.REQUIRED_HELPER_VERSION + ", please update your WildHelpers script");
return;
}
await setDefaults();
// register event handlers
on('chat:message', handleInput);
on('add:token', function (t) {
_.delay(() => {
handleAddToken(t);
}, 100);
});
log(WS_API.NAME + ' v' + WS_API.VERSION + " Ready! WildUtils v" + UTILS.VERSION);
UTILS.chat("API v" + WS_API.VERSION + " Ready! command: " + WS_API.CMD.ROOT);
}
return {
start
};
})();
on('ready', () => {
'use strict';
WildShape.start();
});
|
var session = require('./session');
var rest = require('./rest');
var useragent = require('./useragent');
var livedb = require('livedb');
if (!require('semver').gte(process.versions.node, '0.10.0')) {
throw new Error('ShareJS requires node 0.10 or above.');
}
/** This encapsulates the sharejs server state & exposes a few useful methods.
*
* @constructor
*/
var ShareInstance = function(options) {
this.options = options;
this.preValidate = options.preValidate;
this.validate = options.validate;
if (options.backend) {
this.backend = options.backend;
} else if (options.db) {
this.backend = livedb.client(options.db);
} else {
throw Error("Both options.backend and options.db are missing. Can't function without a database!");
}
if (!this.backend.bulkSubscribe)
throw Error("You're using an old version of livedb. Please update livedb or downgrade ShareJS");
// Map from event name (or '') to a list of middleware.
this.extensions = {'':[]};
this.docFilters = [];
this.opFilters = [];
};
/** A client has connected through the specified stream. Listen for messages.
* Returns the useragent associated with the connected session.
*
* The optional second argument (req) is an initial request which is passed
* through to any connect() middleware. This is useful for inspecting cookies
* or an express session or whatever on the request object in your middleware.
*
* (The useragent is available through all middleware)
*/
ShareInstance.prototype.listen = function(stream, req) {
return session(this, stream, req).agent;
};
// Create and return REST middleware to access the documents
ShareInstance.prototype.rest = function() {
return rest(this);
};
/** Add middleware to an action. The action is optional (if not specified, the
* middleware fires on every action).
*/
ShareInstance.prototype.use = function(action, middleware) {
if (typeof action !== 'string') {
middleware = action;
action = '';
}
if (action === 'getOps') {
throw new Error("The 'getOps' middleware action has been renamed to 'get ops'. Update your code.");
}
var extensions = this.extensions[action];
if (!extensions) extensions = this.extensions[action] = [];
extensions.push(middleware);
};
/** Add a function to filter all data going to the current client */
ShareInstance.prototype.filter = function(fn) {
this.docFilters.push(fn);
};
ShareInstance.prototype.filterOps = function(fn) {
this.opFilters.push(fn);
};
ShareInstance.prototype.createAgent = function(stream) {
return useragent(this, stream);
};
// Return truthy if the instance has registered middleware. Used for bulkSubscribe.
ShareInstance.prototype._hasMiddleware = function(action) {
return this.extensions[action];
};
// Helper method to actually trigger the extension methods
ShareInstance.prototype._trigger = function(request, callback) {
// Copying the triggers we'll fire so they don't get edited while we iterate.
var middlewares = (this.extensions[request.action] || []).concat(this.extensions['']);
var next = function() {
if (!middlewares.length)
return callback ? callback(null, request) : undefined;
var middleware = middlewares.shift();
middleware(request, function(err) {
if (err) return callback ? callback(err) : undefined;
next();
});
};
next();
};
exports.createClient = function(options) {
return new ShareInstance(options);
};
|
require('require-dir')('build/tasks')
|
var bar = {x: true};
var foo = bar;
reassignFooX();
var baz = {x: true};
var foo = baz;
reassignFooX();
function reassignFooX() {
foo.x = false;
}
if (bar.x) assert.fail('bar was not reassigned');
if (baz.x) assert.fail('baz was not reassigned');
|
// flow-typed signature: 89f8074b9679446826e4641701539150
// flow-typed version: <<STUB>>/aphrodite_v1/flow_v0.68.0
/**
* This is an autogenerated libdef stub for:
*
* 'aphrodite'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module "aphrodite" {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module "aphrodite/coverage/prettify" {
declare module.exports: any;
}
declare module "aphrodite/coverage/sorter" {
declare module.exports: any;
}
declare module "aphrodite/dist/aphrodite" {
declare module.exports: any;
}
declare module "aphrodite/dist/aphrodite.umd" {
declare module.exports: any;
}
declare module "aphrodite/dist/aphrodite.umd.min" {
declare module.exports: any;
}
declare module "aphrodite/examples/runkit" {
declare module.exports: any;
}
declare module "aphrodite/examples/server" {
declare module.exports: any;
}
declare module "aphrodite/examples/src/examples-ssr" {
declare module.exports: any;
}
declare module "aphrodite/examples/src/examples" {
declare module.exports: any;
}
declare module "aphrodite/examples/src/StyleTester" {
declare module.exports: any;
}
declare module "aphrodite/examples/webpack.config" {
declare module.exports: any;
}
declare module "aphrodite/lib/exports" {
declare module.exports: any;
}
declare module "aphrodite/lib/generate" {
declare module.exports: any;
}
declare module "aphrodite/lib/index" {
declare module.exports: any;
}
declare module "aphrodite/lib/inject" {
declare module.exports: any;
}
declare module "aphrodite/lib/no-important" {
declare module.exports: any;
}
declare module "aphrodite/lib/ordered-elements" {
declare module.exports: any;
}
declare module "aphrodite/lib/staticPrefixData" {
declare module.exports: any;
}
declare module "aphrodite/lib/util" {
declare module.exports: any;
}
declare module "aphrodite/no-important" {
declare module.exports: any;
}
declare module "aphrodite/src/exports" {
declare module.exports: any;
}
declare module "aphrodite/src/generate" {
declare module.exports: any;
}
declare module "aphrodite/src/index" {
declare module.exports: any;
}
declare module "aphrodite/src/inject" {
declare module.exports: any;
}
declare module "aphrodite/src/no-important" {
declare module.exports: any;
}
declare module "aphrodite/src/ordered-elements" {
declare module.exports: any;
}
declare module "aphrodite/src/util" {
declare module.exports: any;
}
declare module "aphrodite/tests/generate_test" {
declare module.exports: any;
}
declare module "aphrodite/tests/index_test" {
declare module.exports: any;
}
declare module "aphrodite/tests/inject_test" {
declare module.exports: any;
}
declare module "aphrodite/tests/no-important_test" {
declare module.exports: any;
}
declare module "aphrodite/tests/ordered-elements_test" {
declare module.exports: any;
}
declare module "aphrodite/tests/util_test" {
declare module.exports: any;
}
declare module "aphrodite/tools/generate_prefixer_data" {
declare module.exports: any;
}
declare module "aphrodite/webpack.config" {
declare module.exports: any;
}
// Filename aliases
declare module "aphrodite/coverage/prettify.js" {
declare module.exports: $Exports<"aphrodite/coverage/prettify">;
}
declare module "aphrodite/coverage/sorter.js" {
declare module.exports: $Exports<"aphrodite/coverage/sorter">;
}
declare module "aphrodite/dist/aphrodite.js" {
declare module.exports: $Exports<"aphrodite/dist/aphrodite">;
}
declare module "aphrodite/dist/aphrodite.umd.js" {
declare module.exports: $Exports<"aphrodite/dist/aphrodite.umd">;
}
declare module "aphrodite/dist/aphrodite.umd.min.js" {
declare module.exports: $Exports<"aphrodite/dist/aphrodite.umd.min">;
}
declare module "aphrodite/examples/runkit.js" {
declare module.exports: $Exports<"aphrodite/examples/runkit">;
}
declare module "aphrodite/examples/server.js" {
declare module.exports: $Exports<"aphrodite/examples/server">;
}
declare module "aphrodite/examples/src/examples-ssr.js" {
declare module.exports: $Exports<"aphrodite/examples/src/examples-ssr">;
}
declare module "aphrodite/examples/src/examples.js" {
declare module.exports: $Exports<"aphrodite/examples/src/examples">;
}
declare module "aphrodite/examples/src/StyleTester.js" {
declare module.exports: $Exports<"aphrodite/examples/src/StyleTester">;
}
declare module "aphrodite/examples/webpack.config.js" {
declare module.exports: $Exports<"aphrodite/examples/webpack.config">;
}
declare module "aphrodite/lib/exports.js" {
declare module.exports: $Exports<"aphrodite/lib/exports">;
}
declare module "aphrodite/lib/generate.js" {
declare module.exports: $Exports<"aphrodite/lib/generate">;
}
declare module "aphrodite/lib/index.js" {
declare module.exports: $Exports<"aphrodite/lib/index">;
}
declare module "aphrodite/lib/inject.js" {
declare module.exports: $Exports<"aphrodite/lib/inject">;
}
declare module "aphrodite/lib/no-important.js" {
declare module.exports: $Exports<"aphrodite/lib/no-important">;
}
declare module "aphrodite/lib/ordered-elements.js" {
declare module.exports: $Exports<"aphrodite/lib/ordered-elements">;
}
declare module "aphrodite/lib/staticPrefixData.js" {
declare module.exports: $Exports<"aphrodite/lib/staticPrefixData">;
}
declare module "aphrodite/lib/util.js" {
declare module.exports: $Exports<"aphrodite/lib/util">;
}
declare module "aphrodite/no-important.js" {
declare module.exports: $Exports<"aphrodite/no-important">;
}
declare module "aphrodite/src/exports.js" {
declare module.exports: $Exports<"aphrodite/src/exports">;
}
declare module "aphrodite/src/generate.js" {
declare module.exports: $Exports<"aphrodite/src/generate">;
}
declare module "aphrodite/src/index.js" {
declare module.exports: $Exports<"aphrodite/src/index">;
}
declare module "aphrodite/src/inject.js" {
declare module.exports: $Exports<"aphrodite/src/inject">;
}
declare module "aphrodite/src/no-important.js" {
declare module.exports: $Exports<"aphrodite/src/no-important">;
}
declare module "aphrodite/src/ordered-elements.js" {
declare module.exports: $Exports<"aphrodite/src/ordered-elements">;
}
declare module "aphrodite/src/util.js" {
declare module.exports: $Exports<"aphrodite/src/util">;
}
declare module "aphrodite/tests/generate_test.js" {
declare module.exports: $Exports<"aphrodite/tests/generate_test">;
}
declare module "aphrodite/tests/index_test.js" {
declare module.exports: $Exports<"aphrodite/tests/index_test">;
}
declare module "aphrodite/tests/inject_test.js" {
declare module.exports: $Exports<"aphrodite/tests/inject_test">;
}
declare module "aphrodite/tests/no-important_test.js" {
declare module.exports: $Exports<"aphrodite/tests/no-important_test">;
}
declare module "aphrodite/tests/ordered-elements_test.js" {
declare module.exports: $Exports<"aphrodite/tests/ordered-elements_test">;
}
declare module "aphrodite/tests/util_test.js" {
declare module.exports: $Exports<"aphrodite/tests/util_test">;
}
declare module "aphrodite/tools/generate_prefixer_data.js" {
declare module.exports: $Exports<"aphrodite/tools/generate_prefixer_data">;
}
declare module "aphrodite/webpack.config.js" {
declare module.exports: $Exports<"aphrodite/webpack.config">;
}
|
module.exports = function(error, request, response) {
if(typeof error === 'string') {
error = { message: error, errors: [] };
}
//setup an error response
response.message = JSON.stringify({
error: true,
message: error.message,
validation: error.errors || [] });
//trigger that a response has been made
this.trigger('file-response', request, response);
}; |
import React from 'react';
import SigmetsContainer from './SigmetsContainer';
import { mount } from 'enzyme';
import moxios from 'moxios';
describe('(Container) Sigmet/SigmetsContainer', () => {
beforeEach(() => {
moxios.install();
});
afterEach(() => {
moxios.uninstall();
});
it('renders a SigmetsContainer', (done) => {
const drawProperties = {
adagucMapDraw: {
geojson: {
features: []
}
}
};
const urls = {
BACKEND_SERVER_URL: 'http://localhost'
};
const _component = mount(<SigmetsContainer drawProperties={drawProperties} urls={urls} />);
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: null
}).then(() => {
expect(_component.type()).to.eql(SigmetsContainer);
done();
}).catch(done);
});
});
});
|
/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, regexp: true */
/*global define, brackets, $ */
define(function (require, exports, module) {
"use strict";
var StringMatch = brackets.getModule("utils/StringMatch"),
LanguageManager = brackets.getModule("language/LanguageManager"),
HTMLUtils = brackets.getModule("language/HTMLUtils"),
TokenUtils = brackets.getModule("utils/TokenUtils"),
HintUtils = require("HintUtils"),
ScopeManager = require("ScopeManager"),
Acorn = require("thirdparty/acorn/acorn"),
Acorn_Loose = require("thirdparty/acorn/acorn_loose");
/**
* Session objects encapsulate state associated with a hinting session
* and provide methods for updating and querying the session.
*
* @constructor
* @param {Editor} editor - the editor context for the session
*/
function Session(editor) {
this.editor = editor;
this.path = editor.document.file.fullPath;
this.ternHints = [];
this.ternGuesses = null;
this.fnType = null;
this.builtins = null;
}
/**
* Get the builtin libraries tern is using.
*
* @return {Array.<string>} - array of library names.
* @private
*/
Session.prototype._getBuiltins = function () {
if (!this.builtins) {
this.builtins = ScopeManager.getBuiltins();
this.builtins.push("requirejs.js"); // consider these globals as well.
}
return this.builtins;
};
/**
* Get the name of the file associated with the current session
*
* @return {string} - the full pathname of the file associated with the
* current session
*/
Session.prototype.getPath = function () {
return this.path;
};
/**
* Get the current cursor position.
*
* @return {{line: number, ch: number}} - the current cursor position
*/
Session.prototype.getCursor = function () {
return this.editor.getCursorPos();
};
/**
* Get the text of a line.
*
* @param {number} line - the line number
* @return {string} - the text of the line
*/
Session.prototype.getLine = function (line) {
var doc = this.editor.document;
return doc.getLine(line);
};
/**
* Get the offset of the current cursor position
*
* @return {number} - the offset into the current document of the current
* cursor
*/
Session.prototype.getOffset = function () {
var cursor = this.getCursor();
return this.getOffsetFromCursor(cursor);
};
/**
* Get the offset of a cursor position
*
* @param {{line: number, ch: number}} the line/col info
* @return {number} - the offset into the current document of the cursor
*/
Session.prototype.getOffsetFromCursor = function (cursor) {
return this.editor.indexFromPos(cursor);
};
/**
* Get the token at the given cursor position, or at the current cursor
* if none is given.
*
* @param {?{line: number, ch: number}} cursor - the cursor position
* at which to retrieve a token
* @return {Object} - the CodeMirror token at the given cursor position
*/
Session.prototype.getToken = function (cursor) {
var cm = this.editor._codeMirror;
if (cursor) {
return cm.getTokenAt(cursor, true);
} else {
return cm.getTokenAt(this.getCursor(), true);
}
};
/**
* Get the token after the one at the given cursor position
*
* @param {{line: number, ch: number}} cursor - cursor position before
* which a token should be retrieved
* @return {Object} - the CodeMirror token after the one at the given
* cursor position
*/
Session.prototype.getNextTokenOnLine = function (cursor) {
cursor = this.getNextCursorOnLine(cursor);
if (cursor) {
return this.getToken(cursor);
}
return null;
};
/**
* Get the next cursor position on the line, or null if there isn't one.
*
* @return {?{line: number, ch: number}} - the cursor position
* immediately following the current cursor position, or null if
* none exists.
*/
Session.prototype.getNextCursorOnLine = function (cursor) {
var doc = this.editor.document,
line = doc.getLine(cursor.line);
if (cursor.ch < line.length) {
return {
ch : cursor.ch + 1,
line: cursor.line
};
} else {
return null;
}
};
/**
* Get the token before the one at the given cursor position
*
* @param {{line: number, ch: number}} cursor - cursor position after
* which a token should be retrieved
* @return {Object} - the CodeMirror token before the one at the given
* cursor position
*/
Session.prototype._getPreviousToken = function (cursor) {
var token = this.getToken(cursor),
prev = token,
doc = this.editor.document;
do {
if (prev.start < cursor.ch) {
cursor.ch = prev.start;
} else if (prev.start > 0) {
cursor.ch = prev.start - 1;
} else if (cursor.line > 0) {
cursor.ch = doc.getLine(cursor.line - 1).length;
cursor.line--;
} else {
break;
}
prev = this.getToken(cursor);
} while (prev.string.trim() === "");
return prev;
};
/**
* Get the token after the one at the given cursor position
*
* @param {{line: number, ch: number}} cursor - cursor position after
* which a token should be retrieved
* @param {boolean} skipWhitespace - true if this should skip over whitespace tokens
* @return {Object} - the CodeMirror token after the one at the given
* cursor position
*/
Session.prototype.getNextToken = function (cursor, skipWhitespace) {
var token = this.getToken(cursor),
next = token,
doc = this.editor.document;
do {
if (next.end > cursor.ch) {
cursor.ch = next.end;
} else if (next.end < doc.getLine(cursor.line).length) {
cursor.ch = next.end + 1;
} else if (doc.getLine(cursor.line + 1)) {
cursor.ch = 0;
cursor.line++;
} else {
next = null;
break;
}
next = this.getToken(cursor);
} while (skipWhitespace && next.string.trim() === "");
return next;
};
/**
* Calculate a query string relative to the current cursor position
* and token. E.g., from a state "identi<cursor>er", the query string is
* "identi".
*
* @return {string} - the query string for the current cursor position
*/
Session.prototype.getQuery = function () {
var cursor = this.getCursor(),
token = this.getToken(cursor),
query = "",
start = cursor.ch,
end = start;
if (token) {
var line = this.getLine(cursor.line);
while (start > 0) {
if (HintUtils.maybeIdentifier(line[start - 1])) {
start--;
} else {
break;
}
}
query = line.substring(start, end);
}
return query;
};
/**
* Find the context of a property lookup. For example, for a lookup
* foo(bar, baz(quux)).prop, foo is the context.
*
* @param {{line: number, ch: number}} cursor - the cursor position
* at which context information is to be retrieved
* @param {number=} depth - the current depth of the parenthesis stack, or
* undefined if the depth is 0.
* @return {string} - the context for the property that was looked up
*/
Session.prototype.getContext = function (cursor, depth) {
var token = this.getToken(cursor);
if (depth === undefined) {
depth = 0;
}
if (token.string === ")") {
this._getPreviousToken(cursor);
return this.getContext(cursor, ++depth);
} else if (token.string === "(") {
this._getPreviousToken(cursor);
return this.getContext(cursor, --depth);
} else {
if (depth > 0 || token.string === ".") {
this._getPreviousToken(cursor);
return this.getContext(cursor, depth);
} else {
return token.string;
}
}
};
/**
* @return {{line:number, ch:number}} - the line, col info for where the previous "."
* in a property lookup occurred, or undefined if no previous "." was found.
*/
Session.prototype.findPreviousDot = function () {
var cursor = this.getCursor(),
token = this.getToken(cursor);
// If the cursor is right after the dot, then the current token will be "."
if (token && token.string === ".") {
return cursor;
} else {
// If something has been typed like 'foo.b' then we have to look back 2 tokens
// to get past the 'b' token
token = this._getPreviousToken(cursor);
if (token && token.string === ".") {
return cursor;
}
}
return undefined;
};
/**
*
* @param {Object} token - a CodeMirror token
* @return {*} - the lexical state of the token
*/
function getLexicalState(token) {
if (token.state.lexical) {
// in a javascript file this is just in the state field
return token.state.lexical;
} else if (token.state.localState && token.state.localState.lexical) {
// inline javascript in an html file will have this in
// the localState field
return token.state.localState.lexical;
}
}
/**
* Determine if the caret is either within a function call or on the function call itself.
*
* @return {{inFunctionCall: boolean, functionCallPos: {line: number, ch: number}}}
* inFunctionCall - true if the caret if either within a function call or on the
* function call itself.
* functionCallPos - the offset of the '(' character of the function call if inFunctionCall
* is true, otherwise undefined.
*/
Session.prototype.getFunctionInfo = function () {
var inFunctionCall = false,
cursor = this.getCursor(),
functionCallPos,
token = this.getToken(cursor),
lexical,
self = this,
foundCall = false;
/**
* Test if the cursor is on a function identifier
*
* @return {Object} - lexical state if on a function identifier, null otherwise.
*/
function isOnFunctionIdentifier() {
// Check if we might be on function identifier of the function call.
var type = token.type,
nextToken,
localLexical,
localCursor = {line: cursor.line, ch: token.end};
if (type === "variable-2" || type === "variable" || type === "property") {
nextToken = self.getNextToken(localCursor, true);
if (nextToken && nextToken.string === "(") {
localLexical = getLexicalState(nextToken);
return localLexical;
}
}
return null;
}
/**
* Test is a lexical state is in a function call.
*
* @param {Object} lex - lexical state.
* @return {Object | boolean}
*
*/
function isInFunctionalCall(lex) {
// in a call, or inside array or object brackets that are inside a function.
return (lex && (lex.info === "call" ||
(lex.info === undefined && (lex.type === "]" || lex.type === "}") &&
lex.prev.info === "call")));
}
if (token) {
// if this token is part of a function call, then the tokens lexical info
// will be annotated with "call".
// If the cursor is inside an array, "[]", or object, "{}", the lexical state
// will be undefined, not "call". lexical.prev will be the function state.
// Handle this case and then set "lexical" to lexical.prev.
// Also test if the cursor is on a function identifier of a function call.
lexical = getLexicalState(token);
foundCall = isInFunctionalCall(lexical);
if (!foundCall) {
lexical = isOnFunctionIdentifier();
foundCall = isInFunctionalCall(lexical);
}
if (foundCall) {
// we need to find the location of the called function so that we can request the functions type.
// the token's lexical info will contain the column where the open "(" for the
// function call occurs, but for whatever reason it does not have the line, so
// we have to walk back and try to find the correct location. We do this by walking
// up the lines starting with the line the token is on, and seeing if any of the lines
// have "(" at the column indicated by the tokens lexical state.
// We walk back 9 lines, as that should be far enough to find most function calls,
// and it will prevent us from walking back thousands of lines if something went wrong.
// there is nothing magical about 9 lines, and it can be adjusted if it doesn't seem to be
// working well
if (lexical.info === undefined) {
lexical = lexical.prev;
}
var col = lexical.info === "call" ? lexical.column : lexical.prev.column,
line,
e,
found;
for (line = this.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) {
if (this.getLine(line).charAt(col) === "(") {
found = true;
break;
}
}
if (found) {
inFunctionCall = true;
functionCallPos = {line: line, ch: col};
}
}
}
return {
inFunctionCall: inFunctionCall,
functionCallPos: functionCallPos
};
};
/**
* Get the type of the current session, i.e., whether it is a property
* lookup and, if so, what the context of the lookup is.
*
* @return {{property: boolean,
context: string} - an Object consisting
* of a {boolean} "property" that indicates whether or not the type of
* the session is a property lookup, and a {string} "context" that
* indicates the object context (as described in getContext above) of
* the property lookup, or null if there is none. The context is
* always null for non-property lookups.
*/
Session.prototype.getType = function () {
var propertyLookup = false,
context = null,
cursor = this.getCursor(),
token = this.getToken(cursor),
lexical;
if (token) {
// if this token is part of a function call, then the tokens lexical info
// will be annotated with "call"
lexical = getLexicalState(token);
if (token.type === "property") {
propertyLookup = true;
}
cursor = this.findPreviousDot();
if (cursor) {
propertyLookup = true;
context = this.getContext(cursor);
}
}
return {
property: propertyLookup,
context: context
};
};
// Comparison function used for sorting that does a case-insensitive string
// comparison on the "value" field of both objects. Unlike a normal string
// comparison, however, this sorts leading "_" to the bottom, given that a
// leading "_" usually denotes a private value.
function penalizeUnderscoreValueCompare(a, b) {
var aName = a.value.toLowerCase(), bName = b.value.toLowerCase();
// this sort function will cause _ to sort lower than lower case
// alphabetical letters
if (aName[0] === "_" && bName[0] !== "_") {
return 1;
} else if (bName[0] === "_" && aName[0] !== "_") {
return -1;
}
if (aName < bName) {
return -1;
} else if (aName > bName) {
return 1;
}
return 0;
}
/**
* Get a list of hints for the current session using the current scope
* information.
*
* @param {string} query - the query prefix
* @param {StringMatcher} matcher - the class to find query matches and sort the results
* @return {hints: Array.<string>, needGuesses: boolean} - array of
* matching hints. If needGuesses is true, then the caller needs to
* request guesses and call getHints again.
*/
Session.prototype.getHints = function (query, matcher) {
if (query === undefined) {
query = "";
}
var MAX_DISPLAYED_HINTS = 500,
type = this.getType(),
builtins = this._getBuiltins(),
needGuesses = false,
hints;
/**
* Is the origin one of the builtin files.
*
* @param {string} origin
*/
function isBuiltin(origin) {
return builtins.indexOf(origin) !== -1;
}
/**
* Filter an array hints using a given query and matcher.
* The hints are returned in the format of the matcher.
* The matcher returns the value in the "label" property,
* the match score in "matchGoodness" property.
*
* @param {Array} hints - array of hints
* @param {StringMatcher} matcher
* @returns {Array} - array of matching hints.
*/
function filterWithQueryAndMatcher(hints, matcher) {
var matchResults = $.map(hints, function (hint) {
var searchResult = matcher.match(hint.value, query);
if (searchResult) {
searchResult.value = hint.value;
searchResult.guess = hint.guess;
searchResult.type = hint.type;
if (hint.keyword !== undefined) {
searchResult.keyword = hint.keyword;
}
if (hint.literal !== undefined) {
searchResult.literal = hint.literal;
}
if (hint.depth !== undefined) {
searchResult.depth = hint.depth;
}
if (!type.property && !type.showFunctionType && hint.origin &&
isBuiltin(hint.origin)) {
searchResult.builtin = 1;
} else {
searchResult.builtin = 0;
}
}
return searchResult;
});
return matchResults;
}
if (type.property) {
hints = this.ternHints || [];
hints = filterWithQueryAndMatcher(hints, matcher);
// If there are no hints then switch over to guesses.
if (hints.length === 0) {
if (this.ternGuesses) {
hints = filterWithQueryAndMatcher(this.ternGuesses, matcher);
} else {
needGuesses = true;
}
}
StringMatch.multiFieldSort(hints, [ "matchGoodness", penalizeUnderscoreValueCompare ]);
} else { // identifiers, literals, and keywords
hints = this.ternHints || [];
hints = hints.concat(HintUtils.LITERALS);
hints = hints.concat(HintUtils.KEYWORDS);
hints = filterWithQueryAndMatcher(hints, matcher);
StringMatch.multiFieldSort(hints, [ "matchGoodness", "depth", "builtin", penalizeUnderscoreValueCompare ]);
}
if (hints.length > MAX_DISPLAYED_HINTS) {
hints = hints.slice(0, MAX_DISPLAYED_HINTS);
}
return {hints: hints, needGuesses: needGuesses};
};
Session.prototype.setTernHints = function (newHints) {
this.ternHints = newHints;
};
Session.prototype.setGuesses = function (newGuesses) {
this.ternGuesses = newGuesses;
};
/**
* Set a new function type hint.
*
* @param {Array<{name: string, type: string, isOptional: boolean}>} newFnType -
* Array of function hints.
*/
Session.prototype.setFnType = function (newFnType) {
this.fnType = newFnType;
};
/**
* The position of the function call for the current fnType.
*
* @param {{line:number, ch:number}} functionCallPos - the offset of the function call.
*/
Session.prototype.setFunctionCallPos = function (functionCallPos) {
this.functionCallPos = functionCallPos;
};
/**
* Get the function type hint. This will format the hint, showing the
* parameter at the cursor in bold.
*
* @return {{parameters: Array<{name: string, type: string, isOptional: boolean}>,
* currentIndex: number}} An Object where the
* "parameters" property is an array of parameter objects;
* the "currentIndex" property index of the hint the cursor is on, may be
* -1 if the cursor is on the function identifier.
*/
Session.prototype.getParameterHint = function () {
var fnHint = this.fnType,
cursor = this.getCursor(),
token = this.getToken(this.functionCallPos),
start = {line: this.functionCallPos.line, ch: token.start},
fragment = this.editor.document.getRange(start,
{line: this.functionCallPos.line + 10, ch: 0});
var ast;
try {
ast = Acorn.parse(fragment);
} catch (e) { ast = Acorn_Loose.parse_dammit(fragment); }
// find argument as cursor location and bold it.
var startOffset = this.getOffsetFromCursor(start),
cursorOffset = this.getOffsetFromCursor(cursor),
offset = cursorOffset - startOffset,
node = ast.body[0],
currentArg = -1;
if (node.type === "ExpressionStatement") {
node = node.expression;
if (node.type === "SequenceExpression") {
node = node.expressions[0];
}
if (node.type === "BinaryExpression") {
if (node.left.type === "CallExpression") {
node = node.left;
} else if (node.right.type === "CallExpression") {
node = node.right;
}
}
if (node.type === "CallExpression") {
var args = node["arguments"],
i,
n = args.length,
lastEnd = offset,
text;
for (i = 0; i < n; i++) {
node = args[i];
if (offset >= node.start && offset <= node.end) {
currentArg = i;
break;
} else if (offset < node.start) {
// The range of nodes can be disjoint so see i f we
// passed the node. If we passed the node look at the
// text between the nodes to figure out which
// arg we are on.
text = fragment.substring(lastEnd, node.start);
// test if comma is before or after the offset
if (text.indexOf(",") >= (offset - lastEnd)) {
// comma is after the offset so the current arg is the
// previous arg node.
i--;
} else if (i === 0 && text.indexOf("(") !== -1) {
// the cursor is on the function identifier
currentArg = -1;
break;
}
currentArg = Math.max(0, i);
break;
} else if (i + 1 === n) {
// look for a comma after the node.end. This will tell us we
// are on the next argument, even there is no text, and therefore no node,
// for the next argument.
text = fragment.substring(node.end, offset);
if (text.indexOf(",") !== -1) {
currentArg = i + 1; // we know we are after the current arg, but keep looking
}
}
lastEnd = node.end;
}
// if there are no args, then figure out if we are on the function identifier
if (n === 0 && cursorOffset > this.getOffsetFromCursor(this.functionCallPos)) {
currentArg = 0;
}
}
}
return {parameters: fnHint, currentIndex: currentArg};
};
/**
* Get the javascript text of the file open in the editor for this Session.
* For a javascript file, this is just the text of the file. For an HTML file,
* this will be only the text in the <script> tags. This is so that we can pass
* just the javascript text to tern, and avoid confusing it with HTML tags, since it
* only knows how to parse javascript.
* @return {string} - the "javascript" text that can be sent to Tern.
*/
Session.prototype.getJavascriptText = function () {
if (LanguageManager.getLanguageForPath(this.editor.document.file.fullPath).getId() === "html") {
// HTML file - need to send back only the bodies of the
// <script> tags
var text = "",
offset = this.getOffset(),
cursor = this.getCursor(),
editor = this.editor,
scriptBlocks = HTMLUtils.findBlocks(editor, "javascript");
// Add all the javascript text
// For non-javascript blocks we replace everything except for newlines
// with whitespace. This is so that the offset and cursor positions
// we get from the document still work.
// Alternatively we could strip the non-javascript text, and modify the offset,
// and/or cursor, but then we have to remember how to reverse the translation
// to support jump-to-definition
var htmlStart = {line: 0, ch: 0};
scriptBlocks.forEach(function (scriptBlock) {
var start = scriptBlock.start,
end = scriptBlock.end;
// get the preceding html text, and replace it with whitespace
var htmlText = editor.document.getRange(htmlStart, start);
htmlText = htmlText.replace(/./g, " ");
htmlStart = end;
text += htmlText + scriptBlock.text;
});
return text;
} else {
// Javascript file, just return the text
return this.editor.document.getText();
}
};
/**
* Determine if the cursor is located in the name of a function declaration.
* This is so we can suppress hints when in a function name, as we do for variable and
* parameter declarations, but we can tell those from the token itself rather than having
* to look at previous tokens.
*
* @return {boolean} - true if the current cursor position is in the name of a function
* declaration.
*/
Session.prototype.isFunctionName = function () {
var cursor = this.getCursor(),
token = this.getToken(cursor),
prevToken = this._getPreviousToken(cursor);
return prevToken.string === "function";
};
module.exports = Session;
});
|
'use strict';
module.exports = {
/**
* An asynchronous register function that runs before
* your application is initialized.
*
* This gives you an opportunity to extend code.
*/
register(/*{ strapi }*/) {},
/**
* An asynchronous bootstrap function that runs before
* your application gets started.
*
* This gives you an opportunity to set up your data model,
* run jobs, or perform some special logic.
*/
bootstrap(/*{ strapi }*/) {},
};
|
exports.level = {
"name": 'Git ์ปค๋ฐ ์๊ฐ',
"goalTreeString": "{\"branches\":{\"master\":{\"target\":\"C3\",\"id\":\"master\"}},\"commits\":{\"C0\":{\"parents\":[],\"id\":\"C0\",\"rootCommit\":true},\"C1\":{\"parents\":[\"C0\"],\"id\":\"C1\"},\"C2\":{\"parents\":[\"C1\"],\"id\":\"C2\"},\"C3\":{\"parents\":[\"C2\"],\"id\":\"C3\"}},\"HEAD\":{\"target\":\"master\",\"id\":\"HEAD\"}}",
"solutionCommand": "git commit;git commit",
"startTree": "{\"branches\":{\"master\":{\"target\":\"C1\",\"id\":\"master\"}},\"commits\":{\"C0\":{\"parents\":[],\"id\":\"C0\",\"rootCommit\":true},\"C1\":{\"parents\":[\"C0\"],\"id\":\"C1\"}},\"HEAD\":{\"target\":\"master\",\"id\":\"HEAD\"}}",
"hint": "'git commit'์ด๋ผ๊ณ ๋ ๋ฒ ์น์ธ์!",
"disabledMap" : {
"git revert": true
},
"startDialog": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"## Git ์ปค๋ฐ",
// "A commit in a git repository records a snapshot of all the files in your directory. It\'s like a giant copy and paste, but even better!",
"์ปค๋ฐ์ Git ์ ์ฅ์์ ์ฌ๋ฌ๋ถ์ ๋๋ ํ ๋ฆฌ์ ์๋ ๋ชจ๋ ํ์ผ์ ๋ํ ์ค๋
์ท์ ๊ธฐ๋กํ๋ ๊ฒ์
๋๋ค. ๋๋ ํ ๋ฆฌ ์ ์ฒด์ ๋ํ ๋ณต์ฌํด ๋ถ์ด๊ธฐ์ ๋น์ทํ์ง๋ง ํจ์ฌ ์ ์ฉํฉ๋๋ค!",
"",
// "Git wants to keep commits as lightweight as possible though, so it doesn't just copy the entire directory every time you commit. It actually stores each commit as a set of changes, or a \"delta\", from one version of the repository to the next. That\'s why most commits have a parent commit above them -- you\'ll see this later in our visualizations.",
"Git์ ์ปค๋ฐ์ ๊ฐ๋ฅํํ ๊ฐ๋ณ๊ฒ ์ ์งํ๊ณ ์ ํด์, ์ปค๋ฐํ ๋๋ง๋ค ๋๋ ํ ๋ฆฌ ์ ์ฒด๋ฅผ ๋ณต์ฌํ๋ ์ผ์ ํ์ง ์์ต๋๋ค. ๊ฐ ์ปค๋ฐ์ ์ ์ฅ์์ ์ด์ ๋ฒ์ ๊ณผ ๋ค์ ๋ฒ์ ์ ๋ณ๊ฒฝ๋ด์ญ(\"delta\"๋ผ๊ณ ๋ ํจ)์ ์ ์ฅํฉ๋๋ค. ๊ทธ๋์ ๋๋ถ๋ถ์ ์ปค๋ฐ์ด ๊ทธ ์ปค๋ฐ ์์ ๋ถ๋ชจ ์ปค๋ฐ์ ๊ฐ๋ฆฌํค๊ณ ์๊ฒ ๋๋ ๊ฒ์
๋๋ค. -- ๊ณง ๊ทธ๋ฆผ์ผ๋ก ๋ ํ๋ฉด์์ ์ดํด๋ณด๊ฒ ๋ ๊ฒ์
๋๋ค.",
"",
//"In order to clone a repository, you have to unpack or \"resolve\" all these deltas. That's why you might see the command line output:",
"์ ์ฅ์๋ฅผ ๋ณต์ (clone)ํ๋ ค๋ฉด, ๊ทธ ๋ชจ๋ ๋ณ๊ฒฝ๋ถ(delta)๋ฅผ ํ์ด๋ด์ผํ๋๋ฐ, ๊ทธ ๋๋ฌธ์ ๋ช
๋ นํ ๊ฒฐ๊ณผ๋ก ์๋์ ๊ฐ์ด ๋ณด๊ฒ๋ฉ๋๋ค. ",
"",
"`resolving deltas`",
"",
//"when cloning a repo.",
//"",
//"It's a lot to take in, but for now you can think of commits as snapshots of the project. Commits are very light and switching between them is wicked fast!"
"์์์ผํ ๊ฒ์ด ๊ฝค ๋ง์ต๋๋ค๋ง, ์ผ๋จ์ ์ปค๋ฐ์ ํ๋ก์ ํธ์ ๊ฐ๊ฐ์ ์ค๋
์ท๋ค๋ก ์๊ฐํ์๋ ๊ฑธ๋ก ์ถฉ๋ถํฉ๋๋ค. ์ปค๋ฐ์ ๋งค์ฐ ๊ฐ๋ณ๊ณ ์ปค๋ฐ ์ฌ์ด์ ์ ํ๋ ๋งค์ฐ ๋น ๋ฅด๋ค๋ ๊ฒ์ ๊ธฐ์ตํด์ฃผ์ธ์!"
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
// "Let's see what this looks like in practice. On the right we have a visualization of a (small) git repository. There are two commits right now -- the first initial commit, `C0`, and one commit after that `C1` that might have some meaningful changes.",
"์ฐ์ตํ ๋ ์ด๋ป๊ฒ ๋ณด์ด๋์ง ํ์ธํด๋ณด์ฃ . ์ค๋ฅธ์ชฝ ํ๋ฉด์ git ์ ์ฅ์๋ฅผ ๊ทธ๋ฆผ์ผ๋ก ํํํด ๋์์ต๋๋ค. ํ์ฌ ๋๋ฒ ์ปค๋ฐํ ์ํ์
๋๋ค -- ์ฒซ๋ฒ์งธ ์ปค๋ฐ์ผ๋ก `C0`, ๊ทธ ๋ค์์ผ๋ก `C1`์ด๋ผ๋ ์ด๋ค ์๋ฏธ์๋ ๋ณํ๊ฐ ์๋ ์ปค๋ฐ์ด ์์ต๋๋ค.",
"",
// "Hit the button below to make a new commit"
"์๋ ๋ฒํผ์ ๋๋ฌ ์๋ก์ด ์ปค๋ฐ์ ๋ง๋ค์ด๋ณด์ธ์"
],
"afterMarkdowns": [
// "There we go! Awesome. We just made changes to the repository and saved them as a commit. The commit we just made has a parent, `C1`, which references which commit it was based off of."
"์ด๋ ๊ฒ ๋ณด์
๋๋ค! ๋ฉ์ง์ฃ . ์ฐ๋ฆฌ๋ ๋ฐฉ๊ธ ์ ์ฅ์ ๋ด์ฉ์ ๋ณ๊ฒฝํด์ ํ๋ฒ์ ์ปค๋ฐ์ผ๋ก ์ ์ฅํ์ต๋๋ค. ๋ฐฉ๊ธ ๋ง๋ ์ปค๋ฐ์ ๋ถ๋ชจ๋ `C1`์ด๊ณ , ์ด๋ค ์ปค๋ฐ์ ๊ธฐ๋ฐ์ผ๋ก ๋ณ๊ฒฝ๋ ๊ฒ์ธ์ง๋ฅผ ๊ฐ๋ฆฌํต๋๋ค."
],
"command": "git commit",
"beforeCommand": ""
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
// "Go ahead and try it out on your own! After this window closes, make two commits to complete the level"
"๊ณ์ํด์ ์ง์ ํ๋ฒ ํด๋ณด์ธ์! ์ด ์ฐฝ์ ๋ซ๊ณ , ์ปค๋ฐ์ ๋ ๋ฒ ํ๋ฉด ๋ค์ ๋ ๋ฒจ๋ก ๋์ด๊ฐ๋๋ค"
]
}
}
]
}
};
|
define([
"thirdparty/filer/dist/filer.min",
"EventEmitter",
"bramble/client/PathCache"
], function(Filer, EventEmitter, PathCache) {
"use strict";
var Path = Filer.Path;
function ProjectStats(options) {
this.root = options.root;
this.capacity = options.capacity;
}
ProjectStats.prototype = new EventEmitter();
ProjectStats.prototype.constructor = ProjectStats;
// (Re)Initialize the ProjectStats instance with a new filesystem.
ProjectStats.prototype.init = function(fs, callback) {
var self = this;
self.cache = new PathCache();
self.overCapacity = false;
self.wrapFileSystem(fs);
function addSize(path, next) {
// ignore directories and do nothing
if (/\/$/.test(path)){
return next();
}
fs.stat(path, function(err, stats){
if (err){
return next(err);
}
self.cache.add(path, stats.size);
self.checkCapacity();
next();
});
}
// walk the root
var shell = new fs.Shell();
shell.find(self.root, { exec:addSize }, callback);
};
ProjectStats.prototype.wrapFileSystem = function(fs) {
var self = this;
self.fs = fs;
// original unlink
var _innerUnlink = fs.unlink;
// overwrite unlink function to do the bookkeeping of project state and call original unlink.
fs.unlink = function(pathname, callback){
_innerUnlink.call(fs, pathname, function(err){
// only update cache once original was successfull
if (!err){
self.cache.remove(pathname);
self.checkCapacity();
}
callback(err);
});
};
// original writeFile
var _innerWriteFile = fs.writeFile;
// overwrite original writeFile and add bookkeeping of project state and call original writeFile.
fs.writeFile = function(filename, data, options, callback){
if (typeof options === "function"){
callback = options;
options = {};
}
_innerWriteFile.call(fs, filename, data, options, function(err){
// only update cache once original was successfull
if (!err){
self.cache.add(filename, data.length);
self.checkCapacity();
}
callback(err);
});
};
// original rename
var _innerRename = fs.rename;
// overwrite original rename and add bookkeeping of project state and call original rename.
// this is essential because we don't want to lose track of file's size for renamed files.
fs.rename = function(oldPath, newPath, callback){
_innerRename.call(fs, oldPath, newPath, function(err){
// only update cache once original was successfull
if (!err){
self.cache.rename(oldPath, newPath);
}
callback(err);
});
};
};
// Monitor disk activity and trigger when we go over (or back under) capacity.
ProjectStats.prototype.checkCapacity = function() {
var size = this.getTotalProjectSize();
var diff = this.capacity - size;
var percentUsed = size / this.capacity;
this.trigger("projectSizeChange", [size, percentUsed]);
if (size >= this.capacity && !this.overCapacity) {
this.overCapacity = true;
this.trigger("capacityStateChange", [this.overCapacity, diff]);
} else if(size < this.capacity && this.overCapacity) {
this.overCapacity = false;
this.trigger("capacityStateChange", [this.overCapacity, diff]);
}
};
ProjectStats.prototype.getTotalProjectSize = function() {
return this.cache.getTotalBytes();
};
ProjectStats.prototype.getFileCount = function() {
return this.cache.getFileCount();
};
ProjectStats.prototype.hasIndexFile = function() {
var index = Path.join(this.root, "index.html");
return this.cache.hasPath(index);
};
return ProjectStats;
});
|
๏ปฟ/**
* Copyright (c) Microsoft. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Module dependencies.
var util = require('util');
var url = require('url');
var ServiceClient = require('../core/serviceclient');
var WebResource = require('../../http/webresource');
var Constants = require('../../util/constants');
var ServiceClientConstants = require('../core/serviceclientconstants');
var HeaderConstants = Constants.HeaderConstants;
var acsTokenResult = require('./models/acstokenresult');
/**
* Creates a new WrapService object.
*
* @param {string} acsHost The access control host.
* @param {string} [issuer] The service bus issuer.
* @param {string} [accessKey] The service bus issuer password.
*/
function WrapService(acsHost, issuer, accessKey) {
if (!acsHost) {
var acsNamespace = process.env[ServiceClientConstants.EnvironmentVariables.AZURE_WRAP_NAMESPACE];
if (!acsNamespace) {
acsNamespace = process.env[ServiceClientConstants.EnvironmentVariables.AZURE_SERVICEBUS_NAMESPACE] + ServiceClientConstants.DEFAULT_WRAP_NAMESPACE_SUFFIX;
}
acsHost = url.format({ protocol: 'https:', port: 443, hostname: acsNamespace + '.' + ServiceClientConstants.CLOUD_ACCESS_CONTROL_HOST });
}
this.issuer = issuer;
if (!this.issuer) {
this.issuer = process.env[ServiceClientConstants.EnvironmentVariables.AZURE_SERVICEBUS_ISSUER];
if (!this.issuer) {
this.issuer = ServiceClientConstants.DEFAULT_SERVICEBUS_ISSUER;
}
}
this.accessKey = accessKey;
if (!this.accessKey) {
this.accessKey = process.env[ServiceClientConstants.EnvironmentVariables.AZURE_SERVICEBUS_ACCESS_KEY];
}
WrapService['super_'].call(this, acsHost);
}
util.inherits(WrapService, ServiceClient);
/**
* Validates a callback function.
*
* @param (function) callback The callback function.
* @return {undefined}
*/
function validateCallback(callback) {
if (!callback) {
throw new Error('Callback must be specified.');
}
}
WrapService.prototype.wrapAccessToken = function (uri, optionsOrCallback, callback) {
var options = null;
if (typeof optionsOrCallback === 'function' && !callback) {
callback = optionsOrCallback;
} else {
options = optionsOrCallback;
}
validateCallback(callback);
var acsData = 'wrap_name=' + encodeURIComponent(this.issuer) +
'&wrap_password=' + encodeURIComponent(this.accessKey) +
'&wrap_scope=' + encodeURIComponent(uri);
var webResource = WebResource.post('WRAPv0.9/')
.withRawResponse(true);
webResource.withHeader(HeaderConstants.CONTENT_TYPE, 'application/x-www-form-urlencoded');
var processResponseCallback = function (responseObject, next) {
responseObject.acsTokenResult = null;
if (!responseObject.error) {
responseObject.acsTokenResult = acsTokenResult.parse(responseObject.response.body);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.acsTokenResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, acsData, options, processResponseCallback);
};
WrapService.prototype._buildRequestOptions = function (webResource, options, callback) {
var self = this;
if (!webResource.headers || !webResource.headers[HeaderConstants.CONTENT_TYPE]) {
webResource.withHeader(HeaderConstants.CONTENT_TYPE, '');
}
if (!webResource.headers || !webResource.headers[HeaderConstants.CONTENT_LENGTH]) {
webResource.withHeader(HeaderConstants.CONTENT_LENGTH, 0);
}
// Sets the request url in the web resource.
this._setRequestUrl(webResource);
var requestOptions = {
url: url.format({
protocol: self._isHttps() ? 'https:' : 'http:',
hostname: self.host,
port: self.port,
pathname: webResource.path,
query: webResource.queryString
}),
method: webResource.httpVerb,
headers: webResource.headers
};
callback(null, requestOptions);
};
/**
* Retrieves the normalized path to be used in a request.
* It adds a leading "/" to the path in case
* it's not there before.
*
* @param {string} path The path to be normalized.
* @return {string} The normalized path.
*/
WrapService.prototype._getPath = function (path) {
if (path === null || path === undefined) {
path = '/';
} else if (path.indexOf('/') !== 0) {
path = '/' + path;
}
return path;
};
module.exports = WrapService; |
var http = require('http')
, exec = require('child_process').exec
, fs = require('fs')
, Connect = require('connect')
, dispatch = require('dispatch')
, mime = require('mime')
, getMime = function(ext) {
return mime.lookup(ext == 'jsonp' ? 'js' : ext)
}
var routes = {
'/': function (req, res) {
res.write(fs.readFileSync('./tests/tests.html', 'utf8'))
res.end()
},
'(([\\w\\-\\/]+)\\.(css|js|json|jsonp|html|xml)$)': function (req, res, next, uri, file, ext) {
res.writeHead(200, {
'Expires': 0
, 'Cache-Control': 'max-age=0, no-cache, no-store'
, 'Content-Type': getMime(ext)
})
if (req.query.echo !== undefined) {
ext == 'jsonp' && res.write((req.query.callback || req.query.testCallback || 'echoCallback') + '(')
res.write(JSON.stringify({ method: req.method, query: req.query, headers: req.headers }))
ext == 'jsonp' && res.write(');')
} else {
res.write(fs.readFileSync('./' + file + '.' + ext))
}
res.end()
}
}
Connect.createServer(Connect.query(), dispatch(routes)).listen(1234)
var otherOriginRoutes = {
'/get-value': function (req, res) {
res.writeHead(200, {
'Access-Control-Allow-Origin': 'http://localhost:1234',
'Content-Type': 'text/plain'
})
res.end('hello')
},
'/set-cookie': function (req, res) {
res.writeHead(200, {
'Access-Control-Allow-Origin': 'http://localhost:1234',
'Access-Control-Allow-Credentials': 'true',
'Content-Type': 'text/plain',
'Set-Cookie': 'cookie=hello'
})
res.end('Set a cookie!')
},
'/get-cookie-value': function (req, res) {
var cookies = req.headers.cookie
var value = ((cookies.indexOf('=') > -1) ? cookies.split('=')[1] : '')
res.writeHead(200, {
'Access-Control-Allow-Origin': 'http://localhost:1234',
'Access-Control-Allow-Credentials': 'true',
'Content-Type': 'text/plain'
})
res.end(value)
}
}
Connect.createServer(Connect.query(), dispatch(otherOriginRoutes)).listen(5678)
exec('open http://localhost:1234', function () {
console.log('opening tests at http://localhost:1234')
})
|
// js acts as a wrapper to the c++ bindings
// prefer to do error handling and other abstrctions in the
// js layer and only go to c++ when we need to hit libxml
var bindings = require('./lib/bindings');
// document parsing for backwards compat
var Document = require('./lib/document');
/// parse an xml string and return a Document
module.exports.parseXml = Document.fromXml;
/// parse an html string and return a Document
module.exports.parseHtml = Document.fromHtml;
module.exports.parseHtmlFragment = Document.fromHtmlFragment;
// constants
module.exports.version = require('./package.json').version;
module.exports.libxml_version = bindings.libxml_version;
module.exports.libxml_parser_version = bindings.libxml_parser_version;
module.exports.libxml_debug_enabled = bindings.libxml_debug_enabled;
module.exports.features = bindings.features;
// lib exports
module.exports.Comment = require('./lib/comment');
module.exports.Document = Document;
module.exports.Element = require('./lib/element');
module.exports.ProcessingInstruction = require('./lib/pi');
module.exports.Text = require('./lib/text');
// Compatibility synonyms
Document.fromXmlString = Document.fromXml;
Document.fromHtmlString = Document.fromHtml;
module.exports.parseXmlString = module.exports.parseXml;
module.exports.parseHtmlString = module.exports.parseHtml;
var sax_parser = require('./lib/sax_parser');
module.exports.SaxParser = sax_parser.SaxParser;
module.exports.SaxPushParser = sax_parser.SaxPushParser;
module.exports.memoryUsage = bindings.xmlMemUsed;
module.exports.nodeCount = bindings.xmlNodeCount;
|
(function(__global) {
var tmp0, tmp1, tmp2, tmp3, tmp4, tmp5;
tmp5 = "jQuery";
tmp1 = __global[tmp5];
tmp2 = "wait";
tmp3 = tmp1[tmp2];
tmp4 = 1;
tmp0 = tmp3 - tmp4;
tmp1[tmp2] = tmp0;
})(typeof global === 'undefined' ? this : global); |
export default /* glsl */`
#if defined( RE_IndirectDiffuse )
#ifdef USE_LIGHTMAP
vec4 lightMapTexel = texture2D( lightMap, vUv2 );
vec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;
#ifndef PHYSICALLY_CORRECT_LIGHTS
lightMapIrradiance *= PI;
#endif
irradiance += lightMapIrradiance;
#endif
#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
iblIrradiance += getIBLIrradiance( geometry.normal );
#endif
#endif
#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
radiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );
#ifdef USE_CLEARCOAT
clearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );
#endif
#endif
`;
|
/**
* Import(s)
*/
var Vue = require('../../node_modules/vue/dist/vue')
/**
* Export(s)
*/
/**
* Wrap template
*
* @param {String} target
* @param {tag} tag
* @return {String} validator tag
*/
var wrapTemplate = exports.wrapTemplate = function (target, tag) {
tag = tag || 'form'
return '<' + tag + '>' + target + '</' + tag + '>'
}
/**
* Create instance
*
* @params {Function} el
* @params {String} target | template
* @params {Object} validator
* @params {Object} data
* @params {Function} ready
* @return {Object} created Vue component instance
*/
exports.createInstance = function (params, extend) {
params = params || {}
extend = (extend === undefined ? true : extend)
var options = {}
options.el = params.el || function () {
var el = document.createElement('div')
document.body.appendChild(el)
return el
}
options.data = function () {
return params.data || {}
}
options.template = wrapTemplate(params.target || params.template || '')
if (params.components) {
options.components = params.components
}
if (params.computed) {
options.computed = params.computed
}
if (params.methods) {
options.methods = params.methods
}
if (params.validator) {
options.validator = params.validator
}
var events = ['created', 'compiled', 'ready']
events.forEach(function (event) {
if (params[event]) {
options[event] = params[event]
}
})
if (extend) {
var Ctor = Vue.extend(options)
return new Ctor()
} else {
return new Vue(options)
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:c79ec7c19fc556c7fe7870d79f159abbd442388cfad28dd4c34173ab9fb972f8
size 16229
|
/*! jQuery UI - v1.10.4 - 2014-03-23
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional["zh-TW"]={closeText:"้้",prevText:"<ไธๆ",nextText:"ไธๆ>",currentText:"ไปๅคฉ",monthNames:["ไธๆ","ไบๆ","ไธๆ","ๅๆ","ไบๆ","ๅ
ญๆ","ไธๆ","ๅ
ซๆ","ไนๆ","ๅๆ","ๅไธๆ","ๅไบๆ"],monthNamesShort:["ไธๆ","ไบๆ","ไธๆ","ๅๆ","ไบๆ","ๅ
ญๆ","ไธๆ","ๅ
ซๆ","ไนๆ","ๅๆ","ๅไธๆ","ๅไบๆ"],dayNames:["ๆๆๆฅ","ๆๆไธ","ๆๆไบ","ๆๆไธ","ๆๆๅ","ๆๆไบ","ๆๆๅ
ญ"],dayNamesShort:["ๅจๆฅ","ๅจไธ","ๅจไบ","ๅจไธ","ๅจๅ","ๅจไบ","ๅจๅ
ญ"],dayNamesMin:["ๆฅ","ไธ","ไบ","ไธ","ๅ","ไบ","ๅ
ญ"],weekHeader:"ๅจ",dateFormat:"yy/mm/dd",firstDay:1,isRTL:!1,showMonthAfterYear:!0,yearSuffix:"ๅนด"},e.datepicker.setDefaults(e.datepicker.regional["zh-TW"])}); |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* The details of the error.
*
*/
class ErrorResponseError {
/**
* Create a ErrorResponseError.
* @member {string} [code] Error code.
* @member {string} [message] Error message indicating why the operation
* failed.
*/
constructor() {
}
/**
* Defines the metadata of ErrorResponseError
*
* @returns {object} metadata of ErrorResponseError
*
*/
mapper() {
return {
required: false,
serializedName: 'ErrorResponse_error',
type: {
name: 'Composite',
className: 'ErrorResponseError',
modelProperties: {
code: {
required: false,
readOnly: true,
serializedName: 'code',
type: {
name: 'String'
}
},
message: {
required: false,
readOnly: true,
serializedName: 'message',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = ErrorResponseError;
|
'use strict';
Connector.playerSelector = '#radioPlayer';
Connector.artistSelector = '#showDescription';
Connector.trackSelector = '#showName';
Connector.trackArtSelector = '#poster';
Connector.pauseButtonSelector = '#playButton.stop';
|
import { Resource } from '../api-resource';
export default class RemoteChannelResource extends Resource {
static resourceName() {
return 'remotechannel';
}
getKolibriStudioStatus() {
return this.client({
path: this.urls[`${this.name}-kolibri-studio-status`](),
method: 'GET',
});
}
}
|
/**
* Module dependencies
*/
var actionUtil = require('../actionUtil');
/**
* Create Record
*
* post /:modelIdentity
*
* An API call to find and return a single model instance from the data adapter
* using the specified criteria. If an id was specified, just the instance with
* that unique id will be returned.
*
* Optional:
* @param {String} callback - default jsonp callback param (i.e. the name of the js function returned)
* @param {*} * - other params will be used as `values` in the create
*/
module.exports = function createRecord (req, res) {
var Model = actionUtil.parseModel(req);
// Create data object (monolithic combination of all parameters)
// Omit the blacklisted params (like JSONP callback param, etc.)
var data = actionUtil.parseValues(req);
// Create new instance of model using data from params
Model.create(data).then(function(newInstance) {
// If we have the pubsub hook, use the model class's publish method
// to notify all subscribers about the created item
if (req._sails.hooks.pubsub) {
if (req.isSocket) {
Model.subscribe(req, newInstance);
Model.introduce(newInstance);
}
Model.publishCreate(newInstance.toJSON(), !req.options.mirror && req);
}
// Send JSONP-friendly response if it's supported
res.created(newInstance);
}).catch(function(err){
// Differentiate between waterline-originated validation errors
// and serious underlying issues. Respond with badRequest if a
// validation error is encountered, w/ validation info.
return res.negotiate(err);
});
};
|
const jsonSchema = require('@tryghost/admin-api-schema');
/**
*
* @param {Object} apiConfig "frame" api configruation object
* @param {string} apiConfig.docName the name of the resource
* @param {string} apiConfig.method API's method name
* @param {Object} frame "frame" object with data attached to it
* @param {Object} frame.data request data to validate
*/
const validate = async (apiConfig, frame) => await jsonSchema.validate({
data: frame.data,
schema: `${apiConfig.docName}-${apiConfig.method}`,
version: 'v2'
});
module.exports.validate = validate;
|
(function() {
'use strict';
module.exports = function(gulp, args, ifs, print, jshint, jscs, util, handleErrors, logger, config ) {
gulp.task('jscshint', function() {
logger(util, 'Analyzing source with JSHINT and JSCS');
return gulp
.src(config.alljs)
.pipe(ifs(args.verbose, print()))
.pipe(jscs())
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish', {verbose:true}))
.pipe(jshint.reporter('fail'))
.on('error', handleErrors);
});
};
}());
|
// Measure the time it takes for the HTTP client to send a request body.
var common = require('../common.js');
var http = require('http');
var bench = common.createBenchmark(main, {
dur: [5],
type: ['asc', 'utf', 'buf'],
bytes: [32, 256, 1024],
method: ['write', 'end']
});
function main(conf) {
var dur = +conf.dur;
var len = +conf.bytes;
var encoding;
var chunk;
switch (conf.type) {
case 'buf':
chunk = new Buffer(len);
chunk.fill('x');
break;
case 'utf':
encoding = 'utf8';
chunk = new Array(len / 2 + 1).join('รผ');
break;
case 'asc':
chunk = new Array(len + 1).join('a');
break;
}
var nreqs = 0;
var options = {
headers: { 'Connection': 'keep-alive', 'Transfer-Encoding': 'chunked' },
agent: new http.Agent({ maxSockets: 1 }),
host: '127.0.0.1',
port: common.PORT,
path: '/',
method: 'POST'
};
var server = http.createServer(function(req, res) {
res.end();
});
server.listen(options.port, options.host, function() {
setTimeout(done, dur * 1000);
bench.start();
pummel();
});
function pummel() {
var req = http.request(options, function(res) {
nreqs++;
pummel(); // Line up next request.
res.resume();
});
if (conf.method === 'write') {
req.write(chunk, encoding);
req.end();
} else {
req.end(chunk, encoding);
}
}
function done() {
bench.end(nreqs);
}
}
|
/* */
"format global";
/**
* Copyright 2015 Telerik AD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["tzm-Latn-DZ"] = {
name: "tzm-Latn-DZ",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["-n $","n $"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
symbol: "DA"
}
},
calendars: {
standard: {
days: {
names: ["lh\u0027ed","letnayen","ttlata","larebรขa","lexmis","ldjemรขa","ssebt"],
namesAbbr: ["lh\u0027d","let","ttl","lar","lex","ldj","sse"],
namesShort: ["lh","lt","tt","la","lx","ld","ss"]
},
months: {
names: ["Yennayer","Furar","Meghres","Yebrir","Magu","Yunyu","Yulyu","Ghuct","Cutenber","Tuber","Nunember","Dujanbir"],
namesAbbr: ["Yen","Fur","Megh","Yeb","May","Yun","Yul","Ghu","Cut","Tub","Nun","Duj"]
},
AM: [""],
PM: [""],
patterns: {
d: "dd-MM-yyyy",
D: "dd MMMM, yyyy",
F: "dd MMMM, yyyy H:mm:ss",
g: "dd-MM-yyyy H:mm",
G: "dd-MM-yyyy H:mm:ss",
m: "d MMMM",
M: "d MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "H:mm",
T: "H:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM, yyyy",
Y: "MMMM, yyyy"
},
"/": "-",
":": ":",
firstDay: 6
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); |
describe('ez-file-tree', function() {
var el, el2, $scope, rows, $timeout;
beforeEach(module('ez.fileTree'));
beforeEach(inject(function(_$compile_, $rootScope, _$timeout_) {
$compile = _$compile_;
$timeout = _$timeout_;
$scope = $rootScope.$new();
el = angular.element(
'<div id="fileTree" ez-file-tree="folder"></div>'
);
el2 = angular.element(
'<div ez-file-tree="folder" config="config"></div>'
);
$scope.config = {
isFolder: function(file) {
return file.type === 'album' || file.type === 'folder';
}
};
$scope.folder = {
id: "Root",
name: "Root",
type: "folder",
children: [
{
id: "Folder 1",
name: "Folder 1",
type: "folder",
children: [
{
id: "1a",
name: "Folder 1a",
type: "folder",
children: [
{
id: "1a1",
type: "file",
name: "File 1a1"
},
{
id: "1a2",
type: "file",
name: "File 1a2"
},
{
id: "1a2",
type: "file",
name: "File 1a2"
}
]
},
{
id: "1b",
type: "file",
name: "File 1b"
},
{
id: "1c",
type: "file",
name: "File 1c"
}
]
},
{
id: "2",
name: "Folder 2",
type: "folder",
children: [
{
id: "2a",
name: "Folder 2a",
type: "folder",
children: [
{
id: "2a1",
type: "file",
name: "File 2a1"
},
{
id: "2a2",
type: "file",
name: "2a2"
},
{
id: "2a2",
type: "file",
name: "2a2"
}
]
},
{
id: "2b",
type: "file",
name: "File 2b"
},
{
id: "2c",
type: "file",
name: "File 2c"
}
]
},
{
id: "bla",
type: "file",
name: "File on root",
}
]
};
$compile(el)($scope);
$compile(el2)($scope);
$scope.$digest();
}));
it('should have default config', function() {
//assert.deepEqual(el.isolateScope().config, {
//enableChecking: false,
//enableFolderSelection: true,
//multiSelect: false,
//recursiveSelect: false,
//recursiveUnselect: true,
//icons: {
//chevronRight: 'fa fa-chevron-right',
//chevronDown: 'fa fa-chevron-down',
//folder: 'fa fa-folder',
//file: 'fa fa-file'
//},
//childrenField: 'children',
//idField: 'id',
//typeField: 'type',
//folderType: 'folder'
//});
});
it('is a table element', function() {
assert.equal(el.prop('tagName'), 'DIV');
assert.equal(el.attr('id'), 'fileTree');
});
it('should show the first level folders/files', function() {
assert.lengthOf(el.find('ul:first > li'), 3);
assert.equal(el.find('ul:first > li:nth-child(1) .file-name').eq(0).text(), 'Folder 1');
assert.equal(el.find('ul:first > li:nth-child(2) .file-name').eq(0).text(), 'Folder 2');
assert.equal(el.find('ul:first > li:nth-child(3) .file-name').eq(0).text(), 'File on root');
});
it('should hide nested folders', function() {
assert.equal(el.find('ul:first > li:nth-child(1) li .file-name').eq(0).text(), 'Folder 1a');
assert.isTrue(el.find('ul:first > li:nth-child(1) li .file-name').eq(0).parents('ul').hasClass('ng-hide'));
});
it('should select file on click', function() {
el.find('ul:first > li:nth-child(2) input').eq(0).click();
$timeout.flush();
assert.isTrue(el.find('ul:first > li:nth-child(2) input').eq(0).parents('.label-container').hasClass('selected'));
});
it('should unselect previous file on another file click', function() {
el.find('ul:first > li:nth-child(2) input').eq(0).click();
el.find('ul:first > li:nth-child(3) input').eq(0).click();
assert.isFalse(el.find('ul:first > li:nth-child(2) input').eq(0).parents('.label-container').hasClass('selected'));
});
it('should open/close tree on folder toggle', function() {
assert.equal(el.find('ul:first > li:nth-child(2) .label-container:first-child').next().attr('ng-scope ng-hide'));
$(el.find('ul:first > li:nth-child(2) .label-container:first-child .folder-toggle').get(0)).trigger('click');
assert.equal(el.find('ul:first > li:nth-child(2) .label-container:first-child').next().attr('ng-scope'));
});
it('should open/close tree on folder double click', function() {
assert.equal(el.find('ul:first > li:nth-child(2) .label-container:first-child').next().attr('ng-scope ng-hide'));
$(el.find('ul:first > li:nth-child(2) .label-container:first-child .file-name').get(0)).trigger('dblclick');
assert.equal(el.find('ul:first > li:nth-child(2) .label-container:first-child').next().attr('ng-scope'));
});
it('should allow isFolder to be set on config', function() {
assert.isTrue(el.isolateScope().config.isFolder({type: 'folder'}), 'el1');
assert.isFalse(el.isolateScope().config.isFolder({type: 'file'}), 'el1-2');
assert.isTrue(el2.isolateScope().config.isFolder({type: 'folder'}), 'el2-1');
assert.isTrue(el2.isolateScope().config.isFolder({type: 'album'}) ,'el2-2');
assert.isFalse(el2.isolateScope().config.isFolder({type: 'file'}), 'el2-3');
});
});
|
/**
* @fileoverview Tests for the no-restricted-exports rule
* @author Milos Djermanovic
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const rule = require("../../../lib/rules/no-restricted-exports");
const { RuleTester } = require("../../../lib/rule-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2022, sourceType: "module" } });
ruleTester.run("no-restricted-exports", rule, {
valid: [
// nothing configured
"export var a;",
"export function a() {}",
"export class A {}",
"var a; export { a };",
"var b; export { b as a };",
"export { a } from 'foo';",
"export { b as a } from 'foo';",
{ code: "export var a;", options: [{}] },
{ code: "export function a() {}", options: [{}] },
{ code: "export class A {}", options: [{}] },
{ code: "var a; export { a };", options: [{}] },
{ code: "var b; export { b as a };", options: [{}] },
{ code: "export { a } from 'foo';", options: [{}] },
{ code: "export { b as a } from 'foo';", options: [{}] },
{ code: "export var a;", options: [{ restrictedNamedExports: [] }] },
{ code: "export function a() {}", options: [{ restrictedNamedExports: [] }] },
{ code: "export class A {}", options: [{ restrictedNamedExports: [] }] },
{ code: "var a; export { a };", options: [{ restrictedNamedExports: [] }] },
{ code: "var b; export { b as a };", options: [{ restrictedNamedExports: [] }] },
{ code: "export { a } from 'foo';", options: [{ restrictedNamedExports: [] }] },
{ code: "export { b as a } from 'foo';", options: [{ restrictedNamedExports: [] }] },
// not a restricted name
{ code: "export var a;", options: [{ restrictedNamedExports: ["x"] }] },
{ code: "export let a;", options: [{ restrictedNamedExports: ["x"] }] },
{ code: "export const a = 1;", options: [{ restrictedNamedExports: ["x"] }] },
{ code: "export function a() {}", options: [{ restrictedNamedExports: ["x"] }] },
{ code: "export function *a() {}", options: [{ restrictedNamedExports: ["x"] }] },
{ code: "export async function a() {}", options: [{ restrictedNamedExports: ["x"] }] },
{ code: "export async function *a() {}", options: [{ restrictedNamedExports: ["x"] }] },
{ code: "export class A {}", options: [{ restrictedNamedExports: ["x"] }] },
{ code: "var a; export { a };", options: [{ restrictedNamedExports: ["x"] }] },
{ code: "var b; export { b as a };", options: [{ restrictedNamedExports: ["x"] }] },
{ code: "export { a } from 'foo';", options: [{ restrictedNamedExports: ["x"] }] },
{ code: "export { b as a } from 'foo';", options: [{ restrictedNamedExports: ["x"] }] },
{ code: "export { '' } from 'foo';", options: [{ restrictedNamedExports: ["undefined"] }] },
{ code: "export { '' } from 'foo';", options: [{ restrictedNamedExports: [" "] }] },
{ code: "export { ' ' } from 'foo';", options: [{ restrictedNamedExports: [""] }] },
{ code: "export { ' a', 'a ' } from 'foo';", options: [{ restrictedNamedExports: ["a"] }] },
// does not mistakenly disallow non-exported names that appear in named export declarations
{ code: "export var b = a;", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export let [b = a] = [];", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export const [b] = [a];", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export var { a: b } = {};", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export let { b = a } = {};", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export const { c: b = a } = {};", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export function b(a) {}", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export class A { a(){} }", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export class A extends B {}", options: [{ restrictedNamedExports: ["B"] }] },
{ code: "var a; export { a as b };", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "var a; export { a as 'a ' };", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export { a as b } from 'foo';", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export { a as 'a ' } from 'foo';", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export { 'a' as 'a ' } from 'foo';", options: [{ restrictedNamedExports: ["a"] }] },
// does not check source in re-export declarations
{ code: "export { b } from 'a';", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export * as b from 'a';", options: [{ restrictedNamedExports: ["a"] }] },
// does not check non-export declarations
{ code: "var a;", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "let a;", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "const a = 1;", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "function a() {}", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "class A {}", options: [{ restrictedNamedExports: ["A"] }] },
{ code: "import a from 'foo';", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "import { a } from 'foo';", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "import { b as a } from 'foo';", options: [{ restrictedNamedExports: ["a"] }] },
// does not check re-export all declarations
{ code: "export * from 'foo';", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export * from 'a';", options: [{ restrictedNamedExports: ["a"] }] },
// does not mistakenly disallow identifiers in export default declarations (a default export will export "default" name)
{ code: "export default a;", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export default function a() {}", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export default class A {}", options: [{ restrictedNamedExports: ["A"] }] },
{ code: "export default (function a() {});", options: [{ restrictedNamedExports: ["a"] }] },
{ code: "export default (class A {});", options: [{ restrictedNamedExports: ["A"] }] },
// by design, restricted name "default" does not apply to default export declarations, although they do export the "default" name.
{ code: "export default 1;", options: [{ restrictedNamedExports: ["default"] }] },
// "default" does not disallow re-exporting a renamed default export from another module
{ code: "export { default as a } from 'foo';", options: [{ restrictedNamedExports: ["default"] }] }
],
invalid: [
{
code: "export function someFunction() {}",
options: [{ restrictedNamedExports: ["someFunction"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "someFunction" }, type: "Identifier" }]
},
// basic tests
{
code: "export var a;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export var a = 1;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export let a;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export let a = 1;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export const a = 1;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export function a() {}",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export function *a() {}",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export async function a() {}",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export async function *a() {}",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export class A {}",
options: [{ restrictedNamedExports: ["A"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "A" }, type: "Identifier" }]
},
{
code: "let a; export { a };",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 17 }]
},
{
code: "export { a }; var a;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 10 }]
},
{
code: "let b; export { b as a };",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export { a } from 'foo';",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export { b as a } from 'foo';",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
// string literals
{
code: "let a; export { a as 'a' };",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Literal", column: 22 }]
},
{
code: "let a; export { a as 'b' };",
options: [{ restrictedNamedExports: ["b"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "b" }, type: "Literal", column: 22 }]
},
{
code: "let a; export { a as ' b ' };",
options: [{ restrictedNamedExports: [" b "] }],
errors: [{ messageId: "restrictedNamed", data: { name: " b " }, type: "Literal", column: 22 }]
},
{
code: "let a; export { a as '๐' };",
options: [{ restrictedNamedExports: ["๐"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "๐" }, type: "Literal", column: 22 }]
},
{
code: "export { 'a' } from 'foo';",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Literal" }]
},
{
code: "export { '' } from 'foo';",
options: [{ restrictedNamedExports: [""] }],
errors: [{ messageId: "restrictedNamed", data: { name: "" }, type: "Literal" }]
},
{
code: "export { ' ' } from 'foo';",
options: [{ restrictedNamedExports: [" "] }],
errors: [{ messageId: "restrictedNamed", data: { name: " " }, type: "Literal" }]
},
{
code: "export { b as 'a' } from 'foo';",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Literal" }]
},
{
code: "export { b as '\\u0061' } from 'foo';",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Literal" }]
},
{
code: "export * as 'a' from 'foo';",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Literal" }]
},
// destructuring
{
code: "export var [a] = [];",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export let { a } = {};",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export const { b: a } = {};",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export var [{ a }] = [];",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export let { b: { c: a = d } = e } = {};",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
// reports the correct identifier node in the case of a redeclaration. Note: functions cannot be redeclared in a module.
{
code: "var a; export var a;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 19 }]
},
{
code: "export var a; var a;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 12 }]
},
// reports the correct identifier node when the same identifier appears elsewhere in the declaration
{
code: "export var a = a;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 12 }]
},
{
code: "export let b = a, a;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 19 }]
},
{
code: "export const a = 1, b = a;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 14 }]
},
{
code: "export var [a] = a;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 13 }]
},
{
code: "export let { a: a } = {};",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 17 }]
},
{
code: "export const { a: b, b: a } = {};",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 25 }]
},
{
code: "export var { b: a, a: b } = {};",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 17 }]
},
{
code: "export let a, { a: b } = {};",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 12 }]
},
{
code: "export const { a: b } = {}, a = 1;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 29 }]
},
{
code: "export var [a = a] = [];",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 13 }]
},
{
code: "export var { a: a = a } = {};",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 17 }]
},
{
code: "export let { a } = { a };",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 14 }]
},
{
code: "export function a(a) {};",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 17 }]
},
{
code: "export class A { A(){} };",
options: [{ restrictedNamedExports: ["A"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "A" }, type: "Identifier", column: 14 }]
},
{
code: "var a; export { a as a };",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 22 }]
},
{
code: "let a, b; export { a as b, b as a };",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 33 }]
},
{
code: "const a = 1, b = 2; export { b as a, a as b };",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 35 }]
},
{
code: "var a; export { a as b, a };",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 25 }]
},
{
code: "export { a as a } from 'a';",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 15 }]
},
{
code: "export { a as b, b as a } from 'foo';",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 23 }]
},
{
code: "export { b as a, a as b } from 'foo';",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 15 }]
},
{
code: "export * as a from 'a';",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier", column: 13 }]
},
// Note: duplicate identifiers in the same export declaration are a 'duplicate export' syntax error. Example: export var a, a;
// invalid and valid or multiple ivalid in the same declaration
{
code: "export var a, b;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export let b, a;",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export const b = 1, a = 2;",
options: [{ restrictedNamedExports: ["a", "b"] }],
errors: [
{ messageId: "restrictedNamed", data: { name: "b" }, type: "Identifier" },
{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }
]
},
{
code: "export var a, b, c;",
options: [{ restrictedNamedExports: ["a", "c"] }],
errors: [
{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" },
{ messageId: "restrictedNamed", data: { name: "c" }, type: "Identifier" }
]
},
{
code: "export let { a, b, c } = {};",
options: [{ restrictedNamedExports: ["b", "c"] }],
errors: [
{ messageId: "restrictedNamed", data: { name: "b" }, type: "Identifier" },
{ messageId: "restrictedNamed", data: { name: "c" }, type: "Identifier" }
]
},
{
code: "export const [a, b, c, d] = {};",
options: [{ restrictedNamedExports: ["b", "c"] }],
errors: [
{ messageId: "restrictedNamed", data: { name: "b" }, type: "Identifier" },
{ messageId: "restrictedNamed", data: { name: "c" }, type: "Identifier" }
]
},
{
code: "export var { a, x: b, c, d, e: y } = {}, e, f = {};",
options: [{ restrictedNamedExports: ["foo", "a", "b", "bar", "d", "e", "baz"] }],
errors: [
{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" },
{ messageId: "restrictedNamed", data: { name: "b" }, type: "Identifier" },
{ messageId: "restrictedNamed", data: { name: "d" }, type: "Identifier" },
{ messageId: "restrictedNamed", data: { name: "e" }, type: "Identifier", column: 42 }
]
},
{
code: "var a, b; export { a, b };",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "let a, b; export { b, a };",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "const a = 1, b = 1; export { a, b };",
options: [{ restrictedNamedExports: ["a", "b"] }],
errors: [
{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" },
{ messageId: "restrictedNamed", data: { name: "b" }, type: "Identifier" }
]
},
{
code: "export { a, b, c }; var a, b, c;",
options: [{ restrictedNamedExports: ["a", "c"] }],
errors: [
{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" },
{ messageId: "restrictedNamed", data: { name: "c" }, type: "Identifier" }
]
},
{
code: "export { b as a, b } from 'foo';",
options: [{ restrictedNamedExports: ["a"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" }]
},
{
code: "export { b as a, b } from 'foo';",
options: [{ restrictedNamedExports: ["b"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "b" }, type: "Identifier", column: 18 }]
},
{
code: "export { b as a, b } from 'foo';",
options: [{ restrictedNamedExports: ["a", "b"] }],
errors: [
{ messageId: "restrictedNamed", data: { name: "a" }, type: "Identifier" },
{ messageId: "restrictedNamed", data: { name: "b" }, type: "Identifier", column: 18 }
]
},
{
code: "export { a, b, c, d, x as e, f, g } from 'foo';",
options: [{ restrictedNamedExports: ["foo", "b", "bar", "d", "e", "f", "baz"] }],
errors: [
{ messageId: "restrictedNamed", data: { name: "b" }, type: "Identifier" },
{ messageId: "restrictedNamed", data: { name: "d" }, type: "Identifier" },
{ messageId: "restrictedNamed", data: { name: "e" }, type: "Identifier" },
{ messageId: "restrictedNamed", data: { name: "f" }, type: "Identifier" }
]
},
// reports "default" in named export declarations (when configured)
{
code: "var a; export { a as default };",
options: [{ restrictedNamedExports: ["default"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "default" }, type: "Identifier", column: 22 }]
},
{
code: "export { default } from 'foo';",
options: [{ restrictedNamedExports: ["default"] }],
errors: [{ messageId: "restrictedNamed", data: { name: "default" }, type: "Identifier", column: 10 }]
}
]
});
|
describe('TableView', function() {
var $ = jQuery;
it('renders a table with rows of cells for collection items', function() {
var collection = new Backbone.Collection([{firstName: 'Claire'}, {firstName: 'John'}]);
var tableView = new pageflow.TableView({
collection: collection,
columns: [
{name: 'firstName', cellView: pageflow.TextTableCellView}
]
});
tableView.render();
expect(tableView.$el.is('table')).to.eq(true);
expect(tableView.$el.find('tbody tr td').map(function() {
return $(this).text();
}).get()).to.eql(['Claire', 'John']);
});
it('adds selected class to row for selected model', function() {
var collection = new Backbone.Collection([{firstName: 'Claire'}, {firstName: 'John'}]);
var selection = new Backbone.Model();
var tableView = new pageflow.TableView({
collection: collection,
columns: [
{name: 'firstName', cellView: pageflow.TextTableCellView}
],
selection: selection
});
tableView.render();
selection.set('current', collection.last());
expect(tableView.$el.find('tbody tr.is_selected td')).to.have.$text('John');
});
it('allows setting a custom selection attribute name', function() {
var collection = new Backbone.Collection([{firstName: 'Claire'}, {firstName: 'John'}]);
var selection = new Backbone.Model();
var tableView = new pageflow.TableView({
collection: collection,
columns: [
{name: 'firstName', cellView: pageflow.TextTableCellView}
],
selection: selection,
selectionAttribute: 'person'
});
tableView.render();
selection.set('person', collection.last());
expect(tableView.$el.find('tbody tr.is_selected td')).to.have.$text('John');
});
it('sets selection when row is clicked', function() {
var collection = new Backbone.Collection([{firstName: 'Claire'}, {firstName: 'John'}]);
var selection = new Backbone.Model();
var tableView = new pageflow.TableView({
collection: collection,
columns: [
{name: 'firstName', cellView: pageflow.TextTableCellView}
],
selection: selection
});
tableView.render();
tableView.$el.find('tbody tr:last-child td').click();
expect(selection.get('current')).to.eq(collection.last());
});
it('sets custom selection attribute when row is clicked', function() {
var collection = new Backbone.Collection([{firstName: 'Claire'}, {firstName: 'John'}]);
var selection = new Backbone.Model();
var tableView = new pageflow.TableView({
collection: collection,
columns: [
{name: 'firstName', cellView: pageflow.TextTableCellView}
],
selection: selection,
selectionAttribute: 'person'
});
tableView.render();
tableView.$el.find('tbody tr:last-child td').click();
expect(selection.get('person')).to.eq(collection.last());
});
it('allows passing options for cell views', function() {
var collection = new Backbone.Collection([{firstName: 'Claire'}, {firstName: 'John'}]);
var tableView = new pageflow.TableView({
collection: collection,
columns: [
{
name: 'firstName',
cellView: pageflow.TextTableCellView,
cellViewOptions: {
className: 'custom'
}
}
]
});
tableView.render();
expect(tableView.$el.find('tbody tr td.custom').length).to.eq(2);
});
describe('attributeTranslationKeyPrefixes option', function() {
support.useFakeTranslations({
'columns.first_name.column_header': 'First Name',
'columns.last_name.column_header': 'Last Name',
'columns.first_name.text': 'Test'
});
it('is used for column header texts', function() {
var collection = new Backbone.Collection();
var tableView = new pageflow.TableView({
collection: collection,
columns: [
{
name: 'first_name',
cellView: pageflow.TextTableCellView
},
{
name: 'last_name',
cellView: pageflow.TextTableCellView
}
],
attributeTranslationKeyPrefixes: [
'columns'
]
});
tableView.render();
expect(tableView.$el.find('thead th').map(function() {
return $(this).text();
}).get()).to.eql(['First Name', 'Last Name']);
});
it('can be used inside cells', function() {
var collection = new Backbone.Collection([{}]);
var CellView = pageflow.TableCellView.extend({
update: function() {
this.$el.text(this.attributeTranslation('text'));
}
});
var tableView = new pageflow.TableView({
collection: collection,
columns: [
{
name: 'first_name',
cellView: CellView
}
],
attributeTranslationKeyPrefixes: [
'columns'
]
});
tableView.render();
expect(tableView.$el.find('tbody td')).to.have.$text('Test');
});
});
}); |
// Generated on 2015-09-08 using generator-angular 0.12.1
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Automatically load required Grunt tasks
require('jit-grunt')(grunt, {
useminPrepare: 'grunt-usemin',
ngtemplates: 'grunt-angular-templates',
cdnify: 'grunt-google-cdn'
});
// Configurable paths for the application
var appConfig = {
app: require('./bower.json').appPath || 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: appConfig,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
tasks: ['newer:jshint:all'],
options: {
livereload: '<%= connect.options.livereload %>'
}
},
jsTest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['newer:jshint:test', 'karma']
},
styles: {
files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'autoprefixer']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= yeoman.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect().use(
'/app/styles',
connect.static('./app/styles')
),
connect.static(appConfig.app)
];
}
}
},
test: {
options: {
port: 9001,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
dist: {
options: {
open: true,
base: '<%= yeoman.dist %>'
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git{,*/}*'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
server: {
options: {
map: true,
},
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the app
wiredep: {
app: {
src: ['<%= yeoman.app %>/index.html'],
ignorePath: /\.\.\//
},
test: {
devDependencies: true,
src: '<%= karma.unit.configFile %>',
ignorePath: /\.\.\//,
fileTypes:{
js: {
block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
detect: {
js: /'(.*\.js)'/gi
},
replace: {
js: '\'{{filePath}}\','
}
}
}
}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>',
flow: {
html: {
steps: {
js: ['concat', 'uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on filerev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
js: ['<%= yeoman.dist %>/scripts/{,*/}*.js'],
options: {
assetsDirs: [
'<%= yeoman.dist %>',
'<%= yeoman.dist %>/images',
'<%= yeoman.dist %>/styles'
],
patterns: {
js: [[/(images\/[^''""]*\.(png|jpg|jpeg|gif|webp|svg))/g, 'Replacing references to images']]
}
}
},
// The following *-min tasks will produce minified files in the dist folder
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
conservativeCollapse: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true
},
files: [{
expand: true,
cwd: '<%= yeoman.dist %>',
src: ['*.html'],
dest: '<%= yeoman.dist %>'
}]
}
},
ngtemplates: {
dist: {
options: {
module: 'sgasApp',
htmlmin: '<%= htmlmin.dist.options %>',
usemin: 'scripts/scripts.js'
},
cwd: '<%= yeoman.app %>',
src: 'views/{,*/}*.html',
dest: '.tmp/templateCache.js'
}
},
// ng-annotate tries to make the code safe for minification automatically
// by using the Angular long form for dependency injection.
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: '*.js',
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'.htaccess',
'*.html',
'images/{,*/}*.{webp}',
'styles/fonts/{,*/}*.*'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}, {
expand: true,
cwd: 'bower_components/bootstrap/dist',
src: 'fonts/*',
dest: '<%= yeoman.dist %>'
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'test/karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer:server',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve:' + target]);
});
grunt.registerTask('test', [
'clean:server',
'wiredep',
'concurrent:test',
'autoprefixer',
'connect:test',
'karma'
]);
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'ngtemplates',
'concat',
'ngAnnotate',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'filerev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
|
๏ปฟ/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'flash', 'ka', {
access: 'แกแแ แแแขแแก แฌแแแแแ',
accessAlways: 'แงแแแแแแแแก',
accessNever: 'แแ แแกแแ แแก',
accessSameDomain: 'แแแแแ แแแแแแ',
alignAbsBottom: 'แฉแแ แฉแแก แฅแแแแแแ แแแฌแแแแก แกแฌแแ แแแ แขแแฅแกแขแแกแแแแก',
alignAbsMiddle: 'แฉแแ แฉแแก แจแฃแ แแแฌแแแแก แกแฌแแ แแแ แขแแฅแกแขแแกแแแแก',
alignBaseline: 'แกแแแแแแกแ แฎแแแแก แกแฌแแ แแแ',
alignTextTop: 'แขแแฅแกแขแ แแแแแแแ',
bgcolor: 'แคแแแแก แคแแ แ',
chkFull: 'แแแแแ แแแ แแแแก แแแจแแแแ',
chkLoop: 'แฉแแชแแแแแ',
chkMenu: 'Flash-แแก แแแแแฃแก แแแจแแแแ',
chkPlay: 'แแแขแ แแแจแแแแ',
flashvars: 'แชแแแแแแแ Flash-แแกแแแแก',
hSpace: 'แฐแแ แแ. แกแแแ แชแ',
properties: 'Flash-แแก แแแ แแแแขแ แแแ',
propertiesTab: 'แแแ แแแแขแ แแแ',
quality: 'แฎแแ แแกแฎแ',
qualityAutoHigh: 'แแแฆแแแ (แแแขแแแแขแฃแ แ)',
qualityAutoLow: 'แซแแแแแ แแแแแแ',
qualityBest: 'แกแแฃแแแแแกแ',
qualityHigh: 'แแแฆแแแ',
qualityLow: 'แแแแแแ',
qualityMedium: 'แกแแจแฃแแแ',
scale: 'แแแกแจแขแแแแ แแแ',
scaleAll: 'แงแแแแแคแ แแก แฉแแแแแแ',
scaleFit: 'แแฃแกแขแ แฉแแกแแ',
scaleNoBorder: 'แฉแแ แฉแแก แแแ แแจแ',
title: 'Flash-แแก แแแ แแแแขแ แแแ',
vSpace: 'แแแ แข. แกแแแ แชแ',
validateHSpace: 'แฐแแ แแแแแขแแแฃแ แ แกแแแ แชแ แแ แฃแแแ แแงแแก แชแแ แแแแ.',
validateSrc: 'URL แแ แฃแแแ แแงแแก แชแแ แแแแ.',
validateVSpace: 'แแแ แขแแแแแฃแ แ แกแแแ แชแ แแ แฃแแแ แแงแแก แชแแ แแแแ.',
windowMode: 'แคแแแฏแ แแก แ แแแแแ',
windowModeOpaque: 'แแแฃแแญแแแ แแแแ',
windowModeTransparent: 'แแแแญแแแ แแแแ',
windowModeWindow: 'แคแแแฏแแ แ'
});
|
"use strict";
var _br = require('rocambole-linebreak');
var _tk = require('rocambole-token');
var _ws = require('rocambole-whitespace');
exports.format = function VariableDeclaration(node) {
var insideFor = node.parent.type === 'ForStatement';
node.declarations.forEach(function(declarator, i) {
var idStartToken = declarator.id.startToken;
// need to swap comma-first line break
var prevNonEmpty = _tk.findPrevNonEmpty(idStartToken);
if (i && prevNonEmpty.value === ',') {
if (_tk.isBr(prevNonEmpty.prev) || _tk.isBr(prevNonEmpty.prev.prev)) {
var beforeComma = _tk.findPrev(prevNonEmpty, function(t) {
return !_tk.isEmpty(t) && !_tk.isComment(t);
});
_ws.limit(prevNonEmpty, 0);
_tk.remove(prevNonEmpty);
_tk.after(beforeComma, prevNonEmpty);
}
}
if (!i && !_tk.isComment(_tk.findPrevNonEmpty(idStartToken))) {
// XXX: we don't allow line breaks or multiple spaces after "var"
// keyword for now (might change in the future)
_tk.removeEmptyAdjacentBefore(idStartToken);
} else if (!insideFor && declarator.init) {
_br.limit(idStartToken, 'VariableName');
}
_ws.limitBefore(idStartToken, 'VariableName');
if (declarator.init) {
_ws.limitAfter(declarator.id.endToken, 'VariableName');
var equalSign = _tk.findNext(declarator.id.endToken, '=');
var valueStart = _tk.findNextNonEmpty(equalSign);
_br.limitBefore(valueStart, 'VariableValue');
_ws.limitBefore(valueStart, 'VariableValue');
_br.limitAfter(declarator.endToken, 'VariableValue');
_ws.limitAfter(declarator.endToken, 'VariableValue');
}
});
// always add a space after the "var" keyword
_ws.limitAfter(node.startToken, 1);
};
exports.getIndentEdges = function(node, opts) {
var edges = [];
if (opts.MultipleVariableDeclaration && node.declarations.length > 1) {
edges.push(node);
}
node.declarations.forEach(function(declaration) {
var init = declaration.init;
if (init && opts['VariableDeclaration.' + init.type]) {
edges.push({
startToken: init.startToken,
endToken: init.endToken.next || node.endToken
});
}
});
return edges;
};
|
jQuery("#lists2").jqGrid({
url:'server.php?q=2',
datatype: "json",
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:55},
{name:'invdate',index:'invdate', width:90},
{name:'name',index:'name asc, invdate', width:100},
{name:'amount',index:'amount', width:80, align:"right", formatter: 'number'},
{name:'tax',index:'tax', width:80, align:"right", formatter: 'number'},
{name:'total',index:'total', width:80,align:"right", formatter: 'number'},
{name:'note',index:'note', width:150, sortable:false}
],
rowNum:10,
rowList:[10,20,30],
pager: '#pagers2',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
caption:"JSON Example",
footerrow : true,
userDataOnFooter : true,
altRows : true
});
jQuery("#lists2").jqGrid('navGrid','#pagers2',{edit:false,add:false,del:false});
|
function metisButton() {
window.prettyPrint && prettyPrint();
$.each($('.inner a.btn'), function () {
$(this).popover({
placement: 'bottom',
title: this.innerHTML,
content: this.outerHTML,
trigger: 'hover'
});
});
}
|
var Bookshelf = require('bookshelf').mysqlAuth;
var Coupon = Bookshelf.Model.extend({
tableName: 'coupons',
owner: function(){
return this.belongsTo('User');
}
});
module.exports = Bookshelf.model('Coupon', Coupon);
|
(function(root, factory) {
if(typeof define === 'function' && define.amd) {
define(['ember'], function(Ember) { return factory(Ember); });
} else if(typeof exports === 'object') {
factory(require('ember'));
} else {
factory(Ember);
}
})(this, function(Ember) {
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.