code
stringlengths 2
1.05M
|
---|
export default function getKillsPct(currentNumberOfKills, guildKills) {
if (currentNumberOfKills === 0) { return 0; }
return (guildKills * 100) / currentNumberOfKills;
}
|
'use strict';
var path = require('path');
var stormpath = require('stormpath');
var stormpathConfig = require('stormpath-config');
var configStrategy = stormpathConfig.strategy;
// Factory method to create a client using a configuration only.
// The configuration provided to this factory is the final configuration.
function ClientFactory(config) {
return new stormpath.Client(
new stormpathConfig.Loader([
new configStrategy.ExtendConfigStrategy(config)
])
);
}
module.exports = function (config) {
var configLoader = stormpath.configLoader(config);
// Load our integration config.
configLoader.prepend(new configStrategy.LoadFileConfigStrategy(path.join(__dirname, '/config.yml'), true));
configLoader.add(new configStrategy.EnrichClientFromRemoteConfigStrategy(ClientFactory));
configLoader.add(new configStrategy.EnrichIntegrationFromRemoteConfigStrategy(ClientFactory));
return new stormpath.Client(configLoader);
};
|
import React, { Component } from 'react';
import styled from 'styled-components';
import { connect } from 'react-redux';
import { RefreshControl, ActivityIndicator } from 'react-native';
import { ListItem } from 'react-native-elements';
import ActionSheet from 'react-native-actionsheet';
import { SafeAreaView } from 'react-navigation';
import { RestClient } from 'api';
import {
ViewContainer,
UserProfile,
LoadingMembersList,
MembersList,
SectionList,
ParallaxScroll,
EntityInfo,
} from 'components';
import { emojifyText, t, openURLInView } from 'utils';
import { colors, fonts, getHeaderForceInset } from 'config';
const StyledSafeAreaView = styled(SafeAreaView).attrs({
forceInset: getHeaderForceInset('Organization'),
})`
background-color: ${colors.primaryDark};
`;
const DescriptionListItem = styled(ListItem).attrs({
subtitleStyle: {
color: colors.greyDark,
...fonts.fontPrimary,
},
subtitleNumberOfLines: 0,
})``;
const LoadingMembersContainer = styled.View`
padding: 5px;
`;
class OrganizationProfile extends Component {
props: {
org: Object,
orgId: String,
orgMembers: Array,
orgMembersPagination: Object,
navigation: Object,
locale: string,
getOrgById: Function,
getOrgMembers: Function,
};
state: {
refreshing: boolean,
};
constructor(props) {
super(props);
this.state = {
refreshing: false,
};
}
componentDidMount() {
const { org, orgId, getOrgById, getOrgMembers } = this.props;
if (!org.name) {
getOrgById(orgId);
}
getOrgMembers(orgId);
}
componentWillReceiveProps() {
this.setState({ refreshing: false });
}
refresh = () => {
this.setState({ refreshing: true });
const { orgId, getOrgById, getOrgMembers } = this.props;
getOrgById(orgId);
getOrgMembers(orgId, { forceRefresh: true });
};
showMenuActionSheet = () => {
this.ActionSheet.show();
};
handleActionSheetPress = index => {
if (index === 0) {
openURLInView(this.props.org.html_url);
}
};
renderLoadingMembers = () => {
if (this.props.orgMembersPagination.nextPageUrl === null) {
return null;
}
return (
<LoadingMembersContainer>
<ActivityIndicator animating size="small" />
</LoadingMembersContainer>
);
};
render() {
const {
org,
orgId,
orgMembers,
orgMembersPagination,
navigation,
locale,
} = this.props;
const { refreshing } = this.state;
const initialOrganization = this.props.navigation.state.params.organization;
const organizationActions = [t('Open in Browser', locale)];
const isPendingMembers =
orgMembers.length === 0 && orgMembersPagination.isFetching;
return (
<ViewContainer>
<StyledSafeAreaView />
<ParallaxScroll
renderContent={() => (
<UserProfile
type="org"
initialUser={initialOrganization}
user={
initialOrganization.login === org.login
? org
: initialOrganization
}
navigation={navigation}
/>
)}
refreshControl={
<RefreshControl onRefresh={this.refresh} refreshing={refreshing} />
}
stickyTitle={org.name}
navigateBack
navigation={navigation}
showMenu
menuAction={() => this.showMenuActionSheet()}
>
{isPendingMembers && (
<LoadingMembersList title={t('MEMBERS', locale)} />
)}
{!isPendingMembers && (
<MembersList
title={t('MEMBERS', locale)}
members={orgMembers}
noMembersMessage={t('No members found', locale)}
navigation={navigation}
onEndReached={() =>
this.props.getOrgMembers(orgId, { loadMore: true })
}
onEndReachedThreshold={0.5}
ListFooterComponent={this.renderLoadingMembers}
/>
)}
{!!org.description &&
org.description !== '' && (
<SectionList title={t('DESCRIPTION', locale)}>
<DescriptionListItem
subtitle={emojifyText(org.description)}
hideChevron
/>
</SectionList>
)}
{org && (
<EntityInfo entity={org} navigation={navigation} locale={locale} />
)}
</ParallaxScroll>
<ActionSheet
ref={o => {
this.ActionSheet = o;
}}
title={t('Organization Actions', locale)}
options={[...organizationActions, t('Cancel', locale)]}
cancelButtonIndex={1}
onPress={this.handleActionSheetPress}
/>
</ViewContainer>
);
}
}
const mapStateToProps = (state, ownProps) => {
const {
auth: { user, locale },
pagination: { ORGS_GET_MEMBERS },
entities: { orgs, users },
} = state;
const orgId = ownProps.navigation.state.params.organization.login;
const org = orgs[orgId] || ownProps.navigation.state.params.organization;
const orgMembersPagination = ORGS_GET_MEMBERS[orgId] || {
ids: [],
isFetching: true,
};
const orgMembers = orgMembersPagination.ids.map(id => users[id]);
return {
user,
org,
orgId,
orgMembers,
orgMembersPagination,
locale,
};
};
const mapDispatchToProps = {
getOrgById: RestClient.orgs.getById,
getOrgMembers: RestClient.orgs.getMembers,
};
export const OrganizationProfileScreen = connect(
mapStateToProps,
mapDispatchToProps
)(OrganizationProfile);
|
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["react-syntax-highlighter_languages_highlight_scala"],{
/***/ "./node_modules/highlight.js/lib/languages/scala.js":
/*!**********************************************************!*\
!*** ./node_modules/highlight.js/lib/languages/scala.js ***!
\**********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = function(hljs) {
var ANNOTATION = { className: 'meta', begin: '@[A-Za-z]+' };
// used in strings for escaping/interpolation/substitution
var SUBST = {
className: 'subst',
variants: [
{begin: '\\$[A-Za-z0-9_]+'},
{begin: '\\${', end: '}'}
]
};
var STRING = {
className: 'string',
variants: [
{
begin: '"', end: '"',
illegal: '\\n',
contains: [hljs.BACKSLASH_ESCAPE]
},
{
begin: '"""', end: '"""',
relevance: 10
},
{
begin: '[a-z]+"', end: '"',
illegal: '\\n',
contains: [hljs.BACKSLASH_ESCAPE, SUBST]
},
{
className: 'string',
begin: '[a-z]+"""', end: '"""',
contains: [SUBST],
relevance: 10
}
]
};
var SYMBOL = {
className: 'symbol',
begin: '\'\\w[\\w\\d_]*(?!\')'
};
var TYPE = {
className: 'type',
begin: '\\b[A-Z][A-Za-z0-9_]*',
relevance: 0
};
var NAME = {
className: 'title',
begin: /[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/,
relevance: 0
};
var CLASS = {
className: 'class',
beginKeywords: 'class object trait type',
end: /[:={\[\n;]/,
excludeEnd: true,
contains: [
{
beginKeywords: 'extends with',
relevance: 10
},
{
begin: /\[/,
end: /\]/,
excludeBegin: true,
excludeEnd: true,
relevance: 0,
contains: [TYPE]
},
{
className: 'params',
begin: /\(/,
end: /\)/,
excludeBegin: true,
excludeEnd: true,
relevance: 0,
contains: [TYPE]
},
NAME
]
};
var METHOD = {
className: 'function',
beginKeywords: 'def',
end: /[:={\[(\n;]/,
excludeEnd: true,
contains: [NAME]
};
return {
keywords: {
literal: 'true false null',
keyword: 'type yield lazy override def with val var sealed abstract private trait object if forSome for while throw finally protected extends import final return else break new catch super class case package default try this match continue throws implicit'
},
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
STRING,
SYMBOL,
TYPE,
METHOD,
CLASS,
hljs.C_NUMBER_MODE,
ANNOTATION
]
};
};
/***/ })
}]);
//# sourceMappingURL=react-syntax-highlighter_languages_highlight_scala.js.map
|
/**
* Modules in this bundle
*
* loxe:
* license: MIT
* author: ahomu
* version: 0.5.0
*
* object-assign:
* license: MIT
* author: Sindre Sorhus <sindresorhus@gmail.com>
* maintainers: sindresorhus <sindresorhus@gmail.com>
* version: 3.0.0
*
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Loxe = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function ToObject(val) {
if (val == null) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function ownEnumerableKeys(obj) {
var keys = Object.getOwnPropertyNames(obj);
if (Object.getOwnPropertySymbols) {
keys = keys.concat(Object.getOwnPropertySymbols(obj));
}
return keys.filter(function (key) {
return propIsEnumerable.call(obj, key);
});
}
module.exports = Object.assign || function (target, source) {
var from;
var keys;
var to = ToObject(target);
for (var s = 1; s < arguments.length; s++) {
from = arguments[s];
keys = ownEnumerableKeys(Object(from));
for (var i = 0; i < keys.length; i++) {
to[keys[i]] = from[keys[i]];
}
}
return to;
};
},{}],2:[function(require,module,exports){
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _Subject = require('./Subject');
var _implementsReflectionImpl = require('../implements/ReflectionImpl');
/**
* @typedef {Object} ActionData
* @property {string} key
* @property {*} value
*/
/**
* The role of this class is the Flux `Action`.
* Implements the behavior methods subclasses that inherit from it.
* `publish` method is executed, and data flows from the `Observable` to `Store`.
*
* @class Action
*/
var Action = (function () {
function Action() {
_classCallCheck(this, Action);
this.eventStream$ = _Subject['default'].stream();
}
_createClass(Action, [{
key: 'publish',
/**
* @param {string} eventName
* @param {*} payload
*/
value: function publish(eventName, payload) {
this.eventStream$.next({
event: eventName,
payload: payload
});
}
}, {
key: 'do',
/**
* alias of `publish()`
* @param {string} eventName
* @param {*} payload
*/
value: function _do(eventName, payload) {
return this.publish(eventName, payload);
}
}, {
key: 'getClassName',
/**
* @returns {string}
*/
value: function getClassName() {
return _implementsReflectionImpl['default'].getClassName.apply(this);
}
}]);
return Action;
})();
exports['default'] = Action;
/**
* @type {Kefir.Stream<ActionData>}
* @private
*/
},{"../implements/ReflectionImpl":6,"./Subject":5}],3:[function(require,module,exports){
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _react = (window.React);
var React = _react;
var _implementsReflectionImpl = require('../implements/ReflectionImpl');
var _Action = require('./Action');
var _Store = require('./Store');
/**
* `Domain` that manages the `Store` and `Action`.
* Each feature of Flux provides to `Component`,
* using the Context feature of the React.
*
* @class Domain
*/
var Domain = (function () {
function Domain() {
_classCallCheck(this, Domain);
this.stores = new Map();
this.actions = new Map();
}
_createClass(Domain, [{
key: 'registerAction',
/**
* @param {Action} action
*/
value: function registerAction(action) {
if (!(action instanceof _Action['default'])) {
throw new Error('Given instance of ' + action.getClassName() + ' is not Action');
}
var ActionClass = Object.getPrototypeOf(action).constructor;
if (this.actions.has(ActionClass)) {
throw new Error('' + action.getClassName() + ' already exists in this domain.');
} else {
this.actions.set(ActionClass, action);
}
}
}, {
key: 'getAction',
/**
* @param {Function} ActionClass
* @returns {Action}
*/
value: function getAction(ActionClass) {
if (!this.actions.has(ActionClass)) {
throw new Error('' + ActionClass.constructor.name + ' is not registered as Action.');
}
return this.actions.get(ActionClass);
}
}, {
key: 'registerStore',
/**
* @param {Store} store
*/
value: function registerStore(store) {
if (!(store instanceof _Store['default'])) {
throw new Error('Given instance of ' + store.getClassName() + ' is not Store');
}
var StoreClass = Object.getPrototypeOf(store).constructor;
if (this.stores.has(StoreClass)) {
throw new Error('' + store.getClassName() + ' already exists in this domain.');
} else {
this.stores.set(StoreClass, store);
}
}
}, {
key: 'getStore',
/**
* @param {Function} StoreClass
* @returns {Store}
*/
value: function getStore(StoreClass) {
if (!this.stores.has(StoreClass)) {
throw new Error('' + StoreClass.constructor.name + ' is not registered as Store.');
}
return this.stores.get(StoreClass);
}
}, {
key: 'subscribeActionObservableFromStore',
/**
* All `Store` subscribe to all `Action`'s Observable
*/
value: function subscribeActionObservableFromStore() {
var _this = this;
this.stores.forEach(function (store) {
_this.actions.forEach(function (action) {
store.plugAction(action);
});
});
}
}, {
key: 'mountRootComponent',
/**
* @param {Component} Component
* @param {Element} mountNode
* @returns {ReactComponent}
*/
value: function mountRootComponent(Component, mountNode) {
this.subscribeActionObservableFromStore();
return React.render(React.createElement(Component, { domain: this }), mountNode);
}
}, {
key: 'getObservables',
/**
* `getObservables` method not implemented anything initially.
* This method will call from the `provideObservables`.
* Sync the prop component the returned object as a template.
* Good for most `observables` caching as a property value.
*
* @example
* ```
* observables = null;
*
* getObservables() {
* if (!this.observables) {
* this.observables = {
* update$ : this.getStore(AppStore).items$
* };
* }
*
* return this.observables;
* }
* ```
*
* @returns {Object<string, Rx.Observable>}
*/
value: function getObservables() {
throw new Error(this.getClassName() + ':`getObservables` is abstract method.' + 'You should implements in sub-class');
}
}, {
key: 'getClassName',
/**
* @returns {string}
*/
value: function getClassName() {
return _implementsReflectionImpl['default'].getClassName.apply(this);
}
}]);
return Domain;
})();
exports['default'] = Domain;
/**
* @type {Map<Function, Store>}
*/
/**
* @type {Map<Function, Action>}
*/
},{"../implements/ReflectionImpl":6,"./Action":2,"./Store":4}],4:[function(require,module,exports){
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _Subject = require('./Subject');
var _implementsReflectionImpl = require('../implements/ReflectionImpl');
var _implementsSubscriberImpl = require('../implements/SubscriberImpl');
/**
* The role of this class is the Flux `Store`.
* Subscribe the anonymous Observable provided the Action.
* Itself has any Observable to expose Domain property.
*
* @example
* ```
* import {Store, Subject} from 'loxe';
*
* export default class AppStore extends Store {
* _items = [];
* items$ = Subject.property([]);
* initialize() {
* this.subscribe('ADD_ITEM', (item) => {
* this._items.unshift(item);
* this.items$.next(this._items);
* });
* }
* }
* ```
*
* @class Store
*/
var Store = (function () {
function Store() {
_classCallCheck(this, Store);
this.plugStream$ = _Subject['default'].stream();
}
_createClass(Store, [{
key: 'plugAction',
/**
*
* @param {Action} action
*/
value: function plugAction(action) {
this.subscribe(action.eventStream$, this.plugStream$.next.bind(this.plugStream$));
}
}, {
key: 'getEvent',
/**
*
* @param {string} eventName
* @returns {Rx.Observable<*>}
*/
value: function getEvent(eventName) {
return this.plugStream$.filter(function (_ref) {
var event = _ref.event;
return event === eventName;
}).map(function (_ref2) {
var payload = _ref2.payload;
return payload;
});
}
}, {
key: 'subscribeEvent',
/**
* @param {string} eventName
* @param {Function} observer
*/
value: function subscribeEvent(eventName, observer) {
this.subscribe(this.getEvent(eventName), observer);
}
}, {
key: 'subscribe',
/**
* Delegate to `SubscriberImpl.subscribe()`
* Subscribe to if the first argument is a string, it filtered as the event name.
*
* @param {string|Rx.Observable<ActionData>} observable$
* @param {function} observer
*/
value: function subscribe(observable$, observer) {
if (typeof observable$ === 'string') {
observable$ = this.getEvent(observable$);
}
_implementsSubscriberImpl['default'].subscribe.apply(this, [observable$, observer]);
}
}, {
key: 'unsubscribeAll',
/**
* Delegate to `SubscriberImpl.unsubscribeAll()`
*/
value: function unsubscribeAll() {
_implementsSubscriberImpl['default'].unsubscribeAll.apply(this);
}
}, {
key: 'getClassName',
/**
* @returns {string}
*/
value: function getClassName() {
return _implementsReflectionImpl['default'].getClassName.apply(this);
}
}]);
return Store;
})();
exports['default'] = Store;
/**
*
* @type {Kefir.Stream<ActionData>}
* @private
*/
},{"../implements/ReflectionImpl":6,"../implements/SubscriberImpl":7,"./Subject":5}],5:[function(require,module,exports){
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var RxBuilder = (function () {
/**
* @constructor
* @param {Rx} Rx
*/
function RxBuilder(Rx) {
_classCallCheck(this, RxBuilder);
this.MyRx = null;
this.MyRx = Rx;
}
_createClass(RxBuilder, [{
key: 'stream',
/**
* Subject for `Component` ui events & `Action` publish events.
*
* @returns {Rx.Subject}
*/
value: function stream() {
return this.create(this.MyRx.Subject);
}
}, {
key: 'property',
/**
* Subject for `Store` data property.
* Even when starting to subscribe to retained latest value will be published.
*
* @param {*} initialValue
* @returns {Rx.BehaviorSubject}
*/
value: function property(initialValue) {
return this.create(this.MyRx.BehaviorSubject, initialValue);
}
}, {
key: 'create',
/**
* @param {Rx.Subject} BaseClass
* @param {*} [initialValue]
* @returns {Rx.Subject}
*/
value: function create(BaseClass, initialValue) {
function _subject() {
_subject.onNext.apply(_subject, arguments);
}
for (var key in BaseClass.prototype) {
_subject[key] = BaseClass.prototype[key];
}
_subject.next = _subject.onNext;
_subject['throw'] = _subject.onError;
_subject['return'] = _subject.onCompleted;
BaseClass.call(_subject, initialValue);
return _subject;
}
}]);
return RxBuilder;
})();
exports.RxBuilder = RxBuilder;
var KefirBuilder = (function () {
/**
* @constructor
* @param {Kefir} Kefir
*/
function KefirBuilder(Kefir) {
_classCallCheck(this, KefirBuilder);
this.MyKefir = null;
this.MyKefir = Kefir;
}
_createClass(KefirBuilder, [{
key: 'stream',
/**
* Subject for `Component` ui events & `Action` publish events.
*
* @returns {Kefir.Stream}
*/
value: function stream() {
return this.create(this.MyKefir.Stream);
}
}, {
key: 'property',
/**
* Subject for `Store` data property.
* Even when starting to subscribe to retained latest value will be published.
*
* @param {*} initialValue
* @returns {Kefir.Observable}
*/
value: function property(initialValue) {
return this.create(this.MyKefir.Property, initialValue);
}
}, {
key: 'create',
/**
* @param {Kefir.Stream} BaseClass
* @param {*} [initialValue]
* @returns {Observable}
*/
value: function create(BaseClass, initialValue) {
function _subject() {
_subject._emitValue.apply(_subject, arguments);
}
for (var key in BaseClass.prototype) {
_subject[key] = BaseClass.prototype[key];
}
_subject.next = _subject._emitValue;
_subject['throw'] = _subject._emitError;
_subject['return'] = _subject._emitEnd;
BaseClass.call(_subject);
if (initialValue !== undefined) {
_subject._active = true;
_subject._currentEvent = { type: 'value', value: initialValue, current: true };
}
return _subject;
}
}]);
return KefirBuilder;
})();
exports.KefirBuilder = KefirBuilder;
/**
* @class Subject
*/
var Subject = (function () {
function Subject() {
_classCallCheck(this, Subject);
}
_createClass(Subject, null, [{
key: 'stream',
/**
* @returns {Observable}
*/
value: function stream() {
return Subject._builder.stream.apply(Subject._builder, arguments);
}
}, {
key: 'property',
/**
* @param {*} initialValue
* @returns {Observable}
*/
value: function property() {
return Subject._builder.property.apply(Subject._builder, arguments);
}
}, {
key: 'combineTemplate',
/**
* @param {Object} templateObject
* @returns {Observable}
*/
value: function combineTemplate() {
return Subject._combineTemplate.apply(Subject._combineTemplate, arguments);
}
}, {
key: 'setBuilder',
/**
* @param {RxBuilder|KefirBuilder} builderInstance
*/
value: function setBuilder(builderInstance) {
Subject._builder = builderInstance;
}
}, {
key: 'setCombineTemplate',
/**
* @param {Function} combineTemplateFn
*/
value: function setCombineTemplate(combineTemplateFn) {
Subject._combineTemplate = combineTemplateFn;
}
}, {
key: 'KefirBuilder',
value: KefirBuilder,
enumerable: true
}, {
key: 'RxBuilder',
value: RxBuilder,
enumerable: true
}]);
return Subject;
})();
exports['default'] = Subject;
/**
* @type {Rx}
*/
/**
* @type {Kefir}
*/
},{}],6:[function(require,module,exports){
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
/**
* @class ReflectionImpl
*/
var ReflectionImpl = (function () {
function ReflectionImpl() {
_classCallCheck(this, ReflectionImpl);
}
_createClass(ReflectionImpl, null, [{
key: 'getClassName',
/**
* Get `Function#name`
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
*
* @returns {string}
*/
value: function getClassName() {
// < IE9 is not support `Object.getPrototypeOf`
return Object.getPrototypeOf(this).constructor.name;
}
}]);
return ReflectionImpl;
})();
exports['default'] = ReflectionImpl;
},{}],7:[function(require,module,exports){
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
/**
* @class SubscriberImpl
*/
var SubscriberImpl = (function () {
function SubscriberImpl() {
_classCallCheck(this, SubscriberImpl);
this._subscriptions = [];
}
_createClass(SubscriberImpl, null, [{
key: 'subscribe',
/**
* Subscribe to observable, that holds the subscription.
* Become a memory leak if you subscribe using this method,
* the end of instance lifecycle manually subscription must discard.
*
* @param {Observable} observable$
* @param {function} observer
*/
value: function subscribe(observable$, observer) {
if (observable$ == null) {
return;
}
var subscription = undefined;
if (observable$.subscribe) {
// Rx
subscription = observable$.subscribe(observer);
} else {
// Bacon, Kefir
observable$.onValue(observer);
subscription = [observable$, observer];
}
this._subscriptions = this._subscriptions || [];
this._subscriptions.push(subscription);
}
}, {
key: 'unsubscribeAll',
/**
* To discard all subscriptions of the observable.
*/
value: function unsubscribeAll() {
this._subscriptions = this._subscriptions || [];
this._subscriptions.forEach(function (subscription) {
if (subscription.dispose) {
// Rx
subscription.dispose();
} else {
// Bacon, Kefir
subscription[0].offValue(subscription[1]);
}
});
this._subscriptions = [];
}
}]);
return SubscriberImpl;
})();
exports['default'] = SubscriberImpl;
/**
* @type {Array<Subscription>}
*/
},{}],8:[function(require,module,exports){
'use strict';
var _classesAction = require('./classes/Action');
var _classesDomain = require('./classes/Domain');
var _classesStore = require('./classes/Store');
var _classesSubject = require('./classes/Subject');
var _providersProvideContext = require('./providers/provideContext');
var _providersProvideObservables = require('./providers/provideObservables');
var _providersProvideActions = require('./providers/provideActions');
exports.Action = _classesAction['default'];
exports.Domain = _classesDomain['default'];
exports.Store = _classesStore['default'];
exports.Subject = _classesSubject['default'];
exports.provideActions = _providersProvideActions['default'];
exports.provideContext = _providersProvideContext['default'];
exports.provideObservables = _providersProvideObservables['default'];
},{"./classes/Action":2,"./classes/Domain":3,"./classes/Store":4,"./classes/Subject":5,"./providers/provideActions":9,"./providers/provideContext":10,"./providers/provideObservables":11}],9:[function(require,module,exports){
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
var _react = (window.React);
var React = _react;
var _objectAssign = require('object-assign');
var assign = _objectAssign;
var _implementsReflectionImpl = require('../implements/ReflectionImpl');
var _utilsCopyStatics = require('../utils/copy-statics');
var _utilsDecoratable = require('../utils/decoratable');
/**
* @param {Component} Component
* @param {Array<Action>} ActionClasses
* @returns {ActionsProvider}
*/
function provideActions(Component, ActionClasses) {
/**
* @class ActionsProvider
*/
var ActionsProvider = (function (_React$Component) {
function ActionsProvider() {
_classCallCheck(this, ActionsProvider);
if (_React$Component != null) {
_React$Component.apply(this, arguments);
}
}
_inherits(ActionsProvider, _React$Component);
_createClass(ActionsProvider, [{
key: 'getDisplayName',
/**
* for react dev-tools
* @returns {string}
*/
value: function getDisplayName() {
return _implementsReflectionImpl['default'].getClassName.apply(this);
}
}, {
key: 'render',
/**
*
* @returns {*}
*/
value: function render() {
var _this = this;
if (!this.context.getAction) {
throw new Error('The context does not have `getAction`.' + 'Make sure the ancestral component provides ' + 'the domain context, use `@provideContext`.');
}
var actions = {};
ActionClasses.reduce(function (acc, ActionClass) {
acc[ActionClass.name] = _this.context.getAction(ActionClass);
}, actions);
return React.createElement(Component, assign(actions, this.props));
}
}], [{
key: '_originalComponent',
/**
* @type {Component}
* @private
*/
value: Component,
enumerable: true
}, {
key: 'contextTypes',
/**
* @type {Object<string, function>}
*/
value: {
getAction: React.PropTypes.func.isRequired
},
enumerable: true
}]);
return ActionsProvider;
})(React.Component);
(0, _utilsCopyStatics['default'])(Component, ActionsProvider);
return ActionsProvider;
}
exports['default'] = (0, _utilsDecoratable['default'])(provideActions);
},{"../implements/ReflectionImpl":6,"../utils/copy-statics":12,"../utils/decoratable":13,"object-assign":1}],10:[function(require,module,exports){
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
var _react = (window.React);
var React = _react;
var _classesDomain = require('../classes/Domain');
var _implementsReflectionImpl = require('../implements/ReflectionImpl');
var _utilsCopyStatics = require('../utils/copy-statics');
var _utilsDecoratable = require('../utils/decoratable');
/**
* @param {Component} Component
* @returns {ContextProvider}
*/
function provideContext(Component) {
/**
* @class ContextProvider
*/
var ContextProvider = (function (_React$Component) {
function ContextProvider() {
_classCallCheck(this, ContextProvider);
if (_React$Component != null) {
_React$Component.apply(this, arguments);
}
this.childContexts = null;
}
_inherits(ContextProvider, _React$Component);
_createClass(ContextProvider, [{
key: 'componentWillMount',
/**
*
*/
value: function componentWillMount() {
if (!this.props.domain) {
throw new Error('@provideContext higher-ordered component must have `props.domain`');
}
this.childContexts = {
getAction: this.props.domain.getAction.bind(this.props.domain),
getObservables: this.props.domain.getObservables.bind(this.props.domain)
};
}
}, {
key: 'getDisplayName',
/**
* for react dev-tools
* @returns {string}
*/
value: function getDisplayName() {
return _implementsReflectionImpl['default'].getClassName.apply(this);
}
}, {
key: 'getChildContext',
/**
* @returns {Object<string, function>}
*/
value: function getChildContext() {
return this.childContexts;
}
}, {
key: 'render',
/**
* @returns {ReactElement}
*/
value: function render() {
return React.createElement(Component, this.props);
}
}], [{
key: '_originalComponent',
/**
* @type {Component}
* @private
*/
value: Component,
enumerable: true
}, {
key: 'propTypes',
/**
* @type {Object<string, function>}
*/
value: {
domain: React.PropTypes.instanceOf(_classesDomain['default']).isRequired
},
enumerable: true
}, {
key: 'childContextTypes',
/**
* @type {Object<string, function>}
*/
value: {
getAction: React.PropTypes.func.isRequired,
getObservables: React.PropTypes.func.isRequired
},
enumerable: true
}]);
return ContextProvider;
})(React.Component);
(0, _utilsCopyStatics['default'])(Component, ContextProvider);
return ContextProvider;
}
exports['default'] = (0, _utilsDecoratable['default'])(provideContext);
/**
* @type {Object<string, function>}
*/
},{"../classes/Domain":3,"../implements/ReflectionImpl":6,"../utils/copy-statics":12,"../utils/decoratable":13}],11:[function(require,module,exports){
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
var _react = (window.React);
var React = _react;
var _objectAssign = require('object-assign');
var assign = _objectAssign;
var _classesSubject = require('../classes/Subject');
var _implementsSubscriberImpl = require('../implements/SubscriberImpl');
var _implementsReflectionImpl = require('../implements/ReflectionImpl');
var _utilsCopyStatics = require('../utils/copy-statics');
var _utilsDecoratable = require('../utils/decoratable');
/**
* @param {Component} Component
* @param {Function} receiveObservablesHandler
* @returns {ActionsProvider}
*/
function provideObservables(Component, receiveObservablesHandler) {
/**
* @class ObservablesProvider
*/
var ObservablesProvider = (function (_React$Component) {
function ObservablesProvider() {
_classCallCheck(this, ObservablesProvider);
if (_React$Component != null) {
_React$Component.apply(this, arguments);
}
}
_inherits(ObservablesProvider, _React$Component);
_createClass(ObservablesProvider, [{
key: 'subscribe',
/**
* Delegate to `SubscriberImpl.subscribe()`
*
* @param {Observable} observable$
* @param {function} observer
*/
value: function subscribe(observable$, observer) {
_implementsSubscriberImpl['default'].subscribe.apply(this, [observable$, observer]);
}
}, {
key: 'unsubscribeAll',
/**
* Delegate to `SubscriberImpl.unsubscribeAll()`
*/
value: function unsubscribeAll() {
_implementsSubscriberImpl['default'].unsubscribeAll.apply(this);
}
}, {
key: 'getDisplayName',
/**
* for react dev-tools
* @returns {string}
*/
value: function getDisplayName() {
return _implementsReflectionImpl['default'].getClassName.apply(this);
}
}, {
key: 'componentWillMount',
/**
*
*/
value: function componentWillMount() {
if (!this.context.getObservables) {
throw new Error('The context does not have `getObservables`.' + 'Make sure the ancestral component provides ' + 'the domain context, use `@provideContext`.');
}
var observables = this.context.getObservables();
var stateObject = receiveObservablesHandler(observables);
var combined = _classesSubject['default'].combineTemplate(stateObject);
this.subscribe(combined, this.setState.bind(this));
}
}, {
key: 'componentWillUnmount',
/**
* To notify that the component unmounted to the domain.
*/
value: function componentWillUnmount() {
this.unsubscribeAll();
}
}, {
key: 'render',
/**
* Values that from Observables are saved in `state`.
* Delegate to components within props.
*
* @returns {*}
*/
value: function render() {
return React.createElement(Component, assign({}, this.props, this.state));
}
}], [{
key: '_originalComponent',
/**
* @type {Component}
* @private
*/
value: Component,
enumerable: true
}, {
key: 'contextTypes',
/**
* @type {Object<string, function>}
*/
value: {
getObservables: React.PropTypes.func.isRequired
},
enumerable: true
}]);
return ObservablesProvider;
})(React.Component);
(0, _utilsCopyStatics['default'])(Component, ObservablesProvider);
return ObservablesProvider;
}
exports['default'] = (0, _utilsDecoratable['default'])(provideObservables);
},{"../classes/Subject":5,"../implements/ReflectionImpl":6,"../implements/SubscriberImpl":7,"../utils/copy-statics":12,"../utils/decoratable":13,"object-assign":1}],12:[function(require,module,exports){
'use strict';
exports['default'] = copyStatics;
var RESERVED_PROPS = {
arguments: true,
caller: true,
key: true,
length: true,
name: true,
prototype: true,
ref: true,
type: true
};
function copyStatics(fromClass, toObject) {
// copy statics
Object.getOwnPropertyNames(fromClass).filter(function (key) {
return fromClass.hasOwnProperty(key) && !RESERVED_PROPS[key];
}).forEach(function (key) {
toObject[key] = fromClass[key];
});
}
},{}],13:[function(require,module,exports){
'use strict';
exports['default'] = decoratable;
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }
/**
* can be used as decorators
* Main purpose the higher-order component to use as a Decorator.
*
* https://github.com/wycats/javascript-decorators
*
* ```
* let decoratableSubject = decoratable(subject);
* @decoratableSubject(foo, bar, baz)
* class AcmeClass {
* // acme implements
* }
*
* // same as below
*
* class AcmeClass {
* // acme implements
* }
* subject(AcmeClass, foo, bar, baz);
* ```
*
* @param {Function} subjectFunc
*/
function decoratable(subjectFunc) {
return function () {
for (var _len = arguments.length, initialArgs = Array(_len), _key = 0; _key < _len; _key++) {
initialArgs[_key] = arguments[_key];
}
// Decorator
if (initialArgs.length < subjectFunc.length) {
var _ret = (function () {
var diff = subjectFunc.length - initialArgs.length;
return {
v: function decorateWrapper() {
for (var _len2 = arguments.length, targetKeyDescriptor = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
targetKeyDescriptor[_key2] = arguments[_key2];
}
return subjectFunc.apply(null, [].concat(_toConsumableArray(targetKeyDescriptor.slice(0, diff)), initialArgs));
}
};
})();
if (typeof _ret === 'object') return _ret.v;
}
// Normally
return subjectFunc.apply(null, initialArgs);
};
}
},{}]},{},[8])(8)
});
|
define_ibex_controller({
name: "Message",
jqueryWidget: {
_init: function () {
this.cssPrefix = this.options._cssPrefix;
this.utils = this.options._utils;
this.finishedCallback = this.options._finishedCallback;
this.html = this.options.html;
this.element.addClass(this.cssPrefix + "message");
this.element.append(htmlCodeToDOM(this.html));
// Bit of copy/pasting from 'Separator' here.
this.transfer = dget(this.options, "transfer", "click");
assert((! this.transfer) || this.transfer == "click" || this.transfer == "keypress" || typeof(this.transfer) == "number",
"Value of 'transfer' option of Message must either be the string 'click' or a number");
if (this.transfer == "click") {
this.continueMessage = dget(this.options, "continueMessage", "Click here to continue.");
this.consentRequired = dget(this.options, "consentRequired", false);
this.consentMessage = dget(this.options, "consentMessage", "I have read the above and agree to do the experiment.");
this.consentErrorMessage = dget(this.options, "consentErrorMessage", "You must consent before continuing.");
// Add the consent checkbox if necessary.
var checkbox = null;
if (this.consentRequired) {
var names = { };
var checkbox;
var message;
var dom =
$(document.createElement("form"))
.append($(document.createElement("table"))
.css('border', 'none').css('padding', 0).css('margin', 0)
.append($(document.createElement("tr"))
.append($(document.createElement("td"))
.css('border', 0).css('padding-left', 0).css('margin-left', 0)
.append(checkbox = $(document.createElement("input"))
.attr('id', 'consent_checkbox')
.attr('type', 'checkbox')
.attr('checked', 0)))
.append(message = $(document.createElement("td"))
.css('border', 0).css('margin-left', 0).css('padding-left', 0)
.append($("<label>")
.attr('for', 'consent_checkbox')
.text(this.consentMessage)))));
this.element.append(dom);
// Change cursor to pointer when hovering over the message (have to use JS because
// IE doesn't support :hover for anything other than links).
message.mouseover(function () {
message.css('cursor', "default");
});
}
var t = this;
// Get a proper lexical scope for the checkbox element so we can capture it in a closure.
// ALEX: Looking at this again, I don't see why it's necessary to create a local scope here
// but I am leaving it in as I may be missing something and it won't do any harm.
(function (checkbox) {
t.element.append(
$(document.createElement("p"))
.css('clear', 'left')
.append($(document.createElement("a"))
.attr('href', '')
.addClass(t.cssPrefix + 'continue-link')
.text("\u2192 " + t.continueMessage)
.click(function () {
if ((! checkbox) || checkbox.attr('checked'))
t.finishedCallback();
else
alert(t.consentErrorMessage);
return false;
}))
);
})(checkbox);
}
else if (this.transfer == "keypress") {
var t = this;
this.safeBind($(document), 'keydown', function () {
t.finishedCallback(null);
return false;
});
}
else if (typeof(this.transfer) == "number") {
assert(! this.consentRequired, "The 'consentRequired' option of the Message controller can only be set to true if the 'transfer' option is set to 'click'.");
this.utils.setTimeout(this.finishedCallback, this.transfer);
}
}
},
properties: {
obligatory: ["html"],
countsForProgressBar: false,
htmlDescription: function (opts) {
return truncateHTML(htmlCodeToDOM(opts.html), 100);
}
}
});
|
/*
Copyright (c) 2017, Dogan Yazar
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.
*/
// a list of commonly used words that have little meaning and can be excluded
// from analysis.
const words = ["aderton","adertonde","adjö","aldrig","alla","allas","allt","alltid",
"alltså","andra","andras","annan","annat","artonde","artonn","att","av","bakom",
"bara","behöva","behövas","behövde","behövt","beslut","beslutat","beslutit","bland",
"blev","bli","blir","blivit","bort","borta","bra","bäst","bättre","båda","bådas",
"dag","dagar","dagarna","dagen","de","del","delen","dem","den","denna","deras",
"dess","dessa","det","detta","dig","din","dina","dit","ditt","dock","dom","du",
"där","därför","då","e","efter","eftersom","ej","elfte","eller","elva","emot","en",
"enkel","enkelt","enkla","enligt","ens","er","era","ers","ert","ett","ettusen",
"fanns","fem","femte","femtio","femtionde","femton","femtonde","fick","fin",
"finnas","finns","fjorton","fjortonde","fjärde","fler","flera","flesta","fram",
"framför","från","fyra","fyrtio","fyrtionde","få","får","fått","följande","för",
"före","förlåt","förra","första","genast","genom","gick","gjorde","gjort","god",
"goda","godare","godast","gott","gälla","gäller","gällt","gärna","gå","går","gått",
"gör","göra","ha","hade","haft","han","hans","har","heller","hellre","helst","helt",
"henne","hennes","hit","hon","honom","hundra","hundraen","hundraett","hur","här",
"hög","höger","högre","högst","i","ibland","icke","idag","igen","igår","imorgon",
"in","inför","inga","ingen","ingenting","inget","innan","inne","inom","inte",
"inuti","ja","jag","jo","ju","just","jämfört","kan","kanske","knappast","kom",
"komma","kommer","kommit","kr","kunde","kunna","kunnat","kvar","legat","ligga",
"ligger","lika","likställd","likställda","lilla","lite","liten","litet","länge",
"längre","längst","lätt","lättare","lättast","långsam","långsammare","långsammast",
"långsamt","långt","låt","man","med","mej","mellan","men","mer","mera","mest","mig",
"min","mina","mindre","minst","mitt","mittemot","mot","mycket","många","måste",
"möjlig","möjligen","möjligt","möjligtvis","ned","nederst","nedersta","nedre",
"nej","ner","ni","nio","nionde","nittio","nittionde","nitton","nittonde","nog",
"noll","nr","nu","nummer","när","nästa","någon","någonting","något","några","nån",
"nånting","nåt","nödvändig","nödvändiga","nödvändigt","nödvändigtvis","och","också",
"ofta","oftast","olika","olikt","om","oss","på","rakt","redan","rätt","sa","sade",
"sagt","samma","sedan","senare","senast","sent","sex","sextio","sextionde","sexton",
"sextonde","sig","sin","sina","sist","sista","siste","sitt","sitta","sju","sjunde",
"sjuttio","sjuttionde","sjutton","sjuttonde","själv","sjätte","ska","skall","skulle",
"slutligen","små","smått","snart","som","stor","stora","stort","större","störst",
"säga","säger","sämre","sämst","så","sådan","sådana","sådant","ta","tack","tar",
"tidig","tidigare","tidigast","tidigt","till","tills","tillsammans","tio","tionde",
"tjugo","tjugoen","tjugoett","tjugonde","tjugotre","tjugotvå","tjungo","tolfte",
"tolv","tre","tredje","trettio","trettionde","tretton","trettonde","två","tvåhundra",
"under","upp","ur","ursäkt","ut","utan","utanför","ute","va","vad","var","vara",
"varför","varifrån","varit","varje","varken","vars","varsågod","vart","vem","vems",
"verkligen","vi","vid","vidare","viktig","viktigare","viktigast","viktigt","vilka",
"vilkas","vilken","vilket","vill","väl","vänster","vänstra","värre","vår","våra",
"vårt","än","ännu","är","även","åt","åtminstone","åtta","åttio","åttionde",
"åttonde","över","övermorgon","överst","övre", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "0"]
// tell the world about the noise words.
exports.words = words;
|
import React, { Component } from 'react'
import UserList from './UserList'
import Pagination from 'react-js-pagination';
import PropTypes from 'prop-types';
class PaginatedUsers extends Component {
handlePageChange(page){
this.context.router.history.push('/'+page);
this.props.actions.loadUsers(page)
}
componentDidMount() {
this.props.actions.loadUsers(this.props.page);
}
render () {
return (
<div>
<UserList actions={this.props.actions} users={this.props.users} />
{
this.props.users.data !== undefined &&
<div className="text-center">
<Pagination
activePage={Number(this.props.page)}
itemsCountPerPage={this.props.users.per_page}
totalItemsCount={this.props.users.total}
pageRangeDisplayed={11}
onChange={this.handlePageChange.bind(this)}
/>
</div>
}
</div>
)
}
}
PaginatedUsers.contextTypes = {
router: PropTypes.object
}
export default PaginatedUsers
|
"use strict";
var BottleneckError, States;
BottleneckError = require("./BottleneckError");
States = class States {
constructor(status1) {
this.status = status1;
this._jobs = {};
this.counts = this.status.map(function () {
return 0;
});
}
next(id) {
var current, next;
current = this._jobs[id];
next = current + 1;
if (current != null && next < this.status.length) {
this.counts[current]--;
this.counts[next]++;
return this._jobs[id]++;
} else if (current != null) {
this.counts[current]--;
return delete this._jobs[id];
}
}
start(id) {
var initial;
initial = 0;
this._jobs[id] = initial;
return this.counts[initial]++;
}
remove(id) {
var current;
current = this._jobs[id];
if (current != null) {
this.counts[current]--;
delete this._jobs[id];
}
return current != null;
}
jobStatus(id) {
var ref;
return (ref = this.status[this._jobs[id]]) != null ? ref : null;
}
statusJobs(status) {
var k, pos, ref, results, v;
if (status != null) {
pos = this.status.indexOf(status);
if (pos < 0) {
throw new BottleneckError(`status must be one of ${this.status.join(', ')}`);
}
ref = this._jobs;
results = [];
for (k in ref) {
v = ref[k];
if (v === pos) {
results.push(k);
}
}
return results;
} else {
return Object.keys(this._jobs);
}
}
statusCounts() {
return this.counts.reduce((acc, v, i) => {
acc[this.status[i]] = v;
return acc;
}, {});
}
};
module.exports = States;
|
/* global describe,require,it,before */
"use strict";
require("requirish")._(module);
var opcua = require("index");
var AddressSpace = opcua.AddressSpace;
var should = require("should");
var assert = require("assert");
var _ = require("underscore");
var path = require("path");
var encode_decode_round_trip_test = require("test/helpers/encode_decode_round_trip_test").encode_decode_round_trip_test;
var makeNodeId = opcua.makeNodeId;
var makeExpandedNodeId = opcua.makeExpandedNodeId;
var Variant = opcua.Variant;
var DataType = opcua.DataType;
var nodeset = require("lib/address_space/convert_nodeset_to_types").nodeset;
var createExtensionObjectDefinition = require("lib/address_space/convert_nodeset_to_types").createExtensionObjectDefinition;
var assert_arrays_are_equal = require("test/helpers/typedarray_helpers").assert_arrays_are_equal;
//require("lib/datamodel/buildinfo");
describe("ComplexType read from XML NodeSET file shall be binary Encodable", function () {
var addressSpace;
before(function (done) {
addressSpace = new AddressSpace();
var xml_file = path.join(__dirname,"../fixtures/fixture_nodeset_enumtype.xml");
require("fs").existsSync(xml_file).should.be.eql(true);
opcua.generate_address_space(addressSpace, xml_file, function (err) {
createExtensionObjectDefinition(addressSpace);
done(err);
});
});
after(function(){
addressSpace.dispose();
});
it("a DataType should provide a DefaultBinary Encoding object", function () {
var serverStatusType = addressSpace.findDataType("ServerStatusDataType");
serverStatusType.getEncodingNodeId("Default Binary").nodeId.toString().should.eql("ns=0;i=864");
});
it("should create an enumeration from the ServerState object", function (done) {
var test_value = nodeset.ServerState.NoConfiguration;
//xx console.log(nodeset.ServerState);
test_value.value.should.eql(2);
done();
});
it("should create an structure from the ServerStatus object", function () {
var serverStatus = new nodeset.ServerStatus({
startTime: new Date(),
buildInfo: {},
secondsTillShutdown: 100,
shutdownReason: {text: "for maintenance"}
});
assert(serverStatus._schema.name === "ServerStatus");
serverStatus.startTime.should.be.instanceOf(Date);
serverStatus.secondsTillShutdown.should.eql(100);
});
it("should ServerStatus object have correct encodingDefaultBinary ", function () {
var serverStatus = new nodeset.ServerStatus({});
serverStatus.encodingDefaultBinary.should.eql(makeExpandedNodeId(864, 0));
});
it("should encode and decode a ServerStatus object", function () {
var serverStatus = new nodeset.ServerStatus({
startTime: new Date(),
buildInfo: {},
secondsTillShutdown: 100,
shutdownReason: {text: "for maintenance"}
});
encode_decode_round_trip_test(serverStatus);
});
it("should encode and decode a variant containing an extension object being a ServerStatus", function () {
var serverStatus = new nodeset.ServerStatus({});
var v = new Variant({
dataType: DataType.ExtensionObject,
value: serverStatus
});
encode_decode_round_trip_test(v);
});
});
|
/* jshint -W097 */
/* jshint strict:false */
/* jslint node:true */
/* jshint expr:true */
'use strict';
const testAdapter = require('../lib/testAdapter');
const dataDir = `${__dirname}/../tmp/data`;
const statesConfig = {
options: {
auth_pass: null,
retry_max_delay: 100,
retry_max_count: 2
},
type: 'jsonl',
host: '127.0.0.1',
port: 19000,
user: '',
pass: '',
dataDir: dataDir
};
const objectsConfig = {
options: {
auth_pass: null,
retry_max_delay: 100,
retry_max_count: 2
},
dataDir: dataDir,
type: 'jsonl',
host: '127.0.0.1',
port: 19001,
user: '',
pass: '',
noFileCache: true,
connectTimeout: 2000
};
// states in files, objects in files
testAdapter({
statesConfig: statesConfig,
objectsConfig: objectsConfig,
name: 'Tests Jsonl-File Redis'
});
|
import React from 'react';
import TestUtils from 'react-dom/test-utils';
import Formsy from './..';
import { InputFactory } from './utils/TestInput';
const TestInput = InputFactory({
render() {
return <input value={this.props.getValue()} readOnly/>;
}
});
class TestForm extends React.Component {
render() {
return (
<Formsy>
<TestInput name="foo" validations="isNumeric" value={this.props.inputValue}/>
</Formsy>
);
}
}
export default {
'should pass with a default value': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should pass with an empty string': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue=""/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should fail with an unempty string': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue="foo"/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should pass with a number as string': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue="+42"/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should fail with a number as string with not digits': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue="42 is an answer"/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should pass with an int': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={42}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should pass with a float': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={Math.PI}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should fail with a float in science notation': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue="-1e3"/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should pass with an undefined': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={undefined}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should pass with a null': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={null}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should pass with a zero': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={0}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
}
};
|
/**
* Project: darlingjs (GameEngine).
* Copyright (c) 2013, Eugene-Krevenets
*/
var gameFBModule = window.gameFBModule || angular.module('GameFBModule', []);
gameFBModule
// Register the 'myCurrentTime' directive factory method.
// We inject $timeout and dateFilter service since the factory method is DI.
.directive('fbScoreboard', ['FacebookService', '$parse', function(FacebookService, $parse) {
'use strict';
// return the directive link function. (compile function not needed)
return {
restrict: 'E',
template:
'<div class="scoreboard">' +
' <ul> '+
// ' <li ng-repeat="score in scores | orderBy:'score':'name' | limitTo:10"> '+
' <li ng-repeat="score in scores | orderBy:\'name\':\'false\'"> '+
' <img ng-src="{{ score.picture.data.url }}"/> '+
' <span>{{ score.score }}</span> '+
' <span>{{ score.user.name }}</span> '+
' </li> '+
' </ul>' +
' <div ng-if="isShowLogin" class="fbLoginRequest">' +
' <p>To see scoreboard of friends you need to login</p>' +
' <fb-login onLogin="onLoginHandler()"></fb-login> ' +
' </div>' +
'</div>',
link: function(scope, element, attrs) {
scope.isShowLogin = false;
var onLoginHandler = function() {};
if (attrs.hasOwnProperty('onLogin')) {
onLoginHandler = $parse(attrs.onLogin);
}
scope.$on('fb/setMyScore', function() {
validate();
});
scope.onLoginHandler = function() {
onLoginHandler(scope);
validate();
};
function validate() {
console.log('validate');
FacebookService.isLogin().then(function(result) {
if (result) {
FacebookService.getFriendsScores().then(function(scores) {
scope.scores = scores;
});
scope.isShowLogin = false;
} else if (attrs.hasOwnProperty('askToLogin')){
scope.isShowLogin = true;
if (!score.$$phase) score.$digest();
}
});
}
validate();
}
};
}]);
|
module.exports = function (app) {
/*app.get('/', function (req, res) {
res.render('index.ejs', {
user: req.user
});
});*/
};
|
/**
* Using Rails-like standard naming convention for endpoints.
* GET /things -> index
* POST /things -> create
* GET /things/:id -> show
* PUT /things/:id -> update
* DELETE /things/:id -> destroy
*/
'use strict';
var _ = require('lodash');
var Thing = require('./thing.model');
// Get list of things
exports.index = function(req, res) {
Thing.find(function (err, things) {
if(err) { return handleError(res, err); }
return res.json(200, things);
});
};
// Get a single thing
exports.show = function(req, res) {
Thing.findOne({info: {$gt: new Date()}}, function (err, thing) {
if(err) { return handleError(res, err); }
if(!thing) { return res.send(404); }
return res.json(thing);
});
/*Thing.findById(req.params.id, function (err, thing) {
if(err) { return handleError(res, err); }
if(!thing) { return res.send(404); }
return res.json(thing);
});*/
};
// Creates a new thing in the DB.
exports.create = function(req, res) {
Thing.create(req.body, function(err, thing) {
if(err) { return handleError(res, err); }
return res.json(201, thing);
});
};
// Updates an existing thing in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Thing.findById(req.params.id, function (err, thing) {
if (err) { return handleError(res, err); }
if(!thing) { return res.send(404); }
var updated = _.merge(thing, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, thing);
});
});
};
// Deletes a thing from the DB.
exports.destroy = function(req, res) {
Thing.findById(req.params.id, function (err, thing) {
if(err) { return handleError(res, err); }
if(!thing) { return res.send(404); }
thing.remove(function(err) {
if(err) { return handleError(res, err); }
return res.send(204);
});
});
};
function handleError(res, err) {
return res.send(500, err);
}
|
/*!
* Module dependencies.
*/
var util = require('util'),
super_ = require('../Type');
/**
* URL FieldType Constructor
* @extends Field
* @api public
*/
function url(list, path, options) {
this._nativeType = String;
this._underscoreMethods = ['format'];
url.super_.call(this, list, path, options);
}
/*!
* Inherit from Field
*/
util.inherits(url, super_);
/**
* Formats the field value
*
* Strips the leading protocol from the value for simpler display
*
* @api public
*/
url.prototype.format = function(item) {
return (item.get(this.path) || '').replace(/^[a-zA-Z]\:\/\//, '');
};
// TODO: Proper url validation
/*!
* Export class
*/
exports = module.exports = url;
|
/**
* author: yhtml5
* reference: https://github.com/facebook/jest/blob/master/docs/ExpectAPI.md
* description: common matcher
*/
/**** Common Matchers ****/
// toBe uses === to test exact
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
// check the value of an object, use toEqual
test('object assignment', () => {
const data = { one: 1 };
data['two'] = 2;
expect(data).toEqual({ one: 1, two: 2 });
});
// test for the opposite of a matcher
test('adding positive numbers is not zero', () => {
for (let a = 1; a < 10; a++) {
for (let b = 1; b < 10; b++) {
expect(a + b).not.toBe(0);
}
}
});
/**** Truthiness ****/
// In tests you sometimes need to distinguish between undefined, null, and false,
test('null', () => {
const n = null;
expect(n).toBeNull();
expect(n).toBeDefined();
expect(n).not.toBeUndefined();
expect(n).not.toBeTruthy();
expect(n).toBeFalsy();
});
test('zero', () => {
const z = 0;
expect(z).not.toBeNull();
expect(z).toBeDefined();
expect(z).not.toBeUndefined();
expect(z).not.toBeTruthy();
expect(z).toBeFalsy();
});
/**** Numbers ****/
// Most ways of comparing numbers have matcher equivalents.
test('two plus two', () => {
const value = 2 + 2;
expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(3.5);
expect(value).toBeLessThan(5);
expect(value).toBeLessThanOrEqual(4.5);
// toBe and toEqual are equivalent for numbers
expect(value).toBe(4);
expect(value).toEqual(4);
});
/**
* For floating point equality, use toBeCloseTo instead of toEqual,
* because you don't want a test to depend on a tiny rounding error.
*/
test('adding floating point numbers', () => {
const value = 0.1 + 0.2;
expect(value).not.toBe(0.3); // It isn't! Because rounding error
expect(value).toBeCloseTo(0.3); // This works.
});
/**** Strings ****/
// You can check strings against regular expressions with toMatch:
test('there is no I in team', () => {
expect('team').not.toMatch(/I/);
});
test('but there is a "stop" in Christoph', () => {
expect('Christoph').toMatch(/stop/);
});
/**** Arrays ****/
// You can check if an array contains a particular item using toContain:
test('the shopping list has beer on it', () => {
const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'beer',
];
expect(shoppingList).toContain('beer');
});
/**** String ****/
function compileAndroidCode() {
throw 'you are using the wrong JDK'
}
test('compiling android goes as expected', () => {
expect(compileAndroidCode).toThrow();
// expect(compileAndroidCode).toThrow(ConfigError);
// You can also use the exact error message or a regexp
expect(compileAndroidCode).toThrow('you are using the wrong JDK');
expect(compileAndroidCode).toThrow(/JDK/);
});
|
(function() {
//inject angular file upload directives and services.
var app = angular.module('fileUpload');
app.controller('Controller2', [function () {
var ctrl = this;
ctrl.name = undefined;
}]);
})();
|
var phonegapReady = function(){
new jQuery.nd2Toast({message:"we are in phonegap"});
};
jQuery(document).ready(function(){
document.addEventListener("deviceready", phonegapReady, false);
});
|
import React, { Component } from 'react'
import { object } from 'prop-types'
// redux
import { connect } from 'react-redux'
import { signIn } from 'store/modules/ui/profile'
// libs
import { importWallet } from 'helpers/wallet'
import { Link } from 'react-router-dom'
// components
import FileReaderInput from 'react-file-reader-input'
import WalletCard from '../Card'
import Button from '@material-ui/core/Button'
import { toastr } from 'react-redux-toastr'
import { CardActions, CardHeader, Avatar, Divider, CardContent } from '@material-ui/core';
// icons
import WalletIcon from '@material-ui/icons/AccountBalanceWallet'
class ImportWallet extends Component {
static propTypes = {
wallet: object
}
async importWallet(str) {
try {
const wallet = importWallet(str)
await this.props.signIn(wallet)
toastr.success('Wallet imported', 'Your existing data has been imported')
// TODO: redirect user depending on their type: business goes to reviews about me, individual goes to search
} catch (error) {
toastr.error('Could not import Wallet', 'Something went wrong')
console.log(error)
}
}
fileChanged(event, results) {
if (results.length > 0) {
// docs: https://github.com/ngokevin/react-file-reader-input#usage
this.importWallet(results[0][0].target.result)
}
}
render () {
const { loading } = this.props
if (loading) {
return <div>
<WalletCard>
<CardHeader
avatar={<Avatar><WalletIcon/></Avatar>}
title='Signing In...'
subheader='Please wait while your Wallet is imported'
/>
</WalletCard>
</div>
} else {
return (
<div>
<WalletCard>
<CardHeader
avatar={<Avatar><WalletIcon/></Avatar>}
title='Import a Chlu Wallet'
subheader='Access your existing funds and Identity from this device'
/>
<CardContent>
Don't have a wallet yet? <Link to='/'>Create a new one</Link>
</CardContent>
<CardActions>
<FileReaderInput
as='text'
onChange={this.fileChanged.bind(this)}
accept='application/json'
>
<Button variant='raised' color='primary'>
Import from File
</Button>
</FileReaderInput>
</CardActions>
<Divider/>
</WalletCard>
</div>
)
}
}
}
const mapStateToProps = store => ({
wallet: store.data.wallet,
loading: store.ui.profile.loginLoading
})
const mapDispatchToProps = {
signIn
}
export default connect(mapStateToProps, mapDispatchToProps)(ImportWallet)
|
export default from './CodeEditor'
|
import Backbone from 'backbone';
import routes from '../routes';
export default class Variable extends Backbone.Model {
constructor(attributes, options) {
super(attributes, options);
this.urlRoot = routes.variables;
}
}
|
const db = require('georap-db');
module.exports = function (id, callback) {
// Get single location without events and entries
//
// Parameters:
// id
// ObjectId
// callback
// function (err, loc)
// err null and loc null if no loc found
//
const locColl = db.collection('locations');
locColl.findOne({ _id: id }, (err, doc) => {
if (err) {
return callback(err);
}
if (!doc) {
return callback(null, null);
}
return callback(null, doc);
});
};
|
/// <reference path="CoordinateTests.ts" />
/// <reference path="tsUnit.ts" />
var UnitTests;
(function (UnitTests) {
var TestRunner = (function () {
function TestRunner() {
this.test = new tsUnit.Test();
this.test.addTestClass(new UnitTests.CoordinateTests());
}
TestRunner.prototype.runInBrowser = function () {
var _this = this;
window.onload = function () {
_this.test.showResults(document.getElementById('result'), _this.test.run());
};
};
TestRunner.prototype.runInScriptEngine = function () {
var result = this.test.run();
if (result.errors.length > 0) {
var message = '';
for (var i = 0; i < result.errors.length; i++) {
var err = result.errors[i];
message += err.testName + ' ' + err.funcName + ' ' + err.message + '\r\n';
}
throw new Error(message);
}
};
return TestRunner;
})();
UnitTests.TestRunner = TestRunner;
})(UnitTests || (UnitTests = {}));
var testRunner = new UnitTests.TestRunner();
if (typeof isMsScriptEngineContext === "undefined") {
testRunner.runInBrowser();
}
function getResult() {
testRunner.runInScriptEngine();
}
//# sourceMappingURL=TestRunner.js.map
|
var path = require('path');
var webpack = require('webpack');
var pkg = require('./package.json');
module.exports = {
node: {
fs: 'empty'
},
entry: {
'coins-logon-widget': './scripts/coins-logon-widget.js'
},
output: {
path: path.join(__dirname + '/dist'),
filename: '[name].js',
library: 'CoinsLogonWidget',
libraryTarget: 'umd',
umdNamedDefine: true,
},
optimization: {
minimize: true
}
};
|
var jQuery15 = jQuery;
jQuery.noConflict(true);
|
/// <reference types="cypress" />
context('Standard Calendar', () => {
it('Create New Event', () => {
let title = "My New Event - " + Cypress._.random(0, 1e6);
cy.loginStandard("v2/calendar");
cy.get('.fc-row:nth-child(1) > .fc-content-skeleton .fc-thu').click();
cy.get('.modal-header > input').click();
cy.get('.modal-header > input').type(title);
cy.get('tr:nth-child(2) textarea').type('New adult Service');
cy.get('tr:nth-child(6) textarea').type('Come join us');
//cy.get('#PinnedCalendars').type('Public Calendar');
//cy.get('.btn-success').click();
});
});
|
var Kybrd = function(element) {
element = element || document;
element.addEventListener('keydown', this._onKeyDown.bind(this));
element.addEventListener('keyup', this._onKeyUp.bind(this));
this._keys = {};
};
Kybrd.prototype.isPressed = function(key) {
return this._keys.hasOwnProperty(key);
}
Kybrd.prototype._onKeyDown = function(event) {
var code = event.which || event.keyCode;
var key = this._codeToKey(code);
this._keys[key] = true;
};
Kybrd.prototype._onKeyUp = function(event) {
var code = event.which || event.keyCode;
var key = this._codeToKey(code);
delete this._keys[key];
};
Kybrd.prototype._codeToKey = function(code) {
var key = Kybrd.KEYS[code];
var fKey = code - 111;
if (fKey > 0 && fKey < 13) {
key = 'f' + fKey;
}
if (!key) {
key = String.fromCharCode(code).toLowerCase();
}
return key;
};
Kybrd.KEYS = {
13: 'enter',
38: 'up',
40: 'down',
37: 'left',
39: 'right',
27: 'esc',
32: 'space',
8: 'backspace',
9: 'tab',
46: 'delete'
};
module.exports = Kybrd;
|
import Component from 'react-pure-render/component';
import React from 'react';
import { FormattedMessage, defineMessages } from 'react-intl';
import EditorFormatAlignLeft from 'material-ui/svg-icons/editor/format-align-left';
import { grey200 } from 'material-ui/styles/colors';
const _messages = defineMessages({
emptyArticle: {
defaultMessage: 'No data so far',
id: 'ui.emptyArticle.empty'
}
});
export default class EmptyList extends Component {
render() {
const emptyListContainerStyle = {
width: '100%',
height: '70vh',
verticalAlign: 'middle',
textAlign: 'center',
color: grey200
};
const emptyListContentStyle = {
position: 'relative',
top: '50%',
transform: 'translateY(-50%)'
};
const iconStyle = {
width: 300,
height: 300
};
return (
<div style={emptyListContainerStyle}>
<div style={emptyListContentStyle}>
<EditorFormatAlignLeft color={grey200} style={iconStyle} />
<p>
<FormattedMessage {..._messages.emptyArticle} />
</p>
</div>
</div>
);
}
}
|
'use strict';
angular.module('angularjsDE-module-seed')
.controller('ChangepasswordCtrl', function ($scope, $modalInstance, hoodieAccount, $log) {
$scope.alerts = [];
$scope.ok = function () {
hoodieAccount.changePassword($scope.old, $scope.new).then(function(data) {
$log.log(data);
$scope.alerts.push({msg: data, type: 'success'});
$modalInstance.close();
});
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
|
import axios from 'axios';
var api = function api(baseUrl) {
var create = axios.create({
baseURL: baseUrl,
withCredentials: true
});
create.interceptors.request.use(function (request) {
return request;
}, function (error) {
error.msg = 'Erro ao tentar enviar dados.';
console.error(error.msg, error, error.request);
return Promise.reject(error);
});
create.interceptors.response.use(function (response) {
return response;
}, function (error) {
var response = error.response;
error.msg = response && response.data ? response.data.msg : 'Erro ao tentar receber dados.';
console.error(error.msg, error, error.response);
return Promise.reject(error);
});
return create;
};
// const api = {
// apiGeral: apiGenerico(API_URL)
// };
export default api;
//# sourceMappingURL=api.js.map
|
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code originated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function( elem, types, handler, data ) {
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// For whatever reason, IE has trouble passing the window object
// around, causing it to be cloned in the process
if ( elem.setInterval && ( elem !== window && !elem.frameElement ) ) {
elem = window;
}
// Make sure that the function being executed has a unique ID
if ( !handler.guid ) {
handler.guid = this.guid++;
}
// if data is passed, bind to handler
if ( data !== undefined ) {
// Create temporary function pointer to original handler
var fn = handler;
// Create unique handler function, wrapped around original handler
handler = this.proxy( fn );
// Store data in unique handler
handler.data = data;
}
// Init the element's event structure
var events = jQuery.data( elem, "events" ) || jQuery.data( elem, "events", {} ),
handle = jQuery.data( elem, "handle" ) || jQuery.data( elem, "handle", function eventHandle() {
// Handle the second event of a trigger and when
// an event is called after a page has unloaded
return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) :
undefined;
});
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native
// event in IE.
handle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = types.split( /\s+/ );
var type, i=0;
while ( (type = types[ i++ ]) ) {
// Namespaced event handlers
var namespaces = type.split(".");
type = namespaces.shift();
handler.type = namespaces.slice(0).sort().join(".");
// Get the current list of functions bound to this event
var handlers = events[ type ],
special = this.special[ type ] || {};
// Init the event handler queue
if ( !handlers ) {
handlers = events[ type ] = {};
// Check for a special event handler
// Only use addEventListener/attachEvent if the special
// events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, handler) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, handle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, handle );
}
}
}
if ( special.add ) {
var modifiedHandler = special.add.call( elem, handler, data, namespaces, handlers );
if ( modifiedHandler && jQuery.isFunction( modifiedHandler ) ) {
modifiedHandler.guid = modifiedHandler.guid || handler.guid;
handler = modifiedHandler;
}
}
// Add the function to the element's handler list
handlers[ handler.guid ] = handler;
// Keep track of which events have been used, for global triggering
this.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
guid: 1,
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler ) {
// don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
var events = jQuery.data( elem, "events" ), ret, type, fn;
if ( events ) {
// Unbind all events for the element
if ( types === undefined || (typeof types === "string" && types.charAt(0) === ".") ) {
for ( type in events ) {
this.remove( elem, type + (types || "") );
}
} else {
// types is actually an event object here
if ( types.type ) {
handler = types.handler;
types = types.type;
}
// Handle multiple events separated by a space
// jQuery(...).unbind("mouseover mouseout", fn);
types = types.split(/\s+/);
var i = 0;
while ( (type = types[ i++ ]) ) {
// Namespaced event handlers
var namespaces = type.split(".");
type = namespaces.shift();
var all = !namespaces.length,
cleaned = jQuery.map( namespaces.slice(0).sort() , function(nm){ return nm.replace(/[^\w\s\.\|`]/g, function(ch){return "\\"+ch; }); }),
namespace = new RegExp("(^|\\.)" + cleaned.join("\\.(?:.*\\.)?") + "(\\.|$)"),
special = this.special[ type ] || {};
if ( events[ type ] ) {
// remove the given handler for the given type
if ( handler ) {
fn = events[ type ][ handler.guid ];
delete events[ type ][ handler.guid ];
// remove all handlers for the given type
} else {
for ( var handle in events[ type ] ) {
// Handle the removal of namespaced events
if ( all || namespace.test( events[ type ][ handle ].type ) ) {
delete events[ type ][ handle ];
}
}
}
if ( special.remove ) {
special.remove.call( elem, namespaces, fn);
}
// remove generic event handler if no more handlers exist
for ( ret in events[ type ] ) {
break;
}
if ( !ret ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, jQuery.data( elem, "handle" ), false );
} else if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, jQuery.data( elem, "handle" ) );
}
}
ret = null;
delete events[ type ];
}
}
}
}
// Remove the expando if it's no longer used
for ( ret in events ) {
break;
}
if ( !ret ) {
var handle = jQuery.data( elem, "handle" );
if ( handle ) {
handle.elem = null;
}
jQuery.removeData( elem, "events" );
jQuery.removeData( elem, "handle" );
}
}
},
// bubbling is internal
trigger: function( event, data, elem /*, bubbling */ ) {
// Event object or event type
var type = event.type || event,
bubbling = arguments[3];
if ( !bubbling ) {
event = typeof event === "object" ?
// jQuery.Event object
event[expando] ? event :
// Object literal
jQuery.extend( jQuery.Event(type), event ) :
// Just the event type (string)
jQuery.Event(type);
if ( type.indexOf("!") >= 0 ) {
event.type = type = type.slice(0, -1);
event.exclusive = true;
}
// Handle a global trigger
if ( !elem ) {
// Don't bubble custom events when global (to avoid too much overhead)
event.stopPropagation();
// Only trigger if we've ever bound an event for it
if ( this.global[ type ] ) {
jQuery.each( jQuery.cache, function() {
if ( this.events && this.events[type] ) {
jQuery.event.trigger( event, data, this.handle.elem );
}
});
}
}
// Handle triggering a single element
// don't do events on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
return undefined;
}
// Clean up in case it is reused
event.result = undefined;
event.target = elem;
// Clone the incoming data, if any
data = jQuery.makeArray( data );
data.unshift( event );
}
event.currentTarget = elem;
// Trigger the event, it is assumed that "handle" is a function
var handle = jQuery.data( elem, "handle" );
if ( handle ) {
handle.apply( elem, data );
}
var nativeFn, nativeHandler;
try {
if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) {
nativeFn = elem[ type ];
nativeHandler = elem[ "on" + type ];
}
// prevent IE from throwing an error for some elements with some event types, see #3533
} catch (e) {}
var isClick = jQuery.nodeName(elem, "a") && type === "click";
// Trigger the native events (except for clicks on links)
if ( !bubbling && nativeFn && !event.isDefaultPrevented() && !isClick ) {
this.triggered = true;
try {
elem[ type ]();
// prevent IE from throwing an error for some hidden elements
} catch (e) {}
// Handle triggering native .onfoo handlers
} else if ( nativeHandler && elem[ "on" + type ].apply( elem, data ) === false ) {
event.result = false;
}
this.triggered = false;
if ( !event.isPropagationStopped() ) {
var parent = elem.parentNode || elem.ownerDocument;
if ( parent ) {
jQuery.event.trigger( event, data, parent, true );
}
}
},
handle: function( event ) {
// returned undefined or false
var all, handlers;
event = arguments[0] = jQuery.event.fix( event || window.event );
event.currentTarget = this;
// Namespaced event handlers
var namespaces = event.type.split(".");
event.type = namespaces.shift();
// Cache this now, all = true means, any handler
all = !namespaces.length && !event.exclusive;
var namespace = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)");
handlers = ( jQuery.data(this, "events") || {} )[ event.type ];
for ( var j in handlers ) {
var handler = handlers[ j ];
// Filter the functions by class
if ( all || namespace.test(handler.type) ) {
// Pass in a reference to the handler function itself
// So that we can later remove it
event.handler = handler;
event.data = handler.data;
var ret = handler.apply( this, arguments );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
return event.result;
},
props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix: function( event ) {
if ( event[ expando ] ) {
return event;
}
// store a copy of the original event object
// and "clone" to set read-only properties
var originalEvent = event;
event = jQuery.Event( originalEvent );
for ( var i = this.props.length, prop; i; ) {
prop = this.props[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary
if ( !event.target ) {
event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
}
// check if target is a textnode (safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && event.fromElement ) {
event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
}
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
var doc = document.documentElement, body = document.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}
// Add which for key events
if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) {
event.which = event.charCode || event.keyCode;
}
// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if ( !event.metaKey && event.ctrlKey ) {
event.metaKey = event.ctrlKey;
}
// Add which for click: 1 == left; 2 == middle; 3 == right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}
return event;
},
proxy: function( fn, proxy, thisObject ) {
if ( proxy !== undefined && !jQuery.isFunction( proxy ) ) {
thisObject = proxy;
proxy = undefined;
}
// FIXME: Should proxy be redefined to be applied with thisObject if defined?
proxy = proxy || function() { return fn.apply( thisObject !== undefined ? thisObject : this, arguments ); };
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
// So proxy can be declared as an argument
return proxy;
},
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady,
teardown: function() {}
},
live: {
add: function( proxy, data, namespaces, live ) {
jQuery.extend( proxy, data || {} );
proxy.guid += data.selector + data.live;
jQuery.event.add( this, data.live, liveHandler, data );
},
remove: function( namespaces ) {
if ( namespaces.length ) {
var remove = 0, name = new RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
jQuery.each( (jQuery.data(this, "events").live || {}), function() {
if ( name.test(this.type) ) {
remove++;
}
});
if ( remove < 1 ) {
jQuery.event.remove( this, namespaces[0], liveHandler );
}
}
},
special: {}
},
beforeunload: {
setup: function( data, namespaces, fn ) {
// We only want to do this special case on windows
if ( this.setInterval ) {
this.onbeforeunload = fn;
}
return false;
},
teardown: function( namespaces, fn ) {
if ( this.onbeforeunload === fn ) {
this.onbeforeunload = null;
}
}
}
}
};
jQuery.Event = function( src ){
// Allow instantiation without the 'new' keyword
if ( !this.preventDefault ) {
return new jQuery.Event( src );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Event type
} else {
this.type = src;
}
// timeStamp is buggy for some events on Firefox(#3843)
// So we won't rely on the native value
this.timeStamp = now();
// Mark it as fixed
this[ expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
}
// otherwise set the returnValue property of the original event to false (IE)
e.returnValue = false;
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function(){
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function( event ) {
// Check if mouse(over|out) are still within the same parent element
var parent = event.relatedTarget;
// Traverse up the tree
while ( parent && parent != this ) {
// Firefox sometimes assigns relatedTarget a XUL element
// which we cannot access the parentNode property of
try { parent = parent.parentNode; }
// assuming we've left the element since we most likely mousedover a xul element
catch(e) { break; }
}
if ( parent != this ) {
// set the correct event type
event.type = event.data;
// handle event if we actually just moused on to a non sub-element
jQuery.event.handle.apply( this, arguments );
}
},
// In case of event delegation, we only need to rename the event.type,
// liveHandler will take care of the rest.
delegate = function( event ) {
event.type = event.data;
jQuery.event.handle.apply( this, arguments );
};
// Create mouseenter and mouseleave events
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
setup: function(data){
jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
},
teardown: function(data){
jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
}
};
});
// submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function( data, namespaces, fn ) {
if ( this.nodeName.toLowerCase() !== "form" ) {
jQuery.event.add(this, "click.specialSubmit." + fn.guid, function( e ) {
var elem = e.target, type = elem.type;
if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
return trigger( "submit", this, arguments );
}
});
jQuery.event.add(this, "keypress.specialSubmit." + fn.guid, function( e ) {
var elem = e.target, type = elem.type;
if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
return trigger( "submit", this, arguments );
}
});
}
},
remove: function( namespaces, fn ) {
jQuery.event.remove( this, "click.specialSubmit" + (fn ? "."+fn.guid : "") );
jQuery.event.remove( this, "keypress.specialSubmit" + (fn ? "."+fn.guid : "") );
}
};
}
// change delegation, happens here so we have bind.
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
filters: {
click: function( e ) {
var elem = e.target;
if ( elem.nodeName.toLowerCase() === "input" && elem.type === "checkbox" ) {
return trigger( "change", this, arguments );
}
return changeFilters.keyup.call( this, e );
},
keyup: function( e ) {
var elem = e.target, data, index = elem.selectedIndex + "";
if ( elem.nodeName.toLowerCase() === "select" ) {
data = jQuery.data( elem, "_change_data" );
jQuery.data( elem, "_change_data", index );
if ( (elem.type === "select-multiple" || data != null) && data !== index ) {
return trigger( "change", this, arguments );
}
}
},
beforeactivate: function( e ) {
var elem = e.target;
if ( elem.nodeName.toLowerCase() === "input" && elem.type === "radio" && !elem.checked ) {
return trigger( "change", this, arguments );
}
},
blur: function( e ) {
var elem = e.target, nodeName = elem.nodeName.toLowerCase();
if ( (nodeName === "textarea" || (nodeName === "input" && (elem.type === "text" || elem.type === "password")))
&& jQuery.data(elem, "_change_data") !== elem.value ) {
return trigger( "change", this, arguments );
}
},
focus: function( e ) {
var elem = e.target, nodeName = elem.nodeName.toLowerCase();
if ( nodeName === "textarea" || (nodeName === "input" && (elem.type === "text" || elem.type === "password" ) ) ) {
jQuery.data( elem, "_change_data", elem.value );
}
}
},
setup: function( data, namespaces, fn ) {
for ( var type in changeFilters ) {
jQuery.event.add( this, type + ".specialChange." + fn.guid, changeFilters[type] );
}
// always want to listen for change for trigger
return false;
},
remove: function( namespaces, fn ) {
for ( var type in changeFilters ) {
jQuery.event.remove( this, type + ".specialChange" + (fn ? "."+fn.guid : ""), changeFilters[type] );
}
}
};
var changeFilters = jQuery.event.special.change.filters;
}
function trigger( type, elem, args ) {
args[0].type = type;
return jQuery.event.handle.apply( elem, args );
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ){
jQuery.event.special[ orig ] = {
setup: function() {
jQuery.event.add( this, fix, ieHandler );
},
teardown: function() {
jQuery.event.remove( this, fix, ieHandler );
}
};
function ieHandler() {
arguments[0].type = orig;
return jQuery.event.handle.apply(this, arguments);
}
});
}
jQuery.each(["bind", "one"], function(i, name) {
jQuery.fn[ name ] = function( type, data, fn, thisObject ) {
// Handle object literals
if ( typeof type === "object" ) {
for ( var key in type ) {
this[ name ](key, data, type[key], fn);
}
return this;
}
if ( jQuery.isFunction( data ) ) {
thisObject = fn;
fn = data;
data = undefined;
}
fn = thisObject === undefined ? fn : jQuery.event.proxy( fn, thisObject );
var handler = name == "one" ? jQuery.event.proxy( fn, function( event ) {
jQuery( this ).unbind( event, handler );
return fn.apply( this, arguments );
}) : fn;
return type === "unload" ? this.one(type, data, handler, thisObject) : this.each(function() {
jQuery.event.add( this, type, handler, data );
});
};
});
jQuery.fn.extend({
unbind: function( type, fn ) {
// Handle object literals
if ( typeof type === "object" && !type.preventDefault ) {
for ( var key in type ) {
this.unbind(key, type[key]);
}
return this;
}
return this.each(function() {
jQuery.event.remove( this, type, fn );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
var event = jQuery.Event( type );
event.preventDefault();
event.stopPropagation();
jQuery.event.trigger( event, data, this[0] );
return event.result;
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments, i = 1;
// link all the functions, so any of them can unbind this click handler
while( i < args.length ) {
jQuery.event.proxy( fn, args[ i++ ] );
}
return this.click( jQuery.event.proxy( fn, function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery.data( this, 'lastToggle' + fn.guid ) || 0 ) % i;
jQuery.data( this, 'lastToggle' + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
}));
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
live: function( type, data, fn, thisObject ) {
if ( jQuery.isFunction( data ) ) {
if ( fn !== undefined ) {
thisObject = fn;
}
fn = data;
data = undefined;
}
jQuery( this.context ).bind( liveConvert( type, this.selector ), {
data: data, selector: this.selector, live: type
}, fn, thisObject );
return this;
},
die: function( type, fn ) {
jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null );
return this;
}
});
function liveHandler( event ) {
var stop = true, elems = [], selectors = [], args = arguments,
related, match, fn, elem, j, i, data,
live = jQuery.extend({}, jQuery.data( this, "events" ).live);
for ( j in live ) {
fn = live[j];
if ( fn.live === event.type ||
fn.altLive && jQuery.inArray(event.type, fn.altLive) > -1 ) {
data = fn.data;
if ( !(data.beforeFilter && data.beforeFilter[event.type] &&
!data.beforeFilter[event.type](event)) ) {
selectors.push( fn.selector );
}
} else {
delete live[j];
}
}
match = jQuery( event.target ).closest( selectors, event.currentTarget );
for ( i = 0, l = match.length; i < l; i++ ) {
for ( j in live ) {
fn = live[j];
elem = match[i].elem;
related = null;
if ( match[i].selector === fn.selector ) {
// Those two events require additional checking
if ( fn.live === "mouseenter" || fn.live === "mouseleave" ) {
related = jQuery( event.relatedTarget ).closest( fn.selector )[0];
}
if ( !related || related !== elem ) {
elems.push({ elem: elem, fn: fn });
}
}
}
}
for ( i = 0, l = elems.length; i < l; i++ ) {
match = elems[i];
event.currentTarget = match.elem;
event.data = match.fn.data;
if ( match.fn.apply( match.elem, args ) === false ) {
stop = false;
break;
}
}
return stop;
}
function liveConvert( type, selector ) {
return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "&")].join(".");
}
jQuery.each( ("blur focus load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( fn ) {
return fn ? this.bind( name, fn ) : this.trigger( name );
};
if ( jQuery.fnAttr ) {
jQuery.fnAttr[ name ] = true;
}
});
// Prevent memory leaks in IE
// Window isn't included so as not to unbind existing unload events
// More info:
// - http://isaacschlueter.com/2006/10/msie-memory-leaks/
/*@cc_on
jQuery( window ).bind( 'unload', function() {
for ( var id in jQuery.cache ) {
// Skip the window
if ( id != 1 && jQuery.cache[ id ].handle ) {
// Try/Catch is to handle iframes being unloaded, see #4280
try {
jQuery.event.remove( jQuery.cache[ id ].handle.elem );
} catch(e) {}
}
}
});
@*/
|
export default {
getClassName: function(classes) {
if (this.props.className) {
return this.props.className + ` ${classes}`;
}
return classes;
}
}
|
import './a';
import './b';
|
exports.level = {
"goalTreeString": "{\"branches\":{\"master\":{\"target\":\"C7\",\"id\":\"master\"},\"bugWork\":{\"target\":\"C2\",\"id\":\"bugWork\"}},\"commits\":{\"C0\":{\"parents\":[],\"id\":\"C0\",\"rootCommit\":true},\"C1\":{\"parents\":[\"C0\"],\"id\":\"C1\"},\"C2\":{\"parents\":[\"C1\"],\"id\":\"C2\"},\"C3\":{\"parents\":[\"C1\"],\"id\":\"C3\"},\"C4\":{\"parents\":[\"C3\"],\"id\":\"C4\"},\"C5\":{\"parents\":[\"C2\"],\"id\":\"C5\"},\"C6\":{\"parents\":[\"C4\",\"C5\"],\"id\":\"C6\"},\"C7\":{\"parents\":[\"C6\"],\"id\":\"C7\"}},\"HEAD\":{\"target\":\"master\",\"id\":\"HEAD\"}}",
"solutionCommand": "git branch bugWork master^^2^",
"startTree": "{\"branches\":{\"master\":{\"target\":\"C7\",\"id\":\"master\"}},\"commits\":{\"C0\":{\"parents\":[],\"id\":\"C0\",\"rootCommit\":true},\"C1\":{\"parents\":[\"C0\"],\"id\":\"C1\"},\"C2\":{\"parents\":[\"C1\"],\"id\":\"C2\"},\"C3\":{\"parents\":[\"C1\"],\"id\":\"C3\"},\"C4\":{\"parents\":[\"C3\"],\"id\":\"C4\"},\"C5\":{\"parents\":[\"C2\"],\"id\":\"C5\"},\"C6\":{\"parents\":[\"C4\",\"C5\"],\"id\":\"C6\"},\"C7\":{\"parents\":[\"C6\"],\"id\":\"C7\"}},\"HEAD\":{\"target\":\"master\",\"id\":\"HEAD\"}}",
"name": {
"en_US": "Multiple parents",
"zh_CN": "多个父提交记录",
'fr_FR': 'Parents multiples',
"de_DE": "Mehrere Vorgänger",
"ja" : "複数の親",
"es_AR": "Múltiples padres",
"pt_BR": "Múltiplos pais",
"zh_TW": "多個 parent commit",
"ru_RU": "Здоровая семья или несколько родителей"
},
"hint": {
"en_US": "Use `git branch bugWork` with a target commit to create the missing reference.",
"de_DE": "Nutze `git branch bugWork` mit einem Ziel-Commit um die fehlende Referenz zu erstellen.",
"ja" : "`git branch bugWork`を対象のコミットと組み合わせて使い、欠如しているリファレンスを作成しましょう",
'fr_FR': 'Utilisez "git branch bugWork" avec un commit pour créer une référence manquante',
"zh_CN": "使用`git branch bugWork`加上一个目标提交记录来创建消失的引用。",
"es_AR": "Usá `git branch bugWork` sobre algún commit para crear la referencia faltante",
"pt_BR": "Use `git branch bugWork` com um commit alvo para criar a referência que falta",
"zh_TW": "在一個指定的 commit 上面使用 `git branch bugWork`。",
"ru_RU": "`git branch bugWork` на нужном коммите поможет создать нужную ссылку."
},
"startDialog": {
"en_US": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Specifying Parents",
"",
"Like the `~` modifier, the `^` modifier also accepts an optional number after it.",
"",
"Rather than specifying the number of generations to go back (what `~` takes), the modifier on `^` specifies which parent reference to follow from a merge commit. Remember that merge commits have multiple parents, so the path to choose is ambiguous.",
"",
"Git will normally follow the \"first\" parent upwards from a merge commit, but specifying a number with `^` changes this default behavior.",
"",
"Enough talking, let's see it in action.",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Here we have a merge commit. If we checkout `master^` without the modifier, we will follow the first parent after the merge commit. ",
"",
"(*In our visuals, the first parent is positioned directly above the merge commit.*)"
],
"afterMarkdowns": [
"Easy -- this is what we are all used to."
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Now let's try specifying the second parent instead..."
],
"afterMarkdowns": [
"See? We followed the other parent upwards."
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"The `^` and `~` modifiers can make moving around a commit tree very powerful:"
],
"afterMarkdowns": [
"Lightning fast!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Even crazier, these modifiers can be chained together! Check this out:"
],
"afterMarkdowns": [
"The same movement as before, but all in one command."
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Put it to practice",
"",
"To complete this level, create a new branch at the specified destination.",
"",
"Obviously it would be easy to specify the commit directly (with something like `C6`), but I challenge you to use the modifiers we talked about instead!"
]
}
}
]
},
"de_DE": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Vorgänger ansteuern",
"",
"Wie der Operator `~` akzeptiert auch der Operator `^` eine optionale Anzahl.",
"",
"Anstatt der Anzahl von Schritten, die zurückgegangen werden soll (das ist das, was man bei `~` angibt), bezeichnet die Anzahl nach `^` welchem Vorgänger bei einem Merge-Commit gefolgt werden soll. Du erinnerst dich, dass ein Merge-Commit mehrere Vorgänger hat; es gilt also aus diesen auszuwählen.",
"",
"Normalerweise folgt Git dem \"ersten\" Vorgänger des Merge-Commit, aber durch Angabe einer Zahl nach dem `^` lässt sich dieses Verhalten ändern.",
"",
"Aber genug gequatscht, schauen wir's uns in Aktion an.",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Hier sehen wir einen Merge-Commit. Wenn wir einen Checkout von `master^` ohne Zahl machen, wird Git auf den ersten Vorgänger des Commits zurückgehen. ",
"",
"*(In unserer Darstellung befindet sich der erste Vorgänger direkt über dem Merge-Commit.)*"
],
"afterMarkdowns": [
"Simpel -- so kennen wir das."
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Jetzt versuchen wir mal stattdessen den zweiten Vorgänger anzugeben ..."
],
"afterMarkdowns": [
"Gesehen? Wir gehen zu dem anderen Vorgänger zurück."
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Die Operatoren `^` und `~` geben uns eine Menge Möglichkeiten für das Navigieren durch den Commit-Baum:"
],
"afterMarkdowns": [
"Bämm!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Noch abgefahrener: die beiden Operatoren können verkettet werden. Aufgepasst:"
],
"afterMarkdowns": [
"Gleicher Ablauf wie zuvor, nur alles in einem Befehl."
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Setzen wir's um",
"",
"Erstelle einen neuen Branch an dem angegebenen Ziel, um diesen Level abzuschließen.",
"",
"Es ist natürlich möglich den Commit einfach direkt anzugeben (also mit sowas wie `C6`), aber ich fordere dich heraus stattdessen die relativen Operatoren zu benutzen!"
]
}
}
]
},
"fr_FR": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Determine les Parents",
"",
"Comme le symbole `~`, le symbole `^` accepte un numéro après lui.",
"",
"Au lieu d'entrer le nombre de générations à remonter (ce que `~` fait), le symbole `^` détermine quel parent est à remonter. Attention, un merge commit a deux parents ce qui peut porter à confusion.",
"",
"Normalement Git suit le \"premier\" parent pour un commit/merge, mais avec un numéro suivi de `^` le comportement par défault est modifié.",
"",
"Assez de bla bla, passons à l\'action",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Nous avons un commit/merge. Si nous faisons checkout `master^` sans le symbole, on obtient le premier parent suivant ce commit. ",
"",
"(*Dans notre vue, le premier parent se situe juste au dessus du merge.*)"
],
"afterMarkdowns": [
"Facile -- C\'est ce que nous faisons tout le temps."
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Nous allons spécifier le deuxième parent à la place."
],
"afterMarkdowns": [
"Vous voyez ? Nous suivons le second parent."
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Les symboles `^` et `~` permettent de se déplacer de façon très efficace :"
],
"afterMarkdowns": [
"Boum, vitesse du tonnerre !"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Encore plus fou, ces symboles peuvent être enchainés ! Regardez cela :"
],
"afterMarkdowns": [
"Le même résultat, mais en une seule commande."
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Un peu de pratique",
"",
"Pour réussir le niveau, créez une nouvelle branche à la destination indiquée",
"",
"Évidement ce serait plus rapide de spécifier le commit (C6 par exemple), mais faites-le plutôt avec les symboles de déplacement dont nous venons de parler !"
]
}
}
]
},
"zh_CN": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### 选择父提交",
"",
"和`~`修改符一样,`^`修改符之后也可以跟一个(可选的)数字。",
"",
"这不是用来指定向上返回几代(`~`的作用),`^`后的数字指定跟随合并提交记录的哪一个父提交。还记得一个合并提交有多个父提交吧,所有选择哪条路径不是那么清晰。",
"",
"Git默认选择跟随合并提交的\"第一个\"父提交,使用`^`后跟一个数字来改变这一默认行为。",
"",
"废话不多说,举个例子。",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"这里有一个合并提交。如果不加数字修改符直接切换到`master^`,会回到第一个父提交。",
"",
"(*在我们的图示中,第一个父提交是指合并提交正上方的那个父提交。*)"
],
"afterMarkdowns": [
"OK--这恰好是我们想要的。"
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"现在来试试选择第二个父提交……"
],
"afterMarkdowns": [
"看见了吧?我们回到了第二个父提交。"
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"使用`^`和`~`可以自由在在提交树中移动:"
],
"afterMarkdowns": [
"快若闪电!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"再疯狂点,这些修改符支持链式操作!试一下这个:"
],
"afterMarkdowns": [
"和前面的结果一样,但只用了一条命令。"
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### 实践一下",
"",
"要完成此关,在指定的目标位置创建一个新的分支。",
"",
"很明显可以简单的直接使用提交记录的hash值(比如`C6`),但我要求你使用刚刚讲到的相对引用修饰符!"
]
}
}
]
},
"es_AR": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Especificando los padres",
"",
"Como el modificador de `~`, `^` también acepta un número opcional después de él.",
"",
"En lugar de especificar cuántas generaciones hacia atrás ir (como `~`), el modificador de `^` especifica por cuál de las referencias padres seguir en un commit de merge. Recordá que un commit de merge tiene múltiples padres, por lo que el camino a seguir es ambiguo.",
"",
"Git normalmente sigue el \"primer\" padre de un commit de merge, pero especificando un número junto con `^` cambia este comportamiento predefinido.",
"",
"Demasiada charla, veámoslo en acción.",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Acá tenemos un commit de merge. Si hacemos checkout de `master^`, sin modificadores, vamos a seguir al primer padre después del commit de merge. ",
"",
"(*En nuestras visualizaciones, el primer padre se ubica directamente arriba del commit de merge.*)"
],
"afterMarkdowns": [
"Fácil -- esto es a lo que estamos acostumbrados."
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Ahora tratemos de especificar el segundo padre, en cambio..."
],
"afterMarkdowns": [
"¿Ves? Seguimos al otro padre hacia arriba."
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Los modificadores de `^` y `~` son muy poderosos a la hora de movernos en un árbol:"
],
"afterMarkdowns": [
"¡Rapidísimo!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Más loco aún, ¡estos modificadores pueden encadenarse entre sí! Mirá esto:"
],
"afterMarkdowns": [
"El mismo movimiento que antes, pero todo en uno."
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Ponelo en práctica",
"",
"Para completar este nivel, creá una nueva rama en la ubicación indicada.",
"",
"Obviamente sería muy fácil especificar el commit directamente (algo como `C6`), pero te reto a usar los modificadores de los que estuvimos hablando, mejor"
]
}
}
]
},
"pt_BR": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Especificando pais",
"",
"Assim como o modificador `~`, o modificador `^` também aceita um número opcional depois dele.",
"",
"Em vez de especificar o número de gerações a voltar (que é o que o `~` faz), o modificador no `^` especifica qual referência de pai a ser seguida a partir de um commit de merge. Lembre-se que commits de merge possuem múltiplos pais, então o caminho a seguir é ambíguo.",
"",
"O Git normalmente subirá o \"primeiro\" pai de um commit de merge, mas especificar um número após o `^` muda esse comportamento padrão.",
"",
"Basta de conversa, vejamos o operador em ação.",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Aqui temos um commit de merge. Se fizermos checkout em `master^` sem especificar um número, vamos seguir o primeiro pai acima do commit de merge. ",
"",
"(*Em nossa visualização, o primeiro pai é aquele diretamente acima do commit de merge.*)"
],
"afterMarkdowns": [
"Fácil -- isso é aquilo com o que já estamos acostumados."
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Agora vamos, em vez disso, especificar o segundo pai..."
],
"afterMarkdowns": [
"Viu? Subimos para o outro pai."
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Os modificadores `^` e `~` podem tornar a movimentação ao redor da árvore de commits muito poderosa:"
],
"afterMarkdowns": [
"Rápido como a luz!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Ainda mais louco, esses modificadores podem ser encadeados em conjunto! Veja só:"
],
"afterMarkdowns": [
"O mesmo movimento que o anterior, mas tudo em um único comando."
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Coloque em prática",
"",
"Para completar este nível, crie um novo ramo no destino especificado.",
"",
"Obviamente seria mais fácil especificar o commit diretamente (com algo como `C6`), mas em vez disso eu desafio você a usar os modificadores sobre os quais falamos!"
]
}
}
]
},
"zh_TW": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### 選擇 parent commit",
"",
"和 `~` 符號一樣,`^` 符號的後面也可以接一個(可選的)數字。",
"",
"這不是用來指定往上回去幾代(`~` 的作用),`^` 後面所跟的數字表示我要選擇哪一個 parent commit。還記得一個 merge commit 可以有多個 parent commit 吧,所以當我們要選擇走到哪一個 parent commit 的時候就會比較麻煩了。",
"",
"git 預設會選擇 merge commit 的\"第一個\" parent commit,使用 `^` 後面接一個數字可以改變這個預設的行為。",
"",
"廢話不多說,舉一個例子。",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"這裡有一個 merge commit。如果後面不加數字的話會直接切換到`master^`,也就是說會回到第一個 parent commit。",
"",
"(*在我們的圖示中,第一個 parent commit 是指 merge commit 正上方的那一個 parent commit。*)"
],
"afterMarkdowns": [
"簡單吧!這就是預設的情況。"
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"現在來試試選擇第二個 parent commit..."
],
"afterMarkdowns": [
"看到了嗎?我們回到了第二個 parent commit。"
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"使用`^`和`~`可以自由在 commit tree 中移動:"
],
"afterMarkdowns": [
"簡直就像是電光石火!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"再瘋狂點,這些符號可以被連在一起!試一下這個:"
],
"afterMarkdowns": [
"和前面的結果一樣,但只用了一條指令。"
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### 練習一下",
"",
"要完成這一關,在指定的目標位置上面建立一個新的 branch。",
"",
"很明顯可以直接使用 commit 的 hash 值(比如 `C6`),但我要求你使用剛剛講到的相對引用的符號!"
]
}
}
]
},
"ru_RU": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Определение родителей",
"",
"Так же как тильда (~), каретка (^) принимает номер после себя.",
"",
"Но в отличие от количества коммитов, на которые нужно откатиться назад (как делает `~`), номер после `^` определяет на какого из родителей мерджа надо перейти. Учитывая, что мерджевый коммит имеет двух родителей, просто указать ^ нельзя.",
"",
"Git по умолчанию перейдёт на \"первого\" родителя коммита, но указание номера после `^` изменяет это поведение.",
"",
"Посмотрим как это работает.",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Вот мерджевый коммит. Если мы перейдём на master^ без номера, то попадём на первого родителя.",
"",
"(*На нашей визуализации первый родитель находится прямо над коммитом*)"
],
"afterMarkdowns": [
"Просто - прямо как мы любим."
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Теперь попробуем перейти на второго родителя."
],
"afterMarkdowns": [
"Вот. Мы на втором родительском коммите."
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Модификаторы `^` и `~` сильно помогают перемещаться по дереву коммитов:"
],
"afterMarkdowns": [
"Быстро как Флэш!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Более того, эти модификаторы можно применять вместе. Например, так:"
],
"afterMarkdowns": [
"Сделаем то же самое, что перед этим, только в одну команду."
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### На практике",
"",
"Чтобы пройти этот уровень, надо создать ветку в указанном месте.",
"",
"Очевидно, что (в данном случае) будет проще указать коммит напрямую, но для того, чтобы закрепить пройденное, надо использовать модификаторы, о которых мы говорили выше."
]
}
}
]
},
"ja": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### 親の指定",
"",
"`~`修飾子と同じように、`^`修飾子も後に任意の番号を置くことができます。",
"",
"指定した数だけ遡る(これは`~`の場合の機能)のではなく、`^`はマージコミットからどの親を選択するかを指定できます。マージコミットは複数の親で構成されるので、選択する経路が曖昧であることを覚えておいてください。",
"",
"Gitは通常、マージコミットから「一つ目」の親、マージされた側のブランチの親を選びます。しかし、`^`で数を指定することでこのデフォルトの動作を変えることができます。",
"",
"では、実際の動作を見ていきましょう。",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"ここに、マージコミットがあります。もし、指定無しに`master^`でチェックアウトした場合、私たちは一番目の親に移動することになります。",
"",
"(*私たちのツリーでは、一番目の親はマージコミットのちょうど上に位置しています。*)"
],
"afterMarkdowns": [
"簡単ですね -- これがデフォルトの動作になります。"
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"それでは代わりに二つ目の親を指定してみます"
],
"afterMarkdowns": [
"見ましたか?私たちは他の親に移ることができました。"
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"`^`修飾子と`~`修飾子は、コミット履歴を辿るのを強力に補助してくれます:"
],
"afterMarkdowns": [
"超高速ですね!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"より素晴らしいことに、これらの修飾子は連鎖させることができます!これを見てください:"
],
"afterMarkdowns": [
"前と同じ移動ですが、なんと一つのコマンドでできています。"
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### 練習課題",
"",
"このレベルをクリアするためには、まず新しいブランチを指定したように作成します。",
"",
"明らかに直接コミットを指定した方が(`C6`というように)簡単ですが、私は今まで述べたような修飾子を使う方法で挑戦してもらいたいと思います。"
]
}
}
]
},
}
};
|
// Karma configuration
// Generated on Thu Mar 19 2015 17:35:54 GMT+0000 (GMT)
var webpack = require('webpack');
var WATCH = process.argv.indexOf('--watch') > -1;
var MIN = process.argv.indexOf('--min') > -1;
var webpackConfig = {
cache: true,
devtool: 'inline-source-map',
module: {
preLoaders: [{
test: /\.js$/,
loaders: ['eslint'],
exclude: /node_modules/
}],
loaders: [{
test: /\.html$/,
loader: 'html',
exclude: /node_modules/
}],
postLoaders: [{
test: /\.js$/,
exclude: /(test|node_modules)/,
loader: 'istanbul-instrumenter'
}]
},
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
]
};
if (MIN) {
webpackConfig.module.loaders.push({
test: /.*src.*\.js$/,
loaders: ['uglify', 'ng-annotate'],
exclude: /node_modules/
});
}
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai', 'chai-as-promised', 'sinon-chai', 'chai-things'],
// list of files / patterns to load in the browser
files: [
'test/unit/entry.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/unit/entry.js': ['webpack', 'sourcemap']
},
coverageReporter: {
reporters: [{
type: 'text-summary'
}, {
type: 'html'
}]
},
webpack: webpackConfig,
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: WATCH,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: !WATCH
});
};
|
import React from 'react'
import styled from 'styled-components'
import { colors, fontFamily } from '../../style'
import Loader, { StyledLoader } from './Loader'
const Button = styled.button`
display: inline-block;
vertical-align: top;
appearance: none;
outline: none;
border: 0;
border-radius: 2px;
padding: 15px 24px;
font-family: ${fontFamily};
font-size: 1.2rem;
font-weight: 700;
line-height: 1em;
text-align: center;
text-transform: uppercase;
text-decoration: none;
color: white;
background: linear-gradient(to right, ${colors.orange500}, ${colors.red400});
cursor: pointer;
transition: all 120ms ease-out;
will-change: transform, box-shadow;
:hover {
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
${StyledLoader} {
margin-top: 0;
}
`
const LinkedButton = Button.withComponent('a')
export default ({ loading, children, ...props }) => (
<Button {...props}>{loading ? <Loader white /> : children}</Button>
)
export { LinkedButton }
|
import { RenderBuffer } from "./renderbuffer.js";
import { failure } from "../utils.js";
export class FrameBuffer {
constructor(context) {
var _a;
this.context = context;
this.target = WebGL2RenderingContext.FRAMEBUFFER;
this._colorBuffer = null;
this._depthBuffer = null;
this.glFrameBuffer = (_a = context.gl.createFramebuffer()) !== null && _a !== void 0 ? _a : failure("Failed to create a frame buffer!");
}
delete() {
this.context.gl.deleteFramebuffer(this.glFrameBuffer);
}
bind() {
const gl = this.context.gl;
gl.bindFramebuffer(this.target, this.glFrameBuffer);
}
unbind() {
const gl = this.context.gl;
gl.bindFramebuffer(this.target, null);
}
check() {
this.bind();
const result = this.context.gl.checkFramebufferStatus(this.target);
if (result !== WebGL2RenderingContext.FRAMEBUFFER_COMPLETE) {
failure("Frame buffer is in an incomplete status!");
}
}
get colorBuffer() {
return this._colorBuffer;
}
set colorBuffer(buffer) {
this._colorBuffer = this.set(WebGL2RenderingContext.COLOR_ATTACHMENT0, buffer, this._colorBuffer);
}
get depthBuffer() {
return this._depthBuffer;
}
set depthBuffer(buffer) {
this._depthBuffer = this.set(WebGL2RenderingContext.DEPTH_ATTACHMENT, buffer, this._depthBuffer);
}
set(attachment, newBuffer, oldBuffer) {
const gl = this.context.gl;
this.bind();
if (newBuffer !== oldBuffer) {
if (oldBuffer != null) {
if (oldBuffer instanceof RenderBuffer) {
gl.framebufferRenderbuffer(this.target, attachment, oldBuffer.target, null);
}
else {
gl.framebufferTexture2D(this.target, attachment, oldBuffer.target, null, 0);
}
}
if (newBuffer != null) {
newBuffer.bind();
if (newBuffer instanceof RenderBuffer) {
gl.framebufferRenderbuffer(this.target, attachment, newBuffer.target, newBuffer.glRenderBuffer);
}
else {
gl.framebufferTexture2D(this.target, attachment, newBuffer.target, newBuffer.glTexture, 0);
}
}
}
return newBuffer;
}
}
//# sourceMappingURL=framebuffer.js.map
|
import Vue from 'vue'
const style = {
position: 'relative',
backgroundColor: '#808080',
background: 'linear-gradient(-90deg, rgba(0, 0, 0, .1) 1px, transparent 1px), linear-gradient(rgba(0, 0, 0, .1) 1px, transparent 1px)',
backgroundSize: '20px 20px, 20px 20px',
backgroundPosition: '10px 10px',
height: '400px',
width: '400px',
border: '1px solid blue',
boxSizing: 'content-box'
}
export default () => ({
template: `
<div>
<div :style='${JSON.stringify(style)}'>
<vue-draggable-resizable :parent="true" :grid=[20,20] :x="x" :y="y" :h="h" :w="w" @dragging="onDrag" @resizing="onResize">
<p>You cannot move me or resize me outside my parent.</p>
</vue-draggable-resizable>
</div>
<div id="toolbar">
X: <input type="number" v-model.number="x" />
Y: <input type="number" v-model.number="y" />
Width: <input type="number" v-model.number="w" />
Height: <input type="number" v-model.number="h" />
</div>
</div>
`,
data() {
return {
x: 10,
y: 10,
w: 100,
h: 100
}
},
methods: {
onDrag(left, top) {
this.x = left;
this.y = top;
},
onResize(left, top, width, height) {
this.x = left
this.y = top
this.w = width
this.h = height
}
}
})
|
var searchData=
[
['robot',['Robot',['../class_robot.html#a4fc7c70ae20623f05e06f2ecb388b6c4',1,'Robot::Robot()'],['../class_robot.html#a0e6819bf54f9cb47a4147ce6e883ff06',1,'Robot::Robot(std::string str)']]],
['run',['run',['../class_robot.html#a68db0807318b24bf97b590217687f14a',1,'Robot']]]
];
|
Core.soundManager = function(audios, options) {
var created = {};
var playing = {};
var _play = function(id) {
_load(id);
if(sessionStorage.soundDisabled !== 'true') {
playing[id] = created[id];
created[id].play();
}
};
var _stop = function(id) {
if(!playing[id]) { return; }
playing[id].pause();
playing[id].currentTime = 0;
delete playing[id];
};
var _remove = function() {
//todo
};
//todo... (mute by id)...
var _mute = function() {
if(sessionStorage.soundDisabled !== 'true') {
sessionStorage.soundDisabled = 'true';
for(var prop in playing) {
_stop(prop);
}
} else {
sessionStorage.soundDisabled = 'false';
for(var prop in created) {
if(created[prop].loop) {
console.log(prop);
_play(prop);
}
}
}
};
var _load = function(id) {
if(!created[id]) {
created[id] = Core.insertMedia({
audio: true,
source: options.path + audios[id].src
});
if(audios[id].loop) {
created[id].loop = true;
}
if(audios[id].volume) {
created[id].volume = audios[id].volume;
}
}
};
return {
play: _play,
stop: _stop,
remove: _remove,
load: _load,
mute: _mute
};
};
|
var db = require('../config/db');
var sanitizeHtml = require('sanitize-html');
var htmlToText = require('html-to-text');
var NoteSchema = db.Schema({
title: String,
body_html: String,
body_text: String,
user: { type: db.Schema.Types.ObjectId, ref: 'User' },
updated_at: { type: Date, default: Date.now }
});
NoteSchema.pre('save', function(next) {
this.updated_at = Date.now();
this.body_html = sanitizeHtml(this.body_html);
this.body_text = htmlToText.fromString(this.body_html);
next();
});
module.exports = NoteSchema;
|
/* jshint undef:false*/
(function() {
'use strict';
describe('HomeCtrl', function() {
var rootScope;
var ctrl;
var scope;
beforeEach(module('app'));
beforeEach(inject(function($rootScope, $controller) {
rootScope = $rootScope;
scope = $rootScope.$new();
ctrl = $controller('HomeCtrl as home', {
$scope: scope
});
}));
/*
it('should not be null', function() {
expect(ctrl).not.toEqual(null);
});
*/
});
})();
|
const spawn = require('child_process').spawn;
const path = require('path')
const mkdirp = require('mkdirp');
const electron = require('electron');
const ipc = electron.ipcRenderer;
const remote = electron.remote;
const app = remote.app;
const win = remote.getCurrentWindow();
const parentWin = win.getParentWindow();
const path_sounds = path.join(app.getPath("userData"), 'audioData', 'sounds')
const path_musics = path.join(app.getPath("userData"), 'audioData', 'musics')
const path_loops = path.join(app.getPath("userData"), 'audioData', 'loops')
mkdirp(path_sounds);
mkdirp(path_musics);
mkdirp(path_loops);
console.log(path_loops);
var db = remote.getGlobal("db");
var gm_music = remote.getGlobal("gm_music");
// gm_music = require('./gm_music_lib/bin/win32-x64-53/gm_music_lib.node');
// gm_music.initialize();
// gm_music.openDefaultStream();
// const dialog = remote.dialog;
// const menu = remote.Menu;
// win.webContents.openDevTools();
// Prevents the middle click scroll behavior
document.body.onmousedown = e => {
if (e.button === 1) return false;
};
var canClose = false;
window.onbeforeunload = (e) => {
if (!canClose) {
e.returnValue = false
win.hide();
}
else{
// gm_music.closeStream();
// gm_music.terminate();
}
}
function addTableElem(_type, desc) {
var entryType = $jquery("<td name='type'/>");
entryType.text('['+_type+']');
var entryDesc = $jquery("<td name='desc'/>");
entryDesc.text(desc);
var entryResult = $jquery("<td name='res'/>");
entryResult.text("...");
var line = $jquery("<tr/>")
line.append(entryType);
line.append(entryDesc);
line.append(entryResult);
$jquery('#table').append(line);
return line;
}
function getJobDesc(message) {
switch (message.type) {
case "jobClose":
return "Close this window.";
case "jobNewSound":
return "Import the sound file '"+message.data.path+"'";
case "jobNewMusic":
return "Import the music file '"+message.data.path+"'";
case "jobMusicLoad":
return "Loading the music file '"+message.data.filename+"'";
case "jobMusicUnload":
return "Unloading the music file '"+message.data.filename+"'";
default:
return "@todo: add job description";
}
}
var dfd = $jquery.Deferred() // Master deferred
var dfdNext = dfd; // Next deferred in the chain
var x = 0 // Loop index
var values = []
dfd.resolve();
ipc.on('newJob', pushJob);
function pushJob(event, message) {
var rec = JSON.parse(message);
var tableLine = addTableElem(rec.type, getJobDesc(rec));
values.push([rec, tableLine]);
sendParent("working", values.length)
dfdNext = dfdNext.then(function () {
var value = values.shift();
return doNextJobs({ type: value[0].type, data: value[0].data }).then((res)=>{
sendParent("working", values.length)
if (res.ok) {
value[1].find("td[name='res']").text("ok");
value[1].addClass("ok");
}else{
sendParent("error", res.msg);
value[1].addClass("nok");
value[1].find("td[name='res']").text("err");
var errLine = $jquery("<tr class='error' />");
errLine.append($jquery("<td colspan='3' />").text(res.msg));
value[1].after(errLine);
}
});
});
}
function sendParent(type, data) {
parentWin.webContents.send("worker_msg", JSON.stringify({ type: type, data: data }));
}
function doNextJobs(job) {
var dfdJob = $jquery.Deferred();
switch (job.type) {
case "jobClose":
canClose = true;
win.close();
dfdJob.resolve({ok: true, msg: ""});
break;
case "jobNewSound":
jobImportAudioFile(job.data, 'sound', dfdJob);
break;
case "jobNewMusic":
jobImportAudioFile(job.data, 'music', dfdJob);
break;
case "jobMusicLoad":
jobMusicLoad(job.data, dfdJob);
break;
case "jobMusicUnload":
jobMusicUnload(job.data, dfdJob);
break;
default:
console.error("Job unknown !", job);
// sendParent("error", "Tried to start an unknown job ! [" + job.type + "]");
dfdJob.resolve({ok: false, msg: "Tried to run an unknown job ! [" + job.type + "]"});
}
return dfdJob.promise();
}
function jobMusicLoad(data, dfd) {
if(data.slot == null){
// We can't load the file right now, no slot free left
dfd.resolve({ok: false, msg: "No Free Slot left"});
}
var file_path = path.join(path_musics, data.filename);
gm_music.music_load(data.slot, file_path);
sendParent('music_loaded', data);
dfd.resolve({ok: true, msg: ""});
}
function jobMusicUnload(data, dfd) {
gm_music.music_unload(data.slot);
sendParent('music_unloaded', data);
dfd.resolve({ok: true, msg: ""});
}
function jobImportAudioFile(data, type, dfd) {
//{path: filePaths[i], parent_key: data.node.key}
input_path = data.path;
parent_key = data.parent_key;
// Convert the file to the right type and copy the result in the right folder, with a generated unique name.
// 1. Define the name
// 1.1 Create an entry in the db which is labeled 'deleted' to get the id
input_info = path.parse(input_path);
db.insert({ title: input_info.name, is_folder: false, parent: parent_key, deleted: true, type: type }, function(err, newDocs) {
if(err!=null){
dfd.resolve({ok: false, msg: "Error while inserting the entry in the database"});
return;
}
var key = newDocs._id;
console.log("Converting the file...", input_info.name);
var child;
if(type=='music'){
child = spawn('sox.exe', [input_path, '-r', '44100', '-t', 'ogg', path.join(path_musics, key)], { cwd: './include/sox/' });
}
else if(type=='sound'){
child = spawn('sox.exe', [input_path, '-r', '44100', '-t', 'ogg', path.join(path_sounds, key)], { cwd: './include/sox/' });
}
else{
dfd.resolve({ok: false, msg: "Type Unknown!"});
}
child.on('exit', function(code) {
if (code != 0) {
child.stderr.on('data', data => {
console.log(`stderr: ${data}`);
});
dfd.resolve({ok: false, msg: "Error while converting the file"});
return;
}
console.log("Converted !");
db.update({_id: key}, {$set: {deleted: false}}, {}, (err, numAffected)=>{
if(err!=null){
dfd.resolve({ok: false, msg: "Error while updating the database entry !"});
return;
}
sendParent('file_imported', {title: input_info.name, key: key, parent_key: parent_key, type: type});
dfd.resolve({ok: true, msg: ""});
return;
});
});
});
}
// document.addEventListener("DOMContentLoaded", () => {});
// Debug Functions
function sleepFor(sleepDuration) {
var now = new Date().getTime();
while (new Date().getTime() < now + sleepDuration) { /* do nothing */ }
}
|
var should = require('should'),
sinon = require('sinon'),
versionMatch = require('../../../../../server/web/shared/middlewares/api/version-match');
describe('Version Mismatch', function () {
var req, res, getStub, nextStub;
afterEach(function () {
sinon.restore();
});
beforeEach(function () {
getStub = sinon.stub();
nextStub = sinon.stub();
req = {
get: getStub
};
res = {
locals: {}
};
});
function testVersionMatch(serverVersion, clientVersion) {
// Set the server version
res.locals.version = serverVersion;
if (clientVersion) {
// Optionally set the client version
getStub.returns(clientVersion);
}
versionMatch(req, res, nextStub);
}
it('should call next if request does not include a version', function () {
var server = '1.5.1';
testVersionMatch(server);
nextStub.calledOnce.should.be.true();
nextStub.firstCall.args.should.be.empty();
});
it('should call next if versions are an exact match', function () {
var server = '1.5.0',
client = '1.5';
testVersionMatch(server, client);
nextStub.calledOnce.should.be.true();
nextStub.firstCall.args.should.be.empty();
});
it('should call next if client version is earlier than server', function () {
var server = '1.5.0',
client = '1.3';
testVersionMatch(server, client);
nextStub.calledOnce.should.be.true();
nextStub.firstCall.args.should.be.empty();
});
it('should throw VersionMismatchError if client version is earlier by a major version', function () {
var server = '2.5.0',
client = '1.3';
testVersionMatch(server, client);
nextStub.calledOnce.should.be.true();
nextStub.firstCall.args.should.have.lengthOf(1);
nextStub.firstCall.args[0].should.have.property('errorType', 'VersionMismatchError');
nextStub.firstCall.args[0].should.have.property('statusCode', 400);
});
it('should throw VersionMismatchError if client version is later than server', function () {
var server = '1.3.0',
client = '1.5';
testVersionMatch(server, client);
nextStub.calledOnce.should.be.true();
nextStub.firstCall.args.should.have.lengthOf(1);
nextStub.firstCall.args[0].should.have.property('errorType', 'VersionMismatchError');
nextStub.firstCall.args[0].should.have.property('statusCode', 400);
});
it('should throw VersionMismatchError if client version is later by a major version', function () {
var server = '1.5.0',
client = '2.3';
testVersionMatch(server, client);
nextStub.calledOnce.should.be.true();
nextStub.firstCall.args.should.have.lengthOf(1);
nextStub.firstCall.args[0].should.have.property('errorType', 'VersionMismatchError');
nextStub.firstCall.args[0].should.have.property('statusCode', 400);
});
it('should call next if pre-release is allowed', function () {
var server = '1.5.0-pre',
client = '1.4';
testVersionMatch(server, client);
nextStub.calledOnce.should.be.true();
nextStub.firstCall.args.should.be.empty();
});
it('throws error if server is a pre-release, but later by major version', function () {
var server = '2.0.0-alpha',
client = '1.5';
testVersionMatch(server, client);
nextStub.calledOnce.should.be.true();
nextStub.firstCall.args.should.have.lengthOf(1);
nextStub.firstCall.args[0].should.have.property('errorType', 'VersionMismatchError');
nextStub.firstCall.args[0].should.have.property('statusCode', 400);
});
});
|
/*!
* Native JavaScript for Bootstrap v4.0.0 (https://thednp.github.io/bootstrap.native/)
* Copyright 2015-2021 © dnp_theme
* Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE)
*/
var transitionEndEvent = 'webkitTransition' in document.head.style ? 'webkitTransitionEnd' : 'transitionend';
var supportTransition = 'webkitTransition' in document.head.style || 'transition' in document.head.style;
var transitionDuration = 'webkitTransition' in document.head.style ? 'webkitTransitionDuration' : 'transitionDuration';
var transitionProperty = 'webkitTransition' in document.head.style ? 'webkitTransitionProperty' : 'transitionProperty';
function getElementTransitionDuration(element) {
var computedStyle = getComputedStyle(element);
var propertyValue = computedStyle[transitionProperty];
var durationValue = computedStyle[transitionDuration];
var durationScale = durationValue.includes('ms') ? 1 : 1000;
var duration = supportTransition && propertyValue && propertyValue !== 'none'
? parseFloat(durationValue) * durationScale : 0;
return !Number.isNaN(duration) ? duration : 0;
}
function emulateTransitionEnd(element, handler) {
var called = 0;
var endEvent = new Event(transitionEndEvent);
var duration = getElementTransitionDuration(element);
if (duration) {
element.addEventListener(transitionEndEvent, function transitionEndWrapper(e) {
if (e.target === element) {
handler.apply(element, [e]);
element.removeEventListener(transitionEndEvent, transitionEndWrapper);
called = 1;
}
});
setTimeout(function () {
if (!called) { element.dispatchEvent(endEvent); }
}, duration + 17);
} else {
handler.apply(element, [endEvent]);
}
}
function queryElement(selector, parent) {
var lookUp = parent && parent instanceof Element ? parent : document;
return selector instanceof Element ? selector : lookUp.querySelector(selector);
}
function bootstrapCustomEvent(eventType, componentName, eventProperties) {
var OriginalCustomEvent = new CustomEvent((eventType + ".bs." + componentName), { cancelable: true });
if (typeof eventProperties !== 'undefined') {
Object.keys(eventProperties).forEach(function (key) {
Object.defineProperty(OriginalCustomEvent, key, {
value: eventProperties[key],
});
});
}
return OriginalCustomEvent;
}
function dispatchCustomEvent(customEvent) {
if (this) { this.dispatchEvent(customEvent); }
}
/* Native JavaScript for Bootstrap 4 | Alert
-------------------------------------------- */
// ALERT DEFINITION
// ================
function Alert(elem) {
var element;
// bind
var self = this;
// the target alert
var alert;
// custom events
var closeCustomEvent = bootstrapCustomEvent('close', 'alert');
var closedCustomEvent = bootstrapCustomEvent('closed', 'alert');
// private methods
function triggerHandler() {
if (alert.classList.contains('fade')) { emulateTransitionEnd(alert, transitionEndHandler); }
else { transitionEndHandler(); }
}
function toggleEvents(add) {
var action = add ? 'addEventListener' : 'removeEventListener';
element[action]('click', clickHandler, false);
}
// event handlers
function clickHandler(e) {
alert = e && e.target.closest('.alert');
element = queryElement('[data-dismiss="alert"]', alert);
if (element && alert && (element === e.target || element.contains(e.target))) { self.close(); }
}
function transitionEndHandler() {
toggleEvents();
alert.parentNode.removeChild(alert);
dispatchCustomEvent.call(alert, closedCustomEvent);
}
// PUBLIC METHODS
self.close = function () {
if (alert && element && alert.classList.contains('show')) {
dispatchCustomEvent.call(alert, closeCustomEvent);
if (closeCustomEvent.defaultPrevented) { return; }
self.dispose();
alert.classList.remove('show');
triggerHandler();
}
};
self.dispose = function () {
toggleEvents();
delete element.Alert;
};
// INIT
// initialization element
element = queryElement(elem);
// find the target alert
alert = element.closest('.alert');
// reset on re-init
if (element.Alert) { element.Alert.dispose(); }
// prevent adding event handlers twice
if (!element.Alert) { toggleEvents(1); }
// store init object within target element
self.element = element;
element.Alert = self;
}
/* Native JavaScript for Bootstrap 4 | Button
---------------------------------------------*/
// BUTTON DEFINITION
// =================
function Button(elem) {
var element;
// bind and labels
var self = this;
var labels;
// changeEvent
var changeCustomEvent = bootstrapCustomEvent('change', 'button');
// private methods
function toggle(e) {
var eTarget = e.target;
var parentLabel = eTarget.closest('LABEL'); // the .btn label
var label = null;
if (eTarget.tagName === 'LABEL') {
label = eTarget;
} else if (parentLabel) {
label = parentLabel;
}
// current input
var input = label && label.getElementsByTagName('INPUT')[0];
// invalidate if no input
if (!input) { return; }
dispatchCustomEvent.call(input, changeCustomEvent); // trigger the change for the input
dispatchCustomEvent.call(element, changeCustomEvent); // trigger the change for the btn-group
// manage the dom manipulation
if (input.type === 'checkbox') { // checkboxes
if (changeCustomEvent.defaultPrevented) { return; } // discontinue when defaultPrevented is true
if (!input.checked) {
label.classList.add('active');
input.getAttribute('checked');
input.setAttribute('checked', 'checked');
input.checked = true;
} else {
label.classList.remove('active');
input.getAttribute('checked');
input.removeAttribute('checked');
input.checked = false;
}
if (!element.toggled) { // prevent triggering the event twice
element.toggled = true;
}
}
if (input.type === 'radio' && !element.toggled) { // radio buttons
if (changeCustomEvent.defaultPrevented) { return; }
// don't trigger if already active
// (the OR condition is a hack to check if the buttons were selected
// with key press and NOT mouse click)
if (!input.checked || (e.screenX === 0 && e.screenY === 0)) {
label.classList.add('active');
label.classList.add('focus');
input.setAttribute('checked', 'checked');
input.checked = true;
element.toggled = true;
Array.from(labels).forEach(function (otherLabel) {
var otherInput = otherLabel.getElementsByTagName('INPUT')[0];
if (otherLabel !== label && otherLabel.classList.contains('active')) {
dispatchCustomEvent.call(otherInput, changeCustomEvent); // trigger the change
otherLabel.classList.remove('active');
otherInput.removeAttribute('checked');
otherInput.checked = false;
}
});
}
}
setTimeout(function () { element.toggled = false; }, 50);
}
// handlers
function keyHandler(e) {
var key = e.which || e.keyCode;
if (key === 32 && e.target === document.activeElement) { toggle(e); }
}
function preventScroll(e) {
var key = e.which || e.keyCode;
if (key === 32) { e.preventDefault(); }
}
function focusToggle(e) {
if (e.target.tagName === 'INPUT') {
var action = e.type === 'focusin' ? 'add' : 'remove';
e.target.closest('.btn').classList[action]('focus');
}
}
function toggleEvents(add) {
var action = add ? 'addEventListener' : 'removeEventListener';
element[action]('click', toggle, false);
element[action]('keyup', keyHandler, false);
element[action]('keydown', preventScroll, false);
element[action]('focusin', focusToggle, false);
element[action]('focusout', focusToggle, false);
}
// public method
self.dispose = function () {
toggleEvents();
delete element.Button;
};
// init
// initialization element
element = queryElement(elem);
// reset on re-init
if (element.Button) { element.Button.dispose(); }
labels = element.getElementsByClassName('btn');
// invalidate
if (!labels.length) { return; }
// prevent adding event handlers twice
if (!element.Button) { toggleEvents(1); }
// set initial toggled state
// toggled makes sure to prevent triggering twice the change.bs.button events
element.toggled = false;
// associate target with init object
element.Button = self;
// activate items on load
Array.from(labels).forEach(function (btn) {
var hasChecked = queryElement('input:checked', btn);
if (!btn.classList.contains('active') && hasChecked) {
btn.classList.add('active');
}
if (btn.classList.contains('active') && !hasChecked) {
btn.classList.remove('active');
}
});
}
var mouseHoverEvents = ('onmouseleave' in document) ? ['mouseenter', 'mouseleave'] : ['mouseover', 'mouseout'];
var addEventListener = 'addEventListener';
var removeEventListener = 'removeEventListener';
var supportPassive = (function () {
var result = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function get() {
result = true;
return result;
},
});
document[addEventListener]('DOMContentLoaded', function wrap() {
document[removeEventListener]('DOMContentLoaded', wrap, opts);
}, opts);
} catch (e) {
throw Error('Passive events are not supported');
}
return result;
})();
// general event options
var passiveHandler = supportPassive ? { passive: true } : false;
function isElementInScrollRange(element) {
var bcr = element.getBoundingClientRect();
var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
return bcr.top <= viewportHeight && bcr.bottom >= 0; // bottom && top
}
function reflow(element) {
return element.offsetHeight;
}
/* Native JavaScript for Bootstrap 4 | Carousel
----------------------------------------------- */
// CAROUSEL DEFINITION
// ===================
function Carousel(elem, opsInput) {
var assign, assign$1, assign$2;
var element;
// set options
var options = opsInput || {};
// bind
var self = this;
// internal variables
var vars;
var ops;
// custom events
var slideCustomEvent;
var slidCustomEvent;
// carousel elements
var slides;
var leftArrow;
var rightArrow;
var indicator;
var indicators;
// handlers
function pauseHandler() {
if (ops.interval !== false && !element.classList.contains('paused')) {
element.classList.add('paused');
if (!vars.isSliding) {
clearInterval(vars.timer);
vars.timer = null;
}
}
}
function resumeHandler() {
if (ops.interval !== false && element.classList.contains('paused')) {
element.classList.remove('paused');
if (!vars.isSliding) {
clearInterval(vars.timer);
vars.timer = null;
self.cycle();
}
}
}
function indicatorHandler(e) {
e.preventDefault();
if (vars.isSliding) { return; }
var eventTarget = e.target; // event target | the current active item
if (eventTarget && !eventTarget.classList.contains('active') && eventTarget.getAttribute('data-slide-to')) {
vars.index = +(eventTarget.getAttribute('data-slide-to'));
} else { return; }
self.slideTo(vars.index); // Do the slide
}
function controlsHandler(e) {
e.preventDefault();
if (vars.isSliding) { return; }
var eventTarget = e.currentTarget || e.srcElement;
if (eventTarget === rightArrow) {
vars.index += 1;
} else if (eventTarget === leftArrow) {
vars.index -= 1;
}
self.slideTo(vars.index); // Do the slide
}
function keyHandler(ref) {
var which = ref.which;
if (vars.isSliding) { return; }
switch (which) {
case 39:
vars.index += 1;
break;
case 37:
vars.index -= 1;
break;
default: return;
}
self.slideTo(vars.index); // Do the slide
}
function toggleEvents(add) {
var action = add ? 'addEventListener' : 'removeEventListener';
if (ops.pause && ops.interval) {
element[action](mouseHoverEvents[0], pauseHandler, false);
element[action](mouseHoverEvents[1], resumeHandler, false);
element[action]('touchstart', pauseHandler, passiveHandler);
element[action]('touchend', resumeHandler, passiveHandler);
}
if (ops.touch && slides.length > 1) { element[action]('touchstart', touchDownHandler, passiveHandler); }
if (rightArrow) { rightArrow[action]('click', controlsHandler, false); }
if (leftArrow) { leftArrow[action]('click', controlsHandler, false); }
if (indicator) { indicator[action]('click', indicatorHandler, false); }
if (ops.keyboard) { window[action]('keydown', keyHandler, false); }
}
// touch events
function toggleTouchEvents(add) {
var action = add ? 'addEventListener' : 'removeEventListener';
element[action]('touchmove', touchMoveHandler, passiveHandler);
element[action]('touchend', touchEndHandler, passiveHandler);
}
function touchDownHandler(e) {
if (vars.isTouch) { return; }
vars.touchPosition.startX = e.changedTouches[0].pageX;
if (element.contains(e.target)) {
vars.isTouch = true;
toggleTouchEvents(1);
}
}
function touchMoveHandler(e) {
if (!vars.isTouch) { e.preventDefault(); return; }
vars.touchPosition.currentX = e.changedTouches[0].pageX;
// cancel touch if more than one changedTouches detected
if (e.type === 'touchmove' && e.changedTouches.length > 1) {
e.preventDefault();
}
}
function touchEndHandler(e) {
if (!vars.isTouch || vars.isSliding) { return; }
vars.touchPosition.endX = vars.touchPosition.currentX || e.changedTouches[0].pageX;
if (vars.isTouch) {
if ((!element.contains(e.target) || !element.contains(e.relatedTarget))
&& Math.abs(vars.touchPosition.startX - vars.touchPosition.endX) < 75) {
return;
}
if (vars.touchPosition.currentX < vars.touchPosition.startX) {
vars.index += 1;
} else if (vars.touchPosition.currentX > vars.touchPosition.startX) {
vars.index -= 1;
}
vars.isTouch = false;
self.slideTo(vars.index);
toggleTouchEvents(); // remove
}
}
// private methods
function setActivePage(pageIndex) { // indicators
Array.from(indicators).forEach(function (x) { return x.classList.remove('active'); });
if (indicators[pageIndex]) { indicators[pageIndex].classList.add('active'); }
}
function transitionEndHandler(e) {
if (vars.touchPosition) {
var next = vars.index;
var timeout = e && e.target !== slides[next] ? e.elapsedTime * 1000 + 100 : 20;
var activeItem = self.getActiveIndex();
var orientation = vars.direction === 'left' ? 'next' : 'prev';
if (vars.isSliding) {
setTimeout(function () {
if (vars.touchPosition) {
vars.isSliding = false;
slides[next].classList.add('active');
slides[activeItem].classList.remove('active');
slides[next].classList.remove(("carousel-item-" + orientation));
slides[next].classList.remove(("carousel-item-" + (vars.direction)));
slides[activeItem].classList.remove(("carousel-item-" + (vars.direction)));
dispatchCustomEvent.call(element, slidCustomEvent);
// check for element, might have been disposed
if (!document.hidden && ops.interval && !element.classList.contains('paused')) {
self.cycle();
}
}
}, timeout);
}
}
}
// public methods
self.cycle = function () {
if (vars.timer) {
clearInterval(vars.timer);
vars.timer = null;
}
vars.timer = setInterval(function () {
var idx = vars.index || self.getActiveIndex();
if (isElementInScrollRange(element)) {
idx += 1;
self.slideTo(idx);
}
}, ops.interval);
};
self.slideTo = function (idx) {
if (vars.isSliding) { return; } // when controled via methods, make sure to check again
// the current active, orientation, event eventProperties
var activeItem = self.getActiveIndex();
var next = idx;
// first return if we're on the same item #227
if (activeItem === next) {
return;
// or determine slide direction
} if ((activeItem < next) || (activeItem === 0 && next === slides.length - 1)) {
vars.direction = 'left'; // next
} else if ((activeItem > next) || (activeItem === slides.length - 1 && next === 0)) {
vars.direction = 'right'; // prev
}
// find the right next index
if (next < 0) { next = slides.length - 1; }
else if (next >= slides.length) { next = 0; }
var orientation = vars.direction === 'left' ? 'next' : 'prev'; // determine type
var eventProperties = {
relatedTarget: slides[next], direction: vars.direction, from: activeItem, to: next,
};
slideCustomEvent = bootstrapCustomEvent('slide', 'carousel', eventProperties);
slidCustomEvent = bootstrapCustomEvent('slid', 'carousel', eventProperties);
dispatchCustomEvent.call(element, slideCustomEvent); // here we go with the slide
if (slideCustomEvent.defaultPrevented) { return; } // discontinue when prevented
// update index
vars.index = next;
vars.isSliding = true;
clearInterval(vars.timer);
vars.timer = null;
setActivePage(next);
if (getElementTransitionDuration(slides[next]) && element.classList.contains('slide')) {
slides[next].classList.add(("carousel-item-" + orientation));
reflow(slides[next]);
slides[next].classList.add(("carousel-item-" + (vars.direction)));
slides[activeItem].classList.add(("carousel-item-" + (vars.direction)));
emulateTransitionEnd(slides[next], transitionEndHandler);
} else {
slides[next].classList.add('active');
reflow(slides[next]);
slides[activeItem].classList.remove('active');
setTimeout(function () {
vars.isSliding = false;
// check for element, might have been disposed
if (ops.interval && element && !element.classList.contains('paused')) {
self.cycle();
}
dispatchCustomEvent.call(element, slidCustomEvent);
}, 100);
}
};
self.getActiveIndex = function () { return Array.from(slides).indexOf(element.getElementsByClassName('carousel-item active')[0]) || 0; };
self.dispose = function () {
var itemClasses = ['left', 'right', 'prev', 'next'];
Array.from(slides).forEach(function (slide, idx) {
if (slide.classList.contains('active')) { setActivePage(idx); }
itemClasses.forEach(function (cls) { return slide.classList.remove(("carousel-item-" + cls)); });
});
clearInterval(vars.timer);
toggleEvents();
vars = {};
ops = {};
delete element.Carousel;
};
// init
// initialization element
element = queryElement(elem);
// reset on re-init
if (element.Carousel) { element.Carousel.dispose(); }
// carousel elements
slides = element.getElementsByClassName('carousel-item');
(assign = element.getElementsByClassName('carousel-control-prev'), leftArrow = assign[0]);
(assign$1 = element.getElementsByClassName('carousel-control-next'), rightArrow = assign$1[0]);
(assign$2 = element.getElementsByClassName('carousel-indicators'), indicator = assign$2[0]);
indicators = (indicator && indicator.getElementsByTagName('LI')) || [];
// invalidate when not enough items
if (slides.length < 2) { return; }
// check options
// DATA API
var intervalAttribute = element.getAttribute('data-interval');
var intervalData = intervalAttribute === 'false' ? 0 : +(intervalAttribute);
var touchData = element.getAttribute('data-touch') === 'false' ? 0 : 1;
var pauseData = element.getAttribute('data-pause') === 'hover' || false;
var keyboardData = element.getAttribute('data-keyboard') === 'true' || false;
// JS options
var intervalOption = options.interval;
var touchOption = options.touch;
// set instance options
ops = {};
ops.keyboard = options.keyboard === true || keyboardData;
ops.pause = (options.pause === 'hover' || pauseData) ? 'hover' : false; // false / hover
ops.touch = touchOption || touchData;
ops.interval = 5000; // bootstrap carousel default interval
if (typeof intervalOption === 'number') { ops.interval = intervalOption; }
else if (intervalOption === false || intervalData === 0 || intervalData === false) {
ops.interval = 0;
} else if (!Number.isNaN(intervalData)) { ops.interval = intervalData; }
// set first slide active if none
if (self.getActiveIndex() < 0) {
if (slides.length) { slides[0].classList.add('active'); }
if (indicators.length) { setActivePage(0); }
}
// set initial state
vars = {};
vars.direction = 'left';
vars.index = 0;
vars.timer = null;
vars.isSliding = false;
vars.isTouch = false;
vars.touchPosition = {
startX: 0,
currentX: 0,
endX: 0,
};
// attach event handlers
toggleEvents(1);
// start to cycle if interval is set
if (ops.interval) { self.cycle(); }
// associate init object to target
element.Carousel = self;
}
/* Native JavaScript for Bootstrap 4 | Collapse
----------------------------------------------- */
// COLLAPSE DEFINITION
// ===================
function Collapse(elem, opsInput) {
var element;
// set options
var options = opsInput || {};
// bind
var self = this;
// target practice
var accordion = null;
var collapse = null;
var activeCollapse;
var activeElement;
// custom events
var showCustomEvent;
var shownCustomEvent;
var hideCustomEvent;
var hiddenCustomEvent;
// private methods
function openAction(collapseElement, toggle) {
dispatchCustomEvent.call(collapseElement, showCustomEvent);
if (showCustomEvent.defaultPrevented) { return; }
collapseElement.isAnimating = true;
collapseElement.classList.add('collapsing');
collapseElement.classList.remove('collapse');
collapseElement.style.height = (collapseElement.scrollHeight) + "px";
emulateTransitionEnd(collapseElement, function () {
collapseElement.isAnimating = false;
collapseElement.setAttribute('aria-expanded', 'true');
toggle.setAttribute('aria-expanded', 'true');
collapseElement.classList.remove('collapsing');
collapseElement.classList.add('collapse');
collapseElement.classList.add('show');
collapseElement.style.height = '';
dispatchCustomEvent.call(collapseElement, shownCustomEvent);
});
}
function closeAction(collapseElement, toggle) {
dispatchCustomEvent.call(collapseElement, hideCustomEvent);
if (hideCustomEvent.defaultPrevented) { return; }
collapseElement.isAnimating = true;
collapseElement.style.height = (collapseElement.scrollHeight) + "px"; // set height first
collapseElement.classList.remove('collapse');
collapseElement.classList.remove('show');
collapseElement.classList.add('collapsing');
reflow(collapseElement); // force reflow to enable transition
collapseElement.style.height = '0px';
emulateTransitionEnd(collapseElement, function () {
collapseElement.isAnimating = false;
collapseElement.setAttribute('aria-expanded', 'false');
toggle.setAttribute('aria-expanded', 'false');
collapseElement.classList.remove('collapsing');
collapseElement.classList.add('collapse');
collapseElement.style.height = '';
dispatchCustomEvent.call(collapseElement, hiddenCustomEvent);
});
}
// public methods
self.toggle = function (e) {
if ((e && e.target.tagName === 'A') || element.tagName === 'A') { e.preventDefault(); }
if (element.contains(e.target) || e.target === element) {
if (!collapse.classList.contains('show')) { self.show(); }
else { self.hide(); }
}
};
self.hide = function () {
if (collapse.isAnimating) { return; }
closeAction(collapse, element);
element.classList.add('collapsed');
};
self.show = function () {
var assign;
if (accordion) {
(assign = accordion.getElementsByClassName('collapse show'), activeCollapse = assign[0]);
activeElement = activeCollapse && (queryElement(("[data-target=\"#" + (activeCollapse.id) + "\"]"), accordion)
|| queryElement(("[href=\"#" + (activeCollapse.id) + "\"]"), accordion));
}
if (!collapse.isAnimating) {
if (activeElement && activeCollapse !== collapse) {
closeAction(activeCollapse, activeElement);
activeElement.classList.add('collapsed');
}
openAction(collapse, element);
element.classList.remove('collapsed');
}
};
self.dispose = function () {
element.removeEventListener('click', self.toggle, false);
delete element.Collapse;
};
// init
// initialization element
element = queryElement(elem);
// reset on re-init
if (element.Collapse) { element.Collapse.dispose(); }
// DATA API
var accordionData = element.getAttribute('data-parent');
// custom events
showCustomEvent = bootstrapCustomEvent('show', 'collapse');
shownCustomEvent = bootstrapCustomEvent('shown', 'collapse');
hideCustomEvent = bootstrapCustomEvent('hide', 'collapse');
hiddenCustomEvent = bootstrapCustomEvent('hidden', 'collapse');
// determine targets
collapse = queryElement(options.target || element.getAttribute('data-target') || element.getAttribute('href'));
if (collapse !== null) { collapse.isAnimating = false; }
accordion = element.closest(options.parent || accordionData);
// prevent adding event handlers twice
if (!element.Collapse) {
element.addEventListener('click', self.toggle, false);
}
// associate target to init object
element.Collapse = self;
}
function setFocus(element) {
element.focus();
}
/* Native JavaScript for Bootstrap 4 | Dropdown
----------------------------------------------- */
// DROPDOWN DEFINITION
// ===================
function Dropdown(elem, option) {
var element;
// bind
var self = this;
// custom events
var showCustomEvent;
var shownCustomEvent;
var hideCustomEvent;
var hiddenCustomEvent;
// targets
var relatedTarget = null;
var parent; var menu; var menuItems = [];
// option
var persist;
// preventDefault on empty anchor links
function preventEmptyAnchor(anchor) {
if ((anchor.href && anchor.href.slice(-1) === '#') || (anchor.parentNode && anchor.parentNode.href
&& anchor.parentNode.href.slice(-1) === '#')) { this.preventDefault(); }
}
// toggle dismissible events
function toggleDismiss() {
var action = element.open ? 'addEventListener' : 'removeEventListener';
document[action]('click', dismissHandler, false);
document[action]('keydown', preventScroll, false);
document[action]('keyup', keyHandler, false);
document[action]('focus', dismissHandler, false);
}
// handlers
function dismissHandler(e) {
var eventTarget = e.target;
if (!eventTarget.getAttribute) { return; } // some weird FF bug #409
var hasData = ((eventTarget && (eventTarget.getAttribute('data-toggle')))
|| (eventTarget.parentNode && eventTarget.parentNode.getAttribute
&& eventTarget.parentNode.getAttribute('data-toggle')));
if (e.type === 'focus' && (eventTarget === element || eventTarget === menu || menu.contains(eventTarget))) {
return;
}
if ((eventTarget === menu || menu.contains(eventTarget)) && (persist || hasData)) { return; }
relatedTarget = eventTarget === element || element.contains(eventTarget) ? element : null;
self.hide();
preventEmptyAnchor.call(e, eventTarget);
}
function clickHandler(e) {
relatedTarget = element;
self.show();
preventEmptyAnchor.call(e, e.target);
}
function preventScroll(e) {
var key = e.which || e.keyCode;
if (key === 38 || key === 40) { e.preventDefault(); }
}
function keyHandler(e) {
var key = e.which || e.keyCode;
var activeItem = document.activeElement;
var isSameElement = activeItem === element;
var isInsideMenu = menu.contains(activeItem);
var isMenuItem = activeItem.parentNode === menu || activeItem.parentNode.parentNode === menu;
var idx = menuItems.indexOf(activeItem);
if (isMenuItem) { // navigate up | down
if (isSameElement) {
idx = 0;
} else if (key === 38) {
idx = idx > 1 ? idx - 1 : 0;
} else if (key === 40) {
idx = idx < menuItems.length - 1 ? idx + 1 : idx;
}
if (menuItems[idx]) { setFocus(menuItems[idx]); }
}
if (((menuItems.length && isMenuItem) // menu has items
|| (!menuItems.length && (isInsideMenu || isSameElement)) // menu might be a form
|| !isInsideMenu) // or the focused element is not in the menu at all
&& element.open && key === 27 // menu must be open
) {
self.toggle();
relatedTarget = null;
}
}
// public methods
self.show = function () {
showCustomEvent = bootstrapCustomEvent('show', 'dropdown', { relatedTarget: relatedTarget });
dispatchCustomEvent.call(parent, showCustomEvent);
if (showCustomEvent.defaultPrevented) { return; }
menu.classList.add('show');
parent.classList.add('show');
element.setAttribute('aria-expanded', true);
element.open = true;
element.removeEventListener('click', clickHandler, false);
setTimeout(function () {
setFocus(menu.getElementsByTagName('INPUT')[0] || element); // focus the first input item | element
toggleDismiss();
shownCustomEvent = bootstrapCustomEvent('shown', 'dropdown', { relatedTarget: relatedTarget });
dispatchCustomEvent.call(parent, shownCustomEvent);
}, 1);
};
self.hide = function () {
hideCustomEvent = bootstrapCustomEvent('hide', 'dropdown', { relatedTarget: relatedTarget });
dispatchCustomEvent.call(parent, hideCustomEvent);
if (hideCustomEvent.defaultPrevented) { return; }
menu.classList.remove('show');
parent.classList.remove('show');
element.setAttribute('aria-expanded', false);
element.open = false;
toggleDismiss();
setFocus(element);
setTimeout(function () {
// only re-attach handler if the init is not disposed
if (element.Dropdown) { element.addEventListener('click', clickHandler, false); }
}, 1);
hiddenCustomEvent = bootstrapCustomEvent('hidden', 'dropdown', { relatedTarget: relatedTarget });
dispatchCustomEvent.call(parent, hiddenCustomEvent);
};
self.toggle = function () {
if (parent.classList.contains('show') && element.open) { self.hide(); } else { self.show(); }
};
self.dispose = function () {
if (parent.classList.contains('show') && element.open) { self.hide(); }
element.removeEventListener('click', clickHandler, false);
delete element.Dropdown;
};
// init
// initialization element
element = queryElement(elem);
// reset on re-init
if (element.Dropdown) { element.Dropdown.dispose(); }
// set targets
parent = element.parentNode;
menu = queryElement('.dropdown-menu', parent);
Array.from(menu.children).forEach(function (child) {
if (child.children.length && child.children[0].tagName === 'A') {
menuItems.push(child.children[0]);
}
if (child.tagName === 'A') { menuItems.push(child); }
});
// prevent adding event handlers twice
if (!element.Dropdown) {
if (!('tabindex' in menu)) { menu.setAttribute('tabindex', '0'); } // Fix onblur on Chrome | Safari
element.addEventListener('click', clickHandler, false);
}
// set option
persist = option === true || element.getAttribute('data-persist') === 'true' || false;
// set initial state to closed
element.open = false;
// associate element with init object
element.Dropdown = self;
}
/* Native JavaScript for Bootstrap 4 | Modal
-------------------------------------------- */
// MODAL DEFINITION
// ================
function Modal(elem, opsInput) { // element can be the modal/triggering button
var element;
// set options
var options = opsInput || {};
// bind, modal
var self = this;
var modal;
// custom events
var showCustomEvent;
var shownCustomEvent;
var hideCustomEvent;
var hiddenCustomEvent;
// event targets and other
var relatedTarget = null;
var scrollBarWidth;
var overlay;
var overlayDelay;
// also find fixed-top / fixed-bottom items
var fixedItems;
var ops = {};
// private methods
function setScrollbar() {
var bodyClassList = document.body.classList;
var openModal = bodyClassList.contains('modal-open');
var bodyPad = parseInt(getComputedStyle(document.body).paddingRight, 10);
var docClientHeight = document.documentElement.clientHeight;
var docScrollHeight = document.documentElement.scrollHeight;
var bodyClientHeight = document.body.clientHeight;
var bodyScrollHeight = document.body.scrollHeight;
var bodyOverflow = docClientHeight !== docScrollHeight
|| bodyClientHeight !== bodyScrollHeight;
var modalOverflow = modal.clientHeight !== modal.scrollHeight;
scrollBarWidth = measureScrollbar();
modal.style.paddingRight = !modalOverflow && scrollBarWidth ? (scrollBarWidth + "px") : '';
document.body.style.paddingRight = modalOverflow || bodyOverflow
? ((bodyPad + (openModal ? 0 : scrollBarWidth)) + "px") : '';
if (fixedItems.length) {
fixedItems.forEach(function (fixed) {
var itemPad = getComputedStyle(fixed).paddingRight;
fixed.style.paddingRight = modalOverflow || bodyOverflow
? ((parseInt(itemPad, 10) + (openModal ? 0 : scrollBarWidth)) + "px")
: ((parseInt(itemPad, 10)) + "px");
});
}
}
function resetScrollbar() {
document.body.style.paddingRight = '';
modal.style.paddingRight = '';
if (fixedItems.length) {
fixedItems.forEach(function (fixed) {
fixed.style.paddingRight = '';
});
}
}
function measureScrollbar() {
var scrollDiv = document.createElement('div');
scrollDiv.className = 'modal-scrollbar-measure'; // this is here to stay
document.body.appendChild(scrollDiv);
var widthValue = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return widthValue;
}
function createOverlay() {
var newOverlay = document.createElement('div');
overlay = queryElement('.modal-backdrop');
if (overlay === null) {
newOverlay.setAttribute('class', ("modal-backdrop" + (ops.animation ? ' fade' : '')));
overlay = newOverlay;
document.body.appendChild(overlay);
}
return overlay;
}
function removeOverlay() {
overlay = queryElement('.modal-backdrop');
if (overlay && !document.getElementsByClassName('modal show')[0]) {
document.body.removeChild(overlay); overlay = null;
}
if (overlay === null) {
document.body.classList.remove('modal-open');
resetScrollbar();
}
}
function toggleEvents(add) {
var action = add ? 'addEventListener' : 'removeEventListener';
window[action]('resize', self.update, passiveHandler);
modal[action]('click', dismissHandler, false);
document[action]('keydown', keyHandler, false);
}
// triggers
function beforeShow() {
modal.style.display = 'block';
setScrollbar();
if (!document.getElementsByClassName('modal show')[0]) { document.body.classList.add('modal-open'); }
modal.classList.add('show');
modal.setAttribute('aria-hidden', false);
if (modal.classList.contains('fade')) { emulateTransitionEnd(modal, triggerShow); }
else { triggerShow(); }
}
function triggerShow() {
setFocus(modal);
modal.isAnimating = false;
toggleEvents(1);
shownCustomEvent = bootstrapCustomEvent('shown', 'modal', { relatedTarget: relatedTarget });
dispatchCustomEvent.call(modal, shownCustomEvent);
}
function triggerHide(force) {
modal.style.display = '';
if (element) { setFocus(element); }
overlay = queryElement('.modal-backdrop');
// force can also be the transitionEvent object, we wanna make sure it's not
if (force !== 1 && overlay && overlay.classList.contains('show') && !document.getElementsByClassName('modal show')[0]) {
overlay.classList.remove('show');
emulateTransitionEnd(overlay, removeOverlay);
} else {
removeOverlay();
}
toggleEvents();
modal.isAnimating = false;
hiddenCustomEvent = bootstrapCustomEvent('hidden', 'modal');
dispatchCustomEvent.call(modal, hiddenCustomEvent);
}
// handlers
function clickHandler(e) {
if (modal.isAnimating) { return; }
var clickTarget = e.target;
var modalID = "#" + (modal.getAttribute('id'));
var targetAttrValue = clickTarget.getAttribute('data-target') || clickTarget.getAttribute('href');
var elemAttrValue = element.getAttribute('data-target') || element.getAttribute('href');
if (!modal.classList.contains('show')
&& ((clickTarget === element && targetAttrValue === modalID)
|| (element.contains(clickTarget) && elemAttrValue === modalID))) {
modal.modalTrigger = element;
relatedTarget = element;
self.show();
e.preventDefault();
}
}
function keyHandler(ref) {
var which = ref.which;
if (!modal.isAnimating && ops.keyboard && which === 27 && modal.classList.contains('show')) {
self.hide();
}
}
function dismissHandler(e) {
if (modal.isAnimating) { return; }
var clickTarget = e.target;
var hasData = clickTarget.getAttribute('data-dismiss') === 'modal';
var parentWithData = clickTarget.closest('[data-dismiss="modal"]');
if (modal.classList.contains('show') && (parentWithData || hasData
|| (clickTarget === modal && ops.backdrop !== 'static'))) {
self.hide(); relatedTarget = null;
e.preventDefault();
}
}
// public methods
self.toggle = function () {
if (modal.classList.contains('show')) { self.hide(); } else { self.show(); }
};
self.show = function () {
if (modal.classList.contains('show') && !!modal.isAnimating) { return; }
showCustomEvent = bootstrapCustomEvent('show', 'modal', { relatedTarget: relatedTarget });
dispatchCustomEvent.call(modal, showCustomEvent);
if (showCustomEvent.defaultPrevented) { return; }
modal.isAnimating = true;
// we elegantly hide any opened modal
var currentOpen = document.getElementsByClassName('modal show')[0];
if (currentOpen && currentOpen !== modal) {
if (currentOpen.modalTrigger) { currentOpen.modalTrigger.Modal.hide(); }
if (currentOpen.Modal) { currentOpen.Modal.hide(); }
}
if (ops.backdrop) { overlay = createOverlay(); }
if (overlay && !currentOpen && !overlay.classList.contains('show')) {
reflow(overlay);
overlayDelay = getElementTransitionDuration(overlay);
overlay.classList.add('show');
}
if (!currentOpen) { setTimeout(beforeShow, overlay && overlayDelay ? overlayDelay : 0); }
else { beforeShow(); }
};
self.hide = function (force) {
if (!modal.classList.contains('show')) { return; }
hideCustomEvent = bootstrapCustomEvent('hide', 'modal');
dispatchCustomEvent.call(modal, hideCustomEvent);
if (hideCustomEvent.defaultPrevented) { return; }
modal.isAnimating = true;
modal.classList.remove('show');
modal.setAttribute('aria-hidden', true);
if (modal.classList.contains('fade') && force !== 1) { emulateTransitionEnd(modal, triggerHide); }
else { triggerHide(); }
};
self.setContent = function (content) {
queryElement('.modal-content', modal).innerHTML = content;
};
self.update = function () {
if (modal.classList.contains('show')) {
setScrollbar();
}
};
self.dispose = function () {
self.hide(1);
if (element) { element.removeEventListener('click', clickHandler, false); delete element.Modal; } else { delete modal.Modal; }
};
// init
// the modal (both JavaScript / DATA API init) / triggering button element (DATA API)
element = queryElement(elem);
// determine modal, triggering element
var checkModal = queryElement(element.getAttribute('data-target') || element.getAttribute('href'));
modal = element.classList.contains('modal') ? element : checkModal;
// set fixed items
fixedItems = Array.from(document.getElementsByClassName('fixed-top'))
.concat(Array.from(document.getElementsByClassName('fixed-bottom')));
if (element.classList.contains('modal')) { element = null; } // modal is now independent of it's triggering element
// reset on re-init
if (element && element.Modal) { element.Modal.dispose(); }
if (modal && modal.Modal) { modal.Modal.dispose(); }
// set options
ops.keyboard = !(options.keyboard === false || modal.getAttribute('data-keyboard') === 'false');
ops.backdrop = options.backdrop === 'static' || modal.getAttribute('data-backdrop') === 'static' ? 'static' : true;
ops.backdrop = options.backdrop === false || modal.getAttribute('data-backdrop') === 'false' ? false : ops.backdrop;
ops.animation = !!modal.classList.contains('fade');
ops.content = options.content; // JavaScript only
// set an initial state of the modal
modal.isAnimating = false;
// prevent adding event handlers over and over
// modal is independent of a triggering element
if (element && !element.Modal) {
element.addEventListener('click', clickHandler, false);
}
if (ops.content) {
self.setContent(ops.content.trim());
}
// set associations
if (element) {
modal.modalTrigger = element;
element.Modal = self;
} else {
modal.Modal = self;
}
}
var mouseClickEvents = { down: 'mousedown', up: 'mouseup' };
// Popover, Tooltip & ScrollSpy
function getScroll() {
return {
y: window.pageYOffset || document.documentElement.scrollTop,
x: window.pageXOffset || document.documentElement.scrollLeft,
};
}
// both popovers and tooltips (target,tooltip,placement,elementToAppendTo)
function styleTip(link, element, originalPosition, parent) {
var tipPositions = /\b(top|bottom|left|right)+/;
var elementDimensions = { w: element.offsetWidth, h: element.offsetHeight };
var windowWidth = (document.documentElement.clientWidth || document.body.clientWidth);
var windowHeight = (document.documentElement.clientHeight || document.body.clientHeight);
var rect = link.getBoundingClientRect();
var scroll = parent === document.body
? getScroll()
: { x: parent.offsetLeft + parent.scrollLeft, y: parent.offsetTop + parent.scrollTop };
var linkDimensions = { w: rect.right - rect.left, h: rect.bottom - rect.top };
var isPopover = element.classList.contains('popover');
var arrow = element.getElementsByClassName('arrow')[0];
var halfTopExceed = rect.top + linkDimensions.h / 2 - elementDimensions.h / 2 < 0;
var halfLeftExceed = rect.left + linkDimensions.w / 2 - elementDimensions.w / 2 < 0;
var halfRightExceed = rect.left + elementDimensions.w / 2
+ linkDimensions.w / 2 >= windowWidth;
var halfBottomExceed = rect.top + elementDimensions.h / 2
+ linkDimensions.h / 2 >= windowHeight;
var topExceed = rect.top - elementDimensions.h < 0;
var leftExceed = rect.left - elementDimensions.w < 0;
var bottomExceed = rect.top + elementDimensions.h + linkDimensions.h >= windowHeight;
var rightExceed = rect.left + elementDimensions.w + linkDimensions.w >= windowWidth;
var position = originalPosition;
// recompute position
// first, when both left and right limits are exceeded, we fall back to top|bottom
position = (position === 'left' || position === 'right') && leftExceed && rightExceed ? 'top' : position;
position = position === 'top' && topExceed ? 'bottom' : position;
position = position === 'bottom' && bottomExceed ? 'top' : position;
position = position === 'left' && leftExceed ? 'right' : position;
position = position === 'right' && rightExceed ? 'left' : position;
var topPosition;
var leftPosition;
var arrowTop;
var arrowLeft;
// update tooltip/popover class
if (element.className.indexOf(position) === -1) {
element.className = element.className.replace(tipPositions, position);
}
// we check the computed width & height and update here
var arrowWidth = arrow.offsetWidth;
var arrowHeight = arrow.offsetHeight;
// apply styling to tooltip or popover
// secondary|side positions
if (position === 'left' || position === 'right') {
if (position === 'left') { // LEFT
leftPosition = rect.left + scroll.x - elementDimensions.w - (isPopover ? arrowWidth : 0);
} else { // RIGHT
leftPosition = rect.left + scroll.x + linkDimensions.w;
}
// adjust top and arrow
if (halfTopExceed) {
topPosition = rect.top + scroll.y;
arrowTop = linkDimensions.h / 2 - arrowWidth;
} else if (halfBottomExceed) {
topPosition = rect.top + scroll.y - elementDimensions.h + linkDimensions.h;
arrowTop = elementDimensions.h - linkDimensions.h / 2 - arrowWidth;
} else {
topPosition = rect.top + scroll.y - elementDimensions.h / 2 + linkDimensions.h / 2;
arrowTop = elementDimensions.h / 2 - (isPopover ? arrowHeight * 0.9 : arrowHeight / 2);
}
// primary|vertical positions
} else if (position === 'top' || position === 'bottom') {
if (position === 'top') { // TOP
topPosition = rect.top + scroll.y - elementDimensions.h - (isPopover ? arrowHeight : 0);
} else { // BOTTOM
topPosition = rect.top + scroll.y + linkDimensions.h;
}
// adjust left | right and also the arrow
if (halfLeftExceed) {
leftPosition = 0;
arrowLeft = rect.left + linkDimensions.w / 2 - arrowWidth;
} else if (halfRightExceed) {
leftPosition = windowWidth - elementDimensions.w * 1.01;
arrowLeft = elementDimensions.w - (windowWidth - rect.left)
+ linkDimensions.w / 2 - arrowWidth / 2;
} else {
leftPosition = rect.left + scroll.x - elementDimensions.w / 2 + linkDimensions.w / 2;
arrowLeft = elementDimensions.w / 2 - (isPopover ? arrowWidth : arrowWidth / 2);
}
}
// apply style to tooltip/popover and its arrow
element.style.top = topPosition + "px";
element.style.left = leftPosition + "px";
if (arrowTop) { arrow.style.top = arrowTop + "px"; }
if (arrowLeft) { arrow.style.left = arrowLeft + "px"; }
}
/* Native JavaScript for Bootstrap 4 | Popover
---------------------------------------------- */
// POPOVER DEFINITION
// ==================
function Popover(elem, opsInput) {
var assign;
var element;
// set instance options
var options = opsInput || {};
// bind
var self = this;
// popover and timer
var popover = null;
var timer = 0;
var isIphone = /(iPhone|iPod|iPad)/.test(navigator.userAgent);
// title and content
var titleString;
var contentString;
var placementClass;
// options
var ops = {};
// close btn for dissmissible popover
var closeBtn;
// custom events
var showCustomEvent;
var shownCustomEvent;
var hideCustomEvent;
var hiddenCustomEvent;
// handlers
function dismissibleHandler(e) {
if (popover !== null && e.target === queryElement('.close', popover)) {
self.hide();
}
}
// private methods
function getContents() {
return {
0: options.title || element.getAttribute('data-title') || null,
1: options.content || element.getAttribute('data-content') || null,
};
}
function removePopover() {
ops.container.removeChild(popover);
timer = null; popover = null;
}
function createPopover() {
var assign;
(assign = getContents(), titleString = assign[0], contentString = assign[1]);
// fixing https://github.com/thednp/bootstrap.native/issues/233
contentString = contentString ? contentString.trim() : null;
popover = document.createElement('div');
// popover arrow
var popoverArrow = document.createElement('div');
popoverArrow.classList.add('arrow');
popover.appendChild(popoverArrow);
// create the popover from data attributes
if (contentString !== null && ops.template === null) {
popover.setAttribute('role', 'tooltip');
if (titleString !== null) {
var popoverTitle = document.createElement('h3');
popoverTitle.classList.add('popover-header');
popoverTitle.innerHTML = ops.dismissible ? titleString + closeBtn : titleString;
popover.appendChild(popoverTitle);
}
// set popover content
var popoverBodyMarkup = document.createElement('div');
popoverBodyMarkup.classList.add('popover-body');
popoverBodyMarkup.innerHTML = ops.dismissible && titleString === null
? contentString + closeBtn
: contentString;
popover.appendChild(popoverBodyMarkup);
} else { // or create the popover from template
var popoverTemplate = document.createElement('div');
popoverTemplate.innerHTML = ops.template.trim();
popover.className = popoverTemplate.firstChild.className;
popover.innerHTML = popoverTemplate.firstChild.innerHTML;
var popoverHeader = queryElement('.popover-header', popover);
var popoverBody = queryElement('.popover-body', popover);
// fill the template with content from data attributes
if (titleString && popoverHeader) { popoverHeader.innerHTML = titleString.trim(); }
if (contentString && popoverBody) { popoverBody.innerHTML = contentString.trim(); }
}
// append to the container
ops.container.appendChild(popover);
popover.style.display = 'block';
if (!popover.classList.contains('popover')) { popover.classList.add('popover'); }
if (!popover.classList.contains(ops.animation)) { popover.classList.add(ops.animation); }
if (!popover.classList.contains(placementClass)) { popover.classList.add(placementClass); }
}
function showPopover() {
if (!popover.classList.contains('show')) { popover.classList.add('show'); }
}
function updatePopover() {
styleTip(element, popover, ops.placement, ops.container);
}
function forceFocus() {
if (popover === null) { element.focus(); }
}
function toggleEvents(add) {
var action = add ? 'addEventListener' : 'removeEventListener';
if (ops.trigger === 'hover') {
element[action](mouseClickEvents.down, self.show);
element[action](mouseHoverEvents[0], self.show);
// mouseHover = ('onmouseleave' in document)
// ? [ 'mouseenter', 'mouseleave']
// : [ 'mouseover', 'mouseout' ]
if (!ops.dismissible) { element[action](mouseHoverEvents[1], self.hide); }
} else if (ops.trigger === 'click') {
element[action](ops.trigger, self.toggle);
} else if (ops.trigger === 'focus') {
if (isIphone) { element[action]('click', forceFocus, false); }
element[action](ops.trigger, self.toggle);
}
}
function touchHandler(e) {
if ((popover && popover.contains(e.target))
|| e.target === element || element.contains(e.target)) ; else {
self.hide();
}
}
// event toggle
function dismissHandlerToggle(add) {
var action = add ? 'addEventListener' : 'removeEventListener';
if (ops.dismissible) {
document[action]('click', dismissibleHandler, false);
} else {
if (ops.trigger === 'focus') { element[action]('blur', self.hide); }
if (ops.trigger === 'hover') { document[action]('touchstart', touchHandler, passiveHandler); }
}
window[action]('resize', self.hide, passiveHandler);
}
// triggers
function showTrigger() {
dismissHandlerToggle(1);
dispatchCustomEvent.call(element, shownCustomEvent);
}
function hideTrigger() {
dismissHandlerToggle();
removePopover();
dispatchCustomEvent.call(element, hiddenCustomEvent);
}
// public methods / handlers
self.toggle = function () {
if (popover === null) { self.show(); }
else { self.hide(); }
};
self.show = function () {
clearTimeout(timer);
timer = setTimeout(function () {
if (popover === null) {
dispatchCustomEvent.call(element, showCustomEvent);
if (showCustomEvent.defaultPrevented) { return; }
createPopover();
updatePopover();
showPopover();
if (ops.animation) { emulateTransitionEnd(popover, showTrigger); }
else { showTrigger(); }
}
}, 20);
};
self.hide = function () {
clearTimeout(timer);
timer = setTimeout(function () {
if (popover && popover !== null && popover.classList.contains('show')) {
dispatchCustomEvent.call(element, hideCustomEvent);
if (hideCustomEvent.defaultPrevented) { return; }
popover.classList.remove('show');
if (ops.animation) { emulateTransitionEnd(popover, hideTrigger); }
else { hideTrigger(); }
}
}, ops.delay);
};
self.dispose = function () {
self.hide();
toggleEvents();
delete element.Popover;
};
// INIT
// initialization element
element = queryElement(elem);
// reset on re-init
if (element.Popover) { element.Popover.dispose(); }
// DATA API
var triggerData = element.getAttribute('data-trigger'); // click / hover / focus
var animationData = element.getAttribute('data-animation'); // true / false
var placementData = element.getAttribute('data-placement');
var dismissibleData = element.getAttribute('data-dismissible');
var delayData = element.getAttribute('data-delay');
var containerData = element.getAttribute('data-container');
// close btn for dissmissible popover
closeBtn = '<button type="button" class="close">×</button>';
// custom events
showCustomEvent = bootstrapCustomEvent('show', 'popover');
shownCustomEvent = bootstrapCustomEvent('shown', 'popover');
hideCustomEvent = bootstrapCustomEvent('hide', 'popover');
hiddenCustomEvent = bootstrapCustomEvent('hidden', 'popover');
// check container
var containerElement = queryElement(options.container);
var containerDataElement = queryElement(containerData);
// maybe the element is inside a modal
var modal = element.closest('.modal');
// maybe the element is inside a fixed navbar
var navbarFixedTop = element.closest('.fixed-top');
var navbarFixedBottom = element.closest('.fixed-bottom');
// set instance options
ops.template = options.template ? options.template : null; // JavaScript only
ops.trigger = options.trigger ? options.trigger : triggerData || 'hover';
ops.animation = options.animation && options.animation !== 'fade' ? options.animation : animationData || 'fade';
ops.placement = options.placement ? options.placement : placementData || 'top';
ops.delay = parseInt((options.delay || delayData), 10) || 200;
ops.dismissible = !!(options.dismissible || dismissibleData === 'true');
ops.container = containerElement
|| (containerDataElement
|| (navbarFixedTop || (navbarFixedBottom || (modal || document.body))));
placementClass = "bs-popover-" + (ops.placement);
// invalidate
(assign = getContents(), titleString = assign[0], contentString = assign[1]);
if (!contentString && !ops.template) { return; }
// init
if (!element.Popover) { // prevent adding event handlers twice
toggleEvents(1);
}
// associate target to init object
element.Popover = self;
}
/* Native JavaScript for Bootstrap 5 | ScrollSpy
------------------------------------------------ */
// SCROLLSPY DEFINITION
// ====================
function ScrollSpy(elem, opsInput) {
var element;
// set options
var options = opsInput || {};
// bind
var self = this;
// GC internals
var vars;
var links;
// targets
var spyTarget;
// determine which is the real scrollTarget
var scrollTarget;
// options
var ops = {};
// private methods
// populate items and targets
function updateTargets() {
links = spyTarget.getElementsByTagName('A');
vars.scrollTop = vars.isWindow ? getScroll().y : element.scrollTop;
// only update vars once or with each mutation
if (vars.length !== links.length || getScrollHeight() !== vars.scrollHeight) {
var href;
var targetItem;
var rect;
// reset arrays & update
vars.items = [];
vars.offsets = [];
vars.scrollHeight = getScrollHeight();
vars.maxScroll = vars.scrollHeight - getOffsetHeight();
Array.from(links).forEach(function (link) {
href = link.getAttribute('href');
targetItem = href && href.charAt(0) === '#' && href.slice(-1) !== '#' && queryElement(href);
if (targetItem) {
vars.items.push(link);
rect = targetItem.getBoundingClientRect();
vars.offsets.push((vars.isWindow
? rect.top + vars.scrollTop
: targetItem.offsetTop) - ops.offset);
}
});
vars.length = vars.items.length;
}
}
// item update
function toggleEvents(add) {
var action = add ? 'addEventListener' : 'removeEventListener';
scrollTarget[action]('scroll', self.refresh, passiveHandler);
window[action]('resize', self.refresh, passiveHandler);
}
function getScrollHeight() {
return scrollTarget.scrollHeight || Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight
);
}
function getOffsetHeight() {
return !vars.isWindow ? element.getBoundingClientRect().height : window.innerHeight;
}
function clear() {
Array.from(links).map(function (item) { return item.classList.contains('active') && item.classList.remove('active'); });
}
function activate(input) {
var item = input;
var itemClassList;
clear();
vars.activeItem = item;
item.classList.add('active');
// activate all parents
var parents = [];
while (item.parentNode !== document.body) {
item = item.parentNode;
itemClassList = item.classList;
if (itemClassList.contains('dropdown-menu') || itemClassList.contains('nav')) { parents.push(item); }
}
parents.forEach(function (menuItem) {
var parentLink = menuItem.previousElementSibling;
if (parentLink && !parentLink.classList.contains('active')) {
parentLink.classList.add('active');
}
});
dispatchCustomEvent.call(element, bootstrapCustomEvent('activate', 'scrollspy', { relatedTarget: vars.activeItem }));
}
// public method
self.refresh = function () {
updateTargets();
if (vars.scrollTop >= vars.maxScroll) {
var newActiveItem = vars.items[vars.length - 1];
if (vars.activeItem !== newActiveItem) {
activate(newActiveItem);
}
return;
}
if (vars.activeItem && vars.scrollTop < vars.offsets[0] && vars.offsets[0] > 0) {
vars.activeItem = null;
clear();
return;
}
var i = vars.length;
while (i > -1) {
if (vars.activeItem !== vars.items[i] && vars.scrollTop >= vars.offsets[i]
&& (typeof vars.offsets[i + 1] === 'undefined' || vars.scrollTop < vars.offsets[i + 1])) {
activate(vars.items[i]);
}
i -= 1;
}
};
self.dispose = function () {
toggleEvents();
delete element.ScrollSpy;
};
// init
// initialization element, the element we spy on
element = queryElement(elem);
// reset on re-init
if (element.ScrollSpy) { element.ScrollSpy.dispose(); }
// event targets, constants
// DATA API
var targetData = element.getAttribute('data-target');
var offsetData = element.getAttribute('data-offset');
// targets
spyTarget = queryElement(options.target || targetData);
// determine which is the real scrollTarget
scrollTarget = element.clientHeight < element.scrollHeight ? element : window;
if (!spyTarget) { return; }
// set instance option
ops.offset = +(options.offset || offsetData) || 10;
// set instance priority variables
vars = {};
vars.length = 0;
vars.items = [];
vars.offsets = [];
vars.isWindow = scrollTarget === window;
vars.activeItem = null;
vars.scrollHeight = 0;
vars.maxScroll = 0;
// prevent adding event handlers twice
if (!element.ScrollSpy) { toggleEvents(1); }
self.refresh();
// associate target with init object
element.ScrollSpy = self;
}
/* Native JavaScript for Bootstrap 4 | Tab
------------------------------------------ */
// TAB DEFINITION
// ==============
function Tab(elem, opsInput) {
var element;
// set options
var options = opsInput || {};
// bind
var self = this;
// event targets
var tabs;
var dropdown;
// custom events
var showCustomEvent;
var shownCustomEvent;
var hideCustomEvent;
var hiddenCustomEvent;
// more GC material
var next;
var tabsContentContainer = false;
var activeTab;
var activeContent;
var nextContent;
var containerHeight;
var equalContents;
var nextHeight;
// triggers
function triggerEnd() {
tabsContentContainer.style.height = '';
tabsContentContainer.classList.remove('collapsing');
tabs.isAnimating = false;
}
function triggerShow() {
if (tabsContentContainer) { // height animation
if (equalContents) {
triggerEnd();
} else {
setTimeout(function () { // enables height animation
tabsContentContainer.style.height = nextHeight + "px"; // height animation
reflow(tabsContentContainer);
emulateTransitionEnd(tabsContentContainer, triggerEnd);
}, 50);
}
} else {
tabs.isAnimating = false;
}
shownCustomEvent = bootstrapCustomEvent('shown', 'tab', { relatedTarget: activeTab });
dispatchCustomEvent.call(next, shownCustomEvent);
}
function triggerHide() {
if (tabsContentContainer) {
activeContent.style.float = 'left';
nextContent.style.float = 'left';
containerHeight = activeContent.scrollHeight;
}
showCustomEvent = bootstrapCustomEvent('show', 'tab', { relatedTarget: activeTab });
hiddenCustomEvent = bootstrapCustomEvent('hidden', 'tab', { relatedTarget: next });
dispatchCustomEvent.call(next, showCustomEvent);
if (showCustomEvent.defaultPrevented) { return; }
nextContent.classList.add('active');
activeContent.classList.remove('active');
if (tabsContentContainer) {
nextHeight = nextContent.scrollHeight;
equalContents = nextHeight === containerHeight;
tabsContentContainer.classList.add('collapsing');
tabsContentContainer.style.height = containerHeight + "px"; // height animation
reflow(tabsContentContainer);
activeContent.style.float = '';
nextContent.style.float = '';
}
if (nextContent.classList.contains('fade')) {
setTimeout(function () {
nextContent.classList.add('show');
emulateTransitionEnd(nextContent, triggerShow);
}, 20);
} else { triggerShow(); }
dispatchCustomEvent.call(activeTab, hiddenCustomEvent);
}
// private methods
function getActiveTab() {
var assign;
var activeTabs = tabs.getElementsByClassName('active');
if (activeTabs.length === 1 && !activeTabs[0].parentNode.classList.contains('dropdown')) {
(assign = activeTabs, activeTab = assign[0]);
} else if (activeTabs.length > 1) {
activeTab = activeTabs[activeTabs.length - 1];
}
return activeTab;
}
function getActiveContent() { return queryElement(getActiveTab().getAttribute('href')); }
// handler
function clickHandler(e) {
e.preventDefault();
next = e.currentTarget;
if (!tabs.isAnimating) { self.show(); }
}
// public method
self.show = function () { // the tab we clicked is now the next tab
next = next || element;
if (!next.classList.contains('active')) {
nextContent = queryElement(next.getAttribute('href')); // this is the actual object, the next tab content to activate
activeTab = getActiveTab();
activeContent = getActiveContent();
hideCustomEvent = bootstrapCustomEvent('hide', 'tab', { relatedTarget: next });
dispatchCustomEvent.call(activeTab, hideCustomEvent);
if (hideCustomEvent.defaultPrevented) { return; }
tabs.isAnimating = true;
activeTab.classList.remove('active');
activeTab.setAttribute('aria-selected', 'false');
next.classList.add('active');
next.setAttribute('aria-selected', 'true');
if (dropdown) {
if (!element.parentNode.classList.contains('dropdown-menu')) {
if (dropdown.classList.contains('active')) { dropdown.classList.remove('active'); }
} else if (!dropdown.classList.contains('active')) { dropdown.classList.add('active'); }
}
if (activeContent.classList.contains('fade')) {
activeContent.classList.remove('show');
emulateTransitionEnd(activeContent, triggerHide);
} else { triggerHide(); }
}
};
self.dispose = function () {
element.removeEventListener('click', clickHandler, false);
delete element.Tab;
};
// INIT
// initialization element
element = queryElement(elem);
// reset on re-init
if (element.Tab) { element.Tab.dispose(); }
// DATA API
var heightData = element.getAttribute('data-height');
// event targets
tabs = element.closest('.nav');
dropdown = tabs && queryElement('.dropdown-toggle', tabs);
// instance options
var animateHeight = !(!supportTransition || (options.height === false || heightData === 'false'));
// set default animation state
tabs.isAnimating = false;
// init
if (!element.Tab) { // prevent adding event handlers twice
element.addEventListener('click', clickHandler, false);
}
if (animateHeight) { tabsContentContainer = getActiveContent().parentNode; }
// associate target with init object
element.Tab = self;
}
/* Native JavaScript for Bootstrap 4 | Toast
-------------------------------------------- */
// TOAST DEFINITION
// ==================
function Toast(elem, opsInput) {
var element;
// set options
var options = opsInput || {};
// bind
var self = this;
// toast, timer
var toast;
var timer = 0;
// custom events
var showCustomEvent;
var hideCustomEvent;
var shownCustomEvent;
var hiddenCustomEvent;
var ops = {};
// private methods
function showComplete() {
toast.classList.remove('showing');
toast.classList.add('show');
dispatchCustomEvent.call(toast, shownCustomEvent);
if (ops.autohide) { self.hide(); }
}
function hideComplete() {
toast.classList.add('hide');
dispatchCustomEvent.call(toast, hiddenCustomEvent);
}
function close() {
toast.classList.remove('show');
if (ops.animation) { emulateTransitionEnd(toast, hideComplete); }
else { hideComplete(); }
}
function disposeComplete() {
clearTimeout(timer);
element.removeEventListener('click', self.hide, false);
delete element.Toast;
}
// public methods
self.show = function () {
if (toast && !toast.classList.contains('show')) {
dispatchCustomEvent.call(toast, showCustomEvent);
if (showCustomEvent.defaultPrevented) { return; }
if (ops.animation) { toast.classList.add('fade'); }
toast.classList.remove('hide');
reflow(toast); // force reflow
toast.classList.add('showing');
if (ops.animation) { emulateTransitionEnd(toast, showComplete); }
else { showComplete(); }
}
};
self.hide = function (noTimer) {
if (toast && toast.classList.contains('show')) {
dispatchCustomEvent.call(toast, hideCustomEvent);
if (hideCustomEvent.defaultPrevented) { return; }
if (noTimer) { close(); }
else { timer = setTimeout(close, ops.delay); }
}
};
self.dispose = function () {
if (ops.animation) { emulateTransitionEnd(toast, disposeComplete); }
else { disposeComplete(); }
};
// init
// initialization element
element = queryElement(elem);
// reset on re-init
if (element.Toast) { element.Toast.dispose(); }
// toast, timer
toast = element.closest('.toast');
// DATA API
var animationData = element.getAttribute('data-animation');
var autohideData = element.getAttribute('data-autohide');
var delayData = element.getAttribute('data-delay');
// custom events
showCustomEvent = bootstrapCustomEvent('show', 'toast');
hideCustomEvent = bootstrapCustomEvent('hide', 'toast');
shownCustomEvent = bootstrapCustomEvent('shown', 'toast');
hiddenCustomEvent = bootstrapCustomEvent('hidden', 'toast');
// set instance options
ops.animation = options.animation === false || animationData === 'false' ? 0 : 1; // true by default
ops.autohide = options.autohide === false || autohideData === 'false' ? 0 : 1; // true by default
ops.delay = parseInt((options.delay || delayData), 10) || 500; // 500ms default
if (!element.Toast) { // prevent adding event handlers twice
element.addEventListener('click', self.hide, false);
}
// associate targets to init object
element.Toast = self;
}
/* Native JavaScript for Bootstrap 4 | Tooltip
---------------------------------------------- */
// TOOLTIP DEFINITION
// ==================
function Tooltip(elem, opsInput) {
var element;
// set options
var options = opsInput || {};
// bind
var self = this;
// tooltip, timer, and title
var tooltip = null;
var timer = 0;
var titleString;
var placementClass;
// custom events
var showCustomEvent;
var shownCustomEvent;
var hideCustomEvent;
var hiddenCustomEvent;
var ops = {};
// private methods
function getTitle() {
return element.getAttribute('title')
|| element.getAttribute('data-title')
|| element.getAttribute('data-original-title');
}
function removeToolTip() {
ops.container.removeChild(tooltip);
tooltip = null; timer = null;
}
function createToolTip() {
titleString = getTitle(); // read the title again
if (titleString) { // invalidate, maybe markup changed
// create tooltip
tooltip = document.createElement('div');
// set markup
if (ops.template) {
var tooltipMarkup = document.createElement('div');
tooltipMarkup.innerHTML = ops.template.trim();
tooltip.className = tooltipMarkup.firstChild.className;
tooltip.innerHTML = tooltipMarkup.firstChild.innerHTML;
queryElement('.tooltip-inner', tooltip).innerHTML = titleString.trim();
} else {
// tooltip arrow
var tooltipArrow = document.createElement('div');
tooltipArrow.classList.add('arrow');
tooltip.appendChild(tooltipArrow);
// tooltip inner
var tooltipInner = document.createElement('div');
tooltipInner.classList.add('tooltip-inner');
tooltip.appendChild(tooltipInner);
tooltipInner.innerHTML = titleString;
}
// reset position
tooltip.style.left = '0';
tooltip.style.top = '0';
// set class and role attribute
tooltip.setAttribute('role', 'tooltip');
if (!tooltip.classList.contains('tooltip')) { tooltip.classList.add('tooltip'); }
if (!tooltip.classList.contains(ops.animation)) { tooltip.classList.add(ops.animation); }
if (!tooltip.classList.contains(placementClass)) { tooltip.classList.add(placementClass); }
// append to container
ops.container.appendChild(tooltip);
}
}
function updateTooltip() {
styleTip(element, tooltip, ops.placement, ops.container);
}
function showTooltip() {
if (!tooltip.classList.contains('show')) { tooltip.classList.add('show'); }
}
function touchHandler(e) {
if ((tooltip && tooltip.contains(e.target))
|| e.target === element || element.contains(e.target)) ; else {
self.hide();
}
}
// triggers
function toggleAction(add) {
var action = add ? 'addEventListener' : 'removeEventListener';
document[action]('touchstart', touchHandler, passiveHandler);
window[action]('resize', self.hide, passiveHandler);
}
function showAction() {
toggleAction(1);
dispatchCustomEvent.call(element, shownCustomEvent);
}
function hideAction() {
toggleAction();
removeToolTip();
dispatchCustomEvent.call(element, hiddenCustomEvent);
}
function toggleEvents(add) {
var action = add ? 'addEventListener' : 'removeEventListener';
element[action](mouseClickEvents.down, self.show, false);
element[action](mouseHoverEvents[0], self.show, false);
element[action](mouseHoverEvents[1], self.hide, false);
}
// public methods
self.show = function () {
clearTimeout(timer);
timer = setTimeout(function () {
if (tooltip === null) {
dispatchCustomEvent.call(element, showCustomEvent);
if (showCustomEvent.defaultPrevented) { return; }
// if(createToolTip() == false) return;
if (createToolTip() !== false) {
updateTooltip();
showTooltip();
if (ops.animation) { emulateTransitionEnd(tooltip, showAction); }
else { showAction(); }
}
}
}, 20);
};
self.hide = function () {
clearTimeout(timer);
timer = setTimeout(function () {
if (tooltip && tooltip.classList.contains('show')) {
dispatchCustomEvent.call(element, hideCustomEvent);
if (hideCustomEvent.defaultPrevented) { return; }
tooltip.classList.remove('show');
if (ops.animation) { emulateTransitionEnd(tooltip, hideAction); }
else { hideAction(); }
}
}, ops.delay);
};
self.toggle = function () {
if (!tooltip) { self.show(); }
else { self.hide(); }
};
self.dispose = function () {
toggleEvents();
self.hide();
element.setAttribute('title', element.getAttribute('data-original-title'));
element.removeAttribute('data-original-title');
delete element.Tooltip;
};
// init
// initialization element
element = queryElement(elem);
// reset on re-init
if (element.Tooltip) { element.Tooltip.dispose(); }
// DATA API
var animationData = element.getAttribute('data-animation');
var placementData = element.getAttribute('data-placement');
var delayData = element.getAttribute('data-delay');
var containerData = element.getAttribute('data-container');
// check container
var containerElement = queryElement(options.container);
var containerDataElement = queryElement(containerData);
// maybe the element is inside a modal
var modal = element.closest('.modal');
// custom events
showCustomEvent = bootstrapCustomEvent('show', 'tooltip');
shownCustomEvent = bootstrapCustomEvent('shown', 'tooltip');
hideCustomEvent = bootstrapCustomEvent('hide', 'tooltip');
hiddenCustomEvent = bootstrapCustomEvent('hidden', 'tooltip');
// maybe the element is inside a fixed navbar
var navbarFixedTop = element.closest('.fixed-top');
var navbarFixedBottom = element.closest('.fixed-bottom');
// set instance options
ops.animation = options.animation && options.animation !== 'fade' ? options.animation : animationData || 'fade';
ops.placement = options.placement ? options.placement : placementData || 'top';
ops.template = options.template ? options.template : null; // JavaScript only
ops.delay = parseInt((options.delay || delayData), 10) || 200;
ops.container = containerElement
|| (containerDataElement
|| (navbarFixedTop || (navbarFixedBottom || (modal || document.body))));
// set placement class
placementClass = "bs-tooltip-" + (ops.placement);
// set tooltip content
titleString = getTitle();
// invalidate
if (!titleString) { return; }
// prevent adding event handlers twice
if (!element.Tooltip) {
element.setAttribute('data-original-title', titleString);
element.removeAttribute('title');
toggleEvents(1);
}
// associate target to init object
element.Tooltip = self;
}
var componentsInit = {};
/* Native JavaScript for Bootstrap | Initialize Data API
-------------------------------------------------------- */
function initializeDataAPI(Constructor, collection) {
Array.from(collection).map(function (x) { return new Constructor(x); });
}
function initCallback(context) {
var lookUp = context instanceof Element ? context : document;
Object.keys(componentsInit).forEach(function (component) {
initializeDataAPI(componentsInit[component][0],
lookUp.querySelectorAll(componentsInit[component][1]));
});
}
componentsInit.Alert = [Alert, '[data-dismiss="alert"]'];
componentsInit.Button = [Button, '[data-toggle="buttons"]'];
componentsInit.Carousel = [Carousel, '[data-ride="carousel"]'];
componentsInit.Collapse = [Collapse, '[data-toggle="collapse"]'];
componentsInit.Dropdown = [Dropdown, '[data-toggle="dropdown"]'];
componentsInit.Modal = [Modal, '[data-toggle="modal"]'];
componentsInit.Popover = [Popover, '[data-toggle="popover"],[data-tip="popover"]'];
componentsInit.ScrollSpy = [ScrollSpy, '[data-spy="scroll"]'];
componentsInit.Tab = [Tab, '[data-toggle="tab"]'];
componentsInit.Toast = [Toast, '[data-dismiss="toast"]'];
componentsInit.Tooltip = [Tooltip, '[data-toggle="tooltip"],[data-tip="tooltip"]'];
// bulk initialize all components
if (document.body) { initCallback(); }
else {
document.addEventListener('DOMContentLoaded', function initWrapper() {
initCallback();
document.removeEventListener('DOMContentLoaded', initWrapper, false);
}, false);
}
/* Native JavaScript for Bootstrap | Remove Data API
---------------------------------------------------- */
function removeElementDataAPI(ConstructorName, collection) {
Array.from(collection).map(function (x) { return x[ConstructorName].dispose(); });
}
function removeDataAPI(context) {
var lookUp = context instanceof Element ? context : document;
Object.keys(componentsInit).forEach(function (component) {
removeElementDataAPI(component, lookUp.querySelectorAll(componentsInit[component][1]));
});
}
var version = "4.0.0";
var indexV4 = {
Alert: Alert,
Button: Button,
Carousel: Carousel,
Collapse: Collapse,
Dropdown: Dropdown,
Modal: Modal,
Popover: Popover,
ScrollSpy: ScrollSpy,
Tab: Tab,
Toast: Toast,
Tooltip: Tooltip,
initCallback: initCallback,
removeDataAPI: removeDataAPI,
componentsInit: componentsInit,
Version: version,
};
export default indexV4;
|
'use strict';
var sinon = require('sinon');
module.exports = function() {
var logger = {
debug: sinon.stub(),
verbose: sinon.stub(),
info: sinon.stub(),
warn: sinon.stub(),
error: sinon.stub()
};
return logger;
};
|
/**
* Open Payments Cloud Application API
* Open Payments Cloud API
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'));
} else {
// Browser globals (root is window)
if (!root.OpenPaymentsCloudApplicationApi) {
root.OpenPaymentsCloudApplicationApi = {};
}
root.OpenPaymentsCloudApplicationApi.LoginConflict = factory(root.OpenPaymentsCloudApplicationApi.ApiClient);
}
}(this, function(ApiClient) {
'use strict';
/**
* The LoginConflict model module.
* @module model/LoginConflict
* @version 1.1.0
*/
/**
* Constructs a new <code>LoginConflict</code>.
* A conflict error that can be returned when trying to login.
* @alias module:model/LoginConflict
* @class
*/
var exports = function() {
var _this = this;
};
/**
* Constructs a <code>LoginConflict</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/LoginConflict} obj Optional instance to populate.
* @return {module:model/LoginConflict} The populated <code>LoginConflict</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('code')) {
obj['code'] = ApiClient.convertToType(data['code'], 'String');
}
}
return obj;
}
/**
* @member {module:model/LoginConflict.CodeEnum} code
*/
exports.prototype['code'] = undefined;
/**
* Allowed values for the <code>code</code> property.
* @enum {String}
* @readonly
*/
exports.CodeEnum = {
/**
* value: "FAILED_LOGIN"
* @const
*/
"FAILED_LOGIN": "FAILED_LOGIN",
/**
* value: "INVALID_USERNAME_OR_PASSWORD"
* @const
*/
"INVALID_USERNAME_OR_PASSWORD": "INVALID_USERNAME_OR_PASSWORD",
/**
* value: "INACTIVE_IDENTITY"
* @const
*/
"INACTIVE_IDENTITY": "INACTIVE_IDENTITY",
/**
* value: "INACTIVE_CREDENTIAL"
* @const
*/
"INACTIVE_CREDENTIAL": "INACTIVE_CREDENTIAL" };
return exports;
}));
|
import isViablePhoneNumber from './helpers/isViablePhoneNumber'
import parseNumber from './parse_'
import _isValidNumberForRegion from './isValidNumberForRegion_'
export default function isValidNumberForRegion(number, country, metadata) {
if (typeof number !== 'string') {
throw new TypeError('number must be a string')
}
if (typeof country !== 'string') {
throw new TypeError('country must be a string')
}
// `parse` extracts phone numbers from raw text,
// therefore it will cut off all "garbage" characters,
// while this `validate` function needs to verify
// that the phone number contains no "garbage"
// therefore the explicit `isViablePhoneNumber` check.
let input
if (isViablePhoneNumber(number)) {
input = parseNumber(number, { defaultCountry: country }, metadata)
} else {
input = {}
}
return _isValidNumberForRegion(input, country, undefined, metadata)
}
|
import { FETCH_LOCATIONS, CATEGORY_CHANGE, MARKER_CLICK, MARKER_OVER, MARKER_OUT,ITEMS_FETCH_DATA_SUCCESS,ITEMS_IS_LOADING } from '../actions/types';
export function itemsIsLoading(state = false, action) {
switch (action.type) {
case ITEMS_IS_LOADING:
console.log('map is loading')
return action.isLoading;
default:
return state;
}
}
export function venues(state = [],action){
switch(action.type){
case ITEMS_FETCH_DATA_SUCCESS:
var markers = action.venues.data.response.groups[0].items;
return markers.map((marker,index)=>{
return{
...marker,
showInfo:false,
index:index,
isActive:false
}
});
case MARKER_CLICK:
return state.map(marker => {
if(marker.index == action.markerId){
return {
...marker,
showInfo: true,
isActive: true
}
}else if(marker.showInfo){
return {
...marker,
showInfo: false,
isActive: false
}
}else{
return marker;
}
});
case MARKER_OVER:
return state.map(marker => {
if(marker.index == action.markerId){
return {
...marker,
showInfo: true
}
}
else if(!marker.isActive){
return {
...marker,
showInfo: false
}
}
else{
return marker;
}
});
case MARKER_OUT:
return state.map(marker => {
if(marker.isActive){
return marker;
}
return {
...marker,
showInfo: false
}
});
default:
return state;
}
}
|
import React, { PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import { DragSource, DropTarget } from 'react-dnd';
import { Link } from 'react-router';
import handleUpdateTodo from '../helpers/handleUpdateTodo';
const todoSource = {
beginDrag(props) {
return { props };
}
};
const todoTarget = {
hover(props, monitor, component) {
const dragIndex = monitor.getItem().index;
const hoverIndex = props.index;
// Don't replace items with themselves
if (dragIndex === hoverIndex) {
return;
}
// Determine rectangle on screen
const hoverBoundingRect = findDOMNode(component).getBoundingClientRect();
// Get vertical middle
const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
// Determine mouse position
const clientOffset = monitor.getClientOffset();
// Get pixels to the top
const hoverClientY = clientOffset.y - hoverBoundingRect.top;
// Dragging downwards
if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
return;
}
// Dragging upwards
if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
return;
}
// Time to actually perform the action
if (dragIndex !== undefined && hoverIndex !== undefined) {
props.onMoveTodo({ dragIndex, hoverIndex });
}
monitor.getItem().index = hoverIndex;
}
};
const connectDrag = (connect, monitor) => {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
};
};
const connectDrop = (connect) => {
return { connectDropTarget: connect.dropTarget() };
};
const Todo = (props) => {
const {
_id,
index,
name,
note,
completed,
updatedAt,
onRemove,
updateTodo,
connectDragSource,
isDragging,
connectDropTarget
} = props;
const time = new Date(updatedAt);
return connectDragSource(connectDropTarget(
<div className={`todo ${ completed ? 'done' : ''} ${isDragging ? 'dragging' : ''}`}>
<Link to={`/${index}`}>
<h2> { name } </h2>
<p> { note} </p>
<div>
<button
className="btn-status"
onClick={(e) => handleUpdateTodo(e, updateTodo, _id, {
completed: !completed
})}>
Status: { completed ? 'Done' : 'Not Done'}
</button>
<span className="datetime">
Last Updated: { time.toLocaleString() }
</span>
</div>
<span
className="close-todo"
onClick={(e) => {
e.preventDefault();
onRemove(_id);
}}>
X
</span>
</Link>
</div>
));
};
Todo.propTypes = {
_id: PropTypes.string,
index: PropTypes.number,
name: PropTypes.string,
note: PropTypes.string,
completed: PropTypes.bool,
updatedAt: PropTypes.string,
onRemove: PropTypes.func,
updateTodo: PropTypes.func,
connectDragSource: PropTypes.func,
isDragging: PropTypes.bool,
connectDropTarget: PropTypes.func,
onMoveTodo: PropTypes.func
};
const decorateWithDrag = (component) => {
return DragSource('Todo', todoSource, connectDrag)(component);
};
const decorateWithDrop = (component) => {
return DropTarget('Todo', todoTarget, connectDrop)(component);
};
export default decorateWithDrop(decorateWithDrag(Todo));
|
/**
@module ember-time-tools
*/
import Component from '@ember/component';
import layout from '../templates/components/tt-input-time';
import format from 'ember-time-tools/utils/format';
import DestinationElementMixin from 'ember-ui-components/mixins/destination-element';
/**
This component is a container for a TimeFieldComponent and a TimePickerComponent.
@class InputTimeComponent
@namespace Time
*/
export default Component.extend(DestinationElementMixin, {
layout: layout,
/**
@property value
@type {Object} A javascript `Date()` object.
*/
/**
Format can be:
* date (the default)
* timestamp
* object
@property format
@type {String}
*/
/**
@property placeholder
@type {String}
*/
/**
@property to
@type {String}
*/
/**
@property destinationElementId
@type {String}
@private
*/
/**
@property displayFormat
@type {String}
@default `h:mm a`
*/
displayFormat: 'h:mm a',
/**
@property pickerDisplayFormat
@type {String}
@default `hh:mm a`
*/
pickerDisplayFormat: 'hh:mm a',
/**
@property timeInterval
@type {Number}
@default `30`
*/
timeInterval: 30,
/**
## Scroll to selected time
With this property set to `true` the time picker will scroll to display the
selected time. If that is not the desired behaviour then you can set
`scrollToSelectedTime` to `false`.
```
{{input-time scrollToSelectedTime=false}}
```
@property scrollToSelectedTime
@type {Boolean}
@default `true`
*/
scrollToSelectedTime: true,
/**
@property showTimePicker
@type {Boolean}
@private
@default false
*/
showTimePicker: false,
/**
@property classNames
@type {Array}
@private
@default `['input-time']`
*/
classNames: ['input-time'],
/**
@method _selectTime
@param {Object} date A javascript `Date` object
@private
*/
_selectTime(date) {
this.set('value', format(date, this.get('format')));
},
/**
@method _openTimePicker
@private
*/
_openTimePicker() {
this.set('showTimePicker', true);
},
/**
@method _closeTimePicker
@private
*/
_closeTimePicker() {
this.set('showTimePicker', false);
},
actions: {
/**
ACTION - Select time
@method selectTime
@param {Object} time A javascript `Date` object
*/
selectTime(time) {
this._selectTime(time);
this._closeTimePicker();
},
/**
ACTION - toggle the `showTimePicker` property
@method toggleTimePicker
*/
toggleTimePicker() {
this.toggleProperty('showTimePicker');
},
/**
ACTION - Open the time-picker. Set the `showTimePicker` property to true.
@method openTimePicker
*/
openTimePicker() {
this._openTimePicker();
},
/**
ACTION - Close the time-picker. Set the `showTimePicker` property to false.
@method closeTimePicker
*/
closeTimePicker() {
this._closeTimePicker();
}
}
});
|
App.LoadingRoute = Em.Route.extend({
templateName: 'loading_route',
renderTemplate: function() {
// have it always render into the application template
this.render('loading_route', {
outlet: 'main'
});
}
});
|
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var protocol = require('pomelo-protocol');
var logger = require('pomelo-logger').getLogger('pomelo', __filename);
var Package = protocol.Package;
var Message = protocol.Message;
var ST_INITED = 0;
var ST_WAIT_ACK = 1;
var ST_WORKING = 2;
var ST_CLOSED = 3;
/**
* Socket class that wraps socket and websocket to provide unified interface for up level.
*/
var Socket = function(id, socket) {
EventEmitter.call(this);
this.id = id;
this.socket = socket;
this.remoteAddress = {
ip: socket._socket.remoteAddress,
port: socket._socket.remotePort
};
var self = this;
socket.once('close', this.emit.bind(this, 'disconnect'));
socket.on('error', this.emit.bind(this, 'error'));
socket.on('message', function(msg) {
if(msg) {
msg = Package.decode(msg);
handle(self, msg);
}
});
this.state = ST_INITED;
// TODO: any other events?
};
util.inherits(Socket, EventEmitter);
module.exports = Socket;
/**
* Send raw byte data.
*
* @api private
*/
Socket.prototype.sendRaw = function(msg) {
if(this.state !== ST_WORKING) {
return;
}
var self = this;
this.socket.send(msg, {binary: true}, function(err) {
if(!!err) {
logger.error('websocket([%s]:[%s]) send binary data failed: %j', self.socket._socket.remoteAddress, self.socket._socket.remotePort, err);
return;
}
});
};
/**
* Send byte data package to client.
*
* @param {Buffer} msg byte data
*/
Socket.prototype.send = function(msg) {
if(msg instanceof String) {
msg = new Buffer(msg);
} else if(!(msg instanceof Buffer)) {
msg = new Buffer(JSON.stringify(msg));
}
this.sendRaw(Package.encode(Package.TYPE_DATA, msg));
};
/**
* Send byte data packages to client in batch.
*
* @param {Buffer} msgs byte data
*/
Socket.prototype.sendBatch = function(msgs) {
this.send(Buffer.concat(msgs));
};
/**
* Send message to client no matter whether handshake.
*
* @api private
*/
Socket.prototype.sendForce = function(msg) {
if(this.state === ST_CLOSED) {
return;
}
this.socket.send(msg, {binary: true});
};
/**
* Response handshake request
*
* @api private
*/
Socket.prototype.handshakeResponse = function(resp) {
if(this.state !== ST_INITED) {
return;
}
this.socket.send(resp, {binary: true});
this.state = ST_WAIT_ACK;
};
/**
* Close the connection.
*
* @api private
*/
Socket.prototype.disconnect = function() {
if(this.state === ST_CLOSED) {
return;
}
this.state = ST_CLOSED;
this.socket.emit('close');
this.socket.close();
};
var handle = function(socket, msg) {
var handler = handlers[msg.type];
if(handler) {
handler(socket, msg);
}
else {
logger.error('could not find handle invalid data package.');
socket.disconnect();
}
};
var handleHandshake = function(socket, msg) {
if(socket.state !== ST_INITED) {
return;
}
socket.emit('handshake', JSON.parse(protocol.strdecode(msg.body)));
};
var handleHandshakeAck = function(socket, msg) {
if(socket.state !== ST_WAIT_ACK) {
return;
}
socket.state = ST_WORKING;
socket.emit('heartbeat');
};
var handleHeartbeat = function(socket, msg) {
if(socket.state !== ST_WORKING) {
return;
}
socket.emit('heartbeat');
};
var handleData = function(socket, msg) {
if(socket.state !== ST_WORKING) {
return;
}
socket.emit('message', msg);
};
var handlers = {};
handlers[Package.TYPE_HANDSHAKE] = handleHandshake;
handlers[Package.TYPE_HANDSHAKE_ACK] = handleHandshakeAck;
handlers[Package.TYPE_HEARTBEAT] = handleHeartbeat;
handlers[Package.TYPE_DATA] = handleData;
|
(function() {
'use strict';
angular
.module('plagUiApp')
.config(compileServiceConfig);
compileServiceConfig.$inject = ['$compileProvider','DEBUG_INFO_ENABLED'];
function compileServiceConfig($compileProvider,DEBUG_INFO_ENABLED) {
// disable debug data on prod profile to improve performance
$compileProvider.debugInfoEnabled(DEBUG_INFO_ENABLED);
/*
If you wish to debug an application with this information
then you should open up a debug console in the browser
then call this method directly in this console:
angular.reloadWithDebugInfo();
*/
}
})();
|
/*!
* bootstrap-fileinput v5.1.2
* http://plugins.krajee.com/file-input
*
* Krajee Explorer Font Awesome theme configuration for bootstrap-fileinput.
* Load this theme file after loading `fileinput.js`. Ensure that
* font awesome assets and CSS are loaded on the page as well.
*
* Author: Kartik Visweswaran
* Copyright: 2014 - 2020, Kartik Visweswaran, Krajee.com
*
* Licensed under the BSD-3-Clause
* https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md
*/
(function ($) {
'use strict';
$.fn.fileinputThemes['explorer-fas'] = {
layoutTemplates: {
footer: '<div class="file-details-cell">' +
'<div class="explorer-caption" title="{caption}">{caption}</div> ' + '{size}{progress}' +
'</div>' +
'<div class="file-actions-cell">{indicator} {actions}</div>',
actions: '{drag}\n' +
'<div class="file-actions">\n' +
' <div class="file-footer-buttons">\n' +
' {upload} {download} {delete} {zoom} {other} ' +
' </div>\n' +
'</div>',
fileIcon: '<i class="fas fa-file kv-caption-icon"></i> '
},
previewSettings: {
html: {width: '100px', height: '60px'},
text: {width: '100px', height: '60px'},
video: {width: 'auto', height: '60px'},
audio: {width: 'auto', height: '60px'},
flash: {width: '100%', height: '60px'},
object: {width: '100%', height: '60px'},
pdf: {width: '100px', height: '60px'},
other: {width: '100%', height: '60px'}
},
frameClass: 'explorer-frame',
fileActionSettings: {
removeIcon: '<i class="fas fa-trash-alt"></i>',
uploadIcon: '<i class="fas fa-upload"></i>',
uploadRetryIcon: '<i class="fas fa-redo-alt"></i>',
downloadIcon: '<i class="fas fa-download"></i>',
zoomIcon: '<i class="fas fa-search-plus"></i>',
dragIcon: '<i class="fas fa-arrows-alt"></i>',
indicatorNew: '<i class="fas fa-plus-circle text-warning"></i>',
indicatorSuccess: '<i class="fas fa-check-circle text-success"></i>',
indicatorError: '<i class="fas fa-exclamation-circle text-danger"></i>',
indicatorLoading: '<i class="fas fa-hourglass text-muted"></i>',
indicatorPaused: '<i class="fa fa-pause text-info"></i>'
},
previewZoomButtonIcons: {
prev: '<i class="fas fa-caret-left fa-lg"></i>',
next: '<i class="fas fa-caret-right fa-lg"></i>',
toggleheader: '<i class="fas fa-fw fa-arrows-alt-v"></i>',
fullscreen: '<i class="fas fa-fw fa-arrows-alt"></i>',
borderless: '<i class="fas fa-fw fa-external-link-alt"></i>',
close: '<i class="fas fa-fw fa-times"></i>'
},
previewFileIcon: '<i class="fas fa-file"></i>',
browseIcon: '<i class="fas fa-folder-open"></i>',
removeIcon: '<i class="fas fa-trash-alt"></i>',
cancelIcon: '<i class="fas fa-ban"></i>',
pauseIcon: '<i class="fas fa-pause"></i>',
uploadIcon: '<i class="fas fa-upload"></i>',
msgValidationErrorIcon: '<i class="fas fa-exclamation-circle"></i> '
};
})(window.jQuery);
|
/**
* @license Highstock JS v9.1.2 (2021-06-16)
* @module highcharts/indicators/ao
* @requires highcharts
* @requires highcharts/modules/stock
*
* Indicator series type for Highcharts Stock
*
* (c) 2010-2021 Wojciech Chmiel
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../Stock/Indicators/AO/AOIndicator.js';
|
// Executable at least with NodeJS
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
rl.on('line', function(line){
var visited=[[0,0]]; // List of (x,y) coords
for (var i = 0; i < line.length; i++) {
var oldCoord = visited[i];
switch(line[i]){
case "^":
var newCoord = [oldCoord[0],oldCoord[1]+1];
visited.push(newCoord);
break;
case ">":
var newCoord = [oldCoord[0]+1,oldCoord[1]];
visited.push(newCoord);
break;
case "v":
var newCoord = [oldCoord[0],oldCoord[1]-1];
visited.push(newCoord);
break;
case "<":
var newCoord = [oldCoord[0]-1,oldCoord[1]];
visited.push(newCoord);
break;
}
};
// Ugly hack of the day: convert coords into strings
// Reason: Set uses strict equality.
// Strict equality on similar content but not same objects != fun
// Fun fact: even arrays are objects in js
var uniques = new Set();
uniques.add('0,0');
for (var i = 0; i < visited.length; i++) {
uniques.add(visited[i].toString());
}
console.log("Santa only: " +uniques.size);
});
|
/**
* @ Lamosty.com 2015
*/
(function ($) {
function swap_large_image(event) {
event.preventDefault();
var newLargePhotoSrc = $(this).data('photo-large');
$('#large-photo').attr('src', newLargePhotoSrc);
}
var RentiFlat = {
'common': {
init: function () {
$.material.init();
$('[data-toggle="tooltip"]').tooltip();
},
finalize: function () {
}
},
'single_rentiflat_flat': {
init: function () {
$('#flat-photos').find('[data-photo-large]').on('click', swap_large_image);
this.initBids();
this.initGMap();
},
initBids: function () {
React.render(
React.createElement(FlatPageBids, {
'data': RentiFlatTenantData,
'bids': RentiFlatBids
}),
document.getElementById('bids')
);
},
initGMap: function () {
var flatLatLng = new google.maps.LatLng(
parseFloat(RentiFlatGMapsData['flat_lat']),
parseFloat(RentiFlatGMapsData['flat_lng'])
);
var mapOptions = {
zoom: 15,
center: flatLatLng,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById('location-map'), mapOptions);
var flatMarker = new google.maps.Marker({
position: flatLatLng,
map: map,
title: 'Flat'
});
}
},
page_template_page_fb_register: {
init: function () {
var that = this;
$(document).on('rentiflat_fbInit', function () {
that.authBtnClick();
});
},
authBtnClick: function () {
var that = this;
$('#fb-login').on('click', function (e) {
e.preventDefault();
FB.getLoginStatus(function (response) {
// not logged in or authorized yet
if (response.status !== 'connected') {
that.doFBLogin();
} else {
that.handleFBLoggedIn(response.authResponse);
}
});
})
},
doFBLogin: function () {
var that = this;
FB.login(function (response) {
// authorized or logged in successfully
if (response.authResponse) {
that.handleFBLoggedIn(response.authResponse);
}
});
},
handleFBLoggedIn: function (authData) {
$('#fb-login').hide();
$('#rentiflat-register-form').show();
}
}
};
/*
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*/
var UTIL = {
fire: function (func, funcname, args) {
var fire;
var namespace = RentiFlat;
funcname = (funcname === undefined) ? 'init' : funcname;
fire = func !== '';
fire = fire && namespace[func];
fire = fire && typeof namespace[func][funcname] === 'function';
if (fire) {
namespace[func][funcname](args);
}
},
loadEvents: function () {
// Fire common init JS
UTIL.fire('common');
// Fire page-specific init JS, and then finalize JS
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function (i, classnm) {
UTIL.fire(classnm);
UTIL.fire(classnm, 'finalize');
});
// Fire common finalize JS
UTIL.fire('common', 'finalize');
}
};
// Load Events
$(document).ready(UTIL.loadEvents);
})(jQuery);
|
(function (window, document, Laya) {
var __un = Laya.un, __uns = Laya.uns, __static = Laya.static, __class = Laya.class, __getset = Laya.getset, __newvec = Laya.__newvec;
var Browser = laya.utils.Browser, CSSStyle = laya.display.css.CSSStyle, ClassUtils = laya.utils.ClassUtils;
var Event = laya.events.Event, HTMLChar = laya.utils.HTMLChar, Loader = laya.net.Loader, Node = laya.display.Node, Rectangle = laya.maths.Rectangle;
var Render = laya.renders.Render, RenderContext = laya.renders.RenderContext, RenderSprite = laya.renders.RenderSprite;
var Sprite = laya.display.Sprite, Stat = laya.utils.Stat, Text = laya.display.Text, Texture = laya.resource.Texture;
var URL = laya.net.URL, Utils = laya.utils.Utils;
/**
*@private
*/
//class laya.html.utils.HTMLParse
var HTMLParse = (function () {
function HTMLParse() { }
__class(HTMLParse, 'laya.html.utils.HTMLParse');
HTMLParse.parse = function (ower, xmlString, url) {
xmlString = xmlString.replace(/<br>/g, "<br/>");
xmlString = "<root>" + xmlString + "</root>";
xmlString = xmlString.replace(HTMLParse.spacePattern, HTMLParse.char255);
var xml = Utils.parseXMLFromString(xmlString);
HTMLParse._parseXML(ower, xml.childNodes[0].childNodes, url);
}
HTMLParse._parseXML = function (parent, xml, url, href) {
var i = 0, n = 0;
if (xml.join || xml.item) {
for (i = 0, n = xml.length; i < n; ++i) {
HTMLParse._parseXML(parent, xml[i], url, href);
}
} else {
var node;
var nodeName;
if (xml.nodeType == 3) {
var txt;
if ((parent instanceof laya.html.dom.HTMLDivElement)) {
if (xml.nodeName == null) {
xml.nodeName = "#text";
}
nodeName = xml.nodeName.toLowerCase();
txt = xml.textContent.replace(/^\s+|\s+$/g, '');
if (txt.length > 0) {
node = ClassUtils.getInstance(nodeName);
if (node) {
parent.addChild(node);
((node).innerTEXT = txt.replace(HTMLParse.char255AndOneSpacePattern, " "));
}
}
} else {
txt = xml.textContent.replace(/^\s+|\s+$/g, '');
if (txt.length > 0) {
((parent).innerTEXT = txt.replace(HTMLParse.char255AndOneSpacePattern, " "));
}
}
return;
} else {
nodeName = xml.nodeName.toLowerCase();
if (nodeName == "#comment") return;
node = ClassUtils.getInstance(nodeName);
if (node) {
node = parent.addChild(node);
(node).URI = url;
(node).href = href;
var attributes = xml.attributes;
if (attributes && attributes.length > 0) {
for (i = 0, n = attributes.length; i < n; ++i) {
var attribute = attributes[i];
var attrName = attribute.nodeName;
var value = attribute.value;
node._setAttributes(attrName, value);
}
}
HTMLParse._parseXML(node, xml.childNodes, url, (node).href);
} else {
HTMLParse._parseXML(parent, xml.childNodes, url, href);
}
}
}
}
HTMLParse.char255 = String.fromCharCode(255);
HTMLParse.spacePattern = / | /g;
HTMLParse.char255AndOneSpacePattern = new RegExp(String.fromCharCode(255) + "|(\\s+)", "g");
return HTMLParse;
})()
/**
*@private
*HTML的布局类
*对HTML的显示对象进行排版
*/
//class laya.html.utils.Layout
var Layout = (function () {
function Layout() { }
__class(Layout, 'laya.html.utils.Layout');
Layout.later = function (element) {
if (Layout._will == null) {
Layout._will = [];
Laya.stage.frameLoop(1, null, function () {
if (Layout._will.length < 1)
return;
for (var i = 0; i < Layout._will.length; i++) {
laya.html.utils.Layout.layout(Layout._will[i]);
}
Layout._will.length = 0;
});
}
Layout._will.push(element);
}
Layout.layout = function (element) {
if (!element || !element._style) return null;
if ((element._style._type & /*laya.display.css.CSSStyle.ADDLAYOUTED*/0x200) === 0)
return null;
element.getStyle()._type &= ~ /*laya.display.css.CSSStyle.ADDLAYOUTED*/0x200;
var arr = Layout._multiLineLayout(element);
if (Render.isConchApp && element["layaoutCallNative"]) {
(element).layaoutCallNative();
}
return arr;
}
Layout._multiLineLayout = function (element) {
if (Text.RightToLeft) return Layout._multiLineLayout2(element);
var elements = new Array;
element._addChildsToLayout(elements);
var i = 0, n = elements.length, j = 0;
var style = element._getCSSStyle();
var letterSpacing = style.letterSpacing;
var leading = style.leading;
var lineHeight = style.lineHeight;
var widthAuto = style._widthAuto() || !style.wordWrap;
var width = widthAuto ? 999999 : element.width;
var height = element.height;
var maxWidth = 0;
var exWidth = style.italic ? style.fontSize / 3 : 0;
var align = style._getAlign();
var valign = style._getValign();
var endAdjust = valign !== 0 || align !== 0 || lineHeight != 0;
var oneLayout;
var x = 0;
var y = 0;
var w = 0;
var h = 0;
var tBottom = 0;
var lines = new Array;
var curStyle;
var curPadding;
var curLine = lines[0] = new LayoutLine();
var newLine = false, nextNewline = false;
var htmlWord;
var sprite;
curLine.h = 0;
if (style.italic)
width -= style.fontSize / 3;
var tWordWidth = 0;
var tLineFirstKey = true;
function addLine() {
curLine.y = y;
y += curLine.h + leading;
if (curLine.h == 0) y += lineHeight;
curLine.mWidth = tWordWidth;
tWordWidth = 0;
curLine = new LayoutLine();
lines.push(curLine);
curLine.h = 0;
x = 0;
tLineFirstKey = true;
newLine = false;
}
for (i = 0; i < n; i++) {
oneLayout = elements[i];
if (oneLayout == null) {
if (!tLineFirstKey) {
x += Layout.DIV_ELEMENT_PADDING;
}
curLine.wordStartIndex = curLine.elements.length;
continue;
}
tLineFirstKey = false;
if ((oneLayout instanceof laya.html.dom.HTMLBrElement)) {
addLine();
curLine.y = y;
continue;
} else if (oneLayout._isChar()) {
htmlWord = oneLayout;
if (!htmlWord.isWord) {
if (lines.length > 0 && (x + w) > width && curLine.wordStartIndex > 0) {
var tLineWord = 0;
tLineWord = curLine.elements.length - curLine.wordStartIndex + 1;
curLine.elements.length = curLine.wordStartIndex;
i -= tLineWord;
addLine();
continue;
}
newLine = false;
tWordWidth += htmlWord.width;
} else {
newLine = nextNewline || (htmlWord.char === '\n');
curLine.wordStartIndex = curLine.elements.length;
}
w = htmlWord.width + letterSpacing;
h = htmlWord.height;
nextNewline = false;
newLine = newLine || ((x + w) > width);
newLine && addLine();
curLine.minTextHeight = Math.min(curLine.minTextHeight, oneLayout.height);
} else {
curStyle = oneLayout._getCSSStyle();
sprite = oneLayout;
curPadding = curStyle.padding;
curStyle._getCssFloat() === 0 || (endAdjust = true);
newLine = nextNewline || curStyle.lineElement;
w = sprite.width * sprite._style._tf.scaleX + curPadding[1] + curPadding[3] + letterSpacing;
h = sprite.height * sprite._style._tf.scaleY + curPadding[0] + curPadding[2];
nextNewline = curStyle.lineElement;
newLine = newLine || ((x + w) > width && curStyle.wordWrap);
newLine && addLine();
}
curLine.elements.push(oneLayout);
curLine.h = Math.max(curLine.h, h);
oneLayout.x = x;
oneLayout.y = y;
x += w;
curLine.w = x - letterSpacing;
curLine.y = y;
maxWidth = Math.max(x + exWidth, maxWidth);
}
y = curLine.y + curLine.h;
if (endAdjust) {
var tY = 0;
var tWidth = width;
if (widthAuto && element.width > 0) {
tWidth = element.width;
}
for (i = 0, n = lines.length; i < n; i++) {
lines[i].updatePos(0, tWidth, i, tY, align, valign, lineHeight);
tY += Math.max(lineHeight, lines[i].h + leading);
}
y = tY;
}
widthAuto && (element.width = maxWidth);
(y > element.height) && (element.height = y);
return [maxWidth, y];
}
Layout._multiLineLayout2 = function (element) {
var elements = new Array;
element._addChildsToLayout(elements);
var i = 0, n = elements.length, j = 0;
var style = element._getCSSStyle();
var letterSpacing = style.letterSpacing;
var leading = style.leading;
var lineHeight = style.lineHeight;
var widthAuto = style._widthAuto() || !style.wordWrap;
var width = widthAuto ? 999999 : element.width;
var height = element.height;
var maxWidth = 0;
var exWidth = style.italic ? style.fontSize / 3 : 0;
var align = 2 - style._getAlign();
var valign = style._getValign();
var endAdjust = valign !== 0 || align !== 0 || lineHeight != 0;
var oneLayout;
var x = 0;
var y = 0;
var w = 0;
var h = 0;
var tBottom = 0;
var lines = new Array;
var curStyle;
var curPadding;
var curLine = lines[0] = new LayoutLine();
var newLine = false, nextNewline = false;
var htmlWord;
var sprite;
curLine.h = 0;
if (style.italic)
width -= style.fontSize / 3;
var tWordWidth = 0;
var tLineFirstKey = true;
function addLine() {
curLine.y = y;
y += curLine.h + leading;
if (curLine.h == 0) y += lineHeight;
curLine.mWidth = tWordWidth;
tWordWidth = 0;
curLine = new LayoutLine();
lines.push(curLine);
curLine.h = 0;
x = 0;
tLineFirstKey = true;
newLine = false;
}
for (i = 0; i < n; i++) {
oneLayout = elements[i];
if (oneLayout == null) {
if (!tLineFirstKey) {
x += Layout.DIV_ELEMENT_PADDING;
}
curLine.wordStartIndex = curLine.elements.length;
continue;
}
tLineFirstKey = false;
if ((oneLayout instanceof laya.html.dom.HTMLBrElement)) {
addLine();
curLine.y = y;
continue;
} else if (oneLayout._isChar()) {
htmlWord = oneLayout;
if (!htmlWord.isWord) {
if (lines.length > 0 && (x + w) > width && curLine.wordStartIndex > 0) {
var tLineWord = 0;
tLineWord = curLine.elements.length - curLine.wordStartIndex + 1;
curLine.elements.length = curLine.wordStartIndex;
i -= tLineWord;
addLine();
continue;
}
newLine = false;
tWordWidth += htmlWord.width;
} else {
newLine = nextNewline || (htmlWord.char === '\n');
curLine.wordStartIndex = curLine.elements.length;
}
w = htmlWord.width + letterSpacing;
h = htmlWord.height;
nextNewline = false;
newLine = newLine || ((x + w) > width);
newLine && addLine();
curLine.minTextHeight = Math.min(curLine.minTextHeight, oneLayout.height);
} else {
curStyle = oneLayout._getCSSStyle();
sprite = oneLayout;
curPadding = curStyle.padding;
curStyle._getCssFloat() === 0 || (endAdjust = true);
newLine = nextNewline || curStyle.lineElement;
w = sprite.width * sprite._style._tf.scaleX + curPadding[1] + curPadding[3] + letterSpacing;
h = sprite.height * sprite._style._tf.scaleY + curPadding[0] + curPadding[2];
nextNewline = curStyle.lineElement;
newLine = newLine || ((x + w) > width && curStyle.wordWrap);
newLine && addLine();
}
curLine.elements.push(oneLayout);
curLine.h = Math.max(curLine.h, h);
oneLayout.x = x;
oneLayout.y = y;
x += w;
curLine.w = x - letterSpacing;
curLine.y = y;
maxWidth = Math.max(x + exWidth, maxWidth);
}
y = curLine.y + curLine.h;
if (endAdjust) {
var tY = 0;
var tWidth = width;
for (i = 0, n = lines.length; i < n; i++) {
lines[i].updatePos(0, tWidth, i, tY, align, valign, lineHeight);
tY += Math.max(lineHeight, lines[i].h + leading);
}
y = tY;
}
widthAuto && (element.width = maxWidth);
(y > element.height) && (element.height = y);
for (i = 0, n = lines.length; i < n; i++) {
lines[i].revertOrder(width);
}
return [maxWidth, y];
}
Layout._will = null;
Layout.DIV_ELEMENT_PADDING = 0;
return Layout;
})()
/**
*@private
*/
//class laya.html.utils.LayoutLine
var LayoutLine = (function () {
function LayoutLine() {
this.x = 0;
this.y = 0;
this.w = 0;
this.h = 0;
this.wordStartIndex = 0;
this.minTextHeight = 99999;
this.mWidth = 0;
this.elements = new Array;
}
__class(LayoutLine, 'laya.html.utils.LayoutLine');
var __proto = LayoutLine.prototype;
/**
*底对齐(默认)
*@param left
*@param width
*@param dy
*@param align 水平
*@param valign 垂直
*@param lineHeight 行高
*/
__proto.updatePos = function (left, width, lineNum, dy, align, valign, lineHeight) {
var w = 0;
var one
if (this.elements.length > 0) {
one = this.elements[this.elements.length - 1];
w = one.x + one.width - this.elements[0].x;
};
var dx = 0, ddy = NaN;
align ===/*laya.display.css.CSSStyle.ALIGN_CENTER*/1 && (dx = (width - w) / 2);
align ===/*laya.display.css.CSSStyle.ALIGN_RIGHT*/2 && (dx = (width - w));
lineHeight === 0 || valign != 0 || (valign = 1);
for (var i = 0, n = this.elements.length; i < n; i++) {
one = this.elements[i];
var tCSSStyle = one._getCSSStyle();
dx !== 0 && (one.x += dx);
switch (tCSSStyle._getValign()) {
case 0:
one.y = dy;
break;
case /*laya.display.css.CSSStyle.VALIGN_MIDDLE*/1: ;
var tMinTextHeight = 0;
if (this.minTextHeight != 99999) {
tMinTextHeight = this.minTextHeight;
};
var tBottomLineY = (tMinTextHeight + lineHeight) / 2;
tBottomLineY = Math.max(tBottomLineY, this.h);
if ((one instanceof laya.html.dom.HTMLImageElement)) {
ddy = dy + tBottomLineY - one.height;
} else {
ddy = dy + tBottomLineY - one.height;
}
one.y = ddy;
break;
case /*laya.display.css.CSSStyle.VALIGN_BOTTOM*/2:
one.y = dy + (lineHeight - one.height);
break;
}
}
}
/**
*布局反向,目前用于将ltr模式布局转为rtl模式布局
*/
__proto.revertOrder = function (width) {
var one
if (this.elements.length > 0) {
var i = 0, len = 0;
len = this.elements.length;
for (i = 0; i < len; i++) {
one = this.elements[i];
one.x = width - one.x - one.width;
}
}
}
return LayoutLine;
})()
/**
*@private
*/
//class laya.html.dom.HTMLElement extends laya.display.Sprite
var HTMLElement = (function (_super) {
function HTMLElement() {
this.URI = null;
this._href = null;
HTMLElement.__super.call(this);
this._text = HTMLElement._EMPTYTEXT;
this.setStyle(new CSSStyle(this));
this._getCSSStyle().valign = "middle";
this.mouseEnabled = true;
}
__class(HTMLElement, 'laya.html.dom.HTMLElement', _super);
var __proto = HTMLElement.prototype;
/**
*@private
*/
__proto.layaoutCallNative = function () {
var n = 0;
if (this._childs && (n = this._childs.length) > 0) {
for (var i = 0; i < n; i++) {
this._childs[i].layaoutCallNative && this._childs[i].layaoutCallNative();
}
};
var word = this._getWords();
word ? laya.html.dom.HTMLElement.fillWords(this, word, 0, 0, this.style.font, this.style.color, this.style.underLine) : this.graphics.clear();
}
__proto.appendChild = function (c) {
return this.addChild(c);
}
/**
*rtl模式的getWords函數
*/
__proto._getWords2 = function () {
var txt = this._text.text;
if (!txt || txt.length === 0)
return null;
var i = 0, n = 0;
var realWords;
var drawWords;
if (!this._text.drawWords) {
realWords = txt.split(" ");
n = realWords.length - 1;
drawWords = [];
for (i = 0; i < n; i++) {
drawWords.push(realWords[i], " ")
}
if (n >= 0)
drawWords.push(realWords[n]);
this._text.drawWords = drawWords;
} else {
drawWords = this._text.drawWords;
};
var words = this._text.words;
if (words && words.length === drawWords.length)
return words;
words === null && (this._text.words = words = []);
words.length = drawWords.length;
var size;
var style = this.style;
var fontStr = style.font;
for (i = 0, n = drawWords.length; i < n; i++) {
size = Utils.measureText(drawWords[i], fontStr);
var tHTMLChar = words[i] = new HTMLChar(drawWords[i], size.width, size.height || style.fontSize, style);
if (tHTMLChar.char.length > 1) {
tHTMLChar.charNum = tHTMLChar.char;
}
if (this.href) {
var tSprite = new Sprite();
this.addChild(tSprite);
tHTMLChar.setSprite(tSprite);
}
}
return words;
}
__proto._getWords = function () {
if (!Text.CharacterCache) return this._getWords2();
var txt = this._text.text;
if (!txt || txt.length === 0)
return null;
var words = this._text.words;
if (words && words.length === txt.length)
return words;
words === null && (this._text.words = words = []);
words.length = txt.length;
var size;
var style = this.style;
var fontStr = style.font;
var startX = 0;
for (var i = 0, n = txt.length; i < n; i++) {
size = Utils.measureText(txt.charAt(i), fontStr);
var tHTMLChar = words[i] = new HTMLChar(txt.charAt(i), size.width, size.height || style.fontSize, style);
if (this.href) {
var tSprite = new Sprite();
this.addChild(tSprite);
tHTMLChar.setSprite(tSprite);
}
}
return words;
}
__proto.showLinkSprite = function () {
var words = this._text.words;
if (words) {
var tLinkSpriteList = [];
var tSprite;
var tHtmlChar;
for (var i = 0; i < words.length; i++) {
tHtmlChar = words[i];
tSprite = new Sprite();
tSprite.graphics.drawRect(0, 0, tHtmlChar.width, tHtmlChar.height, "#ff0000");
tSprite.width = tHtmlChar.width;
tSprite.height = tHtmlChar.height;
this.addChild(tSprite);
tLinkSpriteList.push(tSprite);
}
}
}
__proto._layoutLater = function () {
var style = this.style;
if ((style._type & /*laya.display.css.CSSStyle.ADDLAYOUTED*/0x200)) return;
if (style.widthed(this) && (this._childs.length > 0 || this._getWords() != null) && style.block) {
Layout.later(this);
style._type |=/*laya.display.css.CSSStyle.ADDLAYOUTED*/0x200;
}
else {
this.parent && (this.parent)._layoutLater();
}
}
__proto._setAttributes = function (name, value) {
switch (name) {
case 'style':
this.style.cssText(value);
return;
case 'class':
this.className = value;
return;
}
_super.prototype._setAttributes.call(this, name, value);
}
__proto.updateHref = function () {
if (this._href != null) {
var words = this._getWords();
if (words) {
var tHTMLChar;
var tSprite;
for (var i = 0; i < words.length; i++) {
tHTMLChar = words[i];
tSprite = tHTMLChar.getSprite();
if (tSprite) {
tSprite.size(tHTMLChar.width, tHTMLChar.height);
tSprite.on(/*laya.events.Event.CLICK*/"click", this, this.onLinkHandler);
}
}
}
}
}
__proto.onLinkHandler = function (e) {
switch (e.type) {
case /*laya.events.Event.CLICK*/"click": ;
var target = this;
while (target) {
target.event(/*laya.events.Event.LINK*/"link", [this.href]);
target = target.parent;
}
break;
}
}
__proto.formatURL = function (url) {
if (!this.URI) return url;
return URL.formatURL(url, this.URI ? this.URI.path : null);
}
__getset(0, __proto, 'href', function () {
return this._href;
}, function (url) {
this._href = url;
if (url != null) {
this._getCSSStyle().underLine = 1;
this.updateHref();
}
});
__getset(0, __proto, 'color', null, function (value) {
this.style.color = value;
});
__getset(0, __proto, 'onClick', null, function (value) {
var fn;
/*__JS__ */eval("fn=function(event){" + value + ";}");
this.on(/*laya.events.Event.CLICK*/"click", this, fn);
});
__getset(0, __proto, 'id', null, function (value) {
HTMLDocument.document.setElementById(value, this);
});
__getset(0, __proto, 'innerTEXT', function () {
return this._text.text;
}, function (value) {
this.text = value;
});
__getset(0, __proto, 'style', function () {
return this._style;
});
__getset(0, __proto, 'text', function () {
return this._text.text;
}, function (value) {
if (this._text == HTMLElement._EMPTYTEXT) {
this._text = { text: value, words: null };
}
else {
this._text.text = value;
this._text.words && (this._text.words.length = 0);
}
Render.isConchApp && this.layaoutCallNative();
this._renderType |=/*laya.renders.RenderSprite.CHILDS*/0x800;
this.repaint();
this.updateHref();
});
__getset(0, __proto, 'parent', _super.prototype._$get_parent, function (value) {
if ((value instanceof laya.html.dom.HTMLElement)) {
var p = value;
this.URI || (this.URI = p.URI);
this.style.inherit(p.style);
}
Laya.superSet(Sprite, this, 'parent', value);
});
__getset(0, __proto, 'className', null, function (value) {
this.style.attrs(HTMLDocument.document.styleSheets['.' + value]);
});
HTMLElement.fillWords = function (ele, words, x, y, font, color, underLine) {
ele.graphics.clear();
for (var i = 0, n = words.length; i < n; i++) {
var a = words[i];
ele.graphics.fillText(a.char, a.x + x, a.y + y, font, color, 'left', underLine);
}
}
HTMLElement._EMPTYTEXT = { text: null, words: null };
return HTMLElement;
})(Sprite)
/**
*@private
*/
//class laya.html.dom.HTMLBrElement extends laya.html.dom.HTMLElement
var HTMLBrElement = (function (_super) {
function HTMLBrElement() {
HTMLBrElement.__super.call(this);
this.style.lineElement = true;
this.style.block = true;
}
__class(HTMLBrElement, 'laya.html.dom.HTMLBrElement', _super);
return HTMLBrElement;
})(HTMLElement)
/**
*DIV标签
*/
//class laya.html.dom.HTMLDivElement extends laya.html.dom.HTMLElement
var HTMLDivElement = (function (_super) {
function HTMLDivElement() {
/**实际内容的高 */
this.contextHeight = NaN;
/**实际内容的宽 */
this.contextWidth = NaN;
HTMLDivElement.__super.call(this);
this.style.block = true;
this.style.lineElement = true;
this.style.width = 200;
this.style.height = 200;
HTMLStyleElement;
}
__class(HTMLDivElement, 'laya.html.dom.HTMLDivElement', _super);
var __proto = HTMLDivElement.prototype;
/**
*追加内容,解析并对显示对象排版
*@param text
*/
__proto.appendHTML = function (text) {
HTMLParse.parse(this, text, this.URI);
this.layout();
}
/**
*@private
*@param out
*@return
*/
__proto._addChildsToLayout = function (out) {
var words = this._getWords();
if (words == null && this._childs.length == 0) return false;
words && words.forEach(function (o) {
out.push(o);
});
var tFirstKey = true;
for (var i = 0, len = this._childs.length; i < len; i++) {
var o = this._childs[i];
if (tFirstKey) {
tFirstKey = false;
} else {
out.push(null);
}
o._addToLayout(out)
}
return true;
}
/**
*@private
*@param out
*/
__proto._addToLayout = function (out) {
this.layout();
}
/**
*@private
*对显示内容进行排版
*/
__proto.layout = function () {
if (!this.style) return;
this.style._type |=/*laya.display.css.CSSStyle.ADDLAYOUTED*/0x200;
var tArray = Layout.layout(this);
if (tArray) {
if (!this._$P.mHtmlBounds) this._set$P("mHtmlBounds", new Rectangle());
var tRectangle = this._$P.mHtmlBounds;
tRectangle.x = tRectangle.y = 0;
tRectangle.width = this.contextWidth = tArray[0];
tRectangle.height = this.contextHeight = tArray[1];
this.setBounds(tRectangle);
}
}
/**
*获取对象的高
*/
__getset(0, __proto, 'height', function () {
if (this._height) return this._height;
return this.contextHeight;
}, _super.prototype._$set_height);
/**
*设置标签内容
*/
__getset(0, __proto, 'innerHTML', null, function (text) {
this.destroyChildren();
this.appendHTML(text);
});
/**
*获取对象的宽
*/
__getset(0, __proto, 'width', function () {
if (this._width) return this._width;
return this.contextWidth;
}, function (value) {
var changed = false;
if (value === 0) {
changed = value != this._width;
} else {
changed = value != this.width;
}
Laya.superSet(HTMLElement, this, 'width', value);
if (changed)
this.layout();
});
return HTMLDivElement;
})(HTMLElement)
/**
*@private
*/
//class laya.html.dom.HTMLDocument extends laya.html.dom.HTMLElement
var HTMLDocument = (function (_super) {
function HTMLDocument() {
this.all = new Array;
this.styleSheets = CSSStyle.styleSheets;
HTMLDocument.__super.call(this);
}
__class(HTMLDocument, 'laya.html.dom.HTMLDocument', _super);
var __proto = HTMLDocument.prototype;
__proto.getElementById = function (id) {
return this.all[id];
}
__proto.setElementById = function (id, e) {
this.all[id] = e;
}
__static(HTMLDocument,
['document', function () { return this.document = new HTMLDocument(); }
]);
return HTMLDocument;
})(HTMLElement)
/**
*@private
*/
//class laya.html.dom.HTMLImageElement extends laya.html.dom.HTMLElement
var HTMLImageElement = (function (_super) {
function HTMLImageElement() {
this._tex = null;
this._url = null;
this._renderArgs = [];
HTMLImageElement.__super.call(this);
this.style.block = true;
}
__class(HTMLImageElement, 'laya.html.dom.HTMLImageElement', _super);
var __proto = HTMLImageElement.prototype;
__proto._addToLayout = function (out) {
!this._style.absolute && out.push(this);
}
__proto.render = function (context, x, y) {
if (!this._tex || !this._tex.loaded || !this._tex.loaded || this._width < 1 || this._height < 1) return;
Stat.spriteCount++;
this._renderArgs[0] = this._tex;
this._renderArgs[1] = this.x;
this._renderArgs[2] = this.y;
this._renderArgs[3] = this.width || this._tex.width;
this._renderArgs[4] = this.height || this._tex.height;
context.ctx.drawTexture2(x, y, this.style.translateX, this.style.translateY, this.transform, this.style.alpha, this.style.blendMode, this._renderArgs);
}
/**
*@private
*/
__proto.layaoutCallNative = function () {
var n = 0;
if (this._childs && (n = this._childs.length) > 0) {
for (var i = 0; i < n; i++) {
this._childs[i].layaoutCallNative && this._childs[i].layaoutCallNative();
}
}
}
__getset(0, __proto, 'src', null, function (url) {
var _$this = this;
url = this.formatURL(url);
if (this._url == url) return;
this._url = url;
var tex = this._tex = Loader.getRes(url);
if (!tex) {
this._tex = tex = new Texture();
tex.load(url);
Loader.cacheRes(url, tex);
}
function onloaded() {
var style = _$this._style;
var w = style.widthed(_$this) ? -1 : _$this._tex.width;
var h = style.heighted(_$this) ? -1 : _$this._tex.height;
if (!style.widthed(_$this) && _$this._width != _$this._tex.width) {
_$this.width = _$this._tex.width;
_$this.parent && (_$this.parent)._layoutLater();
}
if (!style.heighted(_$this) && _$this._height != _$this._tex.height) {
_$this.height = _$this._tex.height;
_$this.parent && (_$this.parent)._layoutLater();
}
if (Render.isConchApp) {
_$this._renderArgs[0] = _$this._tex;
_$this._renderArgs[1] = _$this.x;
_$this._renderArgs[2] = _$this.y;
_$this._renderArgs[3] = _$this.width || _$this._tex.width;
_$this._renderArgs[4] = _$this.height || _$this._tex.height;
_$this.graphics.drawTexture(_$this._tex, 0, 0, _$this._renderArgs[3], _$this._renderArgs[4]);
}
_$this.repaint();
_$this.parentRepaint();
}
tex.loaded ? onloaded() : tex.on(/*laya.events.Event.LOADED*/"loaded", null, onloaded);
});
return HTMLImageElement;
})(HTMLElement)
/**
*@private
*/
//class laya.html.dom.HTMLLinkElement extends laya.html.dom.HTMLElement
var HTMLLinkElement = (function (_super) {
function HTMLLinkElement() {
this.type = null;
HTMLLinkElement.__super.call(this);
this.visible = false;
}
__class(HTMLLinkElement, 'laya.html.dom.HTMLLinkElement', _super);
var __proto = HTMLLinkElement.prototype;
__proto._onload = function (data) {
switch (this.type) {
case 'text/css':
CSSStyle.parseCSS(data, this.URI);
break;
}
}
__getset(0, __proto, 'href', _super.prototype._$get_href, function (url) {
var _$this = this;
url = this.formatURL(url);
this.URI = new URL(url);
var l = new Loader();
l.once(/*laya.events.Event.COMPLETE*/"complete", null, function (data) {
_$this._onload(data);
});
l.load(url,/*laya.net.Loader.TEXT*/"text");
});
HTMLLinkElement._cuttingStyle = new RegExp("((@keyframes[\\s\\t]+|)(.+))[\\t\\n\\r\\\s]*{", "g");
return HTMLLinkElement;
})(HTMLElement)
/**
*@private
*/
//class laya.html.dom.HTMLStyleElement extends laya.html.dom.HTMLElement
var HTMLStyleElement = (function (_super) {
function HTMLStyleElement() {
HTMLStyleElement.__super.call(this);
this.visible = false;
}
__class(HTMLStyleElement, 'laya.html.dom.HTMLStyleElement', _super);
var __proto = HTMLStyleElement.prototype;
/**
*解析样式
*/
__getset(0, __proto, 'text', _super.prototype._$get_text, function (value) {
CSSStyle.parseCSS(value, null);
});
return HTMLStyleElement;
})(HTMLElement)
/**
*iframe标签类,目前用于加载外并解析数据
*/
//class laya.html.dom.HTMLIframeElement extends laya.html.dom.HTMLDivElement
var HTMLIframeElement = (function (_super) {
function HTMLIframeElement() {
HTMLIframeElement.__super.call(this);
this._getCSSStyle().valign = "middle";
}
__class(HTMLIframeElement, 'laya.html.dom.HTMLIframeElement', _super);
var __proto = HTMLIframeElement.prototype;
/**
*加载html文件,并解析数据
*@param url
*/
__getset(0, __proto, 'href', _super.prototype._$get_href, function (url) {
var _$this = this;
url = this.formatURL(url);
var l = new Loader();
l.once(/*laya.events.Event.COMPLETE*/"complete", null, function (data) {
var pre = _$this.URI;
_$this.URI = new URL(url);
_$this.innerHTML = data;
!pre || (_$this.URI = pre);
});
l.load(url,/*laya.net.Loader.TEXT*/"text");
});
return HTMLIframeElement;
})(HTMLDivElement)
})(window, document, Laya);
if (typeof define === 'function' && define.amd) {
define('laya.core', ['require', "exports"], function (require, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
for (var i in Laya) {
var o = Laya[i];
o && o.__isclass && (exports[i] = o);
}
});
}
|
/**
* @ngdoc module
* @name ng-translation.files-loader
*
* @description
* handle load static files phase
*/
angular.module('ng-translation.files-loader', [])
.factory('staticFilesLoader', ['$http', '$q', staticFilesLoaderFactory]);
function staticFilesLoaderFactory($http, $q) {
/**
* @ngdoc method
* @param data
* @param key
* @returns object
* @private
*/
function $$extendRes(data, key) {
var object = {};
object[key] = data;
return object;
}
/**
* @ngdoc method
* @param options [baseUrl, key, value, suffix]
* @returns {Q.promise}
*/
function $$get(options) {
var deferred = $q.defer();
$http({
url: [
options.baseUrl,
options.value,
options.suffix
].join(''),
method: 'GET',
params: ''
}).success(function (data) {
//if everything work well return new object
//contains { name: staticResponse }
deferred.resolve($$extendRes(data, options.key));
}).error(function (data) {
//else return
deferred.reject(options.key);
});
return deferred.promise;
}
return {
get: $$get
}
}
|
// Copyright 2011 Mark Cavage <mcavageginomail> All rights reserved.
module.exports = {
EOC: 0,
Boolean: 1,
Integer: 2,
BitString: 3,
OctetString: 4,
Null: 5,
OID: 6,
ObjectDescriptor: 7,
External: 8,
Real: 9, // float
Enumeration: 10,
PDV: 11,
Utf8String: 12,
RelativeOID: 13,
Sequence: 16,
Set: 17,
NumericString: 18,
PrintableString: 19,
T61String: 20,
VideotexString: 21,
IA5String: 22,
UTCTime: 23,
GeneralizedTime: 24,
GraphicString: 25,
VisibleString: 26,
GeneralString: 28,
UniversalString: 29,
CharacterString: 30,
BMPString: 31,
Constructor: 32,
Context: 128
};
|
'use strict';
var db = require('mano').db;
exports.email = db.Email;
exports.password = db.Password;
|
/*
*
* WeeklyPriorities
*
*/
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import styled from 'styled-components';
import { makeSelectWeeklyPriorities } from 'containers/Priorities/selectors';
import {
addDaily,
editDaily,
deleteDaily
} from 'containers/Priorities/actions';
import Weekly from 'components/Priorities/Weekly';
export class WeeklyPriorities extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
renderDay(day, i) {
const { name, priorities } = day;
const { onAddDaily, onEditDaily, onDeleteDaily} = this.props;
return (
<Weekly
key={ i }
name={ name }
dayIndex={ i }
priorities={ priorities }
onAddDaily={ onAddDaily }
onEditDaily={ onEditDaily }
onDeleteDaily={ onDeleteDaily }
/>
);
}
render() {
const { weeklyPriorities } = this.props;
return (
<div>
{ weeklyPriorities.map((day, i) => this.renderDay(day, i)) }
</div>
);
}
}
WeeklyPriorities.propTypes = {
dispatch: PropTypes.func.isRequired,
};
const mapStateToProps = createStructuredSelector({
weeklyPriorities: makeSelectWeeklyPriorities(),
});
function mapDispatchToProps(dispatch) {
return {
onAddDaily: (date, content) => dispatch(addDaily(date, content)),
onEditDaily: (id, content) => dispatch(editDaily(id, content)),
onDeleteDaily: (id) => dispatch(deleteDaily(id)),
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(WeeklyPriorities);
|
var searchData=
[
['i2c_5fbus_5fref_5fct',['i2c_bus_ref_ct',['../a00843.html#gaa7deec7f5d89dfb4f9746d050b0926f9',1,'hal_linux_i2c_userspace.c']]],
['i2c_5fbuses_5fdefault',['i2c_buses_default',['../a00467.html#ad2e9f2387bb528f37bceb48cd88af3d0',1,'i2c_buses_default(): i2c_bitbang_samd21.c'],['../a00470.html#ad2e9f2387bb528f37bceb48cd88af3d0',1,'i2c_buses_default(): i2c_bitbang_samd21.c']]],
['i2c_5ffile',['i2c_file',['../a00957.html#a386ecc3f01d8b317bc512cab194d844f',1,'atcaI2Cmaster']]],
['i2c_5fhal_5fdata',['i2c_hal_data',['../a00843.html#ga95dac4460cd54b4b073285ebc79d215b',1,'hal_linux_i2c_userspace.c']]],
['i2c_5fmaster_5finstance',['i2c_master_instance',['../a00957.html#a6fa5d175fefe82a0c13cc0f7afbf5593',1,'atcaI2Cmaster::i2c_master_instance()'],['../a00957.html#a6fa5d175fefe82a0c13cc0f7afbf5593',1,'atcaI2Cmaster::i2c_master_instance()'],['../a00957.html#a335b4a621ab538c5a42160a5a14c161f',1,'atcaI2Cmaster::i2c_master_instance()'],['../a00957.html#ad60966bca127551f6271719dd9921045',1,'atcaI2Cmaster::i2c_master_instance()']]],
['i2c_5fsercom',['i2c_sercom',['../a00957.html#af47d648cf53d85c997e715a25fea0372',1,'atcaI2Cmaster::i2c_sercom()'],['../a00957.html#a0d97fa67bd4aa20fd2835fa5c8076061',1,'atcaI2Cmaster::i2c_sercom()']]],
['i2cdriverinit',['i2cDriverInit',['../a00973.html#ae40d3e07534bf6cb2e78c329983048c7',1,'DRV_I2C_Object']]],
['i2cdriverinstance',['i2cDriverInstance',['../a00973.html#af8b2d2e531312c0b6adda321a50fabc7',1,'DRV_I2C_Object']]],
['i2cdriverinstanceindex',['i2cDriverInstanceIndex',['../a00973.html#a61f012e6351d468a23da071e8ee588b6',1,'DRV_I2C_Object']]],
['id',['id',['../a00905.html#a0b1ca4dcd178907e4151c7132e3b55f5',1,'atcacert_cert_element_s::id()'],['../a00957.html#a10c34d148db33a5f64c3730a163fb7a7',1,'atcaI2Cmaster::id()'],['../a00957.html#a7441ef0865bcb3db9b8064dd7375c1ea',1,'atcaI2Cmaster::id()']]],
['idx',['idx',['../a00861.html#ae40354a1051342eb5a9db005715dcfa9',1,'ATCAIfaceCfg']]],
['iface_5ftype',['iface_type',['../a00861.html#a3d0753b214d2a12df80f22b56bfc6e71',1,'ATCAIfaceCfg']]],
['incidental',['INCIDENTAL',['../a00524.html#a672c9264e9de75bce6ab2cb4d5bde5c1',1,'license.txt']]],
['including',['INCLUDING',['../a00524.html#a3e9c2f2beba8585ea947b758fe1a127d',1,'license.txt']]],
['indirect',['INDIRECT',['../a00524.html#ad8724d922f0e30d3010a431017c0aaaa',1,'license.txt']]],
['infringement',['INFRINGEMENT',['../a00524.html#a7c4fbd85a126d156dfee161e8fd6681a',1,'license.txt']]],
['input_5fdata',['input_data',['../a01029.html#a699b6e4448b505a2664025ccca3522f5',1,'atca_write_mac_in_out']]],
['io_5fkey',['io_key',['../a01001.html#a130c5ab3a3f978b77641faa7813aa5d2',1,'atca_io_decrypt_in_out::io_key()'],['../a01005.html#a130c5ab3a3f978b77641faa7813aa5d2',1,'atca_verify_mac::io_key()'],['../a01009.html#a130c5ab3a3f978b77641faa7813aa5d2',1,'atca_secureboot_enc_in_out::io_key()']]],
['is_5f64',['is_64',['../a00989.html#a3f6d684924e3635e6e57441b66b98978',1,'atca_temp_key']]],
['is_5fdevice_5fsn',['is_device_sn',['../a00913.html#a3969ddf030fd0524b62c572070bb3edc',1,'atcacert_build_state_s']]],
['is_5fgenkey',['is_genkey',['../a00897.html#ab0cedc80cd8670d02eee4b6e31500f5f',1,'atcacert_device_loc_s']]],
['is_5fkey_5fnomac',['is_key_nomac',['../a01025.html#a6ab45b7847bf9d25cc2be99b11641e5f',1,'atca_gen_dig_in_out']]],
['is_5fslot_5flocked',['is_slot_locked',['../a01057.html#afaeb2ef8df7a105b7f93a9fdb82fd6e8',1,'atca_sign_internal_in_out']]],
['issue_5fdate_5fformat',['issue_date_format',['../a00909.html#a61f951f9c4366391012057d591888f32',1,'atcacert_def_s']]]
];
|
//set global options
//toastr options
/*global options for plugins and directives */
toastr.options = {
"closeButton": false,
"debug": false,
"newestOnTop": false,
"progressBar": false,
"positionClass": "toast-top-full-width",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
};
var tinymcePlugins = [
'advlist autolink lists link image charmap print preview anchor',
'searchreplace visualblocks code fullscreen',
'insertdatetime media table contextmenu paste code'
];
var tinymceToolbar = 'undo redo | insert | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image code';
var tinymceOptions =
{
height:500,
menubar: false,
plugins: tinymcePlugins,
toolbar: tinymceToolbar
};
//route, storage, and grid dependencies
var NullDelicious = angular.module("Nulldelicious", ["ngRoute", "ngStorage", "ngTouch", "ui.grid", "ui.grid.selection", "ui.tinymce"]);
var ndTextEditor = NullDelicious.directive('ndTextEditor', function() {
return {
//restricted to attributes only
restrict: 'A',
scope: {
/*text param are the list of directive parameters we pass for tinyMCE initialization */
textParam: "@selector"
},
link: function (scope, element, attributes) {
//get id
var id = attributes['id'];
//var id = element.attr('id');
var selectorName = "#{0}".replace("{0}", id);
//init tinymce on our dom element
tinymce.init({ selector : selectorName,
height:500,
menubar: false,
plugins: tinymcePlugins,
toolbar: tinymceToolbar
});
//tinymce settings
}
};
});
var ndCodeEditor = NullDelicious.directive('ndCodeEditor', function() {
return {
restrict: 'A',
require: ['ngModel'],
scope: {
/*code editor mode is the codemirror mode that we wish to use to edit this element*/
mode: "@ndCodeEditor",
/* make ng model available for use*/
ngModel: '='
},
link: function (scope, element, attributes, ctrls) {
//get id
var id = attributes['id'];
var domElement = document.getElementById(id);
var cm = CodeMirror.fromTextArea(domElement, {
value: "",
mode: scope.mode,
theme: "base16-dark"
//htmlMode: true
});
var ngModelCtrl = ctrls[0];
//register control change
cm.on('change', function(obj)
{
var newValue = cm.getValue();
ngModelCtrl.$setViewValue(newValue);
//register value as scope
scope.ngModel = newValue;
});
//watch broadcast event for code changed in the control (outside to inside data binding)
scope.$on('codeChanged', function(event, value)
{
var oldValue = cm.getValue();
//now set our value if this is an external grid update (which means the values won't be the same)
if(oldValue !== value) {
cm.getDoc().setValue(value);
}
})
}
};
});
var Main = NullDelicious.controller("Main", function ($scope, $http, $localStorage, $sessionStorage, $route, $routeParams, $location, DataManager) {
//tinymce editor options for our sub controllers
$scope.tinymceOptions = tinymceOptions;
//scope nui client scope through controller scope
$scope.nui = nui;
//define location in scope
$scope.$location = $location;
$scope.$storage = $localStorage;
$scope.FooterMessage = function () {
return $scope.$location.path() == '' ? ['Welcome to a deliciously simple CMS',
'with a tiny footprint, fantastic performance',
'and all the features you expect',
'running on node. Nulldelicious!'] : [];
};
$scope.Identity = '';
$scope.Login = (function (username, password) {
//get encoded
var encoded = nui.EncodeLogin(username, password);
//clear username and password
$scope.Username = '';
$scope.Password = '';
//now make login request.
var login = nui.Login(encoded).then(function (result) {
//keep track of current identity
$scope.Identity = result[1];
//create data context after login
$scope.DataManager = new DataManager.DataManager($scope.$storage, result[0]);
$scope.$apply();
})
.fail(function (error) {
//display auth error to user.
toastr["error"](error);
$scope.AuthError = true;
$scope.$apply();
});
});
//handle selection change
$scope.$on('changeSiteSelection', function (event, args) {
//get the title for display, and the id for foreign key filtering
$scope.SelectedSite = args.title;
$scope.SelectedSiteId = args.id;
});
});
var Site = NullDelicious.controller("Site", function ($scope, $http, $localStorage, $sessionStorage, $route, $routeParams, $location)
{
//scope nui client scope through controller scope
$scope.nui = nui;
$scope.GetSites = (function()
{
if($scope.DataManager) {
$scope.DataManager.Get('Site').then(function (data) {
$scope.GlobalSites = data;
$scope.GlobalSitesData.data = $scope.GlobalSites;
//select an initial row if $scope.SelectedSiteId is set
//modify rows so that we can make a row selection
$scope.gridApi.grid.modifyRows($scope.GlobalSitesData.data);
var selectedSite = hx$.single($scope.GlobalSitesData.data, function(dt)
{
return dt.id === $scope.SelectedSiteId;
});
if(selectedSite) {
$scope.gridApi.selection.selectRow(selectedSite);
}
$scope.$apply();
});
}
});
//Ng grid templates...
var deleteTemplate = nui.ui.deleteTemplate;
$scope.GlobalSitesColumns = [{field : 'title', displayName : 'Title'},
{field : 'description', displayName: 'Description'},
{field : 'Delete', cellTemplate: deleteTemplate}
];
$scope.GlobalSitesData = {
data : $scope.GlobalSites,
columnDefs : $scope.GlobalSitesColumns,
enableRowSelection: true,
enableSelectAll: false,
selectionRowHeaderWidth: 35,
multiSelect: false
};
$scope.RemoveRow = function(element) {
var self = this;
var targetRow = element.$parent.$parent.row;
var targetId = targetRow.entity.id;
//now get the index of the element that we wish to remove in our collection, and
//delete it on the server
var siteToDelete = hx$.single($scope.GlobalSitesData.data, function(site)
{
return site.id === targetId;
});
$scope.DataManager.Delete('Site', siteToDelete).then(function(result)
{
//now, remove the element from our grid
var index = $scope.GlobalSitesData.data.indexOf(siteToDelete);
$scope.GlobalSitesData.data.splice(index, 1);
$scope.$apply();
}).fail(function(error)
{
$scope.DeleteError = true;
toastr["error"](error);
$scope.$apply();
});
};
$scope.AddSite = (function(title, description)
{
//construct new site
var newSite = new $scope.nui.Site(title, description);
//attempt write to server
$scope.DataManager.Set('Site', newSite).then(function(data)
{
//if successful, add to our global site data collection
$scope.GlobalSitesData.data.push(newSite);
$scope.$apply();
}).fail(function(error)
{
//if write fails, set our error and show an error modal
$scope.ApiError = error;
toastr["error"](error);
$scope.$apply();
});
});
/*start by getting sites*/
$scope.GetSites();
//now register grid API's, specifically, our onchange function when we change the site selection
$scope.GlobalSitesData.onRegisterApi = function(gridApi){
//set gridApi on scope
$scope.gridApi = gridApi;
gridApi.selection.on.rowSelectionChanged($scope,function(row){
//emit a selected site change event so that we can
var selectedSite = row.entity;
$scope.$emit('changeSiteSelection', selectedSite);
});
};
});
var Editor = NullDelicious.controller("Editor", function ($scope, $http, $localStorage, $sessionStorage, $route, $routeParams, $location)
{
//scope nui client scope through controller scope
$scope.nui = nui;
//set editor columns and data
var deleteTemplate = nui.ui.deleteTemplate;
$scope.EditorColumns = [{field : 'title', displayName : 'Title'},
{field : 'body', displayName: 'Body'},
{field : 'Delete', cellTemplate: deleteTemplate},
{field : 'tags', displayName: 'Tags'},
{field : 'siteId', displayName: 'SiteId'},
{field : 'published', displayName: 'Published'}
];
$scope.EditorData = {
data : $scope.Posts,
columnDefs : $scope.EditorColumns,
enableRowSelection: true,
enableSelectAll: false,
selectionRowHeaderWidth: 35,
multiSelect: false
};
/*remove row functionality */
$scope.RemoveRow = function(element) {
var self = this;
var targetRow = element.$parent.$parent.row;
var targetId = targetRow.entity.id;
//now get the index of the element that we wish to remove in our collection, and
//delete it on the server
var postToDelete = hx$.single($scope.EditorData.data, function(post)
{
return post.id === targetId;
});
$scope.DataManager.Delete('Post', postToDelete).then(function(result)
{
//now, remove the element from our grid
var index = $scope.EditorData.data.indexOf(postToDelete);
$scope.EditorData.data.splice(index, 1);
$scope.$apply();
}).fail(function(error)
{
$scope.DeleteError = true;
toastr["error"](error);
$scope.$apply();
});
};
//post states >> either adding posts or editing them
var postStates =
{
Add: 0,
Save: 1
};
//tag constructor
var tag = nui.tag;
var defaultTags = [new tag('')];
$scope.Tags = defaultTags;
$scope.GetPosts = (function()
{
if($scope.DataManager)
{
$scope.DataManager.Get('Post', {
query: {key: 'siteId', value : $scope.SelectedSiteId}
}).then(function (data) {
$scope.Posts = data;
$scope.EditorData.data = $scope.Posts;
$scope.$apply();
});
}
});
//add tags
$scope.AddTag = (function()
{
$scope.Tags.push(new tag(''));
});
//default state is add
$scope.PostActionState = postStates.Add;
$scope.PostActionDescriptor = (function()
{
return hx$.GetKeyByValue(postStates, $scope.PostActionState) + ' Post';
});
$scope.PostAction = (function()
{
if($scope.PostActionState == postStates.Add)
{
//transform tags
var tags = _.map($scope.Tags, function(key)
{
return {name : key.text};
});
var post = new nui.Post($scope.PostTitle, $scope.PostBody, tags, $scope.SelectedSiteId);
//if we are in add state, grab our model data, new up a post, update the server
//and update our grid model
$scope.DataManager.Set('Post', post).then(function(data)
{
$scope.EditorData.data.push(data);
$scope.$apply();
});
}
else if($scope.PostActionState == postStates.Save)
{
//modify selected post with edited body, title, tags
$scope.SelectedPost.body = $scope.PostBody;
$scope.SelectedPost.title = $scope.PostTitle;
$scope.SelectedPost.tags = _.map($scope.Tags, function(key)
{
return {name : key.text};
});
//now write back to the server, update the grid collection in the UI
$scope.DataManager.Set('Post', $scope.SelectedPost).then(function(data)
{
var gridPost = hx$.single($scope.EditorData.data, function(entry)
{
return entry.id === $scope.SelectedPost.id;
});
gridPost = data;
$scope.$apply();
})
}
});
$scope.GetPosts();
$scope.EditorData.onRegisterApi = function(gridApi) {
//set gridApi on scope
$scope.gridApi = gridApi;
//post selection in grid
gridApi.selection.on.rowSelectionChanged($scope, function (row) {
//emit a selected site change event so that we can
var selectedPost = row.entity;
$scope.SelectedPost = selectedPost;
$scope.PostBody = selectedPost.body;
$scope.PostTitle = selectedPost.title;
$scope.Tags = _.map(selectedPost.tags, function (t) {
return new tag(t.name);
});
//switch to save state
$scope.PostActionState = postStates.Save;
});
};
//enable TINY MCE on editor area.
//tinymce.init({ selector : '#PostBody' });
//TODO. refactor this as a directive instead
});
var Images = NullDelicious.controller("Images", function ($scope, $http, $localStorage, $sessionStorage, $route, $routeParams, $location)
{
var imageStates =
{
Add: 0,
Save: 1
};
$scope.ImageActionState = imageStates.Add;
$scope.nui = nui;
var deleteTemplate = nui.ui.deleteTemplate;
$scope.ImagesColumns = [{field : 'title', displayName : 'Title'},
{field : 'Delete', cellTemplate: deleteTemplate},
{field : 'tags', displayName: 'Tags'}];
$scope.ImagesData = {
data : $scope.Images,
columnDefs : $scope.ImagesColumns,
enableRowSelection: true,
enableSelectAll: false,
selectionRowHeaderWidth: 35,
multiSelect: false
};
$scope.GetImages = (function()
{
if($scope.DataManager)
{
$scope.DataManager.Get('Image', {
query: {key: 'siteId', value : $scope.SelectedSiteId}
}).then(function(data){
$scope.Images = data;
$scope.ImagesData.data = $scope.Images;
$scope.$apply();
});
}
});
//tag constructor
var tag = nui.tag;
var defaultTags = [new tag('')];
$scope.Tags = defaultTags;
$scope.AddTag = (function()
{
$scope.Tags.push(new tag(''));
});
$scope.RemoveRow = function(element) {
var self = this;
var targetRow = element.$parent.$parent.row;
var targetId = targetRow.entity.id;
//now get the index of the element that we wish to remove in our collection, and
//delete it on the server
var imageToDelete = hx$.single($scope.ImagesData.data, function(image)
{
return image.id === targetId;
});
$scope.DataManager.Delete('Image', imageToDelete).then(function(result)
{
//now, remove the element from our grid
var index = $scope.ImagesData.data.indexOf(imageToDelete);
$scope.ImagesData.data.splice(index, 1);
$scope.$apply();
}).fail(function(error)
{
$scope.DeleteError = true;
toastr["error"](error);
$scope.$apply();
});
};
$scope.UploadFiles = (function(rawData)
{
var uploadFile = rawData;
//under image state add, we create a new image and upload it
if($scope.ImageActionState == imageStates.Add)
{
//transform tags
var tags = _.map($scope.Tags, function(key)
{
return {name : key.text};
});
//right now, no galleryId to upload
var image = new nui.Image(null, $scope.ImageTitle, uploadFile, null, tags, $scope.SelectedSiteId);
//the downstream promise that we return is a composite of our data update and UI update for the grid data...
var update = Q.defer();
//return the result of our promise upstream to the file upload control
$scope.DataManager.Set('Image', image).then(function(result)
{
//update our grid with the latest data
$scope.ImagesData.data.push(result);
update.resolve(result);
$scope.$apply();
}).catch(function(error)
{
update.reject(error);
});
return update.promise;
}
else if ($scope.ImageActionState == imageStates.Save)
{
}
});
//register image on action change
$scope.ImagesData.onRegisterApi = function(gridApi) {
//set gridApi on scope
$scope.gridApi = gridApi;
//post selection in grid
gridApi.selection.on.rowSelectionChanged($scope, function (row) {
//emit a selected site change event so that we can
var selectedImage = row.entity;
$scope.SelectedImage = selectedImage;
$scope.ImageContent = selectedImage.data;
//switch to save state
$scope.ImageActionState = imageStates.Save;
});
};
$scope.GetImages();
});
/*
Directive adapted from base upload template at :
https://css-tricks.com/examples/DragAndDropFileUploading/?submit-on-demand
we use our injected data manager to make the ajax calls within this directive
*/
var ndFileUpload = Images.directive('ndFileUpload', function(){
return{
restrict : 'E',
scope: {
/* upload callback is the callback that we should use
our parent controller to write our file data back to the server*/
uploadCallback: "@uploadCallback"
},
link: function(scope, element, attributes)
{
var isAdvancedUpload = (function()
{
var div = document.createElement( 'div' );
return ( ( 'draggable' in div ) || ( 'ondragstart' in div && 'ondrop' in div ) ) && 'FormData' in window && 'FileReader' in window;
})();
//now apply the effect in this element's scope.
var form = $(element).find('form');
var input = form.find('input[type="file"]');
var label = form.find( 'label' );
var errorMsg = form.find( '.box-error span' );
var restart = form.find( '.box-restart' );
var droppedFiles = false;
var showFiles = (function( files )
{
label.text( files.length > 1 ? ( input.attr( 'data-multiple-caption' ) || '' ).replace( '{count}', files.length ) : files[ 0 ].name );
});
// letting the server side to know we are going to make an Ajax request
form.append( '<input type="hidden" name="ajax" value="1" />' );
// automatically submit the form on file select
input.on( 'change', function( e )
{
showFiles( e.target.files );
});
// drag&drop files if the feature is available
if( isAdvancedUpload )
{
form
.addClass( 'has-advanced-upload' ) // letting the CSS part to know drag&drop is supported by the browser
.on( 'drag dragstart dragend dragover dragenter dragleave drop', function( e )
{
// preventing the unwanted behaviours
e.preventDefault();
e.stopPropagation();
})
.on( 'dragover dragenter', function() //
{
form.addClass( 'is-dragover' );
})
.on( 'dragleave dragend drop', function()
{
form.removeClass( 'is-dragover' );
})
.on( 'drop', function( e )
{
droppedFiles = e.originalEvent.dataTransfer.files; // the files that were dropped
showFiles( droppedFiles );
});
}
// if the form was submitted
form.on( 'submit', function( e )
{
// preventing the duplicate submissions if the current one is in progress
if( form.hasClass( 'is-uploading' ) ) return false;
form.addClass( 'is-uploading' ).removeClass( 'is-error' );
if( isAdvancedUpload ) // ajax file upload for modern browsers
{
e.preventDefault();
// gathering the form data
//var ajaxData = new FormData( form.get( 0 ) );
var fileData = [];
if( droppedFiles )
{
_.each( droppedFiles, function( i, file )
{
fileData.push(i);
});
}
var callback = scope.$parent[scope.uploadCallback];
if(typeof(callback) !== 'function')
{
throw new Error('callback {0} is not a function!'.replace('{0}', callbackName));
}
else
{
//now read the file data using a file reader, and call our callback with this info
var reader = new FileReader();
reader.onload = function(e) {
var rawData = reader.result;
callback(rawData).then(function(result)
{
form.removeClass( 'is-uploading' );
form.addClass('is-success');
}).fail(function(error)
{
form.removeClass( 'is-uploading' );
alert( 'Error. File upload failed' );
})
};
//read the first uploaded file for this directive only
reader.readAsDataURL(fileData[0]);
}
}
else // fallback Ajax solution upload for older browsers
{
var iframeName = 'uploadiframe' + new Date().getTime();
var iframe = $( '<iframe name="' + iframeName + '" style="display: none;"></iframe>' );
$( 'body' ).append( iframe );
form.attr( 'target', iframeName );
iframe.one( 'load', function()
{
var data = $.parseJSON( iframe.contents().find( 'body' ).text() );
form.removeClass( 'is-uploading' ).addClass( data.success == true ? 'is-success' : 'is-error' ).removeAttr( 'target' );
if( !data.success ) errorMsg.text( data.error );
iframe.remove();
});
}
});
// restart the form if has a state of error/success
restart.on( 'click', function( e )
{
e.preventDefault();
form.removeClass( 'is-error is-success' );
input.trigger( 'click' );
});
// Firefox focus bug fix for file input
input
.on( 'focus', function(){ input.addClass( 'has-focus' ); })
.on( 'blur', function(){ input.removeClass( 'has-focus' ); });
},
templateUrl: '../../template/nui-file-upload.html'
}
});
var Scripts = NullDelicious.controller("Scripts", function ($scope, $http, $localStorage, $sessionStorage, $route, $routeParams, $location)
{
$scope.nui = nui;
var deleteTemplate = nui.ui.deleteTemplate;
$scope.ScriptsColumns = [{field : 'name', displayName : 'Name'},
{field : 'text', displayName: 'Text'},
{field : 'siteId', displayName: 'SiteId'},
{field : 'Delete', cellTemplate: deleteTemplate}
];
$scope.ScriptsData = {
data : $scope.Scripts,
columnDefs : $scope.ScriptsColumns,
enableRowSelection: true,
enableSelectAll: false,
selectionRowHeaderWidth: 35,
multiSelect: false
};
/*remove row functionality */
$scope.RemoveRow = function(element) {
var self = this;
var targetRow = element.$parent.$parent.row;
var targetId = targetRow.entity.id;
//now get the index of the element that we wish to remove in our collection, and
//delete it on the server
var scriptToDelete = hx$.single($scope.ScriptsData.data, function(script)
{
return script.id === targetId;
});
$scope.DataManager.Delete('Script', scriptToDelete).then(function(result)
{
//now, remove the element from our grid
var index = $scope.ScriptsData.data.indexOf(scriptToDelete);
$scope.ScriptsData.data.splice(index, 1);
$scope.$apply();
}).fail(function(error)
{
$scope.DeleteError = true;
toastr["error"](error);
$scope.$apply();
});
};
//styles states >> either adding styles or editing them
var scriptsStates =
{
Add: 0,
Save: 1
};
//default state is add
$scope.ScriptActionState = scriptsStates.Add;
$scope.ScriptActionDescriptor = (function()
{
return hx$.GetKeyByValue(scriptsStates, $scope.ScriptActionState) + ' Script';
});
$scope.ScriptAction = (function() {
if ($scope.ScriptActionState == scriptsStates.Add) {
var name = $scope.ScriptName;
var text = $scope.ScriptText;
var siteId = $scope.SelectedSiteId;
var script = new nui.Style(null, name, text, siteId);
$scope.DataManager.Set('Script', script).then(function (data) {
$scope.ScriptsData.data.push(data);
$scope.$apply();
}).catch(function(error)
{
alert(error);
});
}
else if ($scope.ScriptActionState == scriptsStates.Save) {
$scope.SelectedScript.text = $scope.ScriptText;
$scope.SelectedScript.name = $scope.ScriptName;
$scope.DataManager.Set('Script', $scope.SelectedScript).then(function(data) {
var gridScript = hx$.single($scope.ScriptsData.data, function(entry)
{
return entry.id === $scope.SelectedScript.id;
});
gridScript = data;
$scope.$apply();
})
}
});
$scope.GetScripts = (function()
{
if($scope.DataManager)
{
$scope.DataManager.Get('Script', {
query: {key: 'siteId', value : $scope.SelectedSiteId}
}).then(function(data)
{
$scope.Scripts = data;
$scope.ScriptsData.data = $scope.Scripts;
$scope.$apply();
});
}
});
$scope.ScriptsData.onRegisterApi = function(gridApi) {
//set gridApi on scope
$scope.gridApi = gridApi;
//post selection in grid
gridApi.selection.on.rowSelectionChanged($scope, function (row) {
//emit a selected site change event so that we can
var selectedScript = row.entity;
$scope.SelectedScript = selectedScript;
$scope.ScriptName = selectedScript.name;
$scope.ScriptText = selectedScript.text;
//switch to save state
$scope.ScriptActionState = scriptsStates.Save;
});
};
/*scope watches*/
/*scope watches */
$scope.$watch('ScriptText', function(newValue, oldValue)
{
$scope.$broadcast('codeChanged', newValue);
});
$scope.GetScripts();
});
var Styles = NullDelicious.controller("Styles", function ($scope, $http, $localStorage, $sessionStorage, $route, $routeParams, $location)
{
$scope.nui = nui;
//set editor columns and data
var deleteTemplate = nui.ui.deleteTemplate;
$scope.StylesColumns = [{field : 'name', displayName : 'Name'},
{field : 'text', displayName: 'Text'},
{field : 'siteId', displayName: 'SiteId'},
{field : 'Delete', cellTemplate: deleteTemplate}
];
$scope.StylesData = {
data : $scope.Styles,
columnDefs : $scope.StylesColumns,
enableRowSelection: true,
enableSelectAll: false,
selectionRowHeaderWidth: 35,
multiSelect: false
};
/*remove row functionality */
$scope.RemoveRow = function(element) {
var self = this;
var targetRow = element.$parent.$parent.row;
var targetId = targetRow.entity.id;
//now get the index of the element that we wish to remove in our collection, and
//delete it on the server
var styleToDelete = hx$.single($scope.StylesData.data, function(style)
{
return style.id === targetId;
});
$scope.DataManager.Delete('Style', styleToDelete).then(function(result)
{
//now, remove the element from our grid
var index = $scope.StylesData.data.indexOf(styleToDelete);
$scope.StylesData.data.splice(index, 1);
$scope.$apply();
}).fail(function(error)
{
$scope.DeleteError = true;
toastr["error"](error);
$scope.$apply();
});
};
//styles states >> either adding styles or editing them
var stylesStates =
{
Add: 0,
Save: 1
};
//default state is add
$scope.StyleActionState = stylesStates.Add;
$scope.StyleActionDescriptor = (function()
{
return hx$.GetKeyByValue(stylesStates, $scope.StyleActionState) + ' Style';
});
$scope.StyleAction = (function() {
if ($scope.StyleActionState == stylesStates.Add) {
var name = $scope.StyleName;
var text = $scope.StyleText;
var siteId = $scope.SelectedSiteId;
var style = new nui.Style(null, name, text, siteId);
$scope.DataManager.Set('Style', style).then(function (data) {
$scope.StylesData.data.push(data);
$scope.$apply();
}).catch(function(error)
{
alert(error);
});
}
else if ($scope.StyleActionState == stylesStates.Save) {
$scope.SelectedStyle.text = $scope.StyleText;
$scope.SelectedStyle.name = $scope.StyleName;
$scope.DataManager.Set('Style', $scope.SelectedStyle).then(function(data) {
var gridStyle = hx$.single($scope.StylesData.data, function(entry)
{
return entry.id === $scope.SelectedStyle.id;
});
gridStyle = data;
$scope.$apply();
})
}
});
$scope.GetStyles = (function()
{
if($scope.DataManager)
{
$scope.DataManager.Get('Style', {
query: {key: 'siteId', value : $scope.SelectedSiteId}
}).then(function(data)
{
$scope.Styles = data;
$scope.StylesData.data = $scope.Styles;
$scope.$apply();
});
}
});
$scope.StylesData.onRegisterApi = function(gridApi) {
//set gridApi on scope
$scope.gridApi = gridApi;
//post selection in grid
gridApi.selection.on.rowSelectionChanged($scope, function (row) {
//emit a selected site change event so that we can
var selectedStyle = row.entity;
$scope.SelectedStyle = selectedStyle;
$scope.StyleName = selectedStyle.name;
$scope.StyleText = selectedStyle.text;
//switch to save state
$scope.StyleActionState = stylesStates.Save;
});
};
/*scope watches */
$scope.$watch('StyleText', function(newValue, oldValue)
{
$scope.$broadcast('codeChanged', newValue);
});
$scope.GetStyles();
});
var Users = NullDelicious.controller("Users", function ($scope, $http, $localStorage, $sessionStorage, $route, $routeParams, $location)
{
//scope nui client scope through controller scope
$scope.nui = nui;
var deleteTemplate = nui.ui.deleteTemplate;
var userStates =
{
Add: 0,
Save: 1
};
$scope.UserActionState = userStates.Add;
$scope.UserActionDescriptor = (function () {
return hx$.GetKeyByValue(userStates, $scope.UserActionState) + ' User';
});
$scope.UsersColumns = [{field: 'name', displayName: 'Username'},
{field: 'first', displayName: 'First Name'},
{field: 'last', displayName: 'Last Name'},
{field: 'email', displayName: 'Email'},
{field: 'phone', displayName: 'Phone'},
{field: 'gender', displayName: 'Gender'},
{field: 'Delete', cellTemplate: deleteTemplate}
];
$scope.UsersData = {
data: $scope.Users,
columnDefs: $scope.UsersColumns,
enableRowSelection: true,
enableSelectAll: false,
selectionRowHeaderWidth: 35,
multiSelect: false
};
$scope.GetUsers = (function()
{
$scope.DataManager.Get('User', {
query: {key: 'siteId', value : $scope.SelectedSiteId}
}).then(function(data)
{
$scope.Users = data;
$scope.UsersData.data = data;
$scope.$apply();
});
});
$scope.GetPresets = (function()
{
//TODO: refactor this as one preset call on load of application
$scope.DataManager.Get('Presets').then(function (data) {
var genders = _.map(data.enums.Gender, function(value, key)
{
return key;
});
$scope.UserGenders = genders;
});
});
$scope.GetRoles = (function()
{
$scope.DataManager.Get('Role', {query: {key: 'siteId', value : $scope.SelectedSiteId}}).then(function(data)
{
$scope.UserRoles = data;
$scope.$apply();
});
});
$scope.UserAction = (function () {
//add state
if ($scope.UserActionState == userStates.Add) {
var user = new nui.User(null, $scope.Username, $scope.FirstName, $scope.LastName, $scope.Email, $scope.SelectedGender, $scope.Password, $scope.Phone, $scope.SelectedSiteId, $scope.SelectedRole.id);
$scope.DataManager.Set('User', user).then(function (data) {
$scope.UsersData.data.push(data);
$scope.$apply();
});
}
//save state
else if ($scope.UserActionState == userStates.Save) {
var user = new nui.User($scope.SelectedUser.id, $scope.Username, $scope.FirstName, $scope.LastName, $scope.Email, $scope.SelectedGender, $scope.Password, $scope.Phone, $scope.SelectedSiteId, $scope.SelectedRole.id);
$scope.DataManager.Set('User', user).then(function (data) {
//on save, modify the element in the grid
var gridUser = hx$.single($scope.UsersData.data, function (usr) {
return usr.id == $scope.SelectedUser.id;
});
gridUser = data;
$scope.$apply();
});
}
});
/*remove row functionality */
$scope.RemoveRow = function(element) {
var self = this;
var targetRow = element.$parent.$parent.row;
var targetId = targetRow.entity.id;
//now get the index of the element that we wish to remove in our collection, and
//delete it on the server
var userToDelete = hx$.single($scope.UsersData.data, function(user)
{
return user.id === targetId;
});
$scope.DataManager.Delete('User', userToDelete).then(function(result)
{
//now, remove the element from our grid
var index = $scope.UsersData.data.indexOf(userToDelete);
$scope.UsersData.data.splice(index, 1);
$scope.$apply();
}).fail(function(error)
{
$scope.DeleteError = true;
toastr["error"](error);
$scope.$apply();
});
};
$scope.GetUsers();
$scope.GetPresets();
$scope.GetRoles();
//register grid API's
$scope.UsersData.onRegisterApi = function (gridApi) {
//set gridApi on scope
$scope.gridApi = gridApi;
gridApi.selection.on.rowSelectionChanged($scope, function (row) {
//this is where we set our currently selected row in scope
$scope.SelectedUser = row.entity;
$scope.Username = $scope.SelectedUser.name;
$scope.FirstName = $scope.SelectedUser.first;
$scope.LastName = $scope.SelectedUser.last;
$scope.Email = $scope.SelectedUser.email;
$scope.SelectedGender = $scope.SelectedUser.gender;
$scope.Password = $scope.SelectedUser.password;
$scope.Phone = $scope.SelectedUser.phone;
$scope.SelectedRole = hx$.single($scope.UserRoles, function(data)
{
return data.id === $scope.SelectedUser.roleId;
});
//now change our action to a save action
$scope.UserActionState = userStates.Save;
});
};
});
var Roles = NullDelicious.controller("Roles", function ($scope, $http, $localStorage, $sessionStorage, $route, $routeParams, $location) {
$scope.nui = nui;
var roleStates =
{
Add: 0,
Save: 1
};
//default state is add
$scope.RoleActionState = roleStates.Add;
$scope.RoleActionDescriptor = (function () {
return hx$.GetKeyByValue(roleStates, $scope.RoleActionState) + ' Role';
});
var deleteTemplate = nui.ui.deleteTemplate;
$scope.RoleColumns = [{field: 'name', displayName: 'Name'},
{field: 'access', displayName: 'Access'},
{field: 'siteScoped', displayName: 'Site Scoped'},
{field: 'userScoped', displayName: 'User Scoped'},
{field: 'Delete', cellTemplate: deleteTemplate}
];
$scope.RoleData = {
data: $scope.Roles,
columnDefs: $scope.RoleColumns,
enableRowSelection: true,
enableSelectAll: false,
selectionRowHeaderWidth: 35,
multiSelect: false
};
$scope.GetRoles = (function () {
if ($scope.DataManager) {
$scope.DataManager.Get('Role', {
query: {key: 'siteId', value: $scope.SelectedSiteId}
}).then(function (data) {
if (data.length > 0) {
$scope.Roles = data;
$scope.RoleData.data = $scope.Roles;
$scope.$apply();
}
});
}
});
//TODO: refactor this as one preset call on load of application
$scope.GetPresets = (function () {
if ($scope.DataManager) {
$scope.DataManager.Get('Presets').then(function (data) {
//assign result to scope value for role grid
$scope.roleDefinitions = data;
//assign only keys to roledefinitions - we don't want to show the whole schema
$scope.roleDefinitions.schemas = _.map($scope.roleDefinitions.schemas, function (value, key) {
return key;
});
$scope.DefaultRoleAccess = _.map($scope.roleDefinitions.schemas, function (value, key) {
return {resource: value, actions: []};
});
$scope.$apply();
});
}
});
//toggle role action - whether it is on or off for this scope
$scope.ToggleRole = (function (schema, action) {
//get the object that matches the role access
//now add or remove it from the access array
var access = hx$.single($scope.DefaultRoleAccess, function (element) {
return element.resource == schema;
});
if (access.actions.indexOf(action) == -1) {
access.actions.push(action);
}
else {
hx$.removeFirst(access.actions, function (element) {
return element == action;
});
}
});
//whether or not we should display our button as highlighted
$scope.Highlighted = (function (schema, action)
{
var access = hx$.single($scope.DefaultRoleAccess, function(element) {
return element.resource == schema;
});
//if our schema, action pair already exists, then we want to highlight this role in the UI
return access.actions.indexOf(action) > -1;
});
//role save/write action
$scope.RoleAction = (function () {
//add state
if ($scope.RoleActionState == roleStates.Add) {
var role = new nui.Role($scope.RoleName, $scope.UserScopedRole, $scope.SiteScopedRole, $scope.DefaultRoleAccess, $scope.SelectedSiteId);
$scope.DataManager.Set('Role', role).then(function (data) {
$scope.RoleData.data.push(data);
$scope.$apply();
});
}
//save state
else if ($scope.RoleActionState == roleStates.Save) {
var role = new nui.Role($scope.RoleName, $scope.UserScopedRole, $scope.SiteScopedRole, $scope.DefaultRoleAccess, $scope.SelectedRole.siteId, $scope.SelectedRole.id);
$scope.DataManager.Set('Role', role).then(function (data) {
//on save, modify the element in the grid
var gridRole = hx$.single($scope.RoleData.data, function (rl) {
return rl.id == $scope.SelectedRole.id;
});
gridRole = data;
$scope.$apply();
});
}
});
//grid row removal
$scope.RemoveRow = function(element) {
var self = this;
var targetRow = element.$parent.$parent.row;
var targetId = targetRow.entity.id;
//now get the index of the element that we wish to remove in our collection, and
//delete it on the server
var roleToDelete = hx$.single($scope.RoleData.data, function (role) {
return role.id === targetId;
});
$scope.DataManager.Delete('Role', roleToDelete).then(function (result) {
//now, remove the element from our grid
var index = $scope.RoleData.data.indexOf(roleToDelete);
$scope.RoleData.data.splice(index, 1);
$scope.$apply();
}).fail(function (error) {
$scope.DeleteError = true;
toastr["error"](error);
$scope.$apply();
});
};
//get presets for our role scope
$scope.GetPresets();
//get roles for our present site selection
$scope.GetRoles();
//register grid API's
$scope.RoleData.onRegisterApi = function (gridApi) {
//set gridApi on scope
$scope.gridApi = gridApi;
gridApi.selection.on.rowSelectionChanged($scope, function (row) {
//this is where we set our currently selected row in scope
$scope.SelectedRole = row.entity;
$scope.RoleName = $scope.SelectedRole.name;
$scope.UserScopedRole = $scope.SelectedRole.userScoped;
$scope.SiteScopedRole = $scope.SelectedRole.siteScoped;
var access = $scope.SelectedRole.access;
//transform access and re-assign it to our scope
var convertedAccess = _.map(access, function(object)
{
var convertedActions = _.map(object.actions, function(action)
{
return action.name;
});
return {resource: object.resource, actions: convertedActions};
});
$scope.DefaultRoleAccess = convertedAccess;
//now change our action to a save action
$scope.RoleActionState = roleStates.Save;
});
};
});
//Template controller -> controls which templates are active on our site. Retrieves themes from storage
var template = NullDelicious.controller("Template", function ($scope, $http, $localStorage, $sessionStorage, $route, $routeParams, $location){
$scope.nui = nui;
var templateStates =
{
Add: 0,
Save: 1
};
//default state is add
$scope.TemplateActionState = templateStates.Add;
$scope.TemplateActionDescriptor = (function () {
return hx$.GetKeyByValue(templateStates, $scope.TemplateActionState) + ' Template';
});
var deleteTemplate = nui.ui.deleteTemplate;
$scope.TemplateColumns = [{field: 'name', displayName: 'Name'},
{field: 'text', displayName: 'Text'},
{field: 'parameters', displayName: 'Parameters'},
{field: 'Delete', cellTemplate: deleteTemplate}
];
$scope.TemplateData = {
data: $scope.Templates,
columnDefs: $scope.TemplateColumns,
enableRowSelection: true,
enableSelectAll: false,
selectionRowHeaderWidth: 35,
multiSelect: false
};
$scope.GetTemplates = (function () {
if ($scope.DataManager) {
$scope.DataManager.Get('Theme', {
query: {key: 'siteId', value: $scope.SelectedSiteId}
}).then(function (data) {
if (data.length > 0) {
$scope.Templates = data;
$scope.TemplateData.data = $scope.Templates;
$scope.$apply();
}
});
}
});
//callbacks
//template save/write action
$scope.TemplateAction = (function () {
//add state
if ($scope.TemplateActionState == templateStates.Add) {
var theme = new nui.Theme(null, $scope.TemplateText, $scope.TemplateName, $scope.TemplateText, null, $scope.SelectedSiteId);
$scope.DataManager.Set('Theme', theme).then(function (data) {
$scope.TemplateData.data.push(data);
$scope.$apply();
});
}
//save state
else if ($scope.TemplateActionState == templateStates.Save) {
var theme = new nui.Theme($scope.SelectedTemplateId, $scope.TemplateText, $scope.TemplateName, $scope.TemplateText, null, $scope.SelectedSiteId);
$scope.DataManager.Set('Theme', theme).then(function (data) {
//on save, modify the element in the grid
var gridTemplate = hx$.single($scope.TemplateData.data, function (rl) {
return rl.id == $scope.SelectedTemplateId;
});
gridTemplate = data;
$scope.$apply();
});
}
});
//grid row removal
$scope.RemoveRow = function(element) {
var self = this;
var targetRow = element.$parent.$parent.row;
var targetId = targetRow.entity.id;
//now get the index of the element that we wish to remove in our collection, and
//delete it on the server
var templateToDelete = hx$.single($scope.TemplateData.data, function (template) {
return template.id === targetId;
});
$scope.DataManager.Delete('Template', templateToDelete).then(function (result) {
//now, remove the element from our grid
var index = $scope.TemplateData.data.indexOf(templateToDelete);
$scope.TemplateData.data.splice(index, 1);
$scope.$apply();
}).fail(function (error) {
$scope.DeleteError = true;
toastr["error"](error);
$scope.$apply();
});
};
//get templates
$scope.GetTemplates();
//register grid API's
$scope.TemplateData.onRegisterApi = function (gridApi) {
//set gridApi on scope
$scope.gridApi = gridApi;
gridApi.selection.on.rowSelectionChanged($scope, function (row) {
//this is where we set our currently selected row in scope
$scope.SelectedTemplate = row.entity;
$scope.TemplateName = $scope.SelectedTemplate.name;
$scope.SelectedTemplateId = row.entity.id;
$scope.TemplateActionState = templateStates.Save;
});
}
});
NullDelicious.config(['$routeProvider',
function($routeProvider, $locationProvider){
$routeProvider.when('/Editor', {
templateUrl: 'Editor.html', controller : "Editor"
})
.when('/Site', {templateUrl: 'Site.html', controller: "Site"})
.when('/Users',{templateUrl: 'Users.html', controller : "Users"})
.when('/Styles',{templateUrl: 'Styles.html', controller: "Styles"})
.when('/Images',{templateUrl: 'Images.html', controller: "Images"})
.when('/Roles', {templateUrl: 'Roles.html', controller: "Roles"})
.when('/Scripts', {templateUrl: 'Scripts.html', controller: "Scripts"})
.when('/Templates', {templateUrl: 'Template.html', controller: "Template"})
}]);
|
import React from 'react';
import markdown from '../data/index.md';
import Article from '../components/content/Article';
const Home = () => <Article markdown={markdown} />;
export default Home;
|
'use strict';
import $ from 'jquery';
import { GetYoDigits, ignoreMousedisappear } from './foundation.core.utils';
import { MediaQuery } from './foundation.util.mediaQuery';
import { Triggers } from './foundation.util.triggers';
import { Positionable } from './foundation.positionable';
/**
* Tooltip module.
* @module foundation.tooltip
* @requires foundation.util.box
* @requires foundation.util.mediaQuery
* @requires foundation.util.triggers
*/
class Tooltip extends Positionable {
/**
* Creates a new instance of a Tooltip.
* @class
* @name Tooltip
* @fires Tooltip#init
* @param {jQuery} element - jQuery object to attach a tooltip to.
* @param {Object} options - object to extend the default configuration.
*/
_setup(element, options) {
this.$element = element;
this.options = $.extend({}, Tooltip.defaults, this.$element.data(), options);
this.className = 'Tooltip'; // ie9 back compat
this.isActive = false;
this.isClick = false;
// Triggers init is idempotent, just need to make sure it is initialized
Triggers.init($);
this._init();
}
/**
* Initializes the tooltip by setting the creating the tip element, adding it's text, setting private variables and setting attributes on the anchor.
* @private
*/
_init() {
MediaQuery._init();
var elemId = this.$element.attr('aria-describedby') || GetYoDigits(6, 'tooltip');
this.options.tipText = this.options.tipText || this.$element.attr('title');
this.template = this.options.template ? $(this.options.template) : this._buildTemplate(elemId);
if (this.options.allowHtml) {
this.template.appendTo(document.body)
.html(this.options.tipText)
.hide();
} else {
this.template.appendTo(document.body)
.text(this.options.tipText)
.hide();
}
this.$element.attr({
'title': '',
'aria-describedby': elemId,
'data-yeti-box': elemId,
'data-toggle': elemId,
'data-resize': elemId
}).addClass(this.options.triggerClass);
super._init();
this._events();
}
_getDefaultPosition() {
// handle legacy classnames
var position = this.$element[0].className.match(/\b(top|left|right|bottom)\b/g);
return position ? position[0] : 'top';
}
_getDefaultAlignment() {
return 'center';
}
_getHOffset() {
if(this.position === 'left' || this.position === 'right') {
return this.options.hOffset + this.options.tooltipWidth;
} else {
return this.options.hOffset
}
}
_getVOffset() {
if(this.position === 'top' || this.position === 'bottom') {
return this.options.vOffset + this.options.tooltipHeight;
} else {
return this.options.vOffset
}
}
/**
* builds the tooltip element, adds attributes, and returns the template.
* @private
*/
_buildTemplate(id) {
var templateClasses = (`${this.options.tooltipClass} ${this.options.templateClasses}`).trim();
var $template = $('<div></div>').addClass(templateClasses).attr({
'role': 'tooltip',
'aria-hidden': true,
'data-is-active': false,
'data-is-focus': false,
'id': id
});
return $template;
}
/**
* sets the position class of an element and recursively calls itself until there are no more possible positions to attempt, or the tooltip element is no longer colliding.
* if the tooltip is larger than the screen width, default to full width - any user selected margin
* @private
*/
_setPosition() {
super._setPosition(this.$element, this.template);
}
/**
* reveals the tooltip, and fires an event to close any other open tooltips on the page
* @fires Tooltip#closeme
* @fires Tooltip#show
* @function
*/
show() {
if (this.options.showOn !== 'all' && !MediaQuery.is(this.options.showOn)) {
// console.error('The screen is too small to display this tooltip');
return false;
}
var _this = this;
this.template.css('visibility', 'hidden').show();
this._setPosition();
this.template.removeClass('top bottom left right').addClass(this.position)
this.template.removeClass('align-top align-bottom align-left align-right align-center').addClass('align-' + this.alignment);
/**
* Fires to close all other open tooltips on the page
* @event Closeme#tooltip
*/
this.$element.trigger('closeme.zf.tooltip', this.template.attr('id'));
this.template.attr({
'data-is-active': true,
'aria-hidden': false
});
_this.isActive = true;
// console.log(this.template);
this.template.stop().hide().css('visibility', '').fadeIn(this.options.fadeInDuration, function() {
//maybe do stuff?
});
/**
* Fires when the tooltip is shown
* @event Tooltip#show
*/
this.$element.trigger('show.zf.tooltip');
}
/**
* Hides the current tooltip, and resets the positioning class if it was changed due to collision
* @fires Tooltip#hide
* @function
*/
hide() {
// console.log('hiding', this.$element.data('yeti-box'));
var _this = this;
this.template.stop().attr({
'aria-hidden': true,
'data-is-active': false
}).fadeOut(this.options.fadeOutDuration, function() {
_this.isActive = false;
_this.isClick = false;
});
/**
* fires when the tooltip is hidden
* @event Tooltip#hide
*/
this.$element.trigger('hide.zf.tooltip');
}
/**
* adds event listeners for the tooltip and its anchor
* TODO combine some of the listeners like focus and mouseenter, etc.
* @private
*/
_events() {
const _this = this;
const hasTouch = 'ontouchstart' in window || (typeof window.ontouchstart !== 'undefined');
const $template = this.template;
var isFocus = false;
// `disableForTouch: Fully disable the tooltip on touch devices
if (hasTouch && this.options.disableForTouch) return;
if (!this.options.disableHover) {
this.$element
.on('mouseenter.zf.tooltip', function(e) {
if (!_this.isActive) {
_this.timeout = setTimeout(function() {
_this.show();
}, _this.options.hoverDelay);
}
})
.on('mouseleave.zf.tooltip', ignoreMousedisappear(function(e) {
clearTimeout(_this.timeout);
if (!isFocus || (_this.isClick && !_this.options.clickOpen)) {
_this.hide();
}
}));
}
if (hasTouch) {
this.$element
.on('tap.zf.tooltip touchend.zf.tooltip', function (e) {
_this.isActive ? _this.hide() : _this.show();
});
}
if (this.options.clickOpen) {
this.$element.on('mousedown.zf.tooltip', function(e) {
if (_this.isClick) {
//_this.hide();
// _this.isClick = false;
} else {
_this.isClick = true;
if ((_this.options.disableHover || !_this.$element.attr('tabindex')) && !_this.isActive) {
_this.show();
}
}
});
} else {
this.$element.on('mousedown.zf.tooltip', function(e) {
_this.isClick = true;
});
}
this.$element.on({
// 'toggle.zf.trigger': this.toggle.bind(this),
// 'close.zf.trigger': this.hide.bind(this)
'close.zf.trigger': this.hide.bind(this)
});
this.$element
.on('focus.zf.tooltip', function(e) {
isFocus = true;
if (_this.isClick) {
// If we're not showing open on clicks, we need to pretend a click-launched focus isn't
// a real focus, otherwise on hover and come back we get bad behavior
if(!_this.options.clickOpen) { isFocus = false; }
return false;
} else {
_this.show();
}
})
.on('focusout.zf.tooltip', function(e) {
isFocus = false;
_this.isClick = false;
_this.hide();
})
.on('resizeme.zf.trigger', function() {
if (_this.isActive) {
_this._setPosition();
}
});
}
/**
* adds a toggle method, in addition to the static show() & hide() functions
* @function
*/
toggle() {
if (this.isActive) {
this.hide();
} else {
this.show();
}
}
/**
* Destroys an instance of tooltip, removes template element from the view.
* @function
*/
_destroy() {
this.$element.attr('title', this.template.text())
.off('.zf.trigger .zf.tooltip')
.removeClass(this.options.triggerClass)
.removeClass('top right left bottom')
.removeAttr('aria-describedby data-disable-hover data-resize data-toggle data-tooltip data-yeti-box');
this.template.remove();
}
}
Tooltip.defaults = {
/**
* Time, in ms, before a tooltip should open on hover.
* @option
* @type {number}
* @default 200
*/
hoverDelay: 200,
/**
* Time, in ms, a tooltip should take to fade into view.
* @option
* @type {number}
* @default 150
*/
fadeInDuration: 150,
/**
* Time, in ms, a tooltip should take to fade out of view.
* @option
* @type {number}
* @default 150
*/
fadeOutDuration: 150,
/**
* Disables hover events from opening the tooltip if set to true
* @option
* @type {boolean}
* @default false
*/
disableHover: false,
/**
* Disable the tooltip for touch devices.
* This can be useful to make elements with a tooltip on it trigger their
* action on the first tap instead of displaying the tooltip.
* @option
* @type {booelan}
* @default false
*/
disableForTouch: false,
/**
* Optional addtional classes to apply to the tooltip template on init.
* @option
* @type {string}
* @default ''
*/
templateClasses: '',
/**
* Non-optional class added to tooltip templates. Foundation default is 'tooltip'.
* @option
* @type {string}
* @default 'tooltip'
*/
tooltipClass: 'tooltip',
/**
* Class applied to the tooltip anchor element.
* @option
* @type {string}
* @default 'has-tip'
*/
triggerClass: 'has-tip',
/**
* Minimum breakpoint size at which to open the tooltip.
* @option
* @type {string}
* @default 'small'
*/
showOn: 'small',
/**
* Custom template to be used to generate markup for tooltip.
* @option
* @type {string}
* @default ''
*/
template: '',
/**
* Text displayed in the tooltip template on open.
* @option
* @type {string}
* @default ''
*/
tipText: '',
touchCloseText: 'Tap to close.',
/**
* Allows the tooltip to remain open if triggered with a click or touch event.
* @option
* @type {boolean}
* @default true
*/
clickOpen: true,
/**
* Position of tooltip. Can be left, right, bottom, top, or auto.
* @option
* @type {string}
* @default 'auto'
*/
position: 'auto',
/**
* Alignment of tooltip relative to anchor. Can be left, right, bottom, top, center, or auto.
* @option
* @type {string}
* @default 'auto'
*/
alignment: 'auto',
/**
* Allow overlap of container/window. If false, tooltip will first try to
* position as defined by data-position and data-alignment, but reposition if
* it would cause an overflow. @option
* @type {boolean}
* @default false
*/
allowOverlap: false,
/**
* Allow overlap of only the bottom of the container. This is the most common
* behavior for dropdowns, allowing the dropdown to extend the bottom of the
* screen but not otherwise influence or break out of the container.
* Less common for tooltips.
* @option
* @type {boolean}
* @default false
*/
allowBottomOverlap: false,
/**
* Distance, in pixels, the template should push away from the anchor on the Y axis.
* @option
* @type {number}
* @default 0
*/
vOffset: 0,
/**
* Distance, in pixels, the template should push away from the anchor on the X axis
* @option
* @type {number}
* @default 0
*/
hOffset: 0,
/**
* Distance, in pixels, the template spacing auto-adjust for a vertical tooltip
* @option
* @type {number}
* @default 14
*/
tooltipHeight: 14,
/**
* Distance, in pixels, the template spacing auto-adjust for a horizontal tooltip
* @option
* @type {number}
* @default 12
*/
tooltipWidth: 12,
/**
* Allow HTML in tooltip. Warning: If you are loading user-generated content into tooltips,
* allowing HTML may open yourself up to XSS attacks.
* @option
* @type {boolean}
* @default false
*/
allowHtml: false
};
/**
* TODO utilize resize event trigger
*/
export {Tooltip};
|
'use strict';
/*
* This program is distributed under the terms of the MIT license:
* <https://github.com/v0lkan/talks/blob/master/LICENSE.md>
* Send your comments and suggestions to <me@volkan.io>.
*/
import cluster from 'cluster';
import log from 'local-fluent-logger';
import { cpus } from 'os';
import { init as initLeakDetector } from 'local-fluent-leakdetector';
import { init as initPostMortem } from 'local-fluent-postmortem';
import { listen as attachRepl } from 'local-fluent-repl';
let replPort = 8040;
let forkWorker = () => {
let worker = cluster.fork();
worker.send( {
action: 'init',
// XXX: this is not ideal.
// Keep a mapping of cluster.workers.id::replPort
// whenever the worker dies, remove the repl port
// the used ports list etc.
replPort: replPort++,
workerId: worker.id
} );
console.log( `Forked Worker "[${worker.id}](${worker.process.pid})".` );
log.info( `Forked Worker "[${worker.id}](${worker.process.pid})".` );
return worker;
};
let init = ( preListen, listen, kill ) => {
let suicide = kill || ( () => {} );
if ( cluster.isMaster ) {
let cpuCount = parseInt( process.env.CLUSTER_SIZE, 10 ) || cpus().length;
for ( let i = 0; i < cpuCount; i++ ) {
forkWorker();
}
// Respawn the workers that die:
cluster.on('exit', ( worker, code, signal ) => {
console.log( `Worker "${worker.process.pid}" died (${signal||code}). Restarting…` );
log.info( `Worker "${worker.process.pid}" died (${signal||code}). Restarting…` );
forkWorker();
} );
} else {
// We tell the caller to “die”.
// How to kill itself is up to the caller, though.
process.on( 'SIGUSR2', suicide );
process.on( 'message', ( message ) => {
let { action, workerId, replPort } = message;
switch ( action ) {
case 'init':
initPostMortem();
initLeakDetector();
attachRepl( replPort );
preListen( workerId );
listen( workerId );
break;
default:
break;
}
} );
}
};
export { init };
|
import React from 'react';
import renderer from 'react-test-renderer';
import EventListItem from './EventListItem';
test('renders correctly', () => {
const tree = renderer.create(<EventListItem event={{}} onPress={() => {}} />).toJSON();
expect(tree).toMatchSnapshot();
});
|
/*
MIT License
Copyright (c) 2016 Judd Niemann
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.
*/
// chessdiagram.js : defines Chess Diagram Component
import React, { Component } from 'react';
import BoardContainer from './BoardContainer.js';
import GameHistory from './GameHistory.js';
import PropTypes from 'prop-types';
/** Chessdiagram : draws a chess diagram consisting of a board and pieces, using svg graphics */
class Chessdiagram extends Component {
constructor(props) {
super(props);
// If FEN is present, and it is an array, use it for moves
// If FEN is present, and it is a string, make it the first element of the moves array.
// If FEN is NOT present, and PGN is present, call getFensFromPgn() to generate an array of FENs
// If FEN is NOT present, and PGN is NOT present, make first element of moves array an empty string
const moves = props.fen ?
Array.isArray(props.fen) ? props.fen : [props.fen]
: props.pgn ? props.getFensFromPgn(props.pgn) : [''];
// If there is a PGN, set currentMove to this.startMove, otherwise zero.
const currentMove = props.pgn ? this.startMove : 0;
this.state = {
currentMove,
moves
};
}
// Lifecycle events
componentWillReceiveProps(nextProps) {
if (nextProps.fen && nextProps.fen !== this.props.fen) {
this.setState({currentMove: 0, moves: [nextProps.fen]});
}
if (nextProps.pgn && nextProps.pgn !== this.props.pgn) {
this.setState({currentMove: this.startMove, moves: nextProps.getFensFromPgn(nextProps.pgn)});
}
}
// event handling ////
_onMovePiece(pieceType, from, to) {
if (this.props.allowMoves && this.props.onMovePiece) {
this.props.onMovePiece(pieceType, from, to);
}
}
_onMovePgnHead(halfMove) {
this.setState({
currentMove: halfMove
});
}
// returns halfmove count of the prop startMove ////
get startMove() {
let currentMove;
if (typeof this.props.startMove === 'number' || parseInt(this.props.startMove)) {
// halfMove provided
currentMove = parseInt(this.props.startMove);
} else {
// e.g., 'w12'
currentMove = (parseInt(this.props.startMove.slice(1)) - 1) * 2 + (this.props.startMove[0] === 'w' ? 1 : 2);
}
return currentMove;
}
// render function
render() {
return (
<div>
<BoardContainer
{...this.props}
fen={this.state.moves[this.state.currentMove]}
style={{display: 'inline-block'}}
onMovePiece={this._onMovePiece.bind(this)}
/>
{this.props.gameHistory ?
<GameHistory
currentMove={this.state.currentMove}
getHeader={this.props.getHeader}
getMovetext={this.props.getMovetext}
getResult={this.props.getResult}
getRows={this.props.getRows}
moveHead={this._onMovePgnHead.bind(this)}
newlineChar={this.props.newlineChar}
pgn={this.props.pgn}
style={{display: 'inline-block'}}
/> : null
}
</div>
);
}
}
Chessdiagram.propTypes = {
/** Whether to allow the user to make moves on the board (ie, whether to ignore mouse input) */
allowMoves: PropTypes.bool,
darkSquareColor: PropTypes.string,
/** Fen string to render. Should override */
fen: PropTypes.oneOfType([
PropTypes.string,
PropTypes.array
]),
files: PropTypes.number,
/** if true, rotates the board so that Black pawns are moving up, and White pawns are moving down the board */
flip: PropTypes.bool,
/** whether to render a GameHistory component */
gameHistory: PropTypes.bool,
/** Optional custom callbacks for PGN parsing. should take pgn (string).
*/
getFensFromPgn: PropTypes.func,
getHeader: PropTypes.func,
getMovetext: PropTypes.func,
getResult: PropTypes.func,
/** Returns an array of arrays, containing [<fullmoveNumber>, <whiteMove> <optionalBlackMove>] */
getRows: PropTypes.func,
/** height of main svg container in pixels. If setting this manually, it should be at least 9 * squareSize to fit board AND labels*/
height: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
lightSquareColor: PropTypes.string,
/** Pgn line separator. Defaults to '\r?\n'*/
newlineChar: PropTypes.string,
/** callback function which is called when user moves a piece. Passes pieceType, initialSquare, finalSquare as parameters to callback */
onMovePiece: PropTypes.func,
/** callback function which is called when user clicks on a square. Passes name of square as parameter to callback */
onSelectSquare: PropTypes.func,
/** String representation of a PGN. Note that chess.js can't handle templates,
* so if you'd like to pass templates you'll need a custom getNthMove callback.*/
pgn: PropTypes.string,
/** Height of pgn viewer component */
pgnHeight: PropTypes.number,
/** array of pieces at particular squares (alternative to fen) eg ['P@f2','P@g2','P@h2','K@g1'].
* This format may be more suitable for unconventional board dimensions, for which standard FEN would not work.
* Note: If both FEN and pieces props are present, FEN will take precedence */
pieces: PropTypes.array,
/** Optional associative array containing non-standard chess characters*/
pieceDefinitions: PropTypes.object,
ranks: PropTypes.number,
/** size of the squares in pixels */
squareSize: PropTypes.number,
// Which move to start the game on. Either halfmove count or letter followed by full move eg w12 //
startMove: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]),
/** Chess position in FEN format (Forsyth-Edwards Notation). eg "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" */
startPosition: PropTypes.string,
/** width of main svg container in pixels. If setting this manually, it should be at least 9 * squareSize to fit board AND labels*/
width: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
};
const getFensFromPgnDefault = (pgn) => {
var Game = require('chess.js'); // eslint-disable-line no-undef
if (Game.Chess) { // HACK: make it work in the test suite
Game = Game.Chess;
}
const game = new Game();
if (!pgn) {
return [game.fen()];
}
game.load_pgn(pgn);
let moves = [game.fen()];
while (true) {
const result = game.undo();
if (result) {
moves.push(game.fen());
} else {
break;
}
}
moves = moves.reverse();
return moves;
};
Chessdiagram.defaultProps = {
allowMoves: true,
darkSquareColor: "#005EBB",
height: 'auto',
files: 8,
flip: false,
gameHistory: false,
getFensFromPgn: getFensFromPgnDefault,
lightSquareColor: "#2492FF",
newlineChar: '\r?\n',
pieceDefinitions: {},
pgnHeight: 400,
ranks: 8,
startMove: 0,
squareSize: 45,
width: 'auto',
};
export default Chessdiagram;
|
var Widget = require("./widget")
, ArrowKeys = require("arrow-keys")
, duplex = require("duplexer")
, SPEED = 5
module.exports = Player
/*
A player is a stream which emits requested changes in state and which when
written to changes the actual state.
Generally you hook the input up to the change requests and you hook the
state upto the widget for rendering
*/
function Player(x, y) {
var input = ArrowKeys()
, widget = Widget(x, y)
, player = duplex(widget, input)
player.appendTo = widget.appendTo
player.x = x
player.y = y
return player
}
|
(function(){
'use strict';
angular.module('purpose')
.config(['$routeProvider', '$locationProvider', PurposeRoutes]);
function PurposeRoutes($routeProvider, $locationProvider, $q){
$routeProvider
.when('/purpose', {
templateUrl: '/src/pages/purpose/view/content.html',
controller: 'PurposeController',
controllerAs: 'page'
});
}
})();
|
var path = require('path'),
webdriver = require('selenium-webdriver'),
jasmine = require('jasmine-node');
process.env.PATH += path.delimiter + path.dirname(require('chromedriver').path);
var client = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.build();
jasmine.getEnv().defaultTimeoutInterval = 10000;
jasmine.getEnv().addReporter(new jasmine.ConsoleReporter(console.log));
global.webdriver = webdriver;
global.client = client;
describe('Bulk tests...', function(){
require('./definitions.spec.js');
});
|
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
/**
* @fileoverview Defines an {@linkplain cmd.Executor command executor} that
* communicates with a remote end using HTTP + JSON.
*/
'use strict';
const http = require('http');
const https = require('https');
const url = require('url');
const cmd = require('../lib/command');
const error = require('../lib/error');
const logging = require('../lib/logging');
const promise = require('../lib/promise');
const Session = require('../lib/session').Session;
/**
* Converts a headers map to a HTTP header block string.
* @param {!Map<string, string>} headers The map to convert.
* @return {string} The headers as a string.
*/
function headersToString(headers) {
let ret = [];
headers.forEach(function(value, name) {
ret.push(`${name.toLowerCase()}: ${value}`);
});
return ret.join('\n');
}
/**
* Represents a HTTP request message. This class is a "partial" request and only
* defines the path on the server to send a request to. It is each client's
* responsibility to build the full URL for the final request.
* @final
*/
class HttpRequest {
/**
* @param {string} method The HTTP method to use for the request.
* @param {string} path The path on the server to send the request to.
* @param {Object=} opt_data This request's non-serialized JSON payload data.
*/
constructor(method, path, opt_data) {
this.method = /** string */method;
this.path = /** string */path;
this.data = /** Object */opt_data;
this.headers = /** !Map<string, string> */new Map(
[['Accept', 'application/json; charset=utf-8']]);
}
/** @override */
toString() {
let ret = `${this.method} ${this.path} HTTP/1.1\n`;
ret += headersToString(this.headers) + '\n\n';
if (this.data) {
ret += JSON.stringify(this.data);
}
return ret;
}
}
/**
* Represents a HTTP response message.
* @final
*/
class HttpResponse {
/**
* @param {number} status The response code.
* @param {!Object<string>} headers The response headers. All header names
* will be converted to lowercase strings for consistent lookups.
* @param {string} body The response body.
*/
constructor(status, headers, body) {
this.status = /** number */status;
this.body = /** string */body;
this.headers = /** !Map<string, string>*/new Map;
for (let header in headers) {
this.headers.set(header.toLowerCase(), headers[header]);
}
}
/** @override */
toString() {
let ret = `HTTP/1.1 ${this.status}\n${headersToString(this.headers)}\n\n`;
if (this.body) {
ret += this.body;
}
return ret;
}
}
function post(path) { return resource('POST', path); }
function del(path) { return resource('DELETE', path); }
function get(path) { return resource('GET', path); }
function resource(method, path) { return {method: method, path: path}; }
/** @const {!Map<string, {method: string, path: string}>} */
const COMMAND_MAP = new Map([
[cmd.Name.GET_SERVER_STATUS, get('/status')],
[cmd.Name.NEW_SESSION, post('/session')],
[cmd.Name.GET_SESSIONS, get('/sessions')],
[cmd.Name.DESCRIBE_SESSION, get('/session/:sessionId')],
[cmd.Name.QUIT, del('/session/:sessionId')],
[cmd.Name.CLOSE, del('/session/:sessionId/window')],
[cmd.Name.GET_CURRENT_WINDOW_HANDLE, get('/session/:sessionId/window_handle')],
[cmd.Name.GET_WINDOW_HANDLES, get('/session/:sessionId/window_handles')],
[cmd.Name.GET_CURRENT_URL, get('/session/:sessionId/url')],
[cmd.Name.GET, post('/session/:sessionId/url')],
[cmd.Name.GO_BACK, post('/session/:sessionId/back')],
[cmd.Name.GO_FORWARD, post('/session/:sessionId/forward')],
[cmd.Name.REFRESH, post('/session/:sessionId/refresh')],
[cmd.Name.ADD_COOKIE, post('/session/:sessionId/cookie')],
[cmd.Name.GET_ALL_COOKIES, get('/session/:sessionId/cookie')],
[cmd.Name.DELETE_ALL_COOKIES, del('/session/:sessionId/cookie')],
[cmd.Name.DELETE_COOKIE, del('/session/:sessionId/cookie/:name')],
[cmd.Name.FIND_ELEMENT, post('/session/:sessionId/element')],
[cmd.Name.FIND_ELEMENTS, post('/session/:sessionId/elements')],
[cmd.Name.GET_ACTIVE_ELEMENT, post('/session/:sessionId/element/active')],
[cmd.Name.FIND_CHILD_ELEMENT, post('/session/:sessionId/element/:id/element')],
[cmd.Name.FIND_CHILD_ELEMENTS, post('/session/:sessionId/element/:id/elements')],
[cmd.Name.CLEAR_ELEMENT, post('/session/:sessionId/element/:id/clear')],
[cmd.Name.CLICK_ELEMENT, post('/session/:sessionId/element/:id/click')],
[cmd.Name.SEND_KEYS_TO_ELEMENT, post('/session/:sessionId/element/:id/value')],
[cmd.Name.SUBMIT_ELEMENT, post('/session/:sessionId/element/:id/submit')],
[cmd.Name.GET_ELEMENT_TEXT, get('/session/:sessionId/element/:id/text')],
[cmd.Name.GET_ELEMENT_TAG_NAME, get('/session/:sessionId/element/:id/name')],
[cmd.Name.IS_ELEMENT_SELECTED, get('/session/:sessionId/element/:id/selected')],
[cmd.Name.IS_ELEMENT_ENABLED, get('/session/:sessionId/element/:id/enabled')],
[cmd.Name.IS_ELEMENT_DISPLAYED, get('/session/:sessionId/element/:id/displayed')],
[cmd.Name.GET_ELEMENT_LOCATION, get('/session/:sessionId/element/:id/location')],
[cmd.Name.GET_ELEMENT_SIZE, get('/session/:sessionId/element/:id/size')],
[cmd.Name.GET_ELEMENT_ATTRIBUTE, get('/session/:sessionId/element/:id/attribute/:name')],
[cmd.Name.GET_ELEMENT_VALUE_OF_CSS_PROPERTY, get('/session/:sessionId/element/:id/css/:propertyName')],
[cmd.Name.ELEMENT_EQUALS, get('/session/:sessionId/element/:id/equals/:other')],
[cmd.Name.TAKE_ELEMENT_SCREENSHOT, get('/session/:sessionId/element/:id/screenshot')],
[cmd.Name.SWITCH_TO_WINDOW, post('/session/:sessionId/window')],
[cmd.Name.MAXIMIZE_WINDOW, post('/session/:sessionId/window/current/maximize')],
[cmd.Name.GET_WINDOW_POSITION, get('/session/:sessionId/window/current/position')],
[cmd.Name.SET_WINDOW_POSITION, post('/session/:sessionId/window/current/position')],
[cmd.Name.GET_WINDOW_SIZE, get('/session/:sessionId/window/current/size')],
[cmd.Name.SET_WINDOW_SIZE, post('/session/:sessionId/window/current/size')],
[cmd.Name.SWITCH_TO_FRAME, post('/session/:sessionId/frame')],
[cmd.Name.GET_PAGE_SOURCE, get('/session/:sessionId/source')],
[cmd.Name.GET_TITLE, get('/session/:sessionId/created')],
[cmd.Name.EXECUTE_SCRIPT, post('/session/:sessionId/execute')],
[cmd.Name.EXECUTE_ASYNC_SCRIPT, post('/session/:sessionId/execute_async')],
[cmd.Name.SCREENSHOT, get('/session/:sessionId/screenshot')],
[cmd.Name.SET_TIMEOUT, post('/session/:sessionId/timeouts')],
[cmd.Name.SET_SCRIPT_TIMEOUT, post('/session/:sessionId/timeouts/async_script')],
[cmd.Name.IMPLICITLY_WAIT, post('/session/:sessionId/timeouts/implicit_wait')],
[cmd.Name.MOVE_TO, post('/session/:sessionId/moveto')],
[cmd.Name.CLICK, post('/session/:sessionId/click')],
[cmd.Name.DOUBLE_CLICK, post('/session/:sessionId/doubleclick')],
[cmd.Name.MOUSE_DOWN, post('/session/:sessionId/buttondown')],
[cmd.Name.MOUSE_UP, post('/session/:sessionId/buttonup')],
[cmd.Name.MOVE_TO, post('/session/:sessionId/moveto')],
[cmd.Name.SEND_KEYS_TO_ACTIVE_ELEMENT, post('/session/:sessionId/keys')],
[cmd.Name.TOUCH_SINGLE_TAP, post('/session/:sessionId/touch/click')],
[cmd.Name.TOUCH_DOUBLE_TAP, post('/session/:sessionId/touch/doubleclick')],
[cmd.Name.TOUCH_DOWN, post('/session/:sessionId/touch/down')],
[cmd.Name.TOUCH_UP, post('/session/:sessionId/touch/up')],
[cmd.Name.TOUCH_MOVE, post('/session/:sessionId/touch/move')],
[cmd.Name.TOUCH_SCROLL, post('/session/:sessionId/touch/scroll')],
[cmd.Name.TOUCH_LONG_PRESS, post('/session/:sessionId/touch/longclick')],
[cmd.Name.TOUCH_FLICK, post('/session/:sessionId/touch/flick')],
[cmd.Name.ACCEPT_ALERT, post('/session/:sessionId/accept_alert')],
[cmd.Name.DISMISS_ALERT, post('/session/:sessionId/dismiss_alert')],
[cmd.Name.GET_ALERT_TEXT, get('/session/:sessionId/alert_text')],
[cmd.Name.SET_ALERT_TEXT, post('/session/:sessionId/alert_text')],
[cmd.Name.SET_ALERT_CREDENTIALS, post('/session/:sessionId/alert/credentials')],
[cmd.Name.GET_LOG, post('/session/:sessionId/log')],
[cmd.Name.GET_AVAILABLE_LOG_TYPES, get('/session/:sessionId/log/types')],
[cmd.Name.GET_SESSION_LOGS, post('/logs')],
[cmd.Name.UPLOAD_FILE, post('/session/:sessionId/file')],
]);
/** @const {!Map<string, {method: string, path: string}>} */
const W3C_COMMAND_MAP = new Map([
[cmd.Name.GET_WINDOW_SIZE, get('/session/:sessionId/window/size')],
[cmd.Name.SET_WINDOW_SIZE, post('/session/:sessionId/window/size')],
[cmd.Name.MAXIMIZE_WINDOW, post('/session/:sessionId/window/maximize')],
]);
/**
* A basic HTTP client used to send messages to a remote end.
*/
class HttpClient {
/**
* @param {string} serverUrl URL for the WebDriver server to send commands to.
* @param {http.Agent=} opt_agent The agent to use for each request.
* Defaults to `http.globalAgent`.
* @param {?string=} opt_proxy The proxy to use for the connection to the
* server. Default is to use no proxy.
*/
constructor(serverUrl, opt_agent, opt_proxy) {
let parsedUrl = url.parse(serverUrl);
if (!parsedUrl.hostname) {
throw new Error('Invalid server URL: ' + serverUrl);
}
/** @private {http.Agent} */
this.agent_ = opt_agent || null;
/** @private {?string} */
this.proxy_ = opt_proxy || null;
/**
* Base options for each request.
* @private {{auth: (?string|undefined),
* host: string,
* path: (?string|undefined),
* port: (?string|undefined),
* protocol: (?string|undefined)}}
*/
this.options_ = {
auth: parsedUrl.auth,
host: parsedUrl.hostname,
path: parsedUrl.pathname,
port: parsedUrl.port,
protocol: parsedUrl.protocol
};
}
/**
* Sends a request to the server. The client will automatically follow any
* redirects returned by the server, fulfilling the returned promise with the
* final response.
*
* @param {!HttpRequest} httpRequest The request to send.
* @return {!promise.Promise<HttpResponse>} A promise that will be fulfilled
* with the server's response.
*/
send(httpRequest) {
var data;
let headers = {};
httpRequest.headers.forEach(function(value, name) {
headers[name] = value;
});
headers['Content-Length'] = 0;
if (httpRequest.method == 'POST' || httpRequest.method == 'PUT') {
data = JSON.stringify(httpRequest.data);
headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
headers['Content-Type'] = 'application/json;charset=UTF-8';
}
var path = this.options_.path;
if (path[path.length - 1] === '/' && httpRequest.path[0] === '/') {
path += httpRequest.path.substring(1);
} else {
path += httpRequest.path;
}
var options = {
method: httpRequest.method,
auth: this.options_.auth,
host: this.options_.host,
port: this.options_.port,
protocol: this.options_.protocol,
path: path,
headers: headers
};
if (this.agent_) {
options.agent = this.agent_;
}
var proxy = this.proxy_;
return new promise.Promise(function(fulfill, reject) {
sendRequest(options, fulfill, reject, data, proxy);
});
}
}
/**
* Sends a single HTTP request.
* @param {!Object} options The request options.
* @param {function(!HttpResponse)} onOk The function to call if the
* request succeeds.
* @param {function(!Error)} onError The function to call if the request fails.
* @param {?string=} opt_data The data to send with the request.
* @param {?string=} opt_proxy The proxy server to use for the request.
*/
function sendRequest(options, onOk, onError, opt_data, opt_proxy) {
var host = options.host;
var port = options.port;
if (opt_proxy) {
var proxy = url.parse(opt_proxy);
options.headers['Host'] = options.host;
options.host = proxy.hostname;
options.port = proxy.port;
if (proxy.auth) {
options.headers['Proxy-Authorization'] =
'Basic ' + new Buffer(proxy.auth).toString('base64');
}
}
let requestFn = options.protocol === 'https:' ? https.request : http.request;
var request = requestFn(options, function onResponse(response) {
if (response.statusCode == 302 || response.statusCode == 303) {
try {
var location = url.parse(response.headers['location']);
} catch (ex) {
onError(Error(
'Failed to parse "Location" header for server redirect: ' +
ex.message + '\nResponse was: \n' +
new HttpResponse(response.statusCode, response.headers, '')));
return;
}
if (!location.hostname) {
location.hostname = host;
location.port = port;
}
request.abort();
sendRequest({
method: 'GET',
host: location.hostname,
path: location.pathname + (location.search || ''),
port: location.port,
protocol: location.protocol,
headers: {
'Accept': 'application/json; charset=utf-8'
}
}, onOk, onError, undefined, opt_proxy);
return;
}
var body = [];
response.on('data', body.push.bind(body));
response.on('end', function() {
var resp = new HttpResponse(
/** @type {number} */(response.statusCode),
/** @type {!Object<string>} */(response.headers),
body.join('').replace(/\0/g, ''));
onOk(resp);
});
});
request.on('error', function(e) {
if (e.code === 'ECONNRESET') {
setTimeout(function() {
sendRequest(options, onOk, onError, opt_data, opt_proxy);
}, 15);
} else {
var message = e.message;
if (e.code) {
message = e.code + ' ' + message;
}
onError(new Error(message));
}
});
if (opt_data) {
request.write(opt_data);
}
request.end();
}
/**
* A command executor that communicates with the server using HTTP + JSON.
*
* By default, each instance of this class will use the legacy wire protocol
* from [Selenium project][json]. The executor will automatically switch to the
* [W3C wire protocol][w3c] if the remote end returns a compliant response to
* a new session command.
*
* [json]: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
* [w3c]: https://w3c.github.io/webdriver/webdriver-spec.html
*
* @implements {cmd.Executor}
*/
class Executor {
/**
* @param {!HttpClient} client The client to use for sending requests to the
* server.
*/
constructor(client) {
/** @private {!HttpClient} */
this.client_ = client;
/**
* Whether this executor should use the W3C wire protocol. The executor
* will automatically switch if the remote end sends a compliant response
* to a new session command, however, this property may be directly set to
* `true` to force the executor into W3C mode.
* @type {boolean}
*/
this.w3c = false;
/** @private {Map<string, {method: string, path: string}>} */
this.customCommands_ = null;
/** @private {!logging.Logger} */
this.log_ = logging.getLogger('webdriver.http.Executor');
}
/**
* Defines a new command for use with this executor. When a command is sent,
* the {@code path} will be preprocessed using the command's parameters; any
* path segments prefixed with ":" will be replaced by the parameter of the
* same name. For example, given "/person/:name" and the parameters
* "{name: 'Bob'}", the final command path will be "/person/Bob".
*
* @param {string} name The command name.
* @param {string} method The HTTP method to use when sending this command.
* @param {string} path The path to send the command to, relative to
* the WebDriver server's command root and of the form
* "/path/:variable/segment".
*/
defineCommand(name, method, path) {
if (!this.customCommands_) {
this.customCommands_ = new Map;
}
this.customCommands_.set(name, {method, path});
}
/** @override */
execute(command) {
let resource =
(this.customCommands_ && this.customCommands_.get(command.getName()))
|| (this.w3c && W3C_COMMAND_MAP.get(command.getName()))
|| COMMAND_MAP.get(command.getName());
if (!resource) {
throw new error.UnknownCommandError(
'Unrecognized command: ' + command.getName());
}
let parameters = command.getParameters();
let path = buildPath(resource.path, parameters);
let request = new HttpRequest(resource.method, path, parameters);
let log = this.log_;
log.finer(() => '>>>\n' + request);
return this.client_.send(request).then(response => {
log.finer(() => '<<<\n' + response);
let parsed =
parseHttpResponse(/** @type {!HttpResponse} */ (response), this.w3c);
if (command.getName() === cmd.Name.NEW_SESSION
|| command.getName() === cmd.Name.DESCRIBE_SESSION) {
if (!parsed || !parsed['sessionId']) {
throw new error.WebDriverError(
'Unable to parse new session response: ' + response.body);
}
// The remote end is a W3C compliant server if there is no `status`
// field in the response. This is not appliable for the DESCRIBE_SESSION
// command, which is not defined in the W3C spec.
if (command.getName() === cmd.Name.NEW_SESSION) {
this.w3c = this.w3c || !('status' in parsed);
}
return new Session(parsed['sessionId'], parsed['value']);
}
if (parsed) {
let value = parsed['value'];
return typeof value === 'undefined' ? null : value;
}
return parsed;
});
}
}
/**
* @param {string} str .
* @return {?} .
*/
function tryParse(str) {
try {
return JSON.parse(str);
} catch (ignored) {
// Do nothing.
}
}
/**
* Callback used to parse {@link HttpResponse} objects from a
* {@link HttpClient}.
* @param {!HttpResponse} httpResponse The HTTP response to parse.
* @param {boolean} w3c Whether the response should be processed using the
* W3C wire protocol.
* @return {{value: ?}} The parsed response.
* @throws {WebDriverError} If the HTTP response is an error.
*/
function parseHttpResponse(httpResponse, w3c) {
let parsed = tryParse(httpResponse.body);
if (parsed !== undefined) {
if (w3c) {
if (httpResponse.status > 399) {
error.throwDecodedError(parsed);
}
if (httpResponse.status < 200) {
// This should never happen, but throw the raw response so
// users report it.
throw new error.WebDriverError(
`Unexpected HTTP response:\n${httpResponse}`);
}
} else {
error.checkLegacyResponse(parsed);
}
if (!parsed || typeof parsed !== 'object') {
parsed = {value: parsed};
}
return parsed
}
let value = httpResponse.body.replace(/\r\n/g, '\n');
// 404 represents an unknown command; anything else > 399 is a generic unknown
// error.
if (httpResponse.status == 404) {
throw new error.UnsupportedOperationError(value);
} else if (httpResponse.status >= 400) {
throw new error.WebDriverError(value);
}
return {value: value || null};
}
/**
* Builds a fully qualified path using the given set of command parameters. Each
* path segment prefixed with ':' will be replaced by the value of the
* corresponding parameter. All parameters spliced into the path will be
* removed from the parameter map.
* @param {string} path The original resource path.
* @param {!Object<*>} parameters The parameters object to splice into the path.
* @return {string} The modified path.
*/
function buildPath(path, parameters) {
let pathParameters = path.match(/\/:(\w+)\b/g);
if (pathParameters) {
for (let i = 0; i < pathParameters.length; ++i) {
let key = pathParameters[i].substring(2); // Trim the /:
if (key in parameters) {
let value = parameters[key];
// TODO: move webdriver.WebElement.ELEMENT definition to a
// common file so we can reference it here without pulling in all of
// webdriver.WebElement's dependencies.
if (value && value['ELEMENT']) {
// When inserting a WebElement into the URL, only use its ID value,
// not the full JSON.
value = value['ELEMENT'];
}
path = path.replace(pathParameters[i], '/' + value);
delete parameters[key];
} else {
throw new error.InvalidArgumentError(
'Missing required parameter: ' + key);
}
}
}
return path;
}
// PUBLIC API
exports.Executor = Executor;
exports.HttpClient = HttpClient;
exports.Request = HttpRequest;
exports.Response = HttpResponse;
exports.buildPath = buildPath; // Exported for testing.
|
import React, { PropTypes } from 'react';
const WelcomeMessage = ({ userText }) => {
return (
<h2>{`Welcome, ${userText}. Here's what you should watch tonight:`}</h2>
);
};
WelcomeMessage.propTypes = {
userText: PropTypes.string.isRequired
};
export default WelcomeMessage;
|
const option = require('../option');
it('should return option', () => {
expect(typeof option).toBe('function');
});
|
'use strict';
var expect = require("expect.js"),
simplator = require("simplator"),
templates = {
nameTmpl: simplator.compile("{first},{last}"),
addressTmpl: simplator.compile("{street},{city}")
},
subTemplates = require('../lib/simplator-subtemplates');
describe("simplator_subtemplates", function () {
var results;
before(function () {
subTemplates.use(templates);
});
it("is defined", function () {
expect(subTemplates).to.be.an('object');
});
describe("object context", function () {
before(function () {
var tmplt = simplator.compile("{name | sub('nameTmpl')}\n{address | sub('addressTmpl') }");
results = tmplt({
name: {
first: "Andrea",
last: "Parodi"
},
address: {
street: "via Casata",
city: "Genoa"
}
});
});
it("work!", function () {
expect(results).to.be.equal('Andrea,Parodi\nvia Casata,Genoa');
});
});
describe("array context", function () {
before(function () {
var tmplt = simplator.compile("{name | sub('nameTmpl')}\n{addresses | subEach('addressTmpl','\t') }");
results = tmplt({
name: {
first: "Andrea",
last: "Parodi"
},
addresses: [{
street: "via Casata",
city: "Genoa"
},{
street: "Another address",
city: "Roma"
}]
});
});
it("work!", function () {
expect(results).to.be.equal('Andrea,Parodi\nvia Casata,Genoa\tAnother address,Roma');
});
});
});
|
import React, { Component } from 'react';
import TemplateController from '../../controllers/Templates';
import ContentController from '../../controllers/Content';
import {Card, CardHeader, CardText, TextField, Toggle, RaisedButton, Snackbar} from 'material-ui';
import utl from '../../utl/StringFormatting.js';
export default class InputForm extends Component {
constructor(props){
super(props);
this.state = {
currentKey: props.id,
key: props.id,
label: props.label,
instructions: props.instructions,
required: props.required,
saving: false,
isSaved: false,
error: [],
}
this.handleInput = this.handleInput.bind(this);
}
componentWillReceiveProps(nextProps){
if(this.state !== nextProps){
this.setState(nextProps);
}
}
render(){
const CardHeaderStyle = {
backgroundColor: '#5a5a5a'
},
inputStyle = {
display: 'block'
},
titleColor = "#FFF"
;
return(
<Card>
<CardHeader
title={utl.capitalize(this.state.key)}
style={CardHeaderStyle}
titleColor={titleColor}
/>
<CardText>
<TextField
style={inputStyle}
floatingLabelText="Id"
id="key"
value={this.state.key}
onChange={this.handleInput}
/>
<TextField
style={inputStyle}
floatingLabelText="Label"
id="label"
value={this.state.label}
onChange={this.handleInput}
/>
<TextField
style={inputStyle}
floatingLabelText="Instructions"
label="instructions"
id="instructions"
value={this.state.instructions}
onChange={this.handleInput}
/>
<Toggle
style={inputStyle}
label="Required"
id="required"
labelPosition="right"
toggled={this.state.required}
onToggle={this.handleToggle.bind(this)}
/>
<RaisedButton backgroundColor="#28a745" labelColor="#FFF" disabled={this.state.saving} label={this.state.saving ? "Saving..." : "Save"} onClick={this.handleSave.bind(this)}></RaisedButton>
</CardText>
{this.renderFeedback()}
</Card>
);
}
handleInput(e){
let element = e.target;
this.setState({
[element.id]: element.value
});
}
handleToggle(e, toggle){
let element = e.target;
this.setState({
[element.id]: toggle
});
}
renderFeedback(){
return(
<Snackbar
open={this.state.isSaved}
message={this.state.error.length > 0 ? "Uh Oh something went wrong!": "Save Successful!"}
autoHideDuration={4000}
/>
);
}
handleSave(e){
e.preventDefault();
this.setState({
saving: true
}, ()=>{
let toBeSaved = {
input: this.props.input,
instructions: this.state.instructions,
label: this.state.label,
required: this.state.required
},
oldKey = this.state.currentKey,
template = new TemplateController();
template.UpdateRecord(this.props.contentId, this.state.key , toBeSaved).then((created)=>{
if (this.state.key !== oldKey){
template.DeleteRecord(this.props.contentId, oldKey).then(()=>{
let content = new ContentController();
content.GetRecord(this.props.contentId).then((record)=>{
if(record.type === "single"){
let newContent = { [this.state.key]: record[oldKey] || ""};
content.UpdateRecord(this.props.contentId, newContent).then(()=>{
content.DeleteInput(this.props.contentId, oldKey);
});
} else {
let newContent;
Object.entries(record.items).forEach(([key,item]) => {
newContent = {[this.state.key]: item[oldKey] || ""};
content.UpdateRecord(this.props.contentId, newContent, key).then(()=>{
content.DeleteInput(this.props.contentId, oldKey, key);
});
});
}
});
});
}
this.setState({
saving: false,
isSaved: true,
currentKey: this.state.key
});
}).catch((error)=>{
this.setState({
error: this.state.error.push(error),
saving: false
})
;
});
});
}
}
|
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import App from '../common/components/App'
import configureStore from '../common/store/configureStore';
const preloadedState = window.__PRELOADED_STATE__ ? window.__PRELOADED_STATE__ : {};
const store = configureStore(preloadedState);
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({});
});
|
export { default, slice } from '@abcum/ember-helpers/helpers/slice';
|
// Mouse buttons constants
this.creatine.buttons = {
LEFT : 0,
MIDDLE : 1,
RIGHT : 2,
};
|
var expect = require('../lib');
expect.addAssertion('<any> to bar', function(expect, subject) {
expect(subject, 'to equal', 'bar');
return expect.promise(function(resolve, reject) {});
});
expect.addAssertion('<any> to foo', function(expect) {
expect('bar', 'to bar');
});
it('should call the callback', function() {
expect('foo', 'to foo');
});
|
'use strict';
/**
* app.js
*
* Use `app.js` to run your app without `sails lift`.
* To start the server, run: `node app.js`.
*
* This is handy in situations where the sails CLI is not relevant or useful.
*
* For example:
* => `node app.js`
* => `forever start app.js`
* => `node debug app.js`
* => `modulus deploy`
* => `heroku scale`
*
*
* The same command-line arguments are supported, e.g.:
* `node app.js --silent --port=80 --prod`
*/
// Ensure a "sails" can be located:
var sails;
try {
sails = require('sails');
} catch (e) {
console.error('To run an app using `node app.js`, you usually need to have a version of `sails` installed in the same directory as your app.');
console.error('To do that, run `npm install sails`');
console.error('');
console.error('Alternatively, if you have sails installed globally (i.e. you did `npm install -g sails`), you can use `sails lift`.');
console.error('When you run `sails lift`, your app will still use a local `./node_modules/sails` dependency if it exists,');
console.error('but if it doesn\'t, the app will run with the global sails instead!');
return;
}
// Try to get `rc` dependency
var rc;
try {
rc = require('rc');
} catch (e0) {
try {
rc = require('sails/node_modules/rc');
} catch (e1) {
console.error('Could not find dependency: `rc`.');
console.error('Your `.sailsrc` file(s) will be ignored.');
console.error('To resolve this, run:');
console.error('npm install rc --save');
rc = function () {
return {};
};
}
}
// Start server
sails.lift(rc('sails'));
|
/* @flow */
import * as React from 'react';
type Props = {
text: string,
};
type State = {
text: string,
};
export default class FlowText extends React.Component<Props, State> {
static defaultProps: any;
props: Props;
// property initializers used to ensure issue is fixed: https://github.com/babel/babel/issues/8417
state: State = {
text: 'text:' + this.props.text,
};
render() {
return <span>{this.state.text}</span>;
}
}
|
/**
* Processes a Facebook Group's feed. Allows you to run each group thread
* through any number of filters which expose auto-moderator functionality.
* @module
*/
var Post = require('./Post')
var Promise = require('es6-promise').Promise
var _ = require('underscore')
var fb = require('./fb')
/**
* The query parameters used to refresh a group.
* @constant {Object}
*/
var refreshParams = {
fields: 'created_time,from,message,comments.limit(1000){from,message,created_time}',
limit: 10
}
/**
* Returns the path of the group.
* @param {string} groupID
* @return {string}
*/
function feedPath(groupID) {
return groupID + '/feed'
}
/**
* Converts a raw request body into a feed.
* @param {Object} body
* @return {Post[][]}
*/
function fromRaw(body) {
return _.map(body.data, function (rawPost) {
var op = Post.fromRaw(rawPost)
var thread = [op]
var rawComments = rawPost.comments ? rawPost.comments.data : []
rawComments.forEach(function (raw) {
var cmt = Post.fromRaw(raw)
thread.push(cmt)
})
return thread
})
}
function applyActions(actions) {
var promises = _.map(actions, function (a) {
return a.apply()
})
return Promise.all(promises)
}
function updateThread(thread, actions) {
return _.reduce(actions, function (memo, action) {
return action.update(memo)
}, thread)
}
/**
* Refreshes a group by running its feed through a list of
* filters.
* @param {string} groupID
* @param {module:feed~Filter[]} filters
* @return {Promise}
*/
exports.refresh = function(groupID, filters) {
return fb.get(feedPath(groupID), refreshParams)
.then(function(body) {
var feed = fromRaw(body)
var actions = []
for (var thread of feed) {
for (var filter of filters) {
var filterActions = filter(thread)
actions.push(filterActions)
thread = updateThread(thread, filterActions)
}
}
return applyActions(_.flatten(actions))
})
}
/**
* A filter function for a thread.
* @interface
* @callback Filter
* @param {Post[]} thread
* @return {Action[]}
*/
|
import { getRandNumber } from './Utils';
export default class Particle {
canvas = {};
vector = {};
/*
* Initialize the particle.
* @param {Object} canvas DOM element.
* @param {Object} params Few particle's params.
*/
constructor(canvas, params){
this.params = {
color: 'white',
minSize: 2,
maxSize: 4,
speed: 60
};
for(var param in params){
this.params[param] = params[param];
}
this.setCanvasContext(canvas);
this.initSize();
this.initPosition();
this.initVectors();
}
/*
* Initialize particle's position.
*/
initPosition(){
this.x = getRandNumber(0 + this.radius, this.canvas.element.width - this.radius);
this.y = getRandNumber(0 + this.radius, this.canvas.element.height - this.radius);
};
/*
* Initialize particle's size.
*/
initSize(){
this.size = getRandNumber(this.params.minSize, this.params.maxSize);
this.radius = this.size / 2;
}
/*
* Initialize particle's vectors for speed.
*/
initVectors(){
let { speed } = this.params;
do {
this.vector.x = getRandNumber(-speed / 60, speed / 60, false);
this.vector.y = getRandNumber(-speed / 60, speed / 60, false);
} while (this.vector.x == 0 || this.vector.y == 0);
}
/*
* Set the context to draw particles.
* @param {Object} canvas Canvas.
*/
setCanvasContext(canvas){
this.canvas.element = canvas;
var context = canvas.getContext('2d');
if (typeof context === 'object' && typeof context.canvas === 'object') {
this.canvas.context = context;
} else {
throw 'Error: Can\'t set canvas context to Particle because context isn\'t a CanvasRenderingContext2D object.';
}
}
/*
* Draw particle.
*/
draw(){
var context = this.canvas.context;
context.beginPath();
context.arc(this.x, this.y, this.size /2, 0, Math.PI*2);
context.fillStyle = this.params.color;
context.fill();
context.closePath();
}
/*
* Update the particle's position.
*/
update(){
this.x += this.vector.x;
this.y += this.vector.y;
if (0 > (this.x - this.radius) || (this.x + this.radius) > this.canvas.element.width) {
this.vector.x = -this.vector.x;
}
if (0 > (this.y - this.radius) || (this.y + this.radius) > this.canvas.element.height) {
this.vector.y = -this.vector.y;
}
}
/*
* Return position of particle.
* @param {string} axis Optionnal axis.
* @return {int|Object} Return object if axis is not defined, else return int.
*/
getPosition(axis){
if (typeof axis === 'string' && (axis != 'x' && axis != 'y')) {
axis = null;
}
return (typeof(axis) === 'string') ? this[ axis ] : { x: this.x, y: this.y };
}
}
|
import React from "react";
import {
Page,
HashSection,
Paragraph,
MultiSandbox
} from "../../components/example/common";
let meta = {
title: "Navigation Confirmation"
};
let explanationMeta = {
title: "Explanation",
hash: "explanation"
};
let demoMeta = {
title: "Live Demo",
hash: "demo"
};
let contents = [explanationMeta, demoMeta];
function ConfirmationExample() {
return (
<Page title={meta.title}>
<HashSection meta={explanationMeta} tag="h2">
<Paragraph>
A Curi application that uses navigation confirmation to verify that
the user wants to leave the current page.
</Paragraph>
</HashSection>
<HashSection meta={demoMeta} tag="h2">
<MultiSandbox
sandboxes={[
{
id: "github/pshrmn/curi/tree/master/examples/react/confirmation",
name: "React"
}
]}
/>
</HashSection>
</Page>
);
}
export { ConfirmationExample as component, contents };
|
import { moduleFor, test } from 'ember-qunit';
moduleFor('route:gamer', 'Unit | Route | gamer', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
test('it exists', function(assert) {
var route = this.subject();
assert.ok(route);
});
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.createREGL = factory());
}(this, (function () { 'use strict';
var isTypedArray = function (x) {
return (
x instanceof Uint8Array ||
x instanceof Uint16Array ||
x instanceof Uint32Array ||
x instanceof Int8Array ||
x instanceof Int16Array ||
x instanceof Int32Array ||
x instanceof Float32Array ||
x instanceof Float64Array ||
x instanceof Uint8ClampedArray
)
}
var extend = function (base, opts) {
var keys = Object.keys(opts)
for (var i = 0; i < keys.length; ++i) {
base[keys[i]] = opts[keys[i]]
}
return base
}
// Error checking and parameter validation.
//
// Statements for the form `check.someProcedure(...)` get removed by
// a browserify transform for optimized/minified bundles.
//
/* globals atob */
var endl = '\n'
// only used for extracting shader names. if atob not present, then errors
// will be slightly crappier
function decodeB64 (str) {
if (typeof atob !== 'undefined') {
return atob(str)
}
return 'base64:' + str
}
function raise (message) {
var error = new Error('(regl) ' + message)
console.error(error)
throw error
}
function check (pred, message) {
if (!pred) {
raise(message)
}
}
function encolon (message) {
if (message) {
return ': ' + message
}
return ''
}
function checkParameter (param, possibilities, message) {
if (!(param in possibilities)) {
raise('unknown parameter (' + param + ')' + encolon(message) +
'. possible values: ' + Object.keys(possibilities).join())
}
}
function checkIsTypedArray (data, message) {
if (!isTypedArray(data)) {
raise(
'invalid parameter type' + encolon(message) +
'. must be a typed array')
}
}
function standardTypeEh (value, type) {
switch (type) {
case 'number': return typeof value === 'number'
case 'object': return typeof value === 'object'
case 'string': return typeof value === 'string'
case 'boolean': return typeof value === 'boolean'
case 'function': return typeof value === 'function'
case 'undefined': return typeof value === 'undefined'
case 'symbol': return typeof value === 'symbol'
}
}
function checkTypeOf (value, type, message) {
if (!standardTypeEh(value, type)) {
raise(
'invalid parameter type' + encolon(message) +
'. expected ' + type + ', got ' + (typeof value))
}
}
function checkNonNegativeInt (value, message) {
if (!((value >= 0) &&
((value | 0) === value))) {
raise('invalid parameter type, (' + value + ')' + encolon(message) +
'. must be a nonnegative integer')
}
}
function checkOneOf (value, list, message) {
if (list.indexOf(value) < 0) {
raise('invalid value' + encolon(message) + '. must be one of: ' + list)
}
}
var constructorKeys = [
'gl',
'canvas',
'container',
'attributes',
'pixelRatio',
'extensions',
'optionalExtensions',
'profile',
'onDone'
]
function checkConstructor (obj) {
Object.keys(obj).forEach(function (key) {
if (constructorKeys.indexOf(key) < 0) {
raise('invalid regl constructor argument "' + key + '". must be one of ' + constructorKeys)
}
})
}
function leftPad (str, n) {
str = str + ''
while (str.length < n) {
str = ' ' + str
}
return str
}
function ShaderFile () {
this.name = 'unknown'
this.lines = []
this.index = {}
this.hasErrors = false
}
function ShaderLine (number, line) {
this.number = number
this.line = line
this.errors = []
}
function ShaderError (fileNumber, lineNumber, message) {
this.file = fileNumber
this.line = lineNumber
this.message = message
}
function guessCommand () {
var error = new Error()
var stack = (error.stack || error).toString()
var pat = /compileProcedure.*\n\s*at.*\((.*)\)/.exec(stack)
if (pat) {
return pat[1]
}
var pat2 = /compileProcedure.*\n\s*at\s+(.*)(\n|$)/.exec(stack)
if (pat2) {
return pat2[1]
}
return 'unknown'
}
function guessCallSite () {
var error = new Error()
var stack = (error.stack || error).toString()
var pat = /at REGLCommand.*\n\s+at.*\((.*)\)/.exec(stack)
if (pat) {
return pat[1]
}
var pat2 = /at REGLCommand.*\n\s+at\s+(.*)\n/.exec(stack)
if (pat2) {
return pat2[1]
}
return 'unknown'
}
function parseSource (source, command) {
var lines = source.split('\n')
var lineNumber = 1
var fileNumber = 0
var files = {
unknown: new ShaderFile(),
0: new ShaderFile()
}
files.unknown.name = files[0].name = command || guessCommand()
files.unknown.lines.push(new ShaderLine(0, ''))
for (var i = 0; i < lines.length; ++i) {
var line = lines[i]
var parts = /^\s*#\s*(\w+)\s+(.+)\s*$/.exec(line)
if (parts) {
switch (parts[1]) {
case 'line':
var lineNumberInfo = /(\d+)(\s+\d+)?/.exec(parts[2])
if (lineNumberInfo) {
lineNumber = lineNumberInfo[1] | 0
if (lineNumberInfo[2]) {
fileNumber = lineNumberInfo[2] | 0
if (!(fileNumber in files)) {
files[fileNumber] = new ShaderFile()
}
}
}
break
case 'define':
var nameInfo = /SHADER_NAME(_B64)?\s+(.*)$/.exec(parts[2])
if (nameInfo) {
files[fileNumber].name = (nameInfo[1]
? decodeB64(nameInfo[2])
: nameInfo[2])
}
break
}
}
files[fileNumber].lines.push(new ShaderLine(lineNumber++, line))
}
Object.keys(files).forEach(function (fileNumber) {
var file = files[fileNumber]
file.lines.forEach(function (line) {
file.index[line.number] = line
})
})
return files
}
function parseErrorLog (errLog) {
var result = []
errLog.split('\n').forEach(function (errMsg) {
if (errMsg.length < 5) {
return
}
var parts = /^ERROR:\s+(\d+):(\d+):\s*(.*)$/.exec(errMsg)
if (parts) {
result.push(new ShaderError(
parts[1] | 0,
parts[2] | 0,
parts[3].trim()))
} else if (errMsg.length > 0) {
result.push(new ShaderError('unknown', 0, errMsg))
}
})
return result
}
function annotateFiles (files, errors) {
errors.forEach(function (error) {
var file = files[error.file]
if (file) {
var line = file.index[error.line]
if (line) {
line.errors.push(error)
file.hasErrors = true
return
}
}
files.unknown.hasErrors = true
files.unknown.lines[0].errors.push(error)
})
}
function checkShaderError (gl, shader, source, type, command) {
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
var errLog = gl.getShaderInfoLog(shader)
var typeName = type === gl.FRAGMENT_SHADER ? 'fragment' : 'vertex'
checkCommandType(source, 'string', typeName + ' shader source must be a string', command)
var files = parseSource(source, command)
var errors = parseErrorLog(errLog)
annotateFiles(files, errors)
Object.keys(files).forEach(function (fileNumber) {
var file = files[fileNumber]
if (!file.hasErrors) {
return
}
var strings = ['']
var styles = ['']
function push (str, style) {
strings.push(str)
styles.push(style || '')
}
push('file number ' + fileNumber + ': ' + file.name + '\n', 'color:red;text-decoration:underline;font-weight:bold')
file.lines.forEach(function (line) {
if (line.errors.length > 0) {
push(leftPad(line.number, 4) + '| ', 'background-color:yellow; font-weight:bold')
push(line.line + endl, 'color:red; background-color:yellow; font-weight:bold')
// try to guess token
var offset = 0
line.errors.forEach(function (error) {
var message = error.message
var token = /^\s*'(.*)'\s*:\s*(.*)$/.exec(message)
if (token) {
var tokenPat = token[1]
message = token[2]
switch (tokenPat) {
case 'assign':
tokenPat = '='
break
}
offset = Math.max(line.line.indexOf(tokenPat, offset), 0)
} else {
offset = 0
}
push(leftPad('| ', 6))
push(leftPad('^^^', offset + 3) + endl, 'font-weight:bold')
push(leftPad('| ', 6))
push(message + endl, 'font-weight:bold')
})
push(leftPad('| ', 6) + endl)
} else {
push(leftPad(line.number, 4) + '| ')
push(line.line + endl, 'color:red')
}
})
if (typeof document !== 'undefined' && !window.chrome) {
styles[0] = strings.join('%c')
console.log.apply(console, styles)
} else {
console.log(strings.join(''))
}
})
check.raise('Error compiling ' + typeName + ' shader, ' + files[0].name)
}
}
function checkLinkError (gl, program, fragShader, vertShader, command) {
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
var errLog = gl.getProgramInfoLog(program)
var fragParse = parseSource(fragShader, command)
var vertParse = parseSource(vertShader, command)
var header = 'Error linking program with vertex shader, "' +
vertParse[0].name + '", and fragment shader "' + fragParse[0].name + '"'
if (typeof document !== 'undefined') {
console.log('%c' + header + endl + '%c' + errLog,
'color:red;text-decoration:underline;font-weight:bold',
'color:red')
} else {
console.log(header + endl + errLog)
}
check.raise(header)
}
}
function saveCommandRef (object) {
object._commandRef = guessCommand()
}
function saveDrawCommandInfo (opts, uniforms, attributes, stringStore) {
saveCommandRef(opts)
function id (str) {
if (str) {
return stringStore.id(str)
}
return 0
}
opts._fragId = id(opts.static.frag)
opts._vertId = id(opts.static.vert)
function addProps (dict, set) {
Object.keys(set).forEach(function (u) {
dict[stringStore.id(u)] = true
})
}
var uniformSet = opts._uniformSet = {}
addProps(uniformSet, uniforms.static)
addProps(uniformSet, uniforms.dynamic)
var attributeSet = opts._attributeSet = {}
addProps(attributeSet, attributes.static)
addProps(attributeSet, attributes.dynamic)
opts._hasCount = (
'count' in opts.static ||
'count' in opts.dynamic ||
'elements' in opts.static ||
'elements' in opts.dynamic)
}
function commandRaise (message, command) {
var callSite = guessCallSite()
raise(message +
' in command ' + (command || guessCommand()) +
(callSite === 'unknown' ? '' : ' called from ' + callSite))
}
function checkCommand (pred, message, command) {
if (!pred) {
commandRaise(message, command || guessCommand())
}
}
function checkParameterCommand (param, possibilities, message, command) {
if (!(param in possibilities)) {
commandRaise(
'unknown parameter (' + param + ')' + encolon(message) +
'. possible values: ' + Object.keys(possibilities).join(),
command || guessCommand())
}
}
function checkCommandType (value, type, message, command) {
if (!standardTypeEh(value, type)) {
commandRaise(
'invalid parameter type' + encolon(message) +
'. expected ' + type + ', got ' + (typeof value),
command || guessCommand())
}
}
function checkOptional (block) {
block()
}
function checkFramebufferFormat (attachment, texFormats, rbFormats) {
if (attachment.texture) {
checkOneOf(
attachment.texture._texture.internalformat,
texFormats,
'unsupported texture format for attachment')
} else {
checkOneOf(
attachment.renderbuffer._renderbuffer.format,
rbFormats,
'unsupported renderbuffer format for attachment')
}
}
var GL_CLAMP_TO_EDGE = 0x812F
var GL_NEAREST = 0x2600
var GL_NEAREST_MIPMAP_NEAREST = 0x2700
var GL_LINEAR_MIPMAP_NEAREST = 0x2701
var GL_NEAREST_MIPMAP_LINEAR = 0x2702
var GL_LINEAR_MIPMAP_LINEAR = 0x2703
var GL_BYTE = 5120
var GL_UNSIGNED_BYTE = 5121
var GL_SHORT = 5122
var GL_UNSIGNED_SHORT = 5123
var GL_INT = 5124
var GL_UNSIGNED_INT = 5125
var GL_FLOAT = 5126
var GL_UNSIGNED_SHORT_4_4_4_4 = 0x8033
var GL_UNSIGNED_SHORT_5_5_5_1 = 0x8034
var GL_UNSIGNED_SHORT_5_6_5 = 0x8363
var GL_UNSIGNED_INT_24_8_WEBGL = 0x84FA
var GL_HALF_FLOAT_OES = 0x8D61
var TYPE_SIZE = {}
TYPE_SIZE[GL_BYTE] =
TYPE_SIZE[GL_UNSIGNED_BYTE] = 1
TYPE_SIZE[GL_SHORT] =
TYPE_SIZE[GL_UNSIGNED_SHORT] =
TYPE_SIZE[GL_HALF_FLOAT_OES] =
TYPE_SIZE[GL_UNSIGNED_SHORT_5_6_5] =
TYPE_SIZE[GL_UNSIGNED_SHORT_4_4_4_4] =
TYPE_SIZE[GL_UNSIGNED_SHORT_5_5_5_1] = 2
TYPE_SIZE[GL_INT] =
TYPE_SIZE[GL_UNSIGNED_INT] =
TYPE_SIZE[GL_FLOAT] =
TYPE_SIZE[GL_UNSIGNED_INT_24_8_WEBGL] = 4
function pixelSize (type, channels) {
if (type === GL_UNSIGNED_SHORT_5_5_5_1 ||
type === GL_UNSIGNED_SHORT_4_4_4_4 ||
type === GL_UNSIGNED_SHORT_5_6_5) {
return 2
} else if (type === GL_UNSIGNED_INT_24_8_WEBGL) {
return 4
} else {
return TYPE_SIZE[type] * channels
}
}
function isPow2 (v) {
return !(v & (v - 1)) && (!!v)
}
function checkTexture2D (info, mipData, limits) {
var i
var w = mipData.width
var h = mipData.height
var c = mipData.channels
// Check texture shape
check(w > 0 && w <= limits.maxTextureSize &&
h > 0 && h <= limits.maxTextureSize,
'invalid texture shape')
// check wrap mode
if (info.wrapS !== GL_CLAMP_TO_EDGE || info.wrapT !== GL_CLAMP_TO_EDGE) {
check(isPow2(w) && isPow2(h),
'incompatible wrap mode for texture, both width and height must be power of 2')
}
if (mipData.mipmask === 1) {
if (w !== 1 && h !== 1) {
check(
info.minFilter !== GL_NEAREST_MIPMAP_NEAREST &&
info.minFilter !== GL_NEAREST_MIPMAP_LINEAR &&
info.minFilter !== GL_LINEAR_MIPMAP_NEAREST &&
info.minFilter !== GL_LINEAR_MIPMAP_LINEAR,
'min filter requires mipmap')
}
} else {
// texture must be power of 2
check(isPow2(w) && isPow2(h),
'texture must be a square power of 2 to support mipmapping')
check(mipData.mipmask === (w << 1) - 1,
'missing or incomplete mipmap data')
}
if (mipData.type === GL_FLOAT) {
if (limits.extensions.indexOf('oes_texture_float_linear') < 0) {
check(info.minFilter === GL_NEAREST && info.magFilter === GL_NEAREST,
'filter not supported, must enable oes_texture_float_linear')
}
check(!info.genMipmaps,
'mipmap generation not supported with float textures')
}
// check image complete
var mipimages = mipData.images
for (i = 0; i < 16; ++i) {
if (mipimages[i]) {
var mw = w >> i
var mh = h >> i
check(mipData.mipmask & (1 << i), 'missing mipmap data')
var img = mipimages[i]
check(
img.width === mw &&
img.height === mh,
'invalid shape for mip images')
check(
img.format === mipData.format &&
img.internalformat === mipData.internalformat &&
img.type === mipData.type,
'incompatible type for mip image')
if (img.compressed) {
// TODO: check size for compressed images
} else if (img.data) {
// check(img.data.byteLength === mw * mh *
// Math.max(pixelSize(img.type, c), img.unpackAlignment),
var rowSize = Math.ceil(pixelSize(img.type, c) * mw / img.unpackAlignment) * img.unpackAlignment
check(img.data.byteLength === rowSize * mh,
'invalid data for image, buffer size is inconsistent with image format')
} else if (img.element) {
// TODO: check element can be loaded
} else if (img.copy) {
// TODO: check compatible format and type
}
} else if (!info.genMipmaps) {
check((mipData.mipmask & (1 << i)) === 0, 'extra mipmap data')
}
}
if (mipData.compressed) {
check(!info.genMipmaps,
'mipmap generation for compressed images not supported')
}
}
function checkTextureCube (texture, info, faces, limits) {
var w = texture.width
var h = texture.height
var c = texture.channels
// Check texture shape
check(
w > 0 && w <= limits.maxTextureSize && h > 0 && h <= limits.maxTextureSize,
'invalid texture shape')
check(
w === h,
'cube map must be square')
check(
info.wrapS === GL_CLAMP_TO_EDGE && info.wrapT === GL_CLAMP_TO_EDGE,
'wrap mode not supported by cube map')
for (var i = 0; i < faces.length; ++i) {
var face = faces[i]
check(
face.width === w && face.height === h,
'inconsistent cube map face shape')
if (info.genMipmaps) {
check(!face.compressed,
'can not generate mipmap for compressed textures')
check(face.mipmask === 1,
'can not specify mipmaps and generate mipmaps')
} else {
// TODO: check mip and filter mode
}
var mipmaps = face.images
for (var j = 0; j < 16; ++j) {
var img = mipmaps[j]
if (img) {
var mw = w >> j
var mh = h >> j
check(face.mipmask & (1 << j), 'missing mipmap data')
check(
img.width === mw &&
img.height === mh,
'invalid shape for mip images')
check(
img.format === texture.format &&
img.internalformat === texture.internalformat &&
img.type === texture.type,
'incompatible type for mip image')
if (img.compressed) {
// TODO: check size for compressed images
} else if (img.data) {
check(img.data.byteLength === mw * mh *
Math.max(pixelSize(img.type, c), img.unpackAlignment),
'invalid data for image, buffer size is inconsistent with image format')
} else if (img.element) {
// TODO: check element can be loaded
} else if (img.copy) {
// TODO: check compatible format and type
}
}
}
}
}
var check$1 = extend(check, {
optional: checkOptional,
raise: raise,
commandRaise: commandRaise,
command: checkCommand,
parameter: checkParameter,
commandParameter: checkParameterCommand,
constructor: checkConstructor,
type: checkTypeOf,
commandType: checkCommandType,
isTypedArray: checkIsTypedArray,
nni: checkNonNegativeInt,
oneOf: checkOneOf,
shaderError: checkShaderError,
linkError: checkLinkError,
callSite: guessCallSite,
saveCommandRef: saveCommandRef,
saveDrawInfo: saveDrawCommandInfo,
framebufferFormat: checkFramebufferFormat,
guessCommand: guessCommand,
texture2D: checkTexture2D,
textureCube: checkTextureCube
});
var VARIABLE_COUNTER = 0
var DYN_FUNC = 0
function DynamicVariable (type, data) {
this.id = (VARIABLE_COUNTER++)
this.type = type
this.data = data
}
function escapeStr (str) {
return str.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
}
function splitParts (str) {
if (str.length === 0) {
return []
}
var firstChar = str.charAt(0)
var lastChar = str.charAt(str.length - 1)
if (str.length > 1 &&
firstChar === lastChar &&
(firstChar === '"' || firstChar === "'")) {
return ['"' + escapeStr(str.substr(1, str.length - 2)) + '"']
}
var parts = /\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(str)
if (parts) {
return (
splitParts(str.substr(0, parts.index))
.concat(splitParts(parts[1]))
.concat(splitParts(str.substr(parts.index + parts[0].length)))
)
}
var subparts = str.split('.')
if (subparts.length === 1) {
return ['"' + escapeStr(str) + '"']
}
var result = []
for (var i = 0; i < subparts.length; ++i) {
result = result.concat(splitParts(subparts[i]))
}
return result
}
function toAccessorString (str) {
return '[' + splitParts(str).join('][') + ']'
}
function defineDynamic (type, data) {
return new DynamicVariable(type, toAccessorString(data + ''))
}
function isDynamic (x) {
return (typeof x === 'function' && !x._reglType) ||
x instanceof DynamicVariable
}
function unbox (x, path) {
if (typeof x === 'function') {
return new DynamicVariable(DYN_FUNC, x)
}
return x
}
var dynamic = {
DynamicVariable: DynamicVariable,
define: defineDynamic,
isDynamic: isDynamic,
unbox: unbox,
accessor: toAccessorString
};
/* globals requestAnimationFrame, cancelAnimationFrame */
var raf = {
next: typeof requestAnimationFrame === 'function'
? function (cb) { return requestAnimationFrame(cb) }
: function (cb) { return setTimeout(cb, 16) },
cancel: typeof cancelAnimationFrame === 'function'
? function (raf) { return cancelAnimationFrame(raf) }
: clearTimeout
};
/* globals performance */
var clock = (typeof performance !== 'undefined' && performance.now)
? function () { return performance.now() }
: function () { return +(new Date()) };
function createStringStore () {
var stringIds = { '': 0 }
var stringValues = ['']
return {
id: function (str) {
var result = stringIds[str]
if (result) {
return result
}
result = stringIds[str] = stringValues.length
stringValues.push(str)
return result
},
str: function (id) {
return stringValues[id]
}
}
}
// Context and canvas creation helper functions
function createCanvas (element, onDone, pixelRatio) {
var canvas = document.createElement('canvas')
extend(canvas.style, {
border: 0,
margin: 0,
padding: 0,
top: 0,
left: 0
})
element.appendChild(canvas)
if (element === document.body) {
canvas.style.position = 'absolute'
extend(element.style, {
margin: 0,
padding: 0
})
}
function resize () {
var w = window.innerWidth
var h = window.innerHeight
if (element !== document.body) {
var bounds = element.getBoundingClientRect()
w = bounds.right - bounds.left
h = bounds.bottom - bounds.top
}
canvas.width = pixelRatio * w
canvas.height = pixelRatio * h
extend(canvas.style, {
width: w + 'px',
height: h + 'px'
})
}
var resizeObserver
if (element !== document.body && typeof ResizeObserver === 'function') {
// ignore 'ResizeObserver' is not defined
// eslint-disable-next-line
resizeObserver = new ResizeObserver(function () {
// setTimeout to avoid flicker
setTimeout(resize)
})
resizeObserver.observe(element)
} else {
window.addEventListener('resize', resize, false)
}
function onDestroy () {
if (resizeObserver) {
resizeObserver.disconnect()
} else {
window.removeEventListener('resize', resize)
}
element.removeChild(canvas)
}
resize()
return {
canvas: canvas,
onDestroy: onDestroy
}
}
function createContext (canvas, contextAttributes) {
function get (name) {
try {
return canvas.getContext(name, contextAttributes)
} catch (e) {
return null
}
}
return (
get('webgl') ||
get('experimental-webgl') ||
get('webgl-experimental')
)
}
function isHTMLElement (obj) {
return (
typeof obj.nodeName === 'string' &&
typeof obj.appendChild === 'function' &&
typeof obj.getBoundingClientRect === 'function'
)
}
function isWebGLContext (obj) {
return (
typeof obj.drawArrays === 'function' ||
typeof obj.drawElements === 'function'
)
}
function parseExtensions (input) {
if (typeof input === 'string') {
return input.split()
}
check$1(Array.isArray(input), 'invalid extension array')
return input
}
function getElement (desc) {
if (typeof desc === 'string') {
check$1(typeof document !== 'undefined', 'not supported outside of DOM')
return document.querySelector(desc)
}
return desc
}
function parseArgs (args_) {
var args = args_ || {}
var element, container, canvas, gl
var contextAttributes = {}
var extensions = []
var optionalExtensions = []
var pixelRatio = (typeof window === 'undefined' ? 1 : window.devicePixelRatio)
var profile = false
var onDone = function (err) {
if (err) {
check$1.raise(err)
}
}
var onDestroy = function () {}
if (typeof args === 'string') {
check$1(
typeof document !== 'undefined',
'selector queries only supported in DOM enviroments')
element = document.querySelector(args)
check$1(element, 'invalid query string for element')
} else if (typeof args === 'object') {
if (isHTMLElement(args)) {
element = args
} else if (isWebGLContext(args)) {
gl = args
canvas = gl.canvas
} else {
check$1.constructor(args)
if ('gl' in args) {
gl = args.gl
} else if ('canvas' in args) {
canvas = getElement(args.canvas)
} else if ('container' in args) {
container = getElement(args.container)
}
if ('attributes' in args) {
contextAttributes = args.attributes
check$1.type(contextAttributes, 'object', 'invalid context attributes')
}
if ('extensions' in args) {
extensions = parseExtensions(args.extensions)
}
if ('optionalExtensions' in args) {
optionalExtensions = parseExtensions(args.optionalExtensions)
}
if ('onDone' in args) {
check$1.type(
args.onDone, 'function',
'invalid or missing onDone callback')
onDone = args.onDone
}
if ('profile' in args) {
profile = !!args.profile
}
if ('pixelRatio' in args) {
pixelRatio = +args.pixelRatio
check$1(pixelRatio > 0, 'invalid pixel ratio')
}
}
} else {
check$1.raise('invalid arguments to regl')
}
if (element) {
if (element.nodeName.toLowerCase() === 'canvas') {
canvas = element
} else {
container = element
}
}
if (!gl) {
if (!canvas) {
check$1(
typeof document !== 'undefined',
'must manually specify webgl context outside of DOM environments')
var result = createCanvas(container || document.body, onDone, pixelRatio)
if (!result) {
return null
}
canvas = result.canvas
onDestroy = result.onDestroy
}
// workaround for chromium bug, premultiplied alpha value is platform dependent
contextAttributes.premultipliedAlpha = contextAttributes.premultipliedAlpha || true
gl = createContext(canvas, contextAttributes)
}
if (!gl) {
onDestroy()
onDone('webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org')
return null
}
return {
gl: gl,
canvas: canvas,
container: container,
extensions: extensions,
optionalExtensions: optionalExtensions,
pixelRatio: pixelRatio,
profile: profile,
onDone: onDone,
onDestroy: onDestroy
}
}
function createExtensionCache (gl, config) {
var extensions = {}
function tryLoadExtension (name_) {
check$1.type(name_, 'string', 'extension name must be string')
var name = name_.toLowerCase()
var ext
try {
ext = extensions[name] = gl.getExtension(name)
} catch (e) {}
return !!ext
}
for (var i = 0; i < config.extensions.length; ++i) {
var name = config.extensions[i]
if (!tryLoadExtension(name)) {
config.onDestroy()
config.onDone('"' + name + '" extension is not supported by the current WebGL context, try upgrading your system or a different browser')
return null
}
}
config.optionalExtensions.forEach(tryLoadExtension)
return {
extensions: extensions,
restore: function () {
Object.keys(extensions).forEach(function (name) {
if (extensions[name] && !tryLoadExtension(name)) {
throw new Error('(regl): error restoring extension ' + name)
}
})
}
}
}
function loop (n, f) {
var result = Array(n)
for (var i = 0; i < n; ++i) {
result[i] = f(i)
}
return result
}
var GL_BYTE$1 = 5120
var GL_UNSIGNED_BYTE$2 = 5121
var GL_SHORT$1 = 5122
var GL_UNSIGNED_SHORT$1 = 5123
var GL_INT$1 = 5124
var GL_UNSIGNED_INT$1 = 5125
var GL_FLOAT$2 = 5126
function nextPow16 (v) {
for (var i = 16; i <= (1 << 28); i *= 16) {
if (v <= i) {
return i
}
}
return 0
}
function log2 (v) {
var r, shift
r = (v > 0xFFFF) << 4
v >>>= r
shift = (v > 0xFF) << 3
v >>>= shift; r |= shift
shift = (v > 0xF) << 2
v >>>= shift; r |= shift
shift = (v > 0x3) << 1
v >>>= shift; r |= shift
return r | (v >> 1)
}
function createPool () {
var bufferPool = loop(8, function () {
return []
})
function alloc (n) {
var sz = nextPow16(n)
var bin = bufferPool[log2(sz) >> 2]
if (bin.length > 0) {
return bin.pop()
}
return new ArrayBuffer(sz)
}
function free (buf) {
bufferPool[log2(buf.byteLength) >> 2].push(buf)
}
function allocType (type, n) {
var result = null
switch (type) {
case GL_BYTE$1:
result = new Int8Array(alloc(n), 0, n)
break
case GL_UNSIGNED_BYTE$2:
result = new Uint8Array(alloc(n), 0, n)
break
case GL_SHORT$1:
result = new Int16Array(alloc(2 * n), 0, n)
break
case GL_UNSIGNED_SHORT$1:
result = new Uint16Array(alloc(2 * n), 0, n)
break
case GL_INT$1:
result = new Int32Array(alloc(4 * n), 0, n)
break
case GL_UNSIGNED_INT$1:
result = new Uint32Array(alloc(4 * n), 0, n)
break
case GL_FLOAT$2:
result = new Float32Array(alloc(4 * n), 0, n)
break
default:
return null
}
if (result.length !== n) {
return result.subarray(0, n)
}
return result
}
function freeType (array) {
free(array.buffer)
}
return {
alloc: alloc,
free: free,
allocType: allocType,
freeType: freeType
}
}
var pool = createPool()
// zero pool for initial zero data
pool.zero = createPool()
var GL_SUBPIXEL_BITS = 0x0D50
var GL_RED_BITS = 0x0D52
var GL_GREEN_BITS = 0x0D53
var GL_BLUE_BITS = 0x0D54
var GL_ALPHA_BITS = 0x0D55
var GL_DEPTH_BITS = 0x0D56
var GL_STENCIL_BITS = 0x0D57
var GL_ALIASED_POINT_SIZE_RANGE = 0x846D
var GL_ALIASED_LINE_WIDTH_RANGE = 0x846E
var GL_MAX_TEXTURE_SIZE = 0x0D33
var GL_MAX_VIEWPORT_DIMS = 0x0D3A
var GL_MAX_VERTEX_ATTRIBS = 0x8869
var GL_MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB
var GL_MAX_VARYING_VECTORS = 0x8DFC
var GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D
var GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C
var GL_MAX_TEXTURE_IMAGE_UNITS = 0x8872
var GL_MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD
var GL_MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C
var GL_MAX_RENDERBUFFER_SIZE = 0x84E8
var GL_VENDOR = 0x1F00
var GL_RENDERER = 0x1F01
var GL_VERSION = 0x1F02
var GL_SHADING_LANGUAGE_VERSION = 0x8B8C
var GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FF
var GL_MAX_COLOR_ATTACHMENTS_WEBGL = 0x8CDF
var GL_MAX_DRAW_BUFFERS_WEBGL = 0x8824
var GL_TEXTURE_2D = 0x0DE1
var GL_TEXTURE_CUBE_MAP = 0x8513
var GL_TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515
var GL_TEXTURE0 = 0x84C0
var GL_RGBA = 0x1908
var GL_FLOAT$1 = 0x1406
var GL_UNSIGNED_BYTE$1 = 0x1401
var GL_FRAMEBUFFER = 0x8D40
var GL_FRAMEBUFFER_COMPLETE = 0x8CD5
var GL_COLOR_ATTACHMENT0 = 0x8CE0
var GL_COLOR_BUFFER_BIT$1 = 0x4000
var wrapLimits = function (gl, extensions) {
var maxAnisotropic = 1
if (extensions.ext_texture_filter_anisotropic) {
maxAnisotropic = gl.getParameter(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT)
}
var maxDrawbuffers = 1
var maxColorAttachments = 1
if (extensions.webgl_draw_buffers) {
maxDrawbuffers = gl.getParameter(GL_MAX_DRAW_BUFFERS_WEBGL)
maxColorAttachments = gl.getParameter(GL_MAX_COLOR_ATTACHMENTS_WEBGL)
}
// detect if reading float textures is available (Safari doesn't support)
var readFloat = !!extensions.oes_texture_float
if (readFloat) {
var readFloatTexture = gl.createTexture()
gl.bindTexture(GL_TEXTURE_2D, readFloatTexture)
gl.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_FLOAT$1, null)
var fbo = gl.createFramebuffer()
gl.bindFramebuffer(GL_FRAMEBUFFER, fbo)
gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, readFloatTexture, 0)
gl.bindTexture(GL_TEXTURE_2D, null)
if (gl.checkFramebufferStatus(GL_FRAMEBUFFER) !== GL_FRAMEBUFFER_COMPLETE) readFloat = false
else {
gl.viewport(0, 0, 1, 1)
gl.clearColor(1.0, 0.0, 0.0, 1.0)
gl.clear(GL_COLOR_BUFFER_BIT$1)
var pixels = pool.allocType(GL_FLOAT$1, 4)
gl.readPixels(0, 0, 1, 1, GL_RGBA, GL_FLOAT$1, pixels)
if (gl.getError()) readFloat = false
else {
gl.deleteFramebuffer(fbo)
gl.deleteTexture(readFloatTexture)
readFloat = pixels[0] === 1.0
}
pool.freeType(pixels)
}
}
// detect non power of two cube textures support (IE doesn't support)
var isIE = typeof navigator !== 'undefined' && (/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion) || /Edge/.test(navigator.userAgent))
var npotTextureCube = true
if (!isIE) {
var cubeTexture = gl.createTexture()
var data = pool.allocType(GL_UNSIGNED_BYTE$1, 36)
gl.activeTexture(GL_TEXTURE0)
gl.bindTexture(GL_TEXTURE_CUBE_MAP, cubeTexture)
gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA, 3, 3, 0, GL_RGBA, GL_UNSIGNED_BYTE$1, data)
pool.freeType(data)
gl.bindTexture(GL_TEXTURE_CUBE_MAP, null)
gl.deleteTexture(cubeTexture)
npotTextureCube = !gl.getError()
}
return {
// drawing buffer bit depth
colorBits: [
gl.getParameter(GL_RED_BITS),
gl.getParameter(GL_GREEN_BITS),
gl.getParameter(GL_BLUE_BITS),
gl.getParameter(GL_ALPHA_BITS)
],
depthBits: gl.getParameter(GL_DEPTH_BITS),
stencilBits: gl.getParameter(GL_STENCIL_BITS),
subpixelBits: gl.getParameter(GL_SUBPIXEL_BITS),
// supported extensions
extensions: Object.keys(extensions).filter(function (ext) {
return !!extensions[ext]
}),
// max aniso samples
maxAnisotropic: maxAnisotropic,
// max draw buffers
maxDrawbuffers: maxDrawbuffers,
maxColorAttachments: maxColorAttachments,
// point and line size ranges
pointSizeDims: gl.getParameter(GL_ALIASED_POINT_SIZE_RANGE),
lineWidthDims: gl.getParameter(GL_ALIASED_LINE_WIDTH_RANGE),
maxViewportDims: gl.getParameter(GL_MAX_VIEWPORT_DIMS),
maxCombinedTextureUnits: gl.getParameter(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS),
maxCubeMapSize: gl.getParameter(GL_MAX_CUBE_MAP_TEXTURE_SIZE),
maxRenderbufferSize: gl.getParameter(GL_MAX_RENDERBUFFER_SIZE),
maxTextureUnits: gl.getParameter(GL_MAX_TEXTURE_IMAGE_UNITS),
maxTextureSize: gl.getParameter(GL_MAX_TEXTURE_SIZE),
maxAttributes: gl.getParameter(GL_MAX_VERTEX_ATTRIBS),
maxVertexUniforms: gl.getParameter(GL_MAX_VERTEX_UNIFORM_VECTORS),
maxVertexTextureUnits: gl.getParameter(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS),
maxVaryingVectors: gl.getParameter(GL_MAX_VARYING_VECTORS),
maxFragmentUniforms: gl.getParameter(GL_MAX_FRAGMENT_UNIFORM_VECTORS),
// vendor info
glsl: gl.getParameter(GL_SHADING_LANGUAGE_VERSION),
renderer: gl.getParameter(GL_RENDERER),
vendor: gl.getParameter(GL_VENDOR),
version: gl.getParameter(GL_VERSION),
// quirks
readFloat: readFloat,
npotTextureCube: npotTextureCube
}
}
function isNDArrayLike (obj) {
return (
!!obj &&
typeof obj === 'object' &&
Array.isArray(obj.shape) &&
Array.isArray(obj.stride) &&
typeof obj.offset === 'number' &&
obj.shape.length === obj.stride.length &&
(Array.isArray(obj.data) ||
isTypedArray(obj.data)))
}
var values = function (obj) {
return Object.keys(obj).map(function (key) { return obj[key] })
}
var flattenUtils = {
shape: arrayShape$1,
flatten: flattenArray
};
function flatten1D (array, nx, out) {
for (var i = 0; i < nx; ++i) {
out[i] = array[i]
}
}
function flatten2D (array, nx, ny, out) {
var ptr = 0
for (var i = 0; i < nx; ++i) {
var row = array[i]
for (var j = 0; j < ny; ++j) {
out[ptr++] = row[j]
}
}
}
function flatten3D (array, nx, ny, nz, out, ptr_) {
var ptr = ptr_
for (var i = 0; i < nx; ++i) {
var row = array[i]
for (var j = 0; j < ny; ++j) {
var col = row[j]
for (var k = 0; k < nz; ++k) {
out[ptr++] = col[k]
}
}
}
}
function flattenRec (array, shape, level, out, ptr) {
var stride = 1
for (var i = level + 1; i < shape.length; ++i) {
stride *= shape[i]
}
var n = shape[level]
if (shape.length - level === 4) {
var nx = shape[level + 1]
var ny = shape[level + 2]
var nz = shape[level + 3]
for (i = 0; i < n; ++i) {
flatten3D(array[i], nx, ny, nz, out, ptr)
ptr += stride
}
} else {
for (i = 0; i < n; ++i) {
flattenRec(array[i], shape, level + 1, out, ptr)
ptr += stride
}
}
}
function flattenArray (array, shape, type, out_) {
var sz = 1
if (shape.length) {
for (var i = 0; i < shape.length; ++i) {
sz *= shape[i]
}
} else {
sz = 0
}
var out = out_ || pool.allocType(type, sz)
switch (shape.length) {
case 0:
break
case 1:
flatten1D(array, shape[0], out)
break
case 2:
flatten2D(array, shape[0], shape[1], out)
break
case 3:
flatten3D(array, shape[0], shape[1], shape[2], out, 0)
break
default:
flattenRec(array, shape, 0, out, 0)
}
return out
}
function arrayShape$1 (array_) {
var shape = []
for (var array = array_; array.length; array = array[0]) {
shape.push(array.length)
}
return shape
}
var arrayTypes = {
"[object Int8Array]": 5120,
"[object Int16Array]": 5122,
"[object Int32Array]": 5124,
"[object Uint8Array]": 5121,
"[object Uint8ClampedArray]": 5121,
"[object Uint16Array]": 5123,
"[object Uint32Array]": 5125,
"[object Float32Array]": 5126,
"[object Float64Array]": 5121,
"[object ArrayBuffer]": 5121
};
var int8 = 5120;
var int16 = 5122;
var int32 = 5124;
var uint8 = 5121;
var uint16 = 5123;
var uint32 = 5125;
var float = 5126;
var float32 = 5126;
var glTypes = {
int8: int8,
int16: int16,
int32: int32,
uint8: uint8,
uint16: uint16,
uint32: uint32,
float: float,
float32: float32
};
var dynamic$1 = 35048;
var stream = 35040;
var usageTypes = {
dynamic: dynamic$1,
stream: stream,
"static": 35044
};
var arrayFlatten = flattenUtils.flatten
var arrayShape = flattenUtils.shape
var GL_STATIC_DRAW = 0x88E4
var GL_STREAM_DRAW = 0x88E0
var GL_UNSIGNED_BYTE$3 = 5121
var GL_FLOAT$3 = 5126
var DTYPES_SIZES = []
DTYPES_SIZES[5120] = 1 // int8
DTYPES_SIZES[5122] = 2 // int16
DTYPES_SIZES[5124] = 4 // int32
DTYPES_SIZES[5121] = 1 // uint8
DTYPES_SIZES[5123] = 2 // uint16
DTYPES_SIZES[5125] = 4 // uint32
DTYPES_SIZES[5126] = 4 // float32
function typedArrayCode (data) {
return arrayTypes[Object.prototype.toString.call(data)] | 0
}
function copyArray (out, inp) {
for (var i = 0; i < inp.length; ++i) {
out[i] = inp[i]
}
}
function transpose (
result, data, shapeX, shapeY, strideX, strideY, offset) {
var ptr = 0
for (var i = 0; i < shapeX; ++i) {
for (var j = 0; j < shapeY; ++j) {
result[ptr++] = data[strideX * i + strideY * j + offset]
}
}
}
function wrapBufferState (gl, stats, config, destroyBuffer) {
var bufferCount = 0
var bufferSet = {}
function REGLBuffer (type) {
this.id = bufferCount++
this.buffer = gl.createBuffer()
this.type = type
this.usage = GL_STATIC_DRAW
this.byteLength = 0
this.dimension = 1
this.dtype = GL_UNSIGNED_BYTE$3
this.persistentData = null
if (config.profile) {
this.stats = { size: 0 }
}
}
REGLBuffer.prototype.bind = function () {
gl.bindBuffer(this.type, this.buffer)
}
REGLBuffer.prototype.destroy = function () {
destroy(this)
}
var streamPool = []
function createStream (type, data) {
var buffer = streamPool.pop()
if (!buffer) {
buffer = new REGLBuffer(type)
}
buffer.bind()
initBufferFromData(buffer, data, GL_STREAM_DRAW, 0, 1, false)
return buffer
}
function destroyStream (stream$$1) {
streamPool.push(stream$$1)
}
function initBufferFromTypedArray (buffer, data, usage) {
buffer.byteLength = data.byteLength
gl.bufferData(buffer.type, data, usage)
}
function initBufferFromData (buffer, data, usage, dtype, dimension, persist) {
var shape
buffer.usage = usage
if (Array.isArray(data)) {
buffer.dtype = dtype || GL_FLOAT$3
if (data.length > 0) {
var flatData
if (Array.isArray(data[0])) {
shape = arrayShape(data)
var dim = 1
for (var i = 1; i < shape.length; ++i) {
dim *= shape[i]
}
buffer.dimension = dim
flatData = arrayFlatten(data, shape, buffer.dtype)
initBufferFromTypedArray(buffer, flatData, usage)
if (persist) {
buffer.persistentData = flatData
} else {
pool.freeType(flatData)
}
} else if (typeof data[0] === 'number') {
buffer.dimension = dimension
var typedData = pool.allocType(buffer.dtype, data.length)
copyArray(typedData, data)
initBufferFromTypedArray(buffer, typedData, usage)
if (persist) {
buffer.persistentData = typedData
} else {
pool.freeType(typedData)
}
} else if (isTypedArray(data[0])) {
buffer.dimension = data[0].length
buffer.dtype = dtype || typedArrayCode(data[0]) || GL_FLOAT$3
flatData = arrayFlatten(
data,
[data.length, data[0].length],
buffer.dtype)
initBufferFromTypedArray(buffer, flatData, usage)
if (persist) {
buffer.persistentData = flatData
} else {
pool.freeType(flatData)
}
} else {
check$1.raise('invalid buffer data')
}
}
} else if (isTypedArray(data)) {
buffer.dtype = dtype || typedArrayCode(data)
buffer.dimension = dimension
initBufferFromTypedArray(buffer, data, usage)
if (persist) {
buffer.persistentData = new Uint8Array(new Uint8Array(data.buffer))
}
} else if (isNDArrayLike(data)) {
shape = data.shape
var stride = data.stride
var offset = data.offset
var shapeX = 0
var shapeY = 0
var strideX = 0
var strideY = 0
if (shape.length === 1) {
shapeX = shape[0]
shapeY = 1
strideX = stride[0]
strideY = 0
} else if (shape.length === 2) {
shapeX = shape[0]
shapeY = shape[1]
strideX = stride[0]
strideY = stride[1]
} else {
check$1.raise('invalid shape')
}
buffer.dtype = dtype || typedArrayCode(data.data) || GL_FLOAT$3
buffer.dimension = shapeY
var transposeData = pool.allocType(buffer.dtype, shapeX * shapeY)
transpose(transposeData,
data.data,
shapeX, shapeY,
strideX, strideY,
offset)
initBufferFromTypedArray(buffer, transposeData, usage)
if (persist) {
buffer.persistentData = transposeData
} else {
pool.freeType(transposeData)
}
} else if (data instanceof ArrayBuffer) {
buffer.dtype = GL_UNSIGNED_BYTE$3
buffer.dimension = dimension
initBufferFromTypedArray(buffer, data, usage)
if (persist) {
buffer.persistentData = new Uint8Array(new Uint8Array(data))
}
} else {
check$1.raise('invalid buffer data')
}
}
function destroy (buffer) {
stats.bufferCount--
// remove attribute link
destroyBuffer(buffer)
var handle = buffer.buffer
check$1(handle, 'buffer must not be deleted already')
gl.deleteBuffer(handle)
buffer.buffer = null
delete bufferSet[buffer.id]
}
function createBuffer (options, type, deferInit, persistent) {
stats.bufferCount++
var buffer = new REGLBuffer(type)
bufferSet[buffer.id] = buffer
function reglBuffer (options) {
var usage = GL_STATIC_DRAW
var data = null
var byteLength = 0
var dtype = 0
var dimension = 1
if (Array.isArray(options) ||
isTypedArray(options) ||
isNDArrayLike(options) ||
options instanceof ArrayBuffer) {
data = options
} else if (typeof options === 'number') {
byteLength = options | 0
} else if (options) {
check$1.type(
options, 'object',
'buffer arguments must be an object, a number or an array')
if ('data' in options) {
check$1(
data === null ||
Array.isArray(data) ||
isTypedArray(data) ||
isNDArrayLike(data),
'invalid data for buffer')
data = options.data
}
if ('usage' in options) {
check$1.parameter(options.usage, usageTypes, 'invalid buffer usage')
usage = usageTypes[options.usage]
}
if ('type' in options) {
check$1.parameter(options.type, glTypes, 'invalid buffer type')
dtype = glTypes[options.type]
}
if ('dimension' in options) {
check$1.type(options.dimension, 'number', 'invalid dimension')
dimension = options.dimension | 0
}
if ('length' in options) {
check$1.nni(byteLength, 'buffer length must be a nonnegative integer')
byteLength = options.length | 0
}
}
buffer.bind()
if (!data) {
// #475
if (byteLength) gl.bufferData(buffer.type, byteLength, usage)
buffer.dtype = dtype || GL_UNSIGNED_BYTE$3
buffer.usage = usage
buffer.dimension = dimension
buffer.byteLength = byteLength
} else {
initBufferFromData(buffer, data, usage, dtype, dimension, persistent)
}
if (config.profile) {
buffer.stats.size = buffer.byteLength * DTYPES_SIZES[buffer.dtype]
}
return reglBuffer
}
function setSubData (data, offset) {
check$1(offset + data.byteLength <= buffer.byteLength,
'invalid buffer subdata call, buffer is too small. ' + ' Can\'t write data of size ' + data.byteLength + ' starting from offset ' + offset + ' to a buffer of size ' + buffer.byteLength)
gl.bufferSubData(buffer.type, offset, data)
}
function subdata (data, offset_) {
var offset = (offset_ || 0) | 0
var shape
buffer.bind()
if (isTypedArray(data) || data instanceof ArrayBuffer) {
setSubData(data, offset)
} else if (Array.isArray(data)) {
if (data.length > 0) {
if (typeof data[0] === 'number') {
var converted = pool.allocType(buffer.dtype, data.length)
copyArray(converted, data)
setSubData(converted, offset)
pool.freeType(converted)
} else if (Array.isArray(data[0]) || isTypedArray(data[0])) {
shape = arrayShape(data)
var flatData = arrayFlatten(data, shape, buffer.dtype)
setSubData(flatData, offset)
pool.freeType(flatData)
} else {
check$1.raise('invalid buffer data')
}
}
} else if (isNDArrayLike(data)) {
shape = data.shape
var stride = data.stride
var shapeX = 0
var shapeY = 0
var strideX = 0
var strideY = 0
if (shape.length === 1) {
shapeX = shape[0]
shapeY = 1
strideX = stride[0]
strideY = 0
} else if (shape.length === 2) {
shapeX = shape[0]
shapeY = shape[1]
strideX = stride[0]
strideY = stride[1]
} else {
check$1.raise('invalid shape')
}
var dtype = Array.isArray(data.data)
? buffer.dtype
: typedArrayCode(data.data)
var transposeData = pool.allocType(dtype, shapeX * shapeY)
transpose(transposeData,
data.data,
shapeX, shapeY,
strideX, strideY,
data.offset)
setSubData(transposeData, offset)
pool.freeType(transposeData)
} else {
check$1.raise('invalid data for buffer subdata')
}
return reglBuffer
}
if (!deferInit) {
reglBuffer(options)
}
reglBuffer._reglType = 'buffer'
reglBuffer._buffer = buffer
reglBuffer.subdata = subdata
if (config.profile) {
reglBuffer.stats = buffer.stats
}
reglBuffer.destroy = function () { destroy(buffer) }
return reglBuffer
}
function restoreBuffers () {
values(bufferSet).forEach(function (buffer) {
buffer.buffer = gl.createBuffer()
gl.bindBuffer(buffer.type, buffer.buffer)
gl.bufferData(
buffer.type, buffer.persistentData || buffer.byteLength, buffer.usage)
})
}
if (config.profile) {
stats.getTotalBufferSize = function () {
var total = 0
// TODO: Right now, the streams are not part of the total count.
Object.keys(bufferSet).forEach(function (key) {
total += bufferSet[key].stats.size
})
return total
}
}
return {
create: createBuffer,
createStream: createStream,
destroyStream: destroyStream,
clear: function () {
values(bufferSet).forEach(destroy)
streamPool.forEach(destroy)
},
getBuffer: function (wrapper) {
if (wrapper && wrapper._buffer instanceof REGLBuffer) {
return wrapper._buffer
}
return null
},
restore: restoreBuffers,
_initBuffer: initBufferFromData
}
}
var points = 0;
var point = 0;
var lines = 1;
var line = 1;
var triangles = 4;
var triangle = 4;
var primTypes = {
points: points,
point: point,
lines: lines,
line: line,
triangles: triangles,
triangle: triangle,
"line loop": 2,
"line strip": 3,
"triangle strip": 5,
"triangle fan": 6
};
var GL_POINTS = 0
var GL_LINES = 1
var GL_TRIANGLES = 4
var GL_BYTE$2 = 5120
var GL_UNSIGNED_BYTE$4 = 5121
var GL_SHORT$2 = 5122
var GL_UNSIGNED_SHORT$2 = 5123
var GL_INT$2 = 5124
var GL_UNSIGNED_INT$2 = 5125
var GL_ELEMENT_ARRAY_BUFFER = 34963
var GL_STREAM_DRAW$1 = 0x88E0
var GL_STATIC_DRAW$1 = 0x88E4
function wrapElementsState (gl, extensions, bufferState, stats) {
var elementSet = {}
var elementCount = 0
var elementTypes = {
'uint8': GL_UNSIGNED_BYTE$4,
'uint16': GL_UNSIGNED_SHORT$2
}
if (extensions.oes_element_index_uint) {
elementTypes.uint32 = GL_UNSIGNED_INT$2
}
function REGLElementBuffer (buffer) {
this.id = elementCount++
elementSet[this.id] = this
this.buffer = buffer
this.primType = GL_TRIANGLES
this.vertCount = 0
this.type = 0
}
REGLElementBuffer.prototype.bind = function () {
this.buffer.bind()
}
var bufferPool = []
function createElementStream (data) {
var result = bufferPool.pop()
if (!result) {
result = new REGLElementBuffer(bufferState.create(
null,
GL_ELEMENT_ARRAY_BUFFER,
true,
false)._buffer)
}
initElements(result, data, GL_STREAM_DRAW$1, -1, -1, 0, 0)
return result
}
function destroyElementStream (elements) {
bufferPool.push(elements)
}
function initElements (
elements,
data,
usage,
prim,
count,
byteLength,
type) {
elements.buffer.bind()
var dtype
if (data) {
var predictedType = type
if (!type && (
!isTypedArray(data) ||
(isNDArrayLike(data) && !isTypedArray(data.data)))) {
predictedType = extensions.oes_element_index_uint
? GL_UNSIGNED_INT$2
: GL_UNSIGNED_SHORT$2
}
bufferState._initBuffer(
elements.buffer,
data,
usage,
predictedType,
3)
} else {
gl.bufferData(GL_ELEMENT_ARRAY_BUFFER, byteLength, usage)
elements.buffer.dtype = dtype || GL_UNSIGNED_BYTE$4
elements.buffer.usage = usage
elements.buffer.dimension = 3
elements.buffer.byteLength = byteLength
}
dtype = type
if (!type) {
switch (elements.buffer.dtype) {
case GL_UNSIGNED_BYTE$4:
case GL_BYTE$2:
dtype = GL_UNSIGNED_BYTE$4
break
case GL_UNSIGNED_SHORT$2:
case GL_SHORT$2:
dtype = GL_UNSIGNED_SHORT$2
break
case GL_UNSIGNED_INT$2:
case GL_INT$2:
dtype = GL_UNSIGNED_INT$2
break
default:
check$1.raise('unsupported type for element array')
}
elements.buffer.dtype = dtype
}
elements.type = dtype
// Check oes_element_index_uint extension
check$1(
dtype !== GL_UNSIGNED_INT$2 ||
!!extensions.oes_element_index_uint,
'32 bit element buffers not supported, enable oes_element_index_uint first')
// try to guess default primitive type and arguments
var vertCount = count
if (vertCount < 0) {
vertCount = elements.buffer.byteLength
if (dtype === GL_UNSIGNED_SHORT$2) {
vertCount >>= 1
} else if (dtype === GL_UNSIGNED_INT$2) {
vertCount >>= 2
}
}
elements.vertCount = vertCount
// try to guess primitive type from cell dimension
var primType = prim
if (prim < 0) {
primType = GL_TRIANGLES
var dimension = elements.buffer.dimension
if (dimension === 1) primType = GL_POINTS
if (dimension === 2) primType = GL_LINES
if (dimension === 3) primType = GL_TRIANGLES
}
elements.primType = primType
}
function destroyElements (elements) {
stats.elementsCount--
check$1(elements.buffer !== null, 'must not double destroy elements')
delete elementSet[elements.id]
elements.buffer.destroy()
elements.buffer = null
}
function createElements (options, persistent) {
var buffer = bufferState.create(null, GL_ELEMENT_ARRAY_BUFFER, true)
var elements = new REGLElementBuffer(buffer._buffer)
stats.elementsCount++
function reglElements (options) {
if (!options) {
buffer()
elements.primType = GL_TRIANGLES
elements.vertCount = 0
elements.type = GL_UNSIGNED_BYTE$4
} else if (typeof options === 'number') {
buffer(options)
elements.primType = GL_TRIANGLES
elements.vertCount = options | 0
elements.type = GL_UNSIGNED_BYTE$4
} else {
var data = null
var usage = GL_STATIC_DRAW$1
var primType = -1
var vertCount = -1
var byteLength = 0
var dtype = 0
if (Array.isArray(options) ||
isTypedArray(options) ||
isNDArrayLike(options)) {
data = options
} else {
check$1.type(options, 'object', 'invalid arguments for elements')
if ('data' in options) {
data = options.data
check$1(
Array.isArray(data) ||
isTypedArray(data) ||
isNDArrayLike(data),
'invalid data for element buffer')
}
if ('usage' in options) {
check$1.parameter(
options.usage,
usageTypes,
'invalid element buffer usage')
usage = usageTypes[options.usage]
}
if ('primitive' in options) {
check$1.parameter(
options.primitive,
primTypes,
'invalid element buffer primitive')
primType = primTypes[options.primitive]
}
if ('count' in options) {
check$1(
typeof options.count === 'number' && options.count >= 0,
'invalid vertex count for elements')
vertCount = options.count | 0
}
if ('type' in options) {
check$1.parameter(
options.type,
elementTypes,
'invalid buffer type')
dtype = elementTypes[options.type]
}
if ('length' in options) {
byteLength = options.length | 0
} else {
byteLength = vertCount
if (dtype === GL_UNSIGNED_SHORT$2 || dtype === GL_SHORT$2) {
byteLength *= 2
} else if (dtype === GL_UNSIGNED_INT$2 || dtype === GL_INT$2) {
byteLength *= 4
}
}
}
initElements(
elements,
data,
usage,
primType,
vertCount,
byteLength,
dtype)
}
return reglElements
}
reglElements(options)
reglElements._reglType = 'elements'
reglElements._elements = elements
reglElements.subdata = function (data, offset) {
buffer.subdata(data, offset)
return reglElements
}
reglElements.destroy = function () {
destroyElements(elements)
}
return reglElements
}
return {
create: createElements,
createStream: createElementStream,
destroyStream: destroyElementStream,
getElements: function (elements) {
if (typeof elements === 'function' &&
elements._elements instanceof REGLElementBuffer) {
return elements._elements
}
return null
},
clear: function () {
values(elementSet).forEach(destroyElements)
}
}
}
var FLOAT = new Float32Array(1)
var INT = new Uint32Array(FLOAT.buffer)
var GL_UNSIGNED_SHORT$4 = 5123
function convertToHalfFloat (array) {
var ushorts = pool.allocType(GL_UNSIGNED_SHORT$4, array.length)
for (var i = 0; i < array.length; ++i) {
if (isNaN(array[i])) {
ushorts[i] = 0xffff
} else if (array[i] === Infinity) {
ushorts[i] = 0x7c00
} else if (array[i] === -Infinity) {
ushorts[i] = 0xfc00
} else {
FLOAT[0] = array[i]
var x = INT[0]
var sgn = (x >>> 31) << 15
var exp = ((x << 1) >>> 24) - 127
var frac = (x >> 13) & ((1 << 10) - 1)
if (exp < -24) {
// round non-representable denormals to 0
ushorts[i] = sgn
} else if (exp < -14) {
// handle denormals
var s = -14 - exp
ushorts[i] = sgn + ((frac + (1 << 10)) >> s)
} else if (exp > 15) {
// round overflow to +/- Infinity
ushorts[i] = sgn + 0x7c00
} else {
// otherwise convert directly
ushorts[i] = sgn + ((exp + 15) << 10) + frac
}
}
}
return ushorts
}
function isArrayLike (s) {
return Array.isArray(s) || isTypedArray(s)
}
var isPow2$1 = function (v) {
return !(v & (v - 1)) && (!!v)
}
var GL_COMPRESSED_TEXTURE_FORMATS = 0x86A3
var GL_TEXTURE_2D$1 = 0x0DE1
var GL_TEXTURE_CUBE_MAP$1 = 0x8513
var GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 = 0x8515
var GL_RGBA$1 = 0x1908
var GL_ALPHA = 0x1906
var GL_RGB = 0x1907
var GL_LUMINANCE = 0x1909
var GL_LUMINANCE_ALPHA = 0x190A
var GL_RGBA4 = 0x8056
var GL_RGB5_A1 = 0x8057
var GL_RGB565 = 0x8D62
var GL_UNSIGNED_SHORT_4_4_4_4$1 = 0x8033
var GL_UNSIGNED_SHORT_5_5_5_1$1 = 0x8034
var GL_UNSIGNED_SHORT_5_6_5$1 = 0x8363
var GL_UNSIGNED_INT_24_8_WEBGL$1 = 0x84FA
var GL_DEPTH_COMPONENT = 0x1902
var GL_DEPTH_STENCIL = 0x84F9
var GL_SRGB_EXT = 0x8C40
var GL_SRGB_ALPHA_EXT = 0x8C42
var GL_HALF_FLOAT_OES$1 = 0x8D61
var GL_COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0
var GL_COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1
var GL_COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2
var GL_COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3
var GL_COMPRESSED_RGB_ATC_WEBGL = 0x8C92
var GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL = 0x8C93
var GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL = 0x87EE
var GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00
var GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8C01
var GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8C02
var GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8C03
var GL_COMPRESSED_RGB_ETC1_WEBGL = 0x8D64
var GL_UNSIGNED_BYTE$5 = 0x1401
var GL_UNSIGNED_SHORT$3 = 0x1403
var GL_UNSIGNED_INT$3 = 0x1405
var GL_FLOAT$4 = 0x1406
var GL_TEXTURE_WRAP_S = 0x2802
var GL_TEXTURE_WRAP_T = 0x2803
var GL_REPEAT = 0x2901
var GL_CLAMP_TO_EDGE$1 = 0x812F
var GL_MIRRORED_REPEAT = 0x8370
var GL_TEXTURE_MAG_FILTER = 0x2800
var GL_TEXTURE_MIN_FILTER = 0x2801
var GL_NEAREST$1 = 0x2600
var GL_LINEAR = 0x2601
var GL_NEAREST_MIPMAP_NEAREST$1 = 0x2700
var GL_LINEAR_MIPMAP_NEAREST$1 = 0x2701
var GL_NEAREST_MIPMAP_LINEAR$1 = 0x2702
var GL_LINEAR_MIPMAP_LINEAR$1 = 0x2703
var GL_GENERATE_MIPMAP_HINT = 0x8192
var GL_DONT_CARE = 0x1100
var GL_FASTEST = 0x1101
var GL_NICEST = 0x1102
var GL_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE
var GL_UNPACK_ALIGNMENT = 0x0CF5
var GL_UNPACK_FLIP_Y_WEBGL = 0x9240
var GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241
var GL_UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243
var GL_BROWSER_DEFAULT_WEBGL = 0x9244
var GL_TEXTURE0$1 = 0x84C0
var MIPMAP_FILTERS = [
GL_NEAREST_MIPMAP_NEAREST$1,
GL_NEAREST_MIPMAP_LINEAR$1,
GL_LINEAR_MIPMAP_NEAREST$1,
GL_LINEAR_MIPMAP_LINEAR$1
]
var CHANNELS_FORMAT = [
0,
GL_LUMINANCE,
GL_LUMINANCE_ALPHA,
GL_RGB,
GL_RGBA$1
]
var FORMAT_CHANNELS = {}
FORMAT_CHANNELS[GL_LUMINANCE] =
FORMAT_CHANNELS[GL_ALPHA] =
FORMAT_CHANNELS[GL_DEPTH_COMPONENT] = 1
FORMAT_CHANNELS[GL_DEPTH_STENCIL] =
FORMAT_CHANNELS[GL_LUMINANCE_ALPHA] = 2
FORMAT_CHANNELS[GL_RGB] =
FORMAT_CHANNELS[GL_SRGB_EXT] = 3
FORMAT_CHANNELS[GL_RGBA$1] =
FORMAT_CHANNELS[GL_SRGB_ALPHA_EXT] = 4
function objectName (str) {
return '[object ' + str + ']'
}
var CANVAS_CLASS = objectName('HTMLCanvasElement')
var OFFSCREENCANVAS_CLASS = objectName('OffscreenCanvas')
var CONTEXT2D_CLASS = objectName('CanvasRenderingContext2D')
var BITMAP_CLASS = objectName('ImageBitmap')
var IMAGE_CLASS = objectName('HTMLImageElement')
var VIDEO_CLASS = objectName('HTMLVideoElement')
var PIXEL_CLASSES = Object.keys(arrayTypes).concat([
CANVAS_CLASS,
OFFSCREENCANVAS_CLASS,
CONTEXT2D_CLASS,
BITMAP_CLASS,
IMAGE_CLASS,
VIDEO_CLASS
])
// for every texture type, store
// the size in bytes.
var TYPE_SIZES = []
TYPE_SIZES[GL_UNSIGNED_BYTE$5] = 1
TYPE_SIZES[GL_FLOAT$4] = 4
TYPE_SIZES[GL_HALF_FLOAT_OES$1] = 2
TYPE_SIZES[GL_UNSIGNED_SHORT$3] = 2
TYPE_SIZES[GL_UNSIGNED_INT$3] = 4
var FORMAT_SIZES_SPECIAL = []
FORMAT_SIZES_SPECIAL[GL_RGBA4] = 2
FORMAT_SIZES_SPECIAL[GL_RGB5_A1] = 2
FORMAT_SIZES_SPECIAL[GL_RGB565] = 2
FORMAT_SIZES_SPECIAL[GL_DEPTH_STENCIL] = 4
FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_S3TC_DXT1_EXT] = 0.5
FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT1_EXT] = 0.5
FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT3_EXT] = 1
FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT5_EXT] = 1
FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_ATC_WEBGL] = 0.5
FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL] = 1
FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL] = 1
FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG] = 0.5
FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG] = 0.25
FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG] = 0.5
FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG] = 0.25
FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_ETC1_WEBGL] = 0.5
function isNumericArray (arr) {
return (
Array.isArray(arr) &&
(arr.length === 0 ||
typeof arr[0] === 'number'))
}
function isRectArray (arr) {
if (!Array.isArray(arr)) {
return false
}
var width = arr.length
if (width === 0 || !isArrayLike(arr[0])) {
return false
}
return true
}
function classString (x) {
return Object.prototype.toString.call(x)
}
function isCanvasElement (object) {
return classString(object) === CANVAS_CLASS
}
function isOffscreenCanvas (object) {
return classString(object) === OFFSCREENCANVAS_CLASS
}
function isContext2D (object) {
return classString(object) === CONTEXT2D_CLASS
}
function isBitmap (object) {
return classString(object) === BITMAP_CLASS
}
function isImageElement (object) {
return classString(object) === IMAGE_CLASS
}
function isVideoElement (object) {
return classString(object) === VIDEO_CLASS
}
function isPixelData (object) {
if (!object) {
return false
}
var className = classString(object)
if (PIXEL_CLASSES.indexOf(className) >= 0) {
return true
}
return (
isNumericArray(object) ||
isRectArray(object) ||
isNDArrayLike(object))
}
function typedArrayCode$1 (data) {
return arrayTypes[Object.prototype.toString.call(data)] | 0
}
function convertData (result, data) {
var n = data.length
switch (result.type) {
case GL_UNSIGNED_BYTE$5:
case GL_UNSIGNED_SHORT$3:
case GL_UNSIGNED_INT$3:
case GL_FLOAT$4:
var converted = pool.allocType(result.type, n)
converted.set(data)
result.data = converted
break
case GL_HALF_FLOAT_OES$1:
result.data = convertToHalfFloat(data)
break
default:
check$1.raise('unsupported texture type, must specify a typed array')
}
}
function preConvert (image, n) {
return pool.allocType(
image.type === GL_HALF_FLOAT_OES$1
? GL_FLOAT$4
: image.type, n)
}
function postConvert (image, data) {
if (image.type === GL_HALF_FLOAT_OES$1) {
image.data = convertToHalfFloat(data)
pool.freeType(data)
} else {
image.data = data
}
}
function transposeData (image, array, strideX, strideY, strideC, offset) {
var w = image.width
var h = image.height
var c = image.channels
var n = w * h * c
var data = preConvert(image, n)
var p = 0
for (var i = 0; i < h; ++i) {
for (var j = 0; j < w; ++j) {
for (var k = 0; k < c; ++k) {
data[p++] = array[strideX * j + strideY * i + strideC * k + offset]
}
}
}
postConvert(image, data)
}
function getTextureSize (format, type, width, height, isMipmap, isCube) {
var s
if (typeof FORMAT_SIZES_SPECIAL[format] !== 'undefined') {
// we have a special array for dealing with weird color formats such as RGB5A1
s = FORMAT_SIZES_SPECIAL[format]
} else {
s = FORMAT_CHANNELS[format] * TYPE_SIZES[type]
}
if (isCube) {
s *= 6
}
if (isMipmap) {
// compute the total size of all the mipmaps.
var total = 0
var w = width
while (w >= 1) {
// we can only use mipmaps on a square image,
// so we can simply use the width and ignore the height:
total += s * w * w
w /= 2
}
return total
} else {
return s * width * height
}
}
function createTextureSet (
gl, extensions, limits, reglPoll, contextState, stats, config) {
// -------------------------------------------------------
// Initialize constants and parameter tables here
// -------------------------------------------------------
var mipmapHint = {
"don't care": GL_DONT_CARE,
'dont care': GL_DONT_CARE,
'nice': GL_NICEST,
'fast': GL_FASTEST
}
var wrapModes = {
'repeat': GL_REPEAT,
'clamp': GL_CLAMP_TO_EDGE$1,
'mirror': GL_MIRRORED_REPEAT
}
var magFilters = {
'nearest': GL_NEAREST$1,
'linear': GL_LINEAR
}
var minFilters = extend({
'mipmap': GL_LINEAR_MIPMAP_LINEAR$1,
'nearest mipmap nearest': GL_NEAREST_MIPMAP_NEAREST$1,
'linear mipmap nearest': GL_LINEAR_MIPMAP_NEAREST$1,
'nearest mipmap linear': GL_NEAREST_MIPMAP_LINEAR$1,
'linear mipmap linear': GL_LINEAR_MIPMAP_LINEAR$1
}, magFilters)
var colorSpace = {
'none': 0,
'browser': GL_BROWSER_DEFAULT_WEBGL
}
var textureTypes = {
'uint8': GL_UNSIGNED_BYTE$5,
'rgba4': GL_UNSIGNED_SHORT_4_4_4_4$1,
'rgb565': GL_UNSIGNED_SHORT_5_6_5$1,
'rgb5 a1': GL_UNSIGNED_SHORT_5_5_5_1$1
}
var textureFormats = {
'alpha': GL_ALPHA,
'luminance': GL_LUMINANCE,
'luminance alpha': GL_LUMINANCE_ALPHA,
'rgb': GL_RGB,
'rgba': GL_RGBA$1,
'rgba4': GL_RGBA4,
'rgb5 a1': GL_RGB5_A1,
'rgb565': GL_RGB565
}
var compressedTextureFormats = {}
if (extensions.ext_srgb) {
textureFormats.srgb = GL_SRGB_EXT
textureFormats.srgba = GL_SRGB_ALPHA_EXT
}
if (extensions.oes_texture_float) {
textureTypes.float32 = textureTypes.float = GL_FLOAT$4
}
if (extensions.oes_texture_half_float) {
textureTypes['float16'] = textureTypes['half float'] = GL_HALF_FLOAT_OES$1
}
if (extensions.webgl_depth_texture) {
extend(textureFormats, {
'depth': GL_DEPTH_COMPONENT,
'depth stencil': GL_DEPTH_STENCIL
})
extend(textureTypes, {
'uint16': GL_UNSIGNED_SHORT$3,
'uint32': GL_UNSIGNED_INT$3,
'depth stencil': GL_UNSIGNED_INT_24_8_WEBGL$1
})
}
if (extensions.webgl_compressed_texture_s3tc) {
extend(compressedTextureFormats, {
'rgb s3tc dxt1': GL_COMPRESSED_RGB_S3TC_DXT1_EXT,
'rgba s3tc dxt1': GL_COMPRESSED_RGBA_S3TC_DXT1_EXT,
'rgba s3tc dxt3': GL_COMPRESSED_RGBA_S3TC_DXT3_EXT,
'rgba s3tc dxt5': GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
})
}
if (extensions.webgl_compressed_texture_atc) {
extend(compressedTextureFormats, {
'rgb atc': GL_COMPRESSED_RGB_ATC_WEBGL,
'rgba atc explicit alpha': GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL,
'rgba atc interpolated alpha': GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL
})
}
if (extensions.webgl_compressed_texture_pvrtc) {
extend(compressedTextureFormats, {
'rgb pvrtc 4bppv1': GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG,
'rgb pvrtc 2bppv1': GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG,
'rgba pvrtc 4bppv1': GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG,
'rgba pvrtc 2bppv1': GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG
})
}
if (extensions.webgl_compressed_texture_etc1) {
compressedTextureFormats['rgb etc1'] = GL_COMPRESSED_RGB_ETC1_WEBGL
}
// Copy over all texture formats
var supportedCompressedFormats = Array.prototype.slice.call(
gl.getParameter(GL_COMPRESSED_TEXTURE_FORMATS))
Object.keys(compressedTextureFormats).forEach(function (name) {
var format = compressedTextureFormats[name]
if (supportedCompressedFormats.indexOf(format) >= 0) {
textureFormats[name] = format
}
})
var supportedFormats = Object.keys(textureFormats)
limits.textureFormats = supportedFormats
// associate with every format string its
// corresponding GL-value.
var textureFormatsInvert = []
Object.keys(textureFormats).forEach(function (key) {
var val = textureFormats[key]
textureFormatsInvert[val] = key
})
// associate with every type string its
// corresponding GL-value.
var textureTypesInvert = []
Object.keys(textureTypes).forEach(function (key) {
var val = textureTypes[key]
textureTypesInvert[val] = key
})
var magFiltersInvert = []
Object.keys(magFilters).forEach(function (key) {
var val = magFilters[key]
magFiltersInvert[val] = key
})
var minFiltersInvert = []
Object.keys(minFilters).forEach(function (key) {
var val = minFilters[key]
minFiltersInvert[val] = key
})
var wrapModesInvert = []
Object.keys(wrapModes).forEach(function (key) {
var val = wrapModes[key]
wrapModesInvert[val] = key
})
// colorFormats[] gives the format (channels) associated to an
// internalformat
var colorFormats = supportedFormats.reduce(function (color, key) {
var glenum = textureFormats[key]
if (glenum === GL_LUMINANCE ||
glenum === GL_ALPHA ||
glenum === GL_LUMINANCE ||
glenum === GL_LUMINANCE_ALPHA ||
glenum === GL_DEPTH_COMPONENT ||
glenum === GL_DEPTH_STENCIL ||
(extensions.ext_srgb &&
(glenum === GL_SRGB_EXT ||
glenum === GL_SRGB_ALPHA_EXT))) {
color[glenum] = glenum
} else if (glenum === GL_RGB5_A1 || key.indexOf('rgba') >= 0) {
color[glenum] = GL_RGBA$1
} else {
color[glenum] = GL_RGB
}
return color
}, {})
function TexFlags () {
// format info
this.internalformat = GL_RGBA$1
this.format = GL_RGBA$1
this.type = GL_UNSIGNED_BYTE$5
this.compressed = false
// pixel storage
this.premultiplyAlpha = false
this.flipY = false
this.unpackAlignment = 1
this.colorSpace = GL_BROWSER_DEFAULT_WEBGL
// shape info
this.width = 0
this.height = 0
this.channels = 0
}
function copyFlags (result, other) {
result.internalformat = other.internalformat
result.format = other.format
result.type = other.type
result.compressed = other.compressed
result.premultiplyAlpha = other.premultiplyAlpha
result.flipY = other.flipY
result.unpackAlignment = other.unpackAlignment
result.colorSpace = other.colorSpace
result.width = other.width
result.height = other.height
result.channels = other.channels
}
function parseFlags (flags, options) {
if (typeof options !== 'object' || !options) {
return
}
if ('premultiplyAlpha' in options) {
check$1.type(options.premultiplyAlpha, 'boolean',
'invalid premultiplyAlpha')
flags.premultiplyAlpha = options.premultiplyAlpha
}
if ('flipY' in options) {
check$1.type(options.flipY, 'boolean',
'invalid texture flip')
flags.flipY = options.flipY
}
if ('alignment' in options) {
check$1.oneOf(options.alignment, [1, 2, 4, 8],
'invalid texture unpack alignment')
flags.unpackAlignment = options.alignment
}
if ('colorSpace' in options) {
check$1.parameter(options.colorSpace, colorSpace,
'invalid colorSpace')
flags.colorSpace = colorSpace[options.colorSpace]
}
if ('type' in options) {
var type = options.type
check$1(extensions.oes_texture_float ||
!(type === 'float' || type === 'float32'),
'you must enable the OES_texture_float extension in order to use floating point textures.')
check$1(extensions.oes_texture_half_float ||
!(type === 'half float' || type === 'float16'),
'you must enable the OES_texture_half_float extension in order to use 16-bit floating point textures.')
check$1(extensions.webgl_depth_texture ||
!(type === 'uint16' || type === 'uint32' || type === 'depth stencil'),
'you must enable the WEBGL_depth_texture extension in order to use depth/stencil textures.')
check$1.parameter(type, textureTypes,
'invalid texture type')
flags.type = textureTypes[type]
}
var w = flags.width
var h = flags.height
var c = flags.channels
var hasChannels = false
if ('shape' in options) {
check$1(Array.isArray(options.shape) && options.shape.length >= 2,
'shape must be an array')
w = options.shape[0]
h = options.shape[1]
if (options.shape.length === 3) {
c = options.shape[2]
check$1(c > 0 && c <= 4, 'invalid number of channels')
hasChannels = true
}
check$1(w >= 0 && w <= limits.maxTextureSize, 'invalid width')
check$1(h >= 0 && h <= limits.maxTextureSize, 'invalid height')
} else {
if ('radius' in options) {
w = h = options.radius
check$1(w >= 0 && w <= limits.maxTextureSize, 'invalid radius')
}
if ('width' in options) {
w = options.width
check$1(w >= 0 && w <= limits.maxTextureSize, 'invalid width')
}
if ('height' in options) {
h = options.height
check$1(h >= 0 && h <= limits.maxTextureSize, 'invalid height')
}
if ('channels' in options) {
c = options.channels
check$1(c > 0 && c <= 4, 'invalid number of channels')
hasChannels = true
}
}
flags.width = w | 0
flags.height = h | 0
flags.channels = c | 0
var hasFormat = false
if ('format' in options) {
var formatStr = options.format
check$1(extensions.webgl_depth_texture ||
!(formatStr === 'depth' || formatStr === 'depth stencil'),
'you must enable the WEBGL_depth_texture extension in order to use depth/stencil textures.')
check$1.parameter(formatStr, textureFormats,
'invalid texture format')
var internalformat = flags.internalformat = textureFormats[formatStr]
flags.format = colorFormats[internalformat]
if (formatStr in textureTypes) {
if (!('type' in options)) {
flags.type = textureTypes[formatStr]
}
}
if (formatStr in compressedTextureFormats) {
flags.compressed = true
}
hasFormat = true
}
// Reconcile channels and format
if (!hasChannels && hasFormat) {
flags.channels = FORMAT_CHANNELS[flags.format]
} else if (hasChannels && !hasFormat) {
if (flags.channels !== CHANNELS_FORMAT[flags.format]) {
flags.format = flags.internalformat = CHANNELS_FORMAT[flags.channels]
}
} else if (hasFormat && hasChannels) {
check$1(
flags.channels === FORMAT_CHANNELS[flags.format],
'number of channels inconsistent with specified format')
}
}
function setFlags (flags) {
gl.pixelStorei(GL_UNPACK_FLIP_Y_WEBGL, flags.flipY)
gl.pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL, flags.premultiplyAlpha)
gl.pixelStorei(GL_UNPACK_COLORSPACE_CONVERSION_WEBGL, flags.colorSpace)
gl.pixelStorei(GL_UNPACK_ALIGNMENT, flags.unpackAlignment)
}
// -------------------------------------------------------
// Tex image data
// -------------------------------------------------------
function TexImage () {
TexFlags.call(this)
this.xOffset = 0
this.yOffset = 0
// data
this.data = null
this.needsFree = false
// html element
this.element = null
// copyTexImage info
this.needsCopy = false
}
function parseImage (image, options) {
var data = null
if (isPixelData(options)) {
data = options
} else if (options) {
check$1.type(options, 'object', 'invalid pixel data type')
parseFlags(image, options)
if ('x' in options) {
image.xOffset = options.x | 0
}
if ('y' in options) {
image.yOffset = options.y | 0
}
if (isPixelData(options.data)) {
data = options.data
}
}
check$1(
!image.compressed ||
data instanceof Uint8Array,
'compressed texture data must be stored in a uint8array')
if (options.copy) {
check$1(!data, 'can not specify copy and data field for the same texture')
var viewW = contextState.viewportWidth
var viewH = contextState.viewportHeight
image.width = image.width || (viewW - image.xOffset)
image.height = image.height || (viewH - image.yOffset)
image.needsCopy = true
check$1(image.xOffset >= 0 && image.xOffset < viewW &&
image.yOffset >= 0 && image.yOffset < viewH &&
image.width > 0 && image.width <= viewW &&
image.height > 0 && image.height <= viewH,
'copy texture read out of bounds')
} else if (!data) {
image.width = image.width || 1
image.height = image.height || 1
image.channels = image.channels || 4
} else if (isTypedArray(data)) {
image.channels = image.channels || 4
image.data = data
if (!('type' in options) && image.type === GL_UNSIGNED_BYTE$5) {
image.type = typedArrayCode$1(data)
}
} else if (isNumericArray(data)) {
image.channels = image.channels || 4
convertData(image, data)
image.alignment = 1
image.needsFree = true
} else if (isNDArrayLike(data)) {
var array = data.data
if (!Array.isArray(array) && image.type === GL_UNSIGNED_BYTE$5) {
image.type = typedArrayCode$1(array)
}
var shape = data.shape
var stride = data.stride
var shapeX, shapeY, shapeC, strideX, strideY, strideC
if (shape.length === 3) {
shapeC = shape[2]
strideC = stride[2]
} else {
check$1(shape.length === 2, 'invalid ndarray pixel data, must be 2 or 3D')
shapeC = 1
strideC = 1
}
shapeX = shape[0]
shapeY = shape[1]
strideX = stride[0]
strideY = stride[1]
image.alignment = 1
image.width = shapeX
image.height = shapeY
image.channels = shapeC
image.format = image.internalformat = CHANNELS_FORMAT[shapeC]
image.needsFree = true
transposeData(image, array, strideX, strideY, strideC, data.offset)
} else if (isCanvasElement(data) || isOffscreenCanvas(data) || isContext2D(data)) {
if (isCanvasElement(data) || isOffscreenCanvas(data)) {
image.element = data
} else {
image.element = data.canvas
}
image.width = image.element.width
image.height = image.element.height
image.channels = 4
} else if (isBitmap(data)) {
image.element = data
image.width = data.width
image.height = data.height
image.channels = 4
} else if (isImageElement(data)) {
image.element = data
image.width = data.naturalWidth
image.height = data.naturalHeight
image.channels = 4
} else if (isVideoElement(data)) {
image.element = data
image.width = data.videoWidth
image.height = data.videoHeight
image.channels = 4
} else if (isRectArray(data)) {
var w = image.width || data[0].length
var h = image.height || data.length
var c = image.channels
if (isArrayLike(data[0][0])) {
c = c || data[0][0].length
} else {
c = c || 1
}
var arrayShape = flattenUtils.shape(data)
var n = 1
for (var dd = 0; dd < arrayShape.length; ++dd) {
n *= arrayShape[dd]
}
var allocData = preConvert(image, n)
flattenUtils.flatten(data, arrayShape, '', allocData)
postConvert(image, allocData)
image.alignment = 1
image.width = w
image.height = h
image.channels = c
image.format = image.internalformat = CHANNELS_FORMAT[c]
image.needsFree = true
}
if (image.type === GL_FLOAT$4) {
check$1(limits.extensions.indexOf('oes_texture_float') >= 0,
'oes_texture_float extension not enabled')
} else if (image.type === GL_HALF_FLOAT_OES$1) {
check$1(limits.extensions.indexOf('oes_texture_half_float') >= 0,
'oes_texture_half_float extension not enabled')
}
// do compressed texture validation here.
}
function setImage (info, target, miplevel) {
var element = info.element
var data = info.data
var internalformat = info.internalformat
var format = info.format
var type = info.type
var width = info.width
var height = info.height
setFlags(info)
if (element) {
gl.texImage2D(target, miplevel, format, format, type, element)
} else if (info.compressed) {
gl.compressedTexImage2D(target, miplevel, internalformat, width, height, 0, data)
} else if (info.needsCopy) {
reglPoll()
gl.copyTexImage2D(
target, miplevel, format, info.xOffset, info.yOffset, width, height, 0)
} else {
gl.texImage2D(target, miplevel, format, width, height, 0, format, type, data || null)
}
}
function setSubImage (info, target, x, y, miplevel) {
var element = info.element
var data = info.data
var internalformat = info.internalformat
var format = info.format
var type = info.type
var width = info.width
var height = info.height
setFlags(info)
if (element) {
gl.texSubImage2D(
target, miplevel, x, y, format, type, element)
} else if (info.compressed) {
gl.compressedTexSubImage2D(
target, miplevel, x, y, internalformat, width, height, data)
} else if (info.needsCopy) {
reglPoll()
gl.copyTexSubImage2D(
target, miplevel, x, y, info.xOffset, info.yOffset, width, height)
} else {
gl.texSubImage2D(
target, miplevel, x, y, width, height, format, type, data)
}
}
// texImage pool
var imagePool = []
function allocImage () {
return imagePool.pop() || new TexImage()
}
function freeImage (image) {
if (image.needsFree) {
pool.freeType(image.data)
}
TexImage.call(image)
imagePool.push(image)
}
// -------------------------------------------------------
// Mip map
// -------------------------------------------------------
function MipMap () {
TexFlags.call(this)
this.genMipmaps = false
this.mipmapHint = GL_DONT_CARE
this.mipmask = 0
this.images = Array(16)
}
function parseMipMapFromShape (mipmap, width, height) {
var img = mipmap.images[0] = allocImage()
mipmap.mipmask = 1
img.width = mipmap.width = width
img.height = mipmap.height = height
img.channels = mipmap.channels = 4
}
function parseMipMapFromObject (mipmap, options) {
var imgData = null
if (isPixelData(options)) {
imgData = mipmap.images[0] = allocImage()
copyFlags(imgData, mipmap)
parseImage(imgData, options)
mipmap.mipmask = 1
} else {
parseFlags(mipmap, options)
if (Array.isArray(options.mipmap)) {
var mipData = options.mipmap
for (var i = 0; i < mipData.length; ++i) {
imgData = mipmap.images[i] = allocImage()
copyFlags(imgData, mipmap)
imgData.width >>= i
imgData.height >>= i
parseImage(imgData, mipData[i])
mipmap.mipmask |= (1 << i)
}
} else {
imgData = mipmap.images[0] = allocImage()
copyFlags(imgData, mipmap)
parseImage(imgData, options)
mipmap.mipmask = 1
}
}
copyFlags(mipmap, mipmap.images[0])
// For textures of the compressed format WEBGL_compressed_texture_s3tc
// we must have that
//
// "When level equals zero width and height must be a multiple of 4.
// When level is greater than 0 width and height must be 0, 1, 2 or a multiple of 4. "
//
// but we do not yet support having multiple mipmap levels for compressed textures,
// so we only test for level zero.
if (
mipmap.compressed &&
(
mipmap.internalformat === GL_COMPRESSED_RGB_S3TC_DXT1_EXT ||
mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT1_EXT ||
mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT3_EXT ||
mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
)
) {
check$1(mipmap.width % 4 === 0 && mipmap.height % 4 === 0,
'for compressed texture formats, mipmap level 0 must have width and height that are a multiple of 4')
}
}
function setMipMap (mipmap, target) {
var images = mipmap.images
for (var i = 0; i < images.length; ++i) {
if (!images[i]) {
return
}
setImage(images[i], target, i)
}
}
var mipPool = []
function allocMipMap () {
var result = mipPool.pop() || new MipMap()
TexFlags.call(result)
result.mipmask = 0
for (var i = 0; i < 16; ++i) {
result.images[i] = null
}
return result
}
function freeMipMap (mipmap) {
var images = mipmap.images
for (var i = 0; i < images.length; ++i) {
if (images[i]) {
freeImage(images[i])
}
images[i] = null
}
mipPool.push(mipmap)
}
// -------------------------------------------------------
// Tex info
// -------------------------------------------------------
function TexInfo () {
this.minFilter = GL_NEAREST$1
this.magFilter = GL_NEAREST$1
this.wrapS = GL_CLAMP_TO_EDGE$1
this.wrapT = GL_CLAMP_TO_EDGE$1
this.anisotropic = 1
this.genMipmaps = false
this.mipmapHint = GL_DONT_CARE
}
function parseTexInfo (info, options) {
if ('min' in options) {
var minFilter = options.min
check$1.parameter(minFilter, minFilters)
info.minFilter = minFilters[minFilter]
if (MIPMAP_FILTERS.indexOf(info.minFilter) >= 0 && !('faces' in options)) {
info.genMipmaps = true
}
}
if ('mag' in options) {
var magFilter = options.mag
check$1.parameter(magFilter, magFilters)
info.magFilter = magFilters[magFilter]
}
var wrapS = info.wrapS
var wrapT = info.wrapT
if ('wrap' in options) {
var wrap = options.wrap
if (typeof wrap === 'string') {
check$1.parameter(wrap, wrapModes)
wrapS = wrapT = wrapModes[wrap]
} else if (Array.isArray(wrap)) {
check$1.parameter(wrap[0], wrapModes)
check$1.parameter(wrap[1], wrapModes)
wrapS = wrapModes[wrap[0]]
wrapT = wrapModes[wrap[1]]
}
} else {
if ('wrapS' in options) {
var optWrapS = options.wrapS
check$1.parameter(optWrapS, wrapModes)
wrapS = wrapModes[optWrapS]
}
if ('wrapT' in options) {
var optWrapT = options.wrapT
check$1.parameter(optWrapT, wrapModes)
wrapT = wrapModes[optWrapT]
}
}
info.wrapS = wrapS
info.wrapT = wrapT
if ('anisotropic' in options) {
var anisotropic = options.anisotropic
check$1(typeof anisotropic === 'number' &&
anisotropic >= 1 && anisotropic <= limits.maxAnisotropic,
'aniso samples must be between 1 and ')
info.anisotropic = options.anisotropic
}
if ('mipmap' in options) {
var hasMipMap = false
switch (typeof options.mipmap) {
case 'string':
check$1.parameter(options.mipmap, mipmapHint,
'invalid mipmap hint')
info.mipmapHint = mipmapHint[options.mipmap]
info.genMipmaps = true
hasMipMap = true
break
case 'boolean':
hasMipMap = info.genMipmaps = options.mipmap
break
case 'object':
check$1(Array.isArray(options.mipmap), 'invalid mipmap type')
info.genMipmaps = false
hasMipMap = true
break
default:
check$1.raise('invalid mipmap type')
}
if (hasMipMap && !('min' in options)) {
info.minFilter = GL_NEAREST_MIPMAP_NEAREST$1
}
}
}
function setTexInfo (info, target) {
gl.texParameteri(target, GL_TEXTURE_MIN_FILTER, info.minFilter)
gl.texParameteri(target, GL_TEXTURE_MAG_FILTER, info.magFilter)
gl.texParameteri(target, GL_TEXTURE_WRAP_S, info.wrapS)
gl.texParameteri(target, GL_TEXTURE_WRAP_T, info.wrapT)
if (extensions.ext_texture_filter_anisotropic) {
gl.texParameteri(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, info.anisotropic)
}
if (info.genMipmaps) {
gl.hint(GL_GENERATE_MIPMAP_HINT, info.mipmapHint)
gl.generateMipmap(target)
}
}
// -------------------------------------------------------
// Full texture object
// -------------------------------------------------------
var textureCount = 0
var textureSet = {}
var numTexUnits = limits.maxTextureUnits
var textureUnits = Array(numTexUnits).map(function () {
return null
})
function REGLTexture (target) {
TexFlags.call(this)
this.mipmask = 0
this.internalformat = GL_RGBA$1
this.id = textureCount++
this.refCount = 1
this.target = target
this.texture = gl.createTexture()
this.unit = -1
this.bindCount = 0
this.texInfo = new TexInfo()
if (config.profile) {
this.stats = { size: 0 }
}
}
function tempBind (texture) {
gl.activeTexture(GL_TEXTURE0$1)
gl.bindTexture(texture.target, texture.texture)
}
function tempRestore () {
var prev = textureUnits[0]
if (prev) {
gl.bindTexture(prev.target, prev.texture)
} else {
gl.bindTexture(GL_TEXTURE_2D$1, null)
}
}
function destroy (texture) {
var handle = texture.texture
check$1(handle, 'must not double destroy texture')
var unit = texture.unit
var target = texture.target
if (unit >= 0) {
gl.activeTexture(GL_TEXTURE0$1 + unit)
gl.bindTexture(target, null)
textureUnits[unit] = null
}
gl.deleteTexture(handle)
texture.texture = null
texture.params = null
texture.pixels = null
texture.refCount = 0
delete textureSet[texture.id]
stats.textureCount--
}
extend(REGLTexture.prototype, {
bind: function () {
var texture = this
texture.bindCount += 1
var unit = texture.unit
if (unit < 0) {
for (var i = 0; i < numTexUnits; ++i) {
var other = textureUnits[i]
if (other) {
if (other.bindCount > 0) {
continue
}
other.unit = -1
}
textureUnits[i] = texture
unit = i
break
}
if (unit >= numTexUnits) {
check$1.raise('insufficient number of texture units')
}
if (config.profile && stats.maxTextureUnits < (unit + 1)) {
stats.maxTextureUnits = unit + 1 // +1, since the units are zero-based
}
texture.unit = unit
gl.activeTexture(GL_TEXTURE0$1 + unit)
gl.bindTexture(texture.target, texture.texture)
}
return unit
},
unbind: function () {
this.bindCount -= 1
},
decRef: function () {
if (--this.refCount <= 0) {
destroy(this)
}
}
})
function createTexture2D (a, b) {
var texture = new REGLTexture(GL_TEXTURE_2D$1)
textureSet[texture.id] = texture
stats.textureCount++
function reglTexture2D (a, b) {
var texInfo = texture.texInfo
TexInfo.call(texInfo)
var mipData = allocMipMap()
if (typeof a === 'number') {
if (typeof b === 'number') {
parseMipMapFromShape(mipData, a | 0, b | 0)
} else {
parseMipMapFromShape(mipData, a | 0, a | 0)
}
} else if (a) {
check$1.type(a, 'object', 'invalid arguments to regl.texture')
parseTexInfo(texInfo, a)
parseMipMapFromObject(mipData, a)
} else {
// empty textures get assigned a default shape of 1x1
parseMipMapFromShape(mipData, 1, 1)
}
if (texInfo.genMipmaps) {
mipData.mipmask = (mipData.width << 1) - 1
}
texture.mipmask = mipData.mipmask
copyFlags(texture, mipData)
check$1.texture2D(texInfo, mipData, limits)
texture.internalformat = mipData.internalformat
reglTexture2D.width = mipData.width
reglTexture2D.height = mipData.height
tempBind(texture)
setMipMap(mipData, GL_TEXTURE_2D$1)
setTexInfo(texInfo, GL_TEXTURE_2D$1)
tempRestore()
freeMipMap(mipData)
if (config.profile) {
texture.stats.size = getTextureSize(
texture.internalformat,
texture.type,
mipData.width,
mipData.height,
texInfo.genMipmaps,
false)
}
reglTexture2D.format = textureFormatsInvert[texture.internalformat]
reglTexture2D.type = textureTypesInvert[texture.type]
reglTexture2D.mag = magFiltersInvert[texInfo.magFilter]
reglTexture2D.min = minFiltersInvert[texInfo.minFilter]
reglTexture2D.wrapS = wrapModesInvert[texInfo.wrapS]
reglTexture2D.wrapT = wrapModesInvert[texInfo.wrapT]
return reglTexture2D
}
function subimage (image, x_, y_, level_) {
check$1(!!image, 'must specify image data')
var x = x_ | 0
var y = y_ | 0
var level = level_ | 0
var imageData = allocImage()
copyFlags(imageData, texture)
imageData.width = 0
imageData.height = 0
parseImage(imageData, image)
imageData.width = imageData.width || ((texture.width >> level) - x)
imageData.height = imageData.height || ((texture.height >> level) - y)
check$1(
texture.type === imageData.type &&
texture.format === imageData.format &&
texture.internalformat === imageData.internalformat,
'incompatible format for texture.subimage')
check$1(
x >= 0 && y >= 0 &&
x + imageData.width <= texture.width &&
y + imageData.height <= texture.height,
'texture.subimage write out of bounds')
check$1(
texture.mipmask & (1 << level),
'missing mipmap data')
check$1(
imageData.data || imageData.element || imageData.needsCopy,
'missing image data')
tempBind(texture)
setSubImage(imageData, GL_TEXTURE_2D$1, x, y, level)
tempRestore()
freeImage(imageData)
return reglTexture2D
}
function resize (w_, h_) {
var w = w_ | 0
var h = (h_ | 0) || w
if (w === texture.width && h === texture.height) {
return reglTexture2D
}
reglTexture2D.width = texture.width = w
reglTexture2D.height = texture.height = h
tempBind(texture)
for (var i = 0; texture.mipmask >> i; ++i) {
var _w = w >> i
var _h = h >> i
if (!_w || !_h) break
gl.texImage2D(
GL_TEXTURE_2D$1,
i,
texture.format,
_w,
_h,
0,
texture.format,
texture.type,
null)
}
tempRestore()
// also, recompute the texture size.
if (config.profile) {
texture.stats.size = getTextureSize(
texture.internalformat,
texture.type,
w,
h,
false,
false)
}
return reglTexture2D
}
reglTexture2D(a, b)
reglTexture2D.subimage = subimage
reglTexture2D.resize = resize
reglTexture2D._reglType = 'texture2d'
reglTexture2D._texture = texture
if (config.profile) {
reglTexture2D.stats = texture.stats
}
reglTexture2D.destroy = function () {
texture.decRef()
}
return reglTexture2D
}
function createTextureCube (a0, a1, a2, a3, a4, a5) {
var texture = new REGLTexture(GL_TEXTURE_CUBE_MAP$1)
textureSet[texture.id] = texture
stats.cubeCount++
var faces = new Array(6)
function reglTextureCube (a0, a1, a2, a3, a4, a5) {
var i
var texInfo = texture.texInfo
TexInfo.call(texInfo)
for (i = 0; i < 6; ++i) {
faces[i] = allocMipMap()
}
if (typeof a0 === 'number' || !a0) {
var s = (a0 | 0) || 1
for (i = 0; i < 6; ++i) {
parseMipMapFromShape(faces[i], s, s)
}
} else if (typeof a0 === 'object') {
if (a1) {
parseMipMapFromObject(faces[0], a0)
parseMipMapFromObject(faces[1], a1)
parseMipMapFromObject(faces[2], a2)
parseMipMapFromObject(faces[3], a3)
parseMipMapFromObject(faces[4], a4)
parseMipMapFromObject(faces[5], a5)
} else {
parseTexInfo(texInfo, a0)
parseFlags(texture, a0)
if ('faces' in a0) {
var faceInput = a0.faces
check$1(Array.isArray(faceInput) && faceInput.length === 6,
'cube faces must be a length 6 array')
for (i = 0; i < 6; ++i) {
check$1(typeof faceInput[i] === 'object' && !!faceInput[i],
'invalid input for cube map face')
copyFlags(faces[i], texture)
parseMipMapFromObject(faces[i], faceInput[i])
}
} else {
for (i = 0; i < 6; ++i) {
parseMipMapFromObject(faces[i], a0)
}
}
}
} else {
check$1.raise('invalid arguments to cube map')
}
copyFlags(texture, faces[0])
if (!limits.npotTextureCube) {
check$1(isPow2$1(texture.width) && isPow2$1(texture.height), 'your browser does not support non power or two texture dimensions')
}
if (texInfo.genMipmaps) {
texture.mipmask = (faces[0].width << 1) - 1
} else {
texture.mipmask = faces[0].mipmask
}
check$1.textureCube(texture, texInfo, faces, limits)
texture.internalformat = faces[0].internalformat
reglTextureCube.width = faces[0].width
reglTextureCube.height = faces[0].height
tempBind(texture)
for (i = 0; i < 6; ++i) {
setMipMap(faces[i], GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + i)
}
setTexInfo(texInfo, GL_TEXTURE_CUBE_MAP$1)
tempRestore()
if (config.profile) {
texture.stats.size = getTextureSize(
texture.internalformat,
texture.type,
reglTextureCube.width,
reglTextureCube.height,
texInfo.genMipmaps,
true)
}
reglTextureCube.format = textureFormatsInvert[texture.internalformat]
reglTextureCube.type = textureTypesInvert[texture.type]
reglTextureCube.mag = magFiltersInvert[texInfo.magFilter]
reglTextureCube.min = minFiltersInvert[texInfo.minFilter]
reglTextureCube.wrapS = wrapModesInvert[texInfo.wrapS]
reglTextureCube.wrapT = wrapModesInvert[texInfo.wrapT]
for (i = 0; i < 6; ++i) {
freeMipMap(faces[i])
}
return reglTextureCube
}
function subimage (face, image, x_, y_, level_) {
check$1(!!image, 'must specify image data')
check$1(typeof face === 'number' && face === (face | 0) &&
face >= 0 && face < 6, 'invalid face')
var x = x_ | 0
var y = y_ | 0
var level = level_ | 0
var imageData = allocImage()
copyFlags(imageData, texture)
imageData.width = 0
imageData.height = 0
parseImage(imageData, image)
imageData.width = imageData.width || ((texture.width >> level) - x)
imageData.height = imageData.height || ((texture.height >> level) - y)
check$1(
texture.type === imageData.type &&
texture.format === imageData.format &&
texture.internalformat === imageData.internalformat,
'incompatible format for texture.subimage')
check$1(
x >= 0 && y >= 0 &&
x + imageData.width <= texture.width &&
y + imageData.height <= texture.height,
'texture.subimage write out of bounds')
check$1(
texture.mipmask & (1 << level),
'missing mipmap data')
check$1(
imageData.data || imageData.element || imageData.needsCopy,
'missing image data')
tempBind(texture)
setSubImage(imageData, GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + face, x, y, level)
tempRestore()
freeImage(imageData)
return reglTextureCube
}
function resize (radius_) {
var radius = radius_ | 0
if (radius === texture.width) {
return
}
reglTextureCube.width = texture.width = radius
reglTextureCube.height = texture.height = radius
tempBind(texture)
for (var i = 0; i < 6; ++i) {
for (var j = 0; texture.mipmask >> j; ++j) {
gl.texImage2D(
GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + i,
j,
texture.format,
radius >> j,
radius >> j,
0,
texture.format,
texture.type,
null)
}
}
tempRestore()
if (config.profile) {
texture.stats.size = getTextureSize(
texture.internalformat,
texture.type,
reglTextureCube.width,
reglTextureCube.height,
false,
true)
}
return reglTextureCube
}
reglTextureCube(a0, a1, a2, a3, a4, a5)
reglTextureCube.subimage = subimage
reglTextureCube.resize = resize
reglTextureCube._reglType = 'textureCube'
reglTextureCube._texture = texture
if (config.profile) {
reglTextureCube.stats = texture.stats
}
reglTextureCube.destroy = function () {
texture.decRef()
}
return reglTextureCube
}
// Called when regl is destroyed
function destroyTextures () {
for (var i = 0; i < numTexUnits; ++i) {
gl.activeTexture(GL_TEXTURE0$1 + i)
gl.bindTexture(GL_TEXTURE_2D$1, null)
textureUnits[i] = null
}
values(textureSet).forEach(destroy)
stats.cubeCount = 0
stats.textureCount = 0
}
if (config.profile) {
stats.getTotalTextureSize = function () {
var total = 0
Object.keys(textureSet).forEach(function (key) {
total += textureSet[key].stats.size
})
return total
}
}
function restoreTextures () {
for (var i = 0; i < numTexUnits; ++i) {
var tex = textureUnits[i]
if (tex) {
tex.bindCount = 0
tex.unit = -1
textureUnits[i] = null
}
}
values(textureSet).forEach(function (texture) {
texture.texture = gl.createTexture()
gl.bindTexture(texture.target, texture.texture)
for (var i = 0; i < 32; ++i) {
if ((texture.mipmask & (1 << i)) === 0) {
continue
}
if (texture.target === GL_TEXTURE_2D$1) {
gl.texImage2D(GL_TEXTURE_2D$1,
i,
texture.internalformat,
texture.width >> i,
texture.height >> i,
0,
texture.internalformat,
texture.type,
null)
} else {
for (var j = 0; j < 6; ++j) {
gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + j,
i,
texture.internalformat,
texture.width >> i,
texture.height >> i,
0,
texture.internalformat,
texture.type,
null)
}
}
}
setTexInfo(texture.texInfo, texture.target)
})
}
return {
create2D: createTexture2D,
createCube: createTextureCube,
clear: destroyTextures,
getTexture: function (wrapper) {
return null
},
restore: restoreTextures
}
}
var GL_RENDERBUFFER = 0x8D41
var GL_RGBA4$1 = 0x8056
var GL_RGB5_A1$1 = 0x8057
var GL_RGB565$1 = 0x8D62
var GL_DEPTH_COMPONENT16 = 0x81A5
var GL_STENCIL_INDEX8 = 0x8D48
var GL_DEPTH_STENCIL$1 = 0x84F9
var GL_SRGB8_ALPHA8_EXT = 0x8C43
var GL_RGBA32F_EXT = 0x8814
var GL_RGBA16F_EXT = 0x881A
var GL_RGB16F_EXT = 0x881B
var FORMAT_SIZES = []
FORMAT_SIZES[GL_RGBA4$1] = 2
FORMAT_SIZES[GL_RGB5_A1$1] = 2
FORMAT_SIZES[GL_RGB565$1] = 2
FORMAT_SIZES[GL_DEPTH_COMPONENT16] = 2
FORMAT_SIZES[GL_STENCIL_INDEX8] = 1
FORMAT_SIZES[GL_DEPTH_STENCIL$1] = 4
FORMAT_SIZES[GL_SRGB8_ALPHA8_EXT] = 4
FORMAT_SIZES[GL_RGBA32F_EXT] = 16
FORMAT_SIZES[GL_RGBA16F_EXT] = 8
FORMAT_SIZES[GL_RGB16F_EXT] = 6
function getRenderbufferSize (format, width, height) {
return FORMAT_SIZES[format] * width * height
}
var wrapRenderbuffers = function (gl, extensions, limits, stats, config) {
var formatTypes = {
'rgba4': GL_RGBA4$1,
'rgb565': GL_RGB565$1,
'rgb5 a1': GL_RGB5_A1$1,
'depth': GL_DEPTH_COMPONENT16,
'stencil': GL_STENCIL_INDEX8,
'depth stencil': GL_DEPTH_STENCIL$1
}
if (extensions.ext_srgb) {
formatTypes['srgba'] = GL_SRGB8_ALPHA8_EXT
}
if (extensions.ext_color_buffer_half_float) {
formatTypes['rgba16f'] = GL_RGBA16F_EXT
formatTypes['rgb16f'] = GL_RGB16F_EXT
}
if (extensions.webgl_color_buffer_float) {
formatTypes['rgba32f'] = GL_RGBA32F_EXT
}
var formatTypesInvert = []
Object.keys(formatTypes).forEach(function (key) {
var val = formatTypes[key]
formatTypesInvert[val] = key
})
var renderbufferCount = 0
var renderbufferSet = {}
function REGLRenderbuffer (renderbuffer) {
this.id = renderbufferCount++
this.refCount = 1
this.renderbuffer = renderbuffer
this.format = GL_RGBA4$1
this.width = 0
this.height = 0
if (config.profile) {
this.stats = { size: 0 }
}
}
REGLRenderbuffer.prototype.decRef = function () {
if (--this.refCount <= 0) {
destroy(this)
}
}
function destroy (rb) {
var handle = rb.renderbuffer
check$1(handle, 'must not double destroy renderbuffer')
gl.bindRenderbuffer(GL_RENDERBUFFER, null)
gl.deleteRenderbuffer(handle)
rb.renderbuffer = null
rb.refCount = 0
delete renderbufferSet[rb.id]
stats.renderbufferCount--
}
function createRenderbuffer (a, b) {
var renderbuffer = new REGLRenderbuffer(gl.createRenderbuffer())
renderbufferSet[renderbuffer.id] = renderbuffer
stats.renderbufferCount++
function reglRenderbuffer (a, b) {
var w = 0
var h = 0
var format = GL_RGBA4$1
if (typeof a === 'object' && a) {
var options = a
if ('shape' in options) {
var shape = options.shape
check$1(Array.isArray(shape) && shape.length >= 2,
'invalid renderbuffer shape')
w = shape[0] | 0
h = shape[1] | 0
} else {
if ('radius' in options) {
w = h = options.radius | 0
}
if ('width' in options) {
w = options.width | 0
}
if ('height' in options) {
h = options.height | 0
}
}
if ('format' in options) {
check$1.parameter(options.format, formatTypes,
'invalid renderbuffer format')
format = formatTypes[options.format]
}
} else if (typeof a === 'number') {
w = a | 0
if (typeof b === 'number') {
h = b | 0
} else {
h = w
}
} else if (!a) {
w = h = 1
} else {
check$1.raise('invalid arguments to renderbuffer constructor')
}
// check shape
check$1(
w > 0 && h > 0 &&
w <= limits.maxRenderbufferSize && h <= limits.maxRenderbufferSize,
'invalid renderbuffer size')
if (w === renderbuffer.width &&
h === renderbuffer.height &&
format === renderbuffer.format) {
return
}
reglRenderbuffer.width = renderbuffer.width = w
reglRenderbuffer.height = renderbuffer.height = h
renderbuffer.format = format
gl.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer.renderbuffer)
gl.renderbufferStorage(GL_RENDERBUFFER, format, w, h)
check$1(
gl.getError() === 0,
'invalid render buffer format')
if (config.profile) {
renderbuffer.stats.size = getRenderbufferSize(renderbuffer.format, renderbuffer.width, renderbuffer.height)
}
reglRenderbuffer.format = formatTypesInvert[renderbuffer.format]
return reglRenderbuffer
}
function resize (w_, h_) {
var w = w_ | 0
var h = (h_ | 0) || w
if (w === renderbuffer.width && h === renderbuffer.height) {
return reglRenderbuffer
}
// check shape
check$1(
w > 0 && h > 0 &&
w <= limits.maxRenderbufferSize && h <= limits.maxRenderbufferSize,
'invalid renderbuffer size')
reglRenderbuffer.width = renderbuffer.width = w
reglRenderbuffer.height = renderbuffer.height = h
gl.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer.renderbuffer)
gl.renderbufferStorage(GL_RENDERBUFFER, renderbuffer.format, w, h)
check$1(
gl.getError() === 0,
'invalid render buffer format')
// also, recompute size.
if (config.profile) {
renderbuffer.stats.size = getRenderbufferSize(
renderbuffer.format, renderbuffer.width, renderbuffer.height)
}
return reglRenderbuffer
}
reglRenderbuffer(a, b)
reglRenderbuffer.resize = resize
reglRenderbuffer._reglType = 'renderbuffer'
reglRenderbuffer._renderbuffer = renderbuffer
if (config.profile) {
reglRenderbuffer.stats = renderbuffer.stats
}
reglRenderbuffer.destroy = function () {
renderbuffer.decRef()
}
return reglRenderbuffer
}
if (config.profile) {
stats.getTotalRenderbufferSize = function () {
var total = 0
Object.keys(renderbufferSet).forEach(function (key) {
total += renderbufferSet[key].stats.size
})
return total
}
}
function restoreRenderbuffers () {
values(renderbufferSet).forEach(function (rb) {
rb.renderbuffer = gl.createRenderbuffer()
gl.bindRenderbuffer(GL_RENDERBUFFER, rb.renderbuffer)
gl.renderbufferStorage(GL_RENDERBUFFER, rb.format, rb.width, rb.height)
})
gl.bindRenderbuffer(GL_RENDERBUFFER, null)
}
return {
create: createRenderbuffer,
clear: function () {
values(renderbufferSet).forEach(destroy)
},
restore: restoreRenderbuffers
}
}
// We store these constants so that the minifier can inline them
var GL_FRAMEBUFFER$1 = 0x8D40
var GL_RENDERBUFFER$1 = 0x8D41
var GL_TEXTURE_2D$2 = 0x0DE1
var GL_TEXTURE_CUBE_MAP_POSITIVE_X$2 = 0x8515
var GL_COLOR_ATTACHMENT0$1 = 0x8CE0
var GL_DEPTH_ATTACHMENT = 0x8D00
var GL_STENCIL_ATTACHMENT = 0x8D20
var GL_DEPTH_STENCIL_ATTACHMENT = 0x821A
var GL_FRAMEBUFFER_COMPLETE$1 = 0x8CD5
var GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6
var GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7
var GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8CD9
var GL_FRAMEBUFFER_UNSUPPORTED = 0x8CDD
var GL_HALF_FLOAT_OES$2 = 0x8D61
var GL_UNSIGNED_BYTE$6 = 0x1401
var GL_FLOAT$5 = 0x1406
var GL_RGB$1 = 0x1907
var GL_RGBA$2 = 0x1908
var GL_DEPTH_COMPONENT$1 = 0x1902
var colorTextureFormatEnums = [
GL_RGB$1,
GL_RGBA$2
]
// for every texture format, store
// the number of channels
var textureFormatChannels = []
textureFormatChannels[GL_RGBA$2] = 4
textureFormatChannels[GL_RGB$1] = 3
// for every texture type, store
// the size in bytes.
var textureTypeSizes = []
textureTypeSizes[GL_UNSIGNED_BYTE$6] = 1
textureTypeSizes[GL_FLOAT$5] = 4
textureTypeSizes[GL_HALF_FLOAT_OES$2] = 2
var GL_RGBA4$2 = 0x8056
var GL_RGB5_A1$2 = 0x8057
var GL_RGB565$2 = 0x8D62
var GL_DEPTH_COMPONENT16$1 = 0x81A5
var GL_STENCIL_INDEX8$1 = 0x8D48
var GL_DEPTH_STENCIL$2 = 0x84F9
var GL_SRGB8_ALPHA8_EXT$1 = 0x8C43
var GL_RGBA32F_EXT$1 = 0x8814
var GL_RGBA16F_EXT$1 = 0x881A
var GL_RGB16F_EXT$1 = 0x881B
var colorRenderbufferFormatEnums = [
GL_RGBA4$2,
GL_RGB5_A1$2,
GL_RGB565$2,
GL_SRGB8_ALPHA8_EXT$1,
GL_RGBA16F_EXT$1,
GL_RGB16F_EXT$1,
GL_RGBA32F_EXT$1
]
var statusCode = {}
statusCode[GL_FRAMEBUFFER_COMPLETE$1] = 'complete'
statusCode[GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT] = 'incomplete attachment'
statusCode[GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS] = 'incomplete dimensions'
statusCode[GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT] = 'incomplete, missing attachment'
statusCode[GL_FRAMEBUFFER_UNSUPPORTED] = 'unsupported'
function wrapFBOState (
gl,
extensions,
limits,
textureState,
renderbufferState,
stats) {
var framebufferState = {
cur: null,
next: null,
dirty: false,
setFBO: null
}
var colorTextureFormats = ['rgba']
var colorRenderbufferFormats = ['rgba4', 'rgb565', 'rgb5 a1']
if (extensions.ext_srgb) {
colorRenderbufferFormats.push('srgba')
}
if (extensions.ext_color_buffer_half_float) {
colorRenderbufferFormats.push('rgba16f', 'rgb16f')
}
if (extensions.webgl_color_buffer_float) {
colorRenderbufferFormats.push('rgba32f')
}
var colorTypes = ['uint8']
if (extensions.oes_texture_half_float) {
colorTypes.push('half float', 'float16')
}
if (extensions.oes_texture_float) {
colorTypes.push('float', 'float32')
}
function FramebufferAttachment (target, texture, renderbuffer) {
this.target = target
this.texture = texture
this.renderbuffer = renderbuffer
var w = 0
var h = 0
if (texture) {
w = texture.width
h = texture.height
} else if (renderbuffer) {
w = renderbuffer.width
h = renderbuffer.height
}
this.width = w
this.height = h
}
function decRef (attachment) {
if (attachment) {
if (attachment.texture) {
attachment.texture._texture.decRef()
}
if (attachment.renderbuffer) {
attachment.renderbuffer._renderbuffer.decRef()
}
}
}
function incRefAndCheckShape (attachment, width, height) {
if (!attachment) {
return
}
if (attachment.texture) {
var texture = attachment.texture._texture
var tw = Math.max(1, texture.width)
var th = Math.max(1, texture.height)
check$1(tw === width && th === height,
'inconsistent width/height for supplied texture')
texture.refCount += 1
} else {
var renderbuffer = attachment.renderbuffer._renderbuffer
check$1(
renderbuffer.width === width && renderbuffer.height === height,
'inconsistent width/height for renderbuffer')
renderbuffer.refCount += 1
}
}
function attach (location, attachment) {
if (attachment) {
if (attachment.texture) {
gl.framebufferTexture2D(
GL_FRAMEBUFFER$1,
location,
attachment.target,
attachment.texture._texture.texture,
0)
} else {
gl.framebufferRenderbuffer(
GL_FRAMEBUFFER$1,
location,
GL_RENDERBUFFER$1,
attachment.renderbuffer._renderbuffer.renderbuffer)
}
}
}
function parseAttachment (attachment) {
var target = GL_TEXTURE_2D$2
var texture = null
var renderbuffer = null
var data = attachment
if (typeof attachment === 'object') {
data = attachment.data
if ('target' in attachment) {
target = attachment.target | 0
}
}
check$1.type(data, 'function', 'invalid attachment data')
var type = data._reglType
if (type === 'texture2d') {
texture = data
check$1(target === GL_TEXTURE_2D$2)
} else if (type === 'textureCube') {
texture = data
check$1(
target >= GL_TEXTURE_CUBE_MAP_POSITIVE_X$2 &&
target < GL_TEXTURE_CUBE_MAP_POSITIVE_X$2 + 6,
'invalid cube map target')
} else if (type === 'renderbuffer') {
renderbuffer = data
target = GL_RENDERBUFFER$1
} else {
check$1.raise('invalid regl object for attachment')
}
return new FramebufferAttachment(target, texture, renderbuffer)
}
function allocAttachment (
width,
height,
isTexture,
format,
type) {
if (isTexture) {
var texture = textureState.create2D({
width: width,
height: height,
format: format,
type: type
})
texture._texture.refCount = 0
return new FramebufferAttachment(GL_TEXTURE_2D$2, texture, null)
} else {
var rb = renderbufferState.create({
width: width,
height: height,
format: format
})
rb._renderbuffer.refCount = 0
return new FramebufferAttachment(GL_RENDERBUFFER$1, null, rb)
}
}
function unwrapAttachment (attachment) {
return attachment && (attachment.texture || attachment.renderbuffer)
}
function resizeAttachment (attachment, w, h) {
if (attachment) {
if (attachment.texture) {
attachment.texture.resize(w, h)
} else if (attachment.renderbuffer) {
attachment.renderbuffer.resize(w, h)
}
attachment.width = w
attachment.height = h
}
}
var framebufferCount = 0
var framebufferSet = {}
function REGLFramebuffer () {
this.id = framebufferCount++
framebufferSet[this.id] = this
this.framebuffer = gl.createFramebuffer()
this.width = 0
this.height = 0
this.colorAttachments = []
this.depthAttachment = null
this.stencilAttachment = null
this.depthStencilAttachment = null
}
function decFBORefs (framebuffer) {
framebuffer.colorAttachments.forEach(decRef)
decRef(framebuffer.depthAttachment)
decRef(framebuffer.stencilAttachment)
decRef(framebuffer.depthStencilAttachment)
}
function destroy (framebuffer) {
var handle = framebuffer.framebuffer
check$1(handle, 'must not double destroy framebuffer')
gl.deleteFramebuffer(handle)
framebuffer.framebuffer = null
stats.framebufferCount--
delete framebufferSet[framebuffer.id]
}
function updateFramebuffer (framebuffer) {
var i
gl.bindFramebuffer(GL_FRAMEBUFFER$1, framebuffer.framebuffer)
var colorAttachments = framebuffer.colorAttachments
for (i = 0; i < colorAttachments.length; ++i) {
attach(GL_COLOR_ATTACHMENT0$1 + i, colorAttachments[i])
}
for (i = colorAttachments.length; i < limits.maxColorAttachments; ++i) {
gl.framebufferTexture2D(
GL_FRAMEBUFFER$1,
GL_COLOR_ATTACHMENT0$1 + i,
GL_TEXTURE_2D$2,
null,
0)
}
gl.framebufferTexture2D(
GL_FRAMEBUFFER$1,
GL_DEPTH_STENCIL_ATTACHMENT,
GL_TEXTURE_2D$2,
null,
0)
gl.framebufferTexture2D(
GL_FRAMEBUFFER$1,
GL_DEPTH_ATTACHMENT,
GL_TEXTURE_2D$2,
null,
0)
gl.framebufferTexture2D(
GL_FRAMEBUFFER$1,
GL_STENCIL_ATTACHMENT,
GL_TEXTURE_2D$2,
null,
0)
attach(GL_DEPTH_ATTACHMENT, framebuffer.depthAttachment)
attach(GL_STENCIL_ATTACHMENT, framebuffer.stencilAttachment)
attach(GL_DEPTH_STENCIL_ATTACHMENT, framebuffer.depthStencilAttachment)
// Check status code
var status = gl.checkFramebufferStatus(GL_FRAMEBUFFER$1)
if (!gl.isContextLost() && status !== GL_FRAMEBUFFER_COMPLETE$1) {
check$1.raise('framebuffer configuration not supported, status = ' +
statusCode[status])
}
gl.bindFramebuffer(GL_FRAMEBUFFER$1, framebufferState.next ? framebufferState.next.framebuffer : null)
framebufferState.cur = framebufferState.next
// FIXME: Clear error code here. This is a work around for a bug in
// headless-gl
gl.getError()
}
function createFBO (a0, a1) {
var framebuffer = new REGLFramebuffer()
stats.framebufferCount++
function reglFramebuffer (a, b) {
var i
check$1(framebufferState.next !== framebuffer,
'can not update framebuffer which is currently in use')
var width = 0
var height = 0
var needsDepth = true
var needsStencil = true
var colorBuffer = null
var colorTexture = true
var colorFormat = 'rgba'
var colorType = 'uint8'
var colorCount = 1
var depthBuffer = null
var stencilBuffer = null
var depthStencilBuffer = null
var depthStencilTexture = false
if (typeof a === 'number') {
width = a | 0
height = (b | 0) || width
} else if (!a) {
width = height = 1
} else {
check$1.type(a, 'object', 'invalid arguments for framebuffer')
var options = a
if ('shape' in options) {
var shape = options.shape
check$1(Array.isArray(shape) && shape.length >= 2,
'invalid shape for framebuffer')
width = shape[0]
height = shape[1]
} else {
if ('radius' in options) {
width = height = options.radius
}
if ('width' in options) {
width = options.width
}
if ('height' in options) {
height = options.height
}
}
if ('color' in options ||
'colors' in options) {
colorBuffer =
options.color ||
options.colors
if (Array.isArray(colorBuffer)) {
check$1(
colorBuffer.length === 1 || extensions.webgl_draw_buffers,
'multiple render targets not supported')
}
}
if (!colorBuffer) {
if ('colorCount' in options) {
colorCount = options.colorCount | 0
check$1(colorCount > 0, 'invalid color buffer count')
}
if ('colorTexture' in options) {
colorTexture = !!options.colorTexture
colorFormat = 'rgba4'
}
if ('colorType' in options) {
colorType = options.colorType
if (!colorTexture) {
if (colorType === 'half float' || colorType === 'float16') {
check$1(extensions.ext_color_buffer_half_float,
'you must enable EXT_color_buffer_half_float to use 16-bit render buffers')
colorFormat = 'rgba16f'
} else if (colorType === 'float' || colorType === 'float32') {
check$1(extensions.webgl_color_buffer_float,
'you must enable WEBGL_color_buffer_float in order to use 32-bit floating point renderbuffers')
colorFormat = 'rgba32f'
}
} else {
check$1(extensions.oes_texture_float ||
!(colorType === 'float' || colorType === 'float32'),
'you must enable OES_texture_float in order to use floating point framebuffer objects')
check$1(extensions.oes_texture_half_float ||
!(colorType === 'half float' || colorType === 'float16'),
'you must enable OES_texture_half_float in order to use 16-bit floating point framebuffer objects')
}
check$1.oneOf(colorType, colorTypes, 'invalid color type')
}
if ('colorFormat' in options) {
colorFormat = options.colorFormat
if (colorTextureFormats.indexOf(colorFormat) >= 0) {
colorTexture = true
} else if (colorRenderbufferFormats.indexOf(colorFormat) >= 0) {
colorTexture = false
} else {
if (colorTexture) {
check$1.oneOf(
options.colorFormat, colorTextureFormats,
'invalid color format for texture')
} else {
check$1.oneOf(
options.colorFormat, colorRenderbufferFormats,
'invalid color format for renderbuffer')
}
}
}
}
if ('depthTexture' in options || 'depthStencilTexture' in options) {
depthStencilTexture = !!(options.depthTexture ||
options.depthStencilTexture)
check$1(!depthStencilTexture || extensions.webgl_depth_texture,
'webgl_depth_texture extension not supported')
}
if ('depth' in options) {
if (typeof options.depth === 'boolean') {
needsDepth = options.depth
} else {
depthBuffer = options.depth
needsStencil = false
}
}
if ('stencil' in options) {
if (typeof options.stencil === 'boolean') {
needsStencil = options.stencil
} else {
stencilBuffer = options.stencil
needsDepth = false
}
}
if ('depthStencil' in options) {
if (typeof options.depthStencil === 'boolean') {
needsDepth = needsStencil = options.depthStencil
} else {
depthStencilBuffer = options.depthStencil
needsDepth = false
needsStencil = false
}
}
}
// parse attachments
var colorAttachments = null
var depthAttachment = null
var stencilAttachment = null
var depthStencilAttachment = null
// Set up color attachments
if (Array.isArray(colorBuffer)) {
colorAttachments = colorBuffer.map(parseAttachment)
} else if (colorBuffer) {
colorAttachments = [parseAttachment(colorBuffer)]
} else {
colorAttachments = new Array(colorCount)
for (i = 0; i < colorCount; ++i) {
colorAttachments[i] = allocAttachment(
width,
height,
colorTexture,
colorFormat,
colorType)
}
}
check$1(extensions.webgl_draw_buffers || colorAttachments.length <= 1,
'you must enable the WEBGL_draw_buffers extension in order to use multiple color buffers.')
check$1(colorAttachments.length <= limits.maxColorAttachments,
'too many color attachments, not supported')
width = width || colorAttachments[0].width
height = height || colorAttachments[0].height
if (depthBuffer) {
depthAttachment = parseAttachment(depthBuffer)
} else if (needsDepth && !needsStencil) {
depthAttachment = allocAttachment(
width,
height,
depthStencilTexture,
'depth',
'uint32')
}
if (stencilBuffer) {
stencilAttachment = parseAttachment(stencilBuffer)
} else if (needsStencil && !needsDepth) {
stencilAttachment = allocAttachment(
width,
height,
false,
'stencil',
'uint8')
}
if (depthStencilBuffer) {
depthStencilAttachment = parseAttachment(depthStencilBuffer)
} else if (!depthBuffer && !stencilBuffer && needsStencil && needsDepth) {
depthStencilAttachment = allocAttachment(
width,
height,
depthStencilTexture,
'depth stencil',
'depth stencil')
}
check$1(
(!!depthBuffer) + (!!stencilBuffer) + (!!depthStencilBuffer) <= 1,
'invalid framebuffer configuration, can specify exactly one depth/stencil attachment')
var commonColorAttachmentSize = null
for (i = 0; i < colorAttachments.length; ++i) {
incRefAndCheckShape(colorAttachments[i], width, height)
check$1(!colorAttachments[i] ||
(colorAttachments[i].texture &&
colorTextureFormatEnums.indexOf(colorAttachments[i].texture._texture.format) >= 0) ||
(colorAttachments[i].renderbuffer &&
colorRenderbufferFormatEnums.indexOf(colorAttachments[i].renderbuffer._renderbuffer.format) >= 0),
'framebuffer color attachment ' + i + ' is invalid')
if (colorAttachments[i] && colorAttachments[i].texture) {
var colorAttachmentSize =
textureFormatChannels[colorAttachments[i].texture._texture.format] *
textureTypeSizes[colorAttachments[i].texture._texture.type]
if (commonColorAttachmentSize === null) {
commonColorAttachmentSize = colorAttachmentSize
} else {
// We need to make sure that all color attachments have the same number of bitplanes
// (that is, the same numer of bits per pixel)
// This is required by the GLES2.0 standard. See the beginning of Chapter 4 in that document.
check$1(commonColorAttachmentSize === colorAttachmentSize,
'all color attachments much have the same number of bits per pixel.')
}
}
}
incRefAndCheckShape(depthAttachment, width, height)
check$1(!depthAttachment ||
(depthAttachment.texture &&
depthAttachment.texture._texture.format === GL_DEPTH_COMPONENT$1) ||
(depthAttachment.renderbuffer &&
depthAttachment.renderbuffer._renderbuffer.format === GL_DEPTH_COMPONENT16$1),
'invalid depth attachment for framebuffer object')
incRefAndCheckShape(stencilAttachment, width, height)
check$1(!stencilAttachment ||
(stencilAttachment.renderbuffer &&
stencilAttachment.renderbuffer._renderbuffer.format === GL_STENCIL_INDEX8$1),
'invalid stencil attachment for framebuffer object')
incRefAndCheckShape(depthStencilAttachment, width, height)
check$1(!depthStencilAttachment ||
(depthStencilAttachment.texture &&
depthStencilAttachment.texture._texture.format === GL_DEPTH_STENCIL$2) ||
(depthStencilAttachment.renderbuffer &&
depthStencilAttachment.renderbuffer._renderbuffer.format === GL_DEPTH_STENCIL$2),
'invalid depth-stencil attachment for framebuffer object')
// decrement references
decFBORefs(framebuffer)
framebuffer.width = width
framebuffer.height = height
framebuffer.colorAttachments = colorAttachments
framebuffer.depthAttachment = depthAttachment
framebuffer.stencilAttachment = stencilAttachment
framebuffer.depthStencilAttachment = depthStencilAttachment
reglFramebuffer.color = colorAttachments.map(unwrapAttachment)
reglFramebuffer.depth = unwrapAttachment(depthAttachment)
reglFramebuffer.stencil = unwrapAttachment(stencilAttachment)
reglFramebuffer.depthStencil = unwrapAttachment(depthStencilAttachment)
reglFramebuffer.width = framebuffer.width
reglFramebuffer.height = framebuffer.height
updateFramebuffer(framebuffer)
return reglFramebuffer
}
function resize (w_, h_) {
check$1(framebufferState.next !== framebuffer,
'can not resize a framebuffer which is currently in use')
var w = Math.max(w_ | 0, 1)
var h = Math.max((h_ | 0) || w, 1)
if (w === framebuffer.width && h === framebuffer.height) {
return reglFramebuffer
}
// resize all buffers
var colorAttachments = framebuffer.colorAttachments
for (var i = 0; i < colorAttachments.length; ++i) {
resizeAttachment(colorAttachments[i], w, h)
}
resizeAttachment(framebuffer.depthAttachment, w, h)
resizeAttachment(framebuffer.stencilAttachment, w, h)
resizeAttachment(framebuffer.depthStencilAttachment, w, h)
framebuffer.width = reglFramebuffer.width = w
framebuffer.height = reglFramebuffer.height = h
updateFramebuffer(framebuffer)
return reglFramebuffer
}
reglFramebuffer(a0, a1)
return extend(reglFramebuffer, {
resize: resize,
_reglType: 'framebuffer',
_framebuffer: framebuffer,
destroy: function () {
destroy(framebuffer)
decFBORefs(framebuffer)
},
use: function (block) {
framebufferState.setFBO({
framebuffer: reglFramebuffer
}, block)
}
})
}
function createCubeFBO (options) {
var faces = Array(6)
function reglFramebufferCube (a) {
var i
check$1(faces.indexOf(framebufferState.next) < 0,
'can not update framebuffer which is currently in use')
var params = {
color: null
}
var radius = 0
var colorBuffer = null
var colorFormat = 'rgba'
var colorType = 'uint8'
var colorCount = 1
if (typeof a === 'number') {
radius = a | 0
} else if (!a) {
radius = 1
} else {
check$1.type(a, 'object', 'invalid arguments for framebuffer')
var options = a
if ('shape' in options) {
var shape = options.shape
check$1(
Array.isArray(shape) && shape.length >= 2,
'invalid shape for framebuffer')
check$1(
shape[0] === shape[1],
'cube framebuffer must be square')
radius = shape[0]
} else {
if ('radius' in options) {
radius = options.radius | 0
}
if ('width' in options) {
radius = options.width | 0
if ('height' in options) {
check$1(options.height === radius, 'must be square')
}
} else if ('height' in options) {
radius = options.height | 0
}
}
if ('color' in options ||
'colors' in options) {
colorBuffer =
options.color ||
options.colors
if (Array.isArray(colorBuffer)) {
check$1(
colorBuffer.length === 1 || extensions.webgl_draw_buffers,
'multiple render targets not supported')
}
}
if (!colorBuffer) {
if ('colorCount' in options) {
colorCount = options.colorCount | 0
check$1(colorCount > 0, 'invalid color buffer count')
}
if ('colorType' in options) {
check$1.oneOf(
options.colorType, colorTypes,
'invalid color type')
colorType = options.colorType
}
if ('colorFormat' in options) {
colorFormat = options.colorFormat
check$1.oneOf(
options.colorFormat, colorTextureFormats,
'invalid color format for texture')
}
}
if ('depth' in options) {
params.depth = options.depth
}
if ('stencil' in options) {
params.stencil = options.stencil
}
if ('depthStencil' in options) {
params.depthStencil = options.depthStencil
}
}
var colorCubes
if (colorBuffer) {
if (Array.isArray(colorBuffer)) {
colorCubes = []
for (i = 0; i < colorBuffer.length; ++i) {
colorCubes[i] = colorBuffer[i]
}
} else {
colorCubes = [ colorBuffer ]
}
} else {
colorCubes = Array(colorCount)
var cubeMapParams = {
radius: radius,
format: colorFormat,
type: colorType
}
for (i = 0; i < colorCount; ++i) {
colorCubes[i] = textureState.createCube(cubeMapParams)
}
}
// Check color cubes
params.color = Array(colorCubes.length)
for (i = 0; i < colorCubes.length; ++i) {
var cube = colorCubes[i]
check$1(
typeof cube === 'function' && cube._reglType === 'textureCube',
'invalid cube map')
radius = radius || cube.width
check$1(
cube.width === radius && cube.height === radius,
'invalid cube map shape')
params.color[i] = {
target: GL_TEXTURE_CUBE_MAP_POSITIVE_X$2,
data: colorCubes[i]
}
}
for (i = 0; i < 6; ++i) {
for (var j = 0; j < colorCubes.length; ++j) {
params.color[j].target = GL_TEXTURE_CUBE_MAP_POSITIVE_X$2 + i
}
// reuse depth-stencil attachments across all cube maps
if (i > 0) {
params.depth = faces[0].depth
params.stencil = faces[0].stencil
params.depthStencil = faces[0].depthStencil
}
if (faces[i]) {
(faces[i])(params)
} else {
faces[i] = createFBO(params)
}
}
return extend(reglFramebufferCube, {
width: radius,
height: radius,
color: colorCubes
})
}
function resize (radius_) {
var i
var radius = radius_ | 0
check$1(radius > 0 && radius <= limits.maxCubeMapSize,
'invalid radius for cube fbo')
if (radius === reglFramebufferCube.width) {
return reglFramebufferCube
}
var colors = reglFramebufferCube.color
for (i = 0; i < colors.length; ++i) {
colors[i].resize(radius)
}
for (i = 0; i < 6; ++i) {
faces[i].resize(radius)
}
reglFramebufferCube.width = reglFramebufferCube.height = radius
return reglFramebufferCube
}
reglFramebufferCube(options)
return extend(reglFramebufferCube, {
faces: faces,
resize: resize,
_reglType: 'framebufferCube',
destroy: function () {
faces.forEach(function (f) {
f.destroy()
})
}
})
}
function restoreFramebuffers () {
framebufferState.cur = null
framebufferState.next = null
framebufferState.dirty = true
values(framebufferSet).forEach(function (fb) {
fb.framebuffer = gl.createFramebuffer()
updateFramebuffer(fb)
})
}
return extend(framebufferState, {
getFramebuffer: function (object) {
if (typeof object === 'function' && object._reglType === 'framebuffer') {
var fbo = object._framebuffer
if (fbo instanceof REGLFramebuffer) {
return fbo
}
}
return null
},
create: createFBO,
createCube: createCubeFBO,
clear: function () {
values(framebufferSet).forEach(destroy)
},
restore: restoreFramebuffers
})
}
var GL_FLOAT$6 = 5126
var GL_ARRAY_BUFFER$1 = 34962
function AttributeRecord () {
this.state = 0
this.x = 0.0
this.y = 0.0
this.z = 0.0
this.w = 0.0
this.buffer = null
this.size = 0
this.normalized = false
this.type = GL_FLOAT$6
this.offset = 0
this.stride = 0
this.divisor = 0
}
function wrapAttributeState (
gl,
extensions,
limits,
stats,
bufferState) {
var NUM_ATTRIBUTES = limits.maxAttributes
var attributeBindings = new Array(NUM_ATTRIBUTES)
for (var i = 0; i < NUM_ATTRIBUTES; ++i) {
attributeBindings[i] = new AttributeRecord()
}
var vaoCount = 0
var vaoSet = {}
var state = {
Record: AttributeRecord,
scope: {},
state: attributeBindings,
currentVAO: null,
targetVAO: null,
restore: extVAO() ? restoreVAO : function () {},
createVAO: createVAO,
getVAO: getVAO,
destroyBuffer: destroyBuffer,
setVAO: extVAO() ? setVAOEXT : setVAOEmulated,
clear: extVAO() ? destroyVAOEXT : function () {}
}
function destroyBuffer (buffer) {
for (var i = 0; i < attributeBindings.length; ++i) {
var record = attributeBindings[i]
if (record.buffer === buffer) {
gl.disableVertexAttribArray(i)
record.buffer = null
}
}
}
function extVAO () {
return extensions.oes_vertex_array_object
}
function extInstanced () {
return extensions.angle_instanced_arrays
}
function getVAO (vao) {
if (typeof vao === 'function' && vao._vao) {
return vao._vao
}
return null
}
function setVAOEXT (vao) {
if (vao === state.currentVAO) {
return
}
var ext = extVAO()
if (vao) {
ext.bindVertexArrayOES(vao.vao)
} else {
ext.bindVertexArrayOES(null)
}
state.currentVAO = vao
}
function setVAOEmulated (vao) {
if (vao === state.currentVAO) {
return
}
if (vao) {
vao.bindAttrs()
} else {
var exti = extInstanced()
for (var i = 0; i < attributeBindings.length; ++i) {
var binding = attributeBindings[i]
if (binding.buffer) {
gl.enableVertexAttribArray(i)
gl.vertexAttribPointer(i, binding.size, binding.type, binding.normalized, binding.stride, binding.offfset)
if (exti) {
exti.vertexAttribDivisorANGLE(i, binding.divisor)
}
} else {
gl.disableVertexAttribArray(i)
gl.vertexAttrib4f(i, binding.x, binding.y, binding.z, binding.w)
}
}
}
state.currentVAO = vao
}
function destroyVAOEXT () {
values(vaoSet).forEach(function (vao) {
vao.destroy()
})
}
function REGLVAO () {
this.id = ++vaoCount
this.attributes = []
var extension = extVAO()
if (extension) {
this.vao = extension.createVertexArrayOES()
} else {
this.vao = null
}
vaoSet[this.id] = this
this.buffers = []
}
REGLVAO.prototype.bindAttrs = function () {
var exti = extInstanced()
var attributes = this.attributes
for (var i = 0; i < attributes.length; ++i) {
var attr = attributes[i]
if (attr.buffer) {
gl.enableVertexAttribArray(i)
gl.bindBuffer(GL_ARRAY_BUFFER$1, attr.buffer.buffer)
gl.vertexAttribPointer(i, attr.size, attr.type, attr.normalized, attr.stride, attr.offset)
if (exti) {
exti.vertexAttribDivisorANGLE(i, attr.divisor)
}
} else {
gl.disableVertexAttribArray(i)
gl.vertexAttrib4f(i, attr.x, attr.y, attr.z, attr.w)
}
}
for (var j = attributes.length; j < NUM_ATTRIBUTES; ++j) {
gl.disableVertexAttribArray(j)
}
}
REGLVAO.prototype.refresh = function () {
var ext = extVAO()
if (ext) {
ext.bindVertexArrayOES(this.vao)
this.bindAttrs()
state.currentVAO = this
}
}
REGLVAO.prototype.destroy = function () {
if (this.vao) {
var extension = extVAO()
if (this === state.currentVAO) {
state.currentVAO = null
extension.bindVertexArrayOES(null)
}
extension.deleteVertexArrayOES(this.vao)
this.vao = null
}
if (vaoSet[this.id]) {
delete vaoSet[this.id]
stats.vaoCount -= 1
}
}
function restoreVAO () {
var ext = extVAO()
if (ext) {
values(vaoSet).forEach(function (vao) {
vao.refresh()
})
}
}
function createVAO (_attr) {
var vao = new REGLVAO()
stats.vaoCount += 1
function updateVAO (attributes) {
check$1(Array.isArray(attributes), 'arguments to vertex array constructor must be an array')
check$1(attributes.length < NUM_ATTRIBUTES, 'too many attributes')
check$1(attributes.length > 0, 'must specify at least one attribute')
for (var j = 0; j < vao.buffers.length; ++j) {
vao.buffers[j].destroy()
}
vao.buffers.length = 0
var nattributes = vao.attributes
nattributes.length = attributes.length
for (var i = 0; i < attributes.length; ++i) {
var spec = attributes[i]
var rec = nattributes[i] = new AttributeRecord()
if (Array.isArray(spec) || isTypedArray(spec) || isNDArrayLike(spec)) {
var buf = bufferState.create(spec, GL_ARRAY_BUFFER$1, false, true)
rec.buffer = bufferState.getBuffer(buf)
rec.size = rec.buffer.dimension | 0
rec.normalized = false
rec.type = rec.buffer.dtype
rec.offset = 0
rec.stride = 0
rec.divisor = 0
rec.state = 1
vao.buffers.push(buf)
} else if (bufferState.getBuffer(spec)) {
rec.buffer = bufferState.getBuffer(spec)
rec.size = rec.buffer.dimension | 0
rec.normalized = false
rec.type = rec.buffer.dtype
rec.offset = 0
rec.stride = 0
rec.divisor = 0
rec.state = 1
} else if (bufferState.getBuffer(spec.buffer)) {
rec.buffer = bufferState.getBuffer(spec.buffer)
rec.size = ((+spec.size) || rec.buffer.dimension) | 0
rec.normalized = !!spec.normalized || false
if ('type' in spec) {
check$1.parameter(spec.type, glTypes, 'invalid buffer type')
rec.type = glTypes[spec.type]
} else {
rec.type = rec.buffer.dtype
}
rec.offset = (spec.offset || 0) | 0
rec.stride = (spec.stride || 0) | 0
rec.divisor = (spec.divisor || 0) | 0
rec.state = 1
check$1(rec.size >= 1 && rec.size <= 4, 'size must be between 1 and 4')
check$1(rec.offset >= 0, 'invalid offset')
check$1(rec.stride >= 0 && rec.stride <= 255, 'stride must be between 0 and 255')
check$1(rec.divisor >= 0, 'divisor must be positive')
check$1(!rec.divisor || !!extensions.angle_instanced_arrays, 'ANGLE_instanced_arrays must be enabled to use divisor')
} else if ('x' in spec) {
check$1(i > 0, 'first attribute must not be a constant')
rec.x = +spec.x || 0
rec.y = +spec.y || 0
rec.z = +spec.z || 0
rec.w = +spec.w || 0
rec.state = 2
} else {
check$1(false, 'invalid attribute spec for location ' + i)
}
}
vao.refresh()
return updateVAO
}
updateVAO.destroy = function () {
vao.destroy()
}
updateVAO._vao = vao
updateVAO._reglType = 'vao'
return updateVAO(_attr)
}
return state
}
var GL_FRAGMENT_SHADER = 35632
var GL_VERTEX_SHADER = 35633
var GL_ACTIVE_UNIFORMS = 0x8B86
var GL_ACTIVE_ATTRIBUTES = 0x8B89
function wrapShaderState (gl, stringStore, stats, config) {
// ===================================================
// glsl compilation and linking
// ===================================================
var fragShaders = {}
var vertShaders = {}
function ActiveInfo (name, id, location, info) {
this.name = name
this.id = id
this.location = location
this.info = info
}
function insertActiveInfo (list, info) {
for (var i = 0; i < list.length; ++i) {
if (list[i].id === info.id) {
list[i].location = info.location
return
}
}
list.push(info)
}
function getShader (type, id, command) {
var cache = type === GL_FRAGMENT_SHADER ? fragShaders : vertShaders
var shader = cache[id]
if (!shader) {
var source = stringStore.str(id)
shader = gl.createShader(type)
gl.shaderSource(shader, source)
gl.compileShader(shader)
check$1.shaderError(gl, shader, source, type, command)
cache[id] = shader
}
return shader
}
// ===================================================
// program linking
// ===================================================
var programCache = {}
var programList = []
var PROGRAM_COUNTER = 0
function REGLProgram (fragId, vertId) {
this.id = PROGRAM_COUNTER++
this.fragId = fragId
this.vertId = vertId
this.program = null
this.uniforms = []
this.attributes = []
if (config.profile) {
this.stats = {
uniformsCount: 0,
attributesCount: 0
}
}
}
function linkProgram (desc, command, attributeLocations) {
var i, info
// -------------------------------
// compile & link
// -------------------------------
var fragShader = getShader(GL_FRAGMENT_SHADER, desc.fragId)
var vertShader = getShader(GL_VERTEX_SHADER, desc.vertId)
var program = desc.program = gl.createProgram()
gl.attachShader(program, fragShader)
gl.attachShader(program, vertShader)
if (attributeLocations) {
for (i = 0; i < attributeLocations.length; ++i) {
var binding = attributeLocations[i]
gl.bindAttribLocation(program, binding[0], binding[1])
}
}
gl.linkProgram(program)
check$1.linkError(
gl,
program,
stringStore.str(desc.fragId),
stringStore.str(desc.vertId),
command)
// -------------------------------
// grab uniforms
// -------------------------------
var numUniforms = gl.getProgramParameter(program, GL_ACTIVE_UNIFORMS)
if (config.profile) {
desc.stats.uniformsCount = numUniforms
}
var uniforms = desc.uniforms
for (i = 0; i < numUniforms; ++i) {
info = gl.getActiveUniform(program, i)
if (info) {
if (info.size > 1) {
for (var j = 0; j < info.size; ++j) {
var name = info.name.replace('[0]', '[' + j + ']')
insertActiveInfo(uniforms, new ActiveInfo(
name,
stringStore.id(name),
gl.getUniformLocation(program, name),
info))
}
} else {
insertActiveInfo(uniforms, new ActiveInfo(
info.name,
stringStore.id(info.name),
gl.getUniformLocation(program, info.name),
info))
}
}
}
// -------------------------------
// grab attributes
// -------------------------------
var numAttributes = gl.getProgramParameter(program, GL_ACTIVE_ATTRIBUTES)
if (config.profile) {
desc.stats.attributesCount = numAttributes
}
var attributes = desc.attributes
for (i = 0; i < numAttributes; ++i) {
info = gl.getActiveAttrib(program, i)
if (info) {
insertActiveInfo(attributes, new ActiveInfo(
info.name,
stringStore.id(info.name),
gl.getAttribLocation(program, info.name),
info))
}
}
}
if (config.profile) {
stats.getMaxUniformsCount = function () {
var m = 0
programList.forEach(function (desc) {
if (desc.stats.uniformsCount > m) {
m = desc.stats.uniformsCount
}
})
return m
}
stats.getMaxAttributesCount = function () {
var m = 0
programList.forEach(function (desc) {
if (desc.stats.attributesCount > m) {
m = desc.stats.attributesCount
}
})
return m
}
}
function restoreShaders () {
fragShaders = {}
vertShaders = {}
for (var i = 0; i < programList.length; ++i) {
linkProgram(programList[i], null, programList[i].attributes.map(function (info) {
return [info.location, info.name]
}))
}
}
return {
clear: function () {
var deleteShader = gl.deleteShader.bind(gl)
values(fragShaders).forEach(deleteShader)
fragShaders = {}
values(vertShaders).forEach(deleteShader)
vertShaders = {}
programList.forEach(function (desc) {
gl.deleteProgram(desc.program)
})
programList.length = 0
programCache = {}
stats.shaderCount = 0
},
program: function (vertId, fragId, command, attribLocations) {
check$1.command(vertId >= 0, 'missing vertex shader', command)
check$1.command(fragId >= 0, 'missing fragment shader', command)
var cache = programCache[fragId]
if (!cache) {
cache = programCache[fragId] = {}
}
var prevProgram = cache[vertId]
if (prevProgram && !attribLocations) {
return prevProgram
}
var program = new REGLProgram(fragId, vertId)
stats.shaderCount++
linkProgram(program, command, attribLocations)
if (!prevProgram) {
cache[vertId] = program
}
programList.push(program)
return program
},
restore: restoreShaders,
shader: getShader,
frag: -1,
vert: -1
}
}
var GL_RGBA$3 = 6408
var GL_UNSIGNED_BYTE$7 = 5121
var GL_PACK_ALIGNMENT = 0x0D05
var GL_FLOAT$7 = 0x1406 // 5126
function wrapReadPixels (
gl,
framebufferState,
reglPoll,
context,
glAttributes,
extensions,
limits) {
function readPixelsImpl (input) {
var type
if (framebufferState.next === null) {
check$1(
glAttributes.preserveDrawingBuffer,
'you must create a webgl context with "preserveDrawingBuffer":true in order to read pixels from the drawing buffer')
type = GL_UNSIGNED_BYTE$7
} else {
check$1(
framebufferState.next.colorAttachments[0].texture !== null,
'You cannot read from a renderbuffer')
type = framebufferState.next.colorAttachments[0].texture._texture.type
if (extensions.oes_texture_float) {
check$1(
type === GL_UNSIGNED_BYTE$7 || type === GL_FLOAT$7,
'Reading from a framebuffer is only allowed for the types \'uint8\' and \'float\'')
if (type === GL_FLOAT$7) {
check$1(limits.readFloat, 'Reading \'float\' values is not permitted in your browser. For a fallback, please see: https://www.npmjs.com/package/glsl-read-float')
}
} else {
check$1(
type === GL_UNSIGNED_BYTE$7,
'Reading from a framebuffer is only allowed for the type \'uint8\'')
}
}
var x = 0
var y = 0
var width = context.framebufferWidth
var height = context.framebufferHeight
var data = null
if (isTypedArray(input)) {
data = input
} else if (input) {
check$1.type(input, 'object', 'invalid arguments to regl.read()')
x = input.x | 0
y = input.y | 0
check$1(
x >= 0 && x < context.framebufferWidth,
'invalid x offset for regl.read')
check$1(
y >= 0 && y < context.framebufferHeight,
'invalid y offset for regl.read')
width = (input.width || (context.framebufferWidth - x)) | 0
height = (input.height || (context.framebufferHeight - y)) | 0
data = input.data || null
}
// sanity check input.data
if (data) {
if (type === GL_UNSIGNED_BYTE$7) {
check$1(
data instanceof Uint8Array,
'buffer must be \'Uint8Array\' when reading from a framebuffer of type \'uint8\'')
} else if (type === GL_FLOAT$7) {
check$1(
data instanceof Float32Array,
'buffer must be \'Float32Array\' when reading from a framebuffer of type \'float\'')
}
}
check$1(
width > 0 && width + x <= context.framebufferWidth,
'invalid width for read pixels')
check$1(
height > 0 && height + y <= context.framebufferHeight,
'invalid height for read pixels')
// Update WebGL state
reglPoll()
// Compute size
var size = width * height * 4
// Allocate data
if (!data) {
if (type === GL_UNSIGNED_BYTE$7) {
data = new Uint8Array(size)
} else if (type === GL_FLOAT$7) {
data = data || new Float32Array(size)
}
}
// Type check
check$1.isTypedArray(data, 'data buffer for regl.read() must be a typedarray')
check$1(data.byteLength >= size, 'data buffer for regl.read() too small')
// Run read pixels
gl.pixelStorei(GL_PACK_ALIGNMENT, 4)
gl.readPixels(x, y, width, height, GL_RGBA$3,
type,
data)
return data
}
function readPixelsFBO (options) {
var result
framebufferState.setFBO({
framebuffer: options.framebuffer
}, function () {
result = readPixelsImpl(options)
})
return result
}
function readPixels (options) {
if (!options || !('framebuffer' in options)) {
return readPixelsImpl(options)
} else {
return readPixelsFBO(options)
}
}
return readPixels
}
function slice (x) {
return Array.prototype.slice.call(x)
}
function join (x) {
return slice(x).join('')
}
function createEnvironment () {
// Unique variable id counter
var varCounter = 0
// Linked values are passed from this scope into the generated code block
// Calling link() passes a value into the generated scope and returns
// the variable name which it is bound to
var linkedNames = []
var linkedValues = []
function link (value) {
for (var i = 0; i < linkedValues.length; ++i) {
if (linkedValues[i] === value) {
return linkedNames[i]
}
}
var name = 'g' + (varCounter++)
linkedNames.push(name)
linkedValues.push(value)
return name
}
// create a code block
function block () {
var code = []
function push () {
code.push.apply(code, slice(arguments))
}
var vars = []
function def () {
var name = 'v' + (varCounter++)
vars.push(name)
if (arguments.length > 0) {
code.push(name, '=')
code.push.apply(code, slice(arguments))
code.push(';')
}
return name
}
return extend(push, {
def: def,
toString: function () {
return join([
(vars.length > 0 ? 'var ' + vars.join(',') + ';' : ''),
join(code)
])
}
})
}
function scope () {
var entry = block()
var exit = block()
var entryToString = entry.toString
var exitToString = exit.toString
function save (object, prop) {
exit(object, prop, '=', entry.def(object, prop), ';')
}
return extend(function () {
entry.apply(entry, slice(arguments))
}, {
def: entry.def,
entry: entry,
exit: exit,
save: save,
set: function (object, prop, value) {
save(object, prop)
entry(object, prop, '=', value, ';')
},
toString: function () {
return entryToString() + exitToString()
}
})
}
function conditional () {
var pred = join(arguments)
var thenBlock = scope()
var elseBlock = scope()
var thenToString = thenBlock.toString
var elseToString = elseBlock.toString
return extend(thenBlock, {
then: function () {
thenBlock.apply(thenBlock, slice(arguments))
return this
},
else: function () {
elseBlock.apply(elseBlock, slice(arguments))
return this
},
toString: function () {
var elseClause = elseToString()
if (elseClause) {
elseClause = 'else{' + elseClause + '}'
}
return join([
'if(', pred, '){',
thenToString(),
'}', elseClause
])
}
})
}
// procedure list
var globalBlock = block()
var procedures = {}
function proc (name, count) {
var args = []
function arg () {
var name = 'a' + args.length
args.push(name)
return name
}
count = count || 0
for (var i = 0; i < count; ++i) {
arg()
}
var body = scope()
var bodyToString = body.toString
var result = procedures[name] = extend(body, {
arg: arg,
toString: function () {
return join([
'function(', args.join(), '){',
bodyToString(),
'}'
])
}
})
return result
}
function compile () {
var code = ['"use strict";',
globalBlock,
'return {']
Object.keys(procedures).forEach(function (name) {
code.push('"', name, '":', procedures[name].toString(), ',')
})
code.push('}')
var src = join(code)
.replace(/;/g, ';\n')
.replace(/}/g, '}\n')
.replace(/{/g, '{\n')
var proc = Function.apply(null, linkedNames.concat(src))
return proc.apply(null, linkedValues)
}
return {
global: globalBlock,
link: link,
block: block,
proc: proc,
scope: scope,
cond: conditional,
compile: compile
}
}
// "cute" names for vector components
var CUTE_COMPONENTS = 'xyzw'.split('')
var GL_UNSIGNED_BYTE$8 = 5121
var ATTRIB_STATE_POINTER = 1
var ATTRIB_STATE_CONSTANT = 2
var DYN_FUNC$1 = 0
var DYN_PROP$1 = 1
var DYN_CONTEXT$1 = 2
var DYN_STATE$1 = 3
var DYN_THUNK = 4
var S_DITHER = 'dither'
var S_BLEND_ENABLE = 'blend.enable'
var S_BLEND_COLOR = 'blend.color'
var S_BLEND_EQUATION = 'blend.equation'
var S_BLEND_FUNC = 'blend.func'
var S_DEPTH_ENABLE = 'depth.enable'
var S_DEPTH_FUNC = 'depth.func'
var S_DEPTH_RANGE = 'depth.range'
var S_DEPTH_MASK = 'depth.mask'
var S_COLOR_MASK = 'colorMask'
var S_CULL_ENABLE = 'cull.enable'
var S_CULL_FACE = 'cull.face'
var S_FRONT_FACE = 'frontFace'
var S_LINE_WIDTH = 'lineWidth'
var S_POLYGON_OFFSET_ENABLE = 'polygonOffset.enable'
var S_POLYGON_OFFSET_OFFSET = 'polygonOffset.offset'
var S_SAMPLE_ALPHA = 'sample.alpha'
var S_SAMPLE_ENABLE = 'sample.enable'
var S_SAMPLE_COVERAGE = 'sample.coverage'
var S_STENCIL_ENABLE = 'stencil.enable'
var S_STENCIL_MASK = 'stencil.mask'
var S_STENCIL_FUNC = 'stencil.func'
var S_STENCIL_OPFRONT = 'stencil.opFront'
var S_STENCIL_OPBACK = 'stencil.opBack'
var S_SCISSOR_ENABLE = 'scissor.enable'
var S_SCISSOR_BOX = 'scissor.box'
var S_VIEWPORT = 'viewport'
var S_PROFILE = 'profile'
var S_FRAMEBUFFER = 'framebuffer'
var S_VERT = 'vert'
var S_FRAG = 'frag'
var S_ELEMENTS = 'elements'
var S_PRIMITIVE = 'primitive'
var S_COUNT = 'count'
var S_OFFSET = 'offset'
var S_INSTANCES = 'instances'
var S_VAO = 'vao'
var SUFFIX_WIDTH = 'Width'
var SUFFIX_HEIGHT = 'Height'
var S_FRAMEBUFFER_WIDTH = S_FRAMEBUFFER + SUFFIX_WIDTH
var S_FRAMEBUFFER_HEIGHT = S_FRAMEBUFFER + SUFFIX_HEIGHT
var S_VIEWPORT_WIDTH = S_VIEWPORT + SUFFIX_WIDTH
var S_VIEWPORT_HEIGHT = S_VIEWPORT + SUFFIX_HEIGHT
var S_DRAWINGBUFFER = 'drawingBuffer'
var S_DRAWINGBUFFER_WIDTH = S_DRAWINGBUFFER + SUFFIX_WIDTH
var S_DRAWINGBUFFER_HEIGHT = S_DRAWINGBUFFER + SUFFIX_HEIGHT
var NESTED_OPTIONS = [
S_BLEND_FUNC,
S_BLEND_EQUATION,
S_STENCIL_FUNC,
S_STENCIL_OPFRONT,
S_STENCIL_OPBACK,
S_SAMPLE_COVERAGE,
S_VIEWPORT,
S_SCISSOR_BOX,
S_POLYGON_OFFSET_OFFSET
]
var GL_ARRAY_BUFFER$2 = 34962
var GL_ELEMENT_ARRAY_BUFFER$1 = 34963
var GL_FRAGMENT_SHADER$1 = 35632
var GL_VERTEX_SHADER$1 = 35633
var GL_TEXTURE_2D$3 = 0x0DE1
var GL_TEXTURE_CUBE_MAP$2 = 0x8513
var GL_CULL_FACE = 0x0B44
var GL_BLEND = 0x0BE2
var GL_DITHER = 0x0BD0
var GL_STENCIL_TEST = 0x0B90
var GL_DEPTH_TEST = 0x0B71
var GL_SCISSOR_TEST = 0x0C11
var GL_POLYGON_OFFSET_FILL = 0x8037
var GL_SAMPLE_ALPHA_TO_COVERAGE = 0x809E
var GL_SAMPLE_COVERAGE = 0x80A0
var GL_FLOAT$8 = 5126
var GL_FLOAT_VEC2 = 35664
var GL_FLOAT_VEC3 = 35665
var GL_FLOAT_VEC4 = 35666
var GL_INT$3 = 5124
var GL_INT_VEC2 = 35667
var GL_INT_VEC3 = 35668
var GL_INT_VEC4 = 35669
var GL_BOOL = 35670
var GL_BOOL_VEC2 = 35671
var GL_BOOL_VEC3 = 35672
var GL_BOOL_VEC4 = 35673
var GL_FLOAT_MAT2 = 35674
var GL_FLOAT_MAT3 = 35675
var GL_FLOAT_MAT4 = 35676
var GL_SAMPLER_2D = 35678
var GL_SAMPLER_CUBE = 35680
var GL_TRIANGLES$1 = 4
var GL_FRONT = 1028
var GL_BACK = 1029
var GL_CW = 0x0900
var GL_CCW = 0x0901
var GL_MIN_EXT = 0x8007
var GL_MAX_EXT = 0x8008
var GL_ALWAYS = 519
var GL_KEEP = 7680
var GL_ZERO = 0
var GL_ONE = 1
var GL_FUNC_ADD = 0x8006
var GL_LESS = 513
var GL_FRAMEBUFFER$2 = 0x8D40
var GL_COLOR_ATTACHMENT0$2 = 0x8CE0
var blendFuncs = {
'0': 0,
'1': 1,
'zero': 0,
'one': 1,
'src color': 768,
'one minus src color': 769,
'src alpha': 770,
'one minus src alpha': 771,
'dst color': 774,
'one minus dst color': 775,
'dst alpha': 772,
'one minus dst alpha': 773,
'constant color': 32769,
'one minus constant color': 32770,
'constant alpha': 32771,
'one minus constant alpha': 32772,
'src alpha saturate': 776
}
// There are invalid values for srcRGB and dstRGB. See:
// https://www.khronos.org/registry/webgl/specs/1.0/#6.13
// https://github.com/KhronosGroup/WebGL/blob/0d3201f5f7ec3c0060bc1f04077461541f1987b9/conformance-suites/1.0.3/conformance/misc/webgl-specific.html#L56
var invalidBlendCombinations = [
'constant color, constant alpha',
'one minus constant color, constant alpha',
'constant color, one minus constant alpha',
'one minus constant color, one minus constant alpha',
'constant alpha, constant color',
'constant alpha, one minus constant color',
'one minus constant alpha, constant color',
'one minus constant alpha, one minus constant color'
]
var compareFuncs = {
'never': 512,
'less': 513,
'<': 513,
'equal': 514,
'=': 514,
'==': 514,
'===': 514,
'lequal': 515,
'<=': 515,
'greater': 516,
'>': 516,
'notequal': 517,
'!=': 517,
'!==': 517,
'gequal': 518,
'>=': 518,
'always': 519
}
var stencilOps = {
'0': 0,
'zero': 0,
'keep': 7680,
'replace': 7681,
'increment': 7682,
'decrement': 7683,
'increment wrap': 34055,
'decrement wrap': 34056,
'invert': 5386
}
var shaderType = {
'frag': GL_FRAGMENT_SHADER$1,
'vert': GL_VERTEX_SHADER$1
}
var orientationType = {
'cw': GL_CW,
'ccw': GL_CCW
}
function isBufferArgs (x) {
return Array.isArray(x) ||
isTypedArray(x) ||
isNDArrayLike(x)
}
// Make sure viewport is processed first
function sortState (state) {
return state.sort(function (a, b) {
if (a === S_VIEWPORT) {
return -1
} else if (b === S_VIEWPORT) {
return 1
}
return (a < b) ? -1 : 1
})
}
function Declaration (thisDep, contextDep, propDep, append) {
this.thisDep = thisDep
this.contextDep = contextDep
this.propDep = propDep
this.append = append
}
function isStatic (decl) {
return decl && !(decl.thisDep || decl.contextDep || decl.propDep)
}
function createStaticDecl (append) {
return new Declaration(false, false, false, append)
}
function createDynamicDecl (dyn, append) {
var type = dyn.type
if (type === DYN_FUNC$1) {
var numArgs = dyn.data.length
return new Declaration(
true,
numArgs >= 1,
numArgs >= 2,
append)
} else if (type === DYN_THUNK) {
var data = dyn.data
return new Declaration(
data.thisDep,
data.contextDep,
data.propDep,
append)
} else {
return new Declaration(
type === DYN_STATE$1,
type === DYN_CONTEXT$1,
type === DYN_PROP$1,
append)
}
}
var SCOPE_DECL = new Declaration(false, false, false, function () {})
function reglCore (
gl,
stringStore,
extensions,
limits,
bufferState,
elementState,
textureState,
framebufferState,
uniformState,
attributeState,
shaderState,
drawState,
contextState,
timer,
config) {
var AttributeRecord = attributeState.Record
var blendEquations = {
'add': 32774,
'subtract': 32778,
'reverse subtract': 32779
}
if (extensions.ext_blend_minmax) {
blendEquations.min = GL_MIN_EXT
blendEquations.max = GL_MAX_EXT
}
var extInstancing = extensions.angle_instanced_arrays
var extDrawBuffers = extensions.webgl_draw_buffers
// ===================================================
// ===================================================
// WEBGL STATE
// ===================================================
// ===================================================
var currentState = {
dirty: true,
profile: config.profile
}
var nextState = {}
var GL_STATE_NAMES = []
var GL_FLAGS = {}
var GL_VARIABLES = {}
function propName (name) {
return name.replace('.', '_')
}
function stateFlag (sname, cap, init) {
var name = propName(sname)
GL_STATE_NAMES.push(sname)
nextState[name] = currentState[name] = !!init
GL_FLAGS[name] = cap
}
function stateVariable (sname, func, init) {
var name = propName(sname)
GL_STATE_NAMES.push(sname)
if (Array.isArray(init)) {
currentState[name] = init.slice()
nextState[name] = init.slice()
} else {
currentState[name] = nextState[name] = init
}
GL_VARIABLES[name] = func
}
// Dithering
stateFlag(S_DITHER, GL_DITHER)
// Blending
stateFlag(S_BLEND_ENABLE, GL_BLEND)
stateVariable(S_BLEND_COLOR, 'blendColor', [0, 0, 0, 0])
stateVariable(S_BLEND_EQUATION, 'blendEquationSeparate',
[GL_FUNC_ADD, GL_FUNC_ADD])
stateVariable(S_BLEND_FUNC, 'blendFuncSeparate',
[GL_ONE, GL_ZERO, GL_ONE, GL_ZERO])
// Depth
stateFlag(S_DEPTH_ENABLE, GL_DEPTH_TEST, true)
stateVariable(S_DEPTH_FUNC, 'depthFunc', GL_LESS)
stateVariable(S_DEPTH_RANGE, 'depthRange', [0, 1])
stateVariable(S_DEPTH_MASK, 'depthMask', true)
// Color mask
stateVariable(S_COLOR_MASK, S_COLOR_MASK, [true, true, true, true])
// Face culling
stateFlag(S_CULL_ENABLE, GL_CULL_FACE)
stateVariable(S_CULL_FACE, 'cullFace', GL_BACK)
// Front face orientation
stateVariable(S_FRONT_FACE, S_FRONT_FACE, GL_CCW)
// Line width
stateVariable(S_LINE_WIDTH, S_LINE_WIDTH, 1)
// Polygon offset
stateFlag(S_POLYGON_OFFSET_ENABLE, GL_POLYGON_OFFSET_FILL)
stateVariable(S_POLYGON_OFFSET_OFFSET, 'polygonOffset', [0, 0])
// Sample coverage
stateFlag(S_SAMPLE_ALPHA, GL_SAMPLE_ALPHA_TO_COVERAGE)
stateFlag(S_SAMPLE_ENABLE, GL_SAMPLE_COVERAGE)
stateVariable(S_SAMPLE_COVERAGE, 'sampleCoverage', [1, false])
// Stencil
stateFlag(S_STENCIL_ENABLE, GL_STENCIL_TEST)
stateVariable(S_STENCIL_MASK, 'stencilMask', -1)
stateVariable(S_STENCIL_FUNC, 'stencilFunc', [GL_ALWAYS, 0, -1])
stateVariable(S_STENCIL_OPFRONT, 'stencilOpSeparate',
[GL_FRONT, GL_KEEP, GL_KEEP, GL_KEEP])
stateVariable(S_STENCIL_OPBACK, 'stencilOpSeparate',
[GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP])
// Scissor
stateFlag(S_SCISSOR_ENABLE, GL_SCISSOR_TEST)
stateVariable(S_SCISSOR_BOX, 'scissor',
[0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight])
// Viewport
stateVariable(S_VIEWPORT, S_VIEWPORT,
[0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight])
// ===================================================
// ===================================================
// ENVIRONMENT
// ===================================================
// ===================================================
var sharedState = {
gl: gl,
context: contextState,
strings: stringStore,
next: nextState,
current: currentState,
draw: drawState,
elements: elementState,
buffer: bufferState,
shader: shaderState,
attributes: attributeState.state,
vao: attributeState,
uniforms: uniformState,
framebuffer: framebufferState,
extensions: extensions,
timer: timer,
isBufferArgs: isBufferArgs
}
var sharedConstants = {
primTypes: primTypes,
compareFuncs: compareFuncs,
blendFuncs: blendFuncs,
blendEquations: blendEquations,
stencilOps: stencilOps,
glTypes: glTypes,
orientationType: orientationType
}
check$1.optional(function () {
sharedState.isArrayLike = isArrayLike
})
if (extDrawBuffers) {
sharedConstants.backBuffer = [GL_BACK]
sharedConstants.drawBuffer = loop(limits.maxDrawbuffers, function (i) {
if (i === 0) {
return [0]
}
return loop(i, function (j) {
return GL_COLOR_ATTACHMENT0$2 + j
})
})
}
var drawCallCounter = 0
function createREGLEnvironment () {
var env = createEnvironment()
var link = env.link
var global = env.global
env.id = drawCallCounter++
env.batchId = '0'
// link shared state
var SHARED = link(sharedState)
var shared = env.shared = {
props: 'a0'
}
Object.keys(sharedState).forEach(function (prop) {
shared[prop] = global.def(SHARED, '.', prop)
})
// Inject runtime assertion stuff for debug builds
check$1.optional(function () {
env.CHECK = link(check$1)
env.commandStr = check$1.guessCommand()
env.command = link(env.commandStr)
env.assert = function (block, pred, message) {
block(
'if(!(', pred, '))',
this.CHECK, '.commandRaise(', link(message), ',', this.command, ');')
}
sharedConstants.invalidBlendCombinations = invalidBlendCombinations
})
// Copy GL state variables over
var nextVars = env.next = {}
var currentVars = env.current = {}
Object.keys(GL_VARIABLES).forEach(function (variable) {
if (Array.isArray(currentState[variable])) {
nextVars[variable] = global.def(shared.next, '.', variable)
currentVars[variable] = global.def(shared.current, '.', variable)
}
})
// Initialize shared constants
var constants = env.constants = {}
Object.keys(sharedConstants).forEach(function (name) {
constants[name] = global.def(JSON.stringify(sharedConstants[name]))
})
// Helper function for calling a block
env.invoke = function (block, x) {
switch (x.type) {
case DYN_FUNC$1:
var argList = [
'this',
shared.context,
shared.props,
env.batchId
]
return block.def(
link(x.data), '.call(',
argList.slice(0, Math.max(x.data.length + 1, 4)),
')')
case DYN_PROP$1:
return block.def(shared.props, x.data)
case DYN_CONTEXT$1:
return block.def(shared.context, x.data)
case DYN_STATE$1:
return block.def('this', x.data)
case DYN_THUNK:
x.data.append(env, block)
return x.data.ref
}
}
env.attribCache = {}
var scopeAttribs = {}
env.scopeAttrib = function (name) {
var id = stringStore.id(name)
if (id in scopeAttribs) {
return scopeAttribs[id]
}
var binding = attributeState.scope[id]
if (!binding) {
binding = attributeState.scope[id] = new AttributeRecord()
}
var result = scopeAttribs[id] = link(binding)
return result
}
return env
}
// ===================================================
// ===================================================
// PARSING
// ===================================================
// ===================================================
function parseProfile (options) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
var profileEnable
if (S_PROFILE in staticOptions) {
var value = !!staticOptions[S_PROFILE]
profileEnable = createStaticDecl(function (env, scope) {
return value
})
profileEnable.enable = value
} else if (S_PROFILE in dynamicOptions) {
var dyn = dynamicOptions[S_PROFILE]
profileEnable = createDynamicDecl(dyn, function (env, scope) {
return env.invoke(scope, dyn)
})
}
return profileEnable
}
function parseFramebuffer (options, env) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
if (S_FRAMEBUFFER in staticOptions) {
var framebuffer = staticOptions[S_FRAMEBUFFER]
if (framebuffer) {
framebuffer = framebufferState.getFramebuffer(framebuffer)
check$1.command(framebuffer, 'invalid framebuffer object')
return createStaticDecl(function (env, block) {
var FRAMEBUFFER = env.link(framebuffer)
var shared = env.shared
block.set(
shared.framebuffer,
'.next',
FRAMEBUFFER)
var CONTEXT = shared.context
block.set(
CONTEXT,
'.' + S_FRAMEBUFFER_WIDTH,
FRAMEBUFFER + '.width')
block.set(
CONTEXT,
'.' + S_FRAMEBUFFER_HEIGHT,
FRAMEBUFFER + '.height')
return FRAMEBUFFER
})
} else {
return createStaticDecl(function (env, scope) {
var shared = env.shared
scope.set(
shared.framebuffer,
'.next',
'null')
var CONTEXT = shared.context
scope.set(
CONTEXT,
'.' + S_FRAMEBUFFER_WIDTH,
CONTEXT + '.' + S_DRAWINGBUFFER_WIDTH)
scope.set(
CONTEXT,
'.' + S_FRAMEBUFFER_HEIGHT,
CONTEXT + '.' + S_DRAWINGBUFFER_HEIGHT)
return 'null'
})
}
} else if (S_FRAMEBUFFER in dynamicOptions) {
var dyn = dynamicOptions[S_FRAMEBUFFER]
return createDynamicDecl(dyn, function (env, scope) {
var FRAMEBUFFER_FUNC = env.invoke(scope, dyn)
var shared = env.shared
var FRAMEBUFFER_STATE = shared.framebuffer
var FRAMEBUFFER = scope.def(
FRAMEBUFFER_STATE, '.getFramebuffer(', FRAMEBUFFER_FUNC, ')')
check$1.optional(function () {
env.assert(scope,
'!' + FRAMEBUFFER_FUNC + '||' + FRAMEBUFFER,
'invalid framebuffer object')
})
scope.set(
FRAMEBUFFER_STATE,
'.next',
FRAMEBUFFER)
var CONTEXT = shared.context
scope.set(
CONTEXT,
'.' + S_FRAMEBUFFER_WIDTH,
FRAMEBUFFER + '?' + FRAMEBUFFER + '.width:' +
CONTEXT + '.' + S_DRAWINGBUFFER_WIDTH)
scope.set(
CONTEXT,
'.' + S_FRAMEBUFFER_HEIGHT,
FRAMEBUFFER +
'?' + FRAMEBUFFER + '.height:' +
CONTEXT + '.' + S_DRAWINGBUFFER_HEIGHT)
return FRAMEBUFFER
})
} else {
return null
}
}
function parseViewportScissor (options, framebuffer, env) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
function parseBox (param) {
if (param in staticOptions) {
var box = staticOptions[param]
check$1.commandType(box, 'object', 'invalid ' + param, env.commandStr)
var isStatic = true
var x = box.x | 0
var y = box.y | 0
var w, h
if ('width' in box) {
w = box.width | 0
check$1.command(w >= 0, 'invalid ' + param, env.commandStr)
} else {
isStatic = false
}
if ('height' in box) {
h = box.height | 0
check$1.command(h >= 0, 'invalid ' + param, env.commandStr)
} else {
isStatic = false
}
return new Declaration(
!isStatic && framebuffer && framebuffer.thisDep,
!isStatic && framebuffer && framebuffer.contextDep,
!isStatic && framebuffer && framebuffer.propDep,
function (env, scope) {
var CONTEXT = env.shared.context
var BOX_W = w
if (!('width' in box)) {
BOX_W = scope.def(CONTEXT, '.', S_FRAMEBUFFER_WIDTH, '-', x)
}
var BOX_H = h
if (!('height' in box)) {
BOX_H = scope.def(CONTEXT, '.', S_FRAMEBUFFER_HEIGHT, '-', y)
}
return [x, y, BOX_W, BOX_H]
})
} else if (param in dynamicOptions) {
var dynBox = dynamicOptions[param]
var result = createDynamicDecl(dynBox, function (env, scope) {
var BOX = env.invoke(scope, dynBox)
check$1.optional(function () {
env.assert(scope,
BOX + '&&typeof ' + BOX + '==="object"',
'invalid ' + param)
})
var CONTEXT = env.shared.context
var BOX_X = scope.def(BOX, '.x|0')
var BOX_Y = scope.def(BOX, '.y|0')
var BOX_W = scope.def(
'"width" in ', BOX, '?', BOX, '.width|0:',
'(', CONTEXT, '.', S_FRAMEBUFFER_WIDTH, '-', BOX_X, ')')
var BOX_H = scope.def(
'"height" in ', BOX, '?', BOX, '.height|0:',
'(', CONTEXT, '.', S_FRAMEBUFFER_HEIGHT, '-', BOX_Y, ')')
check$1.optional(function () {
env.assert(scope,
BOX_W + '>=0&&' +
BOX_H + '>=0',
'invalid ' + param)
})
return [BOX_X, BOX_Y, BOX_W, BOX_H]
})
if (framebuffer) {
result.thisDep = result.thisDep || framebuffer.thisDep
result.contextDep = result.contextDep || framebuffer.contextDep
result.propDep = result.propDep || framebuffer.propDep
}
return result
} else if (framebuffer) {
return new Declaration(
framebuffer.thisDep,
framebuffer.contextDep,
framebuffer.propDep,
function (env, scope) {
var CONTEXT = env.shared.context
return [
0, 0,
scope.def(CONTEXT, '.', S_FRAMEBUFFER_WIDTH),
scope.def(CONTEXT, '.', S_FRAMEBUFFER_HEIGHT)]
})
} else {
return null
}
}
var viewport = parseBox(S_VIEWPORT)
if (viewport) {
var prevViewport = viewport
viewport = new Declaration(
viewport.thisDep,
viewport.contextDep,
viewport.propDep,
function (env, scope) {
var VIEWPORT = prevViewport.append(env, scope)
var CONTEXT = env.shared.context
scope.set(
CONTEXT,
'.' + S_VIEWPORT_WIDTH,
VIEWPORT[2])
scope.set(
CONTEXT,
'.' + S_VIEWPORT_HEIGHT,
VIEWPORT[3])
return VIEWPORT
})
}
return {
viewport: viewport,
scissor_box: parseBox(S_SCISSOR_BOX)
}
}
function parseAttribLocations (options, attributes) {
var staticOptions = options.static
var staticProgram =
typeof staticOptions[S_FRAG] === 'string' &&
typeof staticOptions[S_VERT] === 'string'
if (staticProgram) {
if (Object.keys(attributes.dynamic).length > 0) {
return null
}
var staticAttributes = attributes.static
var sAttributes = Object.keys(staticAttributes)
if (sAttributes.length > 0 && typeof staticAttributes[sAttributes[0]] === 'number') {
var bindings = []
for (var i = 0; i < sAttributes.length; ++i) {
check$1(typeof staticAttributes[sAttributes[i]] === 'number', 'must specify all vertex attribute locations when using vaos')
bindings.push([staticAttributes[sAttributes[i]] | 0, sAttributes[i]])
}
return bindings
}
}
return null
}
function parseProgram (options, env, attribLocations) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
function parseShader (name) {
if (name in staticOptions) {
var id = stringStore.id(staticOptions[name])
check$1.optional(function () {
shaderState.shader(shaderType[name], id, check$1.guessCommand())
})
var result = createStaticDecl(function () {
return id
})
result.id = id
return result
} else if (name in dynamicOptions) {
var dyn = dynamicOptions[name]
return createDynamicDecl(dyn, function (env, scope) {
var str = env.invoke(scope, dyn)
var id = scope.def(env.shared.strings, '.id(', str, ')')
check$1.optional(function () {
scope(
env.shared.shader, '.shader(',
shaderType[name], ',',
id, ',',
env.command, ');')
})
return id
})
}
return null
}
var frag = parseShader(S_FRAG)
var vert = parseShader(S_VERT)
var program = null
var progVar
if (isStatic(frag) && isStatic(vert)) {
program = shaderState.program(vert.id, frag.id, null, attribLocations)
progVar = createStaticDecl(function (env, scope) {
return env.link(program)
})
} else {
progVar = new Declaration(
(frag && frag.thisDep) || (vert && vert.thisDep),
(frag && frag.contextDep) || (vert && vert.contextDep),
(frag && frag.propDep) || (vert && vert.propDep),
function (env, scope) {
var SHADER_STATE = env.shared.shader
var fragId
if (frag) {
fragId = frag.append(env, scope)
} else {
fragId = scope.def(SHADER_STATE, '.', S_FRAG)
}
var vertId
if (vert) {
vertId = vert.append(env, scope)
} else {
vertId = scope.def(SHADER_STATE, '.', S_VERT)
}
var progDef = SHADER_STATE + '.program(' + vertId + ',' + fragId
check$1.optional(function () {
progDef += ',' + env.command
})
return scope.def(progDef + ')')
})
}
return {
frag: frag,
vert: vert,
progVar: progVar,
program: program
}
}
function parseDraw (options, env) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
function parseElements () {
if (S_ELEMENTS in staticOptions) {
var elements = staticOptions[S_ELEMENTS]
if (isBufferArgs(elements)) {
elements = elementState.getElements(elementState.create(elements, true))
} else if (elements) {
elements = elementState.getElements(elements)
check$1.command(elements, 'invalid elements', env.commandStr)
}
var result = createStaticDecl(function (env, scope) {
if (elements) {
var result = env.link(elements)
env.ELEMENTS = result
return result
}
env.ELEMENTS = null
return null
})
result.value = elements
return result
} else if (S_ELEMENTS in dynamicOptions) {
var dyn = dynamicOptions[S_ELEMENTS]
return createDynamicDecl(dyn, function (env, scope) {
var shared = env.shared
var IS_BUFFER_ARGS = shared.isBufferArgs
var ELEMENT_STATE = shared.elements
var elementDefn = env.invoke(scope, dyn)
var elements = scope.def('null')
var elementStream = scope.def(IS_BUFFER_ARGS, '(', elementDefn, ')')
var ifte = env.cond(elementStream)
.then(elements, '=', ELEMENT_STATE, '.createStream(', elementDefn, ');')
.else(elements, '=', ELEMENT_STATE, '.getElements(', elementDefn, ');')
check$1.optional(function () {
env.assert(ifte.else,
'!' + elementDefn + '||' + elements,
'invalid elements')
})
scope.entry(ifte)
scope.exit(
env.cond(elementStream)
.then(ELEMENT_STATE, '.destroyStream(', elements, ');'))
env.ELEMENTS = elements
return elements
})
}
return null
}
var elements = parseElements()
function parsePrimitive () {
if (S_PRIMITIVE in staticOptions) {
var primitive = staticOptions[S_PRIMITIVE]
check$1.commandParameter(primitive, primTypes, 'invalid primitve', env.commandStr)
return createStaticDecl(function (env, scope) {
return primTypes[primitive]
})
} else if (S_PRIMITIVE in dynamicOptions) {
var dynPrimitive = dynamicOptions[S_PRIMITIVE]
return createDynamicDecl(dynPrimitive, function (env, scope) {
var PRIM_TYPES = env.constants.primTypes
var prim = env.invoke(scope, dynPrimitive)
check$1.optional(function () {
env.assert(scope,
prim + ' in ' + PRIM_TYPES,
'invalid primitive, must be one of ' + Object.keys(primTypes))
})
return scope.def(PRIM_TYPES, '[', prim, ']')
})
} else if (elements) {
if (isStatic(elements)) {
if (elements.value) {
return createStaticDecl(function (env, scope) {
return scope.def(env.ELEMENTS, '.primType')
})
} else {
return createStaticDecl(function () {
return GL_TRIANGLES$1
})
}
} else {
return new Declaration(
elements.thisDep,
elements.contextDep,
elements.propDep,
function (env, scope) {
var elements = env.ELEMENTS
return scope.def(elements, '?', elements, '.primType:', GL_TRIANGLES$1)
})
}
}
return null
}
function parseParam (param, isOffset) {
if (param in staticOptions) {
var value = staticOptions[param] | 0
check$1.command(!isOffset || value >= 0, 'invalid ' + param, env.commandStr)
return createStaticDecl(function (env, scope) {
if (isOffset) {
env.OFFSET = value
}
return value
})
} else if (param in dynamicOptions) {
var dynValue = dynamicOptions[param]
return createDynamicDecl(dynValue, function (env, scope) {
var result = env.invoke(scope, dynValue)
if (isOffset) {
env.OFFSET = result
check$1.optional(function () {
env.assert(scope,
result + '>=0',
'invalid ' + param)
})
}
return result
})
} else if (isOffset && elements) {
return createStaticDecl(function (env, scope) {
env.OFFSET = '0'
return 0
})
}
return null
}
var OFFSET = parseParam(S_OFFSET, true)
function parseVertCount () {
if (S_COUNT in staticOptions) {
var count = staticOptions[S_COUNT] | 0
check$1.command(
typeof count === 'number' && count >= 0, 'invalid vertex count', env.commandStr)
return createStaticDecl(function () {
return count
})
} else if (S_COUNT in dynamicOptions) {
var dynCount = dynamicOptions[S_COUNT]
return createDynamicDecl(dynCount, function (env, scope) {
var result = env.invoke(scope, dynCount)
check$1.optional(function () {
env.assert(scope,
'typeof ' + result + '==="number"&&' +
result + '>=0&&' +
result + '===(' + result + '|0)',
'invalid vertex count')
})
return result
})
} else if (elements) {
if (isStatic(elements)) {
if (elements) {
if (OFFSET) {
return new Declaration(
OFFSET.thisDep,
OFFSET.contextDep,
OFFSET.propDep,
function (env, scope) {
var result = scope.def(
env.ELEMENTS, '.vertCount-', env.OFFSET)
check$1.optional(function () {
env.assert(scope,
result + '>=0',
'invalid vertex offset/element buffer too small')
})
return result
})
} else {
return createStaticDecl(function (env, scope) {
return scope.def(env.ELEMENTS, '.vertCount')
})
}
} else {
var result = createStaticDecl(function () {
return -1
})
check$1.optional(function () {
result.MISSING = true
})
return result
}
} else {
var variable = new Declaration(
elements.thisDep || OFFSET.thisDep,
elements.contextDep || OFFSET.contextDep,
elements.propDep || OFFSET.propDep,
function (env, scope) {
var elements = env.ELEMENTS
if (env.OFFSET) {
return scope.def(elements, '?', elements, '.vertCount-',
env.OFFSET, ':-1')
}
return scope.def(elements, '?', elements, '.vertCount:-1')
})
check$1.optional(function () {
variable.DYNAMIC = true
})
return variable
}
}
return null
}
return {
elements: elements,
primitive: parsePrimitive(),
count: parseVertCount(),
instances: parseParam(S_INSTANCES, false),
offset: OFFSET
}
}
function parseGLState (options, env) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
var STATE = {}
GL_STATE_NAMES.forEach(function (prop) {
var param = propName(prop)
function parseParam (parseStatic, parseDynamic) {
if (prop in staticOptions) {
var value = parseStatic(staticOptions[prop])
STATE[param] = createStaticDecl(function () {
return value
})
} else if (prop in dynamicOptions) {
var dyn = dynamicOptions[prop]
STATE[param] = createDynamicDecl(dyn, function (env, scope) {
return parseDynamic(env, scope, env.invoke(scope, dyn))
})
}
}
switch (prop) {
case S_CULL_ENABLE:
case S_BLEND_ENABLE:
case S_DITHER:
case S_STENCIL_ENABLE:
case S_DEPTH_ENABLE:
case S_SCISSOR_ENABLE:
case S_POLYGON_OFFSET_ENABLE:
case S_SAMPLE_ALPHA:
case S_SAMPLE_ENABLE:
case S_DEPTH_MASK:
return parseParam(
function (value) {
check$1.commandType(value, 'boolean', prop, env.commandStr)
return value
},
function (env, scope, value) {
check$1.optional(function () {
env.assert(scope,
'typeof ' + value + '==="boolean"',
'invalid flag ' + prop, env.commandStr)
})
return value
})
case S_DEPTH_FUNC:
return parseParam(
function (value) {
check$1.commandParameter(value, compareFuncs, 'invalid ' + prop, env.commandStr)
return compareFuncs[value]
},
function (env, scope, value) {
var COMPARE_FUNCS = env.constants.compareFuncs
check$1.optional(function () {
env.assert(scope,
value + ' in ' + COMPARE_FUNCS,
'invalid ' + prop + ', must be one of ' + Object.keys(compareFuncs))
})
return scope.def(COMPARE_FUNCS, '[', value, ']')
})
case S_DEPTH_RANGE:
return parseParam(
function (value) {
check$1.command(
isArrayLike(value) &&
value.length === 2 &&
typeof value[0] === 'number' &&
typeof value[1] === 'number' &&
value[0] <= value[1],
'depth range is 2d array',
env.commandStr)
return value
},
function (env, scope, value) {
check$1.optional(function () {
env.assert(scope,
env.shared.isArrayLike + '(' + value + ')&&' +
value + '.length===2&&' +
'typeof ' + value + '[0]==="number"&&' +
'typeof ' + value + '[1]==="number"&&' +
value + '[0]<=' + value + '[1]',
'depth range must be a 2d array')
})
var Z_NEAR = scope.def('+', value, '[0]')
var Z_FAR = scope.def('+', value, '[1]')
return [Z_NEAR, Z_FAR]
})
case S_BLEND_FUNC:
return parseParam(
function (value) {
check$1.commandType(value, 'object', 'blend.func', env.commandStr)
var srcRGB = ('srcRGB' in value ? value.srcRGB : value.src)
var srcAlpha = ('srcAlpha' in value ? value.srcAlpha : value.src)
var dstRGB = ('dstRGB' in value ? value.dstRGB : value.dst)
var dstAlpha = ('dstAlpha' in value ? value.dstAlpha : value.dst)
check$1.commandParameter(srcRGB, blendFuncs, param + '.srcRGB', env.commandStr)
check$1.commandParameter(srcAlpha, blendFuncs, param + '.srcAlpha', env.commandStr)
check$1.commandParameter(dstRGB, blendFuncs, param + '.dstRGB', env.commandStr)
check$1.commandParameter(dstAlpha, blendFuncs, param + '.dstAlpha', env.commandStr)
check$1.command(
(invalidBlendCombinations.indexOf(srcRGB + ', ' + dstRGB) === -1),
'unallowed blending combination (srcRGB, dstRGB) = (' + srcRGB + ', ' + dstRGB + ')', env.commandStr)
return [
blendFuncs[srcRGB],
blendFuncs[dstRGB],
blendFuncs[srcAlpha],
blendFuncs[dstAlpha]
]
},
function (env, scope, value) {
var BLEND_FUNCS = env.constants.blendFuncs
check$1.optional(function () {
env.assert(scope,
value + '&&typeof ' + value + '==="object"',
'invalid blend func, must be an object')
})
function read (prefix, suffix) {
var func = scope.def(
'"', prefix, suffix, '" in ', value,
'?', value, '.', prefix, suffix,
':', value, '.', prefix)
check$1.optional(function () {
env.assert(scope,
func + ' in ' + BLEND_FUNCS,
'invalid ' + prop + '.' + prefix + suffix + ', must be one of ' + Object.keys(blendFuncs))
})
return func
}
var srcRGB = read('src', 'RGB')
var dstRGB = read('dst', 'RGB')
check$1.optional(function () {
var INVALID_BLEND_COMBINATIONS = env.constants.invalidBlendCombinations
env.assert(scope,
INVALID_BLEND_COMBINATIONS +
'.indexOf(' + srcRGB + '+", "+' + dstRGB + ') === -1 ',
'unallowed blending combination for (srcRGB, dstRGB)'
)
})
var SRC_RGB = scope.def(BLEND_FUNCS, '[', srcRGB, ']')
var SRC_ALPHA = scope.def(BLEND_FUNCS, '[', read('src', 'Alpha'), ']')
var DST_RGB = scope.def(BLEND_FUNCS, '[', dstRGB, ']')
var DST_ALPHA = scope.def(BLEND_FUNCS, '[', read('dst', 'Alpha'), ']')
return [SRC_RGB, DST_RGB, SRC_ALPHA, DST_ALPHA]
})
case S_BLEND_EQUATION:
return parseParam(
function (value) {
if (typeof value === 'string') {
check$1.commandParameter(value, blendEquations, 'invalid ' + prop, env.commandStr)
return [
blendEquations[value],
blendEquations[value]
]
} else if (typeof value === 'object') {
check$1.commandParameter(
value.rgb, blendEquations, prop + '.rgb', env.commandStr)
check$1.commandParameter(
value.alpha, blendEquations, prop + '.alpha', env.commandStr)
return [
blendEquations[value.rgb],
blendEquations[value.alpha]
]
} else {
check$1.commandRaise('invalid blend.equation', env.commandStr)
}
},
function (env, scope, value) {
var BLEND_EQUATIONS = env.constants.blendEquations
var RGB = scope.def()
var ALPHA = scope.def()
var ifte = env.cond('typeof ', value, '==="string"')
check$1.optional(function () {
function checkProp (block, name, value) {
env.assert(block,
value + ' in ' + BLEND_EQUATIONS,
'invalid ' + name + ', must be one of ' + Object.keys(blendEquations))
}
checkProp(ifte.then, prop, value)
env.assert(ifte.else,
value + '&&typeof ' + value + '==="object"',
'invalid ' + prop)
checkProp(ifte.else, prop + '.rgb', value + '.rgb')
checkProp(ifte.else, prop + '.alpha', value + '.alpha')
})
ifte.then(
RGB, '=', ALPHA, '=', BLEND_EQUATIONS, '[', value, '];')
ifte.else(
RGB, '=', BLEND_EQUATIONS, '[', value, '.rgb];',
ALPHA, '=', BLEND_EQUATIONS, '[', value, '.alpha];')
scope(ifte)
return [RGB, ALPHA]
})
case S_BLEND_COLOR:
return parseParam(
function (value) {
check$1.command(
isArrayLike(value) &&
value.length === 4,
'blend.color must be a 4d array', env.commandStr)
return loop(4, function (i) {
return +value[i]
})
},
function (env, scope, value) {
check$1.optional(function () {
env.assert(scope,
env.shared.isArrayLike + '(' + value + ')&&' +
value + '.length===4',
'blend.color must be a 4d array')
})
return loop(4, function (i) {
return scope.def('+', value, '[', i, ']')
})
})
case S_STENCIL_MASK:
return parseParam(
function (value) {
check$1.commandType(value, 'number', param, env.commandStr)
return value | 0
},
function (env, scope, value) {
check$1.optional(function () {
env.assert(scope,
'typeof ' + value + '==="number"',
'invalid stencil.mask')
})
return scope.def(value, '|0')
})
case S_STENCIL_FUNC:
return parseParam(
function (value) {
check$1.commandType(value, 'object', param, env.commandStr)
var cmp = value.cmp || 'keep'
var ref = value.ref || 0
var mask = 'mask' in value ? value.mask : -1
check$1.commandParameter(cmp, compareFuncs, prop + '.cmp', env.commandStr)
check$1.commandType(ref, 'number', prop + '.ref', env.commandStr)
check$1.commandType(mask, 'number', prop + '.mask', env.commandStr)
return [
compareFuncs[cmp],
ref,
mask
]
},
function (env, scope, value) {
var COMPARE_FUNCS = env.constants.compareFuncs
check$1.optional(function () {
function assert () {
env.assert(scope,
Array.prototype.join.call(arguments, ''),
'invalid stencil.func')
}
assert(value + '&&typeof ', value, '==="object"')
assert('!("cmp" in ', value, ')||(',
value, '.cmp in ', COMPARE_FUNCS, ')')
})
var cmp = scope.def(
'"cmp" in ', value,
'?', COMPARE_FUNCS, '[', value, '.cmp]',
':', GL_KEEP)
var ref = scope.def(value, '.ref|0')
var mask = scope.def(
'"mask" in ', value,
'?', value, '.mask|0:-1')
return [cmp, ref, mask]
})
case S_STENCIL_OPFRONT:
case S_STENCIL_OPBACK:
return parseParam(
function (value) {
check$1.commandType(value, 'object', param, env.commandStr)
var fail = value.fail || 'keep'
var zfail = value.zfail || 'keep'
var zpass = value.zpass || 'keep'
check$1.commandParameter(fail, stencilOps, prop + '.fail', env.commandStr)
check$1.commandParameter(zfail, stencilOps, prop + '.zfail', env.commandStr)
check$1.commandParameter(zpass, stencilOps, prop + '.zpass', env.commandStr)
return [
prop === S_STENCIL_OPBACK ? GL_BACK : GL_FRONT,
stencilOps[fail],
stencilOps[zfail],
stencilOps[zpass]
]
},
function (env, scope, value) {
var STENCIL_OPS = env.constants.stencilOps
check$1.optional(function () {
env.assert(scope,
value + '&&typeof ' + value + '==="object"',
'invalid ' + prop)
})
function read (name) {
check$1.optional(function () {
env.assert(scope,
'!("' + name + '" in ' + value + ')||' +
'(' + value + '.' + name + ' in ' + STENCIL_OPS + ')',
'invalid ' + prop + '.' + name + ', must be one of ' + Object.keys(stencilOps))
})
return scope.def(
'"', name, '" in ', value,
'?', STENCIL_OPS, '[', value, '.', name, ']:',
GL_KEEP)
}
return [
prop === S_STENCIL_OPBACK ? GL_BACK : GL_FRONT,
read('fail'),
read('zfail'),
read('zpass')
]
})
case S_POLYGON_OFFSET_OFFSET:
return parseParam(
function (value) {
check$1.commandType(value, 'object', param, env.commandStr)
var factor = value.factor | 0
var units = value.units | 0
check$1.commandType(factor, 'number', param + '.factor', env.commandStr)
check$1.commandType(units, 'number', param + '.units', env.commandStr)
return [factor, units]
},
function (env, scope, value) {
check$1.optional(function () {
env.assert(scope,
value + '&&typeof ' + value + '==="object"',
'invalid ' + prop)
})
var FACTOR = scope.def(value, '.factor|0')
var UNITS = scope.def(value, '.units|0')
return [FACTOR, UNITS]
})
case S_CULL_FACE:
return parseParam(
function (value) {
var face = 0
if (value === 'front') {
face = GL_FRONT
} else if (value === 'back') {
face = GL_BACK
}
check$1.command(!!face, param, env.commandStr)
return face
},
function (env, scope, value) {
check$1.optional(function () {
env.assert(scope,
value + '==="front"||' +
value + '==="back"',
'invalid cull.face')
})
return scope.def(value, '==="front"?', GL_FRONT, ':', GL_BACK)
})
case S_LINE_WIDTH:
return parseParam(
function (value) {
check$1.command(
typeof value === 'number' &&
value >= limits.lineWidthDims[0] &&
value <= limits.lineWidthDims[1],
'invalid line width, must be a positive number between ' +
limits.lineWidthDims[0] + ' and ' + limits.lineWidthDims[1], env.commandStr)
return value
},
function (env, scope, value) {
check$1.optional(function () {
env.assert(scope,
'typeof ' + value + '==="number"&&' +
value + '>=' + limits.lineWidthDims[0] + '&&' +
value + '<=' + limits.lineWidthDims[1],
'invalid line width')
})
return value
})
case S_FRONT_FACE:
return parseParam(
function (value) {
check$1.commandParameter(value, orientationType, param, env.commandStr)
return orientationType[value]
},
function (env, scope, value) {
check$1.optional(function () {
env.assert(scope,
value + '==="cw"||' +
value + '==="ccw"',
'invalid frontFace, must be one of cw,ccw')
})
return scope.def(value + '==="cw"?' + GL_CW + ':' + GL_CCW)
})
case S_COLOR_MASK:
return parseParam(
function (value) {
check$1.command(
isArrayLike(value) && value.length === 4,
'color.mask must be length 4 array', env.commandStr)
return value.map(function (v) { return !!v })
},
function (env, scope, value) {
check$1.optional(function () {
env.assert(scope,
env.shared.isArrayLike + '(' + value + ')&&' +
value + '.length===4',
'invalid color.mask')
})
return loop(4, function (i) {
return '!!' + value + '[' + i + ']'
})
})
case S_SAMPLE_COVERAGE:
return parseParam(
function (value) {
check$1.command(typeof value === 'object' && value, param, env.commandStr)
var sampleValue = 'value' in value ? value.value : 1
var sampleInvert = !!value.invert
check$1.command(
typeof sampleValue === 'number' &&
sampleValue >= 0 && sampleValue <= 1,
'sample.coverage.value must be a number between 0 and 1', env.commandStr)
return [sampleValue, sampleInvert]
},
function (env, scope, value) {
check$1.optional(function () {
env.assert(scope,
value + '&&typeof ' + value + '==="object"',
'invalid sample.coverage')
})
var VALUE = scope.def(
'"value" in ', value, '?+', value, '.value:1')
var INVERT = scope.def('!!', value, '.invert')
return [VALUE, INVERT]
})
}
})
return STATE
}
function parseUniforms (uniforms, env) {
var staticUniforms = uniforms.static
var dynamicUniforms = uniforms.dynamic
var UNIFORMS = {}
Object.keys(staticUniforms).forEach(function (name) {
var value = staticUniforms[name]
var result
if (typeof value === 'number' ||
typeof value === 'boolean') {
result = createStaticDecl(function () {
return value
})
} else if (typeof value === 'function') {
var reglType = value._reglType
if (reglType === 'texture2d' ||
reglType === 'textureCube') {
result = createStaticDecl(function (env) {
return env.link(value)
})
} else if (reglType === 'framebuffer' ||
reglType === 'framebufferCube') {
check$1.command(value.color.length > 0,
'missing color attachment for framebuffer sent to uniform "' + name + '"', env.commandStr)
result = createStaticDecl(function (env) {
return env.link(value.color[0])
})
} else {
check$1.commandRaise('invalid data for uniform "' + name + '"', env.commandStr)
}
} else if (isArrayLike(value)) {
result = createStaticDecl(function (env) {
var ITEM = env.global.def('[',
loop(value.length, function (i) {
check$1.command(
typeof value[i] === 'number' ||
typeof value[i] === 'boolean',
'invalid uniform ' + name, env.commandStr)
return value[i]
}), ']')
return ITEM
})
} else {
check$1.commandRaise('invalid or missing data for uniform "' + name + '"', env.commandStr)
}
result.value = value
UNIFORMS[name] = result
})
Object.keys(dynamicUniforms).forEach(function (key) {
var dyn = dynamicUniforms[key]
UNIFORMS[key] = createDynamicDecl(dyn, function (env, scope) {
return env.invoke(scope, dyn)
})
})
return UNIFORMS
}
function parseAttributes (attributes, env) {
var staticAttributes = attributes.static
var dynamicAttributes = attributes.dynamic
var attributeDefs = {}
Object.keys(staticAttributes).forEach(function (attribute) {
var value = staticAttributes[attribute]
var id = stringStore.id(attribute)
var record = new AttributeRecord()
if (isBufferArgs(value)) {
record.state = ATTRIB_STATE_POINTER
record.buffer = bufferState.getBuffer(
bufferState.create(value, GL_ARRAY_BUFFER$2, false, true))
record.type = 0
} else {
var buffer = bufferState.getBuffer(value)
if (buffer) {
record.state = ATTRIB_STATE_POINTER
record.buffer = buffer
record.type = 0
} else {
check$1.command(typeof value === 'object' && value,
'invalid data for attribute ' + attribute, env.commandStr)
if ('constant' in value) {
var constant = value.constant
record.buffer = 'null'
record.state = ATTRIB_STATE_CONSTANT
if (typeof constant === 'number') {
record.x = constant
} else {
check$1.command(
isArrayLike(constant) &&
constant.length > 0 &&
constant.length <= 4,
'invalid constant for attribute ' + attribute, env.commandStr)
CUTE_COMPONENTS.forEach(function (c, i) {
if (i < constant.length) {
record[c] = constant[i]
}
})
}
} else {
if (isBufferArgs(value.buffer)) {
buffer = bufferState.getBuffer(
bufferState.create(value.buffer, GL_ARRAY_BUFFER$2, false, true))
} else {
buffer = bufferState.getBuffer(value.buffer)
}
check$1.command(!!buffer, 'missing buffer for attribute "' + attribute + '"', env.commandStr)
var offset = value.offset | 0
check$1.command(offset >= 0,
'invalid offset for attribute "' + attribute + '"', env.commandStr)
var stride = value.stride | 0
check$1.command(stride >= 0 && stride < 256,
'invalid stride for attribute "' + attribute + '", must be integer betweeen [0, 255]', env.commandStr)
var size = value.size | 0
check$1.command(!('size' in value) || (size > 0 && size <= 4),
'invalid size for attribute "' + attribute + '", must be 1,2,3,4', env.commandStr)
var normalized = !!value.normalized
var type = 0
if ('type' in value) {
check$1.commandParameter(
value.type, glTypes,
'invalid type for attribute ' + attribute, env.commandStr)
type = glTypes[value.type]
}
var divisor = value.divisor | 0
if ('divisor' in value) {
check$1.command(divisor === 0 || extInstancing,
'cannot specify divisor for attribute "' + attribute + '", instancing not supported', env.commandStr)
check$1.command(divisor >= 0,
'invalid divisor for attribute "' + attribute + '"', env.commandStr)
}
check$1.optional(function () {
var command = env.commandStr
var VALID_KEYS = [
'buffer',
'offset',
'divisor',
'normalized',
'type',
'size',
'stride'
]
Object.keys(value).forEach(function (prop) {
check$1.command(
VALID_KEYS.indexOf(prop) >= 0,
'unknown parameter "' + prop + '" for attribute pointer "' + attribute + '" (valid parameters are ' + VALID_KEYS + ')',
command)
})
})
record.buffer = buffer
record.state = ATTRIB_STATE_POINTER
record.size = size
record.normalized = normalized
record.type = type || buffer.dtype
record.offset = offset
record.stride = stride
record.divisor = divisor
}
}
}
attributeDefs[attribute] = createStaticDecl(function (env, scope) {
var cache = env.attribCache
if (id in cache) {
return cache[id]
}
var result = {
isStream: false
}
Object.keys(record).forEach(function (key) {
result[key] = record[key]
})
if (record.buffer) {
result.buffer = env.link(record.buffer)
result.type = result.type || (result.buffer + '.dtype')
}
cache[id] = result
return result
})
})
Object.keys(dynamicAttributes).forEach(function (attribute) {
var dyn = dynamicAttributes[attribute]
function appendAttributeCode (env, block) {
var VALUE = env.invoke(block, dyn)
var shared = env.shared
var constants = env.constants
var IS_BUFFER_ARGS = shared.isBufferArgs
var BUFFER_STATE = shared.buffer
// Perform validation on attribute
check$1.optional(function () {
env.assert(block,
VALUE + '&&(typeof ' + VALUE + '==="object"||typeof ' +
VALUE + '==="function")&&(' +
IS_BUFFER_ARGS + '(' + VALUE + ')||' +
BUFFER_STATE + '.getBuffer(' + VALUE + ')||' +
BUFFER_STATE + '.getBuffer(' + VALUE + '.buffer)||' +
IS_BUFFER_ARGS + '(' + VALUE + '.buffer)||' +
'("constant" in ' + VALUE +
'&&(typeof ' + VALUE + '.constant==="number"||' +
shared.isArrayLike + '(' + VALUE + '.constant))))',
'invalid dynamic attribute "' + attribute + '"')
})
// allocate names for result
var result = {
isStream: block.def(false)
}
var defaultRecord = new AttributeRecord()
defaultRecord.state = ATTRIB_STATE_POINTER
Object.keys(defaultRecord).forEach(function (key) {
result[key] = block.def('' + defaultRecord[key])
})
var BUFFER = result.buffer
var TYPE = result.type
block(
'if(', IS_BUFFER_ARGS, '(', VALUE, ')){',
result.isStream, '=true;',
BUFFER, '=', BUFFER_STATE, '.createStream(', GL_ARRAY_BUFFER$2, ',', VALUE, ');',
TYPE, '=', BUFFER, '.dtype;',
'}else{',
BUFFER, '=', BUFFER_STATE, '.getBuffer(', VALUE, ');',
'if(', BUFFER, '){',
TYPE, '=', BUFFER, '.dtype;',
'}else if("constant" in ', VALUE, '){',
result.state, '=', ATTRIB_STATE_CONSTANT, ';',
'if(typeof ' + VALUE + '.constant === "number"){',
result[CUTE_COMPONENTS[0]], '=', VALUE, '.constant;',
CUTE_COMPONENTS.slice(1).map(function (n) {
return result[n]
}).join('='), '=0;',
'}else{',
CUTE_COMPONENTS.map(function (name, i) {
return (
result[name] + '=' + VALUE + '.constant.length>' + i +
'?' + VALUE + '.constant[' + i + ']:0;'
)
}).join(''),
'}}else{',
'if(', IS_BUFFER_ARGS, '(', VALUE, '.buffer)){',
BUFFER, '=', BUFFER_STATE, '.createStream(', GL_ARRAY_BUFFER$2, ',', VALUE, '.buffer);',
'}else{',
BUFFER, '=', BUFFER_STATE, '.getBuffer(', VALUE, '.buffer);',
'}',
TYPE, '="type" in ', VALUE, '?',
constants.glTypes, '[', VALUE, '.type]:', BUFFER, '.dtype;',
result.normalized, '=!!', VALUE, '.normalized;')
function emitReadRecord (name) {
block(result[name], '=', VALUE, '.', name, '|0;')
}
emitReadRecord('size')
emitReadRecord('offset')
emitReadRecord('stride')
emitReadRecord('divisor')
block('}}')
block.exit(
'if(', result.isStream, '){',
BUFFER_STATE, '.destroyStream(', BUFFER, ');',
'}')
return result
}
attributeDefs[attribute] = createDynamicDecl(dyn, appendAttributeCode)
})
return attributeDefs
}
function parseVAO (options, env) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
if (S_VAO in staticOptions) {
var vao = staticOptions[S_VAO]
if (vao !== null && attributeState.getVAO(vao) === null) {
vao = attributeState.createVAO(vao)
}
return createStaticDecl(function (env) {
return env.link(attributeState.getVAO(vao))
})
} else if (S_VAO in dynamicOptions) {
var dyn = dynamicOptions[S_VAO]
return createDynamicDecl(dyn, function (env, scope) {
var vaoRef = env.invoke(scope, dyn)
return scope.def(env.shared.vao + '.getVAO(' + vaoRef + ')')
})
}
return null
}
function parseContext (context) {
var staticContext = context.static
var dynamicContext = context.dynamic
var result = {}
Object.keys(staticContext).forEach(function (name) {
var value = staticContext[name]
result[name] = createStaticDecl(function (env, scope) {
if (typeof value === 'number' || typeof value === 'boolean') {
return '' + value
} else {
return env.link(value)
}
})
})
Object.keys(dynamicContext).forEach(function (name) {
var dyn = dynamicContext[name]
result[name] = createDynamicDecl(dyn, function (env, scope) {
return env.invoke(scope, dyn)
})
})
return result
}
function parseArguments (options, attributes, uniforms, context, env) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
check$1.optional(function () {
var KEY_NAMES = [
S_FRAMEBUFFER,
S_VERT,
S_FRAG,
S_ELEMENTS,
S_PRIMITIVE,
S_OFFSET,
S_COUNT,
S_INSTANCES,
S_PROFILE,
S_VAO
].concat(GL_STATE_NAMES)
function checkKeys (dict) {
Object.keys(dict).forEach(function (key) {
check$1.command(
KEY_NAMES.indexOf(key) >= 0,
'unknown parameter "' + key + '"',
env.commandStr)
})
}
checkKeys(staticOptions)
checkKeys(dynamicOptions)
})
var attribLocations = parseAttribLocations(options, attributes)
var framebuffer = parseFramebuffer(options, env)
var viewportAndScissor = parseViewportScissor(options, framebuffer, env)
var draw = parseDraw(options, env)
var state = parseGLState(options, env)
var shader = parseProgram(options, env, attribLocations)
function copyBox (name) {
var defn = viewportAndScissor[name]
if (defn) {
state[name] = defn
}
}
copyBox(S_VIEWPORT)
copyBox(propName(S_SCISSOR_BOX))
var dirty = Object.keys(state).length > 0
var result = {
framebuffer: framebuffer,
draw: draw,
shader: shader,
state: state,
dirty: dirty,
scopeVAO: null,
drawVAO: null,
useVAO: false,
attributes: {}
}
result.profile = parseProfile(options, env)
result.uniforms = parseUniforms(uniforms, env)
result.drawVAO = result.scopeVAO = parseVAO(options, env)
// special case: check if we can statically allocate a vertex array object for this program
if (!result.drawVAO && shader.program && !attribLocations && extensions.angle_instanced_arrays) {
var useVAO = true
var staticBindings = shader.program.attributes.map(function (attr) {
var binding = attributes.static[attr]
useVAO = useVAO && !!binding
return binding
})
if (useVAO && staticBindings.length > 0) {
var vao = attributeState.getVAO(attributeState.createVAO(staticBindings))
result.drawVAO = new Declaration(null, null, null, function (env, scope) {
return env.link(vao)
})
result.useVAO = true
}
}
if (attribLocations) {
result.useVAO = true
} else {
result.attributes = parseAttributes(attributes, env)
}
result.context = parseContext(context, env)
return result
}
// ===================================================
// ===================================================
// COMMON UPDATE FUNCTIONS
// ===================================================
// ===================================================
function emitContext (env, scope, context) {
var shared = env.shared
var CONTEXT = shared.context
var contextEnter = env.scope()
Object.keys(context).forEach(function (name) {
scope.save(CONTEXT, '.' + name)
var defn = context[name]
contextEnter(CONTEXT, '.', name, '=', defn.append(env, scope), ';')
})
scope(contextEnter)
}
// ===================================================
// ===================================================
// COMMON DRAWING FUNCTIONS
// ===================================================
// ===================================================
function emitPollFramebuffer (env, scope, framebuffer, skipCheck) {
var shared = env.shared
var GL = shared.gl
var FRAMEBUFFER_STATE = shared.framebuffer
var EXT_DRAW_BUFFERS
if (extDrawBuffers) {
EXT_DRAW_BUFFERS = scope.def(shared.extensions, '.webgl_draw_buffers')
}
var constants = env.constants
var DRAW_BUFFERS = constants.drawBuffer
var BACK_BUFFER = constants.backBuffer
var NEXT
if (framebuffer) {
NEXT = framebuffer.append(env, scope)
} else {
NEXT = scope.def(FRAMEBUFFER_STATE, '.next')
}
if (!skipCheck) {
scope('if(', NEXT, '!==', FRAMEBUFFER_STATE, '.cur){')
}
scope(
'if(', NEXT, '){',
GL, '.bindFramebuffer(', GL_FRAMEBUFFER$2, ',', NEXT, '.framebuffer);')
if (extDrawBuffers) {
scope(EXT_DRAW_BUFFERS, '.drawBuffersWEBGL(',
DRAW_BUFFERS, '[', NEXT, '.colorAttachments.length]);')
}
scope('}else{',
GL, '.bindFramebuffer(', GL_FRAMEBUFFER$2, ',null);')
if (extDrawBuffers) {
scope(EXT_DRAW_BUFFERS, '.drawBuffersWEBGL(', BACK_BUFFER, ');')
}
scope(
'}',
FRAMEBUFFER_STATE, '.cur=', NEXT, ';')
if (!skipCheck) {
scope('}')
}
}
function emitPollState (env, scope, args) {
var shared = env.shared
var GL = shared.gl
var CURRENT_VARS = env.current
var NEXT_VARS = env.next
var CURRENT_STATE = shared.current
var NEXT_STATE = shared.next
var block = env.cond(CURRENT_STATE, '.dirty')
GL_STATE_NAMES.forEach(function (prop) {
var param = propName(prop)
if (param in args.state) {
return
}
var NEXT, CURRENT
if (param in NEXT_VARS) {
NEXT = NEXT_VARS[param]
CURRENT = CURRENT_VARS[param]
var parts = loop(currentState[param].length, function (i) {
return block.def(NEXT, '[', i, ']')
})
block(env.cond(parts.map(function (p, i) {
return p + '!==' + CURRENT + '[' + i + ']'
}).join('||'))
.then(
GL, '.', GL_VARIABLES[param], '(', parts, ');',
parts.map(function (p, i) {
return CURRENT + '[' + i + ']=' + p
}).join(';'), ';'))
} else {
NEXT = block.def(NEXT_STATE, '.', param)
var ifte = env.cond(NEXT, '!==', CURRENT_STATE, '.', param)
block(ifte)
if (param in GL_FLAGS) {
ifte(
env.cond(NEXT)
.then(GL, '.enable(', GL_FLAGS[param], ');')
.else(GL, '.disable(', GL_FLAGS[param], ');'),
CURRENT_STATE, '.', param, '=', NEXT, ';')
} else {
ifte(
GL, '.', GL_VARIABLES[param], '(', NEXT, ');',
CURRENT_STATE, '.', param, '=', NEXT, ';')
}
}
})
if (Object.keys(args.state).length === 0) {
block(CURRENT_STATE, '.dirty=false;')
}
scope(block)
}
function emitSetOptions (env, scope, options, filter) {
var shared = env.shared
var CURRENT_VARS = env.current
var CURRENT_STATE = shared.current
var GL = shared.gl
sortState(Object.keys(options)).forEach(function (param) {
var defn = options[param]
if (filter && !filter(defn)) {
return
}
var variable = defn.append(env, scope)
if (GL_FLAGS[param]) {
var flag = GL_FLAGS[param]
if (isStatic(defn)) {
if (variable) {
scope(GL, '.enable(', flag, ');')
} else {
scope(GL, '.disable(', flag, ');')
}
} else {
scope(env.cond(variable)
.then(GL, '.enable(', flag, ');')
.else(GL, '.disable(', flag, ');'))
}
scope(CURRENT_STATE, '.', param, '=', variable, ';')
} else if (isArrayLike(variable)) {
var CURRENT = CURRENT_VARS[param]
scope(
GL, '.', GL_VARIABLES[param], '(', variable, ');',
variable.map(function (v, i) {
return CURRENT + '[' + i + ']=' + v
}).join(';'), ';')
} else {
scope(
GL, '.', GL_VARIABLES[param], '(', variable, ');',
CURRENT_STATE, '.', param, '=', variable, ';')
}
})
}
function injectExtensions (env, scope) {
if (extInstancing) {
env.instancing = scope.def(
env.shared.extensions, '.angle_instanced_arrays')
}
}
function emitProfile (env, scope, args, useScope, incrementCounter) {
var shared = env.shared
var STATS = env.stats
var CURRENT_STATE = shared.current
var TIMER = shared.timer
var profileArg = args.profile
function perfCounter () {
if (typeof performance === 'undefined') {
return 'Date.now()'
} else {
return 'performance.now()'
}
}
var CPU_START, QUERY_COUNTER
function emitProfileStart (block) {
CPU_START = scope.def()
block(CPU_START, '=', perfCounter(), ';')
if (typeof incrementCounter === 'string') {
block(STATS, '.count+=', incrementCounter, ';')
} else {
block(STATS, '.count++;')
}
if (timer) {
if (useScope) {
QUERY_COUNTER = scope.def()
block(QUERY_COUNTER, '=', TIMER, '.getNumPendingQueries();')
} else {
block(TIMER, '.beginQuery(', STATS, ');')
}
}
}
function emitProfileEnd (block) {
block(STATS, '.cpuTime+=', perfCounter(), '-', CPU_START, ';')
if (timer) {
if (useScope) {
block(TIMER, '.pushScopeStats(',
QUERY_COUNTER, ',',
TIMER, '.getNumPendingQueries(),',
STATS, ');')
} else {
block(TIMER, '.endQuery();')
}
}
}
function scopeProfile (value) {
var prev = scope.def(CURRENT_STATE, '.profile')
scope(CURRENT_STATE, '.profile=', value, ';')
scope.exit(CURRENT_STATE, '.profile=', prev, ';')
}
var USE_PROFILE
if (profileArg) {
if (isStatic(profileArg)) {
if (profileArg.enable) {
emitProfileStart(scope)
emitProfileEnd(scope.exit)
scopeProfile('true')
} else {
scopeProfile('false')
}
return
}
USE_PROFILE = profileArg.append(env, scope)
scopeProfile(USE_PROFILE)
} else {
USE_PROFILE = scope.def(CURRENT_STATE, '.profile')
}
var start = env.block()
emitProfileStart(start)
scope('if(', USE_PROFILE, '){', start, '}')
var end = env.block()
emitProfileEnd(end)
scope.exit('if(', USE_PROFILE, '){', end, '}')
}
function emitAttributes (env, scope, args, attributes, filter) {
var shared = env.shared
function typeLength (x) {
switch (x) {
case GL_FLOAT_VEC2:
case GL_INT_VEC2:
case GL_BOOL_VEC2:
return 2
case GL_FLOAT_VEC3:
case GL_INT_VEC3:
case GL_BOOL_VEC3:
return 3
case GL_FLOAT_VEC4:
case GL_INT_VEC4:
case GL_BOOL_VEC4:
return 4
default:
return 1
}
}
function emitBindAttribute (ATTRIBUTE, size, record) {
var GL = shared.gl
var LOCATION = scope.def(ATTRIBUTE, '.location')
var BINDING = scope.def(shared.attributes, '[', LOCATION, ']')
var STATE = record.state
var BUFFER = record.buffer
var CONST_COMPONENTS = [
record.x,
record.y,
record.z,
record.w
]
var COMMON_KEYS = [
'buffer',
'normalized',
'offset',
'stride'
]
function emitBuffer () {
scope(
'if(!', BINDING, '.buffer){',
GL, '.enableVertexAttribArray(', LOCATION, ');}')
var TYPE = record.type
var SIZE
if (!record.size) {
SIZE = size
} else {
SIZE = scope.def(record.size, '||', size)
}
scope('if(',
BINDING, '.type!==', TYPE, '||',
BINDING, '.size!==', SIZE, '||',
COMMON_KEYS.map(function (key) {
return BINDING + '.' + key + '!==' + record[key]
}).join('||'),
'){',
GL, '.bindBuffer(', GL_ARRAY_BUFFER$2, ',', BUFFER, '.buffer);',
GL, '.vertexAttribPointer(', [
LOCATION,
SIZE,
TYPE,
record.normalized,
record.stride,
record.offset
], ');',
BINDING, '.type=', TYPE, ';',
BINDING, '.size=', SIZE, ';',
COMMON_KEYS.map(function (key) {
return BINDING + '.' + key + '=' + record[key] + ';'
}).join(''),
'}')
if (extInstancing) {
var DIVISOR = record.divisor
scope(
'if(', BINDING, '.divisor!==', DIVISOR, '){',
env.instancing, '.vertexAttribDivisorANGLE(', [LOCATION, DIVISOR], ');',
BINDING, '.divisor=', DIVISOR, ';}')
}
}
function emitConstant () {
scope(
'if(', BINDING, '.buffer){',
GL, '.disableVertexAttribArray(', LOCATION, ');',
BINDING, '.buffer=null;',
'}if(', CUTE_COMPONENTS.map(function (c, i) {
return BINDING + '.' + c + '!==' + CONST_COMPONENTS[i]
}).join('||'), '){',
GL, '.vertexAttrib4f(', LOCATION, ',', CONST_COMPONENTS, ');',
CUTE_COMPONENTS.map(function (c, i) {
return BINDING + '.' + c + '=' + CONST_COMPONENTS[i] + ';'
}).join(''),
'}')
}
if (STATE === ATTRIB_STATE_POINTER) {
emitBuffer()
} else if (STATE === ATTRIB_STATE_CONSTANT) {
emitConstant()
} else {
scope('if(', STATE, '===', ATTRIB_STATE_POINTER, '){')
emitBuffer()
scope('}else{')
emitConstant()
scope('}')
}
}
attributes.forEach(function (attribute) {
var name = attribute.name
var arg = args.attributes[name]
var record
if (arg) {
if (!filter(arg)) {
return
}
record = arg.append(env, scope)
} else {
if (!filter(SCOPE_DECL)) {
return
}
var scopeAttrib = env.scopeAttrib(name)
check$1.optional(function () {
env.assert(scope,
scopeAttrib + '.state',
'missing attribute ' + name)
})
record = {}
Object.keys(new AttributeRecord()).forEach(function (key) {
record[key] = scope.def(scopeAttrib, '.', key)
})
}
emitBindAttribute(
env.link(attribute), typeLength(attribute.info.type), record)
})
}
function emitUniforms (env, scope, args, uniforms, filter) {
var shared = env.shared
var GL = shared.gl
var infix
for (var i = 0; i < uniforms.length; ++i) {
var uniform = uniforms[i]
var name = uniform.name
var type = uniform.info.type
var arg = args.uniforms[name]
var UNIFORM = env.link(uniform)
var LOCATION = UNIFORM + '.location'
var VALUE
if (arg) {
if (!filter(arg)) {
continue
}
if (isStatic(arg)) {
var value = arg.value
check$1.command(
value !== null && typeof value !== 'undefined',
'missing uniform "' + name + '"', env.commandStr)
if (type === GL_SAMPLER_2D || type === GL_SAMPLER_CUBE) {
check$1.command(
typeof value === 'function' &&
((type === GL_SAMPLER_2D &&
(value._reglType === 'texture2d' ||
value._reglType === 'framebuffer')) ||
(type === GL_SAMPLER_CUBE &&
(value._reglType === 'textureCube' ||
value._reglType === 'framebufferCube'))),
'invalid texture for uniform ' + name, env.commandStr)
var TEX_VALUE = env.link(value._texture || value.color[0]._texture)
scope(GL, '.uniform1i(', LOCATION, ',', TEX_VALUE + '.bind());')
scope.exit(TEX_VALUE, '.unbind();')
} else if (
type === GL_FLOAT_MAT2 ||
type === GL_FLOAT_MAT3 ||
type === GL_FLOAT_MAT4) {
check$1.optional(function () {
check$1.command(isArrayLike(value),
'invalid matrix for uniform ' + name, env.commandStr)
check$1.command(
(type === GL_FLOAT_MAT2 && value.length === 4) ||
(type === GL_FLOAT_MAT3 && value.length === 9) ||
(type === GL_FLOAT_MAT4 && value.length === 16),
'invalid length for matrix uniform ' + name, env.commandStr)
})
var MAT_VALUE = env.global.def('new Float32Array([' +
Array.prototype.slice.call(value) + '])')
var dim = 2
if (type === GL_FLOAT_MAT3) {
dim = 3
} else if (type === GL_FLOAT_MAT4) {
dim = 4
}
scope(
GL, '.uniformMatrix', dim, 'fv(',
LOCATION, ',false,', MAT_VALUE, ');')
} else {
switch (type) {
case GL_FLOAT$8:
check$1.commandType(value, 'number', 'uniform ' + name, env.commandStr)
infix = '1f'
break
case GL_FLOAT_VEC2:
check$1.command(
isArrayLike(value) && value.length === 2,
'uniform ' + name, env.commandStr)
infix = '2f'
break
case GL_FLOAT_VEC3:
check$1.command(
isArrayLike(value) && value.length === 3,
'uniform ' + name, env.commandStr)
infix = '3f'
break
case GL_FLOAT_VEC4:
check$1.command(
isArrayLike(value) && value.length === 4,
'uniform ' + name, env.commandStr)
infix = '4f'
break
case GL_BOOL:
check$1.commandType(value, 'boolean', 'uniform ' + name, env.commandStr)
infix = '1i'
break
case GL_INT$3:
check$1.commandType(value, 'number', 'uniform ' + name, env.commandStr)
infix = '1i'
break
case GL_BOOL_VEC2:
check$1.command(
isArrayLike(value) && value.length === 2,
'uniform ' + name, env.commandStr)
infix = '2i'
break
case GL_INT_VEC2:
check$1.command(
isArrayLike(value) && value.length === 2,
'uniform ' + name, env.commandStr)
infix = '2i'
break
case GL_BOOL_VEC3:
check$1.command(
isArrayLike(value) && value.length === 3,
'uniform ' + name, env.commandStr)
infix = '3i'
break
case GL_INT_VEC3:
check$1.command(
isArrayLike(value) && value.length === 3,
'uniform ' + name, env.commandStr)
infix = '3i'
break
case GL_BOOL_VEC4:
check$1.command(
isArrayLike(value) && value.length === 4,
'uniform ' + name, env.commandStr)
infix = '4i'
break
case GL_INT_VEC4:
check$1.command(
isArrayLike(value) && value.length === 4,
'uniform ' + name, env.commandStr)
infix = '4i'
break
}
scope(GL, '.uniform', infix, '(', LOCATION, ',',
isArrayLike(value) ? Array.prototype.slice.call(value) : value,
');')
}
continue
} else {
VALUE = arg.append(env, scope)
}
} else {
if (!filter(SCOPE_DECL)) {
continue
}
VALUE = scope.def(shared.uniforms, '[', stringStore.id(name), ']')
}
if (type === GL_SAMPLER_2D) {
scope(
'if(', VALUE, '&&', VALUE, '._reglType==="framebuffer"){',
VALUE, '=', VALUE, '.color[0];',
'}')
} else if (type === GL_SAMPLER_CUBE) {
scope(
'if(', VALUE, '&&', VALUE, '._reglType==="framebufferCube"){',
VALUE, '=', VALUE, '.color[0];',
'}')
}
// perform type validation
check$1.optional(function () {
function check (pred, message) {
env.assert(scope, pred,
'bad data or missing for uniform "' + name + '". ' + message)
}
function checkType (type) {
check(
'typeof ' + VALUE + '==="' + type + '"',
'invalid type, expected ' + type)
}
function checkVector (n, type) {
check(
shared.isArrayLike + '(' + VALUE + ')&&' + VALUE + '.length===' + n,
'invalid vector, should have length ' + n, env.commandStr)
}
function checkTexture (target) {
check(
'typeof ' + VALUE + '==="function"&&' +
VALUE + '._reglType==="texture' +
(target === GL_TEXTURE_2D$3 ? '2d' : 'Cube') + '"',
'invalid texture type', env.commandStr)
}
switch (type) {
case GL_INT$3:
checkType('number')
break
case GL_INT_VEC2:
checkVector(2, 'number')
break
case GL_INT_VEC3:
checkVector(3, 'number')
break
case GL_INT_VEC4:
checkVector(4, 'number')
break
case GL_FLOAT$8:
checkType('number')
break
case GL_FLOAT_VEC2:
checkVector(2, 'number')
break
case GL_FLOAT_VEC3:
checkVector(3, 'number')
break
case GL_FLOAT_VEC4:
checkVector(4, 'number')
break
case GL_BOOL:
checkType('boolean')
break
case GL_BOOL_VEC2:
checkVector(2, 'boolean')
break
case GL_BOOL_VEC3:
checkVector(3, 'boolean')
break
case GL_BOOL_VEC4:
checkVector(4, 'boolean')
break
case GL_FLOAT_MAT2:
checkVector(4, 'number')
break
case GL_FLOAT_MAT3:
checkVector(9, 'number')
break
case GL_FLOAT_MAT4:
checkVector(16, 'number')
break
case GL_SAMPLER_2D:
checkTexture(GL_TEXTURE_2D$3)
break
case GL_SAMPLER_CUBE:
checkTexture(GL_TEXTURE_CUBE_MAP$2)
break
}
})
var unroll = 1
switch (type) {
case GL_SAMPLER_2D:
case GL_SAMPLER_CUBE:
var TEX = scope.def(VALUE, '._texture')
scope(GL, '.uniform1i(', LOCATION, ',', TEX, '.bind());')
scope.exit(TEX, '.unbind();')
continue
case GL_INT$3:
case GL_BOOL:
infix = '1i'
break
case GL_INT_VEC2:
case GL_BOOL_VEC2:
infix = '2i'
unroll = 2
break
case GL_INT_VEC3:
case GL_BOOL_VEC3:
infix = '3i'
unroll = 3
break
case GL_INT_VEC4:
case GL_BOOL_VEC4:
infix = '4i'
unroll = 4
break
case GL_FLOAT$8:
infix = '1f'
break
case GL_FLOAT_VEC2:
infix = '2f'
unroll = 2
break
case GL_FLOAT_VEC3:
infix = '3f'
unroll = 3
break
case GL_FLOAT_VEC4:
infix = '4f'
unroll = 4
break
case GL_FLOAT_MAT2:
infix = 'Matrix2fv'
break
case GL_FLOAT_MAT3:
infix = 'Matrix3fv'
break
case GL_FLOAT_MAT4:
infix = 'Matrix4fv'
break
}
scope(GL, '.uniform', infix, '(', LOCATION, ',')
if (infix.charAt(0) === 'M') {
var matSize = Math.pow(type - GL_FLOAT_MAT2 + 2, 2)
var STORAGE = env.global.def('new Float32Array(', matSize, ')')
scope(
'false,(Array.isArray(', VALUE, ')||', VALUE, ' instanceof Float32Array)?', VALUE, ':(',
loop(matSize, function (i) {
return STORAGE + '[' + i + ']=' + VALUE + '[' + i + ']'
}), ',', STORAGE, ')')
} else if (unroll > 1) {
scope(loop(unroll, function (i) {
return VALUE + '[' + i + ']'
}))
} else {
scope(VALUE)
}
scope(');')
}
}
function emitDraw (env, outer, inner, args) {
var shared = env.shared
var GL = shared.gl
var DRAW_STATE = shared.draw
var drawOptions = args.draw
function emitElements () {
var defn = drawOptions.elements
var ELEMENTS
var scope = outer
if (defn) {
if ((defn.contextDep && args.contextDynamic) || defn.propDep) {
scope = inner
}
ELEMENTS = defn.append(env, scope)
} else {
ELEMENTS = scope.def(DRAW_STATE, '.', S_ELEMENTS)
}
if (ELEMENTS) {
scope(
'if(' + ELEMENTS + ')' +
GL + '.bindBuffer(' + GL_ELEMENT_ARRAY_BUFFER$1 + ',' + ELEMENTS + '.buffer.buffer);')
}
return ELEMENTS
}
function emitCount () {
var defn = drawOptions.count
var COUNT
var scope = outer
if (defn) {
if ((defn.contextDep && args.contextDynamic) || defn.propDep) {
scope = inner
}
COUNT = defn.append(env, scope)
check$1.optional(function () {
if (defn.MISSING) {
env.assert(outer, 'false', 'missing vertex count')
}
if (defn.DYNAMIC) {
env.assert(scope, COUNT + '>=0', 'missing vertex count')
}
})
} else {
COUNT = scope.def(DRAW_STATE, '.', S_COUNT)
check$1.optional(function () {
env.assert(scope, COUNT + '>=0', 'missing vertex count')
})
}
return COUNT
}
var ELEMENTS = emitElements()
function emitValue (name) {
var defn = drawOptions[name]
if (defn) {
if ((defn.contextDep && args.contextDynamic) || defn.propDep) {
return defn.append(env, inner)
} else {
return defn.append(env, outer)
}
} else {
return outer.def(DRAW_STATE, '.', name)
}
}
var PRIMITIVE = emitValue(S_PRIMITIVE)
var OFFSET = emitValue(S_OFFSET)
var COUNT = emitCount()
if (typeof COUNT === 'number') {
if (COUNT === 0) {
return
}
} else {
inner('if(', COUNT, '){')
inner.exit('}')
}
var INSTANCES, EXT_INSTANCING
if (extInstancing) {
INSTANCES = emitValue(S_INSTANCES)
EXT_INSTANCING = env.instancing
}
var ELEMENT_TYPE = ELEMENTS + '.type'
var elementsStatic = drawOptions.elements && isStatic(drawOptions.elements)
function emitInstancing () {
function drawElements () {
inner(EXT_INSTANCING, '.drawElementsInstancedANGLE(', [
PRIMITIVE,
COUNT,
ELEMENT_TYPE,
OFFSET + '<<((' + ELEMENT_TYPE + '-' + GL_UNSIGNED_BYTE$8 + ')>>1)',
INSTANCES
], ');')
}
function drawArrays () {
inner(EXT_INSTANCING, '.drawArraysInstancedANGLE(',
[PRIMITIVE, OFFSET, COUNT, INSTANCES], ');')
}
if (ELEMENTS) {
if (!elementsStatic) {
inner('if(', ELEMENTS, '){')
drawElements()
inner('}else{')
drawArrays()
inner('}')
} else {
drawElements()
}
} else {
drawArrays()
}
}
function emitRegular () {
function drawElements () {
inner(GL + '.drawElements(' + [
PRIMITIVE,
COUNT,
ELEMENT_TYPE,
OFFSET + '<<((' + ELEMENT_TYPE + '-' + GL_UNSIGNED_BYTE$8 + ')>>1)'
] + ');')
}
function drawArrays () {
inner(GL + '.drawArrays(' + [PRIMITIVE, OFFSET, COUNT] + ');')
}
if (ELEMENTS) {
if (!elementsStatic) {
inner('if(', ELEMENTS, '){')
drawElements()
inner('}else{')
drawArrays()
inner('}')
} else {
drawElements()
}
} else {
drawArrays()
}
}
if (extInstancing && (typeof INSTANCES !== 'number' || INSTANCES >= 0)) {
if (typeof INSTANCES === 'string') {
inner('if(', INSTANCES, '>0){')
emitInstancing()
inner('}else if(', INSTANCES, '<0){')
emitRegular()
inner('}')
} else {
emitInstancing()
}
} else {
emitRegular()
}
}
function createBody (emitBody, parentEnv, args, program, count) {
var env = createREGLEnvironment()
var scope = env.proc('body', count)
check$1.optional(function () {
env.commandStr = parentEnv.commandStr
env.command = env.link(parentEnv.commandStr)
})
if (extInstancing) {
env.instancing = scope.def(
env.shared.extensions, '.angle_instanced_arrays')
}
emitBody(env, scope, args, program)
return env.compile().body
}
// ===================================================
// ===================================================
// DRAW PROC
// ===================================================
// ===================================================
function emitDrawBody (env, draw, args, program) {
injectExtensions(env, draw)
if (args.useVAO) {
if (args.drawVAO) {
draw(env.shared.vao, '.setVAO(', args.drawVAO.append(env, draw), ');')
} else {
draw(env.shared.vao, '.setVAO(', env.shared.vao, '.targetVAO);')
}
} else {
draw(env.shared.vao, '.setVAO(null);')
emitAttributes(env, draw, args, program.attributes, function () {
return true
})
}
emitUniforms(env, draw, args, program.uniforms, function () {
return true
})
emitDraw(env, draw, draw, args)
}
function emitDrawProc (env, args) {
var draw = env.proc('draw', 1)
injectExtensions(env, draw)
emitContext(env, draw, args.context)
emitPollFramebuffer(env, draw, args.framebuffer)
emitPollState(env, draw, args)
emitSetOptions(env, draw, args.state)
emitProfile(env, draw, args, false, true)
var program = args.shader.progVar.append(env, draw)
draw(env.shared.gl, '.useProgram(', program, '.program);')
if (args.shader.program) {
emitDrawBody(env, draw, args, args.shader.program)
} else {
draw(env.shared.vao, '.setVAO(null);')
var drawCache = env.global.def('{}')
var PROG_ID = draw.def(program, '.id')
var CACHED_PROC = draw.def(drawCache, '[', PROG_ID, ']')
draw(
env.cond(CACHED_PROC)
.then(CACHED_PROC, '.call(this,a0);')
.else(
CACHED_PROC, '=', drawCache, '[', PROG_ID, ']=',
env.link(function (program) {
return createBody(emitDrawBody, env, args, program, 1)
}), '(', program, ');',
CACHED_PROC, '.call(this,a0);'))
}
if (Object.keys(args.state).length > 0) {
draw(env.shared.current, '.dirty=true;')
}
}
// ===================================================
// ===================================================
// BATCH PROC
// ===================================================
// ===================================================
function emitBatchDynamicShaderBody (env, scope, args, program) {
env.batchId = 'a1'
injectExtensions(env, scope)
function all () {
return true
}
emitAttributes(env, scope, args, program.attributes, all)
emitUniforms(env, scope, args, program.uniforms, all)
emitDraw(env, scope, scope, args)
}
function emitBatchBody (env, scope, args, program) {
injectExtensions(env, scope)
var contextDynamic = args.contextDep
var BATCH_ID = scope.def()
var PROP_LIST = 'a0'
var NUM_PROPS = 'a1'
var PROPS = scope.def()
env.shared.props = PROPS
env.batchId = BATCH_ID
var outer = env.scope()
var inner = env.scope()
scope(
outer.entry,
'for(', BATCH_ID, '=0;', BATCH_ID, '<', NUM_PROPS, ';++', BATCH_ID, '){',
PROPS, '=', PROP_LIST, '[', BATCH_ID, '];',
inner,
'}',
outer.exit)
function isInnerDefn (defn) {
return ((defn.contextDep && contextDynamic) || defn.propDep)
}
function isOuterDefn (defn) {
return !isInnerDefn(defn)
}
if (args.needsContext) {
emitContext(env, inner, args.context)
}
if (args.needsFramebuffer) {
emitPollFramebuffer(env, inner, args.framebuffer)
}
emitSetOptions(env, inner, args.state, isInnerDefn)
if (args.profile && isInnerDefn(args.profile)) {
emitProfile(env, inner, args, false, true)
}
if (!program) {
var progCache = env.global.def('{}')
var PROGRAM = args.shader.progVar.append(env, inner)
var PROG_ID = inner.def(PROGRAM, '.id')
var CACHED_PROC = inner.def(progCache, '[', PROG_ID, ']')
inner(
env.shared.gl, '.useProgram(', PROGRAM, '.program);',
'if(!', CACHED_PROC, '){',
CACHED_PROC, '=', progCache, '[', PROG_ID, ']=',
env.link(function (program) {
return createBody(
emitBatchDynamicShaderBody, env, args, program, 2)
}), '(', PROGRAM, ');}',
CACHED_PROC, '.call(this,a0[', BATCH_ID, '],', BATCH_ID, ');')
} else {
if (args.useVAO) {
if (args.drawVAO) {
if (isInnerDefn(args.drawVAO)) {
// vao is a prop
inner(env.shared.vao, '.setVAO(', args.drawVAO.append(env, inner), ');')
} else {
// vao is invariant
outer(env.shared.vao, '.setVAO(', args.drawVAO.append(env, outer), ');')
}
} else {
// scoped vao binding
outer(env.shared.vao, '.setVAO(', env.shared.vao, '.targetVAO);')
}
} else {
outer(env.shared.vao, '.setVAO(null);')
emitAttributes(env, outer, args, program.attributes, isOuterDefn)
emitAttributes(env, inner, args, program.attributes, isInnerDefn)
}
emitUniforms(env, outer, args, program.uniforms, isOuterDefn)
emitUniforms(env, inner, args, program.uniforms, isInnerDefn)
emitDraw(env, outer, inner, args)
}
}
function emitBatchProc (env, args) {
var batch = env.proc('batch', 2)
env.batchId = '0'
injectExtensions(env, batch)
// Check if any context variables depend on props
var contextDynamic = false
var needsContext = true
Object.keys(args.context).forEach(function (name) {
contextDynamic = contextDynamic || args.context[name].propDep
})
if (!contextDynamic) {
emitContext(env, batch, args.context)
needsContext = false
}
// framebuffer state affects framebufferWidth/height context vars
var framebuffer = args.framebuffer
var needsFramebuffer = false
if (framebuffer) {
if (framebuffer.propDep) {
contextDynamic = needsFramebuffer = true
} else if (framebuffer.contextDep && contextDynamic) {
needsFramebuffer = true
}
if (!needsFramebuffer) {
emitPollFramebuffer(env, batch, framebuffer)
}
} else {
emitPollFramebuffer(env, batch, null)
}
// viewport is weird because it can affect context vars
if (args.state.viewport && args.state.viewport.propDep) {
contextDynamic = true
}
function isInnerDefn (defn) {
return (defn.contextDep && contextDynamic) || defn.propDep
}
// set webgl options
emitPollState(env, batch, args)
emitSetOptions(env, batch, args.state, function (defn) {
return !isInnerDefn(defn)
})
if (!args.profile || !isInnerDefn(args.profile)) {
emitProfile(env, batch, args, false, 'a1')
}
// Save these values to args so that the batch body routine can use them
args.contextDep = contextDynamic
args.needsContext = needsContext
args.needsFramebuffer = needsFramebuffer
// determine if shader is dynamic
var progDefn = args.shader.progVar
if ((progDefn.contextDep && contextDynamic) || progDefn.propDep) {
emitBatchBody(
env,
batch,
args,
null)
} else {
var PROGRAM = progDefn.append(env, batch)
batch(env.shared.gl, '.useProgram(', PROGRAM, '.program);')
if (args.shader.program) {
emitBatchBody(
env,
batch,
args,
args.shader.program)
} else {
batch(env.shared.vao, '.setVAO(null);')
var batchCache = env.global.def('{}')
var PROG_ID = batch.def(PROGRAM, '.id')
var CACHED_PROC = batch.def(batchCache, '[', PROG_ID, ']')
batch(
env.cond(CACHED_PROC)
.then(CACHED_PROC, '.call(this,a0,a1);')
.else(
CACHED_PROC, '=', batchCache, '[', PROG_ID, ']=',
env.link(function (program) {
return createBody(emitBatchBody, env, args, program, 2)
}), '(', PROGRAM, ');',
CACHED_PROC, '.call(this,a0,a1);'))
}
}
if (Object.keys(args.state).length > 0) {
batch(env.shared.current, '.dirty=true;')
}
}
// ===================================================
// ===================================================
// SCOPE COMMAND
// ===================================================
// ===================================================
function emitScopeProc (env, args) {
var scope = env.proc('scope', 3)
env.batchId = 'a2'
var shared = env.shared
var CURRENT_STATE = shared.current
emitContext(env, scope, args.context)
if (args.framebuffer) {
args.framebuffer.append(env, scope)
}
sortState(Object.keys(args.state)).forEach(function (name) {
var defn = args.state[name]
var value = defn.append(env, scope)
if (isArrayLike(value)) {
value.forEach(function (v, i) {
scope.set(env.next[name], '[' + i + ']', v)
})
} else {
scope.set(shared.next, '.' + name, value)
}
})
emitProfile(env, scope, args, true, true)
;[S_ELEMENTS, S_OFFSET, S_COUNT, S_INSTANCES, S_PRIMITIVE].forEach(
function (opt) {
var variable = args.draw[opt]
if (!variable) {
return
}
scope.set(shared.draw, '.' + opt, '' + variable.append(env, scope))
})
Object.keys(args.uniforms).forEach(function (opt) {
scope.set(
shared.uniforms,
'[' + stringStore.id(opt) + ']',
args.uniforms[opt].append(env, scope))
})
Object.keys(args.attributes).forEach(function (name) {
var record = args.attributes[name].append(env, scope)
var scopeAttrib = env.scopeAttrib(name)
Object.keys(new AttributeRecord()).forEach(function (prop) {
scope.set(scopeAttrib, '.' + prop, record[prop])
})
})
if (args.scopeVAO) {
scope.set(shared.vao, '.targetVAO', args.scopeVAO.append(env, scope))
}
function saveShader (name) {
var shader = args.shader[name]
if (shader) {
scope.set(shared.shader, '.' + name, shader.append(env, scope))
}
}
saveShader(S_VERT)
saveShader(S_FRAG)
if (Object.keys(args.state).length > 0) {
scope(CURRENT_STATE, '.dirty=true;')
scope.exit(CURRENT_STATE, '.dirty=true;')
}
scope('a1(', env.shared.context, ',a0,', env.batchId, ');')
}
function isDynamicObject (object) {
if (typeof object !== 'object' || isArrayLike(object)) {
return
}
var props = Object.keys(object)
for (var i = 0; i < props.length; ++i) {
if (dynamic.isDynamic(object[props[i]])) {
return true
}
}
return false
}
function splatObject (env, options, name) {
var object = options.static[name]
if (!object || !isDynamicObject(object)) {
return
}
var globals = env.global
var keys = Object.keys(object)
var thisDep = false
var contextDep = false
var propDep = false
var objectRef = env.global.def('{}')
keys.forEach(function (key) {
var value = object[key]
if (dynamic.isDynamic(value)) {
if (typeof value === 'function') {
value = object[key] = dynamic.unbox(value)
}
var deps = createDynamicDecl(value, null)
thisDep = thisDep || deps.thisDep
propDep = propDep || deps.propDep
contextDep = contextDep || deps.contextDep
} else {
globals(objectRef, '.', key, '=')
switch (typeof value) {
case 'number':
globals(value)
break
case 'string':
globals('"', value, '"')
break
case 'object':
if (Array.isArray(value)) {
globals('[', value.join(), ']')
}
break
default:
globals(env.link(value))
break
}
globals(';')
}
})
function appendBlock (env, block) {
keys.forEach(function (key) {
var value = object[key]
if (!dynamic.isDynamic(value)) {
return
}
var ref = env.invoke(block, value)
block(objectRef, '.', key, '=', ref, ';')
})
}
options.dynamic[name] = new dynamic.DynamicVariable(DYN_THUNK, {
thisDep: thisDep,
contextDep: contextDep,
propDep: propDep,
ref: objectRef,
append: appendBlock
})
delete options.static[name]
}
// ===========================================================================
// ===========================================================================
// MAIN DRAW COMMAND
// ===========================================================================
// ===========================================================================
function compileCommand (options, attributes, uniforms, context, stats) {
var env = createREGLEnvironment()
// link stats, so that we can easily access it in the program.
env.stats = env.link(stats)
// splat options and attributes to allow for dynamic nested properties
Object.keys(attributes.static).forEach(function (key) {
splatObject(env, attributes, key)
})
NESTED_OPTIONS.forEach(function (name) {
splatObject(env, options, name)
})
var args = parseArguments(options, attributes, uniforms, context, env)
emitDrawProc(env, args)
emitScopeProc(env, args)
emitBatchProc(env, args)
return env.compile()
}
// ===========================================================================
// ===========================================================================
// POLL / REFRESH
// ===========================================================================
// ===========================================================================
return {
next: nextState,
current: currentState,
procs: (function () {
var env = createREGLEnvironment()
var poll = env.proc('poll')
var refresh = env.proc('refresh')
var common = env.block()
poll(common)
refresh(common)
var shared = env.shared
var GL = shared.gl
var NEXT_STATE = shared.next
var CURRENT_STATE = shared.current
common(CURRENT_STATE, '.dirty=false;')
emitPollFramebuffer(env, poll)
emitPollFramebuffer(env, refresh, null, true)
// Refresh updates all attribute state changes
var INSTANCING
if (extInstancing) {
INSTANCING = env.link(extInstancing)
}
// update vertex array bindings
if (extensions.oes_vertex_array_object) {
refresh(env.link(extensions.oes_vertex_array_object), '.bindVertexArrayOES(null);')
}
for (var i = 0; i < limits.maxAttributes; ++i) {
var BINDING = refresh.def(shared.attributes, '[', i, ']')
var ifte = env.cond(BINDING, '.buffer')
ifte.then(
GL, '.enableVertexAttribArray(', i, ');',
GL, '.bindBuffer(',
GL_ARRAY_BUFFER$2, ',',
BINDING, '.buffer.buffer);',
GL, '.vertexAttribPointer(',
i, ',',
BINDING, '.size,',
BINDING, '.type,',
BINDING, '.normalized,',
BINDING, '.stride,',
BINDING, '.offset);'
).else(
GL, '.disableVertexAttribArray(', i, ');',
GL, '.vertexAttrib4f(',
i, ',',
BINDING, '.x,',
BINDING, '.y,',
BINDING, '.z,',
BINDING, '.w);',
BINDING, '.buffer=null;')
refresh(ifte)
if (extInstancing) {
refresh(
INSTANCING, '.vertexAttribDivisorANGLE(',
i, ',',
BINDING, '.divisor);')
}
}
refresh(
env.shared.vao, '.currentVAO=null;',
env.shared.vao, '.setVAO(', env.shared.vao, '.targetVAO);')
Object.keys(GL_FLAGS).forEach(function (flag) {
var cap = GL_FLAGS[flag]
var NEXT = common.def(NEXT_STATE, '.', flag)
var block = env.block()
block('if(', NEXT, '){',
GL, '.enable(', cap, ')}else{',
GL, '.disable(', cap, ')}',
CURRENT_STATE, '.', flag, '=', NEXT, ';')
refresh(block)
poll(
'if(', NEXT, '!==', CURRENT_STATE, '.', flag, '){',
block,
'}')
})
Object.keys(GL_VARIABLES).forEach(function (name) {
var func = GL_VARIABLES[name]
var init = currentState[name]
var NEXT, CURRENT
var block = env.block()
block(GL, '.', func, '(')
if (isArrayLike(init)) {
var n = init.length
NEXT = env.global.def(NEXT_STATE, '.', name)
CURRENT = env.global.def(CURRENT_STATE, '.', name)
block(
loop(n, function (i) {
return NEXT + '[' + i + ']'
}), ');',
loop(n, function (i) {
return CURRENT + '[' + i + ']=' + NEXT + '[' + i + '];'
}).join(''))
poll(
'if(', loop(n, function (i) {
return NEXT + '[' + i + ']!==' + CURRENT + '[' + i + ']'
}).join('||'), '){',
block,
'}')
} else {
NEXT = common.def(NEXT_STATE, '.', name)
CURRENT = common.def(CURRENT_STATE, '.', name)
block(
NEXT, ');',
CURRENT_STATE, '.', name, '=', NEXT, ';')
poll(
'if(', NEXT, '!==', CURRENT, '){',
block,
'}')
}
refresh(block)
})
return env.compile()
})(),
compile: compileCommand
}
}
function stats () {
return {
vaoCount: 0,
bufferCount: 0,
elementsCount: 0,
framebufferCount: 0,
shaderCount: 0,
textureCount: 0,
cubeCount: 0,
renderbufferCount: 0,
maxTextureUnits: 0
}
}
var GL_QUERY_RESULT_EXT = 0x8866
var GL_QUERY_RESULT_AVAILABLE_EXT = 0x8867
var GL_TIME_ELAPSED_EXT = 0x88BF
var createTimer = function (gl, extensions) {
if (!extensions.ext_disjoint_timer_query) {
return null
}
// QUERY POOL BEGIN
var queryPool = []
function allocQuery () {
return queryPool.pop() || extensions.ext_disjoint_timer_query.createQueryEXT()
}
function freeQuery (query) {
queryPool.push(query)
}
// QUERY POOL END
var pendingQueries = []
function beginQuery (stats) {
var query = allocQuery()
extensions.ext_disjoint_timer_query.beginQueryEXT(GL_TIME_ELAPSED_EXT, query)
pendingQueries.push(query)
pushScopeStats(pendingQueries.length - 1, pendingQueries.length, stats)
}
function endQuery () {
extensions.ext_disjoint_timer_query.endQueryEXT(GL_TIME_ELAPSED_EXT)
}
//
// Pending stats pool.
//
function PendingStats () {
this.startQueryIndex = -1
this.endQueryIndex = -1
this.sum = 0
this.stats = null
}
var pendingStatsPool = []
function allocPendingStats () {
return pendingStatsPool.pop() || new PendingStats()
}
function freePendingStats (pendingStats) {
pendingStatsPool.push(pendingStats)
}
// Pending stats pool end
var pendingStats = []
function pushScopeStats (start, end, stats) {
var ps = allocPendingStats()
ps.startQueryIndex = start
ps.endQueryIndex = end
ps.sum = 0
ps.stats = stats
pendingStats.push(ps)
}
// we should call this at the beginning of the frame,
// in order to update gpuTime
var timeSum = []
var queryPtr = []
function update () {
var ptr, i
var n = pendingQueries.length
if (n === 0) {
return
}
// Reserve space
queryPtr.length = Math.max(queryPtr.length, n + 1)
timeSum.length = Math.max(timeSum.length, n + 1)
timeSum[0] = 0
queryPtr[0] = 0
// Update all pending timer queries
var queryTime = 0
ptr = 0
for (i = 0; i < pendingQueries.length; ++i) {
var query = pendingQueries[i]
if (extensions.ext_disjoint_timer_query.getQueryObjectEXT(query, GL_QUERY_RESULT_AVAILABLE_EXT)) {
queryTime += extensions.ext_disjoint_timer_query.getQueryObjectEXT(query, GL_QUERY_RESULT_EXT)
freeQuery(query)
} else {
pendingQueries[ptr++] = query
}
timeSum[i + 1] = queryTime
queryPtr[i + 1] = ptr
}
pendingQueries.length = ptr
// Update all pending stat queries
ptr = 0
for (i = 0; i < pendingStats.length; ++i) {
var stats = pendingStats[i]
var start = stats.startQueryIndex
var end = stats.endQueryIndex
stats.sum += timeSum[end] - timeSum[start]
var startPtr = queryPtr[start]
var endPtr = queryPtr[end]
if (endPtr === startPtr) {
stats.stats.gpuTime += stats.sum / 1e6
freePendingStats(stats)
} else {
stats.startQueryIndex = startPtr
stats.endQueryIndex = endPtr
pendingStats[ptr++] = stats
}
}
pendingStats.length = ptr
}
return {
beginQuery: beginQuery,
endQuery: endQuery,
pushScopeStats: pushScopeStats,
update: update,
getNumPendingQueries: function () {
return pendingQueries.length
},
clear: function () {
queryPool.push.apply(queryPool, pendingQueries)
for (var i = 0; i < queryPool.length; i++) {
extensions.ext_disjoint_timer_query.deleteQueryEXT(queryPool[i])
}
pendingQueries.length = 0
queryPool.length = 0
},
restore: function () {
pendingQueries.length = 0
queryPool.length = 0
}
}
}
var GL_COLOR_BUFFER_BIT = 16384
var GL_DEPTH_BUFFER_BIT = 256
var GL_STENCIL_BUFFER_BIT = 1024
var GL_ARRAY_BUFFER = 34962
var CONTEXT_LOST_EVENT = 'webglcontextlost'
var CONTEXT_RESTORED_EVENT = 'webglcontextrestored'
var DYN_PROP = 1
var DYN_CONTEXT = 2
var DYN_STATE = 3
function find (haystack, needle) {
for (var i = 0; i < haystack.length; ++i) {
if (haystack[i] === needle) {
return i
}
}
return -1
}
function wrapREGL (args) {
var config = parseArgs(args)
if (!config) {
return null
}
var gl = config.gl
var glAttributes = gl.getContextAttributes()
var contextLost = gl.isContextLost()
var extensionState = createExtensionCache(gl, config)
if (!extensionState) {
return null
}
var stringStore = createStringStore()
var stats$$1 = stats()
var extensions = extensionState.extensions
var timer = createTimer(gl, extensions)
var START_TIME = clock()
var WIDTH = gl.drawingBufferWidth
var HEIGHT = gl.drawingBufferHeight
var contextState = {
tick: 0,
time: 0,
viewportWidth: WIDTH,
viewportHeight: HEIGHT,
framebufferWidth: WIDTH,
framebufferHeight: HEIGHT,
drawingBufferWidth: WIDTH,
drawingBufferHeight: HEIGHT,
pixelRatio: config.pixelRatio
}
var uniformState = {}
var drawState = {
elements: null,
primitive: 4, // GL_TRIANGLES
count: -1,
offset: 0,
instances: -1
}
var limits = wrapLimits(gl, extensions)
var bufferState = wrapBufferState(
gl,
stats$$1,
config,
destroyBuffer)
var attributeState = wrapAttributeState(
gl,
extensions,
limits,
stats$$1,
bufferState)
function destroyBuffer (buffer) {
return attributeState.destroyBuffer(buffer)
}
var elementState = wrapElementsState(gl, extensions, bufferState, stats$$1)
var shaderState = wrapShaderState(gl, stringStore, stats$$1, config)
var textureState = createTextureSet(
gl,
extensions,
limits,
function () { core.procs.poll() },
contextState,
stats$$1,
config)
var renderbufferState = wrapRenderbuffers(gl, extensions, limits, stats$$1, config)
var framebufferState = wrapFBOState(
gl,
extensions,
limits,
textureState,
renderbufferState,
stats$$1)
var core = reglCore(
gl,
stringStore,
extensions,
limits,
bufferState,
elementState,
textureState,
framebufferState,
uniformState,
attributeState,
shaderState,
drawState,
contextState,
timer,
config)
var readPixels = wrapReadPixels(
gl,
framebufferState,
core.procs.poll,
contextState,
glAttributes, extensions, limits)
var nextState = core.next
var canvas = gl.canvas
var rafCallbacks = []
var lossCallbacks = []
var restoreCallbacks = []
var destroyCallbacks = [config.onDestroy]
var activeRAF = null
function handleRAF () {
if (rafCallbacks.length === 0) {
if (timer) {
timer.update()
}
activeRAF = null
return
}
// schedule next animation frame
activeRAF = raf.next(handleRAF)
// poll for changes
poll()
// fire a callback for all pending rafs
for (var i = rafCallbacks.length - 1; i >= 0; --i) {
var cb = rafCallbacks[i]
if (cb) {
cb(contextState, null, 0)
}
}
// flush all pending webgl calls
gl.flush()
// poll GPU timers *after* gl.flush so we don't delay command dispatch
if (timer) {
timer.update()
}
}
function startRAF () {
if (!activeRAF && rafCallbacks.length > 0) {
activeRAF = raf.next(handleRAF)
}
}
function stopRAF () {
if (activeRAF) {
raf.cancel(handleRAF)
activeRAF = null
}
}
function handleContextLoss (event) {
event.preventDefault()
// set context lost flag
contextLost = true
// pause request animation frame
stopRAF()
// lose context
lossCallbacks.forEach(function (cb) {
cb()
})
}
function handleContextRestored (event) {
// clear error code
gl.getError()
// clear context lost flag
contextLost = false
// refresh state
extensionState.restore()
shaderState.restore()
bufferState.restore()
textureState.restore()
renderbufferState.restore()
framebufferState.restore()
attributeState.restore()
if (timer) {
timer.restore()
}
// refresh state
core.procs.refresh()
// restart RAF
startRAF()
// restore context
restoreCallbacks.forEach(function (cb) {
cb()
})
}
if (canvas) {
canvas.addEventListener(CONTEXT_LOST_EVENT, handleContextLoss, false)
canvas.addEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored, false)
}
function destroy () {
rafCallbacks.length = 0
stopRAF()
if (canvas) {
canvas.removeEventListener(CONTEXT_LOST_EVENT, handleContextLoss)
canvas.removeEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored)
}
shaderState.clear()
framebufferState.clear()
renderbufferState.clear()
textureState.clear()
elementState.clear()
bufferState.clear()
attributeState.clear()
if (timer) {
timer.clear()
}
destroyCallbacks.forEach(function (cb) {
cb()
})
}
function compileProcedure (options) {
check$1(!!options, 'invalid args to regl({...})')
check$1.type(options, 'object', 'invalid args to regl({...})')
function flattenNestedOptions (options) {
var result = extend({}, options)
delete result.uniforms
delete result.attributes
delete result.context
delete result.vao
if ('stencil' in result && result.stencil.op) {
result.stencil.opBack = result.stencil.opFront = result.stencil.op
delete result.stencil.op
}
function merge (name) {
if (name in result) {
var child = result[name]
delete result[name]
Object.keys(child).forEach(function (prop) {
result[name + '.' + prop] = child[prop]
})
}
}
merge('blend')
merge('depth')
merge('cull')
merge('stencil')
merge('polygonOffset')
merge('scissor')
merge('sample')
if ('vao' in options) {
result.vao = options.vao
}
return result
}
function separateDynamic (object) {
var staticItems = {}
var dynamicItems = {}
Object.keys(object).forEach(function (option) {
var value = object[option]
if (dynamic.isDynamic(value)) {
dynamicItems[option] = dynamic.unbox(value, option)
} else {
staticItems[option] = value
}
})
return {
dynamic: dynamicItems,
static: staticItems
}
}
// Treat context variables separate from other dynamic variables
var context = separateDynamic(options.context || {})
var uniforms = separateDynamic(options.uniforms || {})
var attributes = separateDynamic(options.attributes || {})
var opts = separateDynamic(flattenNestedOptions(options))
var stats$$1 = {
gpuTime: 0.0,
cpuTime: 0.0,
count: 0
}
var compiled = core.compile(opts, attributes, uniforms, context, stats$$1)
var draw = compiled.draw
var batch = compiled.batch
var scope = compiled.scope
// FIXME: we should modify code generation for batch commands so this
// isn't necessary
var EMPTY_ARRAY = []
function reserve (count) {
while (EMPTY_ARRAY.length < count) {
EMPTY_ARRAY.push(null)
}
return EMPTY_ARRAY
}
function REGLCommand (args, body) {
var i
if (contextLost) {
check$1.raise('context lost')
}
if (typeof args === 'function') {
return scope.call(this, null, args, 0)
} else if (typeof body === 'function') {
if (typeof args === 'number') {
for (i = 0; i < args; ++i) {
scope.call(this, null, body, i)
}
} else if (Array.isArray(args)) {
for (i = 0; i < args.length; ++i) {
scope.call(this, args[i], body, i)
}
} else {
return scope.call(this, args, body, 0)
}
} else if (typeof args === 'number') {
if (args > 0) {
return batch.call(this, reserve(args | 0), args | 0)
}
} else if (Array.isArray(args)) {
if (args.length) {
return batch.call(this, args, args.length)
}
} else {
return draw.call(this, args)
}
}
return extend(REGLCommand, {
stats: stats$$1
})
}
var setFBO = framebufferState.setFBO = compileProcedure({
framebuffer: dynamic.define.call(null, DYN_PROP, 'framebuffer')
})
function clearImpl (_, options) {
var clearFlags = 0
core.procs.poll()
var c = options.color
if (c) {
gl.clearColor(+c[0] || 0, +c[1] || 0, +c[2] || 0, +c[3] || 0)
clearFlags |= GL_COLOR_BUFFER_BIT
}
if ('depth' in options) {
gl.clearDepth(+options.depth)
clearFlags |= GL_DEPTH_BUFFER_BIT
}
if ('stencil' in options) {
gl.clearStencil(options.stencil | 0)
clearFlags |= GL_STENCIL_BUFFER_BIT
}
check$1(!!clearFlags, 'called regl.clear with no buffer specified')
gl.clear(clearFlags)
}
function clear (options) {
check$1(
typeof options === 'object' && options,
'regl.clear() takes an object as input')
if ('framebuffer' in options) {
if (options.framebuffer &&
options.framebuffer_reglType === 'framebufferCube') {
for (var i = 0; i < 6; ++i) {
setFBO(extend({
framebuffer: options.framebuffer.faces[i]
}, options), clearImpl)
}
} else {
setFBO(options, clearImpl)
}
} else {
clearImpl(null, options)
}
}
function frame (cb) {
check$1.type(cb, 'function', 'regl.frame() callback must be a function')
rafCallbacks.push(cb)
function cancel () {
// FIXME: should we check something other than equals cb here?
// what if a user calls frame twice with the same callback...
//
var i = find(rafCallbacks, cb)
check$1(i >= 0, 'cannot cancel a frame twice')
function pendingCancel () {
var index = find(rafCallbacks, pendingCancel)
rafCallbacks[index] = rafCallbacks[rafCallbacks.length - 1]
rafCallbacks.length -= 1
if (rafCallbacks.length <= 0) {
stopRAF()
}
}
rafCallbacks[i] = pendingCancel
}
startRAF()
return {
cancel: cancel
}
}
// poll viewport
function pollViewport () {
var viewport = nextState.viewport
var scissorBox = nextState.scissor_box
viewport[0] = viewport[1] = scissorBox[0] = scissorBox[1] = 0
contextState.viewportWidth =
contextState.framebufferWidth =
contextState.drawingBufferWidth =
viewport[2] =
scissorBox[2] = gl.drawingBufferWidth
contextState.viewportHeight =
contextState.framebufferHeight =
contextState.drawingBufferHeight =
viewport[3] =
scissorBox[3] = gl.drawingBufferHeight
}
function poll () {
contextState.tick += 1
contextState.time = now()
pollViewport()
core.procs.poll()
}
function refresh () {
pollViewport()
core.procs.refresh()
if (timer) {
timer.update()
}
}
function now () {
return (clock() - START_TIME) / 1000.0
}
refresh()
function addListener (event, callback) {
check$1.type(callback, 'function', 'listener callback must be a function')
var callbacks
switch (event) {
case 'frame':
return frame(callback)
case 'lost':
callbacks = lossCallbacks
break
case 'restore':
callbacks = restoreCallbacks
break
case 'destroy':
callbacks = destroyCallbacks
break
default:
check$1.raise('invalid event, must be one of frame,lost,restore,destroy')
}
callbacks.push(callback)
return {
cancel: function () {
for (var i = 0; i < callbacks.length; ++i) {
if (callbacks[i] === callback) {
callbacks[i] = callbacks[callbacks.length - 1]
callbacks.pop()
return
}
}
}
}
}
var regl = extend(compileProcedure, {
// Clear current FBO
clear: clear,
// Short cuts for dynamic variables
prop: dynamic.define.bind(null, DYN_PROP),
context: dynamic.define.bind(null, DYN_CONTEXT),
this: dynamic.define.bind(null, DYN_STATE),
// executes an empty draw command
draw: compileProcedure({}),
// Resources
buffer: function (options) {
return bufferState.create(options, GL_ARRAY_BUFFER, false, false)
},
elements: function (options) {
return elementState.create(options, false)
},
texture: textureState.create2D,
cube: textureState.createCube,
renderbuffer: renderbufferState.create,
framebuffer: framebufferState.create,
framebufferCube: framebufferState.createCube,
vao: attributeState.createVAO,
// Expose context attributes
attributes: glAttributes,
// Frame rendering
frame: frame,
on: addListener,
// System limits
limits: limits,
hasExtension: function (name) {
return limits.extensions.indexOf(name.toLowerCase()) >= 0
},
// Read pixels
read: readPixels,
// Destroy regl and all associated resources
destroy: destroy,
// Direct GL state manipulation
_gl: gl,
_refresh: refresh,
poll: function () {
poll()
if (timer) {
timer.update()
}
},
// Current time
now: now,
// regl Statistics Information
stats: stats$$1
})
config.onDone(null, regl)
return regl
}
return wrapREGL;
})));
//# sourceMappingURL=regl.js.map
|
export const beforeHooks = {
global: ["auth:verify"]
};
export const afterHooks = { global: [] };
|
import demo from './index';
import {makeDOMDriver} from '@cycle/dom';
import {run} from '@cycle/core';
const main = demo;
run(main, {
DOM: makeDOMDriver(`.demo-container`),
});
|
/*
* View Source
* Generates copy/pastable markup from actual rendered markup.
*
* Copyright (c) 2012 Filament Group, Inc.
* Licensed under the MIT, GPL licenses.
*/
(function( $ ) {
var pluginName = "xrayhtml",
o = {
text: {
open: "View Source",
close: "View Demo"
},
classes: {
button: "btn btn-small",
open: "view-source",
sourcepanel: "source-panel"
},
initSelector: "[data-" + pluginName + "]",
defaultReveal: "inline"
},
methods = {
_create: function() {
return $( this ).each(function() {
var init = $( this ).data( "init." + pluginName );
if( init ) {
return false;
}
$( this )
.data( "init." + pluginName, true )
[ pluginName ]( "_init" )
.trigger( "create." + pluginName );
});
},
_init: function() {
var method = $( this ).data( pluginName ) || o.defaultReveal;
if( method === "flip" ) {
$( this )[ pluginName ]( "_createButton" );
}
$( this )
.addClass( pluginName + " " + "method-" + method )
[ pluginName ]( "_createSource" );
},
_createButton: function() {
var btn = document.createElement( "a" ),
txt = document.createTextNode( o.text.open ),
el = $( this );
btn.setAttribute( "class", o.classes.button );
btn.href = "#";
btn.appendChild( txt );
$( btn )
.bind( "click", function( e ) {
var isOpen = el.attr( "class" ).indexOf( o.classes.open ) > -1;
el[ isOpen ? "removeClass" : "addClass" ]( o.classes.open );
btn.innerHTML = ( isOpen ? o.text.open : o.text.close );
e.preventDefault();
})
.insertBefore( el );
},
_createSource: function() {
var el = this,
preel = document.createElement( "pre" ),
codeel = document.createElement( "code" ),
wrap = document.createElement( "div" ),
sourcepanel = document.createElement( "div" ),
code = el.innerHTML,
source = document.createTextNode( code );
wrap.setAttribute( "class", "snippet" );
$( el ).wrapInner( wrap );
codeel.appendChild( source );
preel.appendChild( codeel );
sourcepanel.setAttribute( "class", o.classes.sourcepanel );
sourcepanel.appendChild( preel );
this.appendChild( sourcepanel );
}
};
// Collection method.
$.fn[ pluginName ] = function( arrg, a, b, c ) {
return this.each(function() {
// if it's a method
if( arrg && typeof( arrg ) === "string" ){
return $.fn[ pluginName ].prototype[ arrg ].call( this, a, b, c );
}
// don't re-init
if( $( this ).data( pluginName + "data" ) ){
return $( this );
}
// otherwise, init
$( this ).data( pluginName + "active", true );
$.fn[ pluginName ].prototype._create.call( this );
});
};
// add methods
$.extend( $.fn[ pluginName ].prototype, methods );
// DOM-ready auto-init
$( function(){
$( o.initSelector )[ pluginName ]();
});
}( jQuery ));
|
// var process = require('child_process');
// const globby = require('globby');
// const shell = require('shelljs');
// const buildReveal = async () => {
// const paths = await globby('md/*.md')
// paths.forEach((path) => {
// const name = path.match(/md\/(\w*).md/)
// if(name[1]) {
// shell.exec(`reveal-md ./md/${name[1]}.md --static web`)
// shell.exec(`mv ./web/index.html ./web/${name[1]}.html`)
// shell.echo(`${name[1]} has been done`)
// }
// })
// shell.exec(`mkdir -p ./web/copy-img`);
// shell.exec(`cp ./md/copy-img/* ./web/copy-img`);
// }
// buildReveal()
var process = require('child_process');
var pageList = [
'vue-cli',
'vue-specification',
'vue-startup',
'vue-test',
'weapp',
'pwa',
'microfrontend',
'index',
'svelte',
'lerna'
]
pageList.forEach((page)=> {
process.execSync(`reveal-md ./md/${page}.md --static web`);
process.execSync(`mv ./web/index.html ./web/${page}.html`);
})
// process.execSync(`mkdir -p ./web/copy-img`);
// process.execSync(`cp ./md/copy-img/* ./web/copy-img`);
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Export from './export';
import Delete from './delete';
import Quantity from './quantity';
import NonOption from '../featureValues/nonOption';
import Option from '../featureValues/option';
export default class Edit extends Component {
featureComponents() {
const { enquiry, product } = this.props;
return Object.keys(enquiry.feature_values).map((id) => {
const fv = enquiry.feature_values[id];
const feature = product.features[fv.feature_id];
if (feature.feature_type === "float" ||
feature.feature_type === "integer" ||
feature.feature_type === "string") {
return (<NonOption key={feature.id} feature={feature} featureValue={fv} />);
} else if (feature.feature_type === "option") {
return (<Option key={feature.id} feature={feature} featureValue={fv} />);
} else {
return null;
}
});
}
render() {
const { enquiry } = this.props;
return (
<div>
<div className="row">
<div className="col-xs-12">
<div className="pull-left">
<ul className="list-inline">
<li><Export id={enquiry.id} /></li>
<li><Delete id={enquiry.id} /></li>
</ul>
</div>
</div>
</div>
<div className="row">
<div className="col-xs-4">
{<Quantity id={enquiry.id} name={'quantity'} value={enquiry.quantity} />}
</div>
<div className="col-xs-4">
{<Quantity id={enquiry.id} name={'quantity2'} value={enquiry.quantity2} />}
</div>
<div className="col-xs-4">
{<Quantity id={enquiry.id} name={'quantity3'} value={enquiry.quantity3} />}
</div>
<div className="col-xs-12">
{this.featureComponents()}
</div>
</div>
</div>
);
}
}
Edit.propTypes = {
enquiry: PropTypes.object.isRequired,
product: PropTypes.object.isRequired,
};
|
'use strict';
const gulp = tars.packages.gulp;
const gulpif = tars.packages.gulpif;
const rename = tars.packages.rename;
const plumber = tars.packages.plumber;
const notifier = tars.helpers.notifier;
const skipTaskWithEmptyPipe = tars.helpers.skipTaskWithEmptyPipe;
const svgImagesPath = `./dev/${tars.config.fs.staticFolderName}/${tars.config.fs.imagesFolderName}/minified-svg/`;
let readySymbolSpritePath = `./dev/${tars.config.svg.symbolsConfig.pathToExternalSymbolsFile}`;
if (tars.config.svg.symbolsConfig.loadingType === 'inject') {
readySymbolSpritePath = './dev/temp/';
}
/**
* Minify png and jpg images
*/
module.exports = () => {
return gulp.task('images:make-symbols-sprite', done => {
if (tars.config.svg.active && tars.config.svg.workflow === 'symbols') {
return gulp.src(`${svgImagesPath}**/*.svg`)
.pipe(plumber({
errorHandler(error) {
notifier.error('An error occurred while creating symbols sprite.', error);
}
}))
.pipe(skipTaskWithEmptyPipe('images:make-symbols-sprite', done))
.pipe(tars.require('gulp-svg-symbols')(
{
templates: [
`${tars.root}/tasks/images/helpers/svg-symbols.svg`,
`${tars.root}/tasks/images/helpers/symbols-data-template.js`
],
transformData: (svg, defaultData) => {
return {
id: defaultData.id,
width: svg.width,
height: svg.height,
name: svg.name
};
}
}
))
.pipe(
gulpif(/[.]svg$/, rename(spritePath => {
spritePath.basename;
//spritePath.basename += tars.options.build.hash;
}))
)
.pipe(
gulpif(/[.]svg$/, gulp.dest(readySymbolSpritePath))
)
.pipe(
gulpif(/[.]js$/, gulp.dest('./dev/temp/'))
)
.pipe(
notifier.success('Symbols sprite\'s been created')
);
}
tars.skipTaskLog('images:make-symbols-sprite', 'SVG is not used or you prefer svg-sprite workflow');
done(null);
});
};
|
'use strict';
describe('filters', function() {
var filter;
beforeEach(inject(function($filter) {
filter = $filter;
}));
it('should call the filter when evaluating expression', function() {
var filter = jasmine.createSpy('myFilter');
createInjector(['ng', function($filterProvider) {
$filterProvider.register('myFilter', valueFn(filter));
}]).invoke(function($rootScope) {
$rootScope.$eval('10|myFilter');
});
expect(filter).toHaveBeenCalledWith(10);
});
describe('formatNumber', function() {
/* global formatNumber: false */
var pattern;
beforeEach(function() {
pattern = { minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3 };
});
it('should format according to different patterns', function() {
pattern.gSize = 2;
var num = formatNumber(1234567.89, pattern, ',', '.');
expect(num).toBe('12,34,567.89');
num = formatNumber(1234.56, pattern, ',', '.');
expect(num).toBe('1,234.56');
pattern.negPre = '(';
pattern.negSuf = '-)';
num = formatNumber(-1234, pattern, ',', '.');
expect(num).toBe('(1,234-)');
pattern.posPre = '+';
pattern.posSuf = '+';
num = formatNumber(1234, pattern, ',', '.');
expect(num).toBe('+1,234+');
pattern.posPre = pattern.posSuf = '';
pattern.minFrac = 2;
num = formatNumber(1, pattern, ',', '.');
expect(num).toBe('1.00');
pattern.maxFrac = 4;
num = formatNumber(1.11119, pattern, ',', '.');
expect(num).toBe('1.1112');
});
it('should format according different separators', function() {
var num = formatNumber(1234567.1, pattern, '.', ',', 2);
expect(num).toBe('1.234.567,10');
});
it('should format with or without fractionSize', function() {
var num = formatNumber(123.1, pattern, ',', '.', 3);
expect(num).toBe('123.100');
num = formatNumber(123.12, pattern, ',', '.');
expect(num).toBe('123.12');
num = formatNumber(123.1116, pattern, ',', '.');
expect(num).toBe('123.112');
});
it('should format the same with string as well as numeric fractionSize', function() {
var num = formatNumber(123.1, pattern, ',', '.', "0");
expect(num).toBe('123');
num = formatNumber(123.1, pattern, ',', '.', 0);
expect(num).toBe('123');
num = formatNumber(123.1, pattern, ',', '.', "3");
expect(num).toBe('123.100');
num = formatNumber(123.1, pattern, ',', '.', 3);
expect(num).toBe('123.100');
});
it('should format numbers that round to zero as nonnegative', function() {
var num = formatNumber(-0.01, pattern, ',', '.', 1);
expect(num).toBe('0.0');
});
});
describe('currency', function() {
var currency;
beforeEach(function() {
currency = filter('currency');
});
it('should do basic currency filtering', function() {
expect(currency(0)).toEqual('$0.00');
expect(currency(-999)).toEqual('($999.00)');
expect(currency(1234.5678, "USD$")).toEqual('USD$1,234.57');
expect(currency(1234.5678, "USD$", 0)).toEqual('USD$1,235');
});
it('should pass through null and undefined to be compatible with one-time binding', function() {
expect(currency(undefined)).toBe(undefined);
expect(currency(null)).toBe(null);
});
it('should return empty string for non-numbers', function() {
expect(currency('abc')).toBe('');
expect(currency({})).toBe('');
});
it('should handle zero and nearly-zero values properly', function() {
// This expression is known to yield 4.440892098500626e-16 instead of 0.0.
expect(currency(1.07 + 1 - 2.07)).toBe('$0.00');
expect(currency(0.008)).toBe('$0.01');
expect(currency(0.003)).toBe('$0.00');
});
it('should set the default fraction size to the max fraction size of the locale value', inject(function($locale) {
$locale.NUMBER_FORMATS.PATTERNS[1].maxFrac = 1;
expect(currency(1.07)).toBe('$1.1');
}));
});
describe('number', function() {
var number;
beforeEach(inject(function($rootScope) {
number = filter('number');
}));
it('should do basic filter', function() {
/* jshint -W008 */
expect(number(0, 0)).toEqual('0');
expect(number(-999)).toEqual('-999');
expect(number(123)).toEqual('123');
expect(number(1234567)).toEqual('1,234,567');
expect(number(1234)).toEqual('1,234');
expect(number(1234.5678)).toEqual('1,234.568');
expect(number(Number.NaN)).toEqual('');
expect(number({})).toEqual('');
expect(number([])).toEqual('');
expect(number(+Infinity)).toEqual('');
expect(number(-Infinity)).toEqual('');
expect(number("1234.5678")).toEqual('1,234.568');
expect(number(1 / 0)).toEqual("");
expect(number(1, 2)).toEqual("1.00");
expect(number(.1, 2)).toEqual("0.10");
expect(number(.01, 2)).toEqual("0.01");
expect(number(.001, 3)).toEqual("0.001");
expect(number(.0001, 3)).toEqual("0.000");
expect(number(9, 2)).toEqual("9.00");
expect(number(.9, 2)).toEqual("0.90");
expect(number(.99, 2)).toEqual("0.99");
expect(number(.999, 3)).toEqual("0.999");
expect(number(.9999, 3)).toEqual("1.000");
expect(number(1.9, 2)).toEqual("1.90");
expect(number(1.99, 2)).toEqual("1.99");
expect(number(1.999, 3)).toEqual("1.999");
expect(number(1.9999, 3)).toEqual("2.000");
expect(number(1234.567, 0)).toEqual("1,235");
expect(number(1234.567, 1)).toEqual("1,234.6");
expect(number(1234.567, 2)).toEqual("1,234.57");
expect(number(1.255, 0)).toEqual("1");
expect(number(1.255, 1)).toEqual("1.3");
expect(number(1.255, 2)).toEqual("1.26");
expect(number(1.255, 3)).toEqual("1.255");
expect(number(0, 8)).toEqual("0.00000000");
});
it('should pass through null and undefined to be compatible with one-time binding', function() {
expect(number(null)).toBe(null);
expect(number(undefined)).toBe(undefined);
});
it('should filter exponentially large numbers', function() {
expect(number(1e50)).toEqual('1e+50');
expect(number(-2e100)).toEqual('-2e+100');
});
it('should ignore fraction sizes for large numbers', function() {
expect(number(1e50, 2)).toEqual('1e+50');
expect(number(-2e100, 5)).toEqual('-2e+100');
});
it('should filter exponentially small numbers', function() {
expect(number(1e-50, 0)).toEqual('0');
expect(number(1e-6, 6)).toEqual('0.000001');
expect(number(1e-7, 6)).toEqual('0.000000');
expect(number(-1e-50, 0)).toEqual('0');
expect(number(-1e-6, 6)).toEqual('-0.000001');
expect(number(-1e-7, 6)).toEqual('-0.000000');
});
});
describe('json', function() {
it('should do basic filter', function() {
expect(filter('json')({a:"b"})).toEqual(toJson({a:"b"}, true));
});
});
describe('lowercase', function() {
it('should do basic filter', function() {
expect(filter('lowercase')('AbC')).toEqual('abc');
expect(filter('lowercase')(null)).toBeNull();
});
});
describe('uppercase', function() {
it('should do basic filter', function() {
expect(filter('uppercase')('AbC')).toEqual('ABC');
expect(filter('uppercase')(null)).toBeNull();
});
});
describe('date', function() {
var morning = new angular.mock.TzDate(+5, '2010-09-03T12:05:08.001Z'); //7am
var noon = new angular.mock.TzDate(+5, '2010-09-03T17:05:08.012Z'); //12pm
var midnight = new angular.mock.TzDate(+5, '2010-09-03T05:05:08.123Z'); //12am
var earlyDate = new angular.mock.TzDate(+5, '0001-09-03T05:05:08.000Z');
var secondWeek = new angular.mock.TzDate(+5, '2013-01-11T12:00:00.000Z'); //Friday Jan 11, 2012
var date;
beforeEach(inject(function($filter) {
date = $filter('date');
}));
it('should ignore falsy inputs', function() {
expect(date(null)).toBeNull();
expect(date('')).toEqual('');
});
it('should do basic filter', function() {
expect(date(noon)).toEqual(date(noon, 'mediumDate'));
expect(date(noon, '')).toEqual(date(noon, 'mediumDate'));
});
it('should accept number or number string representing milliseconds as input', function() {
expect(date(noon.getTime())).toEqual(date(noon.getTime(), 'mediumDate'));
expect(date(noon.getTime() + "")).toEqual(date(noon.getTime() + "", 'mediumDate'));
});
it('should accept various format strings', function() {
expect(date(secondWeek, 'yyyy-Ww')).
toEqual('2013-W2');
expect(date(secondWeek, 'yyyy-Www')).
toEqual('2013-W02');
expect(date(morning, "yy-MM-dd HH:mm:ss")).
toEqual('10-09-03 07:05:08');
expect(date(morning, "yy-MM-dd HH:mm:ss.sss")).
toEqual('10-09-03 07:05:08.001');
expect(date(midnight, "yyyy-M-d h=H:m:saZ")).
toEqual('2010-9-3 12=0:5:8AM-0500');
expect(date(midnight, "yyyy-MM-dd hh=HH:mm:ssaZ")).
toEqual('2010-09-03 12=00:05:08AM-0500');
expect(date(midnight, "yyyy-MM-dd hh=HH:mm:ss.sssaZ")).
toEqual('2010-09-03 12=00:05:08.123AM-0500');
expect(date(noon, "yyyy-MM-dd hh=HH:mm:ssaZ")).
toEqual('2010-09-03 12=12:05:08PM-0500');
expect(date(noon, "yyyy-MM-dd hh=HH:mm:ss.sssaZ")).
toEqual('2010-09-03 12=12:05:08.012PM-0500');
expect(date(noon, "EEE, MMM d, yyyy")).
toEqual('Fri, Sep 3, 2010');
expect(date(noon, "EEEE, MMMM dd, yyyy")).
toEqual('Friday, September 03, 2010');
expect(date(earlyDate, "MMMM dd, y")).
toEqual('September 03, 1');
});
it('should accept negative numbers as strings', function() {
//Note: this tests a timestamp set for 3 days before the unix epoch.
//The behavior of `date` depends on your timezone, which is why we check just
//the year and not the whole daye. See Issue #4218
expect(date('-259200000').split(' ')[2]).toEqual('1969');
});
it('should format timezones correctly (as per ISO_8601)', function() {
//Note: TzDate's first argument is offset, _not_ timezone.
var utc = new angular.mock.TzDate(0, '2010-09-03T12:05:08.000Z');
var eastOfUTC = new angular.mock.TzDate(-5, '2010-09-03T12:05:08.000Z');
var westOfUTC = new angular.mock.TzDate(+5, '2010-09-03T12:05:08.000Z');
var eastOfUTCPartial = new angular.mock.TzDate(-5.5, '2010-09-03T12:05:08.000Z');
var westOfUTCPartial = new angular.mock.TzDate(+5.5, '2010-09-03T12:05:08.000Z');
expect(date(utc, "yyyy-MM-ddTHH:mm:ssZ")).
toEqual('2010-09-03T12:05:08+0000');
expect(date(eastOfUTC, "yyyy-MM-ddTHH:mm:ssZ")).
toEqual('2010-09-03T17:05:08+0500');
expect(date(westOfUTC, "yyyy-MM-ddTHH:mm:ssZ")).
toEqual('2010-09-03T07:05:08-0500');
expect(date(eastOfUTCPartial, "yyyy-MM-ddTHH:mm:ssZ")).
toEqual('2010-09-03T17:35:08+0530');
expect(date(westOfUTCPartial, "yyyy-MM-ddTHH:mm:ssZ")).
toEqual('2010-09-03T06:35:08-0530');
});
it('should treat single quoted strings as string literals', function() {
expect(date(midnight, "yyyy'de' 'a'x'dd' 'adZ' h=H:m:saZ")).
toEqual('2010de axdd adZ 12=0:5:8AM-0500');
});
it('should treat a sequence of two single quotes as a literal single quote', function() {
expect(date(midnight, "yyyy'de' 'a''dd' 'adZ' h=H:m:saZ")).
toEqual("2010de a'dd adZ 12=0:5:8AM-0500");
});
it('should accept default formats', function() {
expect(date(noon, "medium")).
toEqual('Sep 3, 2010 12:05:08 PM');
expect(date(noon, "short")).
toEqual('9/3/10 12:05 PM');
expect(date(noon, "fullDate")).
toEqual('Friday, September 3, 2010');
expect(date(noon, "longDate")).
toEqual('September 3, 2010');
expect(date(noon, "mediumDate")).
toEqual('Sep 3, 2010');
expect(date(noon, "shortDate")).
toEqual('9/3/10');
expect(date(noon, "mediumTime")).
toEqual('12:05:08 PM');
expect(date(noon, "shortTime")).
toEqual('12:05 PM');
});
it('should parse format ending with non-replaced string', function() {
expect(date(morning, 'yy/xxx')).toEqual('10/xxx');
});
it('should support various iso8061 date strings with timezone as input', function() {
var format = 'yyyy-MM-dd ss';
var localDay = new Date(Date.UTC(2003, 9, 10, 13, 2, 3, 0)).getDate();
//full ISO8061
expect(date('2003-09-10T13:02:03.000Z', format)).toEqual('2003-09-' + localDay + ' 03');
expect(date('2003-09-10T13:02:03.000+00:00', format)).toEqual('2003-09-' + localDay + ' 03');
expect(date('20030910T033203-0930', format)).toEqual('2003-09-' + localDay + ' 03');
//no millis
expect(date('2003-09-10T13:02:03Z', format)).toEqual('2003-09-' + localDay + ' 03');
//no seconds
expect(date('2003-09-10T13:02Z', format)).toEqual('2003-09-' + localDay + ' 00');
//no minutes
expect(date('2003-09-10T13Z', format)).toEqual('2003-09-' + localDay + ' 00');
});
it('should parse iso8061 date strings without timezone as local time', function() {
var format = 'yyyy-MM-dd HH-mm-ss';
//full ISO8061 without timezone
expect(date('2003-09-10T03:02:04.000', format)).toEqual('2003-09-10 03-02-04');
expect(date('20030910T030204', format)).toEqual('2003-09-10 03-02-04');
//no time
expect(date('2003-09-10', format)).toEqual('2003-09-10 00-00-00');
});
it('should support different degrees of subsecond precision', function() {
var format = 'yyyy-MM-dd ss';
var localDay = new Date(Date.UTC(2003, 9 - 1, 10, 13, 2, 3, 123)).getDate();
expect(date('2003-09-10T13:02:03.12345678Z', format)).toEqual('2003-09-' + localDay + ' 03');
expect(date('2003-09-10T13:02:03.1234567Z', format)).toEqual('2003-09-' + localDay + ' 03');
expect(date('2003-09-10T13:02:03.123456Z', format)).toEqual('2003-09-' + localDay + ' 03');
expect(date('2003-09-10T13:02:03.12345Z', format)).toEqual('2003-09-' + localDay + ' 03');
expect(date('2003-09-10T13:02:03.1234Z', format)).toEqual('2003-09-' + localDay + ' 03');
expect(date('2003-09-10T13:02:03.123Z', format)).toEqual('2003-09-' + localDay + ' 03');
expect(date('2003-09-10T13:02:03.12Z', format)).toEqual('2003-09-' + localDay + ' 03');
expect(date('2003-09-10T13:02:03.1Z', format)).toEqual('2003-09-' + localDay + ' 03');
});
it('should use UTC if the timezone is set to "UTC"', function() {
expect(date(new Date(2003, 8, 10, 3, 2, 4), 'yyyy-MM-dd HH-mm-ss')).toEqual('2003-09-10 03-02-04');
expect(date(new Date(Date.UTC(2003, 8, 10, 3, 2, 4)), 'yyyy-MM-dd HH-mm-ss', 'UTC')).toEqual('2003-09-10 03-02-04');
});
});
});
|
// More info on Webpack's Node API here: https://webpack.github.io/docs/node.js-api.html
// Allowing console calls below since this is a build file.
/* eslint-disable no-console */
import webpack from 'webpack';
let ncp = require('ncp').ncp;
import config from '../webpack.config.prod';
import {chalkError, chalkSuccess, chalkWarning, chalkProcessing} from './chalkConfig';
process.env.NODE_ENV = 'production'; // this assures React is built in prod mode and that the Babel dev config doesn't apply.
console.log(chalkProcessing('Generating minified bundle. This will take a moment...'));
webpack(config).run((error, stats) => {
if (error) { // so a fatal error occurred. Stop here.
console.log(chalkError(error));
return 1;
}
const jsonStats = stats.toJson();
if (jsonStats.hasErrors) {
return jsonStats.errors.map(error => console.log(chalkError(error)));
}
if (jsonStats.hasWarnings) {
console.log(chalkWarning('Webpack generated the following warnings: '));
jsonStats.warnings.map(warning => console.log(chalkWarning(warning)));
}
console.log(`Webpack stats: ${stats}`);
ncp('./docs', './tmp', (err) => {
if(err) {
return console.log(chalkError(err));
}
console.log(chalkSuccess('dev testing copy to tmp done'));
ncp('./tmp', './docs/scratch-list', err => {
if(err) {
return console.log(chalkError(err));
}
console.log(chalkSuccess('dev testing copy done'));
});
});
// if we got this far, the build succeeded.
console.log(chalkSuccess('Your app is compiled in production mode in /docs. It\'s ready to roll!'));
return 0;
});
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Destroy component is responsible for destroying a Game Object.
*
* @class
*/
Phaser.Component.Destroy = function () {};
Phaser.Component.Destroy.prototype = {
/**
* As a Game Object runs through its destroy method this flag is set to true,
* and can be checked in any sub-systems or plugins it is being destroyed from.
* @property {boolean} destroyPhase
* @readOnly
*/
destroyPhase: false,
/**
* Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present
* and nulls its reference to `game`, freeing it up for garbage collection.
*
* If this Game Object has the Events component it will also dispatch the `onDestroy` event.
*
* You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've
* more than one Game Object sharing the same BaseTexture.
*
* @method
* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well?
* @param {boolean} [destroyTexture=false] - Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it.
*/
destroy: function (destroyChildren, destroyTexture)
{
if (this.game === null || this.destroyPhase) { return; }
if (destroyChildren === undefined) { destroyChildren = true; }
if (destroyTexture === undefined) { destroyTexture = false; }
this.destroyPhase = true;
if (this.events)
{
this.events.onDestroy$dispatch(this);
}
if (this.parent)
{
if (this.parent instanceof Phaser.Group)
{
this.parent.remove(this);
}
else
{
this.parent.removeChild(this);
}
}
if (this.input)
{
this.input.destroy();
}
if (this.animations)
{
this.animations.destroy();
}
if (this.body)
{
this.body.destroy();
}
if (this.events)
{
this.events.destroy();
}
this.game.tweens.removeFrom(this);
var i = this.children.length;
if (destroyChildren)
{
while (i--)
{
this.children[i].destroy(destroyChildren);
}
}
else
{
while (i--)
{
this.removeChild(this.children[i]);
}
}
if (this._crop)
{
this._crop = null;
this.cropRect = null;
}
if (this._frame)
{
this._frame = null;
}
if (Phaser.Video && this.key instanceof Phaser.Video)
{
this.key.onChangeSource.remove(this.resizeFrame, this);
}
if (Phaser.BitmapText && this._glyphs)
{
this._glyphs = [];
}
this.alive = false;
this.exists = false;
this.visible = false;
this.filters = null;
this.mask = null;
this.game = null;
this.data = {};
// In case Pixi is still going to try and render it even though destroyed
this.renderable = false;
if (this.transformCallback)
{
this.transformCallback = null;
this.transformCallbackContext = null;
}
// Pixi level DisplayObject destroy
this.hitArea = null;
this.parent = null;
this.stage = null;
this.worldTransform = null;
this.filterArea = null;
this._bounds = null;
this._currentBounds = null;
this._mask = null;
this._destroyCachedSprite();
// Texture?
if (destroyTexture)
{
this.texture.destroy(true);
}
this.destroyPhase = false;
this.pendingDestroy = false;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.