code
stringlengths 2
1.05M
|
---|
'use strict';
var assign = require('object-assign')
var getSelected = require('./getSelected')
var hasOwn = function(obj, prop){
return Object.prototype.hasOwnProperty.call(obj, prop)
}
/**
* Here is how multi selection is implemented - trying to emulate behavior in OSX Finder
*
* When there is no selection, and an initial click for selection is done, keep that index (SELINDEX)
*
* Next, if we shift+click, we mark as selected the items from initial index to current click index.
*
* Now, if we ctrl+click elsewhere, keep the selection, but also add the selected file,
* and set SELINDEX to the new index. Now on any subsequent clicks, have the same behavior,
* selecting/deselecting items starting from SELINDEX to the new click index
*/
module.exports = {
findInitialSelectionIndex: function(){
var selected = getSelected(this.props, this.state)
var index = undefined
if (!Object.keys(selected).length){
return index
}
var i = 0
var data = this.props.data
var len = data.length
var id
var idProperty = this.props.idProperty
for (; i < len; i++){
id = data[i][idProperty]
if (selected[id]){
index = i
}
}
return index
},
notifySelection: function(selected, data){
if (typeof this.props.onSelectionChange == 'function'){
this.props.onSelectionChange(selected, data)
}
if (!hasOwn(this.props, 'selected')){
this.setState({
defaultSelected: selected
})
}
},
handleSingleSelection: function(data, event){
var props = this.props
var rowSelected = this.isRowSelected(data)
var newSelected = !rowSelected
if (rowSelected && event && !event.ctrlKey){
//if already selected and not ctrl, keep selected
newSelected = true
}
var selectedId = newSelected?
data[props.idProperty]:
null
this.notifySelection(selectedId, data)
},
handleMultiSelection: function(data, event, config){
var selIndex = config.selIndex
var prevShiftKeyIndex = config.prevShiftKeyIndex
var props = this.props
var map = selIndex == null?
{}:
assign({}, getSelected(props, this.state))
if (prevShiftKeyIndex != null && selIndex != null){
var min = Math.min(prevShiftKeyIndex, selIndex)
var max = Math.max(prevShiftKeyIndex, selIndex)
var removeArray = props.data.slice(min, max + 1) || []
removeArray.forEach(function(item){
if (item){
var id = item[props.idProperty]
delete map[id]
}
})
}
data.forEach(function(item){
if (item){
var id = item[props.idProperty]
map[id] = item
}
})
this.notifySelection(map, data)
},
handleMultiSelectionRowToggle: function(data, event){
var selected = getSelected(this.props, this.state)
var isSelected = this.isRowSelected(data)
var clone = assign({}, selected)
var id = data[this.props.idProperty]
if (isSelected){
delete clone[id]
} else {
clone[id] = data
}
this.notifySelection(clone, data)
return isSelected
},
handleSelection: function(rowProps, event){
var props = this.props
if (!hasOwn(props, 'selected') && !hasOwn(props, 'defaultSelected')){
return
}
var isSelected = this.isRowSelected(rowProps.data)
var multiSelect = this.isMultiSelect()
if (!multiSelect){
this.handleSingleSelection(rowProps.data, event)
return
}
if (this.selIndex === undefined){
this.selIndex = this.findInitialSelectionIndex()
}
var selIndex = this.selIndex
//multi selection
var index = rowProps.index
var prevShiftKeyIndex = this.shiftKeyIndex
var start
var end
var data
if (event.ctrlKey){
this.selIndex = index
this.shiftKeyIndex = null
var unselect = this.handleMultiSelectionRowToggle(props.data[index], event)
if (unselect){
this.selIndex++
this.shiftKeyIndex = prevShiftKeyIndex
}
return
}
if (!event.shiftKey){
//set selIndex, for future use
this.selIndex = index
this.shiftKeyIndex = null
//should not select many, so make selIndex null
selIndex = null
} else {
this.shiftKeyIndex = index
}
if (selIndex == null){
data = [props.data[index]]
} else {
start = Math.min(index, selIndex)
end = Math.max(index, selIndex) + 1
data = props.data.slice(start, end)
}
this.handleMultiSelection(data, event, {
selIndex: selIndex,
prevShiftKeyIndex: prevShiftKeyIndex
})
},
isRowSelected: function(data){
var selectedMap = this.getSelectedMap()
var id = data[this.props.idProperty]
return selectedMap[id]
},
isMultiSelect: function(){
var selected = getSelected(this.props, this.state)
return selected && typeof selected == 'object'
},
getSelectedMap: function(){
var selected = getSelected(this.props, this.state)
var multiSelect = selected && typeof selected == 'object'
var map
if (multiSelect){
map = selected
} else {
map = {}
map[selected] = true
}
return map
}
} |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("codesnippet","ug",{button:"كود پارچىسى قىستۇرۇش",codeContents:"Code content",emptySnippetError:"A code snippet cannot be empty.",language:"Language",title:"Code snippet",pathName:"code snippet"}); |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactDom = require('react-dom');
var _reactDom2 = _interopRequireDefault(_reactDom);
var _reactEventListener = require('react-event-listener');
var _reactEventListener2 = _interopRequireDefault(_reactEventListener);
var _RenderToLayer = require('../internal/RenderToLayer');
var _RenderToLayer2 = _interopRequireDefault(_RenderToLayer);
var _propTypes = require('../utils/propTypes');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _Paper = require('../Paper');
var _Paper2 = _interopRequireDefault(_Paper);
var _lodash = require('lodash.throttle');
var _lodash2 = _interopRequireDefault(_lodash);
var _PopoverAnimationDefault = require('./PopoverAnimationDefault');
var _PopoverAnimationDefault2 = _interopRequireDefault(_PopoverAnimationDefault);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Popover = function (_Component) {
_inherits(Popover, _Component);
function Popover(props, context) {
_classCallCheck(this, Popover);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Popover).call(this, props, context));
_this.renderLayer = function () {
var _this$props = _this.props;
var animated = _this$props.animated;
var // eslint-disable-line no-unused-vars
animation = _this$props.animation;
var children = _this$props.children;
var style = _this$props.style;
var other = _objectWithoutProperties(_this$props, ['animated', 'animation', 'children', 'style']);
var Animation = animation || _PopoverAnimationDefault2.default;
var styleRoot = style;
if (!Animation) {
Animation = _Paper2.default;
styleRoot = {
position: 'fixed'
};
if (!_this.state.open) {
return null;
}
}
return _react2.default.createElement(
Animation,
_extends({}, other, { style: styleRoot, open: _this.state.open && !_this.state.closing }),
children
);
};
_this.componentClickAway = function () {
_this.requestClose('clickAway');
};
_this.setPlacement = function (scrolling) {
if (!_this.state.open) {
return;
}
var anchorEl = _this.props.anchorEl || _this.anchorEl;
if (!_this.refs.layer.getLayer()) {
return;
}
var targetEl = _this.refs.layer.getLayer().children[0];
if (!targetEl) {
return;
}
var _this$props2 = _this.props;
var targetOrigin = _this$props2.targetOrigin;
var anchorOrigin = _this$props2.anchorOrigin;
var anchor = _this.getAnchorPosition(anchorEl);
var target = _this.getTargetPosition(targetEl);
var targetPosition = {
top: anchor[anchorOrigin.vertical] - target[targetOrigin.vertical],
left: anchor[anchorOrigin.horizontal] - target[targetOrigin.horizontal]
};
if (scrolling && _this.props.autoCloseWhenOffScreen) {
_this.autoCloseWhenOffScreen(anchor);
}
if (_this.props.canAutoPosition) {
target = _this.getTargetPosition(targetEl); // update as height may have changed
targetPosition = _this.applyAutoPositionIfNeeded(anchor, target, targetOrigin, anchorOrigin, targetPosition);
}
targetEl.style.top = Math.max(0, targetPosition.top) + 'px';
targetEl.style.left = Math.max(0, targetPosition.left) + 'px';
targetEl.style.maxHeight = window.innerHeight + 'px';
};
_this.handleResize = (0, _lodash2.default)(_this.setPlacement, 100);
_this.handleScroll = (0, _lodash2.default)(_this.setPlacement.bind(_this, true), 100);
_this.state = {
open: props.open,
closing: false
};
return _this;
}
_createClass(Popover, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var _this2 = this;
if (nextProps.open !== this.state.open) {
if (nextProps.open) {
this.anchorEl = nextProps.anchorEl || this.props.anchorEl;
this.setState({
open: true,
closing: false
});
} else {
if (nextProps.animated) {
this.setState({ closing: true });
this.timeout = setTimeout(function () {
_this2.setState({
open: false
});
}, 500);
} else {
this.setState({
open: false
});
}
}
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
this.setPlacement();
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
clearTimeout(this.timeout);
}
}, {
key: 'requestClose',
value: function requestClose(reason) {
if (this.props.onRequestClose) {
this.props.onRequestClose(reason);
}
}
}, {
key: '_resizeAutoPosition',
value: function _resizeAutoPosition() {
this.setPlacement();
}
}, {
key: 'getAnchorPosition',
value: function getAnchorPosition(el) {
if (!el) {
el = _reactDom2.default.findDOMNode(this);
}
var rect = el.getBoundingClientRect();
var a = {
top: rect.top,
left: rect.left,
width: el.offsetWidth,
height: el.offsetHeight
};
a.right = rect.right || a.left + a.width;
a.bottom = rect.bottom || a.top + a.height;
a.middle = a.left + (a.right - a.left) / 2;
a.center = a.top + (a.bottom - a.top) / 2;
return a;
}
}, {
key: 'getTargetPosition',
value: function getTargetPosition(targetEl) {
return {
top: 0,
center: targetEl.offsetHeight / 2,
bottom: targetEl.offsetHeight,
left: 0,
middle: targetEl.offsetWidth / 2,
right: targetEl.offsetWidth
};
}
}, {
key: 'autoCloseWhenOffScreen',
value: function autoCloseWhenOffScreen(anchorPosition) {
if (anchorPosition.top < 0 || anchorPosition.top > window.innerHeight || anchorPosition.left < 0 || anchorPosition.left > window.innerWith) {
this.requestClose('offScreen');
}
}
}, {
key: 'getOverlapMode',
value: function getOverlapMode(anchor, target, median) {
if ([anchor, target].indexOf(median) >= 0) return 'auto';
if (anchor === target) return 'inclusive';
return 'exclusive';
}
}, {
key: 'getPositions',
value: function getPositions(anchor, target) {
var a = _extends({}, anchor);
var t = _extends({}, target);
var positions = {
x: ['left', 'right'].filter(function (p) {
return p !== t.horizontal;
}),
y: ['top', 'bottom'].filter(function (p) {
return p !== t.vertical;
})
};
var overlap = {
x: this.getOverlapMode(a.horizontal, t.horizontal, 'middle'),
y: this.getOverlapMode(a.vertical, t.vertical, 'center')
};
positions.x.splice(overlap.x === 'auto' ? 0 : 1, 0, 'middle');
positions.y.splice(overlap.y === 'auto' ? 0 : 1, 0, 'center');
if (overlap.y !== 'auto') {
a.vertical = a.vertical === 'top' ? 'bottom' : 'top';
if (overlap.y === 'inclusive') {
t.vertical = t.vertical;
}
}
if (overlap.x !== 'auto') {
a.horizontal = a.horizontal === 'left' ? 'right' : 'left';
if (overlap.y === 'inclusive') {
t.horizontal = t.horizontal;
}
}
return {
positions: positions,
anchorPos: a
};
}
}, {
key: 'applyAutoPositionIfNeeded',
value: function applyAutoPositionIfNeeded(anchor, target, targetOrigin, anchorOrigin, targetPosition) {
var _getPositions = this.getPositions(anchorOrigin, targetOrigin);
var positions = _getPositions.positions;
var anchorPos = _getPositions.anchorPos;
if (targetPosition.top < 0 || targetPosition.top + target.bottom > window.innerHeight) {
var newTop = anchor[anchorPos.vertical] - target[positions.y[0]];
if (newTop + target.bottom <= window.innerHeight) targetPosition.top = Math.max(0, newTop);else {
newTop = anchor[anchorPos.vertical] - target[positions.y[1]];
if (newTop + target.bottom <= window.innerHeight) targetPosition.top = Math.max(0, newTop);
}
}
if (targetPosition.left < 0 || targetPosition.left + target.right > window.innerWidth) {
var newLeft = anchor[anchorPos.horizontal] - target[positions.x[0]];
if (newLeft + target.right <= window.innerWidth) targetPosition.left = Math.max(0, newLeft);else {
newLeft = anchor[anchorPos.horizontal] - target[positions.x[1]];
if (newLeft + target.right <= window.innerWidth) targetPosition.left = Math.max(0, newLeft);
}
}
return targetPosition;
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
{ style: { display: 'none' } },
_react2.default.createElement(_reactEventListener2.default, {
elementName: 'window',
onScroll: this.handleScroll,
onResize: this.handleResize
}),
_react2.default.createElement(_RenderToLayer2.default, {
ref: 'layer',
open: this.state.open,
componentClickAway: this.componentClickAway,
useLayerForClickAway: this.props.useLayerForClickAway,
render: this.renderLayer
})
);
}
}]);
return Popover;
}(_react.Component);
Popover.propTypes = {
/**
* This is the DOM element that will be used to set the position of the
* popover.
*/
anchorEl: _react.PropTypes.object,
/**
* This is the point on the anchor where the popover's
* `targetOrigin` will attach to.
* Options:
* vertical: [top, middle, bottom];
* horizontal: [left, center, right].
*/
anchorOrigin: _propTypes2.default.origin,
/**
* If true, the popover will apply transitions when
* it is added to the DOM.
*/
animated: _react.PropTypes.bool,
/**
* Override the default animation component used.
*/
animation: _react.PropTypes.func,
/**
* If true, the popover will hide when the anchor is scrolled off the screen.
*/
autoCloseWhenOffScreen: _react.PropTypes.bool,
/**
* If true, the popover (potentially) ignores `targetOrigin`
* and `anchorOrigin` to make itself fit on screen,
* which is useful for mobile devices.
*/
canAutoPosition: _react.PropTypes.bool,
/**
* The content of the popover.
*/
children: _react.PropTypes.node,
/**
* The CSS class name of the root element.
*/
className: _react.PropTypes.string,
/**
* Callback function fired when the popover is requested to be closed.
*
* @param {string} reason The reason for the close request. Possibles values
* are 'clickAway' and 'offScreen'.
*/
onRequestClose: _react.PropTypes.func,
/**
* If true, the popover is visible.
*/
open: _react.PropTypes.bool,
/**
* Override the inline-styles of the root element.
*/
style: _react.PropTypes.object,
/**
* This is the point on the popover which will attach to
* the anchor's origin.
* Options:
* vertical: [top, middle, bottom];
* horizontal: [left, center, right].
*/
targetOrigin: _propTypes2.default.origin,
/**
* If true, the popover will render on top of an invisible
* layer, which will prevent clicks to the underlying
* elements, and trigger an `onRequestClose('clickAway')` call.
*/
useLayerForClickAway: _react.PropTypes.bool,
/**
* The zDepth of the popover.
*/
zDepth: _propTypes2.default.zDepth
};
Popover.defaultProps = {
anchorOrigin: {
vertical: 'bottom',
horizontal: 'left'
},
animated: true,
autoCloseWhenOffScreen: true,
canAutoPosition: true,
onRequestClose: function onRequestClose() {},
open: false,
style: {
overflowY: 'auto'
},
targetOrigin: {
vertical: 'top',
horizontal: 'left'
},
useLayerForClickAway: true,
zDepth: 1
};
Popover.contextTypes = {
muiTheme: _react.PropTypes.object.isRequired
};
exports.default = Popover; |
import React from 'react';
import TextField from 'material-ui/lib/text-field';
import RaisedButton from 'material-ui/lib/raised-button';
import DropDownMenu from 'material-ui/lib/DropDownMenu';
import MenuItem from 'material-ui/lib/menus/menu-item';
import Paper from 'material-ui/lib/paper';
import CardTitle from 'material-ui/lib/card/card-title';
import Card from 'material-ui/lib/card/card';
import CardActions from 'material-ui/lib/card/card-actions';
import FlatButton from 'material-ui/lib/flat-button';
import CardText from 'material-ui/lib/card/card-text';
import Table from 'material-ui/lib/table/table';
import TableRow from 'material-ui/lib/table/table-row';
import TableRowColumn from 'material-ui/lib/table/table-row-column';
import TableBody from 'material-ui/lib/table/table-body';
import Colors from 'material-ui/lib/styles/colors';
import Countries from '../../register/countries.js';
import injectTapEventPlugin from 'react-tap-event-plugin';
import DatePicker from 'material-ui/lib/date-picker/date-picker';
import AboutActions from '../../../actions/profile/AboutActions';
import AboutStore from '../../../stores/AboutStore';
import ErrorStore from '../../../stores/ErrorStore';
import Snackbar from 'material-ui/lib/snackbar';
import IconButton from 'material-ui/lib/icon-button';
import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/lib/menus/icon-menu';
import Checkbox from 'material-ui/lib/checkbox';
const buttonStyle = {
marginTop: 25
}
const listStyle = {
marginBottom: 30
}
const styles = {
errorStyle: {
color: Colors.lightBlue500,
},
checkbox: {
},
};
const editStyle = {
float: 'right'
};
const ageStyle = {
width: 50
}
function validate(data) {
if(data.length >= 100) {
return {
"error": "*limit exceeded"
}
}
else if(data === "") {
return {
"error": "*cannot be empty"
}
}
else {
return true;
}
}
const error = {
color: Colors.red500,
fontSize: 15
};
const iconButtonElement = (
<IconButton
touch={true}
tooltip="more"
tooltipPosition="bottom-left">
<MoreVertIcon color={Colors.grey400} />
</IconButton>
);
const rightIconMenu = (
<IconMenu iconButtonElement={iconButtonElement}>
<MenuItem>Reply</MenuItem>
<MenuItem>Forward</MenuItem>
<MenuItem>Delete</MenuItem>
</IconMenu>
);
const textStyle = {
marginLeft: "15"
}
const LookingFor = React.createClass({
getInitialState: function() {
return {
editing: false,
location: true,
mustBeSingle: true,
shortTerm: true,
longTerm: true,
casualSex: true,
nearYouShow: "",
minAgeShow: 0,
maxAgeShow: 0,
relStatusShow: "",
shortTermShow: "",
longTermShow: "",
casualSexShow: ""
};
},
componentDidMount: function () {
AboutActions.fetchLookingFor();
AboutStore.addChangeListener(this._onChange);
ErrorStore.addChangeListener(this._onChange);
},
_onChange: function () {
if(AboutStore.getLookingFor().location == 0) {
this.setState({
nearYouShow: "Anywhere",
location: false
});
}
else {
this.setState({
nearYouShow: "Near me",
location: true
});
}
if(AboutStore.getLookingFor().status == 1) {
this.setState({
relStatusShow: "Must be Single",
mustBeSingle: true
});
}
else {
this.setState({
relStatusShow: "Doesn't care about relationship status",
mustBeSingle: false
});
}
if(AboutStore.getLookingFor().shortterm == 1) {
this.setState({
shortTermShow: "Looking for short term relationship",
shortTerm: true
});
}
else {
this.setState({
shortTermShow: "Not looking for short term relationship",
shortTerm: false
});
}
if(AboutStore.getLookingFor().longtterm == 1) {
this.setState({
longTermShow: "Looking for long term relationship",
longTerm: true
});
}
else {
this.setState({
longTermShow: "Not looking for long term relationship",
longTerm: false
});
}
if(AboutStore.getLookingFor().casualSex == 1) {
this.setState({
casualSexShow: "For casual sex",
casualSex: true
});
}
else {
this.setState({
casualSexShow: "No casual sex",
casualSex: false
});
}
this.setState({
summary: AboutStore.getSummary(),
life: AboutStore.getLife(),
goodat: AboutStore.getGoodAt(),
spendtime: AboutStore.getSpendTime(),
favs: AboutStore.getFavs(),
error: ErrorStore.getabouterr(),
minAgeShow: AboutStore.getLookingFor().minage,
maxAgeShow: AboutStore.getLookingFor().maxage
});
},
_toggle: function () {
this.setState({
editing: !this.state.editing
});
},
handleChangeGender: function(e, index, value){
this.setState({gender: value});
},
_handleLocationChange: function(e, value) {
this.setState({
location: value
});
},
_handleStatusChange: function(e, value) {
this.setState({
mustBeSingle: value
});
},
_handleShortChange: function(e, value) {
this.setState({
shortTerm: value
});
},
_handleLongChange: function(e, value) {
this.setState({
longTerm: value
});
},
_handleSxChange: function(e, value) {
this.setState({
casualSex: value
});
},
_handleCancel: function() {
this.setState({
editing: false
});
},
_handleSubmit: function() {
let minAge = this.refs.minAge.getValue();
let maxAge = this.refs.maxAge.getValue();
if(minAge == "") {
minAge = this.state.minAgeShow;
}
if(maxAge == "") {
maxAge = this.state.maxAgeShow;
}
if(minAge > maxAge) {
document.getElementById('serverstatus').innerHTML = "*invalid age selection";
return false;
}
let lookingFor = {
location: this.state.location,
minage: minAge,
maxage: maxAge,
relstatus: this.state.mustBeSingle,
shortterm: this.state.shortTerm,
longterm: this.state.longTerm,
casualsex: this.state.casualSex
};
AboutActions.updateLookingFor(lookingFor);
this.setState({
editing: false
});
},
render: function() {
return (
<div>
<Paper zDepth={2}>
<div>
<Card>
<CardTitle title="Looking for" />
{ this.state.editing ? '' : <button style={editStyle} onClick={this._toggle}> edit </button> }
<ul>
{ this.state.editing ?
<div>
<Table>
<TableBody displayRowCheckbox={false}>
<TableRow hoverable={false} hovered={false} selectable={false}>
<TableRowColumn>Location</TableRowColumn>
<TableRowColumn>
<Checkbox
checked={this.state.location}
onCheck={this._handleLocationChange}
label="Near you"
style={styles.checkbox}
/>
</TableRowColumn>
</TableRow>
<TableRow hoverable={false} hovered={false} selectable={false}>
<TableRowColumn>Age</TableRowColumn>
<TableRowColumn>
<TextField
hintText={this.state.minAgeShow} style={ageStyle} hintStyle={styles.errorStyle} fullwidth={true} ref="minAge" type="number" min="18" max="99" />
to
<TextField
hintText={this.state.maxAgeShow} style={ageStyle} hintStyle={styles.errorStyle} fullwidth={true} ref="maxAge" type="number" min="18" max="99" />
<br/><span style={error} id="email"> </span>
</TableRowColumn>
</TableRow>
<TableRow hoverable={false} hovered={false} selectable={false}>
<TableRowColumn>Relationship Status</TableRowColumn>
<TableRowColumn>
<Checkbox
checked={this.state.mustBeSingle}
onCheck={this._handleStatusChange}
label="Must be single"
style={styles.checkbox}
/>
<br/><span style={error} id="orientation"> </span>
</TableRowColumn>
</TableRow>
<TableRow hoverable={false} hovered={false} selectable={false}>
<TableRowColumn>For</TableRowColumn>
<TableRowColumn>
<Checkbox
checked={this.state.shortTerm}
onCheck={this._handleShortChange}
label="Short term relationship"
style={styles.checkbox}
/>
<Checkbox
checked={this.state.longTerm}
onCheck={this._handleLongChange}
label="Long term relationship"
style={styles.checkbox}
/>
<Checkbox
checked={this.state.casualSex}
onCheck={this._handleSxChange}
label="Casual sex"
style={styles.checkbox}
/>
<br/><span style={error} id="orientation"> </span>
</TableRowColumn>
</TableRow>
</TableBody>
<CardText>
</CardText>
</Table>
<div>
<CardActions>
<RaisedButton label="Save changes" style={buttonStyle} onTouchTap={this._handleSubmit} />
<RaisedButton label="Cancel" style={buttonStyle} onTouchTap={this._handleCancel} />
</CardActions>
<span style={error} id="serverstatus"> </span>
</div>
</div>
:
<div>
<li style={listStyle}>
{this.state.nearYouShow}
</li>
<li style={listStyle}>
{this.state.minAgeShow} - {this.state.maxAgeShow}
</li>
<li style={listStyle}>{this.state.relStatusShow}</li>
<li style={listStyle}>{this.state.shortTermShow}, {this.state.longTermShow}, {this.state.casualSexShow}</li>
</div>
}
</ul>
</Card>
</div>
</Paper>
<Snackbar
open={this.state.error}
message="Error occured, please try again later"
autoHideDuration={4000}
onRequestClose={this.handleRequestClose} />
</div>
);
}
});
export default LookingFor; |
/*
*
* Copyright 2013 Jesse MacFadyen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/* jshint node:true, bitwise:true, undef:true, trailing:true, quotmark:true,
indent:4, unused:vars, latedef:nofunc,
laxcomma:true, sub:true
*/
var common = require('./common'),
path = require('path'),
glob = require('glob'),
jsproj = require('../../util/windows/jsproj'),
events = require('../../events'),
xml_helpers = require('../../util/xml-helpers');
module.exports = {
platformName: 'windows8',
InvalidProjectPathError: 'does not appear to be a Windows Store JS project (no .jsproj file)',
www_dir: function(project_dir) {
return path.join(project_dir, 'www');
},
package_name: function(project_dir) {
var manifest = xml_helpers.parseElementtreeSync(path.join(project_dir, 'package.appxmanifest'));
return manifest.find('Properties/DisplayName').text;
},
parseProjectFile: function(project_dir) {
var project_files = glob.sync('*.jsproj', { cwd:project_dir });
if (project_files.length === 0) {
throw new Error(this.InvalidProjectPathError);
}
return new jsproj(path.join(project_dir, project_files[0]));
},
'source-file': {
install:function(source_el, plugin_dir, project_dir, plugin_id, project_file) {
var targetDir = source_el.attrib['target-dir'] || '';
var dest = path.join('www', 'plugins', plugin_id, targetDir, path.basename(source_el.attrib['src']));
common.copyNewFile(plugin_dir, source_el.attrib['src'], project_dir, dest);
// add reference to this file to jsproj.
project_file.addSourceFile(dest);
},
uninstall:function(source_el, project_dir, plugin_id, project_file) {
var dest = path.join('www', 'plugins', plugin_id,
source_el.attrib['target-dir'] ? source_el.attrib['target-dir'] : '',
path.basename(source_el.attrib['src']));
common.removeFile(project_dir, dest);
// remove reference to this file from csproj.
project_file.removeSourceFile(dest);
}
},
'header-file': {
install:function(source_el, plugin_dir, project_dir, plugin_id) {
events.emit('verbose', 'header-fileinstall is not supported for Windows 8');
},
uninstall:function(source_el, project_dir, plugin_id) {
events.emit('verbose', 'header-file.uninstall is not supported for Windows 8');
}
},
'resource-file':{
install:function(el, plugin_dir, project_dir, plugin_id, project_file) {
events.emit('verbose', 'resource-file is not supported for Windows 8');
},
uninstall:function(el, project_dir, plugin_id, project_file) {
}
},
'lib-file': {
install:function(el, plugin_dir, project_dir, plugin_id, project_file) {
var inc = el.attrib['Include'];
project_file.addSDKRef(inc);
},
uninstall:function(el, project_dir, plugin_id, project_file) {
events.emit('verbose', 'windows8 lib-file uninstall :: ' + plugin_id);
var inc = el.attrib['Include'];
project_file.removeSDKRef(inc);
}
},
'framework': {
install:function(el, plugin_dir, project_dir, plugin_id, project_file) {
events.emit('verbose', 'windows8 framework install :: ' + plugin_id);
var src = el.attrib['src'];
var dest = src; // if !isCustom, we will just add a reference to the file in place
// technically it is not possible to get here without isCustom == true -jm
// var isCustom = el.attrib.custom == 'true';
var type = el.attrib['type'];
if(type == 'projectReference') {
project_file.addProjectReference(path.join(plugin_dir,src));
}
else {
// if(isCustom) {}
dest = path.join('plugins', plugin_id, path.basename(src));
common.copyFile(plugin_dir, src, project_dir, dest);
project_file.addReference(dest,src);
}
},
uninstall:function(el, project_dir, plugin_id, project_file) {
events.emit('verbose', 'windows8 framework uninstall :: ' + plugin_id );
var src = el.attrib['src'];
// technically it is not possible to get here without isCustom == true -jm
// var isCustom = el.attrib.custom == 'true';
var type = el.attrib['type'];
// unfortunately we have to generate the plugin_dir path because it is not passed to uninstall
var plugin_dir = path.join(project_dir, 'cordova/plugins', plugin_id,src);
if(type == 'projectReference') {
project_file.removeProjectReference(plugin_dir);
}
else {
// if(isCustom) { }
var targetPath = path.join('plugins', plugin_id);
common.removeFile(project_dir, targetPath);
project_file.removeReference(src);
}
}
}
};
|
/**
* Developer: Stepan Burguchev
* Date: 6/14/2016
* Copyright: 2009-2016 Comindware®
* All Rights Reserved
* Published under the MIT license
*/
"use strict";
import core from 'coreApi';
import { initializeCore } from '../utils/helpers';
import 'jasmine-jquery';
describe('Editors', function () {
beforeEach(function () {
this.rootRegion = initializeCore();
});
describe('Common', function () {
it('has polyfills', function () {
let localPolyfills = Object.assign({}, {a:2});
let globalPolyfills = "asd".includes('a');
});
});
});
|
(function(window, document) {
'use strict';
var lazyRocketsConfig;
var docElem = document.documentElement;
var addEventListener = window.addEventListener;
var setTimeout = window.setTimeout;
var rAF = window.requestAnimationFrame || setTimeout;
var regPicture = /^picture$/i;
var loadEvents = ['load', 'error', 'lazyincluded', '_lazyloaded'];
var hasClass = function(ele, cls) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
return ele.className.match(reg) && reg;
};
var addClass = function(ele, cls) {
if (!hasClass(ele, cls)){
ele.className += ' '+cls;
}
};
var removeClass = function(ele, cls) {
var reg;
if ((reg = hasClass(ele,cls))) {
ele.className = ele.className.replace(reg, ' ');
}
};
var addRemoveLoadEvents = function(dom, fn, add){
var action = add ? 'addEventListener' : 'removeEventListener';
if(add){
addRemoveLoadEvents(dom, fn);
}
loadEvents.forEach(function(evt){
dom[action](evt, fn);
});
};
var triggerEvent = function(elem, name, detail, noBubbles, noCancelable){
var event = document.createEvent('CustomEvent');
event.initCustomEvent(name, !noBubbles, !noCancelable, detail);
event.details = event.detail;
elem.dispatchEvent(event);
return event;
};
var updatePolyfill = function (el, full){
var polyfill;
if(!window.HTMLPictureElement){
if( ( polyfill = (window.picturefill || window.respimage || lazyRocketsConfig.pf) ) ){
polyfill({reevaluate: true, reparse: true, elements: [el]});
} else if(full && full.src){
el.src = full.src;
}
}
};
var getCSS = function (elem, style){
return getComputedStyle(elem, null)[style];
};
var prepareThrottledCheckElements = function(fn){
var noPreparedElems = document.querySelectorAll('[data-lazy-src]:not(.lazyload),[data-lazy-original]:not(.lazyload)');
for (var i = 0; i < noPreparedElems.length; i++) {
addClass(noPreparedElems[i], lazyRocketsConfig.lazyClass);
}
}
var throttle = function(fn){
var running;
var lastTime = 0;
var Date = window.Date;
var run = function(){
running = false;
lastTime = Date.now();
fn();
};
var afterAF = function(){
setTimeout(run);
};
var getAF = function(){
rAF(afterAF);
};
return function(force){
if(running){
return;
}
var delay = lazyRocketsConfig.throttle - (Date.now() - lastTime);
running = true;
if(delay < 4){
delay = 4;
}
if(force === true){
getAF();
} else {
setTimeout(getAF, delay);
}
};
};
var loader = (function(){
var lazyloadElems, preloadElems, isCompleted, resetPreloadingTimer, loadMode;
var eLvW, elvH, eLtop, eLleft, eLright, eLbottom;
var defaultExpand, preloadExpand;
var regImg = /^img$/i;
var regIframe = /^iframe$/i;
var supportScroll = ('onscroll' in window) && !(/glebot/.test(navigator.userAgent));
var shrinkExpand = 0;
var currentExpand = 0;
var lowRuns = 0;
var isLoading = 0;
var resetPreloading = function(e){
isLoading--;
if(e && e.target){
addRemoveLoadEvents(e.target, resetPreloading);
}
if(!e || isLoading < 0 || !e.target){
isLoading = 0;
}
};
var isNestedVisible = function(elem, elemExpand){
var outerRect;
var parent = elem;
var visible = getCSS(elem, 'visibility') != 'hidden';
eLtop -= elemExpand;
eLbottom += elemExpand;
eLleft -= elemExpand;
eLright += elemExpand;
while(visible && (parent = parent.offsetParent)){
visible = ((getCSS(parent, 'opacity') || 1) > 0);
if(visible && getCSS(parent, 'overflow') != 'visible'){
outerRect = parent.getBoundingClientRect();
visible = eLright > outerRect.left &&
eLleft < outerRect.right &&
eLbottom > outerRect.top - 1 &&
eLtop < outerRect.bottom + 1
;
}
}
return visible;
};
var checkElements = function() {
var eLlen, i, rect, autoLoadElem, loadedSomething, elemExpand, elemNegativeExpand, elemExpandVal, beforeExpandVal;
if((loadMode = lazyRocketsConfig.loadMode) && isLoading < 8 && (eLlen = lazyloadElems.length)){
i = 0;
lowRuns++;
if(currentExpand < preloadExpand && isLoading < 1 && lowRuns > 4 && loadMode > 2){
currentExpand = preloadExpand;
lowRuns = 0;
} else if(currentExpand != defaultExpand && loadMode > 1 && lowRuns > 3){
currentExpand = defaultExpand;
} else {
currentExpand = shrinkExpand;
}
for(; i < eLlen; i++){
if(!lazyloadElems[i] || lazyloadElems[i]._lazyRace){continue;}
if(!supportScroll){unveilElement(lazyloadElems[i]);continue;}
if(!(elemExpandVal = lazyloadElems[i].getAttribute('data-expand')) || !(elemExpand = elemExpandVal * 1)){
elemExpand = currentExpand;
}
if(beforeExpandVal !== elemExpand){
eLvW = innerWidth + elemExpand;
elvH = innerHeight + elemExpand;
elemNegativeExpand = elemExpand * -1;
beforeExpandVal = elemExpand;
}
rect = lazyloadElems[i].getBoundingClientRect();
if ((eLbottom = rect.bottom) >= elemNegativeExpand &&
(eLtop = rect.top) <= elvH &&
(eLright = rect.right) >= elemNegativeExpand &&
(eLleft = rect.left) <= eLvW &&
(eLbottom || eLright || eLleft || eLtop) &&
((isCompleted && isLoading < 3 && lowRuns < 4 && !elemExpandVal && loadMode > 2) || isNestedVisible(lazyloadElems[i], elemExpand))){
unveilElement(lazyloadElems[i], false, rect.width);
loadedSomething = true;
} else if(!loadedSomething && isCompleted && !autoLoadElem &&
isLoading < 3 && lowRuns < 4 && loadMode > 2 &&
(preloadElems[0] || lazyRocketsConfig.preloadAfterLoad) &&
(preloadElems[0] || (!elemExpandVal && ((eLbottom || eLright || eLleft || eLtop) /*|| lazyloadElems[i].getAttribute(lazyRocketsConfig.sizesAttr) != 'auto'*/)))){
autoLoadElem = preloadElems[0] || lazyloadElems[i];
}
}
if(autoLoadElem && !loadedSomething){
unveilElement(autoLoadElem);
}
}
};
var throttledCheckElements = throttle(checkElements);
var switchLoadingClass = function(e){
addClass(e.target, lazyRocketsConfig.loadedClass);
removeClass(e.target, lazyRocketsConfig.loadingClass);
addRemoveLoadEvents(e.target, switchLoadingClass);
};
var changeIframeSrc = function(elem, src){
try {
elem.contentWindow.location.replace(src);
} catch(e){
elem.setAttribute('src', src);
}
};
var rafBatch = (function(){
var isRunning;
var batch = [];
var runBatch = function(){
while(batch.length){
(batch.shift())();
}
isRunning = false;
};
return function(fn){
batch.push(fn);
if(!isRunning){
isRunning = true;
rAF(runBatch);
}
};
})();
var unveilElement = function (elem, force, width){
var sources, i, len, sourceSrcset, src, srcset, parent, isPicture, event, firesLoad, customMedia;
var curSrc = elem.currentSrc || elem.src;
var isImg = regImg.test(elem.nodeName);
var sizes = null;
var isAuto = sizes == 'auto';
if( (isAuto || !isCompleted) && isImg && curSrc && !elem.complete && !hasClass(elem, lazyRocketsConfig.errorClass)){return;}
elem._lazyRace = true;
isLoading++;
rafBatch(function lazyUnveil(){
if(elem._lazyRace){
delete elem._lazyRace;
}
removeClass(elem, lazyRocketsConfig.lazyClass);
if(!(event = triggerEvent(elem, 'lazybeforeunveil', {force: !!force})).defaultPrevented){
/*if(sizes){
if(isAuto){*/
addClass(elem, lazyRocketsConfig.autosizesClass);
//} else {
//elem.setAttribute('sizes', sizes);
//}
//}
//srcset = elem.getAttribute(lazyRocketsConfig.srcsetAttr);
srcset = null;
src = elem.getAttribute('data-lazy-src') || elem.getAttribute('data-lazy-original');
if(isImg) {
parent = elem.parentNode;
isPicture = parent && regPicture.test(parent.nodeName || '');
}
firesLoad = event.detail.firesLoad || (('src' in elem) && (srcset || src || isPicture));
event = {target: elem};
if(firesLoad){
addRemoveLoadEvents(elem, resetPreloading, true);
clearTimeout(resetPreloadingTimer);
resetPreloadingTimer = setTimeout(resetPreloading, 2500);
addClass(elem, lazyRocketsConfig.loadingClass);
addRemoveLoadEvents(elem, switchLoadingClass, true);
}
/*if(isPicture){
sources = parent.getElementsByTagName('source');
for(i = 0, len = sources.length; i < len; i++){
if( (customMedia = lazyRocketsConfig.customMedia[sources[i].getAttribute('data-media') || sources[i].getAttribute('media')]) ){
sources[i].setAttribute('media', customMedia);
}
sourceSrcset = sources[i].getAttribute(lazyRocketsConfig.srcsetAttr);
if(sourceSrcset){
sources[i].setAttribute('srcset', sourceSrcset);
}
}
}*/
if(src){
if(regIframe.test(elem.nodeName)){
changeIframeSrc(elem, src);
} else {
elem.setAttribute('src', src);
}
}
if(isPicture){
updatePolyfill(elem, {src: src});
}
}
if( !firesLoad || (elem.complete && curSrc == (elem.currentSrc || elem.src)) ){
if(firesLoad){
resetPreloading(event);
} else {
isLoading--;
}
switchLoadingClass(event);
}
});
};
var onload = function(){
var scrollTimer;
var afterScroll = function(){
lazyRocketsConfig.loadMode = 3;
throttledCheckElements();
};
isCompleted = true;
lowRuns += 8;
lazyRocketsConfig.loadMode = 3;
addEventListener('scroll', function(){
if(lazyRocketsConfig.loadMode == 3){
lazyRocketsConfig.loadMode = 2;
}
clearTimeout(scrollTimer);
scrollTimer = setTimeout(afterScroll, 99);
}, true);
};
return {
_: function(){
lazyloadElems = document.getElementsByClassName(lazyRocketsConfig.lazyClass);
preloadElems = document.getElementsByClassName(lazyRocketsConfig.lazyClass + ' ' + lazyRocketsConfig.preloadClass);
/*lazyloadElems = document.querySelectorAll('[data-lazy-src],[data-lazy-original]');
preloadElems = document.querySelectorAll('[data-lazy-src].' + lazyRocketsConfig.preloadClass + ', [data-lazy-original].' + lazyRocketsConfig.preloadClass);*/
defaultExpand = lazyRocketsConfig.expand;
preloadExpand = Math.round(defaultExpand * lazyRocketsConfig.expFactor);
addEventListener('scroll', throttledCheckElements, true);
addEventListener('resize', throttledCheckElements, true);
if(window.MutationObserver){
new MutationObserver( prepareThrottledCheckElements ).observe( docElem, {childList: true, subtree: true, attributes: true} );
} else {
docElem.addEventListener('DOMNodeInserted', prepareThrottledCheckElements, true);
docElem.addEventListener('DOMAttrModified', prepareThrottledCheckElements, true);
setInterval(prepareThrottledCheckElements, 999);
}
addEventListener('hashchange', prepareThrottledCheckElements, true);
/*if(window.MutationObserver){
new MutationObserver( throttledCheckElements ).observe( docElem, {childList: true, subtree: true, attributes: true} );
} else {
docElem.addEventListener('DOMNodeInserted', throttledCheckElements, true);
docElem.addEventListener('DOMAttrModified', throttledCheckElements, true);
setInterval(throttledCheckElements, 999);
}
addEventListener('hashchange', throttledCheckElements, true);*/
['focus', 'mouseover', 'click', 'load', 'transitionend', 'animationend', 'webkitAnimationEnd'].forEach(function(name){
document.addEventListener(name, throttledCheckElements, true);
});
if(!(isCompleted = /d$|^c/.test(document.readyState))){
addEventListener('load', onload);
document.addEventListener('DOMContentLoaded', throttledCheckElements);
} else {
onload();
}
throttledCheckElements(lazyloadElems.length > 0);
},
checkElems: throttledCheckElements,
unveil: unveilElement
};
})();
var init = function(){
if(!init.i){
init.i = true;
loader._();
}
};
(function(){
var prop;
var lazyRocketsDefaults = {
lazyClass: 'lazyload',
loadedClass: 'lazyloaded',
loadingClass: 'lazyloading',
preloadClass: 'lazypreload',
errorClass: 'lazyerror',
autosizesClass: 'lazyautosizes',
//srcAttr: 'data-src',
//srcsetAttr: 'data-srcset',
//sizesAttr: 'data-sizes',
//minSize: 40,
//customMedia: {},
init: true,
expFactor: 2,
expand: 359,
loadMode: 2,
throttle: 99
};
lazyRocketsConfig = window.lazyRocketsConfig || window.lazyRocketsConfig || {};
for(prop in lazyRocketsDefaults){
if(!(prop in lazyRocketsConfig)){
lazyRocketsConfig[prop] = lazyRocketsDefaults[prop];
}
}
window.lazyRocketsConfig = lazyRocketsConfig;
setTimeout(function(){
if(lazyRocketsConfig.init){
var tmpElems = document.querySelectorAll('[data-lazy-src],[data-lazy-original]');
for (var i = 0; i < tmpElems.length; i++) {
addClass(tmpElems[i], lazyRocketsConfig.lazyClass);
};
init();
}
});
})();
return {
cfg: lazyRocketsConfig,
loader: loader,
init: init,
uP: updatePolyfill,
aC: addClass,
rC: removeClass,
hC: hasClass,
fire: triggerEvent
};
})(window, document);
|
/*
cssx/shim/scrollbar
(c) copyright 2010, unscriptable.com
author: john
LICENSE: see the LICENSE.txt file. If file is missing, this file is subject to the AFL 3.0
license at the following url: http://www.opensource.org/licenses/afl-3.0.php.
*/
define(
function () {
var scrollbarPropRx = /-cssx-scrollbar-(width|height)/g;
// TODO: combine these two functions into one
function getScrollbarSize () {
// summary: figures out the height and width of the scrollbars on this system.
// something like this exists in dojox, but we don't want to rely on dojox
// Returns an object with w and h properties (width and height, Number) in pixels
var sbSize = {w: 15, h: 15}; // default
var testEl = document.createElement('div');
testEl.style.cssText = 'width:100px;height:100px;overflow:scroll;bottom:100%;right:100%;position:absolute;visibility:hidden;';
document.body.appendChild(testEl);
try {
sbSize = {
w: testEl.offsetWidth - Math.max(testEl.clientWidth, testEl.scrollWidth),
h: testEl.offsetHeight - Math.max(testEl.clientHeight, testEl.scrollHeight)
};
document.body.removeChild(testEl);
}
catch (ex) {
// squelch
}
return sbSize;
}
function getSbSize () {
var sbSize = getScrollbarSize();
sbSize = { w: sbSize.w + 'px', h: sbSize.h + 'px' };
getSbSize = function () { return sbSize; };
return sbSize;
}
function replaceScrollbarDim (full, which) {
return which == 'width' ? getSbSize().w : getSbSize().h;
}
return {
onValue: function (prop, value, selectors) {
return value.replace(scrollbarPropRx, replaceScrollbarDim);
}
};
}
);
|
'use strict';
const common = require('../../common');
if (!common.hasCrypto)
common.skip('missing crypto');
const assert = require('assert');
const tmpdir = require('../../common/tmpdir');
const { spawnSync } = require('child_process');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const { pathToFileURL } = require('url');
tmpdir.refresh();
function hash(algo, body) {
const h = crypto.createHash(algo);
h.update(body);
return h.digest('base64');
}
const policyFilepath = path.join(tmpdir.path, 'policy');
const depFilepath = require.resolve(`./build/${common.buildType}/binding.node`);
const depURL = pathToFileURL(depFilepath);
const tmpdirURL = pathToFileURL(tmpdir.path);
if (!tmpdirURL.pathname.endsWith('/')) {
tmpdirURL.pathname += '/';
}
const depBody = fs.readFileSync(depURL);
function writePolicy(...resources) {
const manifest = { resources: {} };
for (const { url, integrity } of resources) {
manifest.resources[url] = { integrity };
}
fs.writeFileSync(policyFilepath, JSON.stringify(manifest, null, 2));
}
function test(shouldFail, resources) {
writePolicy(...resources);
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--experimental-policy',
policyFilepath,
depFilepath
]);
console.log(stdout.toString(), stderr.toString());
if (shouldFail) {
assert.notStrictEqual(status, 0);
} else {
assert.strictEqual(status, 0);
}
}
test(false, [{
url: depURL,
integrity: `sha256-${hash('sha256', depBody)}`
}]);
test(true, [{
url: depURL,
integrity: `sha256akjsalkjdlaskjdk-${hash('sha256', depBody)}`
}]);
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.
*/
var OAuth = require('oauth').OAuth,
pjson = require('../../../package.json'),
Evernote = require('../../../base.js').Evernote;
var Client = function(options) {
this.consumerKey = options.consumerKey;
this.consumerSecret = options.consumerSecret;
this.sandbox = typeof(options.sandbox) !== 'undefined' ? options.sandbox : true;
if (this.sandbox) {
var defaultServiceHost = 'sandbox.evernote.com';
} else {
var defaultServiceHost = 'www.evernote.com';
}
this.serviceHost = options.serviceHost || defaultServiceHost;
this.additionalHeaders = options.additionalHeaders || {};
this.token = options.token;
this.secret = options.secret;
};
Client.prototype.getRequestToken = function(callbackUrl, callback) {
var self = this;
var oauth = self.getOAuthClient(callbackUrl);
oauth.getOAuthRequestToken(function(err, oauthToken, oauthTokenSecret, results) {
callback(err, oauthToken, oauthTokenSecret, results)
});
};
Client.prototype.getAuthorizeUrl = function(oauthToken) {
var self = this;
return self.getEndpoint('OAuth.action') + '?oauth_token=' + oauthToken;
};
Client.prototype.getAccessToken = function(oauthToken, oauthTokenSecret, oauthVerifier, callback) {
var self = this;
var oauth = self.getOAuthClient('');
oauth.getOAuthAccessToken(oauthToken, oauthTokenSecret, oauthVerifier,
function(err, oauthAccessToken, oauthAccessTokenSecret, results) {
callback(err, oauthAccessToken, oauthAccessTokenSecret, results);
self.token = oauthAccessToken;
});
};
Client.prototype.getUserStore = function() {
var self = this;
return new Store(Evernote.UserStoreClient, function(callback) {
callback(null, self.token, self.getEndpoint("/edam/user"));
});
};
Client.prototype.getNoteStore = function(noteStoreUrl) {
var self = this;
if (typeof noteStoreUrl !== 'undefined') {
self.noteStoreUrl = noteStoreUrl;
}
return new Store(Evernote.NoteStoreClient, function(callback) {
if (self.noteStoreUrl) {
callback(null, self.token, self.noteStoreUrl);
} else {
self.getUserStore().getNoteStoreUrl(function(err, noteStoreUrl) {
self.noteStoreUrl = noteStoreUrl;
callback(err, self.token, self.noteStoreUrl);
});
}
});
};
Client.prototype.getSharedNoteStore = function(linkedNotebook) {
var self = this;
return new Store(Evernote.NoteStoreClient, function(callback) {
var thisStore = this;
if (thisStore.sharedToken) {
callback(null, thisStore.sharedToken, linkedNotebook.noteStoreUrl);
} else {
var noteStore = new Store(Evernote.NoteStoreClient, function(cb) {
cb(null, self.token, linkedNotebook.noteStoreUrl);
});
noteStore.authenticateToSharedNotebook(linkedNotebook.shareKey, function(err, sharedAuth) {
thisStore.sharedToken = sharedAuth.authenticationToken;
callback(err, thisStore.sharedToken, linkedNotebook.noteStoreUrl);
});
}
});
};
Client.prototype.getBusinessNoteStore = function() {
var self = this;
return new Store(Evernote.NoteStoreClient, function(callback) {
var thisStore = this;
if (thisStore.bizToken && thisStore.bizNoteStoreUri) {
callback(null, thisStore.bizToken, thisStore.bizNoteStoreUri);
} else {
self.getUserStore().authenticateToBusiness(function(err, bizAuth) {
thisStore.bizToken = bizAuth.authenticationToken;
thisStore.bizNoteStoreUri = bizAuth.noteStoreUrl;
thisStore.bizUser = bizAuth.user;
callback(err, thisStore.bizToken, thisStore.bizNoteStoreUri);
});
}
});
};
Client.prototype.getOAuthClient = function(callbackUrl) {
var self = this;
return new OAuth(
self.getEndpoint('oauth'),
self.getEndpoint('oauth'),
self.consumerKey,
self.consumerSecret,
"1.0",
callbackUrl,
"HMAC-SHA1");
};
Client.prototype.getEndpoint = function(path) {
var self = this;
var url = 'https://' + self.serviceHost;
if (path) {
url += '/' + path;
}
return url
};
var Store = function(clientClass, enInfoFunc) {
var self = this;
self.clientClass = clientClass;
self.enInfoFunc = enInfoFunc;
for (var key in self.clientClass.prototype) {
if (key.indexOf('_') != -1 || typeof(self.clientClass.prototype[key]) != 'function') continue;
self[key] = self.createWrapperFunction(key);
}
};
Store.prototype.createWrapperFunction = function(name) {
var self = this;
return function() {
var orgArgs = arguments;
self.getThriftClient(function(err, client, token) {
if (err) {
callback = orgArgs[orgArgs.length - 1];
if (callback && typeof(callback) === "function") {
callback(err);
} else {
throw "Evernote SDK for Node.js doesn't support synchronous calls";
}
return;
}
var orgFunc = client[name];
var orgArgNames = self.getParamNames(orgFunc);
if (orgArgNames != null && orgArgs.length + 1 == orgArgNames.length) {
try {
var newArgs = [];
for (var i in orgArgNames) {
if (orgArgNames[i] == 'authenticationToken') newArgs.push(token);
if (i < orgArgs.length) newArgs.push(orgArgs[i]);
}
orgFunc.apply(client, newArgs);
} catch (e) {
orgFunc.apply(client, orgArgs);
}
} else {
orgFunc.apply(client, orgArgs);
}
});
};
};
Store.prototype.getThriftClient = function(callback) {
var self = this;
self.enInfoFunc(function(err, token, url) {
var m = token.match(/:A=([^:]+):/);
if (m) {
self.userAgentId = m[1];
} else {
self.userAgentId = '';
}
var transport = new Evernote.Thrift.NodeBinaryHttpTransport(url);
transport.addHeaders(
{'User-Agent':
self.userAgentId + ' / ' + pjson.version + '; Node.js / ' + process.version});
var protocol = new Evernote.Thrift.BinaryProtocol(transport);
callback(err, new self.clientClass(protocol), token);
});
};
Store.prototype.getParamNames = function(func) {
var funStr = func.toString();
return funStr.slice(funStr.indexOf('(')+1, funStr.indexOf(')')).match(/([^\s,]+)/g);
};
exports.Client = Client;
|
(function () {
'use strict';
app.service('gymCoachService', function ($http) {
this.getUserObj = function (gymID) {
return $http({
method: 'GET',
url: '/api/users/gym/' + gymID
}).then(function (response) {
return response.data;
});
};
// service for updating eval status
this.submitEval = function (userInfo) {
return $http({
method: 'PUT',
url: '/api/users/updateEval',
data: userInfo
}).then(function (response) {
return response.data;
});
};
});
} ());
|
export { default as configureStore } from './configureStore';
|
/**
* Adds class 'doc-token' to inline code
*/
module.exports = function (md) {
const defaultRender = md.renderer.rules.code_inline
md.renderer.rules.code_inline = (tokens, idx, options, env, self) => {
const token = tokens[idx]
token.attrSet('class', 'doc-token')
return defaultRender(tokens, idx, options, env, self)
}
}
|
function createAdapter() {
return {
durations: [],
metrics: [],
convert: undefined,
onMetric: function( data ) {
if ( data.type === "time" ) {
this.durations.push( data );
} else {
this.metrics.push( data );
}
},
setConverter: function( convert ) {
this.convert = convert;
}
};
}
module.exports = createAdapter;
|
/*!
@fullcalendar/rrule v4.0.1
Docs & License: https://fullcalendar.io/
(c) 2019 Adam Shaw
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('rrule'), require('@fullcalendar/core')) :
typeof define === 'function' && define.amd ? define(['exports', 'rrule', '@fullcalendar/core'], factory) :
(global = global || self, factory(global.FullCalendarRrule = {}, global.rrule, global.FullCalendar));
}(this, function (exports, rrule, core) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var EVENT_DEF_PROPS = {
rrule: null,
duration: core.createDuration
};
var recurring = {
parse: function (rawEvent, allDayDefault, leftoverProps, dateEnv) {
if (rawEvent.rrule != null) {
var props = core.refineProps(rawEvent, EVENT_DEF_PROPS, {}, leftoverProps);
var parsed = parseRRule(props.rrule, allDayDefault, dateEnv);
if (parsed) {
return {
allDay: parsed.allDay,
duration: props.duration,
typeData: parsed.rrule
};
}
}
return null;
},
expand: function (rrule, eventDef, framingRange) {
return rrule.between(framingRange.start, framingRange.end);
}
};
var main = core.createPlugin({
recurringTypes: [recurring]
});
function parseRRule(input, allDayDefault, dateEnv) {
if (typeof input === 'string') {
return {
rrule: rrule.rrulestr(input),
allDay: false
};
}
else if (typeof input === 'object' && input) { // non-null object
var refined = __assign({}, input); // copy
var allDay = allDayDefault;
if (typeof refined.dtstart === 'string') {
var dtstartMeta = dateEnv.createMarkerMeta(refined.dtstart);
if (dtstartMeta) {
refined.dtstart = dtstartMeta.marker;
allDay = dtstartMeta.isTimeUnspecified;
}
else {
delete refined.dtstart;
}
}
if (typeof refined.until === 'string') {
refined.until = dateEnv.createMarker(refined.until);
}
if (refined.freq != null) {
refined.freq = convertConstant(refined.freq);
}
if (refined.wkst != null) {
refined.wkst = convertConstant(refined.wkst);
}
else {
refined.wkst = (dateEnv.weekDow - 1 + 7) % 7; // convert Sunday-first to Monday-first
}
if (refined.byweekday != null) {
refined.byweekday = convertConstants(refined.byweekday); // the plural version
}
if (allDay == null) { // if not specific event after allDayDefault
allDay = true;
}
return {
rrule: new rrule.RRule(refined),
allDay: allDay
};
}
return null;
}
function convertConstants(input) {
if (Array.isArray(input)) {
return input.map(convertConstant);
}
return convertConstant(input);
}
function convertConstant(input) {
if (typeof input === 'string') {
return rrule.RRule[input.toUpperCase()];
}
return input;
}
exports.default = main;
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
const {resolve} = require('path');
const {DefinePlugin} = require('webpack');
const {
GITHUB_URL,
getVersionString,
} = require('react-devtools-extensions/utils');
const {resolveFeatureFlags} = require('react-devtools-shared/buildUtils');
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
console.error('NODE_ENV not set');
process.exit(1);
}
const __DEV__ = NODE_ENV === 'development';
const DEVTOOLS_VERSION = getVersionString();
module.exports = {
mode: __DEV__ ? 'development' : 'production',
devtool: __DEV__ ? 'eval-cheap-source-map' : 'source-map',
entry: {
backend: './src/backend.js',
frontend: './src/frontend.js',
},
output: {
path: __dirname + '/dist',
filename: '[name].js',
library: '[name]',
libraryTarget: 'commonjs2',
},
externals: {
react: 'react',
// TODO: Once this package is published, remove the external
// 'react-debug-tools': 'react-debug-tools',
'react-devtools-feature-flags': resolveFeatureFlags('inline'),
'react-dom': 'react-dom',
'react-is': 'react-is',
scheduler: 'scheduler',
},
optimization: {
minimize: false,
},
plugins: [
new DefinePlugin({
__DEV__,
__EXPERIMENTAL__: true,
__EXTENSION__: false,
__PROFILE__: false,
__TEST__: NODE_ENV === 'test',
'process.env.DEVTOOLS_VERSION': `"${DEVTOOLS_VERSION}"`,
'process.env.GITHUB_URL': `"${GITHUB_URL}"`,
'process.env.NODE_ENV': `"${NODE_ENV}"`,
}),
],
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
options: {
configFile: resolve(
__dirname,
'..',
'react-devtools-shared',
'babel.config.js',
),
},
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: __DEV__,
modules: true,
localIdentName: '[local]___[hash:base64:5]',
},
},
],
},
],
},
};
|
tinyMCE.addI18n('ru.pdw',{
desc : 'Show/hide toolbars'
});
|
/**
* San
* Copyright 2016 Baidu Inc. All rights reserved.
*
* @file 主文件
* @author errorrik([email protected])
* otakustay([email protected])
* junmer([email protected])
*/
(function (root) {
// 人工调整打包代码顺序,通过注释手工写一些依赖
// // require('./util/guid');
// // require('./util/empty');
// // require('./util/extend');
// // require('./util/inherits');
// // require('./util/each');
// // require('./util/contains');
// // require('./util/bind');
// // require('./browser/on');
// // require('./browser/un');
// // require('./browser/svg-tags');
// // require('./browser/create-el');
// // require('./browser/remove-el');
// // require('./util/next-tick');
// // require('./browser/ie');
// // require('./browser/ie-old-than-9');
// // require('./browser/input-event-compatible');
// // require('./browser/auto-close-tags');
// // require('./util/data-types.js');
// // require('./util/create-data-types-checker.js');
// // require('./parser/walker');
// // require('./parser/create-a-node');
// // require('./parser/parse-template');
// // require('./runtime/change-expr-compare');
// // require('./runtime/data-change-type');
// // require('./runtime/data');
// // require('./runtime/escape-html');
// // require('./runtime/default-filters');
// // require('./runtime/eval-expr');
// // require('./view/life-cycle');
// // require('./view/node-type');
// // require('./view/get-prop-handler');
// // require('./view/is-data-change-by-element');
// // require('./view/event-declaration-listener');
// // require('./view/gen-element-children-html');
// // require('./view/create-node');
/**
* @file 生成唯一id
* @author errorrik([email protected])
*/
/**
* 唯一id的起始值
*
* @inner
* @type {number}
*/
var guidIndex = 1;
/**
* 唯一id的前缀
*
* @inner
* @type {string}
*/
var guidPrefix = (new Date()).getTime().toString(16).slice(8);
/**
* 获取唯一id
*
* @inner
* @return {string} 唯一id
*/
function guid() {
return '_' + guidPrefix + (guidIndex++);
}
// exports = module.exports = guid;
/**
* @file 空函数
* @author errorrik([email protected])
*/
/**
* 啥都不干
*/
function empty() {}
// exports = module.exports = empty;
/**
* @file 属性拷贝
* @author errorrik([email protected])
*/
/**
* 对象属性拷贝
*
* @param {Object} target 目标对象
* @param {Object} source 源对象
* @return {Object} 返回目标对象
*/
function extend(target, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
var value = source[key];
if (typeof value !== 'undefined') {
target[key] = value;
}
}
}
return target;
}
// exports = module.exports = extend;
/**
* @file 构建类之间的继承关系
* @author errorrik([email protected])
*/
// var extend = require('./extend');
/**
* 构建类之间的继承关系
*
* @param {Function} subClass 子类函数
* @param {Function} superClass 父类函数
*/
function inherits(subClass, superClass) {
/* jshint -W054 */
var subClassProto = subClass.prototype;
var F = new Function();
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
extend(subClass.prototype, subClassProto);
/* jshint +W054 */
}
// exports = module.exports = inherits;
/**
* @file 遍历数组
* @author errorrik([email protected])
*/
/**
* 遍历数组集合
*
* @param {Array} array 数组源
* @param {function(Any,number):boolean} iterator 遍历函数
*/
function each(array, iterator) {
if (array && array.length > 0) {
for (var i = 0, l = array.length; i < l; i++) {
if (iterator(array[i], i) === false) {
break;
}
}
}
}
// exports = module.exports = each;
/**
* @file 判断数组中是否包含某项
* @author errorrik([email protected])
*/
// var each = require('./each');
/**
* 判断数组中是否包含某项
*
* @param {Array} array 数组
* @param {*} value 包含的项
* @return {boolean}
*/
function contains(array, value) {
var result = false;
each(array, function (item) {
result = item === value;
return !result;
});
return result;
}
// exports = module.exports = contains;
/**
* @file bind函数
* @author errorrik([email protected])
*/
/**
* Function.prototype.bind 方法的兼容性封装
*
* @param {Function} func 要bind的函数
* @param {Object} thisArg this指向对象
* @param {...*} args 预设的初始参数
* @return {Function}
*/
function bind(func, thisArg) {
var nativeBind = Function.prototype.bind;
var slice = Array.prototype.slice;
// #[begin] allua
// if (nativeBind && func.bind === nativeBind) {
// #[end]
return nativeBind.apply(func, slice.call(arguments, 1));
// #[begin] allua
// }
//
// var args = slice.call(arguments, 2);
// return function () {
// return func.apply(thisArg, args.concat(slice.call(arguments)));
// };
// #[end]
}
// exports = module.exports = bind;
/**
* @file DOM 事件挂载
* @author errorrik([email protected])
*/
/**
* DOM 事件挂载
*
* @inner
* @param {HTMLElement} el DOM元素
* @param {string} eventName 事件名
* @param {Function} listener 监听函数
* @param {boolean} capture 是否是捕获阶段
*/
function on(el, eventName, listener, capture) {
// #[begin] allua
// if (el.addEventListener) {
// #[end]
el.addEventListener(eventName, listener, capture);
// #[begin] allua
// }
// else {
// el.attachEvent('on' + eventName, listener);
// }
// #[end]
}
// exports = module.exports = on;
/**
* @file DOM 事件卸载
* @author errorrik([email protected])
*/
/**
* DOM 事件卸载
*
* @inner
* @param {HTMLElement} el DOM元素
* @param {string} eventName 事件名
* @param {Function} listener 监听函数
* @param {boolean} capture 是否是捕获阶段
*/
function un(el, eventName, listener, capture) {
// #[begin] allua
// if (el.addEventListener) {
// #[end]
el.removeEventListener(eventName, listener, capture);
// #[begin] allua
// }
// else {
// el.detachEvent('on' + eventName, listener);
// }
// #[end]
}
// exports = module.exports = un;
/**
* @file 将字符串逗号切分返回对象
* @author errorrik([email protected])
*/
// var each = require('../util/each');
/**
* 将字符串逗号切分返回对象
*
* @param {string} source 源字符串
* @return {Object}
*/
function splitStr2Obj(source) {
var result = {};
each(
source.split(','),
function (key) {
result[key] = 1;
}
);
return result;
}
// exports = module.exports = splitStr2Obj;
/**
* @file SVG标签表
* @author errorrik([email protected])
*/
// var splitStr2Obj = require('../util/split-str-2-obj');
/**
* svgTags
*
* @see https://www.w3.org/TR/SVG/svgdtd.html 只取常用
* @type {Object}
*/
var svgTags = splitStr2Obj(''
// structure
+ 'svg,g,defs,desc,metadata,symbol,use,'
// image & shape
+ 'image,path,rect,circle,line,ellipse,polyline,polygon,'
// text
+ 'text,tspan,tref,textpath,'
// other
+ 'marker,pattern,clippath,mask,filter,cursor,view,animate,'
// font
+ 'font,font-face,glyph,missing-glyph');
// exports = module.exports = svgTags;
/**
* @file DOM创建
* @author errorrik([email protected])
*/
// var svgTags = require('./svg-tags');
/**
* 创建 DOM 元素
*
* @param {string} tagName tagName
* @return {HTMLElement}
*/
function createEl(tagName) {
if (svgTags[tagName]) {
return document.createElementNS('http://www.w3.org/2000/svg', tagName);
}
return document.createElement(tagName);
}
// exports = module.exports = createEl;
/**
* @file 移除DOM
* @author errorrik([email protected])
*/
/**
* 将 DOM 从页面中移除
*
* @param {HTMLElement} el DOM元素
*/
function removeEl(el) {
if (el && el.parentNode) {
el.parentNode.removeChild(el);
}
}
// exports = module.exports = removeEl;
/**
* @file 在下一个时间周期运行任务
* @author errorrik([email protected])
*/
// 该方法参照了vue2.5.0的实现,感谢vue团队
// SEE: https://github.com/vuejs/vue/blob/0948d999f2fddf9f90991956493f976273c5da1f/src/core/util/env.js#L68
// var bind = require('./bind');
/**
* 下一个周期要执行的任务列表
*
* @inner
* @type {Array}
*/
var nextTasks = [];
/**
* 执行下一个周期任务的函数
*
* @inner
* @type {Function}
*/
var nextHandler;
/**
* 浏览器是否支持原生Promise
* 对Promise做判断,是为了禁用一些不严谨的Promise的polyfill
*
* @inner
* @type {boolean}
*/
var isNativePromise = typeof Promise === 'function' && /native code/.test(Promise);
/**
* 在下一个时间周期运行任务
*
* @inner
* @param {Function} fn 要运行的任务函数
* @param {Object=} thisArg this指向对象
*/
function nextTick(fn, thisArg) {
if (thisArg) {
fn = bind(fn, thisArg);
}
nextTasks.push(fn);
if (nextHandler) {
return;
}
nextHandler = function () {
var tasks = nextTasks.slice(0);
nextTasks = [];
nextHandler = null;
for (var i = 0, l = tasks.length; i < l; i++) {
tasks[i]();
}
};
// 非标准方法,但是此方法非常吻合要求。
if (typeof setImmediate === 'function') {
setImmediate(nextHandler);
}
// 用MessageChannel去做setImmediate的polyfill
// 原理是将新的message事件加入到原有的dom events之后
else if (typeof MessageChannel === 'function') {
var channel = new MessageChannel();
var port = channel.port2;
channel.port1.onmessage = nextHandler;
port.postMessage(1);
}
// for native app
else if (isNativePromise) {
Promise.resolve().then(nextHandler);
}
else {
setTimeout(nextHandler, 0);
}
}
// exports = module.exports = nextTick;
/**
* @file ie版本号
* @author errorrik([email protected])
*/
/**
* 从userAgent中ie版本号的匹配信息
*
* @type {Array}
*/
var ieVersionMatch = typeof navigator !== 'undefined'
&& navigator.userAgent.match(/msie\s*([0-9]+)/i);
/**
* ie版本号,非ie时为0
*
* @type {number}
*/
var ie = ieVersionMatch ? ieVersionMatch[1] - 0 : 0;
// exports = module.exports = ie;
/**
* @file 是否 IE 并且小于 9
* @author errorrik([email protected])
*/
// var ie = require('./ie');
// HACK:
// 1. IE8下,设置innerHTML时如果以html comment开头,comment会被自动滤掉
// 为了保证stump存在,需要设置完html后,createComment并appendChild/insertBefore
// 2. IE8下,innerHTML还不支持custom element,所以需要用div替代,不用createElement
// 3. 虽然IE8已经优化了字符串+连接,碎片化连接性能不再退化
// 但是由于上面多个兼容场景都用 < 9 判断,所以字符串连接也沿用
// 所以结果是IE8下字符串连接用的是数组join的方式
// #[begin] allua
// /**
// * 是否 IE 并且小于 9
// */
// var ieOldThan9 = ie && ie < 9;
// #[end]
// exports = module.exports = ieOldThan9;
/**
* @file DOM 事件挂载
* @author dafrok([email protected])
*/
/**
* DOM 事件挂载
*
* @inner
* @param {HTMLElement} el DOM元素
* @param {string} eventName 事件名
*/
function trigger(el, eventName) {
var event = document.createEvent('HTMLEvents');
event.initEvent(eventName, true, true);
el.dispatchEvent(event);
}
// exports = module.exports = trigger;
/**
* @file 解决 IE9 在表单元素中删除字符时不触发事件的问题
* @author dafrok([email protected])
*/
// var ie = require('./ie');
// var on = require('./on');
// var trigger = require('./trigger');
// #[begin] allua
// if (ie === 9) {
// on(document, 'selectionchange', function () {
// var el = document.activeElement;
// if (el.tagName === 'TEXTAREA' || el.tagName === 'INPUT') {
// trigger(el, 'input');
// }
// });
// }
// #[end]
/**
* @file 自闭合标签表
* @author errorrik([email protected])
*/
// var splitStr2Obj = require('../util/split-str-2-obj');
/**
* 自闭合标签列表
*
* @type {Object}
*/
var autoCloseTags = splitStr2Obj('area,base,br,col,embed,hr,img,input,keygen,param,source,track,wbr');
// exports = module.exports = autoCloseTags;
/**
* @file data types
* @author leon <[email protected]>
*/
// var bind = require('./bind');
// var empty = require('./empty');
// var extend = require('./extend');
// #[begin] error
var ANONYMOUS_CLASS_NAME = '<<anonymous>>';
/**
* 获取精确的类型
*
* @NOTE 如果 obj 是一个 DOMElement,我们会返回 `element`;
*
* @param {*} obj 目标
* @return {string}
*/
function getDataType(obj) {
if (obj && obj.nodeType === 1) {
return 'element';
}
return Object.prototype.toString
.call(obj)
.slice(8, -1)
.toLowerCase();
}
// #[end]
/**
* 创建链式的数据类型校验器
*
* @param {Function} validate 真正的校验器
* @return {Function}
*/
function createChainableChecker(validate) {
var chainedChecker = function () {};
chainedChecker.isRequired = empty;
// 只在 error 功能启用时才有实际上的 dataTypes 检测
// #[begin] error
var checkType = function (isRequired, data, dataName, componentName, fullDataName) {
var dataValue = data[dataName];
var dataType = getDataType(dataValue);
componentName = componentName || ANONYMOUS_CLASS_NAME;
// 如果是 null 或 undefined,那么要提前返回啦
if (dataValue == null) {
// 是 required 就报错
if (isRequired) {
throw new Error('[SAN ERROR] '
+ 'The `' + dataName + '` '
+ 'is marked as required in `' + componentName + '`, '
+ 'but its value is ' + dataType
);
}
// 不是 required,那就是 ok 的
return;
}
validate(data, dataName, componentName, fullDataName);
};
chainedChecker = bind(checkType, null, false);
chainedChecker.isRequired = bind(checkType, null, true);
// #[end]
return chainedChecker;
}
// #[begin] error
/**
* 生成主要类型数据校验器
*
* @param {string} type 主类型
* @return {Function}
*/
function createPrimaryTypeChecker(type) {
return createChainableChecker(function (data, dataName, componentName, fullDataName) {
var dataValue = data[dataName];
var dataType = getDataType(dataValue);
if (dataType !== type) {
throw new Error('[SAN ERROR] '
+ 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
+ '(' + dataType + ' supplied to ' + componentName + ', '
+ 'expected ' + type + ')'
);
}
});
}
/**
* 生成 arrayOf 校验器
*
* @param {Function} arrayItemChecker 数组中每项数据的校验器
* @return {Function}
*/
function createArrayOfChecker(arrayItemChecker) {
return createChainableChecker(function (data, dataName, componentName, fullDataName) {
if (typeof arrayItemChecker !== 'function') {
throw new Error('[SAN ERROR] '
+ 'Data `' + dataName + '` of `' + componentName + '` has invalid '
+ 'DataType notation inside `arrayOf`, expected `function`'
);
}
var dataValue = data[dataName];
var dataType = getDataType(dataValue);
if (dataType !== 'array') {
throw new Error('[SAN ERROR] '
+ 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
+ '(' + dataType + ' supplied to ' + componentName + ', '
+ 'expected array)'
);
}
for (var i = 0, len = dataValue.length; i < len; i++) {
arrayItemChecker(dataValue, i, componentName, fullDataName + '[' + i + ']');
}
});
}
/**
* 生成 instanceOf 检测器
*
* @param {Function|Class} expectedClass 期待的类
* @return {Function}
*/
function createInstanceOfChecker(expectedClass) {
return createChainableChecker(function (data, dataName, componentName, fullDataName) {
var dataValue = data[dataName];
if (dataValue instanceof expectedClass) {
return;
}
var dataValueClassName = dataValue.constructor && dataValue.constructor.name
? dataValue.constructor.name
: ANONYMOUS_CLASS_NAME;
var expectedClassName = expectedClass.name || ANONYMOUS_CLASS_NAME;
throw new Error('[SAN ERROR] '
+ 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
+ '(' + dataValueClassName + ' supplied to ' + componentName + ', '
+ 'expected instance of ' + expectedClassName + ')'
);
});
}
/**
* 生成 shape 校验器
*
* @param {Object} shapeTypes shape 校验规则
* @return {Function}
*/
function createShapeChecker(shapeTypes) {
return createChainableChecker(function (data, dataName, componentName, fullDataName) {
if (getDataType(shapeTypes) !== 'object') {
throw new Error('[SAN ERROR] '
+ 'Data `' + fullDataName + '` of `' + componentName + '` has invalid '
+ 'DataType notation inside `shape`, expected `object`'
);
}
var dataValue = data[dataName];
var dataType = getDataType(dataValue);
if (dataType !== 'object') {
throw new Error('[SAN ERROR] '
+ 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
+ '(' + dataType + ' supplied to ' + componentName + ', '
+ 'expected object)'
);
}
for (var shapeKeyName in shapeTypes) {
if (shapeTypes.hasOwnProperty(shapeKeyName)) {
var checker = shapeTypes[shapeKeyName];
if (typeof checker === 'function') {
checker(dataValue, shapeKeyName, componentName, fullDataName + '.' + shapeKeyName);
}
}
}
});
}
/**
* 生成 oneOf 校验器
*
* @param {Array} expectedEnumValues 期待的枚举值
* @return {Function}
*/
function createOneOfChecker(expectedEnumValues) {
return createChainableChecker(function (data, dataName, componentName, fullDataName) {
if (getDataType(expectedEnumValues) !== 'array') {
throw new Error('[SAN ERROR] '
+ 'Data `' + fullDataName + '` of `' + componentName + '` has invalid '
+ 'DataType notation inside `oneOf`, array is expected.'
);
}
var dataValue = data[dataName];
for (var i = 0, len = expectedEnumValues.length; i < len; i++) {
if (dataValue === expectedEnumValues[i]) {
return;
}
}
throw new Error('[SAN ERROR] '
+ 'Invalid ' + componentName + ' data `' + fullDataName + '` of value'
+ '(`' + dataValue + '` supplied to ' + componentName + ', '
+ 'expected one of ' + expectedEnumValues.join(',') + ')'
);
});
}
/**
* 生成 oneOfType 校验器
*
* @param {Array<Function>} expectedEnumOfTypeValues 期待的枚举类型
* @return {Function}
*/
function createOneOfTypeChecker(expectedEnumOfTypeValues) {
return createChainableChecker(function (data, dataName, componentName, fullDataName) {
if (getDataType(expectedEnumOfTypeValues) !== 'array') {
throw new Error('[SAN ERROR] '
+ 'Data `' + dataName + '` of `' + componentName + '` has invalid '
+ 'DataType notation inside `oneOf`, array is expected.'
);
}
var dataValue = data[dataName];
for (var i = 0, len = expectedEnumOfTypeValues.length; i < len; i++) {
var checker = expectedEnumOfTypeValues[i];
if (typeof checker !== 'function') {
continue;
}
try {
checker(data, dataName, componentName, fullDataName);
// 如果 checker 完成校验没报错,那就返回了
return;
}
catch (e) {
// 如果有错误,那么应该把错误吞掉
}
}
// 所有的可接受 type 都失败了,才丢一个异常
throw new Error('[SAN ERROR] '
+ 'Invalid ' + componentName + ' data `' + dataName + '` of value'
+ '(`' + dataValue + '` supplied to ' + componentName + ')'
);
});
}
/**
* 生成 objectOf 校验器
*
* @param {Function} typeChecker 对象属性值校验器
* @return {Function}
*/
function createObjectOfChecker(typeChecker) {
return createChainableChecker(function (data, dataName, componentName, fullDataName) {
if (typeof typeChecker !== 'function') {
throw new Error('[SAN ERROR] '
+ 'Data `' + dataName + '` of `' + componentName + '` has invalid '
+ 'DataType notation inside `objectOf`, expected function'
);
}
var dataValue = data[dataName];
var dataType = getDataType(dataValue);
if (dataType !== 'object') {
throw new Error('[SAN ERROR] '
+ 'Invalid ' + componentName + ' data `' + dataName + '` of type'
+ '(' + dataType + ' supplied to ' + componentName + ', '
+ 'expected object)'
);
}
for (var dataKeyName in dataValue) {
if (dataValue.hasOwnProperty(dataKeyName)) {
typeChecker(
dataValue,
dataKeyName,
componentName,
fullDataName + '.' + dataKeyName
);
}
}
});
}
/**
* 生成 exact 校验器
*
* @param {Object} shapeTypes object 形态定义
* @return {Function}
*/
function createExactChecker(shapeTypes) {
return createChainableChecker(function (data, dataName, componentName, fullDataName, secret) {
if (getDataType(shapeTypes) !== 'object') {
throw new Error('[SAN ERROR] '
+ 'Data `' + dataName + '` of `' + componentName + '` has invalid '
+ 'DataType notation inside `exact`'
);
}
var dataValue = data[dataName];
var dataValueType = getDataType(dataValue);
if (dataValueType !== 'object') {
throw new Error('[SAN ERROR] '
+ 'Invalid data `' + fullDataName + '` of type `' + dataValueType + '`'
+ '(supplied to ' + componentName + ', expected `object`)'
);
}
var allKeys = {};
// 先合入 shapeTypes
extend(allKeys, shapeTypes);
// 再合入 dataValue
extend(allKeys, dataValue);
// 保证 allKeys 的类型正确
for (var key in allKeys) {
if (allKeys.hasOwnProperty(key)) {
var checker = shapeTypes[key];
// dataValue 中有一个多余的数据项
if (!checker) {
throw new Error('[SAN ERROR] '
+ 'Invalid data `' + fullDataName + '` key `' + key + '` '
+ 'supplied to `' + componentName + '`. '
+ '(`' + key + '` is not defined in `DataTypes.exact`)'
);
}
if (!(key in dataValue)) {
throw new Error('[SAN ERROR] '
+ 'Invalid data `' + fullDataName + '` key `' + key + '` '
+ 'supplied to `' + componentName + '`. '
+ '(`' + key + '` is marked `required` in `DataTypes.exact`)'
);
}
checker(
dataValue,
key,
componentName,
fullDataName + '.' + key,
secret
);
}
}
});
}
// #[end]
/* eslint-disable fecs-valid-var-jsdoc */
var DataTypes = {
array: createChainableChecker(empty),
object: createChainableChecker(empty),
func: createChainableChecker(empty),
string: createChainableChecker(empty),
number: createChainableChecker(empty),
bool: createChainableChecker(empty),
symbol: createChainableChecker(empty),
any: createChainableChecker,
arrayOf: createChainableChecker,
instanceOf: createChainableChecker,
shape: createChainableChecker,
oneOf: createChainableChecker,
oneOfType: createChainableChecker,
objectOf: createChainableChecker,
exact: createChainableChecker
};
// #[begin] error
DataTypes = {
any: createChainableChecker(empty),
// 类型检测
array: createPrimaryTypeChecker('array'),
object: createPrimaryTypeChecker('object'),
func: createPrimaryTypeChecker('function'),
string: createPrimaryTypeChecker('string'),
number: createPrimaryTypeChecker('number'),
bool: createPrimaryTypeChecker('boolean'),
symbol: createPrimaryTypeChecker('symbol'),
// 复合类型检测
arrayOf: createArrayOfChecker,
instanceOf: createInstanceOfChecker,
shape: createShapeChecker,
oneOf: createOneOfChecker,
oneOfType: createOneOfTypeChecker,
objectOf: createObjectOfChecker,
exact: createExactChecker
};
/* eslint-enable fecs-valid-var-jsdoc */
// #[end]
// module.exports = DataTypes;
/**
* @file 创建数据检测函数
* @author leon<[email protected]>
*/
// #[begin] error
/**
* 创建数据检测函数
*
* @param {Object} dataTypes 数据格式
* @param {string} componentName 组件名
* @return {Function}
*/
function createDataTypesChecker(dataTypes, componentName) {
/**
* 校验 data 是否满足 data types 的格式
*
* @param {*} data 数据
*/
return function (data) {
for (var dataTypeName in dataTypes) {
if (dataTypes.hasOwnProperty(dataTypeName)) {
var dataTypeChecker = dataTypes[dataTypeName];
if (typeof dataTypeChecker !== 'function') {
throw new Error('[SAN ERROR] '
+ componentName + ':' + dataTypeName + ' is invalid; '
+ 'it must be a function, usually from san.DataTypes'
);
}
dataTypeChecker(
data,
dataTypeName,
componentName,
dataTypeName
);
}
}
};
}
// #[end]
// module.exports = createDataTypesChecker;
/**
* @file 字符串源码读取类
* @author errorrik([email protected])
*/
/**
* 字符串源码读取类,用于模板字符串解析过程
*
* @class
* @param {string} source 要读取的字符串
*/
function Walker(source) {
this.source = source;
this.len = this.source.length;
this.index = 0;
}
/**
* 获取当前字符码
*
* @return {number}
*/
Walker.prototype.currentCode = function () {
return this.charCode(this.index);
};
/**
* 截取字符串片段
*
* @param {number} start 起始位置
* @param {number} end 结束位置
* @return {string}
*/
Walker.prototype.cut = function (start, end) {
return this.source.slice(start, end);
};
/**
* 向前读取字符
*
* @param {number} distance 读取字符数
*/
Walker.prototype.go = function (distance) {
this.index += distance;
};
/**
* 读取下一个字符,返回下一个字符的 code
*
* @return {number}
*/
Walker.prototype.nextCode = function () {
this.go(1);
return this.currentCode();
};
/**
* 获取相应位置字符的 code
*
* @param {number} index 字符位置
* @return {number}
*/
Walker.prototype.charCode = function (index) {
return this.source.charCodeAt(index);
};
/**
* 向前读取字符,直到遇到指定字符再停止
*
* @param {number=} charCode 指定字符的code
* @return {boolean} 当指定字符时,返回是否碰到指定的字符
*/
Walker.prototype.goUntil = function (charCode) {
var code;
while (this.index < this.len && (code = this.currentCode())) {
switch (code) {
case 32:
case 9:
this.index++;
break;
default:
if (code === charCode) {
this.index++;
return 1;
}
return;
}
}
};
/**
* 向前读取符合规则的字符片段,并返回规则匹配结果
*
* @param {RegExp} reg 字符片段的正则表达式
* @return {Array}
*/
Walker.prototype.match = function (reg) {
reg.lastIndex = this.index;
var match = reg.exec(this.source);
if (match) {
this.index = reg.lastIndex;
}
return match;
};
// exports = module.exports = Walker;
/**
* @file 模板解析生成的抽象节点
* @author errorrik([email protected])
*/
/**
* 创建模板解析生成的抽象节点
*
* @param {Object=} options 节点参数
* @param {string=} options.tagName 标签名
* @param {ANode=} options.parent 父节点
* @param {boolean=} options.textExpr 文本节点表达式对象
* @return {Object}
*/
function createANode(options) {
options = options || {};
if (!options.textExpr) {
options.directives = options.directives || {};
options.props = options.props || [];
options.events = options.events || [];
options.children = options.children || [];
}
return options;
}
// exports = module.exports = createANode;
/**
* @file 把 kebab case 字符串转换成 camel case
* @author errorrik([email protected])
*/
/**
* 把 kebab case 字符串转换成 camel case
*
* @param {string} source 源字符串
* @return {string}
*/
function kebab2camel(source) {
return source.replace(/-([a-z])/g, function (match, alpha) {
return alpha.toUpperCase();
});
}
// exports = module.exports = kebab2camel;
/**
* @file 表达式类型
* @author errorrik([email protected])
*/
/**
* 表达式类型
*
* @const
* @type {Object}
*/
var ExprType = {
STRING: 1,
NUMBER: 2,
BOOL: 3,
ACCESSOR: 4,
INTERP: 5,
CALL: 6,
TEXT: 7,
BINARY: 8,
UNARY: 9,
TERTIARY: 10
};
// exports = module.exports = ExprType;
/**
* @file 创建访问表达式对象
* @author errorrik([email protected])
*/
// var ExprType = require('./expr-type');
/**
* 创建访问表达式对象
*
* @param {Array} paths 访问路径
* @return {Object}
*/
function createAccessor(paths) {
return {
type: ExprType.ACCESSOR,
paths: paths
};
}
// exports = module.exports = createAccessor;
/**
* @file 读取字符串
* @author errorrik([email protected])
*/
// var ExprType = require('./expr-type');
/**
* 读取字符串
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readString(walker) {
var startCode = walker.currentCode();
var startIndex = walker.index;
var charCode;
walkLoop: while ((charCode = walker.nextCode())) {
switch (charCode) {
case 92: // \
walker.go(1);
break;
case startCode:
walker.go(1);
break walkLoop;
}
}
var literal = walker.cut(startIndex, walker.index);
return {
type: ExprType.STRING,
value: (new Function('return ' + literal))()
};
}
// exports = module.exports = readString;
/**
* @file 读取数字
* @author errorrik([email protected])
*/
// var ExprType = require('./expr-type');
/**
* 读取数字
*
* @inner
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readNumber(walker) {
var match = walker.match(/\s*(-?[0-9]+(.[0-9]+)?)/g);
return {
type: ExprType.NUMBER,
value: match[1] - 0
};
}
// exports = module.exports = readNumber;
/**
* @file 读取ident
* @author errorrik([email protected])
*/
/**
* 读取ident
*
* @inner
* @param {Walker} walker 源码读取对象
* @return {string}
*/
function readIdent(walker) {
var match = walker.match(/\s*([\$0-9a-z_]+)/ig);
return match[1];
}
// exports = module.exports = readIdent;
/**
* @file 读取三元表达式
* @author errorrik([email protected])
*/
// var ExprType = require('./expr-type');
// var readLogicalORExpr = require('./read-logical-or-expr');
/**
* 读取三元表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readTertiaryExpr(walker) {
var conditional = readLogicalORExpr(walker);
walker.goUntil();
if (walker.currentCode() === 63) { // ?
walker.go(1);
var yesExpr = readTertiaryExpr(walker);
walker.goUntil();
if (walker.currentCode() === 58) { // :
walker.go(1);
return {
type: ExprType.TERTIARY,
segs: [
conditional,
yesExpr,
readTertiaryExpr(walker)
]
};
}
}
return conditional;
}
// exports = module.exports = readTertiaryExpr;
/**
* @file 读取访问表达式
* @author errorrik([email protected])
*/
// var ExprType = require('./expr-type');
// var createAccessor = require('./create-accessor');
// var readIdent = require('./read-ident');
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 读取访问表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readAccessor(walker) {
var firstSeg = readIdent(walker);
switch (firstSeg) {
case 'true':
case 'false':
return {
type: ExprType.BOOL,
value: firstSeg === 'true'
};
}
var result = createAccessor([
{
type: ExprType.STRING,
value: firstSeg
}
]);
/* eslint-disable no-constant-condition */
accessorLoop: while (1) {
/* eslint-enable no-constant-condition */
switch (walker.currentCode()) {
case 46: // .
walker.go(1);
// ident as string
result.paths.push({
type: ExprType.STRING,
value: readIdent(walker)
});
break;
case 91: // [
walker.go(1);
result.paths.push(readTertiaryExpr(walker));
walker.goUntil(93); // ]
break;
default:
break accessorLoop;
}
}
return result;
}
// exports = module.exports = readAccessor;
/**
* @file 读取括号表达式
* @author errorrik([email protected])
*/
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 读取括号表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readParenthesizedExpr(walker) {
walker.go(1);
var expr = readTertiaryExpr(walker);
walker.goUntil(41); // )
return expr;
}
// exports = module.exports = readParenthesizedExpr;
/**
* @file 读取一元表达式
* @author errorrik([email protected])
*/
// var ExprType = require('./expr-type');
// var readString = require('./read-string');
// var readNumber = require('./read-number');
// var readAccessor = require('./read-accessor');
// var readParenthesizedExpr = require('./read-parenthesized-expr');
/**
* 读取一元表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readUnaryExpr(walker) {
walker.goUntil();
switch (walker.currentCode()) {
case 33: // !
walker.go(1);
return {
type: ExprType.UNARY,
expr: readUnaryExpr(walker)
};
case 34: // "
case 39: // '
return readString(walker);
case 45: // number
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
return readNumber(walker);
case 40: // (
return readParenthesizedExpr(walker);
}
return readAccessor(walker);
}
// exports = module.exports = readUnaryExpr;
/**
* @file 读取乘法表达式
* @author errorrik([email protected])
*/
// var ExprType = require('./expr-type');
// var readUnaryExpr = require('./read-unary-expr');
/**
* 读取乘法表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readMultiplicativeExpr(walker) {
var expr = readUnaryExpr(walker);
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 37: // %
case 42: // *
case 47: // /
walker.go(1);
return {
type: ExprType.BINARY,
operator: code,
segs: [expr, readMultiplicativeExpr(walker)]
};
}
return expr;
}
// exports = module.exports = readMultiplicativeExpr;
/**
* @file 读取加法表达式
* @author errorrik([email protected])
*/
// var ExprType = require('./expr-type');
// var readMultiplicativeExpr = require('./read-multiplicative-expr');
/**
* 读取加法表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readAdditiveExpr(walker) {
var expr = readMultiplicativeExpr(walker);
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 43: // +
case 45: // -
walker.go(1);
return {
type: ExprType.BINARY,
operator: code,
segs: [expr, readAdditiveExpr(walker)]
};
}
return expr;
}
// exports = module.exports = readAdditiveExpr;
/**
* @file 读取关系判断表达式
* @author errorrik([email protected])
*/
// var ExprType = require('./expr-type');
// var readAdditiveExpr = require('./read-additive-expr');
/**
* 读取关系判断表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readRelationalExpr(walker) {
var expr = readAdditiveExpr(walker);
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 60: // <
case 62: // >
if (walker.nextCode() === 61) {
code += 61;
walker.go(1);
}
return {
type: ExprType.BINARY,
operator: code,
segs: [expr, readRelationalExpr(walker)]
};
}
return expr;
}
// exports = module.exports = readRelationalExpr;
/**
* @file 读取相等比对表达式
* @author errorrik([email protected])
*/
// var ExprType = require('./expr-type');
// var readRelationalExpr = require('./read-relational-expr');
/**
* 读取相等比对表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readEqualityExpr(walker) {
var expr = readRelationalExpr(walker);
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 61: // =
case 33: // !
if (walker.nextCode() === 61) {
code += 61;
if (walker.nextCode() === 61) {
code += 61;
walker.go(1);
}
return {
type: ExprType.BINARY,
operator: code,
segs: [expr, readEqualityExpr(walker)]
};
}
walker.go(-1);
}
return expr;
}
// exports = module.exports = readEqualityExpr;
/**
* @file 读取逻辑与表达式
* @author errorrik([email protected])
*/
// var ExprType = require('./expr-type');
// var readEqualityExpr = require('./read-equality-expr');
/**
* 读取逻辑与表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readLogicalANDExpr(walker) {
var expr = readEqualityExpr(walker);
walker.goUntil();
if (walker.currentCode() === 38) { // &
if (walker.nextCode() === 38) {
walker.go(1);
return {
type: ExprType.BINARY,
operator: 76,
segs: [expr, readLogicalANDExpr(walker)]
};
}
walker.go(-1);
}
return expr;
}
// exports = module.exports = readLogicalANDExpr;
/**
* @file 读取逻辑或表达式
* @author errorrik([email protected])
*/
// var ExprType = require('./expr-type');
// var readLogicalANDExpr = require('./read-logical-and-expr');
/**
* 读取逻辑或表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readLogicalORExpr(walker) {
var expr = readLogicalANDExpr(walker);
walker.goUntil();
if (walker.currentCode() === 124) { // |
if (walker.nextCode() === 124) {
walker.go(1);
return {
type: ExprType.BINARY,
operator: 248,
segs: [expr, readLogicalORExpr(walker)]
};
}
walker.go(-1);
}
return expr;
}
// exports = module.exports = readLogicalORExpr;
/**
* @file 解析表达式
* @author errorrik([email protected])
*/
// var Walker = require('./walker');
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 解析表达式
*
* @param {string} source 源码
* @return {Object}
*/
function parseExpr(source) {
if (typeof source === 'object' && source.type) {
return source;
}
var expr = readTertiaryExpr(new Walker(source));
expr.raw = source;
return expr;
}
// exports = module.exports = parseExpr;
/**
* @file 读取调用
* @author errorrik([email protected])
*/
// var ExprType = require('./expr-type');
// var readAccessor = require('./read-accessor');
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 读取调用
*
* @param {Walker} walker 源码读取对象
* @param {Array=} defaultArgs 默认参数
* @return {Object}
*/
function readCall(walker, defaultArgs) {
walker.goUntil();
var ident = readAccessor(walker);
var args = [];
if (walker.goUntil(40)) { // (
while (!walker.goUntil(41)) { // )
args.push(readTertiaryExpr(walker));
walker.goUntil(44); // ,
}
}
else if (defaultArgs) {
args = defaultArgs;
}
return {
type: ExprType.CALL,
name: ident,
args: args
};
}
// exports = module.exports = readCall;
/**
* @file 解析调用
* @author errorrik([email protected])
*/
// var Walker = require('./walker');
// var readCall = require('./read-call');
/**
* 解析调用
*
* @param {string} source 源码
* @param {Array=} defaultArgs 默认参数
* @return {Object}
*/
function parseCall(source, defaultArgs) {
var expr = readCall(new Walker(source), defaultArgs);
expr.raw = source;
return expr;
}
// exports = module.exports = parseCall;
/**
* @file 解析插值替换
* @author errorrik([email protected])
*/
// var Walker = require('./walker');
// var readTertiaryExpr = require('./read-tertiary-expr');
// var ExprType = require('./expr-type');
// var readCall = require('./read-call');
/**
* 解析插值替换
*
* @param {string} source 源码
* @return {Object}
*/
function parseInterp(source) {
var walker = new Walker(source);
var interp = {
type: ExprType.INTERP,
expr: readTertiaryExpr(walker),
filters: [],
raw: source
};
while (walker.goUntil(124)) { // |
var callExpr = readCall(walker);
switch (callExpr.name.paths[0].value) {
case 'html':
break;
case 'raw':
interp.original = 1;
break;
default:
interp.filters.push(callExpr);
}
}
return interp;
}
// exports = module.exports = parseInterp;
/**
* @file 解析文本
* @author errorrik([email protected])
*/
// var Walker = require('./walker');
// var ExprType = require('./expr-type');
// var parseInterp = require('./parse-interp');
/**
* 对字符串进行可用于new RegExp的字面化
*
* @inner
* @param {string} source 需要字面化的字符串
* @return {string} 字符串字面化结果
*/
function regexpLiteral(source) {
return source.replace(/[\^\[\]\$\(\)\{\}\?\*\.\+\\]/g, function (c) {
return '\\' + c;
});
}
/**
* 解析文本
*
* @param {string} source 源码
* @param {Array?} delimiters 分隔符。默认为 ['{{', '}}']
* @return {Object}
*/
function parseText(source, delimiters) {
delimiters = delimiters || ['{{', '}}'];
var exprStartReg = new RegExp(
regexpLiteral(delimiters[0]) + '\\s*([\\s\\S]+?)\\s*' + regexpLiteral(delimiters[1]),
'ig'
);
var exprMatch;
var walker = new Walker(source);
var beforeIndex = 0;
var expr = {
type: ExprType.TEXT,
segs: []
};
function pushStringToSeg(text) {
text && expr.segs.push({
type: ExprType.STRING,
value: text
});
}
while ((exprMatch = walker.match(exprStartReg)) != null) {
pushStringToSeg(walker.cut(
beforeIndex,
walker.index - exprMatch[0].length
));
var interp = parseInterp(exprMatch[1]);
expr.original = expr.original || interp.original;
expr.segs.push(interp);
beforeIndex = walker.index;
}
pushStringToSeg(walker.cut(beforeIndex));
if (expr.segs.length === 1 && expr.segs[0].type === ExprType.STRING) {
expr.value = expr.segs[0].value;
}
return expr;
}
// exports = module.exports = parseText;
/**
* @file 解析指令
* @author errorrik([email protected])
*/
// var Walker = require('./walker');
// var parseExpr = require('./parse-expr');
// var parseCall = require('./parse-call');
// var parseText = require('./parse-text');
// var readAccessor = require('./read-accessor');
/**
* 指令解析器
*
* @inner
* @type {Object}
*/
var directiveParsers = {
'for': function (value) {
var walker = new Walker(value);
var match = walker.match(/^\s*([\$0-9a-z_]+)(\s*,\s*([\$0-9a-z_]+))?\s+in\s+/ig);
if (match) {
return {
item: parseExpr(match[1]),
index: parseExpr(match[3] || '$index'),
value: readAccessor(walker)
};
}
// #[begin] error
throw new Error('[SAN FATAL] for syntax error: ' + value);
// #[end]
},
'ref': function (value, options) {
return {
value: parseText(value, options.delimiters)
};
},
'if': function (value) {
return {
value: parseExpr(value.replace(/(^\{\{|\}\}$)/g, ''))
};
},
'elif': function (value) {
return {
value: parseExpr(value.replace(/(^\{\{|\}\}$)/g, ''))
};
},
'else': function (value) {
return {
value: {}
};
},
'html': function (value) {
return {
value: parseExpr(value.replace(/(^\{\{|\}\}$)/g, ''))
};
},
'transition': function (value) {
return {
value: parseCall(value)
};
}
};
/**
* 解析指令
*
* @param {ANode} aNode 抽象节点
* @param {string} name 指令名称
* @param {string} value 指令值
* @param {Object} options 解析参数
* @param {Array?} options.delimiters 插值分隔符列表
*/
function parseDirective(aNode, name, value, options) {
var parser = directiveParsers[name];
if (parser) {
(aNode.directives[name] = parser(value, options)).raw = value;
}
}
// exports = module.exports = parseDirective;
/**
* @file 对属性信息进行处理
* @author errorrik([email protected])
*/
// var ExprType = require('../parser/expr-type');
/**
* 对属性信息进行处理
* 对组件的 binds 或者特殊的属性(比如 input 的 checked)需要处理
*
* 扁平化:
* 当 text 解析只有一项时,要么就是 string,要么就是 interp
* interp 有可能是绑定到组件属性的表达式,不希望被 eval text 成 string
* 所以这里做个处理,只有一项时直接抽出来
*
* bool属性:
* 当绑定项没有值时,默认为true
*
* @param {Object} prop 属性对象
*/
function postProp(prop) {
var expr = prop.expr;
if (expr.type === ExprType.TEXT) {
switch (expr.segs.length) {
case 0:
prop.expr = {
type: ExprType.BOOL,
value: true
};
break;
case 1:
expr = prop.expr = expr.segs[0];
if (expr.type === ExprType.INTERP && expr.filters.length === 0) {
prop.expr = expr.expr;
}
}
}
}
// exports = module.exports = postProp;
/**
* @file 解析抽象节点属性
* @author errorrik([email protected])
*/
// var each = require('../util/each');
// var kebab2camel = require('../util/kebab2camel');
// var ExprType = require('./expr-type');
// var createAccessor = require('./create-accessor');
// var parseExpr = require('./parse-expr');
// var parseCall = require('./parse-call');
// var parseText = require('./parse-text');
// var parseDirective = require('./parse-directive');
// var postProp = require('./post-prop');
var DEFAULT_EVENT_ARGS = [
createAccessor([
{type: ExprType.STRING, value: '$event'}
])
];
/**
* 解析抽象节点属性
*
* @param {ANode} aNode 抽象节点
* @param {string} name 属性名称
* @param {string} value 属性值
* @param {Object} options 解析参数
* @param {Array?} options.delimiters 插值分隔符列表
*/
function integrateAttr(aNode, name, value, options) {
var prefixIndex = name.indexOf('-');
var realName;
var prefix;
if (prefixIndex > 0) {
prefix = name.slice(0, prefixIndex);
realName = name.slice(prefixIndex + 1);
}
switch (prefix) {
case 'on':
var event = {
name: realName,
modifier: {}
};
aNode.events.push(event);
var colonIndex;
while ((colonIndex = value.indexOf(':')) > 0) {
var modifier = value.slice(0, colonIndex);
// eventHandler("dd:aa") 这种情况不能算modifier,需要辨识
if (!/^[a-z]+$/i.test(modifier)) {
break;
}
event.modifier[modifier] = true;
value = value.slice(colonIndex + 1);
}
event.expr = parseCall(value, DEFAULT_EVENT_ARGS);
break;
case 'san':
case 's':
parseDirective(aNode, realName, value, options);
break;
case 'prop':
integrateProp(aNode, realName, value, options);
break;
case 'var':
if (!aNode.vars) {
aNode.vars = [];
}
realName = kebab2camel(realName);
aNode.vars.push({
name: realName,
expr: parseExpr(value.replace(/(^\{\{|\}\}$)/g, ''))
});
break;
default:
integrateProp(aNode, name, value, options);
}
}
/**
* 解析抽象节点绑定属性
*
* @inner
* @param {ANode} aNode 抽象节点
* @param {string} name 属性名称
* @param {string} value 属性值
* @param {Object} options 解析参数
* @param {Array?} options.delimiters 插值分隔符列表
*/
function integrateProp(aNode, name, value, options) {
// parse two way binding, e.g. value="{=ident=}"
var xMatch = value.match(/^\{=\s*(.*?)\s*=\}$/);
if (xMatch) {
aNode.props.push({
name: name,
expr: parseExpr(xMatch[1]),
x: 1,
raw: value
});
return;
}
// parse normal prop
var prop = {
name: name,
expr: parseText(value, options.delimiters),
raw: value
};
// 这里不能把只有一个插值的属性抽取
// 因为插值里的值可能是html片段,容易被注入
// 组件的数据绑定在组件init时做抽取
switch (name) {
case 'class':
case 'style':
each(prop.expr.segs, function (seg) {
if (seg.type === ExprType.INTERP) {
seg.filters.push({
type: ExprType.CALL,
name: createAccessor([
{
type: ExprType.STRING,
value: '_' + prop.name
}
]),
args: []
});
}
});
break;
case 'checked':
if (aNode.tagName === 'input') {
postProp(prop);
}
break;
}
aNode.props.push(prop);
}
// exports = module.exports = integrateAttr;
/**
* @file 解析模板
* @author errorrik([email protected])
*/
// var createANode = require('./create-a-node');
// var Walker = require('./walker');
// var integrateAttr = require('./integrate-attr');
// var parseText = require('./parse-text');
// var autoCloseTags = require('../browser/auto-close-tags');
// #[begin] error
function getXPath(stack, currentTagName) {
var path = ['ROOT'];
for (var i = 1, len = stack.length; i < len; i++) {
path.push(stack[i].tagName);
}
if (currentTagName) {
path.push(currentTagName);
}
return path.join('>');
}
// #[end]
/* eslint-disable fecs-max-statements */
/**
* 解析 template
*
* @param {string} source template源码
* @param {Object?} options 解析参数
* @param {string?} options.trimWhitespace 空白文本的处理策略。none|blank|all
* @param {Array?} options.delimiters 插值分隔符列表
* @return {ANode}
*/
function parseTemplate(source, options) {
options = options || {};
options.trimWhitespace = options.trimWhitespace || 'none';
var rootNode = createANode();
if (typeof source !== 'string') {
return rootNode;
}
source = source.replace(/<!--([\s\S]*?)-->/mg, '').replace(/(^\s+|\s+$)/g, '');
var walker = new Walker(source);
var tagReg = /<(\/)?([a-z0-9-]+)\s*/ig;
var attrReg = /([-:0-9a-z\(\)\[\]]+)(\s*=\s*(['"])([^\3]*?)\3)?\s*/ig;
var tagMatch;
var currentNode = rootNode;
var stack = [rootNode];
var stackIndex = 0;
var beforeLastIndex = 0;
while ((tagMatch = walker.match(tagReg)) != null) {
var tagEnd = tagMatch[1];
var tagName = tagMatch[2].toLowerCase();
pushTextNode(source.slice(
beforeLastIndex,
walker.index - tagMatch[0].length
));
// 62: >
// 47: /
// 处理 </xxxx >
if (tagEnd && walker.currentCode() === 62) {
// 满足关闭标签的条件时,关闭标签
// 向上查找到对应标签,找不到时忽略关闭
var closeIndex = stackIndex;
// #[begin] error
// 如果正在闭合一个自闭合的标签,例如 </input>,报错
if (autoCloseTags[tagName]) {
throw new Error(''
+ '[SAN ERROR] ' + getXPath(stack, tagName) + ' is a `auto closed` tag, '
+ 'so it cannot be closed with </' + tagName + '>'
);
}
// 如果关闭的 tag 和当前打开的不一致,报错
if (
stack[closeIndex].tagName !== tagName
// 这里要把 table 自动添加 tbody 的情况给去掉
&& !(tagName === 'table' && stack[closeIndex].tagName === 'tbody')
) {
throw new Error('[SAN ERROR] ' + getXPath(stack) + ' is closed with ' + tagName);
}
// #[end]
while (closeIndex > 0 && stack[closeIndex].tagName !== tagName) {
closeIndex--;
}
if (closeIndex > 0) {
stack.length = closeIndex;
stackIndex = closeIndex - 1;
currentNode = stack[stackIndex];
}
walker.go(1);
}
// #[begin] error
// 处理 </xxx 非正常闭合标签
else if (tagEnd) {
// 如果闭合标签时,匹配后的下一个字符是 <,即下一个标签的开始,那么当前闭合标签未闭合
if (walker.currentCode() === 60) {
throw new Error(''
+ '[SAN ERROR] ' + getXPath(stack)
+ '\'s close tag not closed'
);
}
// 闭合标签有属性
throw new Error(''
+ '[SAN ERROR] ' + getXPath(stack)
+ '\'s close tag has attributes'
);
}
// #[end]
else if (!tagEnd) {
var aElement = createANode({
tagName: tagName
});
var tagClose = autoCloseTags[tagName];
// 解析 attributes
/* eslint-disable no-constant-condition */
while (1) {
/* eslint-enable no-constant-condition */
var nextCharCode = walker.currentCode();
// 标签结束时跳出 attributes 读取
// 标签可能直接结束或闭合结束
if (nextCharCode === 62) {
walker.go(1);
break;
}
// 遇到 /> 按闭合处理
else if (nextCharCode === 47
&& walker.charCode(walker.index + 1) === 62
) {
walker.go(2);
tagClose = 1;
break;
}
// #[begin] error
// 在处理一个 open 标签时,如果遇到了 <, 即下一个标签的开始,则当前标签未能正常闭合,报错
if (nextCharCode === 60) {
throw new Error('[SAN ERROR] ' + getXPath(stack, tagName) + ' is not closed');
}
// #[end]
// 读取 attribute
var attrMatch = walker.match(attrReg);
if (attrMatch) {
// #[begin] error
// 如果属性有 =,但没取到 value,报错
if (
walker.charCode(attrMatch.index + attrMatch[1].length) === 61
&& !attrMatch[2]
) {
throw new Error(''
+ '[SAN ERROR] ' + getXPath(stack, tagName) + ' attribute `'
+ attrMatch[1] + '` is not wrapped with ""'
);
}
// #[end]
integrateAttr(
aElement,
attrMatch[1],
attrMatch[2] ? attrMatch[4] : '',
options
);
}
}
// match if directive for else/elif directive
var elseDirective = aElement.directives['else'] || aElement.directives.elif; // eslint-disable-line dot-notation
if (elseDirective) {
var parentChildrenLen = currentNode.children.length;
while (parentChildrenLen--) {
var parentChild = currentNode.children[parentChildrenLen];
if (parentChild.textExpr) {
currentNode.children.splice(parentChildrenLen, 1);
continue;
}
// #[begin] error
if (!parentChild.directives['if']) { // eslint-disable-line dot-notation
throw new Error('[SAN FATEL] else not match if.');
}
// #[end]
parentChild.elses = parentChild.elses || [];
parentChild.elses.push(aElement);
break;
}
}
else {
if (aElement.tagName === 'tr' && currentNode.tagName === 'table') {
var tbodyNode = createANode({
tagName: 'tbody'
});
currentNode.children.push(tbodyNode);
currentNode = tbodyNode;
stack[++stackIndex] = tbodyNode;
}
currentNode.children.push(aElement);
}
if (!tagClose) {
currentNode = aElement;
stack[++stackIndex] = aElement;
}
}
beforeLastIndex = walker.index;
}
pushTextNode(walker.cut(beforeLastIndex));
return rootNode;
/**
* 在读取栈中添加文本节点
*
* @inner
* @param {string} text 文本内容
*/
function pushTextNode(text) {
switch (options.trimWhitespace) {
case 'blank':
if (/^\s+$/.test(text)) {
text = null;
}
break;
case 'all':
text = text.replace(/(^\s+|\s+$)/g, '');
break;
}
if (text) {
currentNode.children.push(createANode({
textExpr: parseText(text, options.delimiters)
}));
}
}
}
/* eslint-enable fecs-max-statements */
// exports = module.exports = parseTemplate;
/**
* @file 默认filter
* @author errorrik([email protected])
*/
/* eslint-disable fecs-camelcase */
/* eslint-disable guard-for-in */
/**
* 默认filter
*
* @const
* @type {Object}
*/
var DEFAULT_FILTERS = {
/**
* URL编码filter
*
* @param {string} source 源串
* @return {string} 替换结果串
*/
url: encodeURIComponent,
_class: function (source) {
if (source instanceof Array) {
return source.join(' ');
}
return source;
},
_style: function (source) {
if (typeof source === 'object') {
var result = '';
for (var key in source) {
result += key + ':' + source[key] + ';';
}
return result;
}
return source;
},
_sep: function (source, sep) {
return source ? sep + source : source;
}
};
/* eslint-enable fecs-camelcase */
// exports = module.exports = DEFAULT_FILTERS;
/**
* @file HTML转义
* @author errorrik([email protected])
*/
/**
* HTML Filter替换的字符实体表
*
* @const
* @inner
* @type {Object}
*/
var HTML_ENTITY = {
/* jshint ignore:start */
'&': '&',
'<': '<',
'>': '>',
'"': '"',
/* eslint-disable quotes */
"'": '''
/* eslint-enable quotes */
/* jshint ignore:end */
};
/**
* HTML Filter的替换函数
*
* @inner
* @param {string} c 替换字符
* @return {string} 替换后的HTML字符实体
*/
function htmlFilterReplacer(c) {
return HTML_ENTITY[c];
}
/**
* HTML转义
*
* @param {string} source 源串
* @return {string} 替换结果串
*/
function escapeHTML(source) {
return source != null
? ('' + source).replace(/[&<>"']/g, htmlFilterReplacer)
: '';
}
// exports = module.exports = escapeHTML;
/**
* @file 表达式计算
* @author errorrik([email protected])
*/
// var ExprType = require('../parser/expr-type');
// var DEFAULT_FILTERS = require('./default-filters');
// var escapeHTML = require('./escape-html');
// var evalArgs = require('./eval-args');
// var dataCache = require('./data-cache');
/**
* 计算表达式的值
*
* @param {Object} expr 表达式对象
* @param {Data} data 数据容器对象
* @param {Component=} owner 所属组件环境
* @param {boolean?} escapeInterpHtml 是否对插值进行html转义
* @return {*}
*/
function evalExpr(expr, data, owner, escapeInterpHtml) {
if (expr.value != null) {
return expr.value;
}
var value = dataCache.get(data, expr);
if (value == null) {
switch (expr.type) {
case ExprType.UNARY:
value = !evalExpr(expr.expr, data, owner);
break;
case ExprType.BINARY:
var leftValue = evalExpr(expr.segs[0], data, owner);
var rightValue = evalExpr(expr.segs[1], data, owner);
/* eslint-disable eqeqeq */
switch (expr.operator) {
case 37:
value = leftValue % rightValue;
break;
case 43:
value = leftValue + rightValue;
break;
case 45:
value = leftValue - rightValue;
break;
case 42:
value = leftValue * rightValue;
break;
case 47:
value = leftValue / rightValue;
break;
case 60:
value = leftValue < rightValue;
break;
case 62:
value = leftValue > rightValue;
break;
case 76:
value = leftValue && rightValue;
break;
case 94:
value = leftValue != rightValue;
break;
case 121:
value = leftValue <= rightValue;
break;
case 122:
value = leftValue == rightValue;
break;
case 123:
value = leftValue >= rightValue;
break;
case 155:
value = leftValue !== rightValue;
break;
case 183:
value = leftValue === rightValue;
break;
case 248:
value = leftValue || rightValue;
break;
}
/* eslint-enable eqeqeq */
break;
case ExprType.TERTIARY:
value = evalExpr(
expr.segs[evalExpr(expr.segs[0], data, owner) ? 1 : 2],
data,
owner
);
break;
case ExprType.ACCESSOR:
value = data.get(expr);
break;
case ExprType.INTERP:
value = evalExpr(expr.expr, data, owner);
if (owner) {
for (var i = 0, l = expr.filters.length; i < l; i++) {
var filter = expr.filters[i];
var filterName = filter.name.paths[0].value;
if (owner.filters[filterName]) {
value = owner.filters[filterName].apply(
owner,
[value].concat(evalArgs(filter.args, data, owner))
);
}
else if (DEFAULT_FILTERS[filterName]) {
value = DEFAULT_FILTERS[filterName](
value,
filter.args[0] ? filter.args[0].value : ''
);
}
}
}
if (value == null) {
value = '';
}
break;
/* eslint-disable no-redeclare */
case ExprType.TEXT:
var buf = '';
for (var i = 0, l = expr.segs.length; i < l; i++) {
var seg = expr.segs[i];
buf += seg.value || evalExpr(seg, data, owner, escapeInterpHtml);
}
return buf;
}
dataCache.set(data, expr, value);
}
if (expr.type === ExprType.INTERP && escapeInterpHtml && !expr.original) {
value = escapeHTML(value);
}
return value;
}
// exports = module.exports = evalExpr;
/**
* @file 为函数调用计算参数数组的值
* @author errorrik([email protected])
*/
// var evalExpr = require('../runtime/eval-expr');
/**
* 为函数调用计算参数数组的值
*
* @param {Array} args 参数表达式列表
* @param {Data} data 数据环境
* @param {Component} owner 组件环境
* @return {Array}
*/
function evalArgs(args, data, owner) {
var result = [];
for (var i = 0; i < args.length; i++) {
result.push(evalExpr(args[i], data, owner));
}
return result;
}
// exports = module.exports = evalArgs;
/**
* @file 数据缓存管理器
* @author errorrik([email protected])
*/
var dataCacheSource = {};
var dataCacheClearly = 1;
/**
* 数据缓存管理器
*
* @const
* @type {Object}
*/
var dataCache = {
clear: function () {
if (!dataCacheClearly) {
dataCacheClearly = 1;
dataCacheSource = {};
}
},
set: function (data, expr, value) {
if (expr.raw) {
dataCacheClearly = 0;
(dataCacheSource[data.id] = dataCacheSource[data.id] || {})[expr.raw] = value;
}
},
get: function (data, expr) {
if (expr.raw && dataCacheSource[data.id]) {
return dataCacheSource[data.id][expr.raw];
}
}
};
// exports = module.exports = dataCache;
/**
* @file 比较变更表达式与目标表达式之间的关系
* @author errorrik([email protected])
*/
// var ExprType = require('../parser/expr-type');
// var evalExpr = require('./eval-expr');
// var each = require('../util/each');
/**
* 判断变更表达式与多个表达式之间的关系,0为完全没关系,1为有关系
*
* @inner
* @param {Object} changeExpr 目标表达式
* @param {Array} exprs 多个源表达式
* @param {Data} data 表达式所属数据环境
* @return {number}
*/
function changeExprCompareExprs(changeExpr, exprs, data) {
for (var i = 0, l = exprs.length; i < l; i++) {
if (changeExprCompare(changeExpr, exprs[i], data)) {
return 1;
}
}
return 0;
}
/**
* 比较变更表达式与目标表达式之间的关系,用于视图更新判断
* 视图更新需要根据其关系,做出相应的更新行为
*
* 0: 完全没关系
* 1: 变更表达式是目标表达式的母项(如a与a.b) 或 表示需要完全变化
* 2: 变更表达式是目标表达式相等
* >2: 变更表达式是目标表达式的子项,如a.b.c与a.b
*
* @param {Object} changeExpr 变更表达式
* @param {Object} expr 要比较的目标表达式
* @param {Data} data 表达式所属数据环境
* @return {number}
*/
function changeExprCompare(changeExpr, expr, data) {
switch (expr.type) {
case ExprType.ACCESSOR:
var paths = expr.paths;
var len = paths.length;
var changePaths = changeExpr.paths;
var changeLen = changePaths.length;
var result = 1;
for (var i = 0; i < len; i++) {
var pathExpr = paths[i];
if (pathExpr.type === ExprType.ACCESSOR
&& changeExprCompare(changeExpr, pathExpr, data)
) {
return 1;
}
if (result && i < changeLen
/* eslint-disable eqeqeq */
&& evalExpr(pathExpr, data) != evalExpr(changePaths[i], data)
/* eslint-enable eqeqeq */
) {
result = 0;
}
}
if (result) {
result = Math.max(1, changeLen - len + 2);
}
return result;
case ExprType.UNARY:
return changeExprCompare(changeExpr, expr.expr, data) ? 1 : 0;
case ExprType.TEXT:
case ExprType.BINARY:
case ExprType.TERTIARY:
return changeExprCompareExprs(changeExpr, expr.segs, data);
case ExprType.INTERP:
if (!changeExprCompare(changeExpr, expr.expr, data)) {
var filterResult;
each(expr.filters, function (filter) {
filterResult = changeExprCompareExprs(changeExpr, filter.args, data);
return !filterResult;
});
return filterResult ? 1 : 0;
}
return 1;
}
return 0;
}
// exports = module.exports = changeExprCompare;
/**
* @file 数据变更类型枚举
* @author errorrik([email protected])
*/
/**
* 数据变更类型枚举
*
* @const
* @type {Object}
*/
var DataChangeType = {
SET: 1,
SPLICE: 2
};
// exports = module.exports = DataChangeType;
/**
* @file 数据类
* @author errorrik([email protected])
*/
// var ExprType = require('../parser/expr-type');
// var evalExpr = require('./eval-expr');
// var DataChangeType = require('./data-change-type');
// var createAccessor = require('../parser/create-accessor');
// var parseExpr = require('../parser/parse-expr');
// var guid = require('../util/guid');
// var dataCache = require('./data-cache');
/**
* 数据类
*
* @class
* @param {Object?} data 初始数据
* @param {Model?} parent 父级数据容器
*/
function Data(data, parent) {
this.id = guid();
this.parent = parent;
this.raw = data || {};
this.listeners = [];
}
// #[begin] error
// 以下两个函数只在开发模式下可用,在生产模式下不存在
/**
* DataTypes 检测
*/
Data.prototype.checkDataTypes = function () {
if (this.typeChecker) {
this.typeChecker(this.raw);
}
};
/**
* 设置 type checker
*
* @param {Function} typeChecker 类型校验器
*/
Data.prototype.setTypeChecker = function (typeChecker) {
this.typeChecker = typeChecker;
};
// #[end]
/**
* 添加数据变更的事件监听器
*
* @param {Function} listener 监听函数
*/
Data.prototype.listen = function (listener) {
if (typeof listener === 'function') {
this.listeners.push(listener);
}
};
/**
* 移除数据变更的事件监听器
*
* @param {Function} listener 监听函数
*/
Data.prototype.unlisten = function (listener) {
var len = this.listeners.length;
while (len--) {
if (!listener || this.listeners[len] === listener) {
this.listeners.splice(len, 1);
}
}
};
/**
* 触发数据变更
*
* @param {Object} change 变更信息对象
*/
Data.prototype.fire = function (change) {
if (change.option.silent || change.option.silence || change.option.quiet) {
return;
}
for (var i = 0; i < this.listeners.length; i++) {
this.listeners[i].call(this, change);
}
};
/**
* 获取数据项
*
* @param {string|Object?} expr 数据项路径
* @param {Data?} callee 当前数据获取的调用环境
* @return {*}
*/
Data.prototype.get = function (expr, callee) {
var value = this.raw;
if (!expr) {
return value;
}
expr = parseExpr(expr);
var paths = expr.paths;
callee = callee || this;
value = value[paths[0].value];
if (value == null && this.parent) {
value = this.parent.get(expr, callee);
}
else {
for (var i = 1, l = paths.length; value != null && i < l; i++) {
value = value[paths[i].value || evalExpr(paths[i], callee)];
}
}
return value;
};
/**
* 数据对象变更操作
*
* @inner
* @param {Object|Array} source 要变更的源数据
* @param {Array} exprPaths 属性路径
* @param {*} value 变更属性值
* @param {Data} data 对应的Data对象
* @return {*} 变更后的新数据
*/
function immutableSet(source, exprPaths, value, data) {
if (exprPaths.length === 0) {
return value;
}
var prop = evalExpr(exprPaths[0], data);
var result;
if (source instanceof Array) {
var index = +prop;
result = source.slice(0);
result[isNaN(index) ? prop : index] = immutableSet(source[index], exprPaths.slice(1), value, data);
return result;
}
else if (typeof source === 'object') {
result = {};
for (var key in source) {
if (key !== prop) {
result[key] = source[key];
}
}
result[prop] = immutableSet(source[prop] || {}, exprPaths.slice(1), value, data);
return result;
}
return source;
}
/**
* 设置数据项
*
* @param {string|Object} expr 数据项路径
* @param {*} value 数据值
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
*/
Data.prototype.set = function (expr, value, option) {
option = option || {};
// #[begin] error
var exprRaw = expr;
// #[end]
expr = parseExpr(expr);
// #[begin] error
if (expr.type !== ExprType.ACCESSOR) {
throw new Error('[SAN ERROR] Invalid Expression in Data set: ' + exprRaw);
}
// #[end]
if (this.get(expr) === value) {
return;
}
dataCache.clear();
this.raw = immutableSet(this.raw, expr.paths, value, this);
this.fire({
type: DataChangeType.SET,
expr: expr,
value: value,
option: option
});
// #[begin] error
this.checkDataTypes();
// #[end]
};
/**
* 合并更新数据项
*
* @param {string|Object} expr 数据项路径
* @param {Object} source 待合并的数据值
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
*/
Data.prototype.merge = function (expr, source, option) {
option = option || {};
// #[begin] error
var exprRaw = expr;
// #[end]
expr = parseExpr(expr);
// #[begin] error
if (expr.type !== ExprType.ACCESSOR) {
throw new Error('[SAN ERROR] Invalid Expression in Data merge: ' + exprRaw);
}
if (typeof this.get(expr) !== 'object') {
throw new Error('[SAN ERROR] Merge Expects a Target of Type \'object\'; got ' + typeof oldValue);
}
if (typeof source !== 'object') {
throw new Error('[SAN ERROR] Merge Expects a Source of Type \'object\'; got ' + typeof source);
}
// #[end]
for (var key in source) {
this.set(
createAccessor(
expr.paths.concat(
[
{
type: ExprType.STRING,
value: key
}
]
)
),
source[key],
option
);
}
};
/**
* 基于更新函数更新数据项
*
* @param {string|Object} expr 数据项路径
* @param {Function} fn 数据处理函数
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
*/
Data.prototype.apply = function (expr, fn, option) {
option = option || {};
// #[begin] error
var exprRaw = expr;
// #[end]
expr = parseExpr(expr);
// #[begin] error
if (expr.type !== ExprType.ACCESSOR) {
throw new Error('[SAN ERROR] Invalid Expression in Data apply: ' + exprRaw);
}
// #[end]
var oldValue = this.get(expr);
// #[begin] error
if (typeof fn !== 'function') {
throw new Error(
'[SAN ERROR] Invalid Argument\'s Type in Data apply: '
+ 'Expected Function but got ' + typeof fn
);
}
// #[end]
var value = fn(oldValue);
if (oldValue === value) {
return;
}
this.set(expr, value, option);
};
/**
* 数组数据项splice操作
*
* @param {string|Object} expr 数据项路径
* @param {Array} args splice 接受的参数列表,数组项与Array.prototype.splice的参数一致
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
* @return {Array} 新数组
*/
Data.prototype.splice = function (expr, args, option) {
option = option || {};
// #[begin] error
var exprRaw = expr;
// #[end]
expr = parseExpr(expr);
// #[begin] error
if (expr.type !== ExprType.ACCESSOR) {
throw new Error('[SAN ERROR] Invalid Expression in Data splice: ' + exprRaw);
}
// #[end]
var target = this.get(expr);
var returnValue = [];
if (target instanceof Array) {
var index = args[0];
if (index < 0 || index > target.length) {
return;
}
var newArray = target.slice(0);
returnValue = newArray.splice.apply(newArray, args);
dataCache.clear();
this.raw = immutableSet(this.raw, expr.paths, newArray, this);
this.fire({
expr: expr,
type: DataChangeType.SPLICE,
index: index,
deleteCount: returnValue.length,
value: returnValue,
insertions: args.slice(2),
option: option
});
}
// #[begin] error
this.checkDataTypes();
// #[end]
return returnValue;
};
/**
* 数组数据项push操作
*
* @param {string|Object} expr 数据项路径
* @param {*} item 要push的值
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
* @return {number} 新数组的length属性
*/
Data.prototype.push = function (expr, item, option) {
var target = this.get(expr);
if (target instanceof Array) {
this.splice(expr, [target.length, 0, item], option);
return target.length + 1;
}
};
/**
* 数组数据项pop操作
*
* @param {string|Object} expr 数据项路径
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
* @return {*}
*/
Data.prototype.pop = function (expr, option) {
var target = this.get(expr);
if (target instanceof Array) {
var len = target.length;
if (len) {
return this.splice(expr, [len - 1, 1], option)[0];
}
}
};
/**
* 数组数据项shift操作
*
* @param {string|Object} expr 数据项路径
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
* @return {*}
*/
Data.prototype.shift = function (expr, option) {
return this.splice(expr, [0, 1], option)[0];
};
/**
* 数组数据项unshift操作
*
* @param {string|Object} expr 数据项路径
* @param {*} item 要unshift的值
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
* @return {number} 新数组的length属性
*/
Data.prototype.unshift = function (expr, item, option) {
var target = this.get(expr);
if (target instanceof Array) {
this.splice(expr, [0, 0, item], option);
return target.length + 1;
}
};
/**
* 数组数据项移除操作
*
* @param {string|Object} expr 数据项路径
* @param {number} index 要移除项的索引
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
*/
Data.prototype.removeAt = function (expr, index, option) {
this.splice(expr, [index, 1], option);
};
/**
* 数组数据项移除操作
*
* @param {string|Object} expr 数据项路径
* @param {*} value 要移除的项
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
*/
Data.prototype.remove = function (expr, value, option) {
var target = this.get(expr);
if (target instanceof Array) {
var len = target.length;
while (len--) {
if (target[len] === value) {
this.splice(expr, [len, 1], option);
break;
}
}
}
};
// exports = module.exports = Data;
/**
* @file 生命周期类
* @author errorrik([email protected])
*/
function lifeCycleOwnIs(name) {
return this[name];
}
/* eslint-disable fecs-valid-var-jsdoc */
/**
* 节点生命周期信息
*
* @inner
* @type {Object}
*/
var LifeCycle = {
start: {},
compiled: {
is: lifeCycleOwnIs,
compiled: true
},
inited: {
is: lifeCycleOwnIs,
compiled: true,
inited: true
},
painting: {
is: lifeCycleOwnIs,
compiled: true,
inited: true,
painting: true
},
created: {
is: lifeCycleOwnIs,
compiled: true,
inited: true,
created: true
},
attached: {
is: lifeCycleOwnIs,
compiled: true,
inited: true,
created: true,
attached: true
},
leaving: {
is: lifeCycleOwnIs,
compiled: true,
inited: true,
created: true,
attached: true,
leaving: true
},
detached: {
is: lifeCycleOwnIs,
compiled: true,
inited: true,
created: true,
detached: true
},
disposed: {
is: lifeCycleOwnIs,
disposed: true
}
};
/* eslint-enable fecs-valid-var-jsdoc */
// exports = module.exports = LifeCycle;
/**
* @file 节点类型
* @author errorrik([email protected])
*/
/**
* 节点类型
*
* @const
* @type {Object}
*/
var NodeType = {
TEXT: 1,
IF: 2,
FOR: 3,
ELEM: 4,
CMPT: 5,
SLOT: 6,
TPL: 7
};
// exports = module.exports = NodeType;
/**
* @file 获取 ANode props 数组中相应 name 的项
* @author errorrik([email protected])
*/
/**
* 获取 ANode props 数组中相应 name 的项
*
* @param {Object} aNode ANode对象
* @param {string} name name属性匹配串
* @return {Object}
*/
function getANodeProp(aNode, name) {
var index = aNode.hotspot.props[name];
if (index != null) {
return aNode.props[index];
}
}
// exports = module.exports = getANodeProp;
/**
* @file 获取属性处理对象
* @author errorrik([email protected])
*/
// var contains = require('../util/contains');
// var empty = require('../util/empty');
// var svgTags = require('../browser/svg-tags');
// var evalExpr = require('../runtime/eval-expr');
// var getANodeProp = require('./get-a-node-prop');
// var NodeType = require('./node-type');
/**
* HTML 属性和 DOM 操作属性的对照表
*
* @inner
* @const
* @type {Object}
*/
var HTML_ATTR_PROP_MAP = {
'readonly': 'readOnly',
'cellpadding': 'cellPadding',
'cellspacing': 'cellSpacing',
'colspan': 'colSpan',
'rowspan': 'rowSpan',
'valign': 'vAlign',
'usemap': 'useMap',
'frameborder': 'frameBorder',
'for': 'htmlFor'
};
/**
* 默认的元素的属性设置的变换方法
*
* @inner
* @type {Object}
*/
var defaultElementPropHandler = {
attr: function (element, name, value) {
if (value != null) {
return ' ' + name + '="' + value + '"';
}
},
prop: function (element, name, value) {
var propName = HTML_ATTR_PROP_MAP[name] || name;
var el = element.el;
// input 的 type 是个特殊属性,其实也应该用 setAttribute
// 但是 type 不应该运行时动态改变,否则会有兼容性问题
// 所以这里直接就不管了
if (svgTags[element.tagName] || !(propName in el)) {
el.setAttribute(name, value);
}
else {
el[propName] = value == null ? '' : value;
}
// attribute 绑定的是 text,所以不会出现 null 的情况,这里无需处理
// 换句话来说,san 是做不到 attribute 时有时无的
// if (value == null) {
// el.removeAttribute(name);
// }
},
output: function (element, bindInfo, data) {
data.set(bindInfo.expr, element.el[bindInfo.name], {
target: {
id: element.id,
prop: bindInfo.name
}
});
}
};
/* eslint-disable fecs-properties-quote */
/**
* 默认的属性设置变换方法
*
* @inner
* @type {Object}
*/
var defaultElementPropHandlers = {
style: {
attr: function (element, name, value) {
if (value) {
return ' style="' + value + '"';
}
},
prop: function (element, name, value) {
element.el.style.cssText = value;
}
},
'class': { // eslint-disable-line
attr: function (element, name, value) {
if (value) {
return ' class="' + value + '"';
}
},
prop: function (element, name, value) {
element.el.className = value;
}
},
slot: {
attr: empty,
prop: empty
},
readonly: genBoolPropHandler('readonly'),
disabled: genBoolPropHandler('disabled'),
autofocus: genBoolPropHandler('autofocus'),
required: genBoolPropHandler('required'),
draggable: genBoolPropHandler('draggable')
};
/* eslint-enable fecs-properties-quote */
// draggable attribute 是枚举类型,但 property 接受 boolean
// 所以这里声明 bool prop,然后 attr 置回来
defaultElementPropHandlers.draggable.attr = defaultElementPropHandler.attr;
var checkedPropHandler = genBoolPropHandler('checked');
var analInputChecker = {
checkbox: contains,
radio: function (a, b) {
return a === b;
}
};
function analInputCheckedState(element, value, oper) {
var bindValue = getANodeProp(element.aNode, 'value');
var bindType = getANodeProp(element.aNode, 'type');
if (bindValue && bindType) {
var type = evalExpr(bindType.expr, element.scope, element.owner);
if (analInputChecker[type]) {
var bindChecked = getANodeProp(element.aNode, 'checked');
if (!bindChecked.hintExpr) {
bindChecked.hintExpr = bindValue.expr;
}
var checkedState = analInputChecker[type](
value,
evalExpr(bindValue.expr, element.scope, element.owner)
);
switch (oper) {
case 'attr':
return checkedState ? ' checked="checked"' : '';
case 'prop':
element.el.checked = checkedState;
return;
}
}
}
return checkedPropHandler[oper](element, 'checked', value);
}
var elementPropHandlers = {
input: {
multiple: genBoolPropHandler('multiple'),
checked: {
attr: function (element, name, value) {
return analInputCheckedState(element, value, 'attr');
},
prop: function (element, name, value) {
analInputCheckedState(element, value, 'prop');
},
output: function (element, bindInfo, data) {
var el = element.el;
var bindValue = getANodeProp(element.aNode, 'value');
var bindType = getANodeProp(element.aNode, 'type') || {};
if (bindValue && bindType) {
switch (bindType.raw) {
case 'checkbox':
data[el.checked ? 'push' : 'remove'](bindInfo.expr, el.value);
return;
case 'radio':
el.checked && data.set(bindInfo.expr, el.value, {
target: {
id: element.id,
prop: bindInfo.name
}
});
return;
}
}
defaultElementPropHandler.output(element, bindInfo, data);
}
}
},
textarea: {
value: {
attr: empty,
prop: defaultElementPropHandler.prop,
output: defaultElementPropHandler.output
}
},
option: {
value: {
attr: function (element, name, value) {
return ' value="' + (value || '') + '"'
+ (isOptionSelected(element, value) ? 'selected' : '');
},
prop: function (element, name, value) {
defaultElementPropHandler.prop(element, name, value);
if (isOptionSelected(element, value)) {
element.el.selected = true;
}
}
}
},
select: {
value: {
attr: empty,
prop: function (element, name, value) {
element.el.value = value || '';
},
output: defaultElementPropHandler.output
}
}
};
function isOptionSelected(element, value) {
var parentSelect = element.parent;
while (parentSelect) {
if (parentSelect.tagName === 'select') {
break;
}
parentSelect = parentSelect.parent;
}
if (parentSelect) {
var selectValue = null;
var prop;
var expr;
if ((prop = getANodeProp(parentSelect.aNode, 'value'))
&& (expr = prop.expr)
) {
selectValue = parentSelect.nodeType === NodeType.CMPT
? evalExpr(expr, parentSelect.data, parentSelect)
: evalExpr(expr, parentSelect.scope, parentSelect.owner)
|| '';
}
if (selectValue === value) {
return 1;
}
}
}
/**
* 生成 bool 类型属性绑定操作的变换方法
*
* @inner
* @param {string} attrName 属性名
* @return {Object}
*/
function genBoolPropHandler(attrName) {
return {
attr: function (element, name, value) {
// 因为元素的attr值必须经过html escape,否则可能有漏洞
// 所以这里直接对假值字符串形式进行处理
// NaN之类非主流的就先不考虑了
var prop = getANodeProp(element.aNode, name);
if (prop && prop.raw === ''
|| value && value !== 'false' && value !== '0'
) {
return ' ' + attrName;
}
},
prop: function (element, name, value) {
var propName = HTML_ATTR_PROP_MAP[attrName] || attrName;
element.el[propName] = !!(value && value !== 'false' && value !== '0');
}
};
}
/**
* 获取属性处理对象
*
* @param {Element} element 元素实例
* @param {string} name 属性名
* @return {Object}
*/
function getPropHandler(element, name) {
var tagPropHandlers = elementPropHandlers[element.tagName];
if (!tagPropHandlers) {
tagPropHandlers = elementPropHandlers[element.tagName] = {};
}
var propHandler = tagPropHandlers[name];
if (!propHandler) {
propHandler = defaultElementPropHandlers[name] || defaultElementPropHandler;
tagPropHandlers[name] = propHandler;
}
return propHandler;
}
// exports = module.exports = getPropHandler;
/**
* @file 判断变更是否来源于元素
* @author errorrik([email protected])
*/
/**
* 判断变更是否来源于元素,来源于元素时,视图更新需要阻断
*
* @param {Object} change 变更对象
* @param {Element} element 元素
* @param {string?} propName 属性名,可选。需要精确判断是否来源于此属性时传入
* @return {boolean}
*/
function isDataChangeByElement(change, element, propName) {
var changeTarget = change.option.target;
return changeTarget && changeTarget.id === element.id
&& (!propName || changeTarget.prop === propName);
}
// exports = module.exports = isDataChangeByElement;
/**
* @file 在对象上使用accessor表达式查找方法
* @author errorrik([email protected])
*/
// var evalExpr = require('../runtime/eval-expr');
/**
* 在对象上使用accessor表达式查找方法
*
* @param {Object} source 源对象
* @param {Object} nameExpr 表达式
* @param {Data} data 所属数据环境
* @return {Function}
*/
function findMethod(source, nameExpr, data) {
var method = source;
for (var i = 0; method != null && i < nameExpr.paths.length; i++) {
method = method[evalExpr(nameExpr.paths[i], data)];
}
return method;
}
// exports = module.exports = findMethod;
/**
* @file 声明式事件的监听函数
* @author errorrik([email protected])
*/
// var evalArgs = require('../runtime/eval-args');
// var findMethod = require('../runtime/find-method');
// var Data = require('../runtime/data');
/**
* 声明式事件的监听函数
*
* @param {Object} eventBind 绑定信息对象
* @param {boolean} isComponentEvent 是否组件自定义事件
* @param {Data} data 数据环境
* @param {Event} e 事件对象
*/
function eventDeclarationListener(eventBind, isComponentEvent, data, e) {
var method = findMethod(this, eventBind.expr.name, data);
if (typeof method === 'function') {
var scope = new Data(
{$event: isComponentEvent ? e : e || window.event},
data
);
method.apply(this, evalArgs(eventBind.expr.args, scope, this));
}
}
// exports = module.exports = eventDeclarationListener;
/**
* @file 往字符串连接对象中添加字符串
* @author errorrik([email protected])
*/
// var ieOldThan9 = require('../browser/ie-old-than-9');
/**
* 往字符串连接对象中添加字符串
*
* @param {Object} buf 字符串连接对象
* @param {string} str 要添加的字符串
*/
var htmlBufferPush =
// #[begin] allua
// ieOldThan9
// ?
// function (buf, str) {
// buf.raw[buf.length++] = str;
// buf.tagStart = 0;
// }
// :
// #[end]
function (buf, str) {
buf.raw += str;
};
// exports = module.exports = htmlBufferPush;
/**
* @file 自闭合标签表
* @author errorrik([email protected])
*/
// var splitStr2Obj = require('../util/split-str-2-obj');
/**
* 自闭合标签列表
*
* @type {Object}
*/
var hotTags = splitStr2Obj('div,span,input,button,textarea,form,label,dl,dt,dd,ul,ol,li,a,b,u,h1,h2,h3,h4,h5,h6');
// exports = module.exports = hotTags;
/**
* @file 是否浏览器环境
* @author errorrik([email protected])
*/
var isBrowser = typeof window !== 'undefined';
// exports = module.exports = isBrowser;
/**
* @file insertBefore 方法的兼容性封装
* @author errorrik([email protected])
*/
/**
* insertBefore 方法的兼容性封装
*
* @param {HTMLNode} targetEl 要插入的节点
* @param {HTMLElement} parentEl 父元素
* @param {HTMLElement?} beforeEl 在此元素之前插入
*/
function insertBefore(targetEl, parentEl, beforeEl) {
if (parentEl) {
if (beforeEl) {
parentEl.insertBefore(targetEl, beforeEl);
}
else {
parentEl.appendChild(targetEl);
}
}
}
// exports = module.exports = insertBefore;
/**
* @file 创建字符串连接对象,用于跨平台提高性能的字符串连接,万一不小心支持老式浏览器了呢
* @author errorrik([email protected])
*/
// var ieOldThan9 = require('../browser/ie-old-than-9');
/**
* 创建字符串连接对象
*
* @return {Object}
*/
function createHTMLBuffer() {
return {
raw:
// #[begin] allua
// ieOldThan9
// ? []
// :
// #[end]
'',
length: 0,
tagStart: 1,
insertComments: []
};
}
// exports = module.exports = createHTMLBuffer;
/**
* @file 往html字符串连接对象中添加注释
* @author errorrik([email protected])
*/
// var ieOldThan9 = require('../browser/ie-old-than-9');
/**
* 往html字符串连接对象中添加注释
*
* @param {Object} buf 字符串连接对象
* @param {string} str 要添加的字符串
*/
var htmlBufferComment =
// #[begin] allua
// ieOldThan9
// ?
// function (buf, str) {
// buf.raw[buf.length++] = '<!--' + str + '-->';
// if (buf.tagStart) {
// buf.insertComments.push([str, buf.tagId]);
// }
// }
// :
// #[end]
function (buf, str) {
buf.raw += '<!--' + str + '-->';
}
;
// exports = module.exports = htmlBufferComment;
/**
* @file 输出 HTML buffer 内容到 DOM 上
* @author errorrik([email protected])
*/
// var ieOldThan9 = require('../browser/ie-old-than-9');
// var insertBefore = require('../browser/insert-before');
/**
* 输出 HTML buffer 内容到 DOM 上
*
* @param {Object} buf html字符串连接对象
* @param {HTMLElement} target 目标DOM元素
* @param {string?} pos 相对target的位置
*/
function outputHTMLBuffer(buf, target, pos) {
// html 没内容就不要设置 innerHTML了
// 这里还能避免在 IE 下 component root 为 input 等元素时设置 innerHTML 报错的问题
var html =
// #[begin] allua
// ieOldThan9
// ? buf.raw.join('')
// :
//
// #[end]
buf.raw;
if (!html) {
return;
}
if (pos) {
target.insertAdjacentHTML(pos, html);
}
else {
target.innerHTML = html;
}
// 处理 ie 低版本下自动过滤 comment 的问题
// #[begin] allua
// if (ieOldThan9) {
// var insertComments = buf.insertComments;
// var len = insertComments.length;
//
// while (len--) {
// var insertComment = insertComments[len];
// var commentNode = document.createComment(insertComment[0]);
// var insertParentEl = insertComment[1] ? document.getElementById(insertComment[1]) : null;
// var insertBeforeEl = null;
//
// if (insertParentEl) {
// insertBeforeEl = insertParentEl.firstChild;
// }
// else {
// switch (pos) {
// case 'afterend':
// insertParentEl = target.parentNode;
// insertBeforeEl = target.nextSibling;
// break;
//
// case 'beforebegin':
// insertParentEl = target.parentNode;
// insertBeforeEl = target;
// break;
//
// case 'beforeend':
// insertParentEl = target;
// insertBeforeEl = null;
// break;
//
// default:
// insertParentEl = target;
// insertBeforeEl = insertParentEl.firstChild;
// }
// }
//
// insertBefore(commentNode, insertParentEl, insertBeforeEl);
// }
// }
// #[end]
}
// exports = module.exports = outputHTMLBuffer;
/**
* @file 输出 HTML buffer 内容到 DOM 上
* @author errorrik([email protected])
*/
// var outputHTMLBuffer = require('./output-html-buffer');
/**
* 将 HTML buffer 内容插入到 DOM 节点之前
*
* @param {Object} buf html字符串连接对象
* @param {HTMLElement} parentEl 父元素
* @param {HTMLNode?} beforeEl 在此节点之前插入
*/
function outputHTMLBufferBefore(buf, parentEl, beforeEl) {
if (beforeEl) {
if (beforeEl.nodeType === 1) {
outputHTMLBuffer(buf, beforeEl, 'beforebegin');
}
else {
var tempFlag = document.createElement('script');
parentEl.insertBefore(tempFlag, beforeEl);
outputHTMLBuffer(buf, tempFlag, 'beforebegin');
parentEl.removeChild(tempFlag);
}
}
else {
outputHTMLBuffer(buf, parentEl, 'beforeend');
}
}
// exports = module.exports = outputHTMLBufferBefore;
/**
* @file 获取节点 stump 的父元素
* @author errorrik([email protected])
*/
/**
* 获取节点 stump 的父元素
* if、for 节点的 el stump 是 comment node,在 IE 下还可能不存在
* 获取其父元素通常用于 el 的查找,以及视图变更的插入操作
*
* @param {Node} node 节点对象
* @return {HTMLElement}
*/
function getNodeStumpParent(node) {
if (node.el) {
return node.el.parentNode;
}
node = node.parent;
var parentNode;
while (node) {
parentNode = node._getEl();
if (parentNode) {
while (parentNode && parentNode.nodeType !== 1) {
parentNode = parentNode.parentNode;
}
break;
}
node = node.parent;
}
return parentNode;
}
// exports = module.exports = getNodeStumpParent;
/**
* @file 获取节点 stump 的 comment
* @author errorrik([email protected])
*/
// var getNodeStumpParent = require('./get-node-stump-parent');
/**
* 获取节点 stump 的 comment
*
* @param {Node} node 节点对象
* @return {Comment}
*/
function getNodeStump(node) {
if (typeof node.el === 'undefined') {
var parentNode = getNodeStumpParent(node);
var el = parentNode.firstChild;
while (el) {
if (el.nodeType === 8
&& el.data.indexOf(node.id) === 0
) {
if (node.el) {
node.sel = node.el;
}
node.el = el;
}
el = el.nextSibling;
}
}
return node.el;
}
// exports = module.exports = getNodeStump;
/**
* @file 判断元素是否不允许设置HTML
* @author errorrik([email protected])
*/
// some html elements cannot set innerHTML in old ie
// see: https://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
/**
* 判断元素是否不允许设置HTML
*
* @param {HTMLElement} el 要判断的元素
* @return {boolean}
*/
function noSetHTML(el) {
return /^(col|colgroup|frameset|style|table|tbody|tfoot|thead|tr|select)$/i.test(el.tagName)
}
// exports = module.exports = noSetHTML;
/**
* @file 获取节点 stump 的 comment
* @author errorrik([email protected])
*/
// var noSetHTML = require('../browser/no-set-html');
// #[begin] error
/**
* 获取节点 stump 的 comment
*
* @param {HTMLElement} el HTML元素
*/
function warnSetHTML(el) {
// dont warn if not in browser runtime
if (!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document)) {
return;
}
// some html elements cannot set innerHTML in old ie
// see: https://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
if (noSetHTML(el)) {
var message = '[SAN WARNING] set html for element "' + el.tagName
+ '" may cause an error in old IE';
/* eslint-disable no-console */
if (typeof console === 'object' && console.warn) {
console.warn(message);
}
else {
throw new Error(message);
}
/* eslint-enable no-console */
}
}
// #[end]
// exports = module.exports = warnSetHTML;
/**
* @file 判断是否结束桩
* @author errorrik([email protected])
*/
// #[begin] reverse
// /**
// * 判断是否结束桩
// *
// * @param {HTMLElement|HTMLComment} target 要判断的元素
// * @param {string} type 桩类型
// * @return {boolean}
// */
// function isEndStump(target, type) {
// return target.nodeType === 8 && target.data === '/s-' + type;
// }
// #[end]
// exports = module.exports = isEndStump;
/**
* @file 获取节点在组件树中的路径
* @author errorrik([email protected])
*/
// var NodeType = require('./node-type');
// #[begin] reverse
// /**
// * 获取节点在组件树中的路径
// *
// * @param {Node} node 节点对象
// * @return {Array}
// */
// function getNodePath(node) {
// var nodePaths = [];
// var nodeParent = node;
// while (nodeParent) {
// switch (nodeParent.nodeType) {
// case NodeType.ELEM:
// nodePaths.unshift(nodeParent.tagName);
// break;
//
// case NodeType.IF:
// nodePaths.unshift('if');
// break;
//
// case NodeType.FOR:
// nodePaths.unshift('for[' + nodeParent.anode.directives['for'].raw + ']'); // eslint-disable-line dot-notation
// break;
//
// case NodeType.SLOT:
// nodePaths.unshift('slot[' + (nodeParent.name || 'default') + ']');
// break;
//
// case NodeType.TPL:
// nodePaths.unshift('template');
// break;
//
// case NodeType.CMPT:
// nodePaths.unshift('component[' + (nodeParent.subTag || 'root') + ']');
// break;
//
// case NodeType.TEXT:
// nodePaths.unshift('text');
// break;
// }
//
// nodeParent = nodeParent.parent;
// }
//
// return nodePaths;
// }
// #[end]
// exports = module.exports = getNodePath;
/**
* @file text 节点类
* @author errorrik([email protected])
*/
// var each = require('../util/each');
// var isBrowser = require('../browser/is-browser');
// var removeEl = require('../browser/remove-el');
// var insertBefore = require('../browser/insert-before');
// var createHTMLBuffer = require('../runtime/create-html-buffer');
// var htmlBufferPush = require('../runtime/html-buffer-push');
// var htmlBufferComment = require('../runtime/html-buffer-comment');
// var outputHTMLBufferBefore = require('../runtime/output-html-buffer-before');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var evalExpr = require('../runtime/eval-expr');
// var NodeType = require('./node-type');
// var getNodeStump = require('./get-node-stump');
// var warnSetHTML = require('./warn-set-html');
// var isEndStump = require('./is-end-stump');
// var getNodePath = require('./get-node-path');
/**
* text 节点类
*
* @param {Object} aNode 抽象节点
* @param {Component} owner 所属组件环境
* @param {Model=} scope 所属数据环境
* @param {Node} parent 父亲节点
* @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象
*/
function TextNode(aNode, owner, scope, parent, reverseWalker) {
this.aNode = aNode;
this.owner = owner;
this.scope = scope;
this.parent = parent;
// #[begin] reverse
// if (reverseWalker) {
// var currentNode = reverseWalker.current;
// if (currentNode) {
// switch (currentNode.nodeType) {
// case 8:
// if (currentNode.data === 's-text') {
// currentNode.data = this.id;
// reverseWalker.goNext();
//
// while (1) { // eslint-disable-line
// currentNode = reverseWalker.current;
// if (!currentNode) {
// throw new Error('[SAN REVERSE ERROR] Text end flag not found. \nPaths: '
// + getNodePath(this).join(' > '));
// }
//
// if (isEndStump(currentNode, 'text')) {
// reverseWalker.goNext();
// currentNode.data = this.id;
// break;
// }
//
// reverseWalker.goNext();
// }
// }
// break;
//
// case 3:
// reverseWalker.goNext();
// if (!this.aNode.textExpr.original) {
// this.el = currentNode;
// }
// break;
// }
// }
// }
// #[end]
}
TextNode.prototype.nodeType = NodeType.TEXT;
/**
* 将text attach到页面
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
TextNode.prototype.attach = function (parentEl, beforeEl) {
var buf = createHTMLBuffer();
this._attachHTML(buf);
outputHTMLBufferBefore(buf, parentEl, beforeEl);
};
/**
* 销毁 text 节点
*/
TextNode.prototype.dispose = function () {
this._prev = null;
this.el = null;
};
/**
* 获取文本节点对应的主元素
*
* @return {HTMLComment|HTMLTextNode}
*/
TextNode.prototype._getEl = function () {
if (this.el) {
return this.el;
}
if (!this.aNode.textExpr.original) {
var parent = this.parent;
var prev;
var me = this;
each(parent.children, function (child, i) {
if (child === me) {
return false;
}
prev = child;
});
var parentEl = parent._getEl();
if (parentEl.nodeType !== 1) {
parentEl = parentEl.parentNode;
}
var prevEl = prev && prev._getEl() && prev.el.nextSibling;
if (!prevEl) {
switch (parent.nodeType) {
case NodeType.TPL:
case NodeType.SLOT:
prevEl = parent.sel.nextSibling;
break;
default:
prevEl = parentEl.firstChild;
}
}
if (this.content) {
this.el = prevEl;
}
else {
this.el = document.createTextNode('');
insertBefore(this.el, parentEl, prevEl);
}
}
return getNodeStump(this);
},
/**
* attach text 节点的 html
*
* @param {Object} buf html串存储对象
*/
TextNode.prototype._attachHTML = function (buf) {
this.content = evalExpr(this.aNode.textExpr, this.scope, this.owner, 1);
if (this.aNode.textExpr.original) {
htmlBufferComment(buf, this.id);
}
htmlBufferPush(buf, this.content);
if (this.aNode.textExpr.original) {
htmlBufferComment(buf, this.id);
}
};
var textUpdateProp = isBrowser
&& (typeof document.createTextNode('').textContent === 'string'
? 'textContent'
: 'data');
/**
* 更新 text 节点的视图
*
* @param {Array} changes 数据变化信息
*/
TextNode.prototype._update = function (changes) {
if (this.aNode.textExpr.value) {
return;
}
var el = this._getEl();
var len = changes ? changes.length : 0;
while (len--) {
if (changeExprCompare(changes[len].expr, this.aNode.textExpr, this.scope)) {
var text = evalExpr(this.aNode.textExpr, this.scope, this.owner, 1);
if (text !== this.content) {
this.content = text;
var rawText = evalExpr(this.aNode.textExpr, this.scope, this.owner);
if (this.aNode.textExpr.original) {
var startRemoveEl = this.sel.nextSibling;
var parentEl = el.parentNode;
while (startRemoveEl !== el) {
var removeTarget = startRemoveEl;
startRemoveEl = startRemoveEl.nextSibling;
removeEl(removeTarget);
}
// #[begin] error
warnSetHTML(parentEl);
// #[end]
var tempFlag = document.createElement('script');
parentEl.insertBefore(tempFlag, el);
tempFlag.insertAdjacentHTML('beforebegin', text);
parentEl.removeChild(tempFlag);
}
else {
el[textUpdateProp] = rawText;
}
}
return;
}
}
};
// exports = module.exports = TextNode;
/**
* @file 判断变更数组是否影响到数据引用摘要
* @author errorrik([email protected])
*/
// var each = require('../util/each');
/**
* 判断变更数组是否影响到数据引用摘要
*
* @param {Array} changes 变更数组
* @param {Object} dataRef 数据引用摘要
* @return {boolean}
*/
function changesIsInDataRef(changes, dataRef) {
var result;
each(changes, function (change) {
if (!change.overview) {
var paths = change.expr.paths;
change.overview = paths[0].value;
if (paths.length > 1) {
change.extOverview = paths[0].value + '.' + paths[1].value;
change.wildOverview = paths[0].value + '.*';
}
}
result = dataRef[change.overview]
|| change.wildOverview && dataRef[change.wildOverview]
|| change.extOverview && dataRef[change.extOverview];
return !result;
});
return result;
}
// exports = module.exports = changesIsInDataRef;
/**
* @file attaching 的 element 和 component 池
完成 html fill 后执行 attached 操作,进行事件绑定等后续行为
* @author errorrik([email protected])
*/
/**
* attaching 的 element 和 component 集合
*
* @inner
* @type {Array}
*/
var attachingNodes = [];
/**
* attaching 操作对象
*
* @type {Object}
*/
var attachings = {
/**
* 添加 attaching 的 element 或 component
*
* @param {Object|Component} node attaching的node
*/
add: function (node) {
attachingNodes.push(node);
},
/**
* 执行 attaching 完成行为
*/
done: function () {
var nodes = attachingNodes.slice(0);
attachingNodes = [];
for (var i = 0, l = nodes.length; i < l; i++) {
nodes[i]._attached();
}
}
};
// exports = module.exports = attachings;
/**
* @file 元素子节点遍历操作类
* @author errorrik([email protected])
*/
// var removeEl = require('../browser/remove-el');
// #[begin] reverse
// /**
// * 元素子节点遍历操作类
// *
// * @inner
// * @class
// * @param {HTMLElement} el 要遍历的元素
// */
// function DOMChildrenWalker(el) {
// this.raw = [];
// this.index = 0;
// this.target = el;
//
// var child = el.firstChild;
// var next;
// while (child) {
// next = child.nextSibling;
//
// switch (child.nodeType) {
// case 3:
// if (/^\s*$/.test(child.data || child.textContent)) {
// removeEl(child);
// }
// else {
// this.raw.push(child);
// }
// break;
//
// case 1:
// case 8:
// this.raw.push(child);
// }
//
// child = next;
// }
//
// this.current = this.raw[this.index];
// this.next = this.raw[this.index + 1];
// }
//
// /**
// * 往下走一个元素
// */
// DOMChildrenWalker.prototype.goNext = function () {
// this.current = this.raw[++this.index];
// this.next = this.raw[this.index + 1];
// };
// #[end]
// exports = module.exports = DOMChildrenWalker;
/**
* @file 元素节点类
* @author errorrik([email protected])
*/
// var each = require('../util/each');
// var guid = require('../util/guid');
// var removeEl = require('../browser/remove-el');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var changesIsInDataRef = require('../runtime/changes-is-in-data-ref');
// var evalExpr = require('../runtime/eval-expr');
// var attachings = require('./attachings');
// var LifeCycle = require('./life-cycle');
// var NodeType = require('./node-type');
// var reverseElementChildren = require('./reverse-element-children');
// var isDataChangeByElement = require('./is-data-change-by-element');
// var elementUpdateChildren = require('./element-update-children');
// var elementOwnAttachHTML = require('./element-own-attach-html');
// var elementOwnCreate = require('./element-own-create');
// var elementOwnAttach = require('./element-own-attach');
// var elementOwnDetach = require('./element-own-detach');
// var elementOwnDispose = require('./element-own-dispose');
// var elementOwnGetEl = require('./element-own-get-el');
// var elementOwnGetElId = require('./element-own-get-el-id');
// var elementOwnOnEl = require('./element-own-on-el');
// var elementOwnToPhase = require('./element-own-to-phase');
// var elementAttached = require('./element-attached');
// var elementDispose = require('./element-dispose');
// var elementInitTagName = require('./element-init-tag-name');
// var handleProp = require('./handle-prop');
// var warnSetHTML = require('./warn-set-html');
// var getNodePath = require('./get-node-path');
/**
* 元素节点类
*
* @param {Object} aNode 抽象节点
* @param {Component} owner 所属组件环境
* @param {Model=} scope 所属数据环境
* @param {Node} parent 父亲节点
* @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象
*/
function Element(aNode, owner, scope, parent, reverseWalker) {
this.aNode = aNode;
this.owner = owner;
this.scope = scope;
this.parent = parent;
this.lifeCycle = LifeCycle.start;
this.children = [];
this._elFns = [];
this.parentComponent = parent.nodeType === NodeType.CMPT
? parent
: parent.parentComponent;
this.id = guid();
elementInitTagName(this);
this._toPhase('inited');
// #[begin] reverse
// if (reverseWalker) {
// var currentNode = reverseWalker.current;
//
// if (!currentNode) {
// throw new Error('[SAN REVERSE ERROR] Element not found. \nPaths: '
// + getNodePath(this).join(' > '));
// }
//
// if (currentNode.nodeType !== 1) {
// throw new Error('[SAN REVERSE ERROR] Element type not match, expect 1 but '
// + currentNode.nodeType + '.\nPaths: '
// + getNodePath(this).join(' > '));
// }
//
// if (currentNode.tagName.toLowerCase() !== this.tagName) {
// throw new Error('[SAN REVERSE ERROR] Element tagName not match, expect '
// + this.tagName + ' but meat ' + currentNode.tagName.toLowerCase() + '.\nPaths: '
// + getNodePath(this).join(' > '));
// }
//
// this.el = currentNode;
// this.el.id = this._getElId();
// reverseWalker.goNext();
//
// reverseElementChildren(this);
//
// attachings.add(this);
// }
// #[end]
}
Element.prototype.nodeType = NodeType.ELEM;
Element.prototype.attach = elementOwnAttach;
Element.prototype.detach = elementOwnDetach;
Element.prototype.dispose = elementOwnDispose;
Element.prototype._attachHTML = elementOwnAttachHTML;
Element.prototype._create = elementOwnCreate;
Element.prototype._getEl = elementOwnGetEl;
Element.prototype._getElId = elementOwnGetElId;
Element.prototype._toPhase = elementOwnToPhase;
Element.prototype._onEl = elementOwnOnEl;
Element.prototype._doneLeave = function () {
if (this.leaveDispose) {
if (!this.lifeCycle.disposed) {
elementDispose(
this,
this.disposeNoDetach,
this.disposeNoTransition
);
}
}
else if (this.lifeCycle.attached) {
removeEl(this._getEl());
this._toPhase('detached');
}
};
/**
* 视图更新
*
* @param {Array} changes 数据变化信息
*/
Element.prototype._update = function (changes) {
if (!changesIsInDataRef(changes, this.aNode.hotspot.data)) {
return;
}
this._getEl();
var me = this;
var dynamicProps = this.aNode.hotspot.dynamicProps;
for (var i = 0, l = dynamicProps.length; i < l; i++) {
var prop = dynamicProps[i];
for (var j = 0, changeLen = changes.length; j < changeLen; j++) {
var change = changes[j];
if (!isDataChangeByElement(change, this, prop.name)
&& (
changeExprCompare(change.expr, prop.expr, this.scope)
|| prop.hintExpr && changeExprCompare(change.expr, prop.hintExpr, this.scope)
)
) {
handleProp.prop(this, prop.name, evalExpr(prop.expr, this.scope, this.owner));
break;
}
}
}
var htmlDirective = this.aNode.directives.html;
if (htmlDirective) {
each(changes, function (change) {
if (changeExprCompare(change.expr, htmlDirective.value, me.scope)) {
// #[begin] error
warnSetHTML(me.el);
// #[end]
me.el.innerHTML = evalExpr(htmlDirective.value, me.scope, me.owner);
return false;
}
});
}
else {
elementUpdateChildren(this, changes);
}
};
/**
* 执行完成attached状态的行为
*/
Element.prototype._attached = function () {
elementAttached(this);
};
// exports = module.exports = Element;
/**
* @file 生成子元素html
* @author errorrik([email protected])
*/
// var escapeHTML = require('../runtime/escape-html');
// var htmlBufferPush = require('../runtime/html-buffer-push');
// var evalExpr = require('../runtime/eval-expr');
// var getANodeProp = require('./get-a-node-prop');
// var createNode = require('./create-node');
/**
* 生成子元素html
*
* @param {Element} element 元素
* @param {Object} buf html串存储对象
*/
function genElementChildrenHTML(element, buf) {
if (element.tagName === 'textarea') {
var valueProp = getANodeProp(element.aNode, 'value');
if (valueProp) {
htmlBufferPush(buf, escapeHTML(evalExpr(valueProp.expr, element.scope, element.owner)));
}
}
else {
var htmlDirective = element.aNode.directives.html;
if (htmlDirective) {
htmlBufferPush(buf, evalExpr(htmlDirective.value, element.scope, element.owner));
}
else {
var aNodeChildren = element.aNode.children;
for (var i = 0, l = aNodeChildren.length; i < l; i++) {
var child = createNode(aNodeChildren[i], element);
element.children.push(child);
child._attachHTML(buf);
}
}
}
}
// exports = module.exports = genElementChildrenHTML;
/**
* @file 销毁节点,清空节点上的无用成员
* @author errorrik([email protected])
*/
/**
* 销毁节点
*
* @param {Object} node 节点对象
*/
function nodeDispose(node) {
node.el = null;
node.owner = null;
node.scope = null;
node.aNode = null;
node.parent = null;
node.parentComponent = null;
node.children = null;
if (node._toPhase) {
node._toPhase('disposed');
}
if (node._ondisposed) {
node._ondisposed();
}
}
// exports = module.exports = nodeDispose;
/**
* @file 通过组件反解创建节点的工厂方法
* @author errorrik([email protected])
*/
// var hotTags = require('../browser/hot-tags');
// var NodeType = require('./node-type');
// var TextNode = require('./text-node');
// var Element = require('./element');
// var SlotNode = require('./slot-node');
// var ForNode = require('./for-node');
// var IfNode = require('./if-node');
// var TemplateNode = require('./template-node');
// #[begin] reverse
// /**
// * 通过组件反解创建节点
// *
// * @param {ANode} aNode 抽象节点
// * @param {DOMChildrenWalker} reverseWalker 子元素遍历对象
// * @param {Node} parent 父亲节点
// * @param {Model=} scope 所属数据环境
// * @return {Node}
// */
// function createReverseNode(aNode, reverseWalker, parent, scope) {
// var parentIsComponent = parent.nodeType === NodeType.CMPT;
// var owner = parentIsComponent ? parent : (parent.childOwner || parent.owner);
// scope = scope || (parentIsComponent ? parent.data : (parent.childScope || parent.scope));
//
// if (aNode.textExpr) {
// return new TextNode(aNode, owner, scope, parent, reverseWalker);
// }
//
// if (aNode.directives['if']) { // eslint-disable-line dot-notation
// return new IfNode(aNode, owner, scope, parent, reverseWalker);
// }
//
// if (aNode.directives['for']) { // eslint-disable-line dot-notation
// return new ForNode(aNode, owner, scope, parent, reverseWalker);
// }
//
// if (hotTags[aNode.tagName]) {
// return new Element(aNode, owner, scope, parent, reverseWalker);
// }
//
// switch (aNode.tagName) {
// case 'slot':
// return new SlotNode(aNode, owner, scope, parent, reverseWalker);
//
// case 'template':
// return new TemplateNode(aNode, owner, scope, parent, reverseWalker);
//
// default:
// var ComponentType = owner.getComponentType(aNode);
// if (ComponentType) {
// return new ComponentType({
// aNode: aNode,
// owner: owner,
// scope: scope,
// parent: parent,
// subTag: aNode.tagName,
// reverseWalker: reverseWalker
// });
// }
// }
//
// return new Element(aNode, owner, scope, parent, reverseWalker);
// }
// #[end]
// exports = module.exports = createReverseNode;
/**
* @file 销毁释放元素的子元素
* @author errorrik([email protected])
*/
/**
* 销毁释放元素的子元素
*
* @param {Object} element 元素节点
* @param {boolean=} noDetach 是否不要把节点从dom移除
* @param {boolean=} noTransition 是否不显示过渡动画效果
*/
function elementDisposeChildren(element, noDetach, noTransition) {
var children = element.children;
var len = children && children.length;
while (len--) {
children[len].dispose(noDetach, noTransition);
}
}
// exports = module.exports = elementDisposeChildren;
/**
* @file 更新元素的子元素视图
* @author errorrik([email protected])
*/
/**
* 更新元素的子元素视图
*
* @param {Object} element 要更新的元素
* @param {Array} changes 数据变化信息
*/
function elementUpdateChildren(element, changes) {
for (var i = 0, l = element.children.length; i < l; i++) {
element.children[i]._update(changes);
}
}
// exports = module.exports = elementUpdateChildren;
/**
* @file 使元素节点到达相应的生命周期
* @author errorrik([email protected])
*/
// var LifeCycle = require('./life-cycle');
/**
* 使元素节点到达相应的生命周期
*
* @param {string} name 生命周期名称
*/
function elementOwnToPhase(name) {
this.lifeCycle = LifeCycle[name] || this.lifeCycle;
}
// exports = module.exports = elementOwnToPhase;
/**
* @file 执行完成attached状态的行为
* @author errorrik([email protected])
*/
/**
* 执行完成attached状态的行为
*/
function nodeOwnSimpleAttached() {
this._toPhase('attached');
}
// exports = module.exports = nodeOwnSimpleAttached;
/**
* @file 创建节点的工厂方法
* @author errorrik([email protected])
*/
// var hotTags = require('../browser/hot-tags');
// var NodeType = require('./node-type');
// var TextNode = require('./text-node');
// var Element = require('./element');
// var SlotNode = require('./slot-node');
// var ForNode = require('./for-node');
// var IfNode = require('./if-node');
// var TemplateNode = require('./template-node');
/**
* 创建节点
*
* @param {ANode} aNode 抽象节点
* @param {Node} parent 父亲节点
* @param {Model=} scope 所属数据环境
* @return {Node}
*/
function createNode(aNode, parent, scope) {
var parentIsComponent = parent.nodeType === NodeType.CMPT;
var owner = parentIsComponent ? parent : (parent.childOwner || parent.owner);
scope = scope || (parentIsComponent ? parent.data : (parent.childScope || parent.scope));
if (aNode.textExpr) {
return new TextNode(aNode, owner, scope, parent);
}
if (aNode.directives['if']) { // eslint-disable-line dot-notation
return new IfNode(aNode, owner, scope, parent);
}
if (aNode.directives['for']) { // eslint-disable-line dot-notation
return new ForNode(aNode, owner, scope, parent);
}
if (hotTags[aNode.tagName]) {
return new Element(aNode, owner, scope, parent);
}
switch (aNode.tagName) {
case 'slot':
return new SlotNode(aNode, owner, scope, parent);
case 'template':
return new TemplateNode(aNode, owner, scope, parent);
default:
var ComponentType = owner.getComponentType(aNode);
if (ComponentType) {
return new ComponentType({
aNode: aNode,
owner: owner,
scope: scope,
parent: parent,
subTag: aNode.tagName
});
}
}
return new Element(aNode, owner, scope, parent);
}
// exports = module.exports = createNode;
/**
* @file 生成子元素
* @author errorrik([email protected])
*/
// var each = require('../util/each');
// var createNode = require('./create-node');
/**
* 生成子元素
*
* @param {Element} element 元素
* @param {Object} buf html串存储对象
*/
function genElementChildren(element, parentEl, beforeEl) {
parentEl = parentEl || element._getEl();
each(element.aNode.children, function (aNodeChild) {
var child = createNode(aNodeChild, element);
element.children.push(child);
child.attach(parentEl, beforeEl);
});
}
// exports = module.exports = genElementChildren;
/**
* @file 将没有 root 只有 children 的元素 attach 到页面
* @author errorrik([email protected])
*/
// var each = require('../util/each');
// var insertBefore = require('../browser/insert-before');
// var createNode = require('./create-node');
// var genElementChildren = require('./gen-element-children');
// var attachings = require('./attachings');
/**
* 将没有 root 只有 children 的元素 attach 到页面
* 主要用于 slot 和 template
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
function nodeOwnOnlyChildrenAttach(parentEl, beforeEl) {
this.sel = document.createComment(this.id);
insertBefore(this.sel, parentEl, beforeEl);
genElementChildren(this, parentEl, beforeEl);
this.el = document.createComment(this.id);
insertBefore(this.el, parentEl, beforeEl);
attachings.done();
}
// exports = module.exports = nodeOwnOnlyChildrenAttach;
/**
* @file 获取节点对应的 stump 主元素
* @author errorrik([email protected])
*/
// var getNodeStump = require('./get-node-stump');
/**
* 获取节点对应的 stump 主元素
*
* @return {Comment}
*/
function nodeOwnGetStumpEl() {
return getNodeStump(this);
}
// exports = module.exports = nodeOwnGetStumpEl;
/**
* @file slot 节点类
* @author errorrik([email protected])
*/
// var each = require('../util/each');
// var guid = require('../util/guid');
// var createANode = require('../parser/create-a-node');
// var ExprType = require('../parser/expr-type');
// var createAccessor = require('../parser/create-accessor');
// var evalExpr = require('../runtime/eval-expr');
// var Data = require('../runtime/data');
// var DataChangeType = require('../runtime/data-change-type');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var htmlBufferComment = require('../runtime/html-buffer-comment');
// var insertBefore = require('../browser/insert-before');
// var NodeType = require('./node-type');
// var attachings = require('./attachings');
// var LifeCycle = require('./life-cycle');
// var getANodeProp = require('./get-a-node-prop');
// var genElementChildrenHTML = require('./gen-element-children-html');
// var nodeDispose = require('./node-dispose');
// var createReverseNode = require('./create-reverse-node');
// var elementDisposeChildren = require('./element-dispose-children');
// var elementUpdateChildren = require('./element-update-children');
// var elementOwnToPhase = require('./element-own-to-phase');
// var nodeOwnSimpleAttached = require('./node-own-simple-attached');
// var nodeOwnOnlyChildrenAttach = require('./node-own-only-children-attach');
// var nodeOwnGetStumpEl = require('./node-own-get-stump-el');
/**
* slot 节点类
*
* @param {Object} aNode 抽象节点
* @param {Component} owner 所属组件环境
* @param {Model=} scope 所属数据环境
* @param {Node} parent 父亲节点
* @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象
*/
function SlotNode(aNode, owner, scope, parent, reverseWalker) {
var realANode = createANode();
this.aNode = realANode;
this.owner = owner;
this.scope = scope;
this.parent = parent;
this.parentComponent = parent.nodeType === NodeType.CMPT
? parent
: parent.parentComponent;
this.id = guid();
this.lifeCycle = LifeCycle.start;
this.children = [];
// calc slot name
this.nameBind = getANodeProp(aNode, 'name');
if (this.nameBind) {
this.isNamed = true;
this.name = evalExpr(this.nameBind.expr, this.scope, this.owner);
}
// calc aNode children
var givenSlots = owner.givenSlots;
var givenChildren;
if (givenSlots) {
givenChildren = this.isNamed ? givenSlots.named[this.name] : givenSlots.noname;
}
if (givenChildren) {
this.isInserted = true;
}
realANode.children = givenChildren || aNode.children.slice(0);
var me = this;
// calc scoped slot vars
realANode.vars = aNode.vars;
var initData = {};
each(realANode.vars, function (varItem) {
me.isScoped = true;
initData[varItem.name] = evalExpr(varItem.expr, scope, owner);
});
// child owner & child scope
if (this.isInserted) {
this.childOwner = owner.owner;
this.childScope = owner.scope;
}
if (this.isScoped) {
this.childScope = new Data(initData, this.childScope || this.scope);
}
owner.slotChildren.push(this);
// #[begin] reverse
// if (reverseWalker) {
//
// this.sel = document.createComment(this.id);
// insertBefore(this.sel, reverseWalker.target, reverseWalker.current);
//
// each(this.aNode.children, function (aNodeChild) {
// me.children.push(createReverseNode(aNodeChild, reverseWalker, me));
// });
//
// this.el = document.createComment(this.id);
// insertBefore(this.el, reverseWalker.target, reverseWalker.current);
//
// attachings.add(this);
// }
// #[end]
}
SlotNode.prototype.nodeType = NodeType.SLOT;
/**
* 销毁释放 slot
*
* @param {boolean=} noDetach 是否不要把节点从dom移除
* @param {boolean=} noTransition 是否不显示过渡动画效果
*/
SlotNode.prototype.dispose = function (noDetach, noTransition) {
this.childOwner = null;
this.childScope = null;
elementDisposeChildren(this, noDetach, noTransition);
nodeDispose(this);
};
SlotNode.prototype.attach = nodeOwnOnlyChildrenAttach;
SlotNode.prototype._toPhase = elementOwnToPhase;
SlotNode.prototype._getEl = nodeOwnGetStumpEl;
SlotNode.prototype._attached = nodeOwnSimpleAttached;
/**
* attach元素的html
*
* @param {Object} buf html串存储对象
*/
SlotNode.prototype._attachHTML = function (buf) {
htmlBufferComment(buf, this.id);
genElementChildrenHTML(this, buf);
htmlBufferComment(buf, this.id);
attachings.add(this);
};
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
* @param {boolean=} isFromOuter 变化信息是否来源于父组件之外的组件
* @return {boolean}
*/
SlotNode.prototype._update = function (changes, isFromOuter) {
var me = this;
if (this.nameBind && evalExpr(this.nameBind.expr, this.scope, this.owner) !== me.name) {
this.owner._notifyNeedReload();
return false;
}
if (isFromOuter) {
if (this.isInserted) {
elementUpdateChildren(this, changes);
}
}
else {
if (this.isScoped) {
each(this.aNode.vars, function (varItem) {
me.childScope.set(varItem.name, evalExpr(varItem.expr, me.scope, me.owner));
});
var scopedChanges = [];
each(changes, function (change) {
if (!me.isInserted) {
scopedChanges.push(change);
}
each(me.aNode.vars, function (varItem) {
var name = varItem.name;
var relation = changeExprCompare(change.expr, varItem.expr, me.scope);
if (relation < 1) {
return;
}
if (change.type === DataChangeType.SET) {
scopedChanges.push({
type: DataChangeType.SET,
expr: createAccessor([
{type: ExprType.STRING, value: name}
]),
value: me.childScope.get(name),
option: change.option
});
}
else if (relation === 2) {
scopedChanges.push({
expr: createAccessor([
{type: ExprType.STRING, value: name}
]),
type: DataChangeType.SPLICE,
index: change.index,
deleteCount: change.deleteCount,
value: change.value,
insertions: change.insertions,
option: change.option
});
}
});
});
elementUpdateChildren(this, scopedChanges);
}
else if (!this.isInserted) {
elementUpdateChildren(this, changes);
}
}
};
// exports = module.exports = SlotNode;
/**
* @file 复制指令集合对象
* @author errorrik([email protected])
*/
/**
* 复制指令集合对象
*
* @param {Object} source 要复制的指令集合对象
* @param {Object=} excludes 需要排除的key集合
* @return {Object}
*/
function cloneDirectives(source, excludes) {
var result = {};
excludes = excludes || {};
for (var key in source) {
if (!excludes[key]) {
result[key] = source[key];
}
}
return result;
}
// exports = module.exports = cloneDirectives;
/**
* @file 简单执行销毁节点的行为
* @author errorrik([email protected])
*/
// var removeEl = require('../browser/remove-el');
// var nodeDispose = require('./node-dispose');
// var elementDisposeChildren = require('./element-dispose-children');
/**
* 简单执行销毁节点的行为
*
* @param {boolean=} noDetach 是否不要把节点从dom移除
*/
function nodeOwnSimpleDispose(noDetach) {
elementDisposeChildren(this, noDetach, 1);
if (!noDetach) {
removeEl(this._getEl());
}
nodeDispose(this);
}
// exports = module.exports = nodeOwnSimpleDispose;
/**
* @file 创建节点对应的 stump comment 元素
* @author errorrik([email protected])
*/
/**
* 创建节点对应的 stump comment 主元素
*/
function nodeOwnCreateStump() {
this.el = this.el || document.createComment(this.id);
}
// exports = module.exports = nodeOwnCreateStump;
// #[begin] allua
// function isSetHTMLNotAllow(node) {
// node = node.parent;
// while (node) {
// switch (node.nodeType) {
// case NodeType.ELEM:
// case NodeType.CMPT:
// return node.aNode.hotspot.noSetHTML;
// }
//
// node = node.parent;
// }
// }
// #[end]
// exports = module.exports = isSetHTMLNotAllow;
/**
* @file for 指令节点类
* @author errorrik([email protected])
*/
// var extend = require('../util/extend');
// var inherits = require('../util/inherits');
// var each = require('../util/each');
// var guid = require('../util/guid');
// var createANode = require('../parser/create-a-node');
// var ExprType = require('../parser/expr-type');
// var parseExpr = require('../parser/parse-expr');
// var createAccessor = require('../parser/create-accessor');
// var cloneDirectives = require('../parser/clone-directives');
// var Data = require('../runtime/data');
// var DataChangeType = require('../runtime/data-change-type');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var createHTMLBuffer = require('../runtime/create-html-buffer');
// var htmlBufferComment = require('../runtime/html-buffer-comment');
// var outputHTMLBuffer = require('../runtime/output-html-buffer');
// var outputHTMLBufferBefore = require('../runtime/output-html-buffer-before');
// var evalExpr = require('../runtime/eval-expr');
// var changesIsInDataRef = require('../runtime/changes-is-in-data-ref');
// var removeEl = require('../browser/remove-el');
// var insertBefore = require('../browser/insert-before');
// var LifeCycle = require('./life-cycle');
// var attachings = require('./attachings');
// var NodeType = require('./node-type');
// var createNode = require('./create-node');
// var createReverseNode = require('./create-reverse-node');
// var getNodeStumpParent = require('./get-node-stump-parent');
// var nodeOwnSimpleDispose = require('./node-own-simple-dispose');
// var nodeOwnCreateStump = require('./node-own-create-stump');
// var nodeOwnGetStumpEl = require('./node-own-get-stump-el');
// var elementDisposeChildren = require('./element-dispose-children');
// var warnSetHTML = require('./warn-set-html');
// var isSetHTMLNotAllow = require('./is-set-html-not-allow');
// var dataCache = require('../runtime/data-cache');
/**
* 循环项的数据容器类
*
* @inner
* @class
* @param {Object} forElement for元素对象
* @param {*} item 当前项的数据
* @param {number} index 当前项的索引
*/
function ForItemData(forElement, item, index) {
this.id = guid();
this.parent = forElement.scope;
this.raw = {};
this.listeners = [];
this.directive = forElement.aNode.directives['for']; // eslint-disable-line dot-notation
this.raw[this.directive.item.raw] = item;
this.raw[this.directive.index.raw] = index;
}
/**
* 将数据操作的表达式,转换成为对parent数据操作的表达式
* 主要是对item和index进行处理
*
* @param {Object} expr 表达式
* @return {Object}
*/
ForItemData.prototype.exprResolve = function (expr) {
var directive = this.directive;
var me = this;
function resolveItem(expr) {
if (expr.type === ExprType.ACCESSOR
&& expr.paths[0].value === directive.item.paths[0].value
) {
return createAccessor(
directive.value.paths.concat(
{
type: ExprType.NUMBER,
value: me.get(directive.index)
},
expr.paths.slice(1)
)
);
}
return expr;
}
expr = resolveItem(expr);
var resolvedPaths = [];
each(expr.paths, function (item) {
resolvedPaths.push(
item.type === ExprType.ACCESSOR
&& item.paths[0].value === directive.index.paths[0].value
? {
type: ExprType.NUMBER,
value: me.get(directive.index)
}
: resolveItem(item)
);
});
return createAccessor(resolvedPaths);
};
// 代理数据操作方法
inherits(ForItemData, Data);
each(
['set', 'remove', 'unshift', 'shift', 'push', 'pop', 'splice'],
function (method) {
ForItemData.prototype['_' + method] = Data.prototype[method];
ForItemData.prototype[method] = function (expr) {
expr = this.exprResolve(parseExpr(expr));
dataCache.clear();
this.parent[method].apply(
this.parent,
[expr].concat(Array.prototype.slice.call(arguments, 1))
);
};
}
);
/**
* 创建 for 指令元素的子元素
*
* @inner
* @param {ForDirective} forElement for 指令元素对象
* @param {*} item 子元素对应数据
* @param {number} index 子元素对应序号
* @return {Element}
*/
function createForDirectiveChild(forElement, item, index) {
var itemScope = new ForItemData(forElement, item, index);
return createNode(forElement.itemANode, forElement, itemScope);
}
/**
* for 指令节点类
*
* @param {Object} aNode 抽象节点
* @param {Component} owner 所属组件环境
* @param {Model=} scope 所属数据环境
* @param {Node} parent 父亲节点
* @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象
*/
function ForNode(aNode, owner, scope, parent, reverseWalker) {
this.aNode = aNode;
this.owner = owner;
this.scope = scope;
this.parent = parent;
this.parentComponent = parent.nodeType === NodeType.CMPT
? parent
: parent.parentComponent;
this.id = guid();
this.children = [];
this.itemANode = createANode({
children: aNode.children,
props: aNode.props,
events: aNode.events,
tagName: aNode.tagName,
vars: aNode.vars,
hotspot: aNode.hotspot,
directives: cloneDirectives(aNode.directives, {
'for': 1
})
});
this.param = aNode.directives['for']; // eslint-disable-line dot-notation
// #[begin] reverse
// if (reverseWalker) {
// var me = this;
// each(
// evalExpr(this.param.value, this.scope, this.owner),
// function (item, i) {
// var itemScope = new ForItemData(me, item, i);
// var child = createReverseNode(me.itemANode, reverseWalker, me, itemScope);
// me.children.push(child);
// }
// );
//
// this._create();
// insertBefore(this.el, reverseWalker.target, reverseWalker.current);
// }
// #[end]
}
ForNode.prototype.nodeType = NodeType.FOR;
ForNode.prototype._create = nodeOwnCreateStump;
ForNode.prototype._getEl = nodeOwnGetStumpEl;
ForNode.prototype.dispose = nodeOwnSimpleDispose;
/**
* 将元素attach到页面的行为
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
ForNode.prototype.attach = function (parentEl, beforeEl) {
this._create();
insertBefore(this.el, parentEl, beforeEl);
// paint list
var el = this.el || parentEl.firstChild;
var prevEl = el && el.previousSibling;
var buf = createHTMLBuffer();
prev: while (prevEl) {
var nextPrev = prevEl.previousSibling;
switch (prevEl.nodeType) {
case 1:
break prev;
case 3:
if (!/^\s*$/.test(prevEl.textContent)) {
break prev;
}
removeEl(prevEl);
break;
}
prevEl = nextPrev;
}
if (
// #[begin] allua
// isSetHTMLNotAllow(this)
// ||
// #[end]
prevEl && prevEl.nodeType !== 1
) {
var me = this;
each(
evalExpr(this.param.value, this.scope, this.owner),
function (item, i) {
var child = createForDirectiveChild(me, item, i);
me.children.push(child);
child.attach(parentEl, el);
}
);
}
else if (!prevEl) {
this._attachHTML(buf, 1);
outputHTMLBuffer(buf, parentEl, 'afterbegin');
}
else {
this._attachHTML(buf, 1);
outputHTMLBuffer(buf, prevEl, 'afterend');
}
attachings.done();
};
/**
* 将元素从页面上移除的行为
*/
ForNode.prototype.detach = function () {
if (this.lifeCycle.attached) {
elementDisposeChildren(this);
this.children = [];
removeEl(this._getEl());
this.lifeCycle = LifeCycle.detached;
}
};
/**
* attach元素的html
*
* @param {Object} buf html串存储对象
* @param {boolean} onlyChildren 是否只attach列表本身html,不包括stump部分
*/
ForNode.prototype._attachHTML = function (buf, onlyChildren) {
var me = this;
each(
evalExpr(this.param.value, this.scope, this.owner),
function (item, i) {
var child = createForDirectiveChild(me, item, i);
me.children.push(child);
child._attachHTML(buf);
}
);
if (!onlyChildren) {
htmlBufferComment(buf, me.id);
}
};
/* eslint-disable fecs-max-statements */
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
ForNode.prototype._update = function (changes) {
var me = this;
// 控制列表更新策略是否原样更新的变量
var originalUpdate = this.aNode.directives.transition;
var oldChildrenLen = this.children.length;
var childrenChanges = new Array(oldChildrenLen);
function pushToChildrenChanges(change) {
for (var i = 0, l = childrenChanges.length; i < l; i++) {
(childrenChanges[i] = childrenChanges[i] || []).push(change);
}
}
var disposeChildren = [];
this._getEl();
// 判断列表是否父元素下唯一的元素
// 如果是的话,可以做一些更新优化
var parentEl = getNodeStumpParent(this);
var parentFirstChild = parentEl.firstChild;
var parentLastChild = parentEl.lastChild;
var isOnlyParentChild = oldChildrenLen > 0 // 有孩子时
&& parentFirstChild === this.children[0]._getEl()
&& (parentLastChild === this.el || parentLastChild === this.children[oldChildrenLen - 1]._getEl())
|| oldChildrenLen === 0 // 无孩子时
&& parentFirstChild === this.el
&& parentLastChild === this.el;
// 控制列表是否整体更新的变量
var isChildrenRebuild;
var newList = evalExpr(this.param.value, this.scope, this.owner);
var newLen = newList && newList.length || 0;
/* eslint-disable no-redeclare */
for (var cIndex = 0, cLen = changes.length; cIndex < cLen; cIndex++) {
var change = changes[cIndex];
var relation = changeExprCompare(change.expr, this.param.value, this.scope);
if (!relation) {
// 无关时,直接传递给子元素更新,列表本身不需要动
pushToChildrenChanges(change);
}
else if (relation > 2) {
// 变更表达式是list绑定表达式的子项
// 只需要对相应的子项进行更新
var changePaths = change.expr.paths;
var forLen = this.param.value.paths.length;
var changeIndex = +evalExpr(changePaths[forLen], this.scope, this.owner);
if (isNaN(changeIndex)) {
pushToChildrenChanges(change);
}
else {
change = {
type: change.type,
expr: createAccessor(
this.param.item.paths.concat(changePaths.slice(forLen + 1))
),
value: change.value,
index: change.index,
deleteCount: change.deleteCount,
insertions: change.insertions,
option: change.option
};
(childrenChanges[changeIndex] = childrenChanges[changeIndex] || [])
.push(change);
switch (change.type) {
case DataChangeType.SET:
this.children[changeIndex].scope._set(
change.expr,
change.value,
{silent: 1}
);
break;
case DataChangeType.SPLICE:
this.children[changeIndex].scope._splice(
change.expr,
[].concat(change.index, change.deleteCount, change.insertions),
{silent: 1}
);
break;
}
}
}
else if (change.type === DataChangeType.SET) {
// 变更表达式是list绑定表达式本身或母项的重新设值
// 此时需要更新整个列表
// 老的比新的多的部分,标记需要dispose
if (oldChildrenLen > newLen) {
disposeChildren = disposeChildren.concat(this.children.slice(newLen));
childrenChanges = childrenChanges.slice(0, newLen);
this.children = this.children.slice(0, newLen);
}
// 整项变更
for (var i = 0; i < newLen; i++) {
(childrenChanges[i] = childrenChanges[i] || []).push({
type: DataChangeType.SET,
option: change.option,
expr: createAccessor(this.param.item.paths.slice(0)),
value: newList[i]
});
// 对list更上级数据的直接设置
if (relation < 2) {
childrenChanges[i].push(change);
}
if (this.children[i]) {
this.children[i].scope._set(
this.param.item,
newList[i],
{silent: 1}
);
}
else {
this.children[i] = 0;
}
}
isChildrenRebuild = 1;
}
else if (relation === 2 && change.type === DataChangeType.SPLICE && !isChildrenRebuild) {
// 变更表达式是list绑定表达式本身数组的splice操作
// 此时需要删除部分项,创建部分项
var changeStart = change.index;
var deleteCount = change.deleteCount;
var insertionsLen = change.insertions.length;
var newCount = insertionsLen - deleteCount;
if (newCount) {
var indexChange = {
type: DataChangeType.SET,
option: change.option,
expr: this.param.index
};
for (var i = changeStart + deleteCount; i < this.children.length; i++) {
(childrenChanges[i] = childrenChanges[i] || []).push(indexChange);
this.children[i] && this.children[i].scope._set(
indexChange.expr,
i - deleteCount + insertionsLen,
{ silent: 1 }
);
}
}
var deleteLen = deleteCount;
while (deleteLen--) {
if (deleteLen < insertionsLen) {
var i = changeStart + deleteLen;
// update
(childrenChanges[i] = childrenChanges[i] || []).push({
type: DataChangeType.SET,
option: change.option,
expr: createAccessor(this.param.item.paths.slice(0)),
value: newList[i]
});
if (this.children[i]) {
this.children[i].scope._set(
this.param.item,
newList[i],
{ silent: 1 }
);
}
}
}
if (newCount < 0) {
disposeChildren = disposeChildren.concat(this.children.splice(changeStart + insertionsLen, -newCount));
childrenChanges.splice(changeStart + insertionsLen, -newCount);
}
else if (newCount > 0) {
var spliceArgs = [changeStart + deleteCount, 0].concat(new Array(newCount));
this.children.splice.apply(this.children, spliceArgs);
childrenChanges.splice.apply(childrenChanges, spliceArgs);
}
}
}
var newChildrenLen = this.children.length;
// 标记 length 是否发生变化
if (newChildrenLen !== oldChildrenLen) {
var lengthChange = {
type: DataChangeType.SET,
option: {},
expr: createAccessor(
this.param.value.paths.concat({
type: ExprType.STRING,
value: 'length'
})
)
};
if (changesIsInDataRef([lengthChange], this.aNode.hotspot.data)) {
pushToChildrenChanges(lengthChange);
}
}
// 清除应该干掉的 child
this._doCreateAndUpdate = doCreateAndUpdate;
// 这里不用getTransition,getTransition和scope相关,for和forItem的scope是不同的
// 所以getTransition结果本身也是不一致的。不如直接判断指令是否存在,如果存在就不进入暴力清除模式
// var violentClear = isOnlyParentChild && newChildrenLen === 0 && !elementGetTransition(me);
var violentClear = !originalUpdate && isOnlyParentChild && newChildrenLen === 0;
var disposedChildCount = 0;
for (var i = 0; i < disposeChildren.length; i++) {
var disposeChild = disposeChildren[i];
if (disposeChild) {
disposeChild._ondisposed = childDisposed;
disposeChild.dispose(violentClear, violentClear);
}
else {
childDisposed();
}
}
if (violentClear) {
// cloneNode + replaceChild is faster
// parentEl.innerHTML = '';
var replaceNode = parentEl.cloneNode(false);
parentEl.parentNode.replaceChild(replaceNode, parentEl);
this.el = document.createComment(this.id);
replaceNode.appendChild(this.el);
}
if (disposeChildren.length === 0) {
doCreateAndUpdate();
}
function childDisposed() {
disposedChildCount++;
if (disposedChildCount === disposeChildren.length
&& doCreateAndUpdate === me._doCreateAndUpdate
) {
doCreateAndUpdate();
}
}
function doCreateAndUpdate() {
me._doCreateAndUpdate = null;
if (violentClear) {
return;
}
var newChildBuf = createHTMLBuffer();
// 对相应的项进行更新
if (oldChildrenLen === 0 && isOnlyParentChild) {
for (var i = 0; i < newChildrenLen; i++) {
(me.children[i] = createForDirectiveChild(me, newList[i], i))._attachHTML(newChildBuf);
}
outputHTMLBuffer(newChildBuf, parentEl);
me.el = document.createComment(me.id);
parentEl.appendChild(me.el);
}
else {
// 如果不attached则直接创建,如果存在则调用更新函数
// var attachStump = this;
// while (newChildrenLen--) {
// var child = me.children[newChildrenLen];
// if (child.lifeCycle.attached) {
// childrenChanges[newChildrenLen].length && child._update(childrenChanges[newChildrenLen]);
// }
// else {
// child.attach(parentEl, attachStump._getEl() || parentEl.firstChild);
// }
// attachStump = child;
// }
// #[begin] allua
// var setHTMLNotAllow = isSetHTMLNotAllow(me);
// #[end]
for (var i = 0; i < newChildrenLen; i++) {
var child = me.children[i];
if (child) {
childrenChanges[i] && child._update(childrenChanges[i]);
}
else {
me.children[i] = createForDirectiveChild(me, newList[i], i);
newChildBuf = newChildBuf || createHTMLBuffer();
// #[begin] allua
// if (setHTMLNotAllow) {
// var newChildStart = i;
// }
// else {
// #[end]
me.children[i]._attachHTML(newChildBuf);
// #[begin] allua
// }
// #[end]
// flush new children html
var nextChild = me.children[i + 1];
if (i === newChildrenLen - 1 || nextChild) {
var beforeEl = nextChild && nextChild._getEl() && (nextChild.sel || nextChild.el)
|| me.el;
// #[begin] allua
// if (setHTMLNotAllow) {
// for (; newChildStart <= i; newChildStart++) {
// me.children[newChildStart].attach(parentEl, beforeEl);
// }
// }
// else {
// #[end]
outputHTMLBufferBefore(
newChildBuf,
parentEl,
beforeEl
);
// #[begin] allua
// }
// #[end]
newChildBuf = null;
}
}
}
}
attachings.done();
}
};
// exports = module.exports = ForNode;
/**
* @file 清洗条件 aNode
* @author errorrik([email protected])
*/
// var createANode = require('../parser/create-a-node');
// var cloneDirectives = require('../parser/clone-directives');
/**
* 清洗条件 aNode,返回纯净无条件指令的 aNode
*
* @param {ANode} aNode 条件节点对象
* @return {ANode}
*/
function rinseCondANode(aNode) {
var clearANode = createANode({
children: aNode.children,
props: aNode.props,
events: aNode.events,
tagName: aNode.tagName,
vars: aNode.vars,
hotspot: aNode.hotspot,
directives: cloneDirectives(aNode.directives, {
'if': 1,
'else': 1,
'elif': 1
})
});
return clearANode;
}
// exports = module.exports = rinseCondANode;
/**
* @file if 指令节点类
* @author errorrik([email protected])
*/
// var each = require('../util/each');
// var guid = require('../util/guid');
// var htmlBufferComment = require('../runtime/html-buffer-comment');
// var evalExpr = require('../runtime/eval-expr');
// var NodeType = require('./node-type');
// var rinseCondANode = require('./rinse-cond-anode');
// var createNode = require('./create-node');
// var createReverseNode = require('./create-reverse-node');
// var getNodeStumpParent = require('./get-node-stump-parent');
// var elementUpdateChildren = require('./element-update-children');
// var nodeOwnSimpleDispose = require('./node-own-simple-dispose');
// var nodeOwnGetStumpEl = require('./node-own-get-stump-el');
/**
* if 指令节点类
*
* @param {Object} aNode 抽象节点
* @param {Component} owner 所属组件环境
* @param {Model=} scope 所属数据环境
* @param {Node} parent 父亲节点
* @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象
*/
function IfNode(aNode, owner, scope, parent, reverseWalker) {
this.aNode = aNode;
this.owner = owner;
this.scope = scope;
this.parent = parent;
this.parentComponent = parent.nodeType === NodeType.CMPT
? parent
: parent.parentComponent;
this.id = guid();
this.children = [];
this.cond = this.aNode.directives['if'].value; // eslint-disable-line dot-notation
// #[begin] reverse
// if (reverseWalker) {
// if (evalExpr(this.cond, this.scope, this.owner)) {
// this.elseIndex = -1;
// this.children[0] = createReverseNode(
// rinseCondANode(aNode),
// reverseWalker,
// this
// );
// }
// else {
// var me = this;
// each(aNode.elses, function (elseANode, index) {
// var elif = elseANode.directives.elif;
//
// if (!elif || elif && evalExpr(elif.value, me.scope, me.owner)) {
// me.elseIndex = index;
// me.children[0] = createReverseNode(
// rinseCondANode(elseANode),
// reverseWalker,
// me
// );
// return false;
// }
// });
// }
// }
// #[end]
}
IfNode.prototype.nodeType = NodeType.IF;
IfNode.prototype._getEl = nodeOwnGetStumpEl;
IfNode.prototype.dispose = nodeOwnSimpleDispose;
/**
* attach元素的html
*
* @param {Object} buf html串存储对象
*/
IfNode.prototype._attachHTML = function (buf) {
var me = this;
var elseIndex;
var child;
if (evalExpr(this.cond, this.scope, this.owner)) {
child = createNode(rinseCondANode(me.aNode), me);
elseIndex = -1;
}
else {
each(me.aNode.elses, function (elseANode, index) {
var elif = elseANode.directives.elif;
if (!elif || elif && evalExpr(elif.value, me.scope, me.owner)) {
child = createNode(rinseCondANode(elseANode), me);
elseIndex = index;
return false;
}
});
}
if (child) {
me.children[0] = child;
child._attachHTML(buf);
me.elseIndex = elseIndex;
}
htmlBufferComment(buf, this.id);
};
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
IfNode.prototype._update = function (changes) {
var me = this;
var childANode = me.aNode;
var elseIndex;
if (evalExpr(this.cond, this.scope, this.owner)) {
elseIndex = -1;
}
else {
each(me.aNode.elses, function (elseANode, index) {
var elif = elseANode.directives.elif;
if (elif && evalExpr(elif.value, me.scope, me.owner) || !elif) {
elseIndex = index;
childANode = elseANode;
return false;
}
});
}
if (elseIndex === me.elseIndex) {
elementUpdateChildren(me, changes);
}
else {
var child = me.children[0];
me.children = [];
if (child) {
child._ondisposed = newChild;
child.dispose();
}
else {
newChild();
}
me.elseIndex = elseIndex;
}
function newChild() {
if (typeof elseIndex !== 'undefined') {
var child = createNode(rinseCondANode(childANode), me);
var parentEl = getNodeStumpParent(me);
child.attach(parentEl, me._getEl() || parentEl.firstChild);
me.children[0] = child;
}
}
};
// exports = module.exports = IfNode;
/**
* @file template 节点类
* @author errorrik([email protected])
*/
// var each = require('../util/each');
// var guid = require('../util/guid');
// var insertBefore = require('../browser/insert-before');
// var htmlBufferComment = require('../runtime/html-buffer-comment');
// var NodeType = require('./node-type');
// var LifeCycle = require('./life-cycle');
// var genElementChildrenHTML = require('./gen-element-children-html');
// var nodeDispose = require('./node-dispose');
// var createReverseNode = require('./create-reverse-node');
// var elementDisposeChildren = require('./element-dispose-children');
// var elementOwnToPhase = require('./element-own-to-phase');
// var attachings = require('./attachings');
// var elementUpdateChildren = require('./element-update-children');
// var nodeOwnSimpleAttached = require('./node-own-simple-attached');
// var nodeOwnOnlyChildrenAttach = require('./node-own-only-children-attach');
// var nodeOwnGetStumpEl = require('./node-own-get-stump-el');
/**
* template 节点类
*
* @param {Object} aNode 抽象节点
* @param {Component} owner 所属组件环境
* @param {Model=} scope 所属数据环境
* @param {Node} parent 父亲节点
* @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象
*/
function TemplateNode(aNode, owner, scope, parent, reverseWalker) {
this.aNode = aNode;
this.owner = owner;
this.scope = scope;
this.parent = parent;
this.parentComponent = parent.nodeType === NodeType.CMPT
? parent
: parent.parentComponent;
this.id = guid();
this.lifeCycle = LifeCycle.start;
this.children = [];
// #[begin] reverse
// if (reverseWalker) {
// this.sel = document.createComment(this.id);
// insertBefore(this.sel, reverseWalker.target, reverseWalker.current);
//
// var me = this;
// each(this.aNode.children, function (aNodeChild) {
// me.children.push(createReverseNode(aNodeChild, reverseWalker, me));
// });
//
// this.el = document.createComment(this.id);
// insertBefore(this.el, reverseWalker.target, reverseWalker.current);
//
// attachings.add(this);
// }
// #[end]
}
TemplateNode.prototype.nodeType = NodeType.TPL;
TemplateNode.prototype.attach = nodeOwnOnlyChildrenAttach;
/**
* 销毁释放
*
* @param {boolean=} noDetach 是否不要把节点从dom移除
* @param {boolean=} noTransition 是否不显示过渡动画效果
*/
TemplateNode.prototype.dispose = function (noDetach, noTransition) {
elementDisposeChildren(this, noDetach, noTransition);
nodeDispose(this);
};
TemplateNode.prototype._toPhase = elementOwnToPhase;
TemplateNode.prototype._getEl = nodeOwnGetStumpEl;
/**
* attach 元素的 html
*
* @param {Object} buf html串存储对象
*/
TemplateNode.prototype._attachHTML = function (buf) {
htmlBufferComment(buf, this.id);
genElementChildrenHTML(this, buf);
htmlBufferComment(buf, this.id);
attachings.add(this);
};
TemplateNode.prototype._attached = nodeOwnSimpleAttached;
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
TemplateNode.prototype._update = function (changes) {
elementUpdateChildren(this, changes);
};
// exports = module.exports = TemplateNode;
/**
* @file 对元素的子节点进行反解
* @author errorrik([email protected])
*/
// var each = require('../util/each');
// var DOMChildrenWalker = require('./dom-children-walker');
// var createReverseNode = require('./create-reverse-node');
// #[begin] reverse
//
// /**
// * 对元素的子节点进行反解
// *
// * @param {Object} element 元素
// */
// function reverseElementChildren(element) {
// var htmlDirective = element.aNode.directives.html;
//
// if (!htmlDirective) {
// var reverseWalker = new DOMChildrenWalker(element.el);
//
// each(element.aNode.children, function (aNodeChild) {
// element.children.push(createReverseNode(aNodeChild, reverseWalker, element));
// });
// }
// }
// #[end]
// exports = module.exports = reverseElementChildren;
/**
* @file 标记 HTML 字符串连接对象当前为 tag 起始位置
* @author errorrik([email protected])
*/
// var ieOldThan9 = require('../browser/ie-old-than-9');
// var empty = require('../util/empty');
/**
* 标记 HTML 字符串连接对象当前为 tag 起始位置
*
* @param {Object} buf 字符串连接对象
* @param {string} id 起始tag的id
*/
var htmlBufferTagStart =
// #[begin] allua
// ieOldThan9
// ? function (buf, id) {
// buf.tagId = id;
// buf.tagStart = 1;
// }
// :
// #[end]
empty;
// exports = module.exports = htmlBufferTagStart;
/**
* @file 处理元素的属性操作
* @author errorrik([email protected])
*/
// var getPropHandler = require('./get-prop-handler');
/**
* 处理元素属性操作
*/
var handleProp = {
attr: function (element, name, value) {
return getPropHandler(element, name).attr(element, name, value);
},
prop: function (element, name, value) {
getPropHandler(element, name).prop(element, name, value);
}
};
// exports = module.exports = handleProp;
/**
* @file bool属性表
* @author errorrik([email protected])
*/
// var splitStr2Obj = require('../util/split-str-2-obj');
/**
* bool属性表
*
* @type {Object}
*/
var boolAttrs = splitStr2Obj('checked,readonly,selected,multiple,disabled');
// exports = module.exports = boolAttrs;
/**
* @file attach 元素的 HTML
* @author errorrik([email protected])
*/
// var htmlBufferPush = require('../runtime/html-buffer-push');
// var htmlBufferTagStart = require('../runtime/html-buffer-tag-start');
// var escapeHTML = require('../runtime/escape-html');
// var evalExpr = require('../runtime/eval-expr');
// var autoCloseTags = require('../browser/auto-close-tags');
// var getANodeProp = require('./get-a-node-prop');
// var NodeType = require('./node-type');
// var handleProp = require('./handle-prop');
// var genElementChildrenHTML = require('./gen-element-children-html');
// var attachings = require('./attachings');
// var LifeCycle = require('./life-cycle');
// var boolAttrs = require('../browser/bool-attrs');
/**
* attach 元素的 HTML
*
* @param {Object} buf html串存储对象
*/
function elementOwnAttachHTML(buf) {
this.lifeCycle = LifeCycle.painting;
var tagName = this.tagName;
// tag start
if (!tagName) {
return;
}
var elementIsComponent = this.nodeType === NodeType.CMPT;
htmlBufferPush(buf, '<' + tagName + this.aNode.hotspot.staticAttr);
var props = this.aNode.hotspot.dynamicProps;
for (var i = 0, l = props.length; i < l; i++) {
var prop = props[i];
if (!prop.id) {
var value = elementIsComponent
? evalExpr(prop.expr, this.data, this)
: evalExpr(prop.expr, this.scope, this.owner, 1);
if (prop.x && !boolAttrs[prop.name]) {
value = escapeHTML(value);
}
htmlBufferPush(buf, handleProp.attr(this, prop.name, value) || '');
}
}
var id = this._getElId();
htmlBufferPush(buf, ' id="' + id + '"' + '>');
if (!autoCloseTags[tagName]) {
htmlBufferTagStart(buf, id);
}
// gen children
genElementChildrenHTML(this, buf);
// tag close
if (!autoCloseTags[tagName]) {
htmlBufferPush(buf, '</' + tagName + '>');
}
attachings.add(this);
}
// exports = module.exports = elementOwnAttachHTML;
/**
* @file 创建节点对应的 HTMLElement 主元素
* @author errorrik([email protected])
*/
// var each = require('../util/each');
// var evalExpr = require('../runtime/eval-expr');
// var createEl = require('../browser/create-el');
// var handleProp = require('./handle-prop');
// var LifeCycle = require('./life-cycle');
// var NodeType = require('./node-type');
/**
* 创建节点对应的 HTMLElement 主元素
*/
function elementOwnCreate() {
if (!this.lifeCycle.created) {
this.lifeCycle = LifeCycle.painting;
this.el = createEl(this.tagName);
var isComponent = this.nodeType === NodeType.CMPT;
var me = this;
each(this.aNode.props, function (prop) {
var value = isComponent
? evalExpr(prop.expr, me.data, me)
: evalExpr(prop.expr, me.scope, me.owner);
handleProp.prop(me, prop.name, value);
if (prop.name === 'id') {
return;
}
});
this.el.id = this._getElId();
this._toPhase('created');
}
}
// exports = module.exports = elementOwnCreate;
/**
* @file 将元素attach到页面
* @author errorrik([email protected])
*/
// var createHTMLBuffer = require('../runtime/create-html-buffer');
// var outputHTMLBuffer = require('../runtime/output-html-buffer');
// var insertBefore = require('../browser/insert-before');
// var genElementChildrenHTML = require('./gen-element-children-html');
// var genElementChildren = require('./gen-element-children');
/**
* 将元素attach到页面
*
* @param {Object} element 元素节点
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
function elementAttach(element, parentEl, beforeEl) {
element._create();
insertBefore(element.el, parentEl, beforeEl);
if (!element._contentReady) {
// #[begin] allua
// if (element.aNode.hotspot.noSetHTML) {
// genElementChildren(element);
// }
// else {
// #[end]
var buf = createHTMLBuffer();
genElementChildrenHTML(element, buf);
outputHTMLBuffer(buf, element.el);
// #[begin] allua
// }
// #[end]
element._contentReady = 1;
}
}
// exports = module.exports = elementAttach;
/**
* @file 将元素attach到页面
* @author errorrik([email protected])
*/
// var elementAttach = require('./element-attach');
// var attachings = require('./attachings');
/**
* 将元素attach到页面
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
function elementOwnAttach(parentEl, beforeEl) {
if (!this.lifeCycle.attached) {
elementAttach(this, parentEl, beforeEl);
attachings.add(this);
attachings.done();
this._toPhase('attached');
}
}
// exports = module.exports = elementOwnAttach;
/**
* @file 获取 element 的 transition 控制对象
* @author errorrik([email protected])
*/
// var evalArgs = require('../runtime/eval-args');
// var findMethod = require('../runtime/find-method');
// var NodeType = require('./node-type');
/**
* 获取 element 的 transition 控制对象
*
* @param {Object} element 元素
* @return {Object?}
*/
function elementGetTransition(element) {
var aNode = element.nodeType === NodeType.CMPT ? element.givenANode : element.aNode;
var directive = aNode && aNode.directives.transition;
var owner = element.owner;
var transition;
if (directive && owner) {
transition = findMethod(owner, directive.value.name);
if (typeof transition === 'function') {
transition = transition.apply(
owner,
evalArgs(directive.value.args, element.scope, owner)
);
}
}
return transition || element.transition;
}
// exports = module.exports = elementGetTransition;
/**
* @file 元素节点执行leave行为
* @author errorrik([email protected])
*/
// var elementGetTransition = require('./element-get-transition');
/**
* 元素节点执行leave行为
*
* @param {Object} element 元素
*/
function elementLeave(element) {
var lifeCycle = element.lifeCycle;
if (lifeCycle.leaving || !lifeCycle.attached) {
return;
}
if (element.disposeNoTransition) {
element._doneLeave();
}
else {
var transition = elementGetTransition(element);
if (transition && transition.leave) {
element._toPhase('leaving');
transition.leave(element._getEl(), function () {
element._doneLeave();
});
}
else {
element._doneLeave();
}
}
}
// exports = module.exports = elementLeave;
/**
* @file 将元素从页面上移除
* @author errorrik([email protected])
*/
// var elementLeave = require('./element-leave');
/**
* 将元素从页面上移除
*/
function elementOwnDetach() {
elementLeave(this);
}
// exports = module.exports = elementOwnDetach;
/**
* @file 销毁释放元素
* @author errorrik([email protected])
*/
// var elementLeave = require('./element-leave');
/**
* 销毁释放元素
*
* @param {boolean=} noDetach 是否不要把节点从dom移除
* @param {boolean=} noTransition 是否不显示过渡动画效果
*/
function elementOwnDispose(noDetach, noTransition) {
this.leaveDispose = 1;
this.disposeNoDetach = noDetach;
this.disposeNoTransition = noTransition;
elementLeave(this);
}
// exports = module.exports = elementOwnDispose;
/**
* @file 获取节点对应的主元素
* @author errorrik([email protected])
*/
/**
* 获取节点对应的主元素
*
* @return {HTMLElement}
*/
function elementOwnGetEl() {
if (!this.el) {
this.el = document.getElementById(this._elId);
}
return this.el;
}
// exports = module.exports = elementOwnGetEl;
/**
* @file 获取节点对应的主元素id
* @author errorrik([email protected])
*/
/**
* 获取节点对应的主元素id
*
* @return {string}
*/
function elementOwnGetElId() {
var id;
if (this.aNode.hotspot.idProp) {
id = this.nodeType === NodeType.CMPT
? evalExpr(this.aNode.hotspot.idProp.expr, this.data, this)
: evalExpr(this.aNode.hotspot.idProp.expr, this.scope, this.owner, 1);
}
return (this._elId = id || this.id);
}
// exports = module.exports = elementOwnGetElId;
/**
* @file 为元素的 el 绑定事件
* @author errorrik([email protected])
*/
// var on = require('../browser/on');
/**
* 为元素的 el 绑定事件
*
* @param {string} name 事件名
* @param {Function} listener 监听器
* @param {boolean} capture 是否是捕获阶段触发
*/
function elementOwnOnEl(name, listener, capture) {
if (typeof listener === 'function') {
capture = !!capture;
this._elFns.push([name, listener, capture]);
on(this._getEl(), name, listener, capture);
}
}
// exports = module.exports = elementOwnOnEl;
/**
* @file 事件绑定不存在的 warning
* @author varsha([email protected])
*/
// var each = require('../util/each');
// #[begin] error
/**
* 事件绑定不存在的 warning
*
* @param {Object} eventBind 事件绑定对象
* @param {Component} owner 所属的组件对象
*/
function warnEventListenMethod(eventBind, owner) {
var valid = true;
var method = owner;
each(eventBind.expr.name.paths, function (path) {
if (!path.value) {
return false;
}
method = method[path.value];
valid = !!method;
return valid;
});
if (!valid) {
var paths = [];
each(eventBind.expr.name.paths, function (path) {
paths.push(path.value);
});
var message = '[SAN WARNING] ' + eventBind.name + ' listen fail,"' + paths.join('.') + '" not exist';
/* eslint-disable no-console */
if (typeof console === 'object' && console.warn) {
console.warn(message);
}
else {
throw new Error(message);
}
/* eslint-enable no-console */
}
}
// #[end]
// exports = module.exports = warnEventListenMethod;
/**
* @file 完成元素 attached 后的行为
* @author errorrik([email protected])
*/
// var bind = require('../util/bind');
// var empty = require('../util/empty');
// var isBrowser = require('../browser/is-browser');
// var trigger = require('../browser/trigger');
// var NodeType = require('./node-type');
// var elementGetTransition = require('./element-get-transition');
// var eventDeclarationListener = require('./event-declaration-listener');
// var getPropHandler = require('./get-prop-handler');
// var warnEventListenMethod = require('./warn-event-listen-method');
/**
* 双绑输入框CompositionEnd事件监听函数
*
* @inner
*/
function inputOnCompositionEnd() {
if (!this.composing) {
return;
}
this.composing = 0;
trigger(this, 'input');
}
/**
* 双绑输入框CompositionStart事件监听函数
*
* @inner
*/
function inputOnCompositionStart() {
this.composing = 1;
}
function xPropOutputer(xProp, data) {
getPropHandler(this, xProp.name).output(this, xProp, data);
}
function inputXPropOutputer(element, xProp, data) {
var outputer = bind(xPropOutputer, element, xProp, data);
return function (e) {
if (!this.composing) {
outputer(e);
}
};
}
/**
* 完成元素 attached 后的行为
*
* @param {Object} element 元素节点
*/
function elementAttached(element) {
element._toPhase('created');
var elementIsComponent = element.nodeType === NodeType.CMPT;
var data = elementIsComponent ? element.data : element.scope;
/* eslint-disable no-redeclare */
// 处理自身变化时双向绑定的逻辑
var xProps = element.aNode.hotspot.xProps;
for (var i = 0, l = xProps.length; i < l; i++) {
var el = element._getEl();
var xProp = xProps[i];
switch (xProp.name) {
case 'value':
switch (element.tagName) {
case 'input':
case 'textarea':
if (isBrowser && window.CompositionEvent) {
element._onEl('change', inputOnCompositionEnd);
element._onEl('compositionstart', inputOnCompositionStart);
element._onEl('compositionend', inputOnCompositionEnd);
}
element._onEl(
('oninput' in el) ? 'input' : 'propertychange',
inputXPropOutputer(element, xProp, data)
);
break;
case 'select':
element._onEl('change', bind(xPropOutputer, element, xProp, data));
break;
}
break;
case 'checked':
switch (element.tagName) {
case 'input':
switch (el.type) {
case 'checkbox':
case 'radio':
element._onEl('click', bind(xPropOutputer, element, xProp, data));
}
}
break;
}
}
// bind events
var events = elementIsComponent
? element.aNode.events.concat(element.nativeEvents)
: element.aNode.events;
for (var i = 0, l = events.length; i < l; i++) {
var eventBind = events[i];
var owner = elementIsComponent ? element : element.owner;
// 判断是否是nativeEvent,下面的warn方法和事件绑定都需要
// 依此指定eventBind.expr.name位于owner还是owner.owner上
if (eventBind.modifier.native) {
owner = owner.owner;
data = element.scope || owner.data;
}
// #[begin] error
warnEventListenMethod(eventBind, owner);
// #[end]
element._onEl(
eventBind.name,
bind(
eventDeclarationListener,
owner,
eventBind,
0,
data
),
eventBind.modifier.capture
);
}
element._toPhase('attached');
if (element._isInitFromEl) {
element._isInitFromEl = false;
}
else {
var transition = elementGetTransition(element);
if (transition && transition.enter) {
transition.enter(element._getEl(), empty);
}
}
}
// exports = module.exports = elementAttached;
/**
* @file 销毁元素节点
* @author errorrik([email protected])
*/
// var un = require('../browser/un');
// var removeEl = require('../browser/remove-el');
// var elementDisposeChildren = require('./element-dispose-children');
// var nodeDispose = require('./node-dispose');
/**
* 销毁元素节点
*
* @param {Object} element 要销毁的元素节点
* @param {Object=} options 销毁行为的参数
*/
function elementDispose(element) {
elementDisposeChildren(element, 1, 1);
// el 事件解绑
var len = element._elFns.length;
while (len--) {
var fn = element._elFns[len];
un(element._getEl(), fn[0], fn[1], fn[2]);
}
element._elFns = null;
// 如果没有parent,说明是一个root component,一定要从dom树中remove
if (!element.disposeNoDetach || !element.parent) {
removeEl(element._getEl());
}
if (element._toPhase) {
element._toPhase('detached');
}
nodeDispose(element);
}
// exports = module.exports = elementDispose;
/**
* @file 初始化 element 节点的 tagName 处理
* @author errorrik([email protected])
*/
// var ieOldThan9 = require('../browser/ie-old-than-9');
/**
* 初始化 element 节点的 tagName 处理
*
* @param {Object} node 节点对象
*/
function elementInitTagName(node) {
node.tagName = node.tagName || node.aNode.tagName || 'div';
// #[begin] allua
// // ie8- 不支持innerHTML输出自定义标签
// if (ieOldThan9 && node.tagName.indexOf('-') > 0) {
// node.tagName = 'div';
// }
// #[end]
}
// exports = module.exports = elementInitTagName;
/**
* @file 给 devtool 发通知消息
* @author errorrik([email protected])
*/
// var isBrowser = require('../browser/is-browser');
// #[begin] devtool
var san4devtool;
/**
* 给 devtool 发通知消息
*
* @param {string} name 消息名称
* @param {*} arg 消息参数
*/
function emitDevtool(name, arg) {
if (isBrowser && san4devtool && san4devtool.debug && window.__san_devtool__) {
window.__san_devtool__.emit(name, arg);
}
}
emitDevtool.start = function (main) {
san4devtool = main;
emitDevtool('san', main);
};
// #[end]
// exports = module.exports = emitDevtool;
/**
* @file 组件类
* @author errorrik([email protected])
*/
// var bind = require('../util/bind');
// var each = require('../util/each');
// var guid = require('../util/guid');
// var extend = require('../util/extend');
// var nextTick = require('../util/next-tick');
// var emitDevtool = require('../util/emit-devtool');
// var ExprType = require('../parser/expr-type');
// var parseExpr = require('../parser/parse-expr');
// var createAccessor = require('../parser/create-accessor');
// var postProp = require('../parser/post-prop');
// var removeEl = require('../browser/remove-el');
// var Data = require('../runtime/data');
// var evalExpr = require('../runtime/eval-expr');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var compileComponent = require('./compile-component');
// var componentPreheat = require('./component-preheat');
// var LifeCycle = require('./life-cycle');
// var attachings = require('./attachings');
// var getANodeProp = require('./get-a-node-prop');
// var isDataChangeByElement = require('./is-data-change-by-element');
// var eventDeclarationListener = require('./event-declaration-listener');
// var reverseElementChildren = require('./reverse-element-children');
// var camelComponentBinds = require('./camel-component-binds');
// var NodeType = require('./node-type');
// var elementInitTagName = require('./element-init-tag-name');
// var elementAttached = require('./element-attached');
// var elementDispose = require('./element-dispose');
// var elementUpdateChildren = require('./element-update-children');
// var elementOwnGetEl = require('./element-own-get-el');
// var elementOwnGetElId = require('./element-own-get-el-id');
// var elementOwnOnEl = require('./element-own-on-el');
// var elementOwnCreate = require('./element-own-create');
// var elementOwnAttach = require('./element-own-attach');
// var elementOwnDetach = require('./element-own-detach');
// var elementOwnDispose = require('./element-own-dispose');
// var elementOwnAttachHTML = require('./element-own-attach-html');
// var warnEventListenMethod = require('./warn-event-listen-method');
// var elementDisposeChildren = require('./element-dispose-children');
// var elementAttach = require('./element-attach');
// var handleProp = require('./handle-prop');
// var createDataTypesChecker = require('../util/create-data-types-checker');
/**
* 组件类
*
* @class
* @param {Object} options 初始化参数
*/
function Component(options) { // eslint-disable-line
options = options || {};
this.lifeCycle = LifeCycle.start;
this.children = [];
this._elFns = [];
this.listeners = {};
this.slotChildren = [];
var clazz = this.constructor;
this.filters = this.filters || clazz.filters || {};
this.computed = this.computed || clazz.computed || {};
this.messages = this.messages || clazz.messages || {};
this.subTag = options.subTag;
// compile
compileComponent(clazz);
componentPreheat(clazz);
var me = this;
var protoANode = clazz.prototype.aNode;
me.givenANode = options.aNode;
me.givenNamedSlotBinds = [];
me.givenSlots = {
named: {}
};
this.owner = options.owner;
this.scope = options.scope;
this.el = options.el;
var parent = options.parent;
if (parent) {
this.parent = parent;
this.parentComponent = parent.nodeType === NodeType.CMPT
? parent
: parent && parent.parentComponent;
}
this.id = guid();
// #[begin] reverse
// if (this.el) {
// var firstChild = this.el.firstChild;
// if (firstChild && firstChild.nodeType === 8) {
// var stumpMatch = firstChild.data.match(/^\s*s-data:([\s\S]+)?$/);
// if (stumpMatch) {
// var stumpText = stumpMatch[1];
//
// // fill component data
// options.data = (new Function(
// 'return ' + stumpText.replace(/^[\s\n]*/, '')
// ))();
//
// removeEl(firstChild);
// }
// }
// }
// #[end]
// native事件数组
this.nativeEvents = [];
if (this.givenANode) {
// 组件运行时传入的结构,做slot解析
this._createGivenSlots();
each(this.givenANode.events, function (eventBind) {
// 保存当前实例的native事件,下面创建aNode时候做合并
if (eventBind.modifier.native) {
me.nativeEvents.push(eventBind);
return;
}
// #[begin] error
warnEventListenMethod(eventBind, options.owner);
// #[end]
me.on(
eventBind.name,
bind(eventDeclarationListener, options.owner, eventBind, 1, options.scope),
eventBind
);
});
this.tagName = protoANode.tagName || me.givenANode.tagName;
this.binds = camelComponentBinds(this.givenANode.props);
}
this._toPhase('compiled');
// init data
this.data = new Data(
extend(
typeof this.initData === 'function' && this.initData() || {},
options.data
)
);
elementInitTagName(this);
each(this.binds, function (bind) {
postProp(bind);
if (me.scope) {
var value = evalExpr(bind.expr, me.scope, me.owner);
if (typeof value !== 'undefined') {
// See: https://github.com/ecomfe/san/issues/191
me.data.set(bind.name, value);
}
}
});
// #[begin] error
// 在初始化 + 数据绑定后,开始数据校验
// NOTE: 只在开发版本中进行属性校验
var dataTypes = this.dataTypes || clazz.dataTypes;
if (dataTypes) {
var dataTypeChecker = createDataTypesChecker(
dataTypes,
this.subTag || this.name || clazz.name
);
this.data.setTypeChecker(dataTypeChecker);
this.data.checkDataTypes();
}
// #[end]
this.computedDeps = {};
/* eslint-disable guard-for-in */
for (var expr in this.computed) {
if (!this.computedDeps[expr]) {
this._calcComputed(expr);
}
}
/* eslint-enable guard-for-in */
if (!this.dataChanger) {
this.dataChanger = bind(this._dataChanger, this);
this.data.listen(this.dataChanger);
}
this._toPhase('inited');
// #[begin] reverse
// if (this.el) {
// attachings.add(this);
// reverseElementChildren(this);
// attachings.done();
// }
//
// var walker = options.reverseWalker;
// if (walker) {
// var currentNode = walker.current;
// if (currentNode && currentNode.nodeType === 1) {
// this.el = currentNode;
// this.el.id = this._getElId();
// walker.goNext();
// }
//
// reverseElementChildren(this);
//
// attachings.add(me);
// }
// #[end]
}
Component.prototype.getComponentType = function (aNode) {
return this.components[aNode.tagName];
};
/**
* 初始化创建组件外部传入的插槽对象
*
* @protected
*/
Component.prototype._createGivenSlots = function () {
var me = this;
me.givenSlots.named = {};
// 组件运行时传入的结构,做slot解析
me.givenANode && me.scope && each(me.givenANode.children, function (child) {
var target;
var slotBind = !child.textExpr && getANodeProp(child, 'slot');
if (slotBind) {
!me.givenSlotInited && me.givenNamedSlotBinds.push(slotBind);
var slotName = evalExpr(slotBind.expr, me.scope, me.owner);
target = me.givenSlots.named[slotName];
if (!target) {
target = me.givenSlots.named[slotName] = [];
}
}
else if (!me.givenSlotInited) {
target = me.givenSlots.noname;
if (!target) {
target = me.givenSlots.noname = [];
}
}
target && target.push(child);
});
me.givenSlotInited = true;
};
/**
* 类型标识
*
* @type {string}
*/
Component.prototype.nodeType = NodeType.CMPT;
/**
* 在下一个更新周期运行函数
*
* @param {Function} fn 要运行的函数
*/
Component.prototype.nextTick = nextTick;
/* eslint-disable operator-linebreak */
/**
* 使节点到达相应的生命周期
*
* @protected
* @param {string} name 生命周期名称
*/
Component.prototype._callHook =
Component.prototype._toPhase = function (name) {
if (!this.lifeCycle[name]) {
this.lifeCycle = LifeCycle[name] || this.lifeCycle;
if (typeof this[name] === 'function') {
this[name]();
}
// 通知devtool
// #[begin] devtool
emitDevtool('comp-' + name, this);
// #[end]
}
};
/* eslint-enable operator-linebreak */
/**
* 添加事件监听器
*
* @param {string} name 事件名
* @param {Function} listener 监听器
* @param {string?} declaration 声明式
*/
Component.prototype.on = function (name, listener, declaration) {
if (typeof listener === 'function') {
if (!this.listeners[name]) {
this.listeners[name] = [];
}
this.listeners[name].push({fn: listener, declaration: declaration});
}
};
/**
* 移除事件监听器
*
* @param {string} name 事件名
* @param {Function=} listener 监听器
*/
Component.prototype.un = function (name, listener) {
var nameListeners = this.listeners[name];
var len = nameListeners && nameListeners.length;
while (len--) {
if (!listener || listener === nameListeners[len].fn) {
nameListeners.splice(len, 1);
}
}
};
/**
* 派发事件
*
* @param {string} name 事件名
* @param {Object} event 事件对象
*/
Component.prototype.fire = function (name, event) {
var me = this;
each(this.listeners[name], function (listener) {
listener.fn.call(me, event);
});
};
/**
* 计算 computed 属性的值
*
* @private
* @param {string} computedExpr computed表达式串
*/
Component.prototype._calcComputed = function (computedExpr) {
var computedDeps = this.computedDeps[computedExpr];
if (!computedDeps) {
computedDeps = this.computedDeps[computedExpr] = {};
}
this.data.set(computedExpr, this.computed[computedExpr].call({
data: {
get: bind(function (expr) {
// #[begin] error
if (!expr) {
throw new Error('[SAN ERROR] call get method in computed need argument');
}
// #[end]
if (!computedDeps[expr]) {
computedDeps[expr] = 1;
if (this.computed[expr]) {
this._calcComputed(expr);
}
this.watch(expr, function () {
this._calcComputed(computedExpr);
});
}
return this.data.get(expr);
}, this)
}
}));
};
/**
* 派发消息
* 组件可以派发消息,消息将沿着组件树向上传递,直到遇上第一个处理消息的组件
*
* @param {string} name 消息名称
* @param {*?} value 消息值
*/
Component.prototype.dispatch = function (name, value) {
var parentComponent = this.parentComponent;
while (parentComponent) {
var receiver = parentComponent.messages[name] || parentComponent.messages['*'];
if (typeof receiver === 'function') {
receiver.call(
parentComponent,
{target: this, value: value, name: name}
);
break;
}
parentComponent = parentComponent.parentComponent;
}
};
/**
* 获取组件内部的 slot
*
* @param {string=} name slot名称,空为default slot
* @return {Array}
*/
Component.prototype.slot = function (name) {
var result = [];
var me = this;
function childrenTraversal(children) {
each(children, function (child) {
if (child.nodeType === NodeType.SLOT && child.owner === me) {
if (child.isNamed && child.name === name
|| !child.isNamed && !name
) {
result.push(child);
}
}
else {
childrenTraversal(child.children);
}
});
}
childrenTraversal(this.children);
return result;
};
/**
* 获取带有 san-ref 指令的子组件引用
*
* @param {string} name 子组件的引用名
* @return {Component}
*/
Component.prototype.ref = function (name) {
var refTarget;
var owner = this;
function childrenTraversal(children) {
each(children, function (child) {
elementTraversal(child);
return !refTarget;
});
}
function elementTraversal(element) {
var nodeType = element.nodeType;
if (nodeType === NodeType.TEXT) {
return;
}
if (element.owner === owner) {
var ref;
switch (element.nodeType) {
case NodeType.ELEM:
ref = element.aNode.directives.ref;
if (ref && evalExpr(ref.value, element.scope, owner) === name) {
refTarget = element._getEl();
}
break;
case NodeType.CMPT:
ref = element.givenANode.directives.ref;
if (ref && evalExpr(ref.value, element.scope, owner) === name) {
refTarget = element;
}
}
!refTarget && childrenTraversal(element.slotChildren);
}
!refTarget && childrenTraversal(element.children);
}
childrenTraversal(this.children);
return refTarget;
};
/**
* 视图更新函数
*
* @param {Array?} changes 数据变化信息
*/
Component.prototype._update = function (changes) {
if (this.lifeCycle.disposed) {
return;
}
var me = this;
var needReloadForSlot = false;
this._notifyNeedReload = function () {
needReloadForSlot = true;
};
if (changes) {
each(changes, function (change) {
var changeExpr = change.expr;
each(me.binds, function (bindItem) {
var relation;
var setExpr = bindItem.name;
var updateExpr = bindItem.expr;
if (!isDataChangeByElement(change, me, setExpr)
&& (relation = changeExprCompare(changeExpr, updateExpr, me.scope))
) {
if (relation > 2) {
setExpr = createAccessor(
[
{
type: ExprType.STRING,
value: setExpr
}
].concat(changeExpr.paths.slice(updateExpr.paths.length))
);
updateExpr = changeExpr;
}
me.data.set(setExpr, evalExpr(updateExpr, me.scope, me.owner), {
target: {
id: me.owner.id
}
});
}
});
each(me.givenNamedSlotBinds, function (bindItem) {
needReloadForSlot = needReloadForSlot || changeExprCompare(changeExpr, bindItem.expr, me.scope);
return !needReloadForSlot;
});
});
if (needReloadForSlot) {
this._createGivenSlots();
this._repaintChildren();
}
else {
var slotChildrenLen = this.slotChildren.length;
while (slotChildrenLen--) {
var slotChild = this.slotChildren[slotChildrenLen];
if (slotChild.lifeCycle.disposed) {
this.slotChildren.splice(slotChildrenLen, 1);
}
else if (slotChild.isInserted) {
slotChild._update(changes, 1);
}
}
}
}
var dataChanges = this.dataChanges;
if (dataChanges) {
this.dataChanges = null;
each(this.aNode.hotspot.dynamicProps, function (prop) {
each(dataChanges, function (change) {
if (changeExprCompare(change.expr, prop.expr, me.data)
|| prop.hintExpr && changeExprCompare(change.expr, prop.hintExpr, me.data)
) {
handleProp.prop(
me,
prop.name,
evalExpr(prop.expr, me.data, me)
);
return false;
}
});
});
elementUpdateChildren(this, dataChanges);
if (needReloadForSlot) {
this._createGivenSlots();
this._repaintChildren();
}
this._toPhase('updated');
if (this.owner) {
this._updateBindxOwner(dataChanges);
this.owner._update();
}
}
this._notifyNeedReload = null;
};
Component.prototype._updateBindxOwner = function (dataChanges) {
var me = this;
if (this.owner) {
each(dataChanges, function (change) {
each(me.binds, function (bindItem) {
var changeExpr = change.expr;
if (bindItem.x
&& !isDataChangeByElement(change, me.owner)
&& changeExprCompare(changeExpr, parseExpr(bindItem.name), me.data)
) {
var updateScopeExpr = bindItem.expr;
if (changeExpr.paths.length > 1) {
updateScopeExpr = createAccessor(
bindItem.expr.paths.concat(changeExpr.paths.slice(1))
);
}
me.scope.set(
updateScopeExpr,
evalExpr(changeExpr, me.data, me),
{
target: {
id: me.id,
prop: bindItem.name
}
}
);
}
});
});
}
};
/**
* 重新绘制组件的内容
* 当 dynamic slot name 发生变更或 slot 匹配发生变化时,重新绘制
* 在组件级别重绘有点粗暴,但是能保证视图结果正确性
*/
Component.prototype._repaintChildren = function () {
elementDisposeChildren(this, 1, 1);
this.children = [];
this._contentReady = 0;
this.slotChildren = [];
elementAttach(this);
attachings.done();
};
/**
* 组件内部监听数据变化的函数
*
* @private
* @param {Object} change 数据变化信息
*/
Component.prototype._dataChanger = function (change) {
if (this.lifeCycle.painting || this.lifeCycle.created) {
if (!this.dataChanges) {
nextTick(this._update, this);
this.dataChanges = [];
}
this.dataChanges.push(change);
}
else if (this.lifeCycle.inited && this.owner) {
this._updateBindxOwner([change]);
}
};
/**
* 监听组件的数据变化
*
* @param {string} dataName 变化的数据项
* @param {Function} listener 监听函数
*/
Component.prototype.watch = function (dataName, listener) {
var dataExpr = parseExpr(dataName);
this.data.listen(bind(function (change) {
if (changeExprCompare(change.expr, dataExpr, this.data)) {
listener.call(this, evalExpr(dataExpr, this.data, this), change);
}
}, this));
};
/**
* 组件销毁的行为
*
* @param {Object} options 销毁行为的参数
*/
Component.prototype.dispose = elementOwnDispose;
Component.prototype._doneLeave = function () {
if (this.leaveDispose) {
if (!this.lifeCycle.disposed) {
// 这里不用挨个调用 dispose 了,因为 children 释放链会调用的
this.slotChildren = null;
this.data.unlisten();
this.dataChanger = null;
this.dataChanges = null;
elementDispose(
this,
this.disposeNoDetach,
this.disposeNoTransition
);
this.listeners = null;
this.givenANode = null;
this.givenSlots = null;
this.givenNamedSlotBinds = null;
}
}
else if (this.lifeCycle.attached) {
removeEl(this._getEl());
this._toPhase('detached');
}
};
/**
* 完成组件 attached 后的行为
*
* @param {Object} element 元素节点
*/
Component.prototype._attached = function () {
this._getEl();
elementAttached(this);
};
Component.prototype.attach = elementOwnAttach;
Component.prototype.detach = elementOwnDetach;
Component.prototype._attachHTML = elementOwnAttachHTML;
Component.prototype._create = elementOwnCreate;
Component.prototype._getEl = elementOwnGetEl;
Component.prototype._getElId = elementOwnGetElId;
Component.prototype._onEl = elementOwnOnEl;
// exports = module.exports = Component;
/**
* @file 创建组件类
* @author errorrik([email protected])
*/
// var Component = require('./component');
// var inherits = require('../util/inherits');
/**
* 创建组件类
*
* @param {Object} proto 组件类的方法表
* @return {Function}
*/
function defineComponent(proto) {
// 如果传入一个不是 san component 的 constructor,直接返回不是组件构造函数
// 这种场景导致的错误 san 不予考虑
if (typeof proto === 'function') {
return proto;
}
// #[begin] error
if (typeof proto !== 'object') {
throw new Error('[SAN FATAL] param must be a plain object.');
}
// #[end]
function ComponentClass(option) { // eslint-disable-line
Component.call(this, option);
}
ComponentClass.prototype = proto;
inherits(ComponentClass, Component);
return ComponentClass;
}
// exports = module.exports = defineComponent;
/**
* @file 编译组件类
* @author errorrik([email protected])
*/
// var createANode = require('../parser/create-a-node');
// var parseTemplate = require('../parser/parse-template');
// var parseText = require('../parser/parse-text');
// var defineComponent = require('./define-component');
/**
* 编译组件类。预解析template和components
*
* @param {Function} ComponentClass 组件类
*/
function compileComponent(ComponentClass) {
var proto = ComponentClass.prototype;
// pre define components class
if (!proto.hasOwnProperty('_cmptReady')) {
proto.components = ComponentClass.components || proto.components || {};
var components = proto.components;
for (var key in components) { // eslint-disable-line
var componentClass = components[key];
if (typeof componentClass === 'object') {
components[key] = defineComponent(componentClass);
}
else if (componentClass === 'self') {
components[key] = ComponentClass;
}
}
proto._cmptReady = 1;
}
// pre compile template
if (!proto.hasOwnProperty('aNode')) {
proto.aNode = createANode();
var tpl = ComponentClass.template || proto.template;
if (tpl) {
var aNode = parseTemplate(tpl, {
trimWhitespace: proto.trimWhitespace || ComponentClass.trimWhitespace,
delimiters: proto.delimiters || ComponentClass.delimiters
});
var firstChild = aNode.children[0];
// #[begin] error
if (aNode.children.length !== 1 || firstChild.isText) {
throw new Error('[SAN FATAL] template must have a root element.');
}
// #[end]
proto.aNode = firstChild;
if (firstChild.tagName === 'template') {
firstChild.tagName = null;
}
var componentPropExtra = {
'class': {name: 'class', expr: parseText('{{class | _class | _sep(" ")}}')},
'style': {name: 'style', expr: parseText('{{style | _style | _sep(";")}}')},
'id': {name: 'id', expr: parseText('{{id}}')}
};
var len = firstChild.props.length;
while (len--) {
var prop = firstChild.props[len];
var extra = componentPropExtra[prop.name];
if (extra) {
firstChild.props.splice(len, 1);
componentPropExtra[prop.name] = prop;
if (prop.name !== 'id') {
prop.expr.segs.push(extra.expr.segs[0]);
prop.expr.value = null;
}
}
}
firstChild.props.push(
componentPropExtra['class'], // eslint-disable-line dot-notation
componentPropExtra.style,
componentPropExtra.id
);
}
}
}
// exports = module.exports = compileComponent;
/**
* @file 组件预热
* @author errorrik([email protected])
*/
// var ExprType = require('../parser/expr-type');
// var each = require('../util/each');
// var handleProp = require('./handle-prop');
// var getANodeProp = require('./get-a-node-prop');
// var noSetHTML = require('../browser/no-set-html');
// var ie = require('../browser/ie');
/**
* 组件预热,分析组件aNode的数据引用等信息
*
* @param {Function} ComponentClass 组件类
*/
function componentPreheat(ComponentClass) {
var stack = [];
function recordHotspotData(refs, notContentData) {
var len = stack.length;
each(stack, function (aNode, index) {
if (!notContentData || index !== len - 1) {
each(refs, function (ref) {
aNode.hotspot.data[ref] = 1;
});
}
});
}
function analyseANodeHotspot(aNode) {
if (!aNode.hotspot) {
stack.push(aNode);
if (aNode.textExpr) {
aNode.hotspot = {data: {}};
recordHotspotData(analyseExprDataHotspot(aNode.textExpr));
}
else {
aNode.hotspot = {
data: {},
// #[begin] allua
// noSetHTML: ie && noSetHTML(aNode),
// #[end]
dynamicProps: [],
xProps: [],
staticAttr: '',
props: {}
};
// === analyse hotspot data: start
each(aNode.vars, function (varItem) {
recordHotspotData(analyseExprDataHotspot(varItem.expr));
});
each(aNode.props, function (prop) {
recordHotspotData(analyseExprDataHotspot(prop.expr));
});
/* eslint-disable guard-for-in */
for (var key in aNode.directives) {
var directive = aNode.directives[key];
recordHotspotData(analyseExprDataHotspot(directive.value), key !== 'html');
}
/* eslint-enable guard-for-in */
each(aNode.elses, function (child) {
analyseANodeHotspot(child);
});
each(aNode.children, function (child) {
analyseANodeHotspot(child);
});
// === analyse hotspot data: end
// === analyse hotspot props: start
each(aNode.props, function (prop, index) {
aNode.hotspot.props[prop.name] = index;
if (prop.name === 'id') {
prop.id = true;
aNode.hotspot.idProp = prop;
aNode.hotspot.dynamicProps.push(prop);
}
else if (prop.expr.value != null
&& !/^(template|input|textarea|select|option)$/.test(aNode.tagName)
) {
aNode.hotspot.staticAttr += handleProp.attr(aNode, prop.name, prop.expr.value) || '';
}
else {
if (prop.x) {
aNode.hotspot.xProps.push(prop);
}
aNode.hotspot.dynamicProps.push(prop);
}
});
// ie 下,如果 option 没有 value 属性,select.value = xx 操作不会选中 option
// 所以没有设置 value 时,默认把 option 的内容作为 value
if (aNode.tagName === 'option'
&& !getANodeProp(aNode, 'value')
&& aNode.children[0]
) {
var valueProp = {
name: 'value',
expr: aNode.children[0].textExpr
};
aNode.props.push(valueProp);
aNode.hotspot.dynamicProps.push(valueProp);
aNode.hotspot.props.value = aNode.props.length - 1;
}
// === analyse hotspot props: end
}
stack.pop();
}
}
analyseANodeHotspot(ComponentClass.prototype.aNode);
}
/**
* 分析表达式的数据引用
*
* @param {Object} expr 要分析的表达式
* @return {Array}
*/
function analyseExprDataHotspot(expr) {
var refs = [];
function analyseExprs(exprs) {
each(exprs, function (expr) {
refs = refs.concat(analyseExprDataHotspot(expr));
});
}
switch (expr.type) {
case ExprType.ACCESSOR:
var paths = expr.paths;
refs.push(paths[0].value);
if (paths.length > 1) {
refs.push(paths[0].value + '.' + (paths[1].value || '*'));
}
analyseExprs(paths.slice(1));
break;
case ExprType.UNARY:
return analyseExprDataHotspot(expr.expr);
case ExprType.TEXT:
case ExprType.BINARY:
case ExprType.TERTIARY:
analyseExprs(expr.segs);
break;
case ExprType.INTERP:
refs = analyseExprDataHotspot(expr.expr);
each(expr.filters, function (filter) {
analyseExprs(filter.name.paths);
analyseExprs(filter.args);
});
break;
}
return refs;
}
// exports = module.exports = componentPreheat;
/**
* @file 将 binds 的 name 从 kebabcase 转换成 camelcase
* @author errorrik([email protected])
*/
// var kebab2camel = require('../util/kebab2camel');
// var each = require('../util/each');
/**
* 将 binds 的 name 从 kebabcase 转换成 camelcase
*
* @param {Array} binds binds集合
* @return {Array}
*/
function camelComponentBinds(binds) {
var result = [];
each(binds, function (bind) {
result.push({
name: kebab2camel(bind.name),
expr: bind.expr,
x: bind.x,
raw: bind.raw
});
});
return result;
}
// exports = module.exports = camelComponentBinds;
/**
* @file 编译源码的 helper 方法集合
* @author errorrik([email protected])
*/
// var each = require('../util/each');
// var ExprType = require('../parser/expr-type');
// #[begin] ssr
//
// /**
// * 编译源码的 helper 方法集合对象
// */
// var compileExprSource = {
//
// /**
// * 字符串字面化
// *
// * @param {string} source 需要字面化的字符串
// * @return {string} 字符串字面化结果
// */
// stringLiteralize: function (source) {
// return '"'
// + source
// .replace(/\x5C/g, '\\\\')
// .replace(/"/g, '\\"')
// .replace(/\x0A/g, '\\n')
// .replace(/\x09/g, '\\t')
// .replace(/\x0D/g, '\\r')
// // .replace( /\x08/g, '\\b' )
// // .replace( /\x0C/g, '\\f' )
// + '"';
// },
//
// /**
// * 生成数据访问表达式代码
// *
// * @param {Object?} accessorExpr accessor表达式对象
// * @return {string}
// */
// dataAccess: function (accessorExpr) {
// var code = 'componentCtx.data';
// if (accessorExpr) {
// each(accessorExpr.paths, function (path) {
// if (path.type === ExprType.ACCESSOR) {
// code += '[' + compileExprSource.dataAccess(path) + ']';
// return;
// }
//
// switch (typeof path.value) {
// case 'string':
// code += '.' + path.value;
// break;
//
// case 'number':
// code += '[' + path.value + ']';
// break;
// }
// });
// }
//
// return code;
// },
//
// /**
// * 生成插值代码
// *
// * @param {Object} interpExpr 插值表达式对象
// * @return {string}
// */
// interp: function (interpExpr) {
// var code = compileExprSource.expr(interpExpr.expr);
//
//
// each(interpExpr.filters, function (filter) {
// code = 'componentCtx.callFilter("' + filter.name.paths[0].value + '", [' + code;
// each(filter.args, function (arg) {
// code += ', ' + compileExprSource.expr(arg);
// });
// code += '])';
// });
//
// if (!interpExpr.original) {
// return 'escapeHTML(' + code + ')';
// }
//
// return code;
// },
//
// /**
// * 生成文本片段代码
// *
// * @param {Object} textExpr 文本片段表达式对象
// * @return {string}
// */
// text: function (textExpr) {
// if (textExpr.segs.length === 0) {
// return '""';
// }
//
// var code = '';
//
// each(textExpr.segs, function (seg) {
// var segCode = compileExprSource.expr(seg);
// code += code ? ' + ' + segCode : segCode;
// });
//
// return code;
// },
//
// /**
// * 二元表达式操作符映射表
// *
// * @type {Object}
// */
// binaryOp: {
// /* eslint-disable */
// 43: '+',
// 45: '-',
// 42: '*',
// 47: '/',
// 60: '<',
// 62: '>',
// 76: '&&',
// 94: '!=',
// 121: '<=',
// 122: '==',
// 123: '>=',
// 155: '!==',
// 183: '===',
// 248: '||'
// /* eslint-enable */
// },
//
// /**
// * 生成表达式代码
// *
// * @param {Object} expr 表达式对象
// * @return {string}
// */
// expr: function (expr) {
// switch (expr.type) {
// case ExprType.UNARY:
// return '!' + compileExprSource.expr(expr.expr);
//
// case ExprType.BINARY:
// return compileExprSource.expr(expr.segs[0])
// + compileExprSource.binaryOp[expr.operator]
// + compileExprSource.expr(expr.segs[1]);
//
// case ExprType.TERTIARY:
// return compileExprSource.expr(expr.segs[0])
// + '?' + compileExprSource.expr(expr.segs[1])
// + ':' + compileExprSource.expr(expr.segs[2]);
//
// case ExprType.STRING:
// return compileExprSource.stringLiteralize(expr.value);
//
// case ExprType.NUMBER:
// return expr.value;
//
// case ExprType.BOOL:
// return expr.value ? 'true' : 'false';
//
// case ExprType.ACCESSOR:
// return compileExprSource.dataAccess(expr);
//
// case ExprType.INTERP:
// return compileExprSource.interp(expr);
//
// case ExprType.TEXT:
// return compileExprSource.text(expr);
// }
// }
// };
// #[end]
// exports = module.exports = compileExprSource;
/**
* @file 编译源码的中间buffer类
* @author errorrik([email protected])
*/
// var each = require('../util/each');
// var compileExprSource = require('./compile-expr-source');
// #[begin] ssr
// /**
// * 编译源码的中间buffer类
// *
// * @class
// */
// function CompileSourceBuffer() {
// this.segs = [];
// }
//
// /**
// * 添加原始代码,将原封不动输出
// *
// * @param {string} code 原始代码
// */
// CompileSourceBuffer.prototype.addRaw = function (code) {
// this.segs.push({
// type: 'RAW',
// code: code
// });
// };
//
// /**
// * 添加被拼接为html的原始代码
// *
// * @param {string} code 原始代码
// */
// CompileSourceBuffer.prototype.joinRaw = function (code) {
// this.segs.push({
// type: 'JOIN_RAW',
// code: code
// });
// };
//
// /**
// * 添加renderer方法的起始源码
// */
// CompileSourceBuffer.prototype.addRendererStart = function () {
// this.addRaw('function (data, parentCtx, givenSlots) {');
// this.addRaw('var html = "";');
// };
//
// /**
// * 添加renderer方法的结束源码
// */
// CompileSourceBuffer.prototype.addRendererEnd = function () {
// this.addRaw('return html;');
// this.addRaw('}');
// };
//
// /**
// * 添加被拼接为html的静态字符串
// *
// * @param {string} str 被拼接的字符串
// */
// CompileSourceBuffer.prototype.joinString = function (str) {
// this.segs.push({
// str: str,
// type: 'JOIN_STRING'
// });
// };
//
// /**
// * 添加被拼接为html的数据访问
// *
// * @param {Object?} accessor 数据访问表达式对象
// */
// CompileSourceBuffer.prototype.joinDataStringify = function () {
// this.segs.push({
// type: 'JOIN_DATA_STRINGIFY'
// });
// };
//
// /**
// * 添加被拼接为html的表达式
// *
// * @param {Object} expr 表达式对象
// */
// CompileSourceBuffer.prototype.joinExpr = function (expr) {
// this.segs.push({
// expr: expr,
// type: 'JOIN_EXPR'
// });
// };
//
// /**
// * 生成编译后代码
// *
// * @return {string}
// */
// CompileSourceBuffer.prototype.toCode = function () {
// var code = [];
// var temp = '';
//
// function genStrLiteral() {
// if (temp) {
// code.push('html += ' + compileExprSource.stringLiteralize(temp) + ';');
// }
//
// temp = '';
// }
//
// each(this.segs, function (seg) {
// if (seg.type === 'JOIN_STRING') {
// temp += seg.str;
// return;
// }
//
// genStrLiteral();
// switch (seg.type) {
// case 'JOIN_DATA_STRINGIFY':
// code.push('html += stringifier.any(' + compileExprSource.dataAccess() + ');');
// break;
//
// case 'JOIN_EXPR':
// code.push('html += ' + compileExprSource.expr(seg.expr) + ';');
// break;
//
// case 'JOIN_RAW':
// code.push('html += ' + seg.code + ';');
// break;
//
// case 'RAW':
// code.push(seg.code);
// break;
//
// }
// });
//
// genStrLiteral();
//
// return code.join('\n');
// };
//
// #[end]
// exports = module.exports = CompileSourceBuffer;
/**
* @file 将组件编译成 render 方法的 js 源码
* @author errorrik([email protected])
*/
// var each = require('../util/each');
// var guid = require('../util/guid');
// var parseExpr = require('../parser/parse-expr');
// var createANode = require('../parser/create-a-node');
// var cloneDirectives = require('../parser/clone-directives');
// var autoCloseTags = require('../browser/auto-close-tags');
// var CompileSourceBuffer = require('./compile-source-buffer');
// var compileExprSource = require('./compile-expr-source');
// var rinseCondANode = require('./rinse-cond-anode');
// var getANodeProp = require('./get-a-node-prop');
// #[begin] ssr
//
// /**
// * 生成序列化时起始桩的html
// *
// * @param {string} type 桩类型标识
// * @param {string?} content 桩内的内容
// * @return {string}
// */
// function serializeStump(type, content) {
// return '<!--s-' + type + (content ? ':' + content : '') + '-->';
// }
//
// /**
// * 生成序列化时结束桩的html
// *
// * @param {string} type 桩类型标识
// * @return {string}
// */
// function serializeStumpEnd(type) {
// return '<!--/s-' + type + '-->';
// }
//
// /**
// * element 的编译方法集合对象
// *
// * @inner
// */
// var elementSourceCompiler = {
//
// /* eslint-disable max-params */
// /**
// * 编译元素标签头
// *
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {string} tagName 标签名
// * @param {Array} props 属性列表
// * @param {string?} extraProp 额外的属性串
// * @param {boolean?} isClose 是否闭合
// */
// tagStart: function (sourceBuffer, tagName, props, extraProp, isClose) {
// sourceBuffer.joinString('<' + tagName);
// sourceBuffer.joinString(extraProp || '');
//
// // index list
// var propsIndex = {};
// each(props, function (prop) {
// propsIndex[prop.name] = prop;
// });
//
// each(props, function (prop) {
// if (prop.name === 'slot') {
// return;
// }
//
// if (prop.name === 'value') {
// switch (tagName) {
// case 'textarea':
// return;
//
// case 'select':
// sourceBuffer.addRaw('$selectValue = '
// + compileExprSource.expr(prop.expr)
// + ' || "";'
// );
// return;
//
// case 'option':
// sourceBuffer.addRaw('$optionValue = '
// + compileExprSource.expr(prop.expr)
// + ';'
// );
// // value
// sourceBuffer.addRaw('if ($optionValue != null) {');
// sourceBuffer.joinRaw('" value=\\"" + $optionValue + "\\""');
// sourceBuffer.addRaw('}');
//
// // selected
// sourceBuffer.addRaw('if ($optionValue === $selectValue) {');
// sourceBuffer.joinString(' selected');
// sourceBuffer.addRaw('}');
// return;
// }
// }
//
// switch (prop.name) {
// case 'readonly':
// case 'disabled':
// case 'multiple':
// if (prop.raw === '') {
// sourceBuffer.joinString(' ' + prop.name);
// }
// else {
// sourceBuffer.joinRaw('boolAttrFilter("' + prop.name + '", '
// + compileExprSource.expr(prop.expr)
// + ')'
// );
// }
// break;
//
// case 'checked':
// if (tagName === 'input') {
// var valueProp = propsIndex.value;
// var valueCode = compileExprSource.expr(valueProp.expr);
//
// if (valueProp) {
// switch (propsIndex.type.raw) {
// case 'checkbox':
// sourceBuffer.addRaw('if (contains('
// + compileExprSource.expr(prop.expr)
// + ', '
// + valueCode
// + ')) {'
// );
// sourceBuffer.joinString(' checked');
// sourceBuffer.addRaw('}');
// break;
//
// case 'radio':
// sourceBuffer.addRaw('if ('
// + compileExprSource.expr(prop.expr)
// + ' === '
// + valueCode
// + ') {'
// );
// sourceBuffer.joinString(' checked');
// sourceBuffer.addRaw('}');
// break;
// }
// }
// }
// break;
//
// default:
// if (prop.attr) {
// sourceBuffer.joinString(' ' + prop.attr);
// }
// else {
// sourceBuffer.joinRaw('attrFilter("' + prop.name + '", '
// + (prop.x ? 'escapeHTML(' : '')
// + compileExprSource.expr(prop.expr)
// + (prop.x ? ')' : '')
// + ')'
// );
// }
// break;
// }
// });
//
// sourceBuffer.joinString(isClose ? '/>' : '>');
// },
// /* eslint-enable max-params */
//
// /**
// * 编译元素闭合
// *
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {string} tagName 标签名
// */
// tagEnd: function (sourceBuffer, tagName) {
// if (!autoCloseTags[tagName]) {
// sourceBuffer.joinString('</' + tagName + '>');
// }
//
// if (tagName === 'select') {
// sourceBuffer.addRaw('$selectValue = null;');
// }
//
// if (tagName === 'option') {
// sourceBuffer.addRaw('$optionValue = null;');
// }
// },
//
// /**
// * 编译元素内容
// *
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {ANode} aNode 元素的抽象节点信息
// * @param {Component} owner 所属组件实例环境
// */
// inner: function (sourceBuffer, aNode, owner) {
// // inner content
// if (aNode.tagName === 'textarea') {
// var valueProp = getANodeProp(aNode, 'value');
// if (valueProp) {
// sourceBuffer.joinRaw('escapeHTML('
// + compileExprSource.expr(valueProp.expr)
// + ')'
// );
// }
//
// return;
// }
//
// var htmlDirective = aNode.directives.html;
// if (htmlDirective) {
// sourceBuffer.joinExpr(htmlDirective.value);
// }
// else {
// /* eslint-disable no-use-before-define */
// each(aNode.children, function (aNodeChild) {
// sourceBuffer.addRaw(aNodeCompiler.compile(aNodeChild, sourceBuffer, owner));
// });
// /* eslint-enable no-use-before-define */
// }
// }
// };
//
// /**
// * ANode 的编译方法集合对象
// *
// * @inner
// */
// var aNodeCompiler = {
//
// /**
// * 编译节点
// *
// * @param {ANode} aNode 抽象节点
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// * @param {Object} extra 编译所需的一些额外信息
// */
// compile: function (aNode, sourceBuffer, owner, extra) {
// extra = extra || {};
// var compileMethod = 'compileElement';
//
// if (aNode.textExpr) {
// compileMethod = 'compileText';
// }
// else if (aNode.directives['if']) { // eslint-disable-line dot-notation
// compileMethod = 'compileIf';
// }
// else if (aNode.directives['for']) { // eslint-disable-line dot-notation
// compileMethod = 'compileFor';
// }
// else if (aNode.tagName === 'slot') {
// compileMethod = 'compileSlot';
// }
// else if (aNode.tagName === 'template') {
// compileMethod = 'compileTemplate';
// }
// else {
// var ComponentType = owner.getComponentType(aNode);
// if (ComponentType) {
// compileMethod = 'compileComponent';
// extra.ComponentClass = ComponentType;
// }
// }
//
// aNodeCompiler[compileMethod](aNode, sourceBuffer, owner, extra);
// },
//
// /**
// * 编译文本节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// */
// compileText: function (aNode, sourceBuffer) {
// if (aNode.textExpr.original) {
// sourceBuffer.joinString(serializeStump('text'));
// }
//
// var value = aNode.textExpr.value;
// if (value == null) {
// sourceBuffer.joinExpr(aNode.textExpr);
// }
// else {
// sourceBuffer.joinString(value);
// }
//
// if (aNode.textExpr.original) {
// sourceBuffer.joinString(serializeStumpEnd('text'));
// }
// },
//
// /**
// * 编译template节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// */
// compileTemplate: function (aNode, sourceBuffer, owner) {
// elementSourceCompiler.inner(sourceBuffer, aNode, owner);
// },
//
// /**
// * 编译 if 节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// */
// compileIf: function (aNode, sourceBuffer, owner) {
// sourceBuffer.addRaw('(function () {');
//
// sourceBuffer.addRaw('var ifIndex = null;');
//
// // output main if
// var ifDirective = aNode.directives['if']; // eslint-disable-line dot-notation
// sourceBuffer.addRaw('if (' + compileExprSource.expr(ifDirective.value) + ') {');
// sourceBuffer.addRaw(
// aNodeCompiler.compile(
// rinseCondANode(aNode),
// sourceBuffer,
// owner
// )
// );
// sourceBuffer.addRaw('}');
//
// // output elif and else
// each(aNode.elses, function (elseANode, index) {
// var elifDirective = elseANode.directives.elif;
// if (elifDirective) {
// sourceBuffer.addRaw('else if (' + compileExprSource.expr(elifDirective.value) + ') {');
// }
// else {
// sourceBuffer.addRaw('else {');
// }
//
// sourceBuffer.addRaw(
// aNodeCompiler.compile(
// rinseCondANode(elseANode),
// sourceBuffer,
// owner
// )
// );
// sourceBuffer.addRaw('}');
// });
//
// sourceBuffer.addRaw('})();');
// },
//
// /**
// * 编译 for 节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// */
// compileFor: function (aNode, sourceBuffer, owner) {
// var forElementANode = createANode({
// children: aNode.children,
// props: aNode.props,
// events: aNode.events,
// tagName: aNode.tagName,
// directives: cloneDirectives(aNode.directives, {
// 'for': 1
// }),
// hotspot: aNode.hotspot
// });
//
// var forDirective = aNode.directives['for']; // eslint-disable-line dot-notation
// var itemName = forDirective.item.raw;
// var indexName = forDirective.index.raw;
// var listName = compileExprSource.dataAccess(forDirective.value);
//
// if (indexName === '$index') {
// indexName = guid();
// }
//
// sourceBuffer.addRaw('for ('
// + 'var ' + indexName + ' = 0; '
// + indexName + ' < ' + listName + '.length; '
// + indexName + '++) {'
// );
// sourceBuffer.addRaw('componentCtx.data.' + indexName + '=' + indexName + ';');
// sourceBuffer.addRaw('componentCtx.data.' + itemName + '= ' + listName + '[' + indexName + '];');
// sourceBuffer.addRaw(
// aNodeCompiler.compile(
// forElementANode,
// sourceBuffer,
// owner
// )
// );
// sourceBuffer.addRaw('}');
// },
//
// /**
// * 编译 slot 节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// */
// compileSlot: function (aNode, sourceBuffer, owner) {
// sourceBuffer.addRaw('(function () {');
//
// sourceBuffer.addRaw('function $defaultSlotRender(componentCtx) {');
// sourceBuffer.addRaw(' var html = "";');
// each(aNode.children, function (aNodeChild) {
// sourceBuffer.addRaw(aNodeCompiler.compile(aNodeChild, sourceBuffer, owner));
// });
// sourceBuffer.addRaw(' return html;');
// sourceBuffer.addRaw('}');
//
// sourceBuffer.addRaw(' var $givenSlot = [];');
//
// var nameProp = getANodeProp(aNode, 'name');
// if (nameProp) {
// sourceBuffer.addRaw('var $slotName = ' + compileExprSource.expr(nameProp.expr) + ';');
// }
// else {
// sourceBuffer.addRaw('var $slotName = null;');
// }
//
// sourceBuffer.addRaw('var $ctxGivenSlots = componentCtx.givenSlots;');
// sourceBuffer.addRaw('for (var $i = 0; $i < $ctxGivenSlots.length; $i++) {');
// sourceBuffer.addRaw(' if ($ctxGivenSlots[$i][1] == $slotName) {');
// sourceBuffer.addRaw(' $givenSlot.push($ctxGivenSlots[$i][0]);');
// sourceBuffer.addRaw(' }');
// sourceBuffer.addRaw('}');
//
//
// sourceBuffer.addRaw('var $isInserted = $givenSlot.length > 0;');
// sourceBuffer.addRaw('if (!$isInserted) { $givenSlot.push($defaultSlotRender); }');
//
// sourceBuffer.addRaw('var $slotCtx = $isInserted ? componentCtx.owner : componentCtx;');
// if (aNode.vars) {
// sourceBuffer.addRaw('$slotCtx = {data: extend({}, $slotCtx.data), filters: $slotCtx.filters, callFilter: $slotCtx.callFilter};'); // eslint-disable-line
// each(aNode.vars, function (varItem) {
// sourceBuffer.addRaw(
// '$slotCtx.data["' + varItem.name + '"] = '
// + compileExprSource.expr(varItem.expr)
// + ';'
// );
// });
// }
//
// sourceBuffer.addRaw('for (var $renderIndex = 0; $renderIndex < $givenSlot.length; $renderIndex++) {');
// sourceBuffer.addRaw(' html += $givenSlot[$renderIndex]($slotCtx);');
// sourceBuffer.addRaw('}');
//
// sourceBuffer.addRaw('})();');
// },
//
// /**
// * 编译普通节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// * @param {Object} extra 编译所需的一些额外信息
// */
// compileElement: function (aNode, sourceBuffer, owner, extra) {
// extra = extra || {};
// // if (aNode.tagName === 'option'
// // && !getANodeProp(aNode, 'value')
// // && aNode.children[0]
// // ) {
// // aNode.props.push({
// // name: 'value',
// // expr: aNode.children[0].textExpr
// // });
// // }
//
// elementSourceCompiler.tagStart(
// sourceBuffer,
// aNode.tagName,
// aNode.props,
// extra.prop
// );
//
// elementSourceCompiler.inner(sourceBuffer, aNode, owner);
// elementSourceCompiler.tagEnd(sourceBuffer, aNode.tagName);
// },
//
// /**
// * 编译组件节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// * @param {Object} extra 编译所需的一些额外信息
// * @param {Function} extra.ComponentClass 对应组件类
// */
// compileComponent: function (aNode, sourceBuffer, owner, extra) {
// if (aNode) {
// sourceBuffer.addRaw('var $slotName = null;');
// sourceBuffer.addRaw('var $givenSlots = [];');
// each(aNode.children, function (child) {
// var slotBind = !child.textExpr && getANodeProp(child, 'slot');
// if (slotBind) {
// sourceBuffer.addRaw('$slotName = ' + compileExprSource.expr(slotBind.expr) + ';');
// sourceBuffer.addRaw('$givenSlots.push([function (componentCtx) {');
// sourceBuffer.addRaw(' var html = "";');
// sourceBuffer.addRaw(aNodeCompiler.compile(child, sourceBuffer, owner));
// sourceBuffer.addRaw(' return html;');
// sourceBuffer.addRaw('}, $slotName]);');
// }
// else {
// sourceBuffer.addRaw('$givenSlots.push([function (componentCtx) {');
// sourceBuffer.addRaw(' var html = "";');
// sourceBuffer.addRaw(aNodeCompiler.compile(child, sourceBuffer, owner));
// sourceBuffer.addRaw(' return html;');
// sourceBuffer.addRaw('}]);');
// }
// });
// }
//
// var ComponentClass = extra.ComponentClass;
// var component = new ComponentClass({
// aNode: aNode,
// owner: owner,
// subTag: aNode.tagName
// });
//
// var givenData = [];
//
// each(component.binds, function (prop) {
// givenData.push(
// compileExprSource.stringLiteralize(prop.name)
// + ':'
// + compileExprSource.expr(prop.expr)
// );
// });
//
// sourceBuffer.addRaw('html += (');
// sourceBuffer.addRendererStart();
// compileComponentSource(sourceBuffer, component, extra && extra.prop);
// sourceBuffer.addRendererEnd();
// sourceBuffer.addRaw(')({' + givenData.join(',\n') + '}, componentCtx, $givenSlots);');
// sourceBuffer.addRaw('$givenSlots = null;');
// }
// };
// /* eslint-disable guard-for-in */
//
// /**
// * 生成组件 renderer 时 ctx 对象构建的代码
// *
// * @inner
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Object} component 组件实例
// * @param {string?} extraProp 额外的属性串
// */
// function compileComponentSource(sourceBuffer, component, extraProp) {
// sourceBuffer.addRaw(genComponentContextCode(component));
// sourceBuffer.addRaw('componentCtx.owner = parentCtx;');
// sourceBuffer.addRaw('componentCtx.givenSlots = givenSlots;');
//
//
// sourceBuffer.addRaw('data = extend(componentCtx.data, data);');
// sourceBuffer.addRaw('for (var $i = 0; $i < componentCtx.computedNames.length; $i++) {');
// sourceBuffer.addRaw(' var $computedName = componentCtx.computedNames[$i];');
// sourceBuffer.addRaw(' data[$computedName] = componentCtx.computed[$computedName]();');
// sourceBuffer.addRaw('}');
//
// extraProp = extraProp || '';
//
// var eventDeclarations = [];
// for (var key in component.listeners) {
// each(component.listeners[key], function (listener) {
// if (listener.declaration) {
// eventDeclarations.push(listener.declaration);
// }
// });
// }
//
// elementSourceCompiler.tagStart(
// sourceBuffer,
// component.tagName,
// component.aNode.props,
// extraProp
// );
//
// if (!component.owner) {
// sourceBuffer.joinString('<!--s-data:');
// sourceBuffer.joinDataStringify();
// sourceBuffer.joinString('-->');
// }
//
//
//
// elementSourceCompiler.inner(sourceBuffer, component.aNode, component);
// elementSourceCompiler.tagEnd(sourceBuffer, component.tagName);
// }
//
// var stringifier = {
// obj: function (source) {
// var prefixComma;
// var result = '{';
//
// for (var key in source) {
// if (typeof source[key] === 'undefined') {
// continue;
// }
//
// if (prefixComma) {
// result += ',';
// }
// prefixComma = 1;
//
// result += compileExprSource.stringLiteralize(key) + ':' + stringifier.any(source[key]);
// }
//
// return result + '}';
// },
//
// arr: function (source) {
// var prefixComma;
// var result = '[';
//
// each(source, function (value) {
// if (prefixComma) {
// result += ',';
// }
// prefixComma = 1;
//
// result += stringifier.any(value);
// });
//
// return result + ']';
// },
//
// str: function (source) {
// return compileExprSource.stringLiteralize(source);
// },
//
// date: function (source) {
// return 'new Date(' + source.getTime() + ')';
// },
//
// any: function (source) {
// switch (typeof source) {
// case 'string':
// return stringifier.str(source);
//
// case 'number':
// return '' + source;
//
// case 'boolean':
// return source ? 'true' : 'false';
//
// case 'object':
// if (!source) {
// return null;
// }
//
// if (source instanceof Array) {
// return stringifier.arr(source);
// }
//
// if (source instanceof Date) {
// return stringifier.date(source);
// }
//
// return stringifier.obj(source);
// }
//
// throw new Error('Cannot Stringify:' + source);
// }
// };
//
// /**
// * 生成组件 renderer 时 ctx 对象构建的代码
// *
// * @inner
// * @param {Object} component 组件实例
// * @return {string}
// */
// function genComponentContextCode(component) {
// var code = ['var componentCtx = {'];
//
// // given anode
// code.push('givenSlots: [],');
//
// // filters
// code.push('filters: {');
// var filterCode = [];
// for (var key in component.filters) {
// var filter = component.filters[key];
//
// if (typeof filter === 'function') {
// filterCode.push(key + ': ' + filter.toString());
// }
// }
// code.push(filterCode.join(','));
// code.push('},');
//
// code.push(
// 'callFilter: function (name, args) {',
// ' var filter = this.filters[name] || DEFAULT_FILTERS[name];',
// ' if (typeof filter === "function") {',
// ' return filter.apply(this, args);',
// ' }',
// '},'
// );
//
// /* eslint-disable no-redeclare */
// // computed obj
// code.push('computed: {');
// var computedCode = [];
// for (var key in component.computed) {
// var computed = component.computed[key];
//
// if (typeof computed === 'function') {
// computedCode.push(key + ': '
// + computed.toString().replace(
// /this.data.get\(([^\)]+)\)/g,
// function (match, exprLiteral) {
// var exprStr = (new Function('return ' + exprLiteral))();
// var expr = parseExpr(exprStr);
//
// return compileExprSource.expr(expr);
// })
// );
// }
// }
// code.push(computedCode.join(','));
// code.push('},');
//
// // computed names
// code.push('computedNames: [');
// computedCode = [];
// for (var key in component.computed) {
// var computed = component.computed[key];
//
// if (typeof computed === 'function') {
// computedCode.push('"' + key + '"');
// }
// }
// code.push(computedCode.join(','));
// code.push('],');
// /* eslint-enable no-redeclare */
//
// // data
// code.push('data: ' + stringifier.any(component.data.get()) + ',');
//
// // tagName
// code.push('tagName: "' + component.tagName + '"');
// code.push('};');
//
// return code.join('\n');
// }
//
// /* eslint-enable guard-for-in */
//
// /* eslint-disable no-unused-vars */
// /* eslint-disable fecs-camelcase */
//
// /**
// * 组件编译的模板函数
// *
// * @inner
// */
// function componentCompilePreCode() {
// var $version = '3.5.0';
//
// function extend(target, source) {
// if (source) {
// Object.keys(source).forEach(function (key) {
// let value = source[key];
// if (typeof value !== 'undefined') {
// target[key] = value;
// }
// });
// }
//
// return target;
// }
//
// function each(array, iterator) {
// if (array && array.length > 0) {
// for (var i = 0, l = array.length; i < l; i++) {
// if (iterator(array[i], i) === false) {
// break;
// }
// }
// }
// }
//
// function contains(array, value) {
// var result;
// each(array, function (item) {
// result = item === value;
// return !result;
// });
//
// return result;
// }
//
// var HTML_ENTITY = {
// /* jshint ignore:start */
// '&': '&',
// '<': '<',
// '>': '>',
// '"': '"',
// /* eslint-disable quotes */
// "'": '''
// /* eslint-enable quotes */
// /* jshint ignore:end */
// };
//
// function htmlFilterReplacer(c) {
// return HTML_ENTITY[c];
// }
//
// function escapeHTML(source) {
// if (source == null) {
// return '';
// }
//
// return String(source).replace(/[&<>"']/g, htmlFilterReplacer);
// }
//
// var DEFAULT_FILTERS = {
// url: encodeURIComponent,
// _class: function (source) {
// if (source instanceof Array) {
// return source.join(' ');
// }
//
// return source;
// },
// _style: function (source) {
// if (typeof source === 'object') {
// var result = '';
// if (source) {
// Object.keys(source).forEach(function (key) {
// result += key + ':' + source[key] + ';';
// });
// }
//
// return result;
// }
//
// return source || '';
// },
// _sep: function (source, sep) {
// return source ? sep + source : '';
// }
// };
//
// function attrFilter(name, value) {
// if (value) {
// return ' ' + name + '="' + value + '"';
// }
//
// return '';
// }
//
// function boolAttrFilter(name, value) {
// if (value && value !== 'false' && value !== '0') {
// return ' ' + name;
// }
//
// return '';
// }
//
// function stringLiteralize(source) {
// return '"'
// + source
// .replace(/\x5C/g, '\\\\')
// .replace(/"/g, '\\"')
// .replace(/\x0A/g, '\\n')
// .replace(/\x09/g, '\\t')
// .replace(/\x0D/g, '\\r')
// + '"';
// }
//
// var stringifier = {
// obj: function (source) {
// var prefixComma;
// var result = '{';
//
// Object.keys(source).forEach(function (key) {
// if (typeof source[key] === 'undefined') {
// return;
// }
//
// if (prefixComma) {
// result += ',';
// }
// prefixComma = 1;
//
// result += stringLiteralize(key) + ':' + stringifier.any(source[key]);
// });
//
// return result + '}';
// },
//
// arr: function (source) {
// var prefixComma;
// var result = '[';
//
// each(source, function (value) {
// if (prefixComma) {
// result += ',';
// }
// prefixComma = 1;
//
// result += stringifier.any(value);
// });
//
// return result + ']';
// },
//
// str: function (source) {
// return stringLiteralize(source);
// },
//
// date: function (source) {
// return 'new Date(' + source.getTime() + ')';
// },
//
// any: function (source) {
// switch (typeof source) {
// case 'string':
// return stringifier.str(source);
//
// case 'number':
// return '' + source;
//
// case 'boolean':
// return source ? 'true' : 'false';
//
// case 'object':
// if (!source) {
// return null;
// }
//
// if (source instanceof Array) {
// return stringifier.arr(source);
// }
//
// if (source instanceof Date) {
// return stringifier.date(source);
// }
//
// return stringifier.obj(source);
// }
//
// throw new Error('Cannot Stringify:' + source);
// }
// };
// }
// /* eslint-enable no-unused-vars */
// /* eslint-enable fecs-camelcase */
//
// /**
// * 将组件编译成 render 方法的 js 源码
// *
// * @param {Function} ComponentClass 组件类
// * @return {string}
// */
// function compileJSSource(ComponentClass) {
// var sourceBuffer = new CompileSourceBuffer();
//
// sourceBuffer.addRendererStart();
// sourceBuffer.addRaw(
// componentCompilePreCode.toString()
// .split('\n')
// .slice(1)
// .join('\n')
// .replace(/\}\s*$/, '')
// );
//
// // 先初始化个实例,让模板编译成 ANode,并且能获得初始化数据
// var component = new ComponentClass();
//
// compileComponentSource(sourceBuffer, component);
// sourceBuffer.addRendererEnd();
// return sourceBuffer.toCode();
// }
// #[end]
// exports = module.exports = compileJSSource;
/* eslint-disable no-unused-vars */
// var nextTick = require('./util/next-tick');
// var inherits = require('./util/inherits');
// var parseTemplate = require('./parser/parse-template');
// var parseExpr = require('./parser/parse-expr');
// var ExprType = require('./parser/expr-type');
// var LifeCycle = require('./view/life-cycle');
// var NodeType = require('./view/node-type');
// var Component = require('./view/component');
// var compileComponent = require('./view/compile-component');
// var defineComponent = require('./view/define-component');
// var emitDevtool = require('./util/emit-devtool');
// var compileJSSource = require('./view/compile-js-source');
// var DataTypes = require('./util/data-types');
var san = {
/**
* san版本号
*
* @type {string}
*/
version: '3.5.0',
// #[begin] devtool
/**
* 是否开启调试。开启调试时 devtool 会工作
*
* @type {boolean}
*/
debug: true,
// #[end]
// #[begin] ssr
// /**
// * 将组件类编译成 renderer 方法
// *
// * @param {Function} ComponentClass 组件类
// * @return {function(Object):string}
// */
// compileToRenderer: function (ComponentClass) {
// var renderer = ComponentClass.__ssrRenderer;
//
// if (!renderer) {
// var code = compileJSSource(ComponentClass);
// renderer = (new Function('return ' + code))();
// ComponentClass.__ssrRenderer = renderer;
// }
//
// return renderer;
// },
//
// /**
// * 将组件类编译成 renderer 方法的源文件
// *
// * @param {Function} ComponentClass 组件类
// * @return {string}
// */
// compileToSource: compileJSSource,
// #[end]
/**
* 组件基类
*
* @type {Function}
*/
Component: Component,
/**
* 创建组件类
*
* @param {Object} proto 组件类的方法表
* @return {Function}
*/
defineComponent: defineComponent,
/**
* 编译组件类。预解析template和components
*
* @param {Function} ComponentClass 组件类
*/
compileComponent: compileComponent,
/**
* 解析 template
*
* @inner
* @param {string} source template 源码
* @return {ANode}
*/
parseTemplate: parseTemplate,
/**
* 解析表达式
*
* @param {string} source 源码
* @return {Object}
*/
parseExpr: parseExpr,
/**
* 表达式类型枚举
*
* @const
* @type {Object}
*/
ExprType: ExprType,
/**
* 生命周期
*/
LifeCycle: LifeCycle,
/**
* 节点类型
*
* @const
* @type {Object}
*/
NodeType: NodeType,
/**
* 在下一个更新周期运行函数
*
* @param {Function} fn 要运行的函数
*/
nextTick: nextTick,
/**
* 构建类之间的继承关系
*
* @param {Function} subClass 子类函数
* @param {Function} superClass 父类函数
*/
inherits: inherits,
/**
* DataTypes
*
* @type {Object}
*/
DataTypes: DataTypes
};
// export
if (typeof exports === 'object' && typeof module === 'object') {
// For CommonJS
exports = module.exports = san;
}
else if (typeof define === 'function' && define.amd) {
// For AMD
define('san', [], san);
}
else {
// For <script src="..."
root.san = san;
}
// #[begin] devtool
emitDevtool.start(san);
// #[end]
})(this);
|
define([
'dojo/_base/declare',
'dojo/Deferred',
'dojo/data/ItemFileWriteStore',
'dojo/store/DataStore',
'intern!object',
'intern/chai!assert',
'dojo/store/Memory',
'dojo/_base/lang',
'dojo/when',
'dstore/legacy/StoreAdapter',
'../data/testData'
], function (declare, Deferred, ItemFileWriteStore, DataStore, registerSuite, assert, Memory, lang, when, StoreAdapter, testData) {
var Model = function () {};
function getResultsArray(store) {
var results = [];
store.forEach(function (data) {
results.push(data);
});
return results;
}
var store;
registerSuite(lang.mixin({
name: 'legacy dstore adapter - dojo data',
beforeEach: function () {
var dataStore = new DataStore({
store: new ItemFileWriteStore({
data: lang.clone(testData)
}),
idProperty: 'id'
});
store = new StoreAdapter({
objectStore: dataStore,
Model: Model
});
store.Model.prototype.describe = function () {
return this.name + ' is ' + (this.prime ? '' : 'not ') + 'a prime';
};
},
'get': function () {
assert.strictEqual(store.get(1).name, 'one');
assert.strictEqual(store.get(4).name, 'four');
assert.isTrue(store.get(5).prime);
assert.strictEqual(store.getIdentity(store.get(1)), 1);
},
'Model': function () {
assert.strictEqual(store.get(1).describe(), 'one is not a prime');
assert.strictEqual(store.get(3).describe(), 'three is a prime');
var results = getResultsArray(store.filter({even: true}));
assert.strictEqual(results.length, 2, 'The length is 2');
assert.strictEqual(results[1].describe(), 'four is not a prime');
},
'filter': function () {
assert.strictEqual(getResultsArray(store.filter({prime: true})).length, 3);
assert.strictEqual(getResultsArray(store.filter({even: true}))[1].name, 'four');
},
'filter with string': function () {
assert.strictEqual(getResultsArray(store.filter({name: 'two'})).length, 1);
assert.strictEqual(getResultsArray(store.filter({name: 'two'}))[0].name, 'two');
},
'filter with regexp': function () {
assert.strictEqual(getResultsArray(store.filter({name: /^t/})).length, 2);
assert.strictEqual(getResultsArray(store.filter({name: /^t/}))[1].name, 'three');
assert.strictEqual(getResultsArray(store.filter({name: /^o/})).length, 1);
assert.strictEqual(getResultsArray(store.filter({name: /o/})).length, 3);
},
'filter with paging': function () {
when(store.filter({prime: true}).fetchRange({start: 1, end: 2}), function (results) {
assert.strictEqual(results.length, 1);
});
when(store.filter({even: true}).fetchRange({start: 1, end: 2}), function (results) {
assert.strictEqual(results[0].name, 'four');
});
},
'put new': function () {
store.put({
id: 6,
perfect: true
});
assert.isTrue(store.get(6).perfect);
}
// if we have the update DataStore (as of Dojo 1.10), we will use these tests as well
}, DataStore.prototype.add &&
{
'put update': function () {
var four = store.get(4);
four.square = true;
store.put(four);
four = store.get(4);
assert.isTrue(four.square);
},
'add duplicate': function () {
var dfd = this.async();
store.add({
id: 5,
perfect: true
}).then(function () {
dfd.reject('add duplicate should be rejected');
}, dfd.callback(function (error) {
assert.strictEqual(error.message, 'Overwriting existing object not allowed');
}));
},
'add new': function () {
store.add({
id: 7,
prime: true
});
assert.isTrue(store.get(7).prime);
},
'remove': function () {
return store.remove(3).then(function (result) {
assert.isTrue(result);
assert.strictEqual(store.get(3), undefined);
});
},
'remove missing': function () {
return store.remove(30).then(function (result) {
assert.isFalse(result);
// make sure nothing changed
assert.strictEqual(store.get(1).id, 1);
});
},
'filter after changes': function () {
store.add({ id: 7, prime: true });
assert.strictEqual(getResultsArray(store.filter({prime: true})).length, 4);
assert.strictEqual(getResultsArray(store.filter({perfect: true})).length, 0);
store.remove(3);
store.put({ id: 6, perfect: true });
assert.strictEqual(getResultsArray(store.filter({prime: true})).length, 3);
assert.strictEqual(getResultsArray(store.filter({perfect: true})).length, 1);
}
}));
});
|
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
/**
* <p>
* cc.AnimationFrame
* A frame of the animation. It contains information like:
* - sprite frame name
* - # of delay units.
* - offset
* </p>
* @class
* @extends cc.Class
*/
cc.AnimationFrame = cc.Class.extend(/** @lends cc.AnimationFrame# */{
_spriteFrame:null,
_delayPerUnit:0,
_userInfo:null,
ctor:function () {
this._delayPerUnit = 0;
},
clone: function(){
var frame = new cc.AnimationFrame();
frame.initWithSpriteFrame(this._spriteFrame.clone(), this._delayPerUnit, this._userInfo);
return frame;
},
copyWithZone:function (pZone) {
return cc.clone(this);
},
copy:function (pZone) {
var newFrame = new cc.AnimationFrame();
newFrame.initWithSpriteFrame(this._spriteFrame.clone(), this._delayPerUnit, this._userInfo);
return newFrame;
},
/**
* initializes the animation frame with a spriteframe, number of delay units and a notification user info
* @param {cc.SpriteFrame} spriteFrame
* @param {Number} delayUnits
* @param {object} userInfo
*/
initWithSpriteFrame:function (spriteFrame, delayUnits, userInfo) {
this._spriteFrame = spriteFrame;
this._delayPerUnit = delayUnits;
this._userInfo = userInfo;
return true;
},
/**
* cc.SpriteFrameName to be used
* @return {cc.SpriteFrame}
*/
getSpriteFrame:function () {
return this._spriteFrame;
},
/**
* cc.SpriteFrameName to be used
* @param {cc.SpriteFrame} spriteFrame
*/
setSpriteFrame:function (spriteFrame) {
this._spriteFrame = spriteFrame;
},
/**
* how many units of time the frame takes getter
* @return {Number}
*/
getDelayUnits:function () {
return this._delayPerUnit;
},
/**
* how many units of time the frame takes setter
* @param delayUnits
*/
setDelayUnits:function (delayUnits) {
this._delayPerUnit = delayUnits;
},
/**
* <p>A cc.AnimationFrameDisplayedNotification notification will be broadcasted when the frame is displayed with this dictionary as UserInfo.<br/>
* If UserInfo is nil, then no notification will be broadcasted. </p>
* @return {object}
*/
getUserInfo:function () {
return this._userInfo;
},
/**
* @param {object} userInfo
*/
setUserInfo:function (userInfo) {
this._userInfo = userInfo;
}
});
/**
* <p>
* A cc.Animation object is used to perform animations on the cc.Sprite objects.<br/>
* <br/>
* The cc.Animation object contains cc.SpriteFrame objects, and a possible delay between the frames. <br/>
* You can animate a cc.Animation object by using the cc.Animate action. Example: <br/>
* </p>
* @class
* @extends cc.Class
*
* @example
* //create an animation object
* var animation = cc.Animation.create();
*
* //add a sprite frame to this animation
* animation.addFrameWithFile("grossini_dance_01.png");
*
* //create an animate with this animation
* var action = cc.Animate.create(animation);
*
* //run animate
* this._grossini.runAction(action);
*/
cc.Animation = cc.Class.extend(/** @lends cc.Animation# */{
_frames:null,
_loops:0,
_restoreOriginalFrame:false,
_duration:0,
_delayPerUnit:0,
_totalDelayUnits:0,
/**
* Constructor
*/
ctor:function () {
this._frames = [];
},
// attributes
/**
* return array of CCAnimationFrames
* @return {Array}
*/
getFrames:function () {
return this._frames;
},
/**
* array of CCAnimationFrames setter
* @param {Array} frames
*/
setFrames:function (frames) {
this._frames = frames;
},
/**
* adds a frame to a cc.Animation The frame will be added with one "delay unit".
* @param {cc.SpriteFrame} frame
*/
addSpriteFrame:function (frame) {
var animFrame = new cc.AnimationFrame();
animFrame.initWithSpriteFrame(frame, 1, null);
this._frames.push(animFrame);
// update duration
this._totalDelayUnits++;
},
/**
* Adds a frame with an image filename. Internally it will create a cc.SpriteFrame and it will add it. The frame will be added with one "delay unit".
* @param {String} fileName
*/
addSpriteFrameWithFile:function (fileName) {
var texture = cc.TextureCache.getInstance().addImage(fileName);
var rect = cc.RectZero();
rect.size = texture.getContentSize();
var frame = cc.SpriteFrame.createWithTexture(texture, rect);
this.addSpriteFrame(frame);
},
/**
* Adds a frame with a texture and a rect. Internally it will create a cc.SpriteFrame and it will add it. The frame will be added with one "delay unit".
* @param {cc.Texture2D} texture
* @param {cc.Rect} rect
*/
addSpriteFrameWithTexture:function (texture, rect) {
var pFrame = cc.SpriteFrame.createWithTexture(texture, rect);
this.addSpriteFrame(pFrame);
},
/**
* Initializes a cc.Animation with cc.AnimationFrame
* @param {Array} arrayOfAnimationFrames
* @param {Number} delayPerUnit
* @param {Number} loops
*/
initWithAnimationFrames:function (arrayOfAnimationFrames, delayPerUnit, loops) {
cc.ArrayVerifyType(arrayOfAnimationFrames, cc.AnimationFrame);
this._delayPerUnit = delayPerUnit;
this._loops = loops;
this.setFrames([]);
for (var i = 0; i < arrayOfAnimationFrames.length; i++) {
var animFrame = arrayOfAnimationFrames[i];
this._frames.push(animFrame);
this._totalDelayUnits += animFrame.getDelayUnits();
}
return true;
},
clone: function(){
var animation = new cc.Animation();
animation.initWithAnimationFrames(this._copyFrames(), this._delayPerUnit, this._loops);
animation.setRestoreOriginalFrame(this._restoreOriginalFrame);
return animation;
},
/**
* @param {cc.Animation} pZone
*/
copyWithZone:function (pZone) {
var pCopy = new cc.Animation();
pCopy.initWithAnimationFrames(this._copyFrames(), this._delayPerUnit, this._loops);
pCopy.setRestoreOriginalFrame(this._restoreOriginalFrame);
return pCopy;
},
_copyFrames:function(){
var copyFrames = [];
for(var i = 0; i< this._frames.length;i++)
copyFrames.push(this._frames[i].clone());
return copyFrames;
},
copy:function (pZone) {
return this.copyWithZone(null);
},
/**
* return how many times the animation is going to loop. 0 means animation is not animated. 1, animation is executed one time, ...
* @return {Number}
*/
getLoops:function () {
return this._loops;
},
/**
* set how many times the animation is going to loop. 0 means animation is not animated. 1, animation is executed one time, ...
* @param {Number} value
*/
setLoops:function (value) {
this._loops = value;
},
/**
* whether or not it shall restore the original frame when the animation finishes
* @param {Boolean} restOrigFrame
*/
setRestoreOriginalFrame:function (restOrigFrame) {
this._restoreOriginalFrame = restOrigFrame;
},
/**
* return whether or not it shall restore the original frame when the animation finishes
* @return {Boolean}
*/
getRestoreOriginalFrame:function () {
return this._restoreOriginalFrame;
},
/**
* return duration in seconds of the whole animation. It is the result of totalDelayUnits * delayPerUnit
* @return {Number}
*/
getDuration:function () {
return this._totalDelayUnits * this._delayPerUnit;
},
/**
* return Delay in seconds of the "delay unit"
* @return {Number}
*/
getDelayPerUnit:function () {
return this._delayPerUnit;
},
/**
* set Delay in seconds of the "delay unit"
* @param {Number} delayPerUnit
*/
setDelayPerUnit:function (delayPerUnit) {
this._delayPerUnit = delayPerUnit;
},
/**
* return total Delay units of the cc.Animation.
* @return {Number}
*/
getTotalDelayUnits:function () {
return this._totalDelayUnits;
},
/**
* Initializes a cc.Animation with frames and a delay between frames
* @param {Array} frames
* @param {Number} delay
*/
initWithSpriteFrames:function (frames, delay) {
cc.ArrayVerifyType(frames, cc.SpriteFrame);
this._loops = 1;
delay = delay || 0;
this._delayPerUnit = delay;
var tempFrames = [];
this.setFrames(tempFrames);
if (frames) {
for (var i = 0; i < frames.length; i++) {
var frame = frames[i];
var animFrame = new cc.AnimationFrame();
animFrame.initWithSpriteFrame(frame, 1, null);
this._frames.push(animFrame);
this._totalDelayUnits++;
}
}
return true;
},
/**
* Currently JavaScript Bindigns (JSB), in some cases, needs to use retain and release. This is a bug in JSB,
* and the ugly workaround is to use retain/release. So, these 2 methods were added to be compatible with JSB.
* This is a hack, and should be removed once JSB fixes the retain/release bug
*/
retain:function () {
},
release:function () {
}
});
/**
* Creates an animation.
* @param {Array} frames
* @param {Number} delay
* @param {Number} loops
* @return {cc.Animation}
* @example
* //Creates an animation
* var animation1 = cc.Animation.create();
*
* //Create an animation with sprite frames
* var animFrames = [];
* var frame = cache.getSpriteFrame("grossini_dance_01.png");
* animFrames.push(frame);
* var animation2 = cc.Animation.create(animFrames);
*
* //Create an animation with sprite frames and delay
* var animation3 = cc.Animation.create(animFrames, 0.2);
*/
cc.Animation.create = function (frames, delay, loops) {
var len = arguments.length;
var animation = new cc.Animation();
if (len == 0) {
animation.initWithSpriteFrames(null, 0);
} else if (len == 2) {
/** with frames and a delay between frames */
delay = delay || 0;
animation.initWithSpriteFrames(frames, delay);
} else if (len == 3) {
animation.initWithAnimationFrames(frames, delay, loops);
}
return animation;
};
/**
* Creates an animation with an array of cc.AnimationFrame, the delay per units in seconds and and how many times it should be executed.
* @param {Array} arrayOfAnimationFrameNames
* @param {Number} delayPerUnit
* @param {Number} loops
* @return {cc.Animation}
*/
cc.Animation.createWithAnimationFrames = function (arrayOfAnimationFrameNames, delayPerUnit, loops) {
var animation = new cc.Animation();
animation.initWithAnimationFrames(arrayOfAnimationFrameNames, delayPerUnit, loops);
return animation;
};
|
// Copyright 2017 Joyent, Inc.
module.exports = {
read: read,
verify: verify,
sign: sign,
signAsync: signAsync,
write: write,
/* Internal private API */
fromBuffer: fromBuffer,
toBuffer: toBuffer
};
var assert = require('assert-plus');
var SSHBuffer = require('../ssh-buffer');
var crypto = require('crypto');
var algs = require('../algs');
var Key = require('../key');
var PrivateKey = require('../private-key');
var Identity = require('../identity');
var rfc4253 = require('./rfc4253');
var Signature = require('../signature');
var utils = require('../utils');
var Certificate = require('../certificate');
function verify(cert, key) {
/*
* We always give an issuerKey, so if our verify() is being called then
* there was no signature. Return false.
*/
return (false);
}
var TYPES = {
'user': 1,
'host': 2
};
Object.keys(TYPES).forEach(function (k) { TYPES[TYPES[k]] = k; });
var ECDSA_ALGO = /^ecdsa-sha2-([^@-]+)[email protected]$/;
function read(buf, options) {
if (Buffer.isBuffer(buf))
buf = buf.toString('ascii');
var parts = buf.trim().split(/[ \t\n]+/g);
if (parts.length < 2 || parts.length > 3)
throw (new Error('Not a valid SSH certificate line'));
var algo = parts[0];
var data = parts[1];
data = new Buffer(data, 'base64');
return (fromBuffer(data, algo));
}
function fromBuffer(data, algo, partial) {
var sshbuf = new SSHBuffer({ buffer: data });
var innerAlgo = sshbuf.readString();
if (algo !== undefined && innerAlgo !== algo)
throw (new Error('SSH certificate algorithm mismatch'));
if (algo === undefined)
algo = innerAlgo;
var cert = {};
cert.signatures = {};
cert.signatures.openssh = {};
cert.signatures.openssh.nonce = sshbuf.readBuffer();
var key = {};
var parts = (key.parts = []);
key.type = getAlg(algo);
var partCount = algs.info[key.type].parts.length;
while (parts.length < partCount)
parts.push(sshbuf.readPart());
assert.ok(parts.length >= 1, 'key must have at least one part');
var algInfo = algs.info[key.type];
if (key.type === 'ecdsa') {
var res = ECDSA_ALGO.exec(algo);
assert.ok(res !== null);
assert.strictEqual(res[1], parts[0].data.toString());
}
for (var i = 0; i < algInfo.parts.length; ++i) {
parts[i].name = algInfo.parts[i];
if (parts[i].name !== 'curve' &&
algInfo.normalize !== false) {
var p = parts[i];
p.data = utils.mpNormalize(p.data);
}
}
cert.subjectKey = new Key(key);
cert.serial = sshbuf.readInt64();
var type = TYPES[sshbuf.readInt()];
assert.string(type, 'valid cert type');
cert.signatures.openssh.keyId = sshbuf.readString();
var principals = [];
var pbuf = sshbuf.readBuffer();
var psshbuf = new SSHBuffer({ buffer: pbuf });
while (!psshbuf.atEnd())
principals.push(psshbuf.readString());
if (principals.length === 0)
principals = ['*'];
cert.subjects = principals.map(function (pr) {
if (type === 'user')
return (Identity.forUser(pr));
else if (type === 'host')
return (Identity.forHost(pr));
throw (new Error('Unknown identity type ' + type));
});
cert.validFrom = int64ToDate(sshbuf.readInt64());
cert.validUntil = int64ToDate(sshbuf.readInt64());
cert.signatures.openssh.critical = sshbuf.readBuffer();
cert.signatures.openssh.exts = sshbuf.readBuffer();
/* reserved */
sshbuf.readBuffer();
var signingKeyBuf = sshbuf.readBuffer();
cert.issuerKey = rfc4253.read(signingKeyBuf);
/*
* OpenSSH certs don't give the identity of the issuer, just their
* public key. So, we use an Identity that matches anything. The
* isSignedBy() function will later tell you if the key matches.
*/
cert.issuer = Identity.forHost('**');
var sigBuf = sshbuf.readBuffer();
cert.signatures.openssh.signature =
Signature.parse(sigBuf, cert.issuerKey.type, 'ssh');
if (partial !== undefined) {
partial.remainder = sshbuf.remainder();
partial.consumed = sshbuf._offset;
}
return (new Certificate(cert));
}
function int64ToDate(buf) {
var i = buf.readUInt32BE(0) * 4294967296;
i += buf.readUInt32BE(4);
var d = new Date();
d.setTime(i * 1000);
d.sourceInt64 = buf;
return (d);
}
function dateToInt64(date) {
if (date.sourceInt64 !== undefined)
return (date.sourceInt64);
var i = Math.round(date.getTime() / 1000);
var upper = Math.floor(i / 4294967296);
var lower = Math.floor(i % 4294967296);
var buf = new Buffer(8);
buf.writeUInt32BE(upper, 0);
buf.writeUInt32BE(lower, 4);
return (buf);
}
function sign(cert, key) {
if (cert.signatures.openssh === undefined)
cert.signatures.openssh = {};
try {
var blob = toBuffer(cert, true);
} catch (e) {
delete (cert.signatures.openssh);
return (false);
}
var sig = cert.signatures.openssh;
var hashAlgo = undefined;
if (key.type === 'rsa' || key.type === 'dsa')
hashAlgo = 'sha1';
var signer = key.createSign(hashAlgo);
signer.write(blob);
sig.signature = signer.sign();
return (true);
}
function signAsync(cert, signer, done) {
if (cert.signatures.openssh === undefined)
cert.signatures.openssh = {};
try {
var blob = toBuffer(cert, true);
} catch (e) {
delete (cert.signatures.openssh);
done(e);
return;
}
var sig = cert.signatures.openssh;
signer(blob, function (err, signature) {
if (err) {
done(err);
return;
}
try {
/*
* This will throw if the signature isn't of a
* type/algo that can be used for SSH.
*/
signature.toBuffer('ssh');
} catch (e) {
done(e);
return;
}
sig.signature = signature;
done();
});
}
function write(cert, options) {
if (options === undefined)
options = {};
var blob = toBuffer(cert);
var out = getCertType(cert.subjectKey) + ' ' + blob.toString('base64');
if (options.comment)
out = out + ' ' + options.comment;
return (out);
}
function toBuffer(cert, noSig) {
assert.object(cert.signatures.openssh, 'signature for openssh format');
var sig = cert.signatures.openssh;
if (sig.nonce === undefined)
sig.nonce = crypto.randomBytes(16);
var buf = new SSHBuffer({});
buf.writeString(getCertType(cert.subjectKey));
buf.writeBuffer(sig.nonce);
var key = cert.subjectKey;
var algInfo = algs.info[key.type];
algInfo.parts.forEach(function (part) {
buf.writePart(key.part[part]);
});
buf.writeInt64(cert.serial);
var type = cert.subjects[0].type;
assert.notStrictEqual(type, 'unknown');
cert.subjects.forEach(function (id) {
assert.strictEqual(id.type, type);
});
type = TYPES[type];
buf.writeInt(type);
if (sig.keyId === undefined) {
sig.keyId = cert.subjects[0].type + '_' +
(cert.subjects[0].uid || cert.subjects[0].hostname);
}
buf.writeString(sig.keyId);
var sub = new SSHBuffer({});
cert.subjects.forEach(function (id) {
if (type === TYPES.host)
sub.writeString(id.hostname);
else if (type === TYPES.user)
sub.writeString(id.uid);
});
buf.writeBuffer(sub.toBuffer());
buf.writeInt64(dateToInt64(cert.validFrom));
buf.writeInt64(dateToInt64(cert.validUntil));
if (sig.critical === undefined)
sig.critical = new Buffer(0);
buf.writeBuffer(sig.critical);
if (sig.exts === undefined)
sig.exts = new Buffer(0);
buf.writeBuffer(sig.exts);
/* reserved */
buf.writeBuffer(new Buffer(0));
sub = rfc4253.write(cert.issuerKey);
buf.writeBuffer(sub);
if (!noSig)
buf.writeBuffer(sig.signature.toBuffer('ssh'));
return (buf.toBuffer());
}
function getAlg(certType) {
if (certType === '[email protected]')
return ('rsa');
if (certType === '[email protected]')
return ('dsa');
if (certType.match(ECDSA_ALGO))
return ('ecdsa');
if (certType === '[email protected]')
return ('ed25519');
throw (new Error('Unsupported cert type ' + certType));
}
function getCertType(key) {
if (key.type === 'rsa')
return ('[email protected]');
if (key.type === 'dsa')
return ('[email protected]');
if (key.type === 'ecdsa')
return ('ecdsa-sha2-' + key.curve + '[email protected]');
if (key.type === 'ed25519')
return ('[email protected]');
throw (new Error('Unsupported key type ' + key.type));
}
|
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
const common = require('../common');
const assert = require('assert');
const http = require('http');
const server = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain',
'Connection': 'close'
});
res.write('hello ');
res.write('world\n');
res.end();
});
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();
server.listen(common.PIPE, common.mustCall(function() {
const options = {
socketPath: common.PIPE,
path: '/'
};
const req = http.get(options, common.mustCall(function(res) {
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.headers['content-type'], 'text/plain');
res.body = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
res.body += chunk;
});
res.on('end', common.mustCall(function() {
assert.strictEqual(res.body, 'hello world\n');
server.close(common.mustCall(function(error) {
assert.strictEqual(error, undefined);
server.close(common.expectsError({
code: 'ERR_SERVER_NOT_RUNNING',
message: 'Server is not running.',
name: 'Error'
}));
}));
}));
}));
req.on('error', function(e) {
assert.fail(e);
});
req.end();
}));
|
var registry = require('./registry/registry')
module.exports = function(search_opts, callback) {
registry.search(search_opts, function(err, plugins) {
if(callback) {
if(err) return callback(err);
callback(null, plugins);
} else {
if(err) return console.log(err);
for(var plugin in plugins) {
console.log(plugins[plugin].name, '-', plugins[plugin].description || 'no description provided');
}
}
});
}
|
//>>built
define("dojox/editor/plugins/nls/sr/AutoSave",{"saveLabel":"Sačuvaj","saveSettingLabelOn":"Podesi interval za automatsko čuvanje...","saveSettingLabelOff":"Isključi automatsko čuvanje","saveSettingdialogTitle":"Automatsko čuvanje","saveSettingdialogDescription":"Navedite interval za automatsko čuvanje","saveSettingdialogParamName":"Interval za automatsko čuvanje","saveSettingdialogParamLabel":"min","saveSettingdialogButtonOk":"Podesi interval","saveSettingdialogButtonCancel":"Otkaži","saveMessageSuccess":"Sačuvano u ${0}","saveMessageFail":"Nije uspelo čuvanje u ${0}"});
|
var mongoose = require('mongoose'),
elasticsearch = require('elasticsearch'),
esClient = new elasticsearch.Client({
deadTimeout: 0,
keepAlive: false
}),
async = require('async'),
config = require('./config'),
Schema = mongoose.Schema,
mongoosastic = require('../lib/mongoosastic');
var KittenSchema;
var Kitten;
describe('Suggesters', function() {
before(function(done) {
mongoose.connect(config.mongoUrl, function() {
config.deleteIndexIfExists(['kittens'], function() {
KittenSchema = new Schema({
name: {
type: String,
es_type: 'completion',
es_analyzer: 'simple',
es_indexed: true
},
breed: {
type: String
}
});
KittenSchema.plugin(mongoosastic);
Kitten = mongoose.model('Kitten', KittenSchema);
Kitten.createMapping({}, function() {
Kitten.remove(function() {
var kittens = [
new Kitten({
name: 'Cookie',
breed: 'Aegean'
}),
new Kitten({
name: 'Chipmunk',
breed: 'Aegean'
}),
new Kitten({
name: 'Twix',
breed: 'Persian'
}),
new Kitten({
name: 'Cookies and Cream',
breed: 'Persian'
})
];
async.forEach(kittens, config.saveAndWaitIndex, function() {
setTimeout(done, config.INDEXING_TIMEOUT);
});
});
});
});
});
});
after(function(done) {
Kitten.esClient.close();
mongoose.disconnect();
esClient.close();
done();
});
describe('Testing Suggest', function() {
it('should index property name with type completion', function(done) {
Kitten = mongoose.model('Kitten', KittenSchema);
Kitten.createMapping(function() {
esClient.indices.getMapping({
index: 'kittens',
type: 'kitten'
}, function(err, mapping) {
var props = mapping.kitten !== undefined ? /* elasticsearch 1.0 & 0.9 support */
mapping.kitten.properties : /* ES 0.9.11 */
mapping.kittens.mappings.kitten.properties; /* ES 1.0.0 */
props.name.type.should.eql('completion');
done();
});
});
});
it('should return suggestions after hits', function(done) {
Kitten.search({
match_all: {}
}, {
suggest: {
kittensuggest: {
text: 'Cook',
completion: {
field: 'name'
}
}
}
}, function(err, res) {
res.should.have.property('suggest');
res.suggest.kittensuggest[0].options.length.should.eql(2);
done();
});
});
});
});
|
var title = "A Hidden Treasure";
var desc = "The map is pretty hard to read, but it seems to depict a small, wooded island in the sea. On the north-east corner of the island, down a dead-end street, is a big, red, X.";
var offer = "This is clearly a pirate's treasure map, big red X and all. Following it will almost certainly net you a reward.";
var completion = "You've found the treasure!";
var auto_complete = 0;
var familiar_turnin = 1;
var is_tracked = 0;
var show_alert = 0;
var silent_complete = 0;
var is_emergency = 1;
var progress = [
];
var giver_progress = [
];
var no_progress = "null";
var prereq_quests = [];
var prerequisites = [];
var end_npcs = [];
var locations = {};
var requirements = {
"r374" : {
"type" : "flag",
"name" : "treasure_1",
"class_id" : "money_bag",
"desc" : "Find the treasure"
}
};
function onComplete(pc){ // generated from rewards
var xp=0;
var currants=0;
var mood=0;
var energy=0;
var favor=0;
var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0;
multiplier += pc.imagination_get_quest_modifier();
xp = pc.stats_add_xp(round_to_5(10 * multiplier), true, {type: 'quest_complete', quest: this.class_tsid});
apiLogAction('QUEST_REWARDS', 'pc='+pc.tsid, 'quest='+this.class_tsid, 'xp='+intval(xp), 'mood='+intval(mood), 'energy='+intval(energy), 'currants='+intval(currants), 'favor='+intval(favor));
if(pc.buffs_has('gift_of_gab')) {
pc.buffs_remove('gift_of_gab');
}
else if(pc.buffs_has('silvertongue')) {
pc.buffs_remove('silvertongue');
}
}
var rewards = {
"xp" : 10
};
// generated ok (NO DATE)
|
/**
* Module Dependencies
*/
var Waterline = require('waterline');
var _ = require('lodash');
var async = require('async');
var assert = require('assert');
// Require Fixtures
var fixtures = {
UserFixture: require('./fixtures/crud.fixture')
};
/////////////////////////////////////////////////////
// TEST SETUP
////////////////////////////////////////////////////
var waterline, ontology;
before(function(done) {
waterline = new Waterline();
Object.keys(fixtures).forEach(function(key) {
waterline.loadCollection(fixtures[key]);
});
var connections = { queryable: _.clone(Connections.test) };
waterline.initialize({ adapters: { wl_tests: Adapter }, connections: connections }, function(err, _ontology) {
if(err) return done(err);
ontology = _ontology;
Object.keys(_ontology.collections).forEach(function(key) {
var globalName = key.charAt(0).toUpperCase() + key.slice(1);
global.Queryable[globalName] = _ontology.collections[key];
});
done();
});
});
after(function(done) {
function dropCollection(item, next) {
if(!Adapter.hasOwnProperty('drop')) return next();
ontology.collections[item].drop(function(err) {
if(err) return next(err);
next();
});
}
async.each(Object.keys(ontology.collections), dropCollection, function(err) {
if(err) return done(err);
waterline.teardown(done);
});
});
|
/*!
* ic-ajax
*
* - (c) 2013 Instructure, Inc
* - please see license at https://github.com/instructure/ic-ajax/blob/master/LICENSE
* - inspired by discourse ajax: https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/mixins/ajax.js#L19
*/
import Ember from 'ember';
/*
* jQuery.ajax wrapper, supports the same signature except providing
* `success` and `error` handlers will throw an error (use promises instead)
* and it resolves only the response (no access to jqXHR or textStatus).
*/
export function request() {
return raw.apply(null, arguments).then(function(result) {
return result.response;
}, null, 'ic-ajax: unwrap raw ajax response');
}
request.OVERRIDE_REST_ADAPTER = true;
export default request;
/*
* Same as `request` except it resolves an object with `{response, textStatus,
* jqXHR}`, useful if you need access to the jqXHR object for headers, etc.
*/
export function raw() {
return makePromise(parseArgs.apply(null, arguments));
}
export var __fixtures__ = {};
/*
* Defines a fixture that will be used instead of an actual ajax
* request to a given url. This is useful for testing, allowing you to
* stub out responses your application will send without requiring
* libraries like sinon or mockjax, etc.
*
* For example:
*
* defineFixture('/self', {
* response: { firstName: 'Ryan', lastName: 'Florence' },
* textStatus: 'success'
* jqXHR: {}
* });
*
* @param {String} url
* @param {Object} fixture
*/
export function defineFixture(url, fixture) {
__fixtures__[url] = JSON.parse(JSON.stringify(fixture));
}
/*
* Looks up a fixture by url.
*
* @param {String} url
*/
export function lookupFixture (url) {
return __fixtures__ && __fixtures__[url];
}
function makePromise(settings) {
return new Ember.RSVP.Promise(function(resolve, reject) {
var fixture = lookupFixture(settings.url);
if (fixture) {
if (fixture.textStatus === 'success') {
return Ember.run(null, resolve, fixture);
} else {
return Ember.run(null, reject, fixture);
}
}
settings.success = makeSuccess(resolve);
settings.error = makeError(reject);
Ember.$.ajax(settings);
}, 'ic-ajax: ' + (settings.type || 'GET') + ' to ' + settings.url);
};
function parseArgs() {
var settings = {};
if (arguments.length === 1) {
if (typeof arguments[0] === "string") {
settings.url = arguments[0];
} else {
settings = arguments[0];
}
} else if (arguments.length === 2) {
settings = arguments[1];
settings.url = arguments[0];
}
if (settings.success || settings.error) {
throw new Ember.Error("ajax should use promises, received 'success' or 'error' callback");
}
return settings;
}
function makeSuccess(resolve) {
return function(response, textStatus, jqXHR) {
Ember.run(null, resolve, {
response: response,
textStatus: textStatus,
jqXHR: jqXHR
});
}
}
function makeError(reject) {
return function(jqXHR, textStatus, errorThrown) {
Ember.run(null, reject, {
jqXHR: jqXHR,
textStatus: textStatus,
errorThrown: errorThrown
});
};
}
if (typeof window.DS !== 'undefined'){
Ember.onLoad('Ember.Application', function(Application){
Application.initializer({
name: 'ic-ajax_REST_Adapter',
after: 'store',
initialize: function(container, application){
if (request.OVERRIDE_REST_ADAPTER) {
DS.RESTAdapter.reopen({
ajax: function(url, type, options){
options = this.ajaxOptions(url, type, options);
return request(options);
}
});
}
}
});
});
}
|
import React from 'react'
import { Item } from 'semantic-ui-react'
const ItemExampleRelaxed = () => (
<Item.Group relaxed>
<Item>
<Item.Image size='tiny' src='http://semantic-ui.com/images/wireframe/image.png' />
<Item.Content verticalAlign='middle'>
<Item.Header as='a'>12 Years a Slave</Item.Header>
</Item.Content>
</Item>
<Item>
<Item.Image size='tiny' src='http://semantic-ui.com/images/wireframe/image.png' />
<Item.Content verticalAlign='middle'>
<Item.Header as='a'>My Neighbor Totoro</Item.Header>
</Item.Content>
</Item>
<Item>
<Item.Image size='tiny' src='http://semantic-ui.com/images/wireframe/image.png' />
<Item.Content verticalAlign='middle'>
<Item.Header as='a'>Watchmen</Item.Header>
</Item.Content>
</Item>
</Item.Group>
)
export default ItemExampleRelaxed
|
Event.observe(window, 'load', function(){
// This would be so much easier with jQuery :(
Element.addMethods({
credentialDisable: function(el){
var el = $(el);
el.hide();
var input = el.down('input');
if(input)
input.disable();
},
credentialEnable: function(el){
var el = $(el);
var input = el.down('input');
if(input)
input.enable();
el.show();
}
});
var oi_input = $$('.openid input')[0];
if(oi_input && oi_input.value != ''){
$$('.password').each(function(el){
el.credentialDisable();
});
} else {
$$('.openid').each(function(el){
el.credentialDisable();
});
}
$$('.usePassword').each(function(link){
link.observe('click', function(e){
e.stop();
$$('.password').each(function(el) {
el.credentialEnable();
});
$$('.openid').each(function(el) {
el.credentialDisable();
});
});
});
$$('.useOpenid').each(function(link){
link.observe('click', function(e){
e.stop();
$$('.password').each(function(el) {
el.credentialDisable();
});
$$('.openid').each(function(el) {
el.credentialEnable();
});
});
});
}); |
app.directive('bunkerDropzone', function ($document, $compile, DroppableItem) {
// Takes raw DOM events and translates them in to our DroppableItem model.
// returns falsy if we can't find a valid item to turn in to a droppable.
var getDroppableItem = function (event) {
var dataTransfer = event.originalEvent.dataTransfer,
rawItem;
if (!dataTransfer) {
return null;
}
// Here is how to get a FF -> FF or Chrome -> FF image drag to work:
// dataTransfer.mozItemCount
// dataTransfer.mozGetDataAt('text/x-moz-url', 0)
// if dragging a file from within a browser window
if (dataTransfer.items && dataTransfer.items.length) {
rawItem = _.find(dataTransfer.items, function (i) {
return i.type === "text/uri-list";
});
if (rawItem) {
return new DroppableItem(rawItem);
}
}
// If dragging a file from outside the browser window (desktop)
if (dataTransfer.files && dataTransfer.files.length) {
return new DroppableItem(dataTransfer.files[0]);
}
return null;
};
return {
restrict: 'A',
scope: true,
controller: function ($modal, $rootScope, imageUpload) {
var self = this;
self.isModalOpen = false;
self.doSingleImageUpload = function (droppableItem) {
droppableItem.loadData().then(function (loadedData) {
if (loadedData.droppable.isFile()) {
self.isModalOpen = true;
$modal.open({
templateUrl: '/assets/app/fileUpload/imageUpload.html',
controller: 'ImageUpload as imageUpload',
resolve: {
imageData: function () {
return loadedData.data;
}
},
size: 'lg'
})
.result
.then(function (url) {
self.setModalClosed();
$rootScope.$broadcast('inputText', url);
}, self.setModalClosed);
}
else {
$rootScope.$broadcast('inputText', loadedData.data);
}
}, function (errorObj) {
$modal.open({
templateUrl: '/assets/app/fileUpload/fileError.html',
controller: 'FileError as fileError',
resolve: {
errorMessage: function () {
return errorObj.error;
}
}
})
.result
.then(self.setModalClosed, self.setModalClosed);
});
};
self.isImageFile = function (item) {
// TODO: can probably change this to just be a regex: /image.*/
return item.type && (
_.includes(item.type, '/jpeg') ||
_.includes(item.type, '/jpg') ||
_.includes(item.type, '/gif') ||
_.includes(item.type, '/bmp') ||
_.includes(item.type, '/png'));
};
self.setModalClosed = function () {
self.isModalOpen = false;
};
},
controllerAs: 'dropzoneCtrl',
link: function (scope, element, attrs, dropzoneCtrl) {
/* There's gotta be a better way to do this */
var overlay = angular.element('<div id="bunker-dropzone-overlay"><div class="overlay"></div><div overlay-contents></div></div>');
element
.append(overlay);
$compile(overlay)(scope);
/* listen for main drag/drop events */
element
.on('dragover.dropzone', function (e) {
e.preventDefault(); // this must be here otherwise the browser won't listen for the drop event.
})
.on('dragbetterenter.dropzone', function () {
// We should be doing a check here to make sure it's valid. To fix when fixing the FF
// bug. 'dragbetterenter' doesn't propagate the dragenter event properly :( /* && getDroppableItem(e) */
if (!dropzoneCtrl.isModalOpen) {
$(this).addClass('dragover');
}
})
.on('dragbetterleave.dropzone', function () {
$(this).removeClass('dragover');
})
.on('drop.dropzone', function (e) {
e.preventDefault();
if (dropzoneCtrl.isModalOpen) {
return;
}
var droppableItem = getDroppableItem(e);
if (!droppableItem) {
return;
}
dropzoneCtrl.doSingleImageUpload(droppableItem);
});
/* we listen on doc element also to swallow "missed" drops.
also listening for paste event */
$document
.on('dragover.dropzone drop.dropzone', function (e) {
e.preventDefault();
})
.on('paste.dropzone', function (e) {
if (!e.originalEvent.clipboardData || dropzoneCtrl.isModalOpen) {
return;
}
var copiedImage = _.find(e.originalEvent.clipboardData.items, function (item) {
return dropzoneCtrl.isImageFile(item);
});
if (!copiedImage) {
return;
}
e.preventDefault();
dropzoneCtrl.doSingleImageUpload(new DroppableItem(copiedImage.getAsFile()));
});
scope.$on('$destroy', function () {
element.off('.dropzone');
$document.off('.dropzone');
});
}
};
});
|
// @remove-on-eject-begin
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @remove-on-eject-end
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
throw new Error('Production builds must have NODE_ENV=production.');
}
// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';
// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
? // Making sure that the publicPath goes back to to build folder.
{ publicPath: Array(cssFilename.split('/').length).join('../') }
: {};
// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
// Don't attempt to continue if there are any errors.
bail: true,
// We generate sourcemaps in production. This is slow but gives good results.
// You can exclude the *.map files from the build during deployment.
devtool: shouldUseSourceMap ? 'source-map' : false,
// In production, we only want to load the polyfills and the app code.
entry: [require.resolve('./polyfills'), paths.appIndexJs],
output: {
// The build folder.
path: paths.appBuild,
// Generated JS file names (with nested folders).
// There will be one main bundle, and one file per asynchronous chunk.
// We don't currently advertise code splitting but Webpack supports it.
filename: 'static/js/[name].[chunkhash:8].js',
chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/'),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// @remove-on-eject-begin
// Resolve Babel runtime relative to react-scripts.
// It usually still works on npm 3 without this but it would be
// unfortunate to rely on, as react-scripts could be symlinked,
// and thus babel-runtime might not be resolvable from the source.
'babel-runtime': path.dirname(
require.resolve('babel-runtime/package.json')
),
// @remove-on-eject-end
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
// @remove-on-eject-begin
// TODO: consider separate config for production,
// e.g. to enable no-console and no-debugger only in production.
baseConfig: {
extends: [require.resolve('eslint-config-react-app')],
},
ignore: false,
useEslintrc: false,
// @remove-on-eject-end
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works just like "file" loader but it also embeds
// assets smaller than specified size as data URLs to avoid requests.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// @remove-on-eject-begin
babelrc: false,
presets: [require.resolve('babel-preset-react-app')],
// @remove-on-eject-end
compact: true,
},
},
// The notation here is somewhat confusing.
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader normally turns CSS into JS modules injecting <style>,
// but unlike in development configuration, we do something different.
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
// (second argument), then grabs the result CSS and puts it into a
// separate file in our build process. This way we actually ship
// a single CSS file in production instead of JS code injecting <style>
// tags. If you use code splitting, however, any async bundles will still
// use the "style" loader inside the async code so CSS from them won't be
// in the main CSS file.
{
test: /\.css$/,
loader: ExtractTextPlugin.extract(
Object.assign(
{
fallback: require.resolve('style-loader'),
use: [
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
minimize: true,
sourceMap: shouldUseSourceMap,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
extractTextPluginOptions
)
),
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
},
// "file" loader makes sure assets end up in the `build` folder.
// When you `import` an asset, you get its filename.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve('file-loader'),
// Exclude `js` files to keep "css" loader working as it injects
// it's runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.js$/, /\.html$/, /\.json$/],
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
],
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In production, it will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV was set to production here.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// Minify the code.
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebookincubator/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
},
output: {
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebookincubator/create-react-app/issues/2488
ascii_only: true,
},
sourceMap: shouldUseSourceMap,
}),
// Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
new ExtractTextPlugin({
filename: cssFilename,
}),
// Generate a manifest file which contains a mapping of all asset filenames
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
new ManifestPlugin({
fileName: 'asset-manifest.json',
}),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the Webpack build.
new SWPrecacheWebpackPlugin({
// By default, a cache-busting query parameter is appended to requests
// used to populate the caches, to ensure the responses are fresh.
// If a URL is already hashed by Webpack, then there is no concern
// about it being stale, and the cache-busting can be skipped.
dontCacheBustUrlsMatching: /\.\w{8}\./,
filename: 'service-worker.js',
logger(message) {
if (message.indexOf('Total precache size is') === 0) {
// This message occurs for every build and is a bit too noisy.
return;
}
if (message.indexOf('Skipping static resource') === 0) {
// This message obscures real errors so we ignore it.
// https://github.com/facebookincubator/create-react-app/issues/2612
return;
}
console.log(message);
},
minify: true,
// For unknown URLs, fallback to the index page
navigateFallback: publicUrl + '/index.html',
// Ignores URLs starting from /__ (useful for Firebase):
// https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
navigateFallbackWhitelist: [/^(?!\/__).*/],
// Don't precache sourcemaps (they're large) and build asset manifest:
staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
};
|
Prism.hooks.add('before-highlight', function(env) {
if (env.code) {
var pre = env.element.parentNode;
var clsReg = /\s*\bkeep-initial-line-feed\b\s*/;
if (
pre && pre.nodeName.toLowerCase() === 'pre' &&
// Apply only if nor the <pre> or the <code> have the class
(!clsReg.test(pre.className) && !clsReg.test(env.element.className))
) {
env.code = env.code.replace(/^(?:\r?\n|\r)/, '');
}
}
}); |
define(["../_StoreMixin", "dojo/_base/declare", "dojo/_base/array", "dojo/_base/lang", "dojo/_base/Deferred",
"dojo/on", "dojo/query", "dojo/string", "dojo/has", "put-selector/put", "dojo/i18n!./nls/pagination",
"dojo/_base/sniff", "xstyle/css!../css/extensions/Pagination.css"],
function(_StoreMixin, declare, arrayUtil, lang, Deferred, on, query, string, has, put, i18n){
function cleanupContent(grid){
// Remove any currently-rendered rows, or noDataMessage
if(grid.noDataNode){
put(grid.noDataNode, "!");
delete grid.noDataNode;
}else{
grid.cleanup();
}
grid.contentNode.innerHTML = "";
}
function cleanupLoading(grid){
if(grid.loadingNode){
put(grid.loadingNode, "!");
delete grid.loadingNode;
}else if(grid._oldPageNodes){
// If cleaning up after a load w/ showLoadingMessage: false,
// be careful to only clean up rows from the old page, not the new one
for(var id in grid._oldPageNodes){
grid.removeRow(grid._oldPageNodes[id]);
}
delete grid._oldPageNodes;
// Also remove the observer from the previous page, if there is one
if(grid._oldPageObserver){
grid._oldPageObserver.cancel();
grid._numObservers--;
delete grid._oldPageObserver;
}
}
delete grid._isLoading;
}
return declare(_StoreMixin, {
// summary:
// An extension for adding discrete pagination to a List or Grid.
// rowsPerPage: Number
// Number of rows (items) to show on a given page.
rowsPerPage: 10,
// pagingTextBox: Boolean
// Indicates whether or not to show a textbox for paging.
pagingTextBox: false,
// previousNextArrows: Boolean
// Indicates whether or not to show the previous and next arrow links.
previousNextArrows: true,
// firstLastArrows: Boolean
// Indicates whether or not to show the first and last arrow links.
firstLastArrows: false,
// pagingLinks: Number
// The number of page links to show on each side of the current page
// Set to 0 (or false) to disable page links.
pagingLinks: 2,
// pageSizeOptions: Array[Number]
// This provides options for different page sizes in a drop-down.
// If it is empty (default), no page size drop-down will be displayed.
pageSizeOptions: null,
// showLoadingMessage: Boolean
// If true, clears previous data and displays loading node when requesting
// another page; if false, leaves previous data in place until new data
// arrives, then replaces it immediately.
showLoadingMessage: true,
// i18nPagination: Object
// This object contains all of the internationalized strings as
// key/value pairs.
i18nPagination: i18n,
showFooter: true,
_currentPage: 1,
_total: 0,
buildRendering: function(){
this.inherited(arguments);
// add pagination to footer
var grid = this,
paginationNode = this.paginationNode =
put(this.footerNode, "div.dgrid-pagination"),
statusNode = this.paginationStatusNode =
put(paginationNode, "div.dgrid-status"),
i18n = this.i18nPagination,
navigationNode,
node,
i;
statusNode.tabIndex = 0;
// Initialize UI based on pageSizeOptions and rowsPerPage
this._updatePaginationSizeSelect();
this._updateRowsPerPageOption();
// initialize some content into paginationStatusNode, to ensure
// accurate results on initial resize call
statusNode.innerHTML = string.substitute(i18n.status,
{ start: 1, end: 1, total: 0 });
navigationNode = this.paginationNavigationNode =
put(paginationNode, "div.dgrid-navigation");
if(this.firstLastArrows){
// create a first-page link
node = this.paginationFirstNode =
put(navigationNode, "span.dgrid-first.dgrid-page-link", "«");
node.setAttribute("aria-label", i18n.gotoFirst);
node.tabIndex = 0;
}
if(this.previousNextArrows){
// create a previous link
node = this.paginationPreviousNode =
put(navigationNode, "span.dgrid-previous.dgrid-page-link", "‹");
node.setAttribute("aria-label", i18n.gotoPrev);
node.tabIndex = 0;
}
this.paginationLinksNode = put(navigationNode, "span.dgrid-pagination-links");
if(this.previousNextArrows){
// create a next link
node = this.paginationNextNode =
put(navigationNode, "span.dgrid-next.dgrid-page-link", "›");
node.setAttribute("aria-label", i18n.gotoNext);
node.tabIndex = 0;
}
if(this.firstLastArrows){
// create a last-page link
node = this.paginationLastNode =
put(navigationNode, "span.dgrid-last.dgrid-page-link", "»");
node.setAttribute("aria-label", i18n.gotoLast);
node.tabIndex = 0;
}
this._listeners.push(on(navigationNode, ".dgrid-page-link:click,.dgrid-page-link:keydown", function(event){
// For keyboard events, only respond to enter
if(event.type === "keydown" && event.keyCode !== 13){
return;
}
var cls = this.className,
curr, max;
if(grid._isLoading || cls.indexOf("dgrid-page-disabled") > -1){
return;
}
curr = grid._currentPage;
max = Math.ceil(grid._total / grid.rowsPerPage);
// determine navigation target based on clicked link's class
if(this === grid.paginationPreviousNode){
grid.gotoPage(curr - 1);
}else if(this === grid.paginationNextNode){
grid.gotoPage(curr + 1);
}else if(this === grid.paginationFirstNode){
grid.gotoPage(1);
}else if(this === grid.paginationLastNode){
grid.gotoPage(max);
}else if(cls === "dgrid-page-link"){
grid.gotoPage(+this.innerHTML, true); // the innerHTML has the page number
}
}));
},
destroy: function(){
this.inherited(arguments);
if(this._pagingTextBoxHandle){
this._pagingTextBoxHandle.remove();
}
},
_updatePaginationSizeSelect: function(){
// summary:
// Creates or repopulates the pagination size selector based on
// the values in pageSizeOptions. Called from buildRendering
// and _setPageSizeOptions.
var pageSizeOptions = this.pageSizeOptions,
paginationSizeSelect = this.paginationSizeSelect,
handle;
if(pageSizeOptions && pageSizeOptions.length){
if(!paginationSizeSelect){
// First time setting page options; create the select
paginationSizeSelect = this.paginationSizeSelect =
put(this.paginationNode, "select.dgrid-page-size");
handle = this._paginationSizeChangeHandle =
on(paginationSizeSelect, "change", lang.hitch(this, function(){
this.set("rowsPerPage", +this.paginationSizeSelect.value);
}));
this._listeners.push(handle);
}
// Repopulate options
paginationSizeSelect.options.length = 0;
for(i = 0; i < pageSizeOptions.length; i++){
put(paginationSizeSelect, "option", pageSizeOptions[i], {
value: pageSizeOptions[i],
selected: this.rowsPerPage === pageSizeOptions[i]
});
}
// Ensure current rowsPerPage value is in options
this._updateRowsPerPageOption();
}else if(!(pageSizeOptions && pageSizeOptions.length) && paginationSizeSelect){
// pageSizeOptions was removed; remove/unhook the drop-down
put(paginationSizeSelect, "!");
this.paginationSizeSelect = null;
this._paginationSizeChangeHandle.remove();
}
},
_setPageSizeOptions: function(pageSizeOptions){
this.pageSizeOptions = pageSizeOptions && pageSizeOptions.sort(function(a, b){
return a - b;
});
this._updatePaginationSizeSelect();
},
_updateRowsPerPageOption: function(){
// summary:
// Ensures that an option for rowsPerPage's value exists in the
// paginationSizeSelect drop-down (if one is rendered).
// Called from buildRendering and _setRowsPerPage.
var rowsPerPage = this.rowsPerPage,
pageSizeOptions = this.pageSizeOptions,
paginationSizeSelect = this.paginationSizeSelect;
if(paginationSizeSelect){
if(arrayUtil.indexOf(pageSizeOptions, rowsPerPage) < 0){
this._setPageSizeOptions(pageSizeOptions.concat([rowsPerPage]));
}else{
paginationSizeSelect.value = "" + rowsPerPage;
}
}
},
_setRowsPerPage: function(rowsPerPage){
this.rowsPerPage = rowsPerPage;
this._updateRowsPerPageOption();
this.gotoPage(1);
},
_updateNavigation: function(focusLink){
// summary:
// Update status and navigation controls based on total count from query
var grid = this,
i18n = this.i18nPagination,
linksNode = this.paginationLinksNode,
currentPage = this._currentPage,
pagingLinks = this.pagingLinks,
paginationNavigationNode = this.paginationNavigationNode,
end = Math.ceil(this._total / this.rowsPerPage),
pagingTextBoxHandle = this._pagingTextBoxHandle;
function pageLink(page, addSpace){
var link;
if(grid.pagingTextBox && page == currentPage && end > 1){
// use a paging text box if enabled instead of just a number
link = put(linksNode, 'input.dgrid-page-input[type=text][value=$]', currentPage);
link.setAttribute("aria-label", i18n.jumpPage);
grid._pagingTextBoxHandle = on(link, "change", function(){
var value = +this.value;
if(!isNaN(value) && value > 0 && value <= end){
grid.gotoPage(+this.value, true);
}
});
}else{
// normal link
link = put(linksNode,
'span' + (page == currentPage ? '.dgrid-page-disabled' : '') + '.dgrid-page-link',
page + (addSpace ? " " : ""));
link.setAttribute("aria-label", i18n.gotoPage);
link.tabIndex = 0;
}
if(page == currentPage && focusLink){
// focus on it if we are supposed to retain the focus
link.focus();
}
}
if(pagingTextBoxHandle){ pagingTextBoxHandle.remove(); }
linksNode.innerHTML = "";
query(".dgrid-first, .dgrid-previous", paginationNavigationNode).forEach(function(link){
put(link, (currentPage == 1 ? "." : "!") + "dgrid-page-disabled");
});
query(".dgrid-last, .dgrid-next", paginationNavigationNode).forEach(function(link){
put(link, (currentPage >= end ? "." : "!") + "dgrid-page-disabled");
});
if(pagingLinks && end > 0){
// always include the first page (back to the beginning)
pageLink(1, true);
var start = currentPage - pagingLinks;
if(start > 2) {
// visual indication of skipped page links
put(linksNode, "span.dgrid-page-skip", "...");
}else{
start = 2;
}
// now iterate through all the page links we should show
for(var i = start; i < Math.min(currentPage + pagingLinks + 1, end); i++){
pageLink(i, true);
}
if(currentPage + pagingLinks + 1 < end){
put(linksNode, "span.dgrid-page-skip", "...");
}
// last link
if(end > 1){
pageLink(end);
}
}else if(grid.pagingTextBox){
// The pageLink function is also used to create the paging textbox.
pageLink(currentPage);
}
},
refresh: function(){
var self = this;
this.inherited(arguments);
if(!this.store){
console.warn("Pagination requires a store to operate.");
return;
}
// Reset to first page and return promise from gotoPage
return this.gotoPage(1).then(function(results){
// Emit on a separate turn to enable event to be used consistently for
// initial render, regardless of whether the backing store is async
setTimeout(function() {
on.emit(self.domNode, "dgrid-refresh-complete", {
bubbles: true,
cancelable: false,
grid: self,
results: results // QueryResults object (may be a wrapped promise)
});
}, 0);
return results;
});
},
_onNotification: function(rows){
if(rows.length !== this._rowsOnPage){
// Refresh the current page to maintain correct number of rows on page
this.gotoPage(this._currentPage);
}
},
renderArray: function(results, beforeNode){
var grid = this,
rows = this.inherited(arguments);
// Make sure _lastCollection is cleared (due to logic in List)
this._lastCollection = null;
if(!beforeNode){
if(this._topLevelRequest){
// Cancel previous async request that didn't finish
this._topLevelRequest.cancel();
delete this._topLevelRequest;
}
if (typeof results.cancel === "function") {
// Store reference to new async request in progress
this._topLevelRequest = results;
}
Deferred.when(results, function(){
if(grid._topLevelRequest){
// Remove reference to request now that it's finished
delete grid._topLevelRequest;
}
});
}
return rows;
},
insertRow: function(){
var oldNodes = this._oldPageNodes,
row = this.inherited(arguments);
if(oldNodes && row === oldNodes[row.id]){
// If the previous row was reused, avoid removing it in cleanup
delete oldNodes[row.id];
}
return row;
},
gotoPage: function(page, focusLink){
// summary:
// Loads the given page. Note that page numbers start at 1.
var grid = this,
dfd = new Deferred();
var result = this._trackError(function(){
var count = grid.rowsPerPage,
start = (page - 1) * count,
options = lang.mixin(grid.get("queryOptions"), {
start: start,
count: count
// current sort is also included by get("queryOptions")
}),
results,
contentNode = grid.contentNode,
loadingNode,
oldNodes,
children,
i,
len;
if(grid.showLoadingMessage){
cleanupContent(grid);
loadingNode = grid.loadingNode = put(contentNode, "div.dgrid-loading");
loadingNode.innerHTML = grid.loadingMessage;
}else{
// Reference nodes to be cleared later, rather than now;
// iterate manually since IE < 9 doesn't like slicing HTMLCollections
grid._oldPageNodes = oldNodes = {};
children = contentNode.children;
for(i = 0, len = children.length; i < len; i++){
oldNodes[children[i].id] = children[i];
}
// Also reference the current page's observer (if any)
grid._oldPageObserver = grid.observers.pop();
}
// set flag to deactivate pagination event handlers until loaded
grid._isLoading = true;
// Run new query and pass it into renderArray
results = grid.store.query(grid.query, options);
Deferred.when(grid.renderArray(results, null, options), function(rows){
cleanupLoading(grid);
// Reset scroll Y-position now that new page is loaded.
grid.scrollTo({ y: 0 });
Deferred.when(results.total, function(total){
if(!total){
if(grid.noDataNode){
put(grid.noDataNode, "!");
delete grid.noDataNode;
}
// If there are no results, display the no data message.
grid.noDataNode = put(grid.contentNode, "div.dgrid-no-data");
grid.noDataNode.innerHTML = grid.noDataMessage;
}
// Update status text based on now-current page and total.
grid.paginationStatusNode.innerHTML = string.substitute(grid.i18nPagination.status, {
start: Math.min(start + 1, total),
end: Math.min(total, start + count),
total: total
});
grid._total = total;
grid._currentPage = page;
grid._rowsOnPage = rows.length;
// It's especially important that _updateNavigation is called only
// after renderArray is resolved as well (to prevent jumping).
grid._updateNavigation(focusLink);
});
if (has("ie") < 7 || (has("ie") && has("quirks"))) {
// call resize in old IE in case grid is set to height: auto
grid.resize();
}
dfd.resolve(results);
}, function(error){
cleanupLoading(grid);
dfd.reject(error);
});
return dfd.promise;
});
if (!result) {
// A synchronous error occurred; reject the promise.
dfd.reject();
}
return dfd.promise;
}
});
});
|
(function(win, doc) {
var iframe;
var bodyOverflow;
var onMessage = function(event) {
if (event.data === 'collapse') {
iframe.height = 40;
iframe.width = 40;
doc.body.style.overflow = bodyOverflow;
return;
}
if (event.data === 'toolbar') {
iframe.height = 40;
iframe.width = '100%';
doc.body.style.overflow = bodyOverflow;
return;
}
if (event.data === 'expand') {
iframe.width = '100%';
iframe.height = '100%';
doc.body.style.overflow = 'hidden';
return;
}
};
var onReady = function() {
if (!win.__debug_kit_id) {
return;
}
var body = doc.body;
iframe = doc.createElement('iframe');
iframe.setAttribute('style', 'position: fixed; bottom: 0; right: 0; border: 0; outline: 0; overflow: hidden; z-index: 99999;');
iframe.height = 40;
iframe.width = 40;
iframe.src = __debug_kit_base_url + 'debug_kit/toolbar/' + __debug_kit_id;
body.appendChild(iframe);
bodyOverflow = body.style.overflow;
window.addEventListener('message', onMessage, false);
};
var logAjaxRequest = function(original) {
return function() {
if (this.readyState === 4 && this.getResponseHeader('X-DEBUGKIT-ID')) {
var params = {
requestId: this.getResponseHeader('X-DEBUGKIT-ID'),
status: this.status,
date: new Date,
method: this._arguments[0],
url: this._arguments[1],
type: this.getResponseHeader('Content-Type')
}
iframe.contentWindow.postMessage('ajax-completed$$' + JSON.stringify(params), window.location.origin);
}
if (original) {
return original.apply(this, [].slice.call(arguments));
}
};
};
var proxyAjaxOpen = function() {
var proxied = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
this._arguments = arguments;
return proxied.apply(this, [].slice.call(arguments));
};
};
var proxyAjaxSend = function() {
var proxied = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
this.onreadystatechange = logAjaxRequest(this.onreadystatechange);
return proxied.apply(this, [].slice.call(arguments));
};
};
// Bind on ready callback.
if (doc.addEventListener) {
doc.addEventListener('DOMContentLoaded', onReady, false);
doc.addEventListener('DOMContentLoaded', proxyAjaxOpen, false);
doc.addEventListener('DOMContentLoaded', proxyAjaxSend, false);
} else {
throw new Error('Unable to add event listener for DebugKit. Please use a browser' +
'that supports addEventListener().')
}
}(window, document));
|
version https://git-lfs.github.com/spec/v1
oid sha256:d7864b56261240c2204a7df0f625eed7852ff8ff64003e3e1877de785859c84f
size 5053
|
jQuery.extend(jQuery.fn.pickadate.defaults, {
monthsFull: ["urtarrila", "otsaila", "martxoa", "apirila", "maiatza", "ekaina", "uztaila", "abuztua", "iraila", "urria", "azaroa", "abendua"],
monthsShort: ["urt", "ots", "mar", "api", "mai", "eka", "uzt", "abu", "ira", "urr", "aza", "abe"],
weekdaysFull: ["igandea", "astelehena", "asteartea", "asteazkena", "osteguna", "ostirala", "larunbata"],
weekdaysShort: ["ig.", "al.", "ar.", "az.", "og.", "or.", "lr."],
today: "gaur",
clear: "garbitu",
firstDay: 1,
format: "dddd, yyyy(e)ko mmmmren da",
formatSubmit: "yyyy/mm/dd"
}); |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.9.5.28_A1_T2;
* @section: 15.9.5.28;
* @assertion: The Date.prototype property "setMilliseconds" has { DontEnum } attributes;
* @description: Checking absence of DontDelete attribute;
*/
if (delete Date.prototype.setMilliseconds === false) {
$ERROR('#1: The Date.prototype.setMilliseconds property has not the attributes DontDelete');
}
if (Date.prototype.hasOwnProperty('setMilliseconds')) {
$FAIL('#2: The Date.prototype.setMilliseconds property has not the attributes DontDelete');
}
|
/**
* Subtitles plugin JavaScript
*
* @since 1.0.0
*/
(function( $, undefined ) {
/**
* Presentational JS which fires on DOM load
*
* @since 1.0.0
*/
function documentScripts() {
/**
* Toggle screen-reader-text class on the subtitle
* input field. When a user loads a new post page,
* there will be input field placeholder text that
* reads "Enter subtitle here". When the user clicks
* the subtitle input field, then the text will have
* the class screen-reader-text added to it so that
* it's no longer visible. If the user edits a pre-existing
* post subtitle and removes it altogether, then the
* class screen-reader-text will also be added to it.
*
* @since 1.0.0
*/
$( '#subtitle' ).each( function() { // Cribbed from WordPress' dashboard.js
var input = $( this ), // Subtitle input
prompt = $( '#' + this.id + '-prompt-text' ); // The subtitle label
if ( '' === this.value ) { // If the input is blank on page load then show helper text.
prompt.removeClass( 'screen-reader-text' );
}
prompt.click( function() { // Hide the helper text when the subtitle input label is clicked on.
$( this ).addClass( 'screen-reader-text' );
input.focus();
} );
input.focus( function() { // Hide the helper text when the subtitle input is clicked on.
prompt.addClass( 'screen-reader-text' );
});
input.blur( function() { // When input has lost focus and it's empty show helper text.
if ( '' === this.value ) {
prompt.removeClass( 'screen-reader-text' );
}
});
// Tab from the title to the subtitle, rather than the post content.
$( '#title' ).on( 'keydown', function( event ) {
if ( 9 === event.keyCode && ! event.ctrlKey && ! event.altKey && ! event.shiftKey ) {
$( '#subtitle' ).focus();
event.preventDefault();
}
});
// Tab from the subtitle directly to post content. Borrowed from post.js.
$( '#subtitle' ).on( 'keydown.editor-focus', function( event ) {
var editor, $textarea;
if ( 9 === event.keyCode && ! event.ctrlKey && ! event.altKey && ! event.shiftKey ) {
editor = 'undefined' !== typeof tinymce && tinymce.get( 'content' );
$textarea = $( '#content' );
if ( editor && ! editor.isHidden() ) {
editor.focus();
} else if ( $textarea.length ) {
$textarea.focus();
} else {
return;
}
event.preventDefault();
}
});
});
}
$( document ).ready( documentScripts );
})( jQuery );
|
var searchData=
[
['enabling_20buffer_20device_20address_0',['Enabling buffer device address',['../enabling_buffer_device_address.html',1,'index']]]
];
|
module.exports=['\u3130','\u3131','\u3132','\u3133','\u3134','\u3135','\u3136','\u3137','\u3138','\u3139','\u313A','\u313B','\u313C','\u313D','\u313E','\u313F','\u3140','\u3141','\u3142','\u3143','\u3144','\u3145','\u3146','\u3147','\u3148','\u3149','\u314A','\u314B','\u314C','\u314D','\u314E','\u314F','\u3150','\u3151','\u3152','\u3153','\u3154','\u3155','\u3156','\u3157','\u3158','\u3159','\u315A','\u315B','\u315C','\u315D','\u315E','\u315F','\u3160','\u3161','\u3162','\u3163','\u3164','\u3165','\u3166','\u3167','\u3168','\u3169','\u316A','\u316B','\u316C','\u316D','\u316E','\u316F','\u3170','\u3171','\u3172','\u3173','\u3174','\u3175','\u3176','\u3177','\u3178','\u3179','\u317A','\u317B','\u317C','\u317D','\u317E','\u317F','\u3180','\u3181','\u3182','\u3183','\u3184','\u3185','\u3186','\u3187','\u3188','\u3189','\u318A','\u318B','\u318C','\u318D','\u318E','\u318F'] |
'use strict';
var files = require('./angularFiles').files;
var util = require('./lib/grunt/utils.js');
var versionInfo = require('./lib/versions/version-info');
var path = require('path');
var e2e = require('./test/e2e/tools');
module.exports = function(grunt) {
//grunt plugins
require('load-grunt-tasks')(grunt);
grunt.loadTasks('lib/grunt');
grunt.loadNpmTasks('angular-benchpress');
var NG_VERSION = versionInfo.currentVersion;
NG_VERSION.cdn = versionInfo.cdnVersion;
var dist = 'angular-'+ NG_VERSION.full;
//config
grunt.initConfig({
NG_VERSION: NG_VERSION,
bp_build: {
options: {
buildPath: 'build/benchmarks',
benchmarksPath: 'benchmarks'
}
},
connect: {
devserver: {
options: {
port: 8000,
hostname: '0.0.0.0',
base: '.',
keepalive: true,
middleware: function(connect, options){
var base = Array.isArray(options.base) ? options.base[options.base.length - 1] : options.base;
return [
util.conditionalCsp(),
util.rewrite(),
e2e.middleware(),
connect.favicon('images/favicon.ico'),
connect.static(base),
connect.directory(base)
];
}
}
},
testserver: {
options: {
// We use end2end task (which does not start the webserver)
// and start the webserver as a separate process (in travis_build.sh)
// to avoid https://github.com/joyent/libuv/issues/826
port: 8000,
hostname: '0.0.0.0',
middleware: function(connect, options){
var base = Array.isArray(options.base) ? options.base[options.base.length - 1] : options.base;
return [
function(req, resp, next) {
// cache get requests to speed up tests on travis
if (req.method === 'GET') {
resp.setHeader('Cache-control', 'public, max-age=3600');
}
next();
},
util.conditionalCsp(),
e2e.middleware(),
connect.favicon('images/favicon.ico'),
connect.static(base)
];
}
}
}
},
tests: {
jqlite: 'karma-jqlite.conf.js',
jquery: 'karma-jquery.conf.js',
docs: 'karma-docs.conf.js',
modules: 'karma-modules.conf.js'
},
autotest: {
jqlite: 'karma-jqlite.conf.js',
jquery: 'karma-jquery.conf.js',
modules: 'karma-modules.conf.js',
docs: 'karma-docs.conf.js'
},
protractor: {
normal: 'protractor-conf.js',
travis: 'protractor-travis-conf.js',
jenkins: 'protractor-jenkins-conf.js'
},
clean: {
build: ['build'],
tmp: ['tmp']
},
jshint: {
options: {
jshintrc: true,
},
node: {
files: { src: ['*.js', 'lib/**/*.js'] },
},
tests: {
files: { src: 'test/**/*.js' },
},
ng: {
files: { src: files['angularSrc'] },
},
ngAnimate: {
files: { src: 'src/ngAnimate/**/*.js' },
},
ngCookies: {
files: { src: 'src/ngCookies/**/*.js' },
},
ngLocale: {
files: { src: 'src/ngLocale/**/*.js' },
},
ngMessages: {
files: { src: 'src/ngMessages/**/*.js' },
},
ngMock: {
files: { src: 'src/ngMock/**/*.js' },
},
ngResource: {
files: { src: 'src/ngResource/**/*.js' },
},
ngRoute: {
files: { src: 'src/ngRoute/**/*.js' },
},
ngSanitize: {
files: { src: 'src/ngSanitize/**/*.js' },
},
ngScenario: {
files: { src: 'src/ngScenario/**/*.js' },
},
ngTouch: {
files: { src: 'src/ngTouch/**/*.js' },
},
ngAria: {
files: {src: 'src/ngAria/**/*.js'},
}
},
jscs: {
src: ['src/**/*.js', 'test/**/*.js'],
options: {
config: ".jscs.json"
}
},
build: {
scenario: {
dest: 'build/angular-scenario.js',
src: [
'bower_components/jquery/dist/jquery.js',
util.wrap([files['angularSrc'], files['angularScenario']], 'ngScenario/angular')
],
styles: {
css: ['css/angular.css', 'css/angular-scenario.css']
}
},
angular: {
dest: 'build/angular.js',
src: util.wrap([files['angularSrc']], 'angular'),
styles: {
css: ['css/angular.css'],
generateCspCssFile: true,
minify: true
}
},
loader: {
dest: 'build/angular-loader.js',
src: util.wrap(files['angularLoader'], 'loader')
},
touch: {
dest: 'build/angular-touch.js',
src: util.wrap(files['angularModules']['ngTouch'], 'module')
},
mocks: {
dest: 'build/angular-mocks.js',
src: util.wrap(files['angularModules']['ngMock'], 'module'),
strict: false
},
sanitize: {
dest: 'build/angular-sanitize.js',
src: util.wrap(files['angularModules']['ngSanitize'], 'module')
},
resource: {
dest: 'build/angular-resource.js',
src: util.wrap(files['angularModules']['ngResource'], 'module')
},
messages: {
dest: 'build/angular-messages.js',
src: util.wrap(files['angularModules']['ngMessages'], 'module')
},
animate: {
dest: 'build/angular-animate.js',
src: util.wrap(files['angularModules']['ngAnimate'], 'module')
},
route: {
dest: 'build/angular-route.js',
src: util.wrap(files['angularModules']['ngRoute'], 'module')
},
cookies: {
dest: 'build/angular-cookies.js',
src: util.wrap(files['angularModules']['ngCookies'], 'module')
},
aria: {
dest: 'build/angular-aria.js',
src: util.wrap(files['angularModules']['ngAria'], 'module')
},
"promises-aplus-adapter": {
dest:'tmp/promises-aplus-adapter++.js',
src:['src/ng/q.js','lib/promises-aplus/promises-aplus-test-adapter.js']
}
},
min: {
angular: 'build/angular.js',
animate: 'build/angular-animate.js',
cookies: 'build/angular-cookies.js',
loader: 'build/angular-loader.js',
messages: 'build/angular-messages.js',
touch: 'build/angular-touch.js',
resource: 'build/angular-resource.js',
route: 'build/angular-route.js',
sanitize: 'build/angular-sanitize.js',
aria: 'build/angular-aria.js'
},
"ddescribe-iit": {
files: [
'src/**/*.js',
'test/**/*.js',
'!test/ngScenario/DescribeSpec.js',
'!src/ng/directive/attrs.js', // legitimate xit here
'!src/ngScenario/**/*.js'
]
},
"merge-conflict": {
files: [
'src/**/*',
'test/**/*',
'docs/**/*',
'css/**/*'
]
},
copy: {
i18n: {
files: [
{ src: 'src/ngLocale/**', dest: 'build/i18n/', expand: true, flatten: true }
]
}
},
compress: {
build: {
options: {archive: 'build/' + dist +'.zip', mode: 'zip'},
src: ['**'],
cwd: 'build',
expand: true,
dot: true,
dest: dist + '/'
}
},
shell: {
"npm-install": {
command: path.normalize('scripts/npm/install-dependencies.sh')
},
"promises-aplus-tests": {
options: {
stdout: false,
stderr: true,
failOnError: true
},
command: path.normalize('./node_modules/.bin/promises-aplus-tests tmp/promises-aplus-adapter++.js')
}
},
write: {
versionTXT: {file: 'build/version.txt', val: NG_VERSION.full},
versionJSON: {file: 'build/version.json', val: JSON.stringify(NG_VERSION)}
},
bump: {
options: {
files: ['package.json'],
commit: false,
createTag: false,
push: false
}
}
});
// global beforeEach task
if (!process.env.TRAVIS) {
grunt.task.run('shell:npm-install');
}
//alias tasks
grunt.registerTask('test', 'Run unit, docs and e2e tests with Karma', ['jshint', 'jscs', 'package','test:unit','test:promises-aplus', 'tests:docs', 'test:protractor']);
grunt.registerTask('test:jqlite', 'Run the unit tests with Karma' , ['tests:jqlite']);
grunt.registerTask('test:jquery', 'Run the jQuery unit tests with Karma', ['tests:jquery']);
grunt.registerTask('test:modules', 'Run the Karma module tests with Karma', ['build', 'tests:modules']);
grunt.registerTask('test:docs', 'Run the doc-page tests with Karma', ['package', 'tests:docs']);
grunt.registerTask('test:unit', 'Run unit, jQuery and Karma module tests with Karma', ['test:jqlite', 'test:jquery', 'test:modules']);
grunt.registerTask('test:protractor', 'Run the end to end tests with Protractor and keep a test server running in the background', ['webdriver', 'connect:testserver', 'protractor:normal']);
grunt.registerTask('test:travis-protractor', 'Run the end to end tests with Protractor for Travis CI builds', ['connect:testserver', 'protractor:travis']);
grunt.registerTask('test:ci-protractor', 'Run the end to end tests with Protractor for Jenkins CI builds', ['webdriver', 'connect:testserver', 'protractor:jenkins']);
grunt.registerTask('test:e2e', 'Alias for test:protractor', ['test:protractor']);
grunt.registerTask('test:promises-aplus',['build:promises-aplus-adapter','shell:promises-aplus-tests']);
grunt.registerTask('minify', ['bower','clean', 'build', 'minall']);
grunt.registerTask('webserver', ['connect:devserver']);
grunt.registerTask('package', ['bower','clean', 'buildall', 'minall', 'collect-errors', 'docs', 'copy', 'write', 'compress']);
grunt.registerTask('ci-checks', ['ddescribe-iit', 'merge-conflict', 'jshint', 'jscs']);
grunt.registerTask('default', ['package']);
};
|
/*jshint eqeqeq:false, eqnull:true */
/*global jQuery, define */
// Grouping module
(function( factory ) {
"use strict";
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([
"jquery",
"./grid.base"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
"use strict";
//module begin
$.jgrid.extend({
groupingSetup : function () {
return this.each(function (){
var $t = this, i, j, cml, cm = $t.p.colModel, grp = $t.p.groupingView,
classes = $.jgrid.styleUI[($t.p.styleUI || 'jQueryUI')].grouping;
if(grp !== null && ( (typeof grp === 'object') || $.isFunction(grp) ) ) {
if(!grp.plusicon) { grp.plusicon = classes.icon_plus;}
if(!grp.minusicon) { grp.minusicon = classes.icon_minus;}
if(!grp.groupField.length) {
$t.p.grouping = false;
} else {
if (grp.visibiltyOnNextGrouping === undefined) {
grp.visibiltyOnNextGrouping = [];
}
grp.lastvalues=[];
if(!grp._locgr) {
grp.groups =[];
}
grp.counters =[];
for(i=0;i<grp.groupField.length;i++) {
if(!grp.groupOrder[i]) {
grp.groupOrder[i] = 'asc';
}
if(!grp.groupText[i]) {
grp.groupText[i] = '{0}';
}
if( typeof grp.groupColumnShow[i] !== 'boolean') {
grp.groupColumnShow[i] = true;
}
if( typeof grp.groupSummary[i] !== 'boolean') {
grp.groupSummary[i] = false;
}
if( !grp.groupSummaryPos[i]) {
grp.groupSummaryPos[i] = 'footer';
}
if(grp.groupColumnShow[i] === true) {
grp.visibiltyOnNextGrouping[i] = true;
$($t).jqGrid('showCol',grp.groupField[i]);
} else {
grp.visibiltyOnNextGrouping[i] = $("#"+$.jgrid.jqID($t.p.id+"_"+grp.groupField[i])).is(":visible");
$($t).jqGrid('hideCol',grp.groupField[i]);
}
}
grp.summary =[];
if(grp.hideFirstGroupCol) {
grp.formatDisplayField[0] = function (v) { return v;};
}
for(j=0, cml = cm.length; j < cml; j++) {
if(grp.hideFirstGroupCol) {
if(!cm[j].hidden && grp.groupField[0] === cm[j].name) {
cm[j].formatter = function(){return '';};
}
}
if(cm[j].summaryType ) {
if(cm[j].summaryDivider) {
grp.summary.push({nm:cm[j].name,st:cm[j].summaryType, v: '', sd:cm[j].summaryDivider, vd:'', sr: cm[j].summaryRound, srt: cm[j].summaryRoundType || 'round'});
} else {
grp.summary.push({nm:cm[j].name,st:cm[j].summaryType, v: '', sr: cm[j].summaryRound, srt: cm[j].summaryRoundType || 'round'});
}
}
}
}
} else {
$t.p.grouping = false;
}
});
},
groupingPrepare : function ( record, irow ) {
this.each(function(){
var grp = this.p.groupingView, $t= this, i,
sumGroups = function() {
if ($.isFunction(this.st)) {
this.v = this.st.call($t, this.v, this.nm, record);
} else {
this.v = $($t).jqGrid('groupingCalculations.handler',this.st, this.v, this.nm, this.sr, this.srt, record);
if(this.st.toLowerCase() === 'avg' && this.sd) {
this.vd = $($t).jqGrid('groupingCalculations.handler',this.st, this.vd, this.sd, this.sr, this.srt, record);
}
}
},
grlen = grp.groupField.length,
fieldName,
v,
displayName,
displayValue,
changed = 0;
for(i=0;i<grlen;i++) {
fieldName = grp.groupField[i];
displayName = grp.displayField[i];
v = record[fieldName];
displayValue = displayName == null ? null : record[displayName];
if( displayValue == null ) {
displayValue = v;
}
if( v !== undefined ) {
if(irow === 0 ) {
// First record always starts a new group
grp.groups.push({idx:i,dataIndex:fieldName,value:v, displayValue: displayValue, startRow: irow, cnt:1, summary : [] } );
grp.lastvalues[i] = v;
grp.counters[i] = {cnt:1, pos:grp.groups.length-1, summary: $.extend(true,[],grp.summary)};
$.each(grp.counters[i].summary, sumGroups);
grp.groups[grp.counters[i].pos].summary = grp.counters[i].summary;
} else {
if (typeof v !== "object" && ($.isArray(grp.isInTheSameGroup) && $.isFunction(grp.isInTheSameGroup[i]) ? ! grp.isInTheSameGroup[i].call($t, grp.lastvalues[i], v, i, grp): grp.lastvalues[i] !== v)) {
// This record is not in same group as previous one
grp.groups.push({idx:i,dataIndex:fieldName,value:v, displayValue: displayValue, startRow: irow, cnt:1, summary : [] } );
grp.lastvalues[i] = v;
changed = 1;
grp.counters[i] = {cnt:1, pos:grp.groups.length-1, summary: $.extend(true,[],grp.summary)};
$.each(grp.counters[i].summary, sumGroups);
grp.groups[grp.counters[i].pos].summary = grp.counters[i].summary;
} else {
if (changed === 1) {
// This group has changed because an earlier group changed.
grp.groups.push({idx:i,dataIndex:fieldName,value:v, displayValue: displayValue, startRow: irow, cnt:1, summary : [] } );
grp.lastvalues[i] = v;
grp.counters[i] = {cnt:1, pos:grp.groups.length-1, summary: $.extend(true,[],grp.summary)};
$.each(grp.counters[i].summary, sumGroups);
grp.groups[grp.counters[i].pos].summary = grp.counters[i].summary;
} else {
grp.counters[i].cnt += 1;
grp.groups[grp.counters[i].pos].cnt = grp.counters[i].cnt;
$.each(grp.counters[i].summary, sumGroups);
grp.groups[grp.counters[i].pos].summary = grp.counters[i].summary;
}
}
}
}
}
//gdata.push( rData );
});
return this;
},
groupingToggle : function(hid){
this.each(function(){
var $t = this,
grp = $t.p.groupingView,
strpos = hid.split('_'),
num = parseInt(strpos[strpos.length-2], 10);
strpos.splice(strpos.length-2,2);
var uid = strpos.join("_"),
minus = grp.minusicon,
plus = grp.plusicon,
tar = $("#"+$.jgrid.jqID(hid)),
r = tar.length ? tar[0].nextSibling : null,
tarspan = $("#"+$.jgrid.jqID(hid)+" span."+"tree-wrap-"+$t.p.direction),
getGroupingLevelFromClass = function (className) {
var nums = $.map(className.split(" "), function (item) {
if (item.substring(0, uid.length + 1) === uid + "_") {
return parseInt(item.substring(uid.length + 1), 10);
}
});
return nums.length > 0 ? nums[0] : undefined;
},
itemGroupingLevel,
showData,
collapsed = false,
skip = false,
frz = $t.p.frozenColumns ? $t.p.id+"_frozen" : false,
tar2 = frz ? $("#"+$.jgrid.jqID(hid), "#"+$.jgrid.jqID(frz) ) : false,
r2 = (tar2 && tar2.length) ? tar2[0].nextSibling : null;
if( tarspan.hasClass(minus) ) {
if(grp.showSummaryOnHide) {
if(r){
while(r) {
itemGroupingLevel = getGroupingLevelFromClass(r.className);
if (itemGroupingLevel !== undefined && itemGroupingLevel <= num) {
break;
}
$(r).hide();
r = r.nextSibling;
if(frz) {
$(r2).hide();
r2 = r2.nextSibling;
}
}
}
} else {
if(r){
while(r) {
itemGroupingLevel = getGroupingLevelFromClass(r.className);
if (itemGroupingLevel !== undefined && itemGroupingLevel <= num) {
break;
}
$(r).hide();
r = r.nextSibling;
if(frz) {
$(r2).hide();
r2 = r2.nextSibling;
}
}
}
}
tarspan.removeClass(minus).addClass(plus);
collapsed = true;
} else {
if(r){
showData = undefined;
while(r) {
itemGroupingLevel = getGroupingLevelFromClass(r.className);
if (showData === undefined) {
showData = itemGroupingLevel === undefined; // if the first row after the opening group is data row then show the data rows
}
skip = $(r).hasClass("ui-subgrid") && $(r).hasClass("ui-sg-collapsed");
if (itemGroupingLevel !== undefined) {
if (itemGroupingLevel <= num) {
break;// next item of the same lever are found
}
if (itemGroupingLevel === num + 1) {
if(!skip) {
$(r).show().find(">td>span."+"tree-wrap-"+$t.p.direction).removeClass(minus).addClass(plus);
if(frz) {
$(r2).show().find(">td>span."+"tree-wrap-"+$t.p.direction).removeClass(minus).addClass(plus);
}
}
}
} else if (showData) {
if(!skip) {
$(r).show();
if(frz) {
$(r2).show();
}
}
}
r = r.nextSibling;
if(frz) {
r2 = r2.nextSibling;
}
}
}
tarspan.removeClass(plus).addClass(minus);
}
$($t).triggerHandler("jqGridGroupingClickGroup", [hid , collapsed]);
if( $.isFunction($t.p.onClickGroup)) { $t.p.onClickGroup.call($t, hid , collapsed); }
});
return false;
},
groupingRender : function (grdata, colspans, page, rn ) {
return this.each(function(){
var $t = this,
grp = $t.p.groupingView,
str = "", icon = "", hid, clid, pmrtl = grp.groupCollapse ? grp.plusicon : grp.minusicon, gv, cp=[], len =grp.groupField.length,
//classes = $.jgrid.styleUI[($t.p.styleUI || 'jQueryUI')]['grouping'],
common = $.jgrid.styleUI[($t.p.styleUI || 'jQueryUI')].common;
pmrtl = pmrtl+" tree-wrap-"+$t.p.direction;
$.each($t.p.colModel, function (i,n){
var ii;
for(ii=0;ii<len;ii++) {
if(grp.groupField[ii] === n.name ) {
cp[ii] = i;
break;
}
}
});
var toEnd = 0;
function findGroupIdx( ind , offset, grp) {
var ret = false, i;
if(offset===0) {
ret = grp[ind];
} else {
var id = grp[ind].idx;
if(id===0) {
ret = grp[ind];
} else {
for(i=ind;i >= 0; i--) {
if(grp[i].idx === id-offset) {
ret = grp[i];
break;
}
}
}
}
return ret;
}
function buildSummaryTd(i, ik, grp, foffset) {
var fdata = findGroupIdx(i, ik, grp),
cm = $t.p.colModel,
vv, grlen = fdata.cnt, str="", k;
for(k=foffset; k<colspans;k++) {
var tmpdata = "<td "+$t.formatCol(k,1,'')+"> </td>",
tplfld = "{0}";
$.each(fdata.summary,function(){
if(this.nm === cm[k].name) {
if(cm[k].summaryTpl) {
tplfld = cm[k].summaryTpl;
}
if(typeof this.st === 'string' && this.st.toLowerCase() === 'avg') {
if(this.sd && this.vd) {
this.v = (this.v/this.vd);
} else if(this.v && grlen > 0) {
this.v = (this.v/grlen);
}
}
try {
this.groupCount = fdata.cnt;
this.groupIndex = fdata.dataIndex;
this.groupValue = fdata.value;
vv = $t.formatter('', this.v, k, this);
} catch (ef) {
vv = this.v;
}
tmpdata= "<td "+$t.formatCol(k,1,'')+">"+$.jgrid.template(tplfld,vv)+ "</td>";
return false;
}
});
str += tmpdata;
}
return str;
}
var sumreverse = $.makeArray(grp.groupSummary), mul;
sumreverse.reverse();
mul = $t.p.multiselect ? " colspan=\"2\"" : "";
$.each(grp.groups,function(i,n){
if(grp._locgr) {
if( !(n.startRow +n.cnt > (page-1)*rn && n.startRow < page*rn)) {
return true;
}
}
toEnd++;
clid = $t.p.id+"ghead_"+n.idx;
hid = clid+"_"+i;
icon = "<span style='cursor:pointer;margin-right:8px;margin-left:5px;' class='" + common.icon_base +" "+pmrtl+"' onclick=\"jQuery('#"+$.jgrid.jqID($t.p.id)+"').jqGrid('groupingToggle','"+hid+"');return false;\"></span>";
try {
if ($.isArray(grp.formatDisplayField) && $.isFunction(grp.formatDisplayField[n.idx])) {
n.displayValue = grp.formatDisplayField[n.idx].call($t, n.displayValue, n.value, $t.p.colModel[cp[n.idx]], n.idx, grp);
gv = n.displayValue;
} else {
gv = $t.formatter(hid, n.displayValue, cp[n.idx], n.value );
}
} catch (egv) {
gv = n.displayValue;
}
var grpTextStr = '';
if($.isFunction(grp.groupText[n.idx])) {
grpTextStr = grp.groupText[n.idx].call($t, gv, n.cnt, n.summary);
} else {
grpTextStr = $.jgrid.template(grp.groupText[n.idx], gv, n.cnt, n.summary);
}
if( !(typeof grpTextStr ==='string' || typeof grpTextStr ==='number' ) ) {
grpTextStr = gv;
}
if(grp.groupSummaryPos[n.idx] === 'header') {
str += "<tr id=\""+hid+"\"" +(grp.groupCollapse && n.idx>0 ? " style=\"display:none;\" " : " ") + "role=\"row\" class= \"" + common.content + " jqgroup ui-row-"+$t.p.direction+" "+clid+"\"><td style=\"padding-left:"+(n.idx * 12) + "px;"+"\"" + mul +">" + icon+grpTextStr + "</td>";
str += buildSummaryTd(i, 0, grp.groups, grp.groupColumnShow[n.idx] === false ? (mul ==="" ? 2 : 3) : ((mul ==="") ? 1 : 2) );
str += "</tr>";
} else {
str += "<tr id=\""+hid+"\"" +(grp.groupCollapse && n.idx>0 ? " style=\"display:none;\" " : " ") + "role=\"row\" class= \"" + common.content + " jqgroup ui-row-"+$t.p.direction+" "+clid+"\"><td style=\"padding-left:"+(n.idx * 12) + "px;"+"\" colspan=\""+(grp.groupColumnShow[n.idx] === false ? colspans-1 : colspans)+"\">" + icon + grpTextStr + "</td></tr>";
}
var leaf = len-1 === n.idx;
if( leaf ) {
var gg = grp.groups[i+1], kk, ik, offset = 0, sgr = n.startRow,
end = gg !== undefined ? gg.startRow : grp.groups[i].startRow + grp.groups[i].cnt;
if(grp._locgr) {
offset = (page-1)*rn;
if(offset > n.startRow) {
sgr = offset;
}
}
for(kk=sgr;kk<end;kk++) {
if(!grdata[kk - offset]) { break; }
str += grdata[kk - offset].join('');
}
if(grp.groupSummaryPos[n.idx] !== 'header') {
var jj;
if (gg !== undefined) {
for (jj = 0; jj < grp.groupField.length; jj++) {
if (gg.dataIndex === grp.groupField[jj]) {
break;
}
}
toEnd = grp.groupField.length - jj;
}
for (ik = 0; ik < toEnd; ik++) {
if(!sumreverse[ik]) { continue; }
var hhdr = "";
if(grp.groupCollapse && !grp.showSummaryOnHide) {
hhdr = " style=\"display:none;\"";
}
str += "<tr"+hhdr+" jqfootlevel=\""+(n.idx-ik)+"\" role=\"row\" class=\"" + common.content + " jqfoot ui-row-"+$t.p.direction+"\">";
str += buildSummaryTd(i, ik, grp.groups, 0);
str += "</tr>";
}
toEnd = jj;
}
}
});
$("#"+$.jgrid.jqID($t.p.id)+" tbody:first").append(str);
// free up memory
str = null;
});
},
groupingGroupBy : function (name, options ) {
return this.each(function(){
var $t = this;
if(typeof name === "string") {
name = [name];
}
var grp = $t.p.groupingView;
$t.p.grouping = true;
grp._locgr = false;
//Set default, in case visibilityOnNextGrouping is undefined
if (grp.visibiltyOnNextGrouping === undefined) {
grp.visibiltyOnNextGrouping = [];
}
var i;
// show previous hidden groups if they are hidden and weren't removed yet
for(i=0;i<grp.groupField.length;i++) {
if(!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
$($t).jqGrid('showCol',grp.groupField[i]);
}
}
// set visibility status of current group columns on next grouping
for(i=0;i<name.length;i++) {
grp.visibiltyOnNextGrouping[i] = $("#"+$.jgrid.jqID($t.p.id)+"_"+$.jgrid.jqID(name[i])).is(":visible");
}
$t.p.groupingView = $.extend($t.p.groupingView, options || {});
grp.groupField = name;
$($t).trigger("reloadGrid");
});
},
groupingRemove : function (current) {
return this.each(function(){
var $t = this;
if(current === undefined) {
current = true;
}
$t.p.grouping = false;
if(current===true) {
var grp = $t.p.groupingView, i;
// show previous hidden groups if they are hidden and weren't removed yet
for(i=0;i<grp.groupField.length;i++) {
if (!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
$($t).jqGrid('showCol', grp.groupField);
}
}
$("tr.jqgroup, tr.jqfoot","#"+$.jgrid.jqID($t.p.id)+" tbody:first").remove();
$("tr.jqgrow:hidden","#"+$.jgrid.jqID($t.p.id)+" tbody:first").show();
} else {
$($t).trigger("reloadGrid");
}
});
},
groupingCalculations : {
handler: function(fn, v, field, round, roundType, rc) {
var funcs = {
sum: function() {
return parseFloat(v||0) + parseFloat((rc[field]||0));
},
min: function() {
if(v==="") {
return parseFloat(rc[field]||0);
}
return Math.min(parseFloat(v),parseFloat(rc[field]||0));
},
max: function() {
if(v==="") {
return parseFloat(rc[field]||0);
}
return Math.max(parseFloat(v),parseFloat(rc[field]||0));
},
count: function() {
if(v==="") {v=0;}
if(rc.hasOwnProperty(field)) {
return v+1;
}
return 0;
},
avg: function() {
// the same as sum, but at end we divide it
// so use sum instead of duplicating the code (?)
return funcs.sum();
}
};
if(!funcs[fn]) {
throw ("jqGrid Grouping No such method: " + fn);
}
var res = funcs[fn]();
if (round != null) {
if (roundType === 'fixed') {
res = res.toFixed(round);
} else {
var mul = Math.pow(10, round);
res = Math.round(res * mul) / mul;
}
}
return res;
}
},
setGroupHeaders : function ( o ) {
o = $.extend({
useColSpanStyle : false,
groupHeaders: []
},o || {});
return this.each(function(){
var ts = this,
i, cmi, skip = 0, $tr, $colHeader, th, $th, thStyle,
iCol,
cghi,
//startColumnName,
numberOfColumns,
titleText,
cVisibleColumns,
className,
colModel = ts.p.colModel,
cml = colModel.length,
ths = ts.grid.headers,
$htable = $("table.ui-jqgrid-htable", ts.grid.hDiv),
$trLabels = $htable.children("thead").children("tr.ui-jqgrid-labels:last").addClass("jqg-second-row-header"),
$thead = $htable.children("thead"),
$theadInTable,
$firstHeaderRow = $htable.find(".jqg-first-row-header"),
//classes = $.jgrid.styleUI[($t.p.styleUI || 'jQueryUI')]['grouping'],
base = $.jgrid.styleUI[(ts.p.styleUI || 'jQueryUI')].base;
if(!ts.p.groupHeader) {
ts.p.groupHeader = [];
}
ts.p.groupHeader.push(o);
if($firstHeaderRow[0] === undefined) {
$firstHeaderRow = $('<tr>', {role: "row", "aria-hidden": "true"}).addClass("jqg-first-row-header").css("height", "auto");
} else {
$firstHeaderRow.empty();
}
var $firstRow,
inColumnHeader = function (text, columnHeaders) {
var length = columnHeaders.length, i;
for (i = 0; i < length; i++) {
if (columnHeaders[i].startColumnName === text) {
return i;
}
}
return -1;
};
$(ts).prepend($thead);
$tr = $('<tr>', {role: "row"}).addClass("ui-jqgrid-labels jqg-third-row-header");
for (i = 0; i < cml; i++) {
th = ths[i].el;
$th = $(th);
cmi = colModel[i];
// build the next cell for the first header row
thStyle = { height: '0px', width: ths[i].width + 'px', display: (cmi.hidden ? 'none' : '')};
$("<th>", {role: 'gridcell'}).css(thStyle).addClass("ui-first-th-"+ts.p.direction).appendTo($firstHeaderRow);
th.style.width = ""; // remove unneeded style
iCol = inColumnHeader(cmi.name, o.groupHeaders);
if (iCol >= 0) {
cghi = o.groupHeaders[iCol];
numberOfColumns = cghi.numberOfColumns;
titleText = cghi.titleText;
className = cghi.className || "";
// caclulate the number of visible columns from the next numberOfColumns columns
for (cVisibleColumns = 0, iCol = 0; iCol < numberOfColumns && (i + iCol < cml); iCol++) {
if (!colModel[i + iCol].hidden) {
cVisibleColumns++;
}
}
// The next numberOfColumns headers will be moved in the next row
// in the current row will be placed the new column header with the titleText.
// The text will be over the cVisibleColumns columns
$colHeader = $('<th>').attr({role: "columnheader"})
.addClass(base.headerBox+ " ui-th-column-header ui-th-"+ts.p.direction+" "+className)
//.css({'height':'22px', 'border-top': '0 none'})
.html(titleText);
if(cVisibleColumns > 0) {
$colHeader.attr("colspan", String(cVisibleColumns));
}
if (ts.p.headertitles) {
$colHeader.attr("title", $colHeader.text());
}
// hide if not a visible cols
if( cVisibleColumns === 0) {
$colHeader.hide();
}
$th.before($colHeader); // insert new column header before the current
$tr.append(th); // move the current header in the next row
// set the coumter of headers which will be moved in the next row
skip = numberOfColumns - 1;
} else {
if (skip === 0) {
if (o.useColSpanStyle) {
// expand the header height to two rows
$th.attr("rowspan", "2");
} else {
$('<th>', {role: "columnheader"})
.addClass(base.headerBox+" ui-th-column-header ui-th-"+ts.p.direction)
.css({"display": cmi.hidden ? 'none' : ''})
.insertBefore($th);
$tr.append(th);
}
} else {
// move the header to the next row
//$th.css({"padding-top": "2px", height: "19px"});
$tr.append(th);
skip--;
}
}
}
$theadInTable = $(ts).children("thead");
$theadInTable.prepend($firstHeaderRow);
$tr.insertAfter($trLabels);
$htable.append($theadInTable);
if (o.useColSpanStyle) {
// Increase the height of resizing span of visible headers
$htable.find("span.ui-jqgrid-resize").each(function () {
var $parent = $(this).parent();
if ($parent.is(":visible")) {
this.style.cssText = 'height: ' + $parent.height() + 'px !important; cursor: col-resize;';
}
});
// Set position of the sortable div (the main lable)
// with the column header text to the middle of the cell.
// One should not do this for hidden headers.
$htable.find("div.ui-jqgrid-sortable").each(function () {
var $ts = $(this), $parent = $ts.parent();
if ($parent.is(":visible") && $parent.is(":has(span.ui-jqgrid-resize)")) {
// minus 4px from the margins of the resize markers
$ts.css('top', ($parent.height() - $ts.outerHeight()) / 2 - 4 + 'px');
}
});
}
$firstRow = $theadInTable.find("tr.jqg-first-row-header");
$(ts).bind('jqGridResizeStop.setGroupHeaders', function (e, nw, idx) {
$firstRow.find('th').eq(idx).width(nw);
});
});
},
destroyGroupHeader : function(nullHeader) {
if(nullHeader === undefined) {
nullHeader = true;
}
return this.each(function()
{
var $t = this, $tr, i, l, headers, $th, $resizing, grid = $t.grid,
thead = $("table.ui-jqgrid-htable thead", grid.hDiv), cm = $t.p.colModel, hc;
if(!grid) { return; }
$(this).unbind('.setGroupHeaders');
$tr = $("<tr>", {role: "row"}).addClass("ui-jqgrid-labels");
headers = grid.headers;
for (i = 0, l = headers.length; i < l; i++) {
hc = cm[i].hidden ? "none" : "";
$th = $(headers[i].el)
.width(headers[i].width)
.css('display',hc);
try {
$th.removeAttr("rowSpan");
} catch (rs) {
//IE 6/7
$th.attr("rowSpan",1);
}
$tr.append($th);
$resizing = $th.children("span.ui-jqgrid-resize");
if ($resizing.length>0) {// resizable column
$resizing[0].style.height = "";
}
$th.children("div")[0].style.top = "";
}
$(thead).children('tr.ui-jqgrid-labels').remove();
$(thead).prepend($tr);
if(nullHeader === true) {
$($t).jqGrid('setGridParam',{ 'groupHeader': null});
}
});
}
});
//module end
}));
|
(function(){$(function(){$.miniNotification=function(e,c){var h,f,k,d,g,l,b=this;this.defaults={position:"top",show:!0,effect:"slide",opacity:0.95,time:4E3,showSpeed:600,hideSpeed:450,showEasing:"",hideEasing:"",innerDivClass:"inner",closeButton:!1,closeButtonText:"close",closeButtonClass:"close",hideOnClick:!0,onLoad:function(){},onVisible:function(){},onHide:function(){},onHidden:function(){}};g="";this.settings={};this.$element=$(e);d=function(a){return g=a};f=function(){var a,c;c="slide"===b.getSetting("effect")?
0-b.$element.outerHeight():0;a={};"bottom"===b.getSetting("position")?a.bottom=c:a.top=c;"fade"===b.getSetting("effect")&&(a.opacity=0);return a};k=function(){var a;a={opacity:b.getSetting("opacity")};"bottom"===b.getSetting("position")?a.bottom=0:a.top=0;return a};l=function(){b.$elementInner=$("<div />",{"class":b.getSetting("innerDivClass")});return b.$element.wrapInner(b.$elementInner)};h=function(){var a;a=$("<a />",{"class":b.getSetting("closeButtonClass"),html:b.getSetting("closeButtonText")});
b.$element.children().append(a);return a.bind("click",function(){return b.hide()})};this.getState=function(){return g};this.getSetting=function(a){return this.settings[a]};this.callSettingFunction=function(a){return this.settings[a](e)};this.init=function(){var a=this;d("hidden");this.settings=$.extend({},this.defaults,c);if(this.$element.length&&(l(),this.getSetting("closeButton")&&h(),this.$element.css(f()).css({display:"inline"}),this.getSetting("show")&&this.show(),this.getSetting("hideOnClick")))return this.$element.bind("click",
function(){if("hiding"!==a.getState())return a.hide()})};this.show=function(){var a=this;if("showing"!==this.getState()&&"visible"!==this.getState())return d("showing"),this.callSettingFunction("onLoad"),this.$element.animate(k(),this.getSetting("showSpeed"),this.getSetting("showEasing"),function(){d("visible");a.callSettingFunction("onVisible");return setTimeout(function(){return a.hide()},a.settings.time)})};this.hide=function(){var a=this;if("hiding"!==this.getState()&&"hidden"!==this.getState())return d("hiding"),
this.callSettingFunction("onHide"),this.$element.animate(f(),this.getSetting("hideSpeed"),this.getSetting("hideEasing"),function(){d("hidden");return a.callSettingFunction("onHidden")})};this.init();return this};return $.fn.miniNotification=function(e){return this.each(function(){var c;c=$(this).data("miniNotification");return void 0===c?(c=new $.miniNotification(this,e),$(this).data("miniNotification",c)):c.show()})}})}).call(this);
|
'use strict';
angular.module('frontendApp')
.controller('MainCtrl', function ($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
});
|
/**
* @callback Phaser.Types.Cameras.Scene2D.CameraShakeCallback
* @since 3.5.0
*
* @param {Phaser.Cameras.Scene2D.Camera} camera - The camera on which the effect is running.
* @param {number} progress - The progress of the effect. A value between 0 and 1.
*/
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.7.3.3_A1;
* @section: 15.7.3.3;
* @assertion: Number.MIN_VALUE is approximately 5e-324;
* @description: Checking Number.MIN_VALUE value;
*/
$INCLUDE("math_precision.js");
$INCLUDE("math_isequal.js");
// CHECK#1
if (!isEqual(Number.MIN_VALUE, 5e-324)) {
$ERROR('#1: Number.MIN_VALUE approximately equal to 5e-324');
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _extends2;
function _load_extends() {
return _extends2 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
}
var _index;
function _load_index() {
return _index = require('../index.js');
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _misc;
function _load_misc() {
return _misc = _interopRequireWildcard(require('../../util/misc.js'));
}
var _version;
function _load_version() {
return _version = _interopRequireWildcard(require('../../util/version.js'));
}
var _index2;
function _load_index2() {
return _index2 = require('../../registries/index.js');
}
var _exoticResolver;
function _load_exoticResolver() {
return _exoticResolver = _interopRequireDefault(require('./exotic-resolver.js'));
}
var _git;
function _load_git() {
return _git = _interopRequireDefault(require('../../util/git.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const urlParse = require('url').parse;
const urlFormat = require('url').format;
// we purposefully omit https and http as those are only valid if they end in the .git extension
const GIT_PROTOCOLS = ['git:', 'git+ssh:', 'git+https:', 'ssh:'];
const GIT_HOSTS = ['github.com', 'gitlab.com', 'bitbucket.com', 'bitbucket.org'];
class GitResolver extends (_exoticResolver || _load_exoticResolver()).default {
constructor(request, fragment) {
super(request, fragment);
var _versionUtil$explodeH = (_version || _load_version()).explodeHashedUrl(fragment);
const url = _versionUtil$explodeH.url,
hash = _versionUtil$explodeH.hash;
this.url = url;
this.hash = hash;
}
static isVersion(pattern) {
const parts = urlParse(pattern);
// this pattern hasn't been exploded yet, we'll hit this code path again later once
// we've been normalized #59
if (!parts.protocol) {
return false;
}
const pathname = parts.pathname;
if (pathname && pathname.endsWith('.git')) {
// ends in .git
return true;
}
if (GIT_PROTOCOLS.indexOf(parts.protocol) >= 0) {
return true;
}
if (parts.hostname && parts.path) {
const path = parts.path;
if (GIT_HOSTS.indexOf(parts.hostname) >= 0) {
// only if dependency is pointing to a git repo,
// e.g. facebook/flow and not file in a git repo facebook/flow/archive/v1.0.0.tar.gz
return path.split('/').filter(p => !!p).length === 2;
}
}
return false;
}
// This transformUrl util is here to replace colon separators in the pathname
// from private urls. It takes the url parts retrieved using urlFormat and
// returns the associated url. Related to #573, introduced in #2519.
static transformUrl(parts) {
const pathname = parts.pathname ? parts.pathname.replace(/^\/:/, '/') : '';
return urlFormat((0, (_extends2 || _load_extends()).default)({}, parts, { pathname: pathname }));
}
resolve(forked) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
let tryRegistry = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (registry) {
const filename = (_index2 || _load_index2()).registries[registry].filename;
const file = yield client.getFile(filename);
if (!file) {
return null;
}
const json = yield config.readJson(`${transformedUrl}/${filename}`, function () {
return JSON.parse(file);
});
json._uid = commit;
json._remote = {
resolved: `${transformedUrl}#${commit}`,
type: 'git',
reference: transformedUrl,
hash: commit,
registry: registry
};
return json;
});
return function tryRegistry(_x) {
return _ref.apply(this, arguments);
};
})();
const url = _this.url;
// shortcut for hosted git. we will fallback to a GitResolver if the hosted git
// optimisations fail which the `forked` flag indicates so we don't get into an
// infinite loop
const parts = urlParse(url);
if (false && !forked && !parts.auth && parts.pathname) {
// check if this git url uses any of the hostnames defined in our hosted git resolvers
for (const name in (_index || _load_index()).hostedGit) {
const Resolver = (_index || _load_index()).hostedGit[name];
if (Resolver.hostname !== parts.hostname) {
continue;
}
// we have a match! clean up the pathname of url artifacts
let pathname = parts.pathname;
pathname = (_misc || _load_misc()).removePrefix(pathname, '/'); // remove prefixed slash
pathname = (_misc || _load_misc()).removeSuffix(pathname, '.git'); // remove .git suffix if present
const url = `${pathname}${_this.hash ? '#' + decodeURIComponent(_this.hash) : ''}`;
return _this.fork(Resolver, false, url);
}
}
// get from lockfile
const shrunk = _this.request.getLocked('git');
if (shrunk) {
return shrunk;
}
const config = _this.config;
const transformedUrl = GitResolver.transformUrl(parts);
const client = new (_git || _load_git()).default(config, transformedUrl, _this.hash);
const commit = yield client.init();
const file = yield tryRegistry(_this.registry);
if (file) {
return file;
}
for (const registry in (_index2 || _load_index2()).registries) {
if (registry === _this.registry) {
continue;
}
const file = yield tryRegistry(registry);
if (file) {
return file;
}
}
throw new (_errors || _load_errors()).MessageError(_this.reporter.lang('couldntFindManifestIn', transformedUrl));
})();
}
}
exports.default = GitResolver; |
module.exports = {
purge: ['./components/**/*.js', './pages/**/*.js'],
theme: {
extend: {
colors: {
'accent-1': '#FAFAFA',
'accent-2': '#EAEAEA',
'accent-7': '#333',
success: '#0070f3',
cyan: '#79FFE1',
},
spacing: {
28: '7rem',
},
letterSpacing: {
tighter: '-.04em',
},
lineHeight: {
tight: 1.2,
},
fontSize: {
'5xl': '2.5rem',
'6xl': '2.75rem',
'7xl': '4.5rem',
'8xl': '6.25rem',
},
boxShadow: {
small: '0 5px 10px rgba(0, 0, 0, 0.12)',
medium: '0 8px 30px rgba(0, 0, 0, 0.12)',
},
},
},
}
|
'use strict'
const assert = require('assert')
const Buffer = require('buffer').Buffer
const binding = process.binding('zlib')
const constants = exports.constants = require('./constants.js')
const MiniPass = require('minipass')
// translation table for return codes.
const codes = new Map([
[constants.Z_OK, 'Z_OK'],
[constants.Z_STREAM_END, 'Z_STREAM_END'],
[constants.Z_NEED_DICT, 'Z_NEED_DICT'],
[constants.Z_ERRNO, 'Z_ERRNO'],
[constants.Z_STREAM_ERROR, 'Z_STREAM_ERROR'],
[constants.Z_DATA_ERROR, 'Z_DATA_ERROR'],
[constants.Z_MEM_ERROR, 'Z_MEM_ERROR'],
[constants.Z_BUF_ERROR, 'Z_BUF_ERROR'],
[constants.Z_VERSION_ERROR, 'Z_VERSION_ERROR']
])
const validFlushFlags = new Set([
constants.Z_NO_FLUSH,
constants.Z_PARTIAL_FLUSH,
constants.Z_SYNC_FLUSH,
constants.Z_FULL_FLUSH,
constants.Z_FINISH,
constants.Z_BLOCK
])
const strategies = new Set([
constants.Z_FILTERED,
constants.Z_HUFFMAN_ONLY,
constants.Z_RLE,
constants.Z_FIXED,
constants.Z_DEFAULT_STRATEGY
])
// the Zlib class they all inherit from
// This thing manages the queue of requests, and returns
// true or false if there is anything in the queue when
// you call the .write() method.
const _opts = Symbol('opts')
const _chunkSize = Symbol('chunkSize')
const _flushFlag = Symbol('flushFlag')
const _finishFlush = Symbol('finishFlush')
const _handle = Symbol('handle')
const _hadError = Symbol('hadError')
const _buffer = Symbol('buffer')
const _offset = Symbol('offset')
const _level = Symbol('level')
const _strategy = Symbol('strategy')
const _ended = Symbol('ended')
class Zlib extends MiniPass {
constructor (opts, mode) {
super(opts)
this[_ended] = false
this[_opts] = opts = opts || {}
this[_chunkSize] = opts.chunkSize || constants.Z_DEFAULT_CHUNK
if (opts.flush && !validFlushFlags.has(opts.flush)) {
throw new Error('Invalid flush flag: ' + opts.flush)
}
if (opts.finishFlush && !validFlushFlags.has(opts.finishFlush)) {
throw new Error('Invalid flush flag: ' + opts.finishFlush)
}
this[_flushFlag] = opts.flush || constants.Z_NO_FLUSH
this[_finishFlush] = typeof opts.finishFlush !== 'undefined' ?
opts.finishFlush : constants.Z_FINISH
if (opts.chunkSize) {
if (opts.chunkSize < constants.Z_MIN_CHUNK) {
throw new Error('Invalid chunk size: ' + opts.chunkSize)
}
}
if (opts.windowBits) {
if (opts.windowBits < constants.Z_MIN_WINDOWBITS ||
opts.windowBits > constants.Z_MAX_WINDOWBITS) {
throw new Error('Invalid windowBits: ' + opts.windowBits)
}
}
if (opts.level) {
if (opts.level < constants.Z_MIN_LEVEL ||
opts.level > constants.Z_MAX_LEVEL) {
throw new Error('Invalid compression level: ' + opts.level)
}
}
if (opts.memLevel) {
if (opts.memLevel < constants.Z_MIN_MEMLEVEL ||
opts.memLevel > constants.Z_MAX_MEMLEVEL) {
throw new Error('Invalid memLevel: ' + opts.memLevel)
}
}
if (opts.strategy && !(strategies.has(opts.strategy)))
throw new Error('Invalid strategy: ' + opts.strategy)
if (opts.dictionary) {
if (!(opts.dictionary instanceof Buffer)) {
throw new Error('Invalid dictionary: it should be a Buffer instance')
}
}
this[_handle] = new binding.Zlib(mode)
this[_hadError] = false
this[_handle].onerror = (message, errno) => {
// there is no way to cleanly recover.
// continuing only obscures problems.
this.close()
this[_hadError] = true
const error = new Error(message)
error.errno = errno
error.code = codes.get(errno)
this.emit('error', error)
}
const level = typeof opts.level === 'number' ? opts.level
: constants.Z_DEFAULT_COMPRESSION
var strategy = typeof opts.strategy === 'number' ? opts.strategy
: constants.Z_DEFAULT_STRATEGY
this[_handle].init(opts.windowBits || constants.Z_DEFAULT_WINDOWBITS,
level,
opts.memLevel || constants.Z_DEFAULT_MEMLEVEL,
strategy,
opts.dictionary)
this[_buffer] = Buffer.allocUnsafe(this[_chunkSize])
this[_offset] = 0
this[_level] = level
this[_strategy] = strategy
this.once('end', this.close)
}
close () {
if (this[_handle]) {
this[_handle].close()
this[_handle] = null
this.emit('close')
}
}
params (level, strategy) {
if (!this[_handle])
throw new Error('cannot switch params when binding is closed')
// no way to test this without also not supporting params at all
/* istanbul ignore if */
if (!this[_handle].params)
throw new Error('not supported in this implementation')
if (level < constants.Z_MIN_LEVEL ||
level > constants.Z_MAX_LEVEL) {
throw new RangeError('Invalid compression level: ' + level)
}
if (!(strategies.has(strategy)))
throw new TypeError('Invalid strategy: ' + strategy)
if (this[_level] !== level || this[_strategy] !== strategy) {
this.flush(constants.Z_SYNC_FLUSH)
assert(this[_handle], 'zlib binding closed')
this[_handle].params(level, strategy)
/* istanbul ignore else */
if (!this[_hadError]) {
this[_level] = level
this[_strategy] = strategy
}
}
}
reset () {
assert(this[_handle], 'zlib binding closed')
return this[_handle].reset()
}
flush (kind) {
if (kind === undefined)
kind = constants.Z_FULL_FLUSH
if (this.ended)
return
const flushFlag = this[_flushFlag]
this[_flushFlag] = kind
this.write(Buffer.alloc(0))
this[_flushFlag] = flushFlag
}
end (chunk, encoding, cb) {
if (chunk)
this.write(chunk, encoding)
this.flush(this[_finishFlush])
this[_ended] = true
return super.end(null, null, cb)
}
get ended () {
return this[_ended]
}
write (chunk, encoding, cb) {
// process the chunk using the sync process
// then super.write() all the outputted chunks
if (typeof encoding === 'function')
cb = encoding, encoding = 'utf8'
if (typeof chunk === 'string')
chunk = new Buffer(chunk, encoding)
let availInBefore = chunk && chunk.length
let availOutBefore = this[_chunkSize] - this[_offset]
let inOff = 0 // the offset of the input buffer
const flushFlag = this[_flushFlag]
let writeReturn = true
assert(this[_handle], 'zlib binding closed')
do {
let res = this[_handle].writeSync(
flushFlag,
chunk, // in
inOff, // in_off
availInBefore, // in_len
this[_buffer], // out
this[_offset], //out_off
availOutBefore // out_len
)
if (this[_hadError])
break
let availInAfter = res[0]
let availOutAfter = res[1]
const have = availOutBefore - availOutAfter
assert(have >= 0, 'have should not go down')
if (have > 0) {
const out = this[_buffer].slice(
this[_offset], this[_offset] + have
)
this[_offset] += have
// serve some output to the consumer.
writeReturn = super.write(out) && writeReturn
}
// exhausted the output buffer, or used all the input create a new one.
if (availOutAfter === 0 || this[_offset] >= this[_chunkSize]) {
availOutBefore = this[_chunkSize]
this[_offset] = 0
this[_buffer] = Buffer.allocUnsafe(this[_chunkSize])
}
if (availOutAfter === 0) {
// Not actually done. Need to reprocess.
// Also, update the availInBefore to the availInAfter value,
// so that if we have to hit it a third (fourth, etc.) time,
// it'll have the correct byte counts.
inOff += (availInBefore - availInAfter)
availInBefore = availInAfter
continue
}
break
} while (!this[_hadError])
if (cb)
cb()
return writeReturn
}
}
// minimal 2-byte header
class Deflate extends Zlib {
constructor (opts) {
super(opts, constants.DEFLATE)
}
}
class Inflate extends Zlib {
constructor (opts) {
super(opts, constants.INFLATE)
}
}
// gzip - bigger header, same deflate compression
class Gzip extends Zlib {
constructor (opts) {
super(opts, constants.GZIP)
}
}
class Gunzip extends Zlib {
constructor (opts) {
super(opts, constants.GUNZIP)
}
}
// raw - no header
class DeflateRaw extends Zlib {
constructor (opts) {
super(opts, constants.DEFLATERAW)
}
}
class InflateRaw extends Zlib {
constructor (opts) {
super(opts, constants.INFLATERAW)
}
}
// auto-detect header.
class Unzip extends Zlib {
constructor (opts) {
super(opts, constants.UNZIP)
}
}
exports.Deflate = Deflate
exports.Inflate = Inflate
exports.Gzip = Gzip
exports.Gunzip = Gunzip
exports.DeflateRaw = DeflateRaw
exports.InflateRaw = InflateRaw
exports.Unzip = Unzip
|
'use strict';
var util = require('./util.js');
/**
* Check if an argument seems to be a number
**/
function isNumericalArgument(arg) {
return (/^[\d\-.,]+$/).test(arg);
}
/**
* Check if an arguments item is an option or an option's argument
**/
function isAnOption(arg) {
return arg[0] === '-' && !isNumericalArgument(arg);
}
/**
* Process an arguments list and refactorizes it replacing each -a=b element for two new elements: -a and b
**/
function preProcessArguments (argv) {
var processedArgs = [];
argv.forEach(function (arg) {
// If the argument is not an option, do not touch it
if (arg[0] !== '-' || isNumericalArgument(arg)) {
processedArgs.push(arg);
return;
}
// For collapsed options, like "-abc" instead of "-a -b -c"
if (arg[0] === '-' && arg[1] !== '-' && arg.length > 2 && arg.indexOf('=') === -1) {
processedArgs = processedArgs.concat(arg.slice(1).split('').map(function (x) {
return '-' + x;
}));
return;
}
// The general case, without collapsed options or assignments
if (arg[0] !== '-' || arg.indexOf('=') === -1) {
processedArgs.push(arg);
return;
}
// For assignment options, like "-b=2" instead of "-b 2"
arg = arg.match(/(.*?)=(.*)/);
processedArgs.push(arg[1]);
processedArgs.push(arg[2]);
});
return processedArgs;
}
/**
* Builds an arguments map from a processed arguments list and a getopt() options object
**/
function extractArgumentsMap (argv, config) {
/**
* Find the nearest option of a provided one
**/
function getNearestOption(option) {
var options = Object.keys(config);
var minDistance = Infinity;
var nearestWord = null;
options.forEach(function (o) {
var d = util.textDistance(o, option);
if (d < minDistance) {
minDistance = d;
nearestWord = o;
}
});
if (minDistance < 3) {
return nearestWord;
}
return null;
}
/**
* Find the option name of an argument key
**/
function getOptionNameFromArgument (key) {
// If key is a large form, then it is the option name itself
if (key.indexOf('--') === 0) {
return key.slice(2);
}
// If key is a short form, then we have to find the option name
key = key.slice(1);
for (var option in config) {
if (config[option].key === key) {
return option;
}
}
// If no name is found, throw an error
console.log('Unknown option: "-' + key + '".');
console.log('Try "--help" for more information.');
process.exit(-1);
}
/**
* Check if all arguments have been already specified for an option
**/
function isOptionCompleted (option) {
// args option is never fully specified, so any free argument is always a part of it
if (option === 'args') {
return false;
}
// Multiple arguments are not fully specified. They can be repeated many times
if (config[option].multiple) {
return false;
}
// Variable arguments count
if (config[option].args === '*') {
return false;
}
// Get the expected arguments count
var expected = config[option].args;
if (expected && typeof expected !== 'number') {
throw new Error('"args" attribute has to be a number or the string "*" when specifying getopt() settings');
}
// Compute how many arguments have been already specified and how many ones are expected
var argsCount = 0;
if (config[option]) {
if (Array.isArray(options[option])) {
argsCount = options[option].length;
} else if (options[option] !== true){
argsCount = 1;
} else {
argsCount = 0;
}
}
return !expected || (argsCount === expected);
}
// Remove "node" and "program.js", then preprocess arguments array
argv = argv.slice(2);
argv = preProcessArguments(argv);
var options = {};
var lastArgument;
for (var i = 0, len = argv.length; i < len; i++) {
// Not allowed arguments
if (argv[i] === '-' || argv[i] == '--') {
console.log('Wrong argument provided: "%s".\nTry "--help" for more information.', argv[i]);
process.exit(-1);
}
if (isAnOption(argv[i])) {
// It is an option name (not an argument for an option)
lastArgument = getOptionNameFromArgument(argv[i]);
if (!config[lastArgument]) {
var strError = 'Unknown option "--' + lastArgument + '".';
var suggestion = getNearestOption(lastArgument);
if (suggestion) {
strError += ' Did you mean "--' + suggestion + '"?';
}
strError += '\nTry "--help" for more information.';
console.log(strError);
process.exit(-1);
}
options[lastArgument] = options[lastArgument] || true;
} else {
// It is an argument for an option
if (!lastArgument || isOptionCompleted(lastArgument)) {
lastArgument = 'args';
} else if ((config[lastArgument] || {}).multiple && i > 0 && !isAnOption(argv[i - 1])) {
lastArgument = 'args';
}
if (options[lastArgument] === true) {
options[lastArgument] = argv[i];
} else if (Array.isArray(options[lastArgument])) {
options[lastArgument].push(argv[i]);
} else if (lastArgument === 'args') {
options[lastArgument] = [argv[i]];
} else {
options[lastArgument] = [options[lastArgument]];
options[lastArgument].push(argv[i]);
}
}
}
return options;
}
/**
* Core getopt function
**/
function getopt (config, helpTail, argv, testing) {
argv = argv || process.argv;
config = config || {};
var programName = argv[1].split('/').pop();
// Help option cannot be overrided
if (config.help) {
throw new Error('"--help" option is reserved for the automatic help message. You cannot override it when calling getopt().');
}
var usedKeys = {};
var key, option;
for (option in config) {
key = config[option].key;
if (!key) {
continue;
}
// Short options name has to be unique
if (usedKeys[key]) {
throw new Error('Short key "' + key + '" is repeated in getopt() config. You cannot use the same key for two options.');
}
// Multiple option is not compatible with args count
if (config[option].multiple && ('args' in config[option])) {
throw new Error('"args" count cannot be specified for options marked with "multiple" flag.');
}
usedKeys[key] = true;
}
// Print help message when executing with --help or -h
if (argv.indexOf('--help') !== -1) {
printHelpMessage(config, helpTail, programName);
process.exit(0);
}
// Build de options/arguments map
var cmdOptions = extractArgumentsMap(argv, config);
// Check every mandatory option is specified
for (option in config) {
if (option === '_meta_') {
continue;
}
if (config[option].mandatory && !(option in cmdOptions)) {
if (testing) {
return null;
}
console.log('Missing "%s" argument.\nTry "--help" for more information.', option);
process.exit(-1);
}
if (!(option in cmdOptions)) {
continue;
}
// Check all required arguments have been specified for each option
var requiredArgumentsCount = config[option].args;
var providedArgumentsCount = cmdOptions[option] === true ? 0 : (Array.isArray(cmdOptions[option]) ? cmdOptions[option].length : 1);
if (requiredArgumentsCount > 1 && providedArgumentsCount !== requiredArgumentsCount) {
if (testing) {
return null;
}
console.log('Option "--%s" requires %d arguments, but %d were provided. Try "--help" for more information.', option, requiredArgumentsCount, providedArgumentsCount);
printHelpMessage(config, helpTail, programName);
process.exit(-1);
}
}
// Check expected positional arguments are provided
var providedArgs = 0;
if (Array.isArray(cmdOptions.args) && cmdOptions.args.length > 0) {
providedArgs = cmdOptions.args.length;
}
if (config._meta_ && config._meta_.args && providedArgs !== config._meta_.args) {
console.log('%d positional arguments (without option flag) are required, but %d have been provided.', config._meta_.args, providedArgs);
printHelpMessage(config, helpTail, programName);
process.exit(-1);
}
if (config._meta_ && config._meta_.minArgs && providedArgs < config._meta_.minArgs) {
console.log('At least %d positional arguments (without option flag) are required, but %d have been provided.', config._meta_.minArgs, providedArgs);
printHelpMessage(config, helpTail, programName);
process.exit(-1);
}
if (config._meta_ && config._meta_.maxArgs && providedArgs > config._meta_.maxArgs) {
console.log('Too many positional arguments (without option flag) provided. The maximum allowed is %d, but %d have been provided.', config._meta_.maxArgs, providedArgs);
printHelpMessage(config, helpTail, programName);
process.exit(-1);
}
// Apply default values
for (option in config) {
if (typeof config[option] === 'object' && 'default' in config[option]) {
if ((!Array.isArray(config[option]['default']) && parseInt(config[option].args, 10) > 1) ||
(Array.isArray(config[option]['default']) && config[option]['default'].length !== parseInt(config[option].args, 10))) {
throw new Error('Default value of an option must have the same length as specified by its "args" attribute');
}
cmdOptions[option] = cmdOptions[option] || config[option]['default'];
}
}
// A function to print help message manually
cmdOptions.printHelp = function () {
printHelpMessage(config, helpTail, programName);
};
return cmdOptions;
}
/**
* Prints the help (--help, -h)
**/
function printHelpMessage(options, helpTail, programName) {
helpTail = helpTail || 'node ' + programName + ' [OPTION1] [OPTION2]... arg1 arg2...';
console.log('USAGE:', helpTail);
console.log('The following options are supported:');
var o = null, lines = [], maxLength;
for (o in options) {
if (o === '_meta_') {
continue;
}
if (options.hasOwnProperty(o)) {
var ops = ' ', i;
if (options[o].multiple) {
options[o].args = 1;
}
for (i = 0; i < options[o].args; i++) {
ops += '<ARG' + (i + 1) + '> ';
}
if (options[o].args === '*') {
ops += '<ARG1>...<ARGN>';
}
lines.push([' ' + (options[o].key ? '-' + options[o].key + ', --' : '--') + o + ops, (options[o].description || '') + (options[o].mandatory ? ' (mandatory)' : '') + (options[o].multiple ? ' (multiple)' : '' + (options[o]['default'] ? ' ("' + options[o]['default'] + '" by default)' : ''))]);
}
}
maxLength = lines.reduce(function (prev, curr) {
var aux = curr[0].length;
if (aux > prev) {
return aux;
}
return prev;
}, 0);
lines = lines.map(function (l) {
return l[0] + (new Array(maxLength - l[0].length + 1)).join(' ') + '\t' + l[1];
});
console.log(lines.join('\n'));
}
// Exports
module.exports.getopt = getopt;
module.exports.preProcessArguments = preProcessArguments;
|
module.exports = {
'chat': function (browser) {
browser
.url('http://localhost:8080/chat/')
.waitForElementVisible('.chatapp', 1000)
.assert.containsText('.thread-count', 'Unread threads: 2')
.assert.count('.thread-list-item', 3)
.assert.containsText('.thread-list-item.active', 'Functional Heads')
.assert.containsText('.message-thread-heading', 'Functional Heads')
.assert.count('.message-list-item', 2)
.assert.containsText('.message-list-item:nth-child(1) .message-author-name', 'Bill')
.assert.containsText('.message-list-item:nth-child(1) .message-text', 'Hey Brian')
.enterValue('.message-composer', 'hi')
.waitFor(50) // fake api
.assert.count('.message-list-item', 3)
.assert.containsText('.message-list-item:nth-child(3)', 'hi')
.click('.thread-list-item:nth-child(2)')
.assert.containsText('.thread-list-item.active', 'Dave and Bill')
.assert.containsText('.message-thread-heading', 'Dave and Bill')
.assert.count('.message-list-item', 2)
.assert.containsText('.message-list-item:nth-child(1) .message-author-name', 'Bill')
.assert.containsText('.message-list-item:nth-child(1) .message-text', 'Hey Dave')
.enterValue('.message-composer', 'hi')
.waitFor(50) // fake api
.assert.count('.message-list-item', 3)
.assert.containsText('.message-list-item:nth-child(3)', 'hi')
}
}
|
/*
* rhtml_highlight_rules.js
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var RHighlightRules = require("./r_highlight_rules").RHighlightRules;
var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var RHtmlHighlightRules = function() {
HtmlHighlightRules.call(this);
this.$rules["start"].unshift({
token: "support.function.codebegin",
regex: "^<" + "!--\\s*begin.rcode\\s*(?:.*)",
next: "r-start"
});
this.embedRules(RHighlightRules, "r-", [{
token: "support.function.codeend",
regex: "^\\s*end.rcode\\s*-->",
next: "start"
}], ["start"]);
this.normalizeRules();
};
oop.inherits(RHtmlHighlightRules, TextHighlightRules);
exports.RHtmlHighlightRules = RHtmlHighlightRules;
});
|
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var strings={prefixAgo:"cách đây",prefixFromNow:null,suffixAgo:null,suffixFromNow:"trước",seconds:"chưa đến 1 phút",minute:"khoảng 1 phút",minutes:"%d phút",hour:"khoảng 1 tiếng",hours:"khoảng %d tiếng",day:"1 ngày",days:"%d ngày",month:"khoảng 1 tháng",months:"%d tháng",year:"khoảng 1 năm",years:"%d năm",wordSeparator:" "},_default=strings;exports.default=_default; |
/**
`Ember.ViewTargetActionSupport` is a mixin that can be included in a
view class to add a `triggerAction` method with semantics similar to
the Handlebars `{{action}}` helper. It provides intelligent defaults
for the action's target: the view's controller; and the context that is
sent with the action: the view's context.
Note: In normal Ember usage, the `{{action}}` helper is usually the best
choice. This mixin is most often useful when you are doing more complex
event handling in custom View subclasses.
For example:
```javascript
App.SaveButtonView = Ember.View.extend(Ember.ViewTargetActionSupport, {
action: 'save',
click: function(){
this.triggerAction(); // Sends the `save` action, along with the current context
// to the current controller
}
});
```
The `action` can be provided as properties of an optional object argument
to `triggerAction` as well.
```javascript
App.SaveButtonView = Ember.View.extend(Ember.ViewTargetActionSupport, {
click: function(){
this.triggerAction({
action: 'save'
}); // Sends the `save` action, along with the current context
// to the current controller
}
});
```
@class ViewTargetActionSupport
@namespace Ember
@extends Ember.TargetActionSupport
*/
Ember.ViewTargetActionSupport = Ember.Mixin.create(Ember.TargetActionSupport, {
/**
@property target
*/
target: Ember.computed.alias('controller'),
/**
@property actionContext
*/
actionContext: Ember.computed.alias('context')
});
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) :
typeof define === 'function' && define.amd ? define(['jquery'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jQuery));
}(this, (function ($) { 'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var $__default = /*#__PURE__*/_interopDefaultLegacy($);
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
/**
* @author: Jewway
* @update zhixin wen <[email protected]>
*/
$__default['default'].fn.bootstrapTable.methods.push('changeTitle');
$__default['default'].fn.bootstrapTable.methods.push('changeLocale');
$__default['default'].BootstrapTable = /*#__PURE__*/function (_$$BootstrapTable) {
_inherits(_class, _$$BootstrapTable);
var _super = _createSuper(_class);
function _class() {
_classCallCheck(this, _class);
return _super.apply(this, arguments);
}
_createClass(_class, [{
key: "changeTitle",
value: function changeTitle(locale) {
$__default['default'].each(this.options.columns, function (idx, columnList) {
$__default['default'].each(columnList, function (idx, column) {
if (column.field) {
column.title = locale[column.field];
}
});
});
this.initHeader();
this.initBody();
this.initToolbar();
}
}, {
key: "changeLocale",
value: function changeLocale(localeId) {
this.options.locale = localeId;
this.initLocale();
this.initPagination();
this.initBody();
this.initToolbar();
}
}]);
return _class;
}($__default['default'].BootstrapTable);
})));
|
goog.provide('ol.test.color');
describe('ol.color', function() {
describe('ol.color.asArray()', function() {
it('returns the same for an array', function() {
var color = [1, 2, 3, 0.4];
var got = ol.color.asArray(color);
expect(got).to.be(color);
});
it('returns an array given an rgba string', function() {
var color = ol.color.asArray('rgba(1,2,3,0.4)');
expect(color).to.eql([1, 2, 3, 0.4]);
});
it('returns an array given an rgb string', function() {
var color = ol.color.asArray('rgb(1,2,3)');
expect(color).to.eql([1, 2, 3, 1]);
});
it('returns an array given a hex string', function() {
var color = ol.color.asArray('#00ccff');
expect(color).to.eql([0, 204, 255, 1]);
});
});
describe('ol.color.asString()', function() {
it('returns the same for a string', function() {
var color = 'rgba(0,1,2,0.3)';
var got = ol.color.asString(color);
expect(got).to.be(color);
});
it('returns a string given an rgba array', function() {
var color = ol.color.asString([1, 2, 3, 0.4]);
expect(color).to.eql('rgba(1,2,3,0.4)');
});
it('returns a string given an rgb array', function() {
var color = ol.color.asString([1, 2, 3]);
expect(color).to.eql('rgba(1,2,3,1)');
});
});
describe('ol.color.fromString', function() {
before(function() {
sinon.spy(ol.color, 'fromStringInternal_');
});
after(function() {
ol.color.fromStringInternal_.restore();
});
if (ol.ENABLE_NAMED_COLORS) {
it('can parse named colors', function() {
expect(ol.color.fromString('red')).to.eql([255, 0, 0, 1]);
});
}
it('can parse 3-digit hex colors', function() {
expect(ol.color.fromString('#087')).to.eql([0, 136, 119, 1]);
});
it('can parse 6-digit hex colors', function() {
expect(ol.color.fromString('#56789a')).to.eql([86, 120, 154, 1]);
});
it('can parse rgb colors', function() {
expect(ol.color.fromString('rgb(0, 0, 255)')).to.eql([0, 0, 255, 1]);
});
it('can parse rgba colors', function() {
expect(ol.color.fromString('rgba(255, 255, 0, 0.1)')).to.eql(
[255, 255, 0, 0.1]);
});
if (ol.ENABLE_NAMED_COLORS) {
it('caches parsed values', function() {
var count = ol.color.fromStringInternal_.callCount;
ol.color.fromString('aquamarine');
expect(ol.color.fromStringInternal_.callCount).to.be(count + 1);
ol.color.fromString('aquamarine');
expect(ol.color.fromStringInternal_.callCount).to.be(count + 1);
});
}
it('throws an error on invalid colors', function() {
var invalidColors = ['tuesday', '#1234567', 'rgb(255.0,0,0)'];
var i, ii;
for (i = 0, ii < invalidColors.length; i < ii; ++i) {
expect(function() {
ol.color.fromString(invalidColors[i]);
}).to.throwException();
}
});
});
describe('ol.color.isValid', function() {
it('identifies valid colors', function() {
expect(ol.color.isValid([0, 0, 0, 0])).to.be(true);
expect(ol.color.isValid([255, 255, 255, 1])).to.be(true);
});
it('identifies out-of-range channels', function() {
expect(ol.color.isValid([-1, 0, 0, 0])).to.be(false);
expect(ol.color.isValid([256, 0, 0, 0])).to.be(false);
expect(ol.color.isValid([0, -1, 0, 0])).to.be(false);
expect(ol.color.isValid([0, 256, 0, 0])).to.be(false);
expect(ol.color.isValid([0, 0, -1, 0])).to.be(false);
expect(ol.color.isValid([0, 0, 256, 0])).to.be(false);
expect(ol.color.isValid([0, 0, -1, 0])).to.be(false);
expect(ol.color.isValid([0, 0, 256, 0])).to.be(false);
expect(ol.color.isValid([0, 0, 0, -1])).to.be(false);
expect(ol.color.isValid([0, 0, 0, 2])).to.be(false);
});
});
describe('ol.color.normalize', function() {
it('clamps out-of-range channels', function() {
expect(ol.color.normalize([-1, 256, 0, 2])).to.eql([0, 255, 0, 1]);
});
it('rounds color channels to integers', function() {
expect(ol.color.normalize([1.2, 2.5, 3.7, 1])).to.eql([1, 3, 4, 1]);
});
});
describe('ol.color.toString', function() {
it('converts valid colors', function() {
expect(ol.color.toString([1, 2, 3, 0.4])).to.be('rgba(1,2,3,0.4)');
});
it('rounds to integers if needed', function() {
expect(ol.color.toString([1.2, 2.5, 3.7, 0.4])).to.be('rgba(1,3,4,0.4)');
});
it('sets default alpha value if undefined', function() {
expect(ol.color.toString([0, 0, 0])).to.be('rgba(0,0,0,1)');
});
});
});
goog.require('ol.color');
|
/*
David Cramer
<david AT thingbag DOT net>
Kasun Gajasinghe
<kasunbg AT gmail DOT com>
Copyright © 2008-2012 Kasun Gajasinghe, David Cramer
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:
1. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
2. Except as contained in this notice, the names of individuals credited with contribution to this software shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from the individuals in question.
3. Any stylesheet derived from this Software that is publicly distributed will be identified with a different name and the version strings in any derived Software will be changed so that no possibility of confusion between the derived package and this Software will exist.
Warranty: 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 DAVID CRAMER, KASUN GAJASINGHE, OR ANY OTHER CONTRIBUTOR 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.
*/
/*
List of modifications added by the Oxygen Webhelp plugin:
1. Make sure the space-separated words from the search query are
passed to the search function realSearch() in all cases (the
total number of words can be less than or greater than 10 words).
2. Accept as valid search words a sequence of two words separated
by ':', '.' or '-'.
3. Convert the search query to lowercase before executing the search.
4. Do not omit words between angle brackets from the title of the
search results.
5. Normalize search results HREFs and add '#' for no-frames webhelp
6. Keep custom footer in TOC after searching some text
7. Accept as valid search words that contains only 2 characters
*/
// Return true if "word1" starts with "word2"
function startsWith(word1, word2) {
var prefix = false;
if (word1 !== null && word2 !== null) {
if (word2.length <= word1.length) {
prefix = true;
for (var i = 0; i < word2.length; i++) {
if (word1.charAt(i) !== word2.charAt(i)) {
prefix = false;
break;
}
}
}
} else {
if (word1 !== null) {
prefix = true;
}
}
return prefix;
}
if (!("console" in window) || !("firebug" in console)) {
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
window.console = {};
for (var i = 0, len = names.length; i < len; ++i) {
window.console[names[i]] = function () {
};
}
}
function logLocal(msg){
console.log(msg);
}
if (typeof debug !== 'function') {
function debug(msg, obj) {
if ( withFrames ){
if (typeof parent.debug !== 'function') {
logLocal(msg);
}else{
if (typeof msg!=="undefined"){
if (typeof msg==="object"){
parent.debug('['+src+']',msg);
}else{
parent.debug('['+src+']'+msg,obj);
}
}
}
}else{
logLocal(msg);
}
}
}
var useCJKTokenizing = false;
var w = {};
var searchTextField = '';
var no = 0;
var noWords = [];
var partialSearch2 = "excluded.terms";
var warningMsg = '<div style="padding: 5px;margin-right:5px;;background-color:#FFFF00;">';
warningMsg += '<b>Please note that due to security settings, Google Chrome does not highlight';
warningMsg += ' the search results.</b><br>';
warningMsg += 'This happens only when the WebHelp files are loaded from the local file system.<br>';
warningMsg += 'Workarounds:';
warningMsg += '<ul>';
warningMsg += '<li>Try using another web browser.</li>';
warningMsg += '<li>Deploy the WebHelp files on a web server.</li>';
warningMsg += '</div>';
var txt_filesfound = 'Results';
var txt_enter_at_least_1_char = "Search string can't be void";
var txt_enter_at_least_2_char = "Search string must have at least two characters";
var txt_enter_more_than_10_words = "Only first 10 words will be processed.";
var txt_browser_not_supported = "Your browser is not supported. Use of Mozilla Firefox is recommended.";
var txt_please_wait = "Please wait. Search in progress...";
var txt_results_for = "Results for:";
var result=new Pages([]);
var excluded=[];
var realSearchQuery;
var defaultOperator = "or";
var stackResults = [];
/**
* @description This function make a search request. If all necessary resources are loaded search occurs
* otherwise search will be delayed until all resources are loaded.
*/
function searchRequest() {
$('#search').trigger('click');
var ditaSearch_Form = document.getElementById('searchForm');
var ready = setInterval(function () {
if (searchLoaded) {
$('#loadingError').remove();
SearchToc(ditaSearch_Form);
clearInterval(ready);
} else {
if ($('#loadingError').length < 1) {
$('#searchResults').prepend('<span id="loadingError">' + getLocalization('Loading, please wait ...') + '</span>');
}
}
}, 100);
}
/**
* List of all known operators
* @type {string[]}
*/
var knownOperators = ["and", "or", "not"];
/**
* @description Execute the search and display results after splitting a given query into different arrays that will contain search terms and
* operators
* @param searchQuery
*/
function searchAndDisplayResults(searchQuery) {
var searchTerms = searchQuery.toLowerCase().split(" ");
var toSearch = [];
var operators = [];
for (var i=0;i<searchTerms.length;i++) {
if (!inArray(searchTerms[i], knownOperators)) {
toSearch.push(searchTerms[i]);
} else {
operators.push(searchTerms[i]);
}
}
searchQuery = normalizeQuery(searchQuery);
computeResults(searchQuery);
displayResults(stackResults[0]);
}
/**
* @description Normalize query so that we have an operator between each two adjacent search terms. We'll add the defaultOperator if the
* operator is missing.
* e.g: If the defaultOperator is "and" the "iris flower" query will be "iris and flower"
* @param query Search query
* @return {string} Normalized query
*/
function normalizeQuery(query) {
debug("normalizeQuery("+query+")");
query = query.trim();
query = query.replace(/\( /g, "(");
query = query.replace(/ \)/g, ")");
query = query.replace(/ -/g, "-");
query = query.replace(/- /g, "-");
query = query.replace(/-/g, " and ");
query = query.replace(/ and or /g, " or ");
query = query.replace(/^not /g, "");
query = query.replace(/ or and /g, " or ");
var regex = " " + defaultOperator + " " + defaultOperator + " ";
query = query.replace(new RegExp(regex,"g"), " " + defaultOperator + " ");
query = query.replace(/ not and /g, " not ");
query = query.replace(/ and not /g, " not ");
query = query.replace(/ or not /g, " not ");
query = query.trim();
query = query.indexOf("or ")==0 ? query.substring(3) : query;
query = query.indexOf("and ")==0 ? query.substring(4) : query;
query = query.indexOf("not ")==0 ? query.substring(4) : query;
query = (query.lastIndexOf(" or")==query.length-3 && query.lastIndexOf(" or")!=-1) ? query.substring(0,query.lastIndexOf(" or")) : query;
query = (query.lastIndexOf(" and")==query.length-4 && query.lastIndexOf(" and")!=-1) ? query.substring(0,query.lastIndexOf(" and")) : query;
query = (query.lastIndexOf(" not")==query.length-4 && query.lastIndexOf(" not")!=-1) ? query.substring(0,query.lastIndexOf(" not")) : query;
var result = "";
try {
result = query.toLowerCase().trim().replace(/ /g, " " + defaultOperator + " ");
result = result.replace(/ or and or /g, " and ");
result = result.replace(/ or not or /g, " not ");
result = result.replace(/ or or or /g, " or ");
result = result.replace(/ and and and /g, " and ");
result = result.replace(/ and or /g, " or ");
result = result.replace(/ not or /g, " not ");
result = result.replace(/ or not /g, " not ");
result = result.replace(/ or and /g, " or ");
result = result.replace(/ not and /g, " not ");
result = result.replace(/ and not /g, " not ");
} catch (e) {
debug(e);
}
return result;
}
/**
* @description Convert search expression from infix notation to reverse polish notation (RPN): iris and flower => iris flower and
* @param {string} search Search expression to be converted. e.g.: iris and flower or (gerbera not salvia)
*/
function computeResults(search) {
debug("computeResults("+search+")");
var stringToStore="";
var stack=[];
var item = "";
var items = [];
for (var i=0;i<search.length;i++) {
if (search[i]!=" " && search[i]!="(" && search[i]!=")") {
item+=search[i];
}
if (search[i]==" ") {
if (item!="") {
items.push(item);
item = "";
}
}
if (search[i]=="(") {
if (item!="") {
items.push(item);
items.push("(");
item = "";
} else {
items.push("(");
}
}
if (search[i]==")") {
if (item!="") {
items.push(item);
items.push(")");
item = "";
} else {
items.push(")");
}
}
}
if (item!="") {
items.push(item);
item="";
}
for (i=0;i<items.length;i++) {
if (isTerm(items[i])) {
stringToStore+=items[i] + " ";
}
if (inArray(items[i], knownOperators)) {
while (stack.length>0 && inArray(stack[stack.length-1],knownOperators)) {
stringToStore+=stack.pop() + " ";
}
stack.push(items[i]);
} else if (items[i]=="(") {
stack.push(items[i]);
} else if (items[i]==")") {
var popped = stack.pop();
while (popped!="(") {
stringToStore+=popped + " ";
popped = stack.pop();
}
}
}
while (stack.length > 0) {
stringToStore+=stack.pop() + " ";
}
calculateRPN(stringToStore);
}
/**
* @description Compute results from a RPN expression
* @param {string} rpn Expression in Reverse Polish notation
*/
function calculateRPN(rpn) {
debug("calculate("+rpn+")");
var lastResult;
var rpnTokens = trim(rpn);
rpnTokens = rpnTokens.split(' ');
var result;
for(var i=0;i<rpnTokens.length;i++) {
var token = rpnTokens[i];
if (isTerm(token)) {
result = realSearch(token);
if (result.length > 0) {
stackResults.push(new Pages(result[0]));
} else {
stackResults.push(new Pages([]));
}
} else {
switch (token) {
case "and":
lastResult = stackResults.pop();
if (lastResult.value !== undefined) {
stackResults.push(stackResults.pop().and(lastResult));
}
break;
case "or":
lastResult = stackResults.pop();
if (lastResult.value !== undefined) {
stackResults.push(stackResults.pop().or(lastResult));
}
break;
case "not":
lastResult = stackResults.pop();
if (lastResult.value !== undefined) {
stackResults.push(stackResults.pop().not(lastResult));
}
break;
default:
debug("Error in calculateRPN(string) Method!");
break;
}
}
}
}
/**
* @description Tests if a given string is a valid search term or not
* @param {string} string String to look for in the known operators list
* @return {boolean} TRUE if the search string is a search term
* FALSE if the search string is not a search term
*/
function isTerm(string) {
return !inArray(string, knownOperators) && string.indexOf("(") == -1 && string.indexOf(")") == -1;
}
/**
* @description Search for an element into an array
* @param needle Searched element
* @param haystack Array of elements
* @return {boolean} TRUE if the searched element is part of the array
* FALSE otherwise
*/
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
/**
* @description This function find all matches using the search term
* @param {HTMLObjectElement} ditaSearch_Form The search form from WebHelp page as HTML Object
*/
function SearchToc(ditaSearch_Form) {
debug('SearchToc(..)');
result = new Pages([]);
noWords = [];
excluded = [];
stackResults = [];
//START - EXM-30790
var $searchResults = $("#searchResults");
var footer = $searchResults.find(".footer");
//END - EXM-30790
// Check browser compatibility
if (navigator.userAgent.indexOf("Konquerer") > -1) {
alert(getLocalization(txt_browser_not_supported));
return;
}
searchTextField = trim(ditaSearch_Form.textToSearch.value);
// Eliminate the cross site scripting possibility.
searchTextField = searchTextField.replace(/</g, " ")
.replace(/>/g, " ")
.replace(/"/g, " ")
.replace(/'/g, " ")
.replace(/=/g, " ")
.replace(/0\\/g, " ")
.replace(/\\/g, " ")
.replace(/\//g, " ")
.replace(/ +/g, " ");
var expressionInput = searchTextField;
debug('Search for: ' + expressionInput);
var wordsArray = [];
var splittedExpression = expressionInput.split(" ");
for (var t in splittedExpression) {
if (!contains(stopWords, splittedExpression[t]) || contains(knownOperators, splittedExpression[t])) {
wordsArray.push(splittedExpression[t]);
} else {
excluded.push(splittedExpression[t]);
}
}
expressionInput = wordsArray.join(" ");
realSearchQuery = expressionInput;
if (expressionInput.trim().length > 0 || excluded.length > 0) {
searchAndDisplayResults(expressionInput);
//START - EXM-30790
$searchResults.append(footer);
$searchResults.scrollTop(0);
//END - EXM-30790
}
clearHighlights();
ditaSearch_Form.textToSearch.focus();
}
var stemQueryMap = []; // A hashtable which maps stems to query words
var scriptLetterTab = null;
/**
* @description This function parses the search expression and loads the indices.
* @param {String} expressionInput A single search term to search for.
* @return {Array} Array with the resulted pages and indices.
*/
function realSearch(expressionInput) {
expressionInput = trim(expressionInput);
debug('realSearch("' + expressionInput + '")');
/**
*data initialisation
*/
scriptLetterTab = new Scriptfirstchar(); // Array containing the first letter of each word to look for
var finalWordsList = []; // Array with the words to look for after removing spaces
var fileAndWordList = [];
var txt_wordsnotfound = "";
/* EXM-26412 */
expressionInput = expressionInput.toLowerCase();
/* START - EXM-20414 */
var searchFor = expressionInput.replace(/<\//g, "_st_").replace(/\$_/g, "_di_").replace(/%2C|%3B|%21|%3A|@|\/|\*/g, " ").replace(/(%20)+/g, " ").replace(/_st_/g, "</").replace(/_di_/g, "%24_");
/* END - EXM-20414 */
searchFor = searchFor.replace(/ +/g, " ");
searchFor = searchFor.replace(/ $/, "").replace(/^ /, "");
var wordsList = [searchFor];
debug('words from search:', wordsList);
// set the tokenizing method
useCJKTokenizing = !!(typeof indexerLanguage != "undefined" && (indexerLanguage == "zh" || indexerLanguage == "ko"));
//If Lucene CJKTokenizer was used as the indexer, then useCJKTokenizing will be true. Else, do normal tokenizing.
// 2-gram tokenizing happens in CJKTokenizing,
// If doStem then make tokenize with Stemmer
//var finalArray;
if (doStem) {
if (useCJKTokenizing) {
// Array of words
finalWordsList = cjkTokenize(wordsList);
} else {
// Array of words
finalWordsList = tokenize(wordsList);
}
} else if (useCJKTokenizing) {
// Array of words
finalWordsList = cjkTokenize(wordsList);
debug('CJKTokenizing, finalWordsList: ' + finalWordsList);
} else {
finalWordsList = [searchFor];
}
if (!useCJKTokenizing) {
/**
* Compare with the indexed words (in the w[] array), and push words that are in it to tempTab.
*/
var tempTab = [];
var wordsArray = '';
for (var t in finalWordsList) {
if (!contains(stopWords, finalWordsList[t])) {
if (doStem || finalWordsList[t].toString().length == 2) {
if (w[finalWordsList[t].toString()] == undefined) {
txt_wordsnotfound += finalWordsList[t] + " ";
} else {
tempTab.push(finalWordsList[t]);
}
} else {
var searchedValue = finalWordsList[t].toString();
var listOfWordsStartWith = wordsStartsWith(searchedValue);
if (listOfWordsStartWith != undefined) {
listOfWordsStartWith = listOfWordsStartWith.substr(0, listOfWordsStartWith.length - 1);
wordsArray = listOfWordsStartWith.split(",");
for (var i in wordsArray) {
tempTab.push(wordsArray[i]);
}
}
}
}
}
finalWordsList = tempTab;
finalWordsList = removeDuplicate(finalWordsList);
}
for (var word in txt_wordsnotfound.split(" ")) {
if (!inArray(word, noWords) && word.length>1) {
noWords.push(word);
}
}
if (finalWordsList.length) {
fileAndWordList = SortResults(finalWordsList, expressionInput);
} else {
noWords.push(expressionInput);
}
return fileAndWordList;
}
/**
* @description Display results in HTML format
* @param {Array} fileAndWordList Array with pages and indices that will be displayed
*/
function displayResults(fileAndWordList) {
var linkTab = [];
var results = "";
var txt_wordsnotfound = "";
for (var i = 0; i < excluded.length; i++) {
txt_wordsnotfound += excluded[i] + " ";
}
if (fileAndWordList.value !== undefined) {
var allPages = fileAndWordList.sort().value;
if (excluded.length > 0) {
var tempString = "<p>" + getLocalization(partialSearch2) + " " + txt_wordsnotfound + "</p>";
linkTab.push(tempString);
}
if (realSearchQuery.length > 0) {
linkTab.push("<p>" + getLocalization(txt_results_for) + " " + "<span class=\"searchExpression\">" + realSearchQuery + "</span>" + "</p>");
}
linkTab.push("<ul class='searchresult'>");
var ttScore_first = 1;
if (allPages.length > 0) {
ttScore_first = allPages[0].scoring;
}
for (var page = 0; page < allPages.length; page++) {
debug("Page number: " + page);
var hundredPercent = allPages[page].scoring + 100 * allPages[page].motsnb;
var numberOfWords = allPages[page].motsnb;
debug("hundredPercent: " + hundredPercent + "; ttScore_first: " + ttScore_first + "; numberOfWords: " + numberOfWords);
var ttInfo = allPages[page].filenb;
// Get scoring
var ttScore = allPages[page].scoring;
debug('score for' + allPages[page].motslisteDisplay + ' = ' + ttScore);
var tempInfo = fil[ttInfo];
var pos1 = tempInfo.indexOf("@@@");
var pos2 = tempInfo.lastIndexOf("@@@");
var tempPath = tempInfo.substring(0, pos1);
// EXM-27709 START
// Display words between '<' and '>' in title of search results.
var tempTitle = tempInfo.substring(pos1 + 3, pos2)
.replace(/</g, "<").replace(/>/g, ">");
// EXM-27709 END
var tempShortDesc = tempInfo.substring(pos2 + 3, tempInfo.length);
if (tempPath == 'toc.html') {
continue;
}
//var split = allPages[page].motsliste.split(",");
var finalArray = allPages[page].motsliste.split(", ");
debug(finalArray);
var arrayString = 'Array(';
for (var x in finalArray) {
if (finalArray[x].length >= 2 || useCJKTokenizing || (indexerLanguage == "ja" && finalArray[x].length >= 1)) {
arrayString += "'" + finalArray[x] + "',";
}
}
arrayString = arrayString.substring(0, arrayString.length - 1) + ")";
var idLink = 'foundLink' + page;
var link = 'return openAndHighlight(\'' + tempPath + '\', ' + arrayString + '\)';
var linkString = '<li><a id="' + idLink + '" href="' + tempPath + '" class="foundResult" onclick="' + link + '">' + tempTitle + '</a>';
// Fake value
var maxNumberOfWords = allPages[page].motsnb;
var starWidth = (ttScore * 100 / hundredPercent) / (ttScore_first / hundredPercent) * (numberOfWords / maxNumberOfWords);
starWidth = starWidth < 10 ? (starWidth + 5) : starWidth;
// Keep the 5 stars format
if (starWidth > 85) {
starWidth = 85;
}
// Also check if we have a valid description
if ((tempShortDesc != "null" && tempShortDesc != '...')) {
linkString += "\n<div class=\"shortdesclink\">" + tempShortDesc + "</div>";
}
try {
if (webhelpSearchRanking) {
// Add rating values for scoring at the list of matches
linkString += "<div id=\"rightDiv\">";
linkString += "<div id=\"star\">";
linkString += "<div id=\"star0\" class=\"star\">";
linkString += "<div id=\"starCur0\" class=\"curr\" style=\"width: " + starWidth + "px;\"> </div>";
linkString += "</div>";
linkString += "<br style=\"clear: both;\">";
linkString += "</div>";
linkString += "</div>";
}
} catch (e) {
debug(e);
}
linkString += "</li>";
linkTab.push(linkString);
}
linkTab.push("</ul>");
if (linkTab.length > 2) {
results = "<p>";
for (var t in linkTab) {
results += linkTab[t].toString();
}
results += "</p>";
} else {
results = "<p>" + getLocalization("Search no results") + " " + "<span class=\"searchExpression\">" + txt_wordsnotfound + "</span>" + "</p>";
}
} else {
results = "<p>" + getLocalization("Search no results") + " " + "<span class=\"searchExpression\">" + txt_wordsnotfound + "</span>" + "</p>";
}
// Verify if the browser is Google Chrome and the WebHelp is used on a local machine
// If browser is Google Chrome and WebHelp is used on a local machine a warning message will appear
// Highlighting will not work in this conditions. There is 2 workarounds
if (notLocalChrome) {
document.getElementById('searchResults').innerHTML = results;
} else {
document.getElementById('searchResults').innerHTML = warningMsg + results;
}
$("#search").trigger('click');
}
// Return true if "word" value is an element of "arrayOfWords"
function contains(arrayOfWords, word) {
var found = true;
if (word.length >= 2 || (indexerLanguage == "ja" && word.length >= 1)) {
found = false;
for (var w in arrayOfWords) {
if (arrayOfWords[w] === word) {
found = true;
break;
}
}
}
return found;
}
// Look for elements that start with searchedValue.
function wordsStartsWith(searchedValue) {
var toReturn = '';
for (var sv in w) {
if (sv.toLowerCase().indexOf(searchedValue.toLowerCase()) == 0) {
toReturn += sv + ",";
}
}
return toReturn.length > 0 ? toReturn : undefined;
}
function tokenize(wordsList) {
debug('tokenize(' + wordsList + ')');
var stemmedWordsList = []; // Array with the words to look for after removing spaces
var cleanwordsList = []; // Array with the words to look for
for (var j in wordsList) {
var word = wordsList[j];
if (typeof stemmer != "undefined" && doStem) {
stemQueryMap[stemmer(word)] = word;
} else {
stemQueryMap[word] = word;
}
}
debug('scriptLetterTab in tokenize: ', scriptLetterTab);
scriptLetterTab.add('s');
//stemmedWordsList is the stemmed list of words separated by spaces.
for (var t in wordsList) {
if (wordsList.hasOwnProperty(t)) {
wordsList[t] = wordsList[t].replace(/(%22)|^-/g, "");
if (wordsList[t] != "%20") {
var firstChar = wordsList[t].charAt(0);
scriptLetterTab.add(firstChar);
cleanwordsList.push(wordsList[t]);
}
}
}
if (typeof stemmer != "undefined" && doStem) {
//Do the stemming using Porter's stemming algorithm
for (var i = 0; i < cleanwordsList.length; i++) {
var stemWord = stemmer(cleanwordsList[i]);
stemmedWordsList.push(stemWord);
}
} else {
stemmedWordsList = cleanwordsList;
}
return stemmedWordsList;
}
//Invoker of CJKTokenizer class methods.
function cjkTokenize(wordsList) {
var allTokens = [];
var notCJKTokens = [];
debug('in cjkTokenize(), wordsList: ', wordsList);
for (var j = 0; j < wordsList.length; j++) {
var word = wordsList[j];
debug('in cjkTokenize(), next word: ', word);
if (getAvgAsciiValue(word) < 127) {
notCJKTokens.push(word);
} else {
debug('in cjkTokenize(), use CJKTokenizer');
var tokenizer = new CJKTokenizer(word);
var tokensTmp = tokenizer.getAllTokens();
allTokens = allTokens.concat(tokensTmp);
debug('in cjkTokenize(), found new tokens: ', allTokens);
}
}
allTokens = allTokens.concat(tokenize(notCJKTokens));
return allTokens;
}
//A simple way to determine whether the query is in english or not.
function getAvgAsciiValue(word) {
var tmp = 0;
var num = word.length < 5 ? word.length : 5;
for (var i = 0; i < num; i++) {
if (i == 5) break;
tmp += word.charCodeAt(i);
}
return tmp / num;
}
//CJKTokenizer
function CJKTokenizer(input) {
this.input = input;
this.offset = -1;
this.tokens = [];
this.incrementToken = incrementToken;
this.tokenize = tokenize;
this.getAllTokens = getAllTokens;
this.unique = unique;
function incrementToken() {
if (this.input.length - 2 <= this.offset) {
return false;
} else {
this.offset += 1;
return true;
}
}
function tokenize() {
return this.input.substring(this.offset, this.offset + 2);
}
function getAllTokens() {
while (this.incrementToken()) {
var tmp = this.tokenize();
this.tokens.push(tmp);
}
return this.unique(this.tokens);
}
function unique(a) {
var r = [];
o:for (var i = 0, n = a.length; i < n; i++) {
for (var x = 0, y = r.length; x < y; x++) {
if (r[x] == a[i]) continue o;
}
r[r.length] = a[i];
}
return r;
}
}
/* Scriptfirstchar: to gather the first letter of index js files to upload */
function Scriptfirstchar() {
this.strLetters = "";
}
Scriptfirstchar.prototype.add = function (caract) {
if (typeof this.strLetters == 'undefined') {
this.strLetters = caract;
} else if (this.strLetters.indexOf(caract) < 0) {
this.strLetters += caract;
}
return 0;
};
/* end of scriptfirstchar */
// Array.unique( strict ) - Remove duplicate values
function unique(tab) {
debug("unique(",tab,")");
var a = [];
var i;
var l = tab.length;
if (tab[0] != undefined) {
a[0] = tab[0];
}
else {
return -1;
}
for (i = 1; i < l; i++) {
if (indexof(a, tab[i], 0) < 0) {
a.push(tab[i]);
}
}
return a;
}
function indexof(tab, element, begin) {
for (var i = begin; i < tab.length; i++) {
if (tab[i] == element) {
return i;
}
}
return -1;
}
/* end of Array functions */
/**
* This function creates an hashtable:
* - The key is the index of an HTML file which contains a word to look for.
* - The value is the list of all words contained in the HTML file.
*
* @param {Array} words - list of words to look for.
* @param {String} searchedWord - search term typed by user
* @return {Array} - the hashtable fileAndWordList
*/
function SortResults(words, searchedWord) {
var fileAndWordList = {};
if (words.length == 0 || words[0].length == 0) {
return null;
}
// In generated js file we add scoring at the end of the word
// Example word1*scoringForWord1,word2*scoringForWord2 and so on
// Split after * to obtain the right values
var scoringArr = [];
for (var t in words) {
// get the list of the indices of the files.
var listNumerosDesFicStr = w[words[t].toString()];
var tab = listNumerosDesFicStr.split(",");
//for each file (file's index):
for (var t2 in tab) {
var tmp = '';
var idx;
var temp = tab[t2].toString();
if (temp.indexOf('*') != -1) {
idx = temp.indexOf('*');
tmp = temp.substring(idx + 3, temp.length);
temp = temp.substring(0, idx);
}
scoringArr.push(tmp);
if (fileAndWordList[temp] == undefined) {
fileAndWordList[temp] = "" + words[t];
} else {
fileAndWordList[temp] += "," + words[t];
}
}
}
var fileAndWordListValuesOnly = [];
// sort results according to values
var temptab = [];
var finalObj = [];
for (t in fileAndWordList) {
finalObj.push(new newObj(t, fileAndWordList[t]));
}
finalObj = removeDerivates(finalObj, searchedWord);
for (t in finalObj) {
tab = finalObj[t].wordList.split(',');
var tempDisplay = [];
for (var x in tab) {
if (stemQueryMap[tab[x]] != undefined && doStem) {
tempDisplay.push(stemQueryMap[tab[x]]); //get the original word from the stem word.
} else {
tempDisplay.push(tab[x]); //no stem is available. (probably a CJK language)
}
}
var tempDispString = tempDisplay.join(", ");
var index;
for (x in fileAndWordList) {
if (x === finalObj[t].filesNo) {
index = x;
break;
}
}
var scoring = findRating(fileAndWordList[index], index);
temptab.push(new resultPerFile(finalObj[t].filesNo, finalObj[t].wordList, tab.length, tempDispString, scoring));
fileAndWordListValuesOnly.push(finalObj[t].wordList);
}
debug("fileAndWordListValuesOnly: ", fileAndWordListValuesOnly);
fileAndWordListValuesOnly = unique(fileAndWordListValuesOnly);
fileAndWordListValuesOnly = fileAndWordListValuesOnly.sort(compareWords);
var listToOutput = [];
for (var j in fileAndWordListValuesOnly) {
for (t in temptab) {
if (temptab[t].motsliste == fileAndWordListValuesOnly[j]) {
if (listToOutput[j] == undefined) {
listToOutput[j] = new Array(temptab[t]);
} else {
listToOutput[j].push(temptab[t]);
}
}
}
}
// Sort results by scoring, descending on the same group
for (var i in listToOutput) {
listToOutput[i].sort(function (a, b) {
return b.scoring - a.scoring;
});
}
// If we have groups with same number of words,
// will sort groups by higher scoring of each group
for (i = 0; i < listToOutput.length - 1; i++) {
for (j = i + 1; j < listToOutput.length; j++) {
if (listToOutput[i][0].motsnb < listToOutput[j][0].motsnb
|| (listToOutput[i][0].motsnb == listToOutput[j][0].motsnb
&& listToOutput[i][0].scoring < listToOutput[j][0].scoring)
) {
var x = listToOutput[i];
listToOutput[i] = listToOutput[j];
listToOutput[j] = x;
}
}
}
return listToOutput;
}
/**
* @description Remove derivatives words from the list of words
* @param {Array} obj Array that contains results for searched words
* @param {String} searchedWord search term typed by user
* @return {Array} Clean array results without duplicated and derivatives words
*/
function removeDerivates(obj, searchedWord) {
debug("removeDerivatives(",obj,")");
var toResultObject = [];
for (var i in obj) {
var filesNo = obj[i].filesNo;
var wordList = obj[i].wordList;
var wList = wordList.split(",");
for (var j = 0; j < wList.length; j++) {
if (startsWith(wList[j], searchedWord)) {
wList[j] = searchedWord;
}
}
wList = removeDuplicate(wList);
var recreateList = '';
for (var x in wList) {
recreateList += wList[x] + ",";
}
recreateList = recreateList.substr(0, recreateList.length - 1);
toResultObject.push(new newObj(filesNo, recreateList));
}
return toResultObject;
}
function newObj(filesNo, wordList) {
this.filesNo = filesNo;
this.wordList = wordList;
}
// Object.
// Add a new parameter - scoring.
function resultPerFile(filenb, motsliste, motsnb, motslisteDisplay, scoring, group) {
//10 - spring,time - 2 - spring, time - 55 - 3
this.filenb = filenb;
this.motsliste = motsliste;
this.motsnb = motsnb;
this.motslisteDisplay = motslisteDisplay;
this.scoring = scoring;
}
function findRating(words, nr) {
var sum = 0;
var xx = words.split(',');
for (var jj = 0; jj < xx.length; jj++) {
var wrd = w[xx[jj]].split(',');
for (var ii = 0; ii < wrd.length; ii++) {
var wrdno = wrd[ii].split('*');
if (wrdno[0] == nr) {
sum += parseInt(wrdno[1]);
}
}
}
return sum;
}
function compareWords(s1, s2) {
var t1 = s1.split(',');
var t2 = s2.split(',');
if (t1.length == t2.length) {
return 0;
} else if (t1.length > t2.length) {
return 1;
} else {
return -1;
}
}
// return false if browser is Google Chrome and WebHelp is used on a local machine, not a web server
function verifyBrowser() {
var returnedValue = true;
BrowserDetect.init();
var browser = BrowserDetect.browser;
var addressBar = window.location.href;
if (browser == 'Chrome' && addressBar.indexOf('file://') === 0) {
returnedValue = false;
}
return returnedValue;
}
// Remove duplicate values from an array
function removeDuplicate(arr) {
var r = [];
o:for (var i = 0, n = arr.length; i < n; i++) {
for (var x = 0, y = r.length; x < y; x++) {
if (r[x] == arr[i]) continue o;
}
r[r.length] = arr[i];
}
return r;
}
function trim(str, chars) {
return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
/**
* PATCH FOR BOOLEAN SEARCH
*/
/**
* @description Object with resulted pages as array
* @param array Array that contains partial results
* @constructor
*/
function Pages(array) {
this.value = array;
this.toString = function() {
var stringResult = "";
stringResult += "INDEX\t|\tfilenb\t|\tscoring\n";
for (var i=0;i<this.value.length;i++) {
stringResult += i + ".\t\t|\t" + this.value[i].filenb + "\t\t|\t" + this.value[i].scoring + "\n";
}
return stringResult;
};
this.writeIDs = function() {
var stringResult = "";
for (var i=0;i<this.value.length;i++) {
stringResult += this.value[i].filenb + " | ";
}
return stringResult;
};
this.and = function and(newArray) {
var result = [];
for (var x=0; x<this.value.length; x++) {
var found = false;
for (var y=0; y<newArray.value.length; y++) {
if (this.value[x].filenb == newArray.value[y].filenb) {
this.value[x].motsliste += ", " + newArray.value[y].motsliste;
this.value[x].scoring += newArray.value[y].scoring;
found = true;
break;
}
}
if (found) {
result.push(this.value[x]);
}
}
this.value = result;
return this;
};
this.or = function or(newArray) {
this.value = this.value.concat(newArray.value);
var result = [];
for (var i=0;i<this.value.length;i++) {
var unique = true;
for (var j=0;j<result.length;j++) {
if (this.value[i].filenb == result[j].filenb) {
result[j].motsliste += ", " + this.value[i].motsliste;
var numberOfWords = result[j].motsliste.split(", ").length;
result[j].scoring = numberOfWords*(this.value[i].scoring + result[j].scoring);
unique = false;
break;
}
}
if (unique) {
result.push(this.value[i]);
}
}
this.value = result;
return this;
};
this.not = function not(newArray) {
var result = [];
for (var x=0; x<this.value.length; x++) {
var found = false;
for (var y=0; y<newArray.value.length; y++) {
if (this.value[x].filenb == newArray.value[y].filenb) {
found = true;
}
}
if (!found) {
result.push(this.value[x]);
}
}
this.value = result;
return this;
};
this.sort = function() {
for (var i = 0; i < this.value.length; i++) {
for (var j = i; j > 0; j--) {
if ((this.value[j].scoring - this.value[j - 1].scoring) > 0) {
var aux = this.value[j];
this.value[j] = this.value[j-1];
this.value[j-1] = aux;
}
}
}
return this;
};
}
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return $.trim(this);
}
} |
goog.provide('Todos.views.Application');
goog.require('Todos.views.Stats');
goog.require('Todos.views.Filters');
goog.require('Todos.views.ClearButton');
/**
* Main application view
*
* Requires
* Class StatsView, stats view class
* Class FiltersView, filters view class
* Class ClearBtnView, clear button view class
* @returns Class
*/
Todos.views.Application = Ember.ContainerView.extend({});
|
/* jshint node:true */
var fs = require('fs');
var site = require('apostrophe-site')();
site.init({
// This line is required and allows apostrophe-site to use require() and manage our NPM modules for us.
root: module,
shortName: 'apostrophe-sandbox',
hostName: 'apostrophe-sandbox',
title: 'Apostrophe Sandbox',
sessionSecret: 'apostrophe sandbox demo party',
adminPassword: 'demo',
// Force a2 to prefix all of its URLs. It still
// listens on its own port, but you can configure
// your reverse proxy to send it traffic only
// for URLs with this prefix. With this option
// "/" becomes a 404, which is supposed to happen!
// prefix: '/test',
// If true, new tags can only be added by admins accessing
// the tag editor modal via the admin bar. Sometimes useful
// if your folksonomy has gotten completely out of hand
lockTags: false,
// Give users a chance to log in if they attempt to visit a page
// which requires login
secondChanceLogin: true,
locals: require('./lib/locals.js'),
// you can define lockups for areas here
// lockups: {},
// Here we define what page templates we have and what they will be called in the Page Types menu.
// For html templates, the 'name' property refers to the filename in ./views/pages, e.g. 'default'
// refers to '/views/pages/default.html'.
// The name property can also refer to a module, in the case of 'blog', 'map', 'events', etc.
pages: {
types: [
{ name: 'default', label: 'Default Page' },
{ name: 'home', label: 'Home Page' },
{ name: 'blog', label: 'Blog' }
]
},
lockups: {
left: {
label: 'Left',
tooltip: 'Inset Left',
icon: 'icon-arrow-left',
widgets: [ 'slideshow', 'video' ],
slideshow: {
size: 'one-half'
}
},
right: {
label: 'Right',
tooltip: 'Inset Right',
icon: 'icon-arrow-right',
widgets: [ 'slideshow', 'video' ],
slideshow: {
size: 'one-half'
}
}
},
// These are the modules we want to bring into the project.
modules: {
// Styles required by the new editor, must go FIRST
'apostrophe-editor-2': {},
'apostrophe-ui-2': {},
'apostrophe-blog-2': {
perPage: 5,
pieces: {
addFields: [
{
name: '_author',
type: 'joinByOne',
withType: 'person',
idField: 'authorId',
label: 'Author'
}
]
}
},
'apostrophe-people': {
addFields: [
{
name: '_blogPosts',
type: 'joinByOneReverse',
withType: 'blogPost',
idField: 'authorId',
label: 'Author',
withJoins: [ '_editor' ]
},
{
name: 'thumbnail',
type: 'singleton',
widgetType: 'slideshow',
label: 'Picture',
options: {
aspectRatio: [100,100]
}
}
]
},
'apostrophe-groups': {},
'apostrophe-browserify': {
files: ["./public/js/modules/_site.js"]
},
'apostrophe-demo-login': {
}
},
// These are assets we want to push to the browser.
// The scripts array contains the names of JS files in /public/js,
// while stylesheets contains the names of LESS files in /public/css
assets: {
stylesheets: ['site'],
scripts: ['_site-compiled']
},
afterInit: function(callback) {
// We're going to do a special console message now that the
// server has started. Are we in development or production?
var locals = require('./data/local');
if(locals.development || !locals.minify) {
console.error('Apostrophe Sandbox is running in development.');
} else {
console.error('Apostrophe Sandbox is running in production.');
}
callback(null);
}
});
|
var env, store, serializer;
var get = Ember.get;
var run = Ember.run;
var User, Handle, GithubHandle, TwitterHandle, Company;
module('integration/serializers/json-api-serializer - JSONAPISerializer', {
setup: function() {
User = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
handles: DS.hasMany('handle', { async: true, polymorphic: true }),
company: DS.belongsTo('company', { async: true })
});
Handle = DS.Model.extend({
user: DS.belongsTo('user', { async: true })
});
GithubHandle = Handle.extend({
username: DS.attr('string')
});
TwitterHandle = Handle.extend({
nickname: DS.attr('string')
});
Company = DS.Model.extend({
name: DS.attr('string'),
employees: DS.hasMany('user', { async: true })
});
env = setupStore({
adapter: DS.JSONAPIAdapter,
user: User,
handle: Handle,
'github-handle': GithubHandle,
'twitter-handle': TwitterHandle,
company: Company
});
store = env.store;
serializer = env.container.lookup('serializer:-json-api');
},
teardown: function() {
run(env.store, 'destroy');
}
});
test('Calling pushPayload works', function() {
run(function() {
serializer.pushPayload(store, {
data: {
type: 'users',
id: '1',
attributes: {
'first-name': 'Yehuda',
'last-name': 'Katz'
},
relationships: {
company: {
data: { type: 'companies', id: '2' }
},
handles: {
data: [
{ type: 'github-handles', id: '3' },
{ type: 'twitter-handles', id: '4' }
]
}
}
},
included: [{
type: 'companies',
id: '2',
attributes: {
name: 'Tilde Inc.'
}
}, {
type: 'github-handles',
id: '3',
attributes: {
username: 'wycats'
}
}, {
type: 'twitter-handles',
id: '4',
attributes: {
nickname: '@wycats'
}
}]
});
var user = store.peekRecord('user', 1);
equal(get(user, 'firstName'), 'Yehuda', 'firstName is correct');
equal(get(user, 'lastName'), 'Katz', 'lastName is correct');
equal(get(user, 'company.name'), 'Tilde Inc.', 'company.name is correct');
equal(get(user, 'handles.firstObject.username'), 'wycats', 'handles.firstObject.username is correct');
equal(get(user, 'handles.lastObject.nickname'), '@wycats', 'handles.lastObject.nickname is correct');
});
});
|
'use strict';
//Setting up route
angular.module('recipes').config(['$stateProvider',
function($stateProvider) {
// Recipes state routing
$stateProvider.
state('listRecipes', {
url: '/recipes',
templateUrl: 'modules/recipes/views/list-recipes.client.view.html'
}).
state('createRecipe', {
url: '/recipes/create',
templateUrl: 'modules/recipes/views/create-recipe.client.view.html'
}).
state('viewRecipe', {
url: '/recipes/:recipeId',
templateUrl: 'modules/recipes/views/view-recipe.client.view.html'
}).
state('editRecipe', {
url: '/recipes/:recipeId/edit',
templateUrl: 'modules/recipes/views/edit-recipe.client.view.html'
});
}
]); |
'use strict';
var test = require('tape');
var events = require('./lib/events');
var dragula = require('..');
test('drag event gets emitted when clicking an item', function (t) {
testCase('works for left clicks', { which: 0 });
testCase('works for wheel clicks', { which: 1 });
testCase('fails for right clicks', { which: 2 }, { passes: false });
testCase('fails for meta-clicks', { which: 0, metaKey: true }, { passes: false });
testCase('fails for ctrl-clicks', { which: 0, ctrlKey: true }, { passes: false });
testCase('fails when clicking containers', { which: 0 }, { containerClick: true, passes: false });
testCase('fails when clicking buttons by default', { which: 0 }, { tag: 'button', passes: false });
testCase('fails when clicking anchors by default', { which: 0 }, { tag: 'a', passes: false });
testCase('fails whenever invalid returns true', { which: 0 }, { passes: false, dragulaOpts: { invalid: always } });
testCase('fails whenever moves returns false', { which: 0 }, { passes: false, dragulaOpts: { moves: never } });
t.end();
function testCase (desc, eventOptions, options) {
t.test(desc, function subtest (st) {
var o = options || {};
var div = document.createElement('div');
var item = document.createElement(o.tag || 'div');
var passes = o.passes !== false;
var drake = dragula([div], o.dragulaOpts);
div.appendChild(item);
document.body.appendChild(div);
drake.on('drag', drag);
events.raise(o.containerClick ? div : item, 'mousedown', eventOptions);
if (passes) { events.raise(o.containerClick ? div : item, 'mousemove'); }
st.plan(passes ? 4 : 1);
st.equal(drake.dragging, passes, 'final state is drake is ' + (passes ? '' : 'not ') + 'dragging');
st.end();
function drag (target, container) {
st[passes ? 'pass' : 'fail']('drag event was emitted synchronously');
st.equal(target, item, 'first argument is selected item');
st.equal(container, div, 'second argument is container');
}
});
}
});
test('when already dragging, ends (cancels) previous drag', function (t) {
var div = document.createElement('div');
var item1 = document.createElement('div');
var item2 = document.createElement('div');
var drake = dragula([div]);
div.appendChild(item1);
div.appendChild(item2);
document.body.appendChild(div);
drake.start(item1);
drake.on('dragend', end);
drake.on('cancel', cancel);
drake.on('drag', drag);
events.raise(item2, 'mousedown', { which: 0 });
events.raise(item2, 'mousemove', { which: 0 });
t.plan(7);
t.equal(drake.dragging, true, 'final state is drake is dragging');
t.end();
function end (item) {
t.equal(item, item1, 'dragend invoked with correct item');
}
function cancel (item, source) {
t.equal(item, item1, 'cancel invoked with correct item');
t.equal(source, div, 'cancel invoked with correct source');
}
function drag (item, container) {
t.pass('drag event was emitted synchronously');
t.equal(item, item2, 'first argument is selected item');
t.equal(container, div, 'second argument is container');
}
});
test('when already dragged, ends (drops) previous drag', function (t) {
var div = document.createElement('div');
var div2 = document.createElement('div');
var item1 = document.createElement('div');
var item2 = document.createElement('div');
var drake = dragula([div, div2]);
div.appendChild(item1);
div.appendChild(item2);
document.body.appendChild(div);
document.body.appendChild(div2);
drake.start(item1);
div2.appendChild(item1);
drake.on('dragend', end);
drake.on('drop', drop);
drake.on('drag', drag);
events.raise(item2, 'mousedown', { which: 0 });
events.raise(item2, 'mousemove', { which: 0 });
t.plan(8);
t.equal(drake.dragging, true, 'final state is drake is dragging');
t.end();
function end (item) {
t.equal(item, item1, 'dragend invoked with correct item');
}
function drop (item, target, source) {
t.equal(item, item1, 'drop invoked with correct item');
t.equal(source, div, 'drop invoked with correct source');
t.equal(target, div2, 'drop invoked with correct target');
}
function drag (item, container) {
t.pass('drag event was emitted synchronously');
t.equal(item, item2, 'first argument is selected item');
t.equal(container, div, 'second argument is container');
}
});
test('when copying, emits cloned with the copy', function (t) {
var div = document.createElement('div');
var item1 = document.createElement('div');
var item2 = document.createElement('span');
var drake = dragula([div], { copy: true });
item2.innerHTML = '<em>the force is <strong>with this one</strong></em>';
div.appendChild(item1);
div.appendChild(item2);
document.body.appendChild(div);
drake.start(item1);
drake.on('cloned', cloned);
drake.on('drag', drag);
events.raise(item2, 'mousedown', { which: 0 });
events.raise(item2, 'mousemove', { which: 0 });
t.plan(12);
t.equal(drake.dragging, true, 'final state is drake is dragging');
t.end();
function cloned (copy, item) {
t.notEqual(copy, item2, 'first argument is not exactly the target');
t.equal(copy.tagName, item2.tagName, 'first argument has same tag as target');
t.equal(copy.innerHTML, item2.innerHTML, 'first argument has same inner html as target');
t.equal(item, item2, 'second argument is clicked item');
}
function drag (item, container) {
t.pass('drag event was emitted synchronously');
t.equal(item, item2, 'first argument is selected item');
t.equal(container, div, 'second argument is container');
}
});
test('when dragging, element gets gu-transit class', function (t) {
var div = document.createElement('div');
var item = document.createElement('div');
dragula([div]);
div.appendChild(item);
document.body.appendChild(div);
events.raise(item, 'mousedown', { which: 0 });
events.raise(item, 'mousemove', { which: 0 });
t.equal(item.className, 'gu-transit', 'item has gu-transit class');
t.end();
});
test('when dragging, body gets gu-unselectable class', function (t) {
var div = document.createElement('div');
var item = document.createElement('div');
dragula([div]);
div.appendChild(item);
document.body.appendChild(div);
events.raise(item, 'mousedown', { which: 0 });
events.raise(item, 'mousemove', { which: 0 });
t.equal(document.body.className, 'gu-unselectable', 'body has gu-unselectable class');
t.end();
});
test('when dragging, element gets a mirror image for show', function (t) {
var div = document.createElement('div');
var item = document.createElement('div');
var drake = dragula([div]);
item.innerHTML = '<em>the force is <strong>with this one</strong></em>';
div.appendChild(item);
document.body.appendChild(div);
drake.on('cloned', cloned);
events.raise(item, 'mousedown', { which: 0 });
events.raise(item, 'mousemove', { which: 0 });
t.plan(4);
t.end();
function cloned (mirror, target) {
t.equal(item.className, 'gu-transit', 'item does not have gu-mirror class');
t.equal(mirror.className, 'gu-mirror', 'mirror only has gu-mirror class');
t.equal(mirror.innerHTML, item.innerHTML, 'mirror is passed to \'cloned\' event');
t.equal(target, item, 'cloned lets you know that the mirror is a clone of `item`');
}
});
test('when dragging, mirror element gets appended to configured mirrorContainer', function (t) {
var mirrorContainer = document.createElement('div');
var div = document.createElement('div');
var item = document.createElement('div');
var drake = dragula([div], {
'mirrorContainer': mirrorContainer
});
item.innerHTML = '<em>the force is <strong>with this one</strong></em>';
div.appendChild(item);
document.body.appendChild(div);
drake.on('cloned', cloned);
events.raise(item, 'mousedown', { which: 0 });
events.raise(item, 'mousemove', { which: 0 });
t.plan(1);
t.end();
function cloned (mirror) {
t.equal(mirror.parentNode, mirrorContainer, 'mirrors parent is the configured mirrorContainer');
}
});
test('when dragging stops, element gets gu-transit class removed', function (t) {
var div = document.createElement('div');
var item = document.createElement('div');
var drake = dragula([div]);
div.appendChild(item);
document.body.appendChild(div);
events.raise(item, 'mousedown', { which: 0 });
events.raise(item, 'mousemove', { which: 0 });
t.equal(item.className, 'gu-transit', 'item has gu-transit class');
drake.end();
t.equal(item.className, '', 'item has gu-transit class removed');
t.end();
});
test('when dragging stops, body becomes selectable again', function (t) {
var div = document.createElement('div');
var item = document.createElement('div');
var drake = dragula([div]);
div.appendChild(item);
document.body.appendChild(div);
events.raise(item, 'mousedown', { which: 0 });
events.raise(item, 'mousemove', { which: 0 });
t.equal(document.body.className, 'gu-unselectable', 'body has gu-unselectable class');
drake.end();
t.equal(document.body.className, '', 'body got gu-unselectable class removed');
t.end();
});
function always () { return true; }
function never () { return false; }
|
import expect from 'expect'
import { bindActionCreators, createStore } from '../../src'
import { todos } from '../helpers/reducers'
import * as actionCreators from '../helpers/actionCreators'
describe('bindActionCreators', () => {
let store
beforeEach(() => {
store = createStore(todos)
})
it('wraps the action creators with the dispatch function', () => {
const boundActionCreators = bindActionCreators(actionCreators, store.dispatch)
expect(
Object.keys(boundActionCreators)
).toEqual(
Object.keys(actionCreators)
)
const action = boundActionCreators.addTodo('Hello')
expect(action).toEqual(
actionCreators.addTodo('Hello')
)
expect(store.getState()).toEqual([
{ id: 1, text: 'Hello' }
])
})
it('supports wrapping a single function only', () => {
const actionCreator = actionCreators.addTodo
const boundActionCreator = bindActionCreators(actionCreator, store.dispatch)
const action = boundActionCreator('Hello')
expect(action).toEqual(actionCreator('Hello'))
expect(store.getState()).toEqual([
{ id: 1, text: 'Hello' }
])
})
it('throws for an undefined actionCreator', () => {
expect(() => {
bindActionCreators(undefined, store.dispatch)
}).toThrow(
'bindActionCreators expected an object or a function, instead received undefined. ' +
'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
)
})
it('throws for a null actionCreator', () => {
expect(() => {
bindActionCreators(null, store.dispatch)
}).toThrow(
'bindActionCreators expected an object or a function, instead received null. ' +
'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
)
})
it('throws for a primitive actionCreator', () => {
expect(() => {
bindActionCreators('string', store.dispatch)
}).toThrow(
'bindActionCreators expected an object or a function, instead received string. ' +
'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
)
})
})
|
enum E of string {
A = true,
}
|
export default function defineLazyProperty (obj, propName, initializer) {
Object.defineProperty(obj, propName, {
propValue: null,
get () {
if (!this.propValue)
this.propValue = initializer();
return this.propValue;
}
});
}
|
//jshint strict: false
exports.config = {
allScriptsTimeout: 11000,
specs: [
'*.js'
],
capabilities: {
'browserName': 'chrome'
},
baseUrl: 'http://localhost:8000/',
framework: 'jasmine',
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}
};
|
// # Templates
//
// Figure out which template should be used to render a request
// based on the templates which are allowed, and what is available in the theme
var _ = require('lodash'),
config = require('../../config');
function getActiveThemePaths(activeTheme) {
return config.get('paths').availableThemes[activeTheme];
}
/**
* ## Get Channel Template Hierarchy
*
* Fetch the ordered list of templates that can be used to render this request.
* 'index' is the default / fallback
* For channels with slugs: [:channelName-:slug, :channelName, index]
* For channels without slugs: [:channelName, index]
* Channels can also have a front page template which is used if this is the first page of the channel, e.g. 'home.hbs'
*
* @param {Object} channelOpts
* @returns {String[]}
*/
function getChannelTemplateHierarchy(channelOpts) {
var templateList = ['index'];
if (channelOpts.name && channelOpts.name !== 'index') {
templateList.unshift(channelOpts.name);
if (channelOpts.slugTemplate && channelOpts.slugParam) {
templateList.unshift(channelOpts.name + '-' + channelOpts.slugParam);
}
}
if (channelOpts.frontPageTemplate && channelOpts.postOptions.page === 1) {
templateList.unshift(channelOpts.frontPageTemplate);
}
return templateList;
}
/**
* ## Get Single Template Hierarchy
*
* Fetch the ordered list of templates that can be used to render this request.
* 'post' is the default / fallback
* For posts: [post-:slug, post]
* For pages: [page-:slug, page, post]
*
* @param {Object} single
* @returns {String[]}
*/
function getSingleTemplateHierarchy(single) {
var templateList = ['post'],
type = 'post';
if (single.page) {
templateList.unshift('page');
type = 'page';
}
templateList.unshift(type + '-' + single.slug);
return templateList;
}
/**
* ## Pick Template
*
* Taking the ordered list of allowed templates for this request
* Cycle through and find the first one which has a match in the theme
*
* @param {Object} themePaths
* @param {Array} templateList
*/
function pickTemplate(themePaths, templateList) {
var template = _.find(templateList, function (template) {
return themePaths.hasOwnProperty(template + '.hbs');
});
if (!template) {
template = templateList[templateList.length - 1];
}
return template;
}
function getTemplateForSingle(activeTheme, single) {
return pickTemplate(getActiveThemePaths(activeTheme), getSingleTemplateHierarchy(single));
}
function getTemplateForChannel(activeTheme, channelOpts) {
return pickTemplate(getActiveThemePaths(activeTheme), getChannelTemplateHierarchy(channelOpts));
}
module.exports = {
getActiveThemePaths: getActiveThemePaths,
channel: getTemplateForChannel,
single: getTemplateForSingle
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:708a7536a3e9ad1ad857d7e8241ab4ea94d382bc9b5d9b608732d33cbdd08772
size 669
|
export const integrations = {
outgoingEvents: {
sendMessage: {
label: 'Integrations_Outgoing_Type_SendMessage',
value: 'sendMessage',
use: {
channel: true,
triggerWords: true,
targetRoom: false,
},
},
fileUploaded: {
label: 'Integrations_Outgoing_Type_FileUploaded',
value: 'fileUploaded',
use: {
channel: true,
triggerWords: false,
targetRoom: false,
},
},
roomArchived: {
label: 'Integrations_Outgoing_Type_RoomArchived',
value: 'roomArchived',
use: {
channel: false,
triggerWords: false,
targetRoom: false,
},
},
roomCreated: {
label: 'Integrations_Outgoing_Type_RoomCreated',
value: 'roomCreated',
use: {
channel: false,
triggerWords: false,
targetRoom: false,
},
},
roomJoined: {
label: 'Integrations_Outgoing_Type_RoomJoined',
value: 'roomJoined',
use: {
channel: true,
triggerWords: false,
targetRoom: false,
},
},
roomLeft: {
label: 'Integrations_Outgoing_Type_RoomLeft',
value: 'roomLeft',
use: {
channel: true,
triggerWords: false,
targetRoom: false,
},
},
userCreated: {
label: 'Integrations_Outgoing_Type_UserCreated',
value: 'userCreated',
use: {
channel: false,
triggerWords: false,
targetRoom: true,
},
},
},
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:25dad4b46a1c2a267f1c3b5dec174ab4ab3d26eb2f3042e351b618091d6a1ae3
size 2571
|
/*
// tabs.js widget for creating and displaying tabs
// Instantiation
// optional: content, active, removable
// you can make all tabs or individual tabs removable
var tabs = $('#ele').tabs();
//or
var tabs = $('#ele').tabs({tabs: [
{name: 'tab1', content: 'foo text or html', active: true},
{name: 'tab2', content: 'text or html 2', removable: true}
]
});
// Add a new tab
// optional: content, active
tabs.addTab({name: 'tab3', content: 'new content'})
// Retrieve a tab button
// (useful for adding events or other stuff)
var mytab = tabs.tab('tab1')
// Add content to existing tab
// (useful for ajax/event stuff)
tabs.tab({name: 'tab3', content: 'blah blah blah'})
// manually show a tab
// Tab panes are shown when clicked automatically.
// This is a programmatic way of showing a tab.
tabs.showTab('tab_name');
*/
(function( $, undefined ) {
$.KBWidget({
name: "kbTabs",
version: "1.0.0",
init: function(options) {
this._super(options);
if (!options) options = {};
var container = this.$elem;
var self = this;
var tabs = $('<ul class="nav nav-'+(options.pills ? 'pills' : 'tabs')+'">');
var tab_contents = $('<div class="tab-content">');
container.append(tabs, tab_contents);
// adds a single tab and content
this.addTab = function(p) {
// if tab exists, don't add
if ( tabs.find('a[data-id="'+p.name+'"]').length > 0)
return;
var tab = $('<li class="'+(p.active ? 'active' :'')+'">');
var tab_link = $('<a data-toggle="tab" data-id="'+p.name+'">'+p.name+'</a>');
// animate by sliding tab up
if (p.animate === false) {
tab.append(tab_link)
tabs.append(tab);
} else {
tab.append(tab_link).hide();
tabs.append(tab);
tab.toggle('slide', {direction: 'down', duration: 'fast'});
}
// add close button if needed
if (p.removable || options.removable) {
var rm_btn = $('<span class="glyphicon glyphicon-remove">');
tab_link.append(rm_btn);
rm_btn.click(function(e) {
self.rmTab(p.name)
})
}
// add content pane
var c = $('<div class="tab-pane '+(p.active ? 'active' :'')+'" data-id="'+p.name+'">')
c.append((p.content ? p.content : ''))
tab_contents.append(c);
tab.click(function(e) {
e.preventDefault();
e.stopPropagation();
var id = $(this).find('a').data('id');
self.showTab(id);
})
return p.content;
}
// remove tab and tab content
this.rmTab = function(name) {
var tab = tabs.find('a[data-id="'+name+'"]').parent('li');
var tab_content = tab_contents.children('[data-id="'+name+'"]')
// get previous or next tab
if (tab.next().length > 0)
var id = tab.next().children('a').data('id');
else
var id = tab.prev().children('a').data('id');
// remove the tab
tab.remove();
tab_content.remove();
// show prev or next tab
self.showTab(id);
}
// returns tab
this.tab = function(name) {
return tabs.children('[data-id="'+name+'"]');
}
// returns content of tab
this.tabContent = function(name) {
return tab_contents.children('[data-id="'+name+'"]');
}
// adds content to existing tab pane; useful for ajax
this.addContent = function(p) {
var c = tab_contents.children('[data-id="'+p.name+'"]')
c.append((p.content ? p.content : ''));
return c;
}
// highlights tab and shows content
this.showTab = function(id) {
tabs.children('li').removeClass('active');
tab_contents.children('.tab-pane').removeClass('active');
tabs.find('a[data-id="'+id+'"]').parent().addClass('active');
tab_contents.children('[data-id="'+id+'"]').addClass('active');
}
this.getTabNav = function() {
return tabs;
}
// if tabs are supplied, add them
// don't animate intial tabs
if ('tabs' in options) {
for (var i in options.tabs) {
var p = $.extend(options.tabs[i], {animate: false})
this.addTab(p)
}
}
return this;
},
});
}( jQuery ) );
|
var copy = require("../../../../util/copy.coffee"),
fontTester = require("../../../../core/font/tester.coffee"),
form = require("../../../form.js"),
print = require("../../../../core/console/print.coffee"),
validObject = require("../../../../object/validate.coffee")
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// If no widths are defined, then this calculates the width needed to fit the
// longest entry in the list.
//------------------------------------------------------------------------------
module.exports = function ( vars ) {
var data = [], buffer = 0
for ( var level in vars.data.nested.all ) {
var newData = vars.data.nested.all[level]
, key = validObject(vars.text.nesting) && level in vars.text.nesting
? vars.text.nesting[level][0] : level
if ( [vars.id.value,vars.text.value].indexOf(key) < 0 ) {
newData = copy(newData)
newData.forEach(function(d){
d[vars.text.value || vars.id.value] = d[key]
})
}
data = data.concat( newData )
}
function getWidth( type ) {
var key = type === "primary" ? "value" : type
, icon = key === "value" ? vars.icon.drop.value
: vars.icon.select.value || vars.icon.drop.value
, text = key === "value" ? vars.text.value
: vars.text.secondary.value || vars.text.value
, font = key === "value" ? vars.font : vars.font.secondary
if ( vars.dev.value ) print.time("calculating "+type+" width")
var button = form()
.container( fontTester() )
.data({
"large": 9999,
"value": data
})
.draw({ "update": false })
.font( font )
.format(vars.format)
.icon({ "button": icon, "value": vars.icon.value })
.id(vars.id.value)
.timing({
"ui": 0
})
.text( text || vars.id.value )
.type( "button" )
.ui({
"border": type === "primary" ? vars.ui.border : 0,
"display": "inline-block",
"margin": 0,
"padding": vars.ui.padding.css
})
.width(false)
.draw()
var w = []
button.selectAll("div.d3plus_node").each(function(o){
w.push(this.offsetWidth + 1)
}).remove()
var dropWidth = {}
dropWidth[key] = d3.max(w)
vars.self.width( dropWidth )
if ( vars.dev.value ) print.timeEnd("calculating "+type+" width")
}
if ( typeof vars.width.value !== "number" ) {
getWidth( "primary" )
}
if ( typeof vars.width.secondary !== "number" ) {
if ( !vars.text.secondary.value || vars.text.value === vars.text.secondary.value ) {
vars.self.width({"secondary": vars.width.value})
}
else {
getWidth( "secondary" )
}
}
}
|
(function (window, ch) {
'use strict';
/**
* Modal is a dialog window with an underlay.
* @memberof ch
* @constructor
* @augments ch.Popover
* @param {HTMLElement} [el] A HTMLElement to create an instance of ch.Modal.
* @param {Object} [options] Options to customize an instance.
* @param {String} [options.addClass] CSS class names that will be added to the container on the component initialization.
* @param {String} [options.fx] Enable or disable UI effects. You must use: "slideDown", "fadeIn" or "none". Default: "fadeIn".
* @param {String} [options.width] Set a width for the container. Default: "50%".
* @param {String} [options.height] Set a height for the container. Default: "auto".
* @param {String} [options.shownby] Determines how to interact with the trigger to show the container. You must use: "pointertap", "pointerenter" or "none". Default: "pointertap".
* @param {String} [options.hiddenby] Determines how to hide the component. You must use: "button", "pointers", "pointerleave", "all" or "none". Default: "all".
* @param {HTMLElement} [options.reference] It's a reference to position and size of element that will be considered to carry out the position. Default: ch.viewport.
* @param {String} [options.side] The side option where the target element will be positioned. Its value can be: "left", "right", "top", "bottom" or "center". Default: "center".
* @param {String} [options.align] The align options where the target element will be positioned. Its value can be: "left", "right", "top", "bottom" or "center". Default: "center".
* @param {Number} [options.offsetX] Distance to displace the target horizontally. Default: 0.
* @param {Number} [options.offsetY] Distance to displace the target vertically. Default: 0.
* @param {String} [options.position] The type of positioning used. Its value must be "absolute" or "fixed". Default: "fixed".
* @param {String} [options.method] The type of request ("POST" or "GET") to load content by ajax. Default: "GET".
* @param {String} [options.params] Params like query string to be sent to the server.
* @param {Boolean} [options.cache] Force to cache the request by the browser. Default: true.
* @param {Boolean} [options.async] Force to sent request asynchronously. Default: true.
* @param {(String | HTMLElement)} [options.waiting] Temporary content to use while the ajax request is loading. Default: '<div class="ch-loading-large ch-loading-centered"></div>'.
* @param {(String | HTMLElement)} [options.content] The content to be shown into the Modal container.
* @returns {modal} Returns a new instance of Modal.
* @example
* // Create a new Modal.
* var modal = new ch.Modal([el], [options]);
* @example
* // Create a new Modal.
* var modal = new ch.Modal([options]);
* @example
* // Create a new Modal with disabled effects.
* var modal = new ch.Modal({
* 'content': 'This is the content of the Modal'
* });
* @example
* // Create a new Modal using the shorthand way (content as parameter).
* var modal = new ch.Modal('http://ui.ml.com:3040/ajax');
*/
function Modal(el, options) {
/**
* Reference to context of an instance.
* @type {Object}
* @private
*/
var that = this;
this._init(el, options);
if (this.initialize !== undefined) {
/**
* If you define an initialize method, it will be executed when a new Modal is created.
* @memberof! ch.Modal.prototype
* @function
*/
this.initialize();
}
/**
* Event emitted when the component is ready to use.
* @event ch.Modal#ready
* @example
* // Subscribe to "ready" event.
* modal.on('ready', function () {
* // Some code here!
* });
*/
window.setTimeout(function () { that.emit('ready'); }, 50);
}
// Inheritance
tiny.inherits(Modal, ch.Popover);
var document = window.document,
underlay = (function () {
var dummyElement = document.createElement('div');
dummyElement.innerHTML = '<div class="ch-underlay" tabindex="-1"></div>';
return dummyElement.querySelector('div');
}()),
parent = Modal.super_.prototype;
/**
* The name of the component.
* @memberof! ch.Modal.prototype
* @type {String}
*/
Modal.prototype.name = 'modal';
/**
* Returns a reference to the constructor function.
* @memberof! ch.Modal.prototype
* @function
*/
Modal.prototype.constructor = Modal;
/**
* Configuration by default.
* @memberof! ch.Modal.prototype
* @type {Object}
* @private
*/
Modal.prototype._defaults = tiny.extend(tiny.clone(parent._defaults), {
'_className': 'ch-modal ch-box-lite',
'_ariaRole': 'dialog',
'width': '50%',
'hiddenby': 'all',
'reference': ch.viewport,
'waiting': '<div class="ch-loading-large ch-loading-centered"></div>',
'position': 'fixed'
});
/**
* Shows the Modal underlay.
* @memberof! ch.Modal.prototype
* @function
* @private
*/
Modal.prototype._showUnderlay = function () {
var useAnimation = tiny.support.transition && this._options.fx !== 'none' && this._options.fx !== false,
fxName = 'ch-fx-' + this._options.fx.toLowerCase();
document.body.appendChild(underlay);
function showCallback(e) {
tiny.removeClass(underlay, fxName + '-enter-active');
tiny.removeClass(underlay, fxName + '-enter');
tiny.off(e.target, e.type, showCallback);
}
if (useAnimation) {
tiny.addClass(underlay, fxName + '-enter');
setTimeout(function() {
tiny.addClass(underlay, fxName + '-enter-active');
},10);
tiny.on(underlay, tiny.support.transition.end, showCallback);
}
};
/**
* Hides the Modal underlay.
* @memberof! ch.Modal.prototype
* @function
* @private
*/
Modal.prototype._hideUnderlay = function () {
var useAnimation = tiny.support.transition && this._options.fx !== 'none' && this._options.fx !== false,
fxName = 'ch-fx-' + this._options.fx.toLowerCase(),
parent = underlay.parentNode;
function hideCallback(e) {
tiny.removeClass(underlay, fxName + '-leave-active');
tiny.removeClass(underlay, fxName + '-leave');
tiny.off(e.target, e.type, hideCallback);
parent.removeChild(underlay);
}
if (useAnimation) {
tiny.addClass(underlay, fxName + '-leave');
setTimeout(function() {
tiny.addClass(underlay, fxName + '-leave-active');
},10);
tiny.on(underlay, tiny.support.transition.end, hideCallback);
} else {
parent.removeChild(underlay);
}
};
/**
* Shows the modal container and the underlay.
* @memberof! ch.Modal.prototype
* @function
* @param {(String | HTMLElement)} [content] The content that will be used by modal.
* @param {Object} [options] A custom options to be used with content loaded by ajax.
* @param {String} [options.method] The type of request ("POST" or "GET") to load content by ajax. Default: "GET".
* @param {String} [options.params] Params like query string to be sent to the server.
* @param {Boolean} [options.cache] Force to cache the request by the browser. Default: true.
* @param {Boolean} [options.async] Force to sent request asynchronously. Default: true.
* @param {(String | HTMLElement)} [options.waiting] Temporary content to use while the ajax request is loading.
* @returns {modal}
* @example
* // Shows a basic modal.
* modal.show();
* @example
* // Shows a modal with new content
* modal.show('Some new content here!');
* @example
* // Shows a modal with a new content that will be loaded by ajax with some custom options
* modal.show('http://domain.com/ajax/url', {
* 'cache': false,
* 'params': 'x-request=true'
* });
*/
Modal.prototype.show = function (content, options) {
// Don't execute when it's disabled
if (!this._enabled || this._shown) {
return this;
}
/**
* Reference to context of an instance.
* @type {Object}
* @private
*/
var that = this;
function hideByUnderlay(e) {
that.hide();
// Allow only one click to analyze the config every time and to close ONLY THIS modal
e.target.removeEventListener(e.type, hideByUnderlay);
}
// Add to the underlay the ability to hide the component
if (this._options.hiddenby === 'all' || this._options.hiddenby === 'pointers') {
tiny.on(underlay, ch.onpointertap, hideByUnderlay);
}
// Show the underlay
this._showUnderlay();
// Execute the original show()
parent.show.call(this, content, options);
return this;
};
/**
* Hides the modal container and the underlay.
* @memberof! ch.Modal.prototype
* @function
* @returns {modal}
* @example
* // Close a modal
* modal.hide();
*/
Modal.prototype.hide = function () {
if (!this._shown) {
return this;
}
// Delete the underlay listener
tiny.off(underlay, ch.onpointertap);
// Hide the underlay element
this._hideUnderlay();
// Execute the original hide()
parent.hide.call(this);
return this;
};
ch.factory(Modal, parent._normalizeOptions);
}(this, this.ch));
|
function setProperties(object, properties) {
for (let key in properties) {
if (properties.hasOwnProperty(key)) {
object[key] = properties[key];
}
}
}
let guids = 0;
export default function factory() {
function Klass(options) {
setProperties(this, options);
this._guid = guids++;
this.isDestroyed = false;
}
Klass.prototype.constructor = Klass;
Klass.prototype.destroy = function() {
this.isDestroyed = true;
};
Klass.prototype.toString = function() {
return '<Factory:' + this._guid + '>';
};
Klass.create = create;
Klass.extend = extend;
Klass.reopen = extend;
Klass.reopenClass = reopenClass;
return Klass;
function create(options) {
return new this.prototype.constructor(options);
}
function reopenClass(options) {
setProperties(this, options);
}
function extend(options) {
function Child(options) {
Klass.call(this, options);
}
let Parent = this;
Child.prototype = new Parent();
Child.prototype.constructor = Child;
setProperties(Child, Klass);
setProperties(Child.prototype, options);
Child.create = create;
Child.extend = extend;
Child.reopen = extend;
Child.reopenClass = reopenClass;
return Child;
}
}
|
fis.set('project.ignore', [
'output/**',
'node_modules/**',
'.git/**',
'.svn/**',
'widget/**/*.html',
'widget/**/*.css',
'widget/**/*.md',
'/config/**',
'/pages/**',
'/components/**',
'/lib/foundation/**',
'/lib/Font-Awesome/master/**',
'fis-conf.js',
'fis-conf-pages.js',
'/pages/**',
'/template/Layer/*',
'/**/*.bat',
'*.bat',
'*.sh',
'*.log',
'**/*.map'
]);
fis.match('::packager', {
packager: fis.plugin('map'),
postpackager: fis.plugin('loader', {
})
});
fis.match('*.less', {
parser: fis.plugin('less'), //启用fis-parser-less插件
rExt: '.css'
});
fis.media('um')
.match('::packager', {
packager: fis.plugin('map'),
postpackager: fis.plugin('loader', {
allInOne: true,
processor : {
'.less':'css',
'.tpl':'html'
}
})
})
// 主模板文件规则
.match('/template/UserManage/(*).tpl', {
isHtmlLike: true,
rExt: '.html',
release: '/UserManage/pages/$1.html'
})
.match('/template/{UserHome,Mall,Layer}/*', {
release: false
})
// 禁止发布的文件
.match('/widget/(**)/*.{md,tpl,html,css}', {
release: false
})
.match('/lib/*', {
release: '/UserManage/lib/$0',
url: '/lib/$0'
})
.match('/data/*', {
release: '/UserManage/data/$0',
url: '/data/$0'
})
// JSON文件规则
.match('/widget/(**)/(*.json)', {
release: '/UserManage/data/$1/$2',
url: '/data/$1/$2'
})
// JS规则
.match('/widget/(**)/(*.js)', {
release: '/UserManage/static/js/_temp.js',
packTo: '/UserManage/static/js/xue.usermanage.js',
url: '/static/js/xue.usermanage.js'
})
// Less规则
.match('/widget/(**)/(*.less)', {
parser: fis.plugin('less'), //启用fis-parser-less插件
rExt: '.css',
release: '/UserManage/static/css/_temp.css',
packTo: '/UserManage/static/css/xue.usermanage.css',
url: '/static/css/xue.usermanage.css'
})
// pic资源图片规则
.match('/widget/(*)/pic/(*.{png,jpg,gif,cur})', {
release: '/UserManage/static/pic/$2$4$6$8',
url: '/static/pic/$2$4$6$8'
})
// img素材图片规则
.match('/widget/(*)/img/(*.{png,jpg,gif,cur})', {
release: '/UserManage/static/img/$1$3$5$7/$2$4$6$8',
url: '/static/img/$1$3$5$7/$2$4$6$8'
})
// img里面存在文件夹时的规则
.match('/widget/(**)/img/(**)/(*.png)', {
release:'/UserManage/static/img/$1/$2/$3',
url:'/static/img/$1/$2/$3'
})
;
fis.media('tmpl')
// 主模板文件规则
.match('/template/(**)/(*).tpl', {
isHtmlLike: true,
rExt: '.html',
release: '/pages/$1/$2.html'
})
// 禁止发布的文件
.match('/widget/(**)/*.{md,tpl,html}', {
release: false
})
// 不做修改直接拷贝的目录
.match('/lib/*', {
release: '/lib/$0'
})
.match('/data/*', {
release: '/data/$0'
})
// JSON文件规则
.match('/widget/(**)/(*.json)', {
release: '/data/$1/js/$2',
})
// JS规则
.match('/widget/(**)/(*.js)', {
release: '/static/js/$1.$2'
})
// Less规则
.match('/widget/(**)/(*.less)', {
parser: fis.plugin('less'), //启用fis-parser-less插件
rExt: '.css',
release: '/static/css/$1/$2'
})
.match('/static/less/(*.less)', {
parser: fis.plugin('less'), //启用fis-parser-less插件
rExt: '.css',
release: '/static/css/$1'
})
// pic资源图片规则
.match('/widget/(*)/pic/(*.{png,jpg,gif,cur})', {
release: '/static/pic/$1$3$5$7/$2$4$6$8'
})
// img素材图片规则
.match('/widget/(*)/img/(*.{png,jpg,gif,cur})', {
release: '/static/img/$1$3$5$7/$2$4$6$8'
})
// img里面存在文件夹时的规则
.match('/widget/(**)/img/(**)/(*.png)', {
release:'/static/img/$1/$2/$3'
})
;
fis.media('home')
.match('::packager', {
packager: fis.plugin('map'),
postpackager: fis.plugin('loader', {
processor : {
'.less':'css',
'.tpl':'html'
}
})
})
// 主模板文件规则
.match('/template/UserHome/(*).tpl', {
isHtmlLike: true,
rExt: '.html',
release: '/UserHome/pages/$1.html'
})
.match('/template/{UserManage,Mall,Layer}/*', {
release: false
})
// 禁止发布的文件
.match('/widget/(**)/*.{md,tpl,html,css}', {
release: false
})
.match('/lib/*', {
release: '/UserHome/lib/$0',
url: '/lib/$0'
})
.match('/data/*', {
release: '/UserHome/data/$0',
url: '/data/$0'
})
// JSON文件规则
.match('/widget/(**)/(*.json)', {
release: '/UserHome/data/$1/$2',
url: '/data/$1/$2'
})
// JS规则
.match('/widget/(**)/(*.js)', {
release: '/UserHome/static/js/$1.$2',
url: '/static/js/$1.$2'
})
// Less规则
.match('/widget/(**)/(*.less)', {
parser: fis.plugin('less'), //启用fis-parser-less插件
rExt: '.css',
release: '/UserHome/static/css/$1/$2',
url: '/static/css/$1/$2'
})
// pic资源图片规则
.match('/widget/(*)/pic/(*.{png,jpg,gif,cur})', {
release: '/UserHome/static/pic/$2$4$6$8',
url: '/static/pic/$2$4$6$8'
})
// img素材图片规则
.match('/widget/(*)/img/(*.{png,jpg,gif,cur})', {
release: '/UserHome/static/img/$1$3$5$7/$2$4$6$8',
url: '/static/img/$1$3$5$7/$2$4$6$8'
})
// img里面存在文件夹时的规则
.match('/widget/(**)/img/(**)/(*.png)', {
release:'/UserHome/static/img/$1/$2/$3',
url:'/static/img/$1/$2/$3'
})
;
|
/*!
* jQuery Password Strength plugin for Twitter Bootstrap
* Version: 2.2.0
*
* Copyright (c) 2008-2013 Tane Piper
* Copyright (c) 2013 Alejandro Blanco
* Dual licensed under the MIT and GPL licenses.
*/
(function (jQuery) {
// Source: src/i18n.js
var i18n = {};
(function (i18n, i18next) {
'use strict';
i18n.fallback = {
"wordMinLength": "Your password is too short",
"wordMaxLength": "Your password is too long",
"wordInvalidChar": "Your password contains an invalid character",
"wordNotEmail": "Do not use your email as your password",
"wordSimilarToUsername": "Your password cannot contain your username",
"wordTwoCharacterClasses": "Use different character classes",
"wordRepetitions": "Too many repetitions",
"wordSequences": "Your password contains sequences",
"errorList": "Errors:",
"veryWeak": "Very Weak",
"weak": "Weak",
"normal": "Normal",
"medium": "Medium",
"strong": "Strong",
"veryStrong": "Very Strong"
};
i18n.t = function (key) {
var result = '';
// Try to use i18next.com
if (i18next) {
result = i18next.t(key);
} else {
// Fallback to english
result = i18n.fallback[key];
}
return result === key ? '' : result;
};
}(i18n, window.i18next));
// Source: src/rules.js
var rulesEngine = {};
try {
if (!jQuery && module && module.exports) {
var jQuery = require("jquery"),
jsdom = require("jsdom").jsdom;
jQuery = jQuery(jsdom().defaultView);
}
} catch (ignore) {}
(function ($, rulesEngine) {
"use strict";
var validation = {};
rulesEngine.forbiddenSequences = [
"0123456789", "abcdefghijklmnopqrstuvwxyz", "qwertyuiop", "asdfghjkl",
"zxcvbnm", "!@#$%^&*()_+"
];
validation.wordNotEmail = function (options, word, score) {
if (word.match(/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i)) {
return score;
}
return 0;
};
validation.wordMinLength = function (options, word, score) {
var wordlen = word.length,
lenScore = Math.pow(wordlen, options.rules.raisePower);
if (wordlen < options.common.minChar) {
lenScore = (lenScore + score);
}
return lenScore;
};
validation.wordMaxLength = function (options, word, score) {
var wordlen = word.length,
lenScore = Math.pow(wordlen, options.rules.raisePower);
if (wordlen > options.common.maxChar) {
return score;
}
return lenScore;
};
validation.wordInvalidChar = function (options, word, score) {
if (options.common.invalidCharsRegExp.test(word)) {
return score;
}
return 0;
};
validation.wordMinLengthStaticScore = function (options, word, score) {
return word.length < options.common.minChar ? 0 : score;
};
validation.wordMaxLengthStaticScore = function (options, word, score) {
return word.length > options.common.maxChar ? 0 : score;
};
validation.wordSimilarToUsername = function (options, word, score) {
var username = $(options.common.usernameField).val();
if (username && word.toLowerCase().match(username.replace(/[\-\[\]\/\{\}\(\)\*\+\=\?\:\.\\\^\$\|\!\,]/g, "\\$&").toLowerCase())) {
return score;
}
return 0;
};
validation.wordTwoCharacterClasses = function (options, word, score) {
if (word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) ||
(word.match(/([a-zA-Z])/) && word.match(/([0-9])/)) ||
(word.match(/(.[!,@,#,$,%,\^,&,*,?,_,~])/) && word.match(/[a-zA-Z0-9_]/))) {
return score;
}
return 0;
};
validation.wordRepetitions = function (options, word, score) {
if (word.match(/(.)\1\1/)) { return score; }
return 0;
};
validation.wordSequences = function (options, word, score) {
var found = false,
j;
if (word.length > 2) {
$.each(rulesEngine.forbiddenSequences, function (idx, seq) {
if (found) { return; }
var sequences = [seq, seq.split('').reverse().join('')];
$.each(sequences, function (idx, sequence) {
for (j = 0; j < (word.length - 2); j += 1) { // iterate the word trough a sliding window of size 3:
if (sequence.indexOf(word.toLowerCase().substring(j, j + 3)) > -1) {
found = true;
}
}
});
});
if (found) { return score; }
}
return 0;
};
validation.wordLowercase = function (options, word, score) {
return word.match(/[a-z]/) && score;
};
validation.wordUppercase = function (options, word, score) {
return word.match(/[A-Z]/) && score;
};
validation.wordOneNumber = function (options, word, score) {
return word.match(/\d+/) && score;
};
validation.wordThreeNumbers = function (options, word, score) {
return word.match(/(.*[0-9].*[0-9].*[0-9])/) && score;
};
validation.wordOneSpecialChar = function (options, word, score) {
return word.match(/[!,@,#,$,%,\^,&,*,?,_,~]/) && score;
};
validation.wordTwoSpecialChar = function (options, word, score) {
return word.match(/(.*[!,@,#,$,%,\^,&,*,?,_,~].*[!,@,#,$,%,\^,&,*,?,_,~])/) && score;
};
validation.wordUpperLowerCombo = function (options, word, score) {
return word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) && score;
};
validation.wordLetterNumberCombo = function (options, word, score) {
return word.match(/([a-zA-Z])/) && word.match(/([0-9])/) && score;
};
validation.wordLetterNumberCharCombo = function (options, word, score) {
return word.match(/([a-zA-Z0-9].*[!,@,#,$,%,\^,&,*,?,_,~])|([!,@,#,$,%,\^,&,*,?,_,~].*[a-zA-Z0-9])/) && score;
};
validation.wordIsACommonPassword = function (options, word, score) {
return ($.inArray(word, options.rules.commonPasswords) >= 0) && score;
};
rulesEngine.validation = validation;
rulesEngine.executeRules = function (options, word) {
var totalScore = 0;
$.each(options.rules.activated, function (rule, active) {
if (active) {
var score = options.rules.scores[rule],
funct = rulesEngine.validation[rule],
result,
errorMessage;
if (!$.isFunction(funct)) {
funct = options.rules.extra[rule];
}
if ($.isFunction(funct)) {
result = funct(options, word, score);
if (result) {
totalScore += result;
}
if (result < 0 || (!$.isNumeric(result) && !result)) {
errorMessage = options.ui.spanError(options, rule);
if (errorMessage.length > 0) {
options.instances.errors.push(errorMessage);
}
}
}
}
});
return totalScore;
};
}(jQuery, rulesEngine));
try {
if (module && module.exports) {
module.exports = rulesEngine;
}
} catch (ignore) {}
// Source: src/options.js
var defaultOptions = {};
defaultOptions.common = {};
defaultOptions.common.minChar = 6;
defaultOptions.common.maxChar = 20;
defaultOptions.common.usernameField = "#username";
defaultOptions.common.invalidCharsRegExp = new RegExp(/[\s,'"]/);
defaultOptions.common.userInputs = [
// Selectors for input fields with user input
];
defaultOptions.common.onLoad = undefined;
defaultOptions.common.onKeyUp = undefined;
defaultOptions.common.onScore = undefined;
defaultOptions.common.zxcvbn = false;
defaultOptions.common.zxcvbnTerms = [
// List of disrecommended words
];
defaultOptions.common.events = ["keyup", "change", "paste"];
defaultOptions.common.debug = false;
defaultOptions.rules = {};
defaultOptions.rules.extra = {};
defaultOptions.rules.scores = {
wordNotEmail: -100,
wordMinLength: -50,
wordMaxLength: -50,
wordInvalidChar: -100,
wordSimilarToUsername: -100,
wordSequences: -20,
wordTwoCharacterClasses: 2,
wordRepetitions: -25,
wordLowercase: 1,
wordUppercase: 3,
wordOneNumber: 3,
wordThreeNumbers: 5,
wordOneSpecialChar: 3,
wordTwoSpecialChar: 5,
wordUpperLowerCombo: 2,
wordLetterNumberCombo: 2,
wordLetterNumberCharCombo: 2,
wordIsACommonPassword: -100
};
defaultOptions.rules.activated = {
wordNotEmail: true,
wordMinLength: true,
wordMaxLength: false,
wordInvalidChar: false,
wordSimilarToUsername: true,
wordSequences: true,
wordTwoCharacterClasses: true,
wordRepetitions: true,
wordLowercase: true,
wordUppercase: true,
wordOneNumber: true,
wordThreeNumbers: true,
wordOneSpecialChar: true,
wordTwoSpecialChar: true,
wordUpperLowerCombo: true,
wordLetterNumberCombo: true,
wordLetterNumberCharCombo: true,
wordIsACommonPassword: true
};
defaultOptions.rules.raisePower = 1.4;
// List taken from https://github.com/danielmiessler/SecLists (MIT License)
defaultOptions.rules.commonPasswords = [
'123456',
'password',
'12345678',
'qwerty',
'123456789',
'12345',
'1234',
'111111',
'1234567',
'dragon',
'123123',
'baseball',
'abc123',
'football',
'monkey',
'letmein',
'696969',
'shadow',
'master',
'666666',
'qwertyuiop',
'123321',
'mustang',
'1234567890',
'michael',
'654321',
'pussy',
'superman',
'1qaz2wsx',
'7777777',
'fuckyou',
'121212',
'000000',
'qazwsx',
'123qwe',
'killer',
'trustno1',
'jordan',
'jennifer',
'zxcvbnm',
'asdfgh',
'hunter',
'buster',
'soccer',
'harley',
'batman',
'andrew',
'tigger',
'sunshine',
'iloveyou',
'fuckme',
'2000',
'charlie',
'robert',
'thomas',
'hockey',
'ranger',
'daniel',
'starwars',
'klaster',
'112233',
'george',
'asshole',
'computer',
'michelle',
'jessica',
'pepper',
'1111',
'zxcvbn',
'555555',
'11111111',
'131313',
'freedom',
'777777',
'pass',
'fuck',
'maggie',
'159753',
'aaaaaa',
'ginger',
'princess',
'joshua',
'cheese',
'amanda',
'summer',
'love',
'ashley',
'6969',
'nicole',
'chelsea',
'biteme',
'matthew',
'access',
'yankees',
'987654321',
'dallas',
'austin',
'thunder',
'taylor',
'matrix'
];
defaultOptions.ui = {};
defaultOptions.ui.bootstrap2 = false;
defaultOptions.ui.bootstrap4 = false;
defaultOptions.ui.colorClasses = [
"danger", "danger", "danger", "warning", "warning", "success"
];
defaultOptions.ui.showProgressBar = true;
defaultOptions.ui.progressBarEmptyPercentage = 1;
defaultOptions.ui.progressBarMinPercentage = 1;
defaultOptions.ui.progressExtraCssClasses = '';
defaultOptions.ui.progressBarExtraCssClasses = '';
defaultOptions.ui.showPopover = false;
defaultOptions.ui.popoverPlacement = "bottom";
defaultOptions.ui.showStatus = false;
defaultOptions.ui.spanError = function (options, key) {
"use strict";
var text = options.i18n.t(key);
if (!text) { return ''; }
return '<span style="color: #d52929">' + text + '</span>';
};
defaultOptions.ui.popoverError = function (options) {
"use strict";
var errors = options.instances.errors,
errorsTitle = options.i18n.t("errorList"),
message = "<div>" + errorsTitle + "<ul class='error-list' style='margin-bottom: 0;'>";
jQuery.each(errors, function (idx, err) {
message += "<li>" + err + "</li>";
});
message += "</ul></div>";
return message;
};
defaultOptions.ui.showVerdicts = true;
defaultOptions.ui.showVerdictsInsideProgressBar = false;
defaultOptions.ui.useVerdictCssClass = false;
defaultOptions.ui.showErrors = false;
defaultOptions.ui.showScore = false;
defaultOptions.ui.container = undefined;
defaultOptions.ui.viewports = {
progress: undefined,
verdict: undefined,
errors: undefined,
score: undefined
};
defaultOptions.ui.scores = [0, 14, 26, 38, 50];
defaultOptions.i18n = {};
defaultOptions.i18n.t = i18n.t;
// Source: src/ui.js
var ui = {};
(function ($, ui) {
"use strict";
var statusClasses = ["error", "warning", "success"],
verdictKeys = [
"veryWeak", "weak", "normal", "medium", "strong", "veryStrong"
];
ui.getContainer = function (options, $el) {
var $container;
$container = $(options.ui.container);
if (!($container && $container.length === 1)) {
$container = $el.parent();
}
return $container;
};
ui.findElement = function ($container, viewport, cssSelector) {
if (viewport) {
return $container.find(viewport).find(cssSelector);
}
return $container.find(cssSelector);
};
ui.getUIElements = function (options, $el) {
var $container, result;
if (options.instances.viewports) {
return options.instances.viewports;
}
$container = ui.getContainer(options, $el);
result = {};
result.$progressbar = ui.findElement($container, options.ui.viewports.progress, "div.progress");
if (options.ui.showVerdictsInsideProgressBar) {
result.$verdict = result.$progressbar.find("span.password-verdict");
}
if (!options.ui.showPopover) {
if (!options.ui.showVerdictsInsideProgressBar) {
result.$verdict = ui.findElement($container, options.ui.viewports.verdict, "span.password-verdict");
}
result.$errors = ui.findElement($container, options.ui.viewports.errors, "ul.error-list");
}
result.$score = ui.findElement($container, options.ui.viewports.score,
"span.password-score");
options.instances.viewports = result;
return result;
};
ui.initProgressBar = function (options, $el) {
var $container = ui.getContainer(options, $el),
progressbar = "<div class='progress ";
if (options.ui.bootstrap2) {
// Boostrap 2
progressbar += options.ui.progressBarExtraCssClasses +
"'><div class='";
} else {
// Bootstrap 3 & 4
progressbar += options.ui.progressExtraCssClasses + "'><div class='" +
options.ui.progressBarExtraCssClasses + " progress-";
}
progressbar += "bar'>";
if (options.ui.showVerdictsInsideProgressBar) {
progressbar += "<span class='password-verdict'></span>";
}
progressbar += "</div></div>";
if (options.ui.viewports.progress) {
$container.find(options.ui.viewports.progress).append(progressbar);
} else {
$(progressbar).insertAfter($el);
}
};
ui.initHelper = function (options, $el, html, viewport) {
var $container = ui.getContainer(options, $el);
if (viewport) {
$container.find(viewport).append(html);
} else {
$(html).insertAfter($el);
}
};
ui.initVerdict = function (options, $el) {
ui.initHelper(options, $el, "<span class='password-verdict'></span>",
options.ui.viewports.verdict);
};
ui.initErrorList = function (options, $el) {
ui.initHelper(options, $el, "<ul class='error-list'></ul>",
options.ui.viewports.errors);
};
ui.initScore = function (options, $el) {
ui.initHelper(options, $el, "<span class='password-score'></span>",
options.ui.viewports.score);
};
ui.initPopover = function (options, $el) {
$el.popover("destroy");
$el.popover({
html: true,
placement: options.ui.popoverPlacement,
trigger: "manual",
content: " "
});
};
ui.initUI = function (options, $el) {
if (options.ui.showPopover) {
ui.initPopover(options, $el);
} else {
if (options.ui.showErrors) { ui.initErrorList(options, $el); }
if (options.ui.showVerdicts && !options.ui.showVerdictsInsideProgressBar) {
ui.initVerdict(options, $el);
}
}
if (options.ui.showProgressBar) {
ui.initProgressBar(options, $el);
}
if (options.ui.showScore) {
ui.initScore(options, $el);
}
};
ui.updateProgressBar = function (options, $el, cssClass, percentage) {
var $progressbar = ui.getUIElements(options, $el).$progressbar,
$bar = $progressbar.find(".progress-bar"),
cssPrefix = "progress-";
if (options.ui.bootstrap2) {
$bar = $progressbar.find(".bar");
cssPrefix = "";
}
$.each(options.ui.colorClasses, function (idx, value) {
if (options.ui.bootstrap4) {
$bar.removeClass("bg-" + value);
} else {
$bar.removeClass(cssPrefix + "bar-" + value);
}
});
if (options.ui.bootstrap4) {
$bar.addClass("bg-" + options.ui.colorClasses[cssClass]);
} else {
$bar.addClass(cssPrefix + "bar-" + options.ui.colorClasses[cssClass]);
}
$bar.css("width", percentage + '%');
};
ui.updateVerdict = function (options, $el, cssClass, text) {
var $verdict = ui.getUIElements(options, $el).$verdict;
$verdict.removeClass(options.ui.colorClasses.join(' '));
if (cssClass > -1) {
$verdict.addClass(options.ui.colorClasses[cssClass]);
}
if (options.ui.showVerdictsInsideProgressBar) {
$verdict.css('white-space', 'nowrap');
}
$verdict.html(text);
};
ui.updateErrors = function (options, $el, remove) {
var $errors = ui.getUIElements(options, $el).$errors,
html = "";
if (!remove) {
$.each(options.instances.errors, function (idx, err) {
html += "<li>" + err + "</li>";
});
}
$errors.html(html);
};
ui.updateScore = function (options, $el, score, remove) {
var $score = ui.getUIElements(options, $el).$score,
html = "";
if (!remove) { html = score.toFixed(2); }
$score.html(html);
};
ui.updatePopover = function (options, $el, verdictText, remove) {
var popover = $el.data("bs.popover"),
html = "",
hide = true;
if (options.ui.showVerdicts &&
!options.ui.showVerdictsInsideProgressBar &&
verdictText.length > 0) {
html = "<h5><span class='password-verdict'>" + verdictText +
"</span></h5>";
hide = false;
}
if (options.ui.showErrors) {
if (options.instances.errors.length > 0) {
hide = false;
}
html += options.ui.popoverError(options);
}
if (hide || remove) {
$el.popover("hide");
return;
}
if (options.ui.bootstrap2) { popover = $el.data("popover"); }
if (popover.$arrow && popover.$arrow.parents("body").length > 0) {
$el.find("+ .popover .popover-content").html(html);
} else {
// It's hidden
popover.options.content = html;
$el.popover("show");
}
};
ui.updateFieldStatus = function (options, $el, cssClass, remove) {
var targetClass = options.ui.bootstrap2 ? ".control-group" : ".form-group",
$container = $el.parents(targetClass).first();
$.each(statusClasses, function (idx, css) {
if (!options.ui.bootstrap2) { css = "has-" + css; }
$container.removeClass(css);
});
if (remove) { return; }
cssClass = statusClasses[Math.floor(cssClass / 2)];
if (!options.ui.bootstrap2) { cssClass = "has-" + cssClass; }
$container.addClass(cssClass);
};
ui.percentage = function (options, score, maximun) {
var result = Math.floor(100 * score / maximun),
min = options.ui.progressBarMinPercentage;
result = result <= min ? min : result;
result = result > 100 ? 100 : result;
return result;
};
ui.getVerdictAndCssClass = function (options, score) {
var level, verdict;
if (score === undefined) { return ['', 0]; }
if (score <= options.ui.scores[0]) {
level = 0;
} else if (score < options.ui.scores[1]) {
level = 1;
} else if (score < options.ui.scores[2]) {
level = 2;
} else if (score < options.ui.scores[3]) {
level = 3;
} else if (score < options.ui.scores[4]) {
level = 4;
} else {
level = 5;
}
verdict = verdictKeys[level];
return [options.i18n.t(verdict), level];
};
ui.updateUI = function (options, $el, score) {
var cssClass, barPercentage, verdictText, verdictCssClass;
cssClass = ui.getVerdictAndCssClass(options, score);
verdictText = score === 0 ? '' : cssClass[0];
cssClass = cssClass[1];
verdictCssClass = options.ui.useVerdictCssClass ? cssClass : -1;
if (options.ui.showProgressBar) {
if (score === undefined) {
barPercentage = options.ui.progressBarEmptyPercentage;
} else {
barPercentage = ui.percentage(options, score, options.ui.scores[4]);
}
ui.updateProgressBar(options, $el, cssClass, barPercentage);
if (options.ui.showVerdictsInsideProgressBar) {
ui.updateVerdict(options, $el, verdictCssClass, verdictText);
}
}
if (options.ui.showStatus) {
ui.updateFieldStatus(options, $el, cssClass, score === undefined);
}
if (options.ui.showPopover) {
ui.updatePopover(options, $el, verdictText, score === undefined);
} else {
if (options.ui.showVerdicts && !options.ui.showVerdictsInsideProgressBar) {
ui.updateVerdict(options, $el, verdictCssClass, verdictText);
}
if (options.ui.showErrors) {
ui.updateErrors(options, $el, score === undefined);
}
}
if (options.ui.showScore) {
ui.updateScore(options, $el, score, score === undefined);
}
};
}(jQuery, ui));
// Source: src/methods.js
var methods = {};
(function ($, methods) {
"use strict";
var onKeyUp, onPaste, applyToAll;
onKeyUp = function (event) {
var $el = $(event.target),
options = $el.data("pwstrength-bootstrap"),
word = $el.val(),
userInputs,
verdictText,
verdictLevel,
score;
if (options === undefined) { return; }
options.instances.errors = [];
if (word.length === 0) {
score = undefined;
} else {
if (options.common.zxcvbn) {
userInputs = [];
$.each(options.common.userInputs.concat([options.common.usernameField]), function (idx, selector) {
var value = $(selector).val();
if (value) { userInputs.push(value); }
});
userInputs = userInputs.concat(options.common.zxcvbnTerms);
score = zxcvbn(word, userInputs).guesses;
score = Math.log(score) * Math.LOG2E;
} else {
score = rulesEngine.executeRules(options, word);
}
if ($.isFunction(options.common.onScore)) {
score = options.common.onScore(options, word, score);
}
}
ui.updateUI(options, $el, score);
verdictText = ui.getVerdictAndCssClass(options, score);
verdictLevel = verdictText[1];
verdictText = verdictText[0];
if (options.common.debug) {
console.log(score + ' - ' + verdictText);
}
if ($.isFunction(options.common.onKeyUp)) {
options.common.onKeyUp(event, {
score: score,
verdictText: verdictText,
verdictLevel: verdictLevel
});
}
};
onPaste = function (event) {
// This handler is necessary because the paste event fires before the
// content is actually in the input, so we cannot read its value right
// away. Therefore, the timeouts.
var $el = $(event.target),
word = $el.val(),
tries = 0,
callback;
callback = function () {
var newWord = $el.val();
if (newWord !== word) {
onKeyUp(event);
} else if (tries < 3) {
tries += 1;
setTimeout(callback, 100);
}
};
setTimeout(callback, 100);
};
methods.init = function (settings) {
this.each(function (idx, el) {
// Make it deep extend (first param) so it extends also the
// rules and other inside objects
var clonedDefaults = $.extend(true, {}, defaultOptions),
localOptions = $.extend(true, clonedDefaults, settings),
$el = $(el);
localOptions.instances = {};
$el.data("pwstrength-bootstrap", localOptions);
$.each(localOptions.common.events, function (idx, eventName) {
var handler = eventName === "paste" ? onPaste : onKeyUp;
$el.on(eventName, handler);
});
ui.initUI(localOptions, $el);
$el.trigger("keyup");
if ($.isFunction(localOptions.common.onLoad)) {
localOptions.common.onLoad();
}
});
return this;
};
methods.destroy = function () {
this.each(function (idx, el) {
var $el = $(el),
options = $el.data("pwstrength-bootstrap"),
elements = ui.getUIElements(options, $el);
elements.$progressbar.remove();
elements.$verdict.remove();
elements.$errors.remove();
$el.removeData("pwstrength-bootstrap");
});
};
methods.forceUpdate = function () {
this.each(function (idx, el) {
var event = { target: el };
onKeyUp(event);
});
};
methods.addRule = function (name, method, score, active) {
this.each(function (idx, el) {
var options = $(el).data("pwstrength-bootstrap");
options.rules.activated[name] = active;
options.rules.scores[name] = score;
options.rules.extra[name] = method;
});
};
applyToAll = function (rule, prop, value) {
this.each(function (idx, el) {
$(el).data("pwstrength-bootstrap").rules[prop][rule] = value;
});
};
methods.changeScore = function (rule, score) {
applyToAll.call(this, rule, "scores", score);
};
methods.ruleActive = function (rule, active) {
applyToAll.call(this, rule, "activated", active);
};
methods.ruleIsMet = function (rule) {
if ($.isFunction(rulesEngine.validation[rule])) {
if (rule === "wordMinLength") {
rule = "wordMinLengthStaticScore";
} else if (rule === "wordMaxLength") {
rule = "wordMaxLengthStaticScore";
}
var rulesMetCnt = 0;
this.each(function (idx, el) {
var options = $(el).data("pwstrength-bootstrap");
rulesMetCnt += rulesEngine.validation[rule](options, $(el).val(), 1);
});
return (rulesMetCnt === this.length);
}
$.error("Rule " + rule + " does not exist on jQuery.pwstrength-bootstrap.validation");
};
$.fn.pwstrength = function (method) {
var result;
if (methods[method]) {
result = methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === "object" || !method) {
result = methods.init.apply(this, arguments);
} else {
$.error("Method " + method + " does not exist on jQuery.pwstrength-bootstrap");
}
return result;
};
}(jQuery, methods));
}(jQuery)); |
/*
* /MathJax/localization/bcc/HTML-CSS.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Localization.addTranslation("bcc","HTML-CSS",{version:"2.7.4",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/bcc/HTML-CSS.js");
|
import React, {Component} from "react";
import App from "../components/App";
class Root extends Component {
constructor() {
super();
}
render() {
return (
<div className="siteImportExport-app personaBar-mainContainer">
<App />
</div>
);
}
}
export default (Root); |
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import SafeAnchor from './SafeAnchor';
import createChainedFunction from './utils/createChainedFunction';
var propTypes = {
active: React.PropTypes.bool,
disabled: React.PropTypes.bool,
role: React.PropTypes.string,
href: React.PropTypes.string,
onClick: React.PropTypes.func,
onSelect: React.PropTypes.func,
eventKey: React.PropTypes.any
};
var defaultProps = {
active: false,
disabled: false
};
var NavItem = function (_React$Component) {
_inherits(NavItem, _React$Component);
function NavItem(props, context) {
_classCallCheck(this, NavItem);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleClick = _this.handleClick.bind(_this);
return _this;
}
NavItem.prototype.handleClick = function handleClick(e) {
if (this.props.onSelect) {
e.preventDefault();
if (!this.props.disabled) {
this.props.onSelect(this.props.eventKey, e);
}
}
};
NavItem.prototype.render = function render() {
var _props = this.props;
var active = _props.active;
var disabled = _props.disabled;
var onClick = _props.onClick;
var className = _props.className;
var style = _props.style;
var props = _objectWithoutProperties(_props, ['active', 'disabled', 'onClick', 'className', 'style']);
delete props.onSelect;
delete props.eventKey;
// These are injected down by `<Nav>` for building `<SubNav>`s.
delete props.activeKey;
delete props.activeHref;
if (!props.role) {
if (props.href === '#') {
props.role = 'button';
}
} else if (props.role === 'tab') {
props['aria-selected'] = active;
}
return React.createElement(
'li',
{
role: 'presentation',
className: classNames(className, { active: active, disabled: disabled }),
style: style
},
React.createElement(SafeAnchor, _extends({}, props, {
disabled: disabled,
onClick: createChainedFunction(onClick, this.handleClick)
}))
);
};
return NavItem;
}(React.Component);
NavItem.propTypes = propTypes;
NavItem.defaultProps = defaultProps;
export default NavItem; |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v16.0.1
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// class returns unique instance id's for columns.
// eg, the following calls (in this order) will result in:
//
// getInstanceIdForKey('country') => 0
// getInstanceIdForKey('country') => 1
// getInstanceIdForKey('country') => 2
// getInstanceIdForKey('country') => 3
// getInstanceIdForKey('age') => 0
// getInstanceIdForKey('age') => 1
// getInstanceIdForKey('country') => 4
var GroupInstanceIdCreator = (function () {
function GroupInstanceIdCreator() {
// this map contains keys to numbers, so we remember what the last call was
this.existingIds = {};
}
GroupInstanceIdCreator.prototype.getInstanceIdForKey = function (key) {
var lastResult = this.existingIds[key];
var result;
if (typeof lastResult !== 'number') {
// first time this key
result = 0;
}
else {
result = lastResult + 1;
}
this.existingIds[key] = result;
return result;
};
return GroupInstanceIdCreator;
}());
exports.GroupInstanceIdCreator = GroupInstanceIdCreator;
|
QUnit.module( "ready" );
( function() {
var notYetReady, noEarlyExecution,
order = [],
args = {};
notYetReady = !jQuery.isReady;
QUnit.test( "jQuery.isReady", function( assert ) {
assert.expect( 2 );
assert.equal( notYetReady, true, "jQuery.isReady should not be true before DOM ready" );
assert.equal( jQuery.isReady, true, "jQuery.isReady should be true once DOM is ready" );
} );
// Create an event handler.
function makeHandler( testId ) {
// When returned function is executed, push testId onto `order` array
// to ensure execution order. Also, store event handler arg to ensure
// the correct arg is being passed into the event handler.
return function( arg ) {
order.push( testId );
args[ testId ] = arg;
};
}
// Bind to the ready event in every possible way.
jQuery( makeHandler( "a" ) );
jQuery( document ).ready( makeHandler( "b" ) );
jQuery( document ).on( "ready.readytest", makeHandler( "c" ) );
// Do it twice, just to be sure.
jQuery( makeHandler( "d" ) );
jQuery( document ).ready( makeHandler( "e" ) );
jQuery( document ).on( "ready.readytest", makeHandler( "f" ) );
noEarlyExecution = order.length === 0;
// This assumes that QUnit tests are run on DOM ready!
QUnit.test( "jQuery ready", function( assert ) {
assert.expect( 10 );
assert.ok( noEarlyExecution, "Handlers bound to DOM ready should not execute before DOM ready" );
// Ensure execution order.
assert.deepEqual( order, [ "a", "b", "d", "e", "c", "f" ],
"Bound DOM ready handlers should execute in on-order, but those bound with" +
"jQuery(document).on( 'ready', fn ) will always execute last" );
// Ensure handler argument is correct.
assert.equal( args[ "a" ], jQuery,
"Argument passed to fn in jQuery( fn ) should be jQuery" );
assert.equal( args[ "b" ], jQuery,
"Argument passed to fn in jQuery(document).ready( fn ) should be jQuery" );
assert.ok( args[ "c" ] instanceof jQuery.Event,
"Argument passed to fn in jQuery(document).on( 'ready', fn )" +
" should be an event object" );
order = [];
// Now that the ready event has fired, again bind to the ready event
// in every possible way. These event handlers should execute immediately.
jQuery( makeHandler( "g" ) );
assert.equal( order.pop(), "g", "Event handler should execute immediately" );
assert.equal( args[ "g" ], jQuery,
"Argument passed to fn in jQuery( fn ) should be jQuery" );
jQuery( document ).ready( makeHandler( "h" ) );
assert.equal( order.pop(), "h", "Event handler should execute immediately" );
assert.equal( args[ "h" ], jQuery,
"Argument passed to fn in jQuery(document).ready( fn ) should be jQuery" );
jQuery( document ).on( "ready.readytest", makeHandler( "never" ) );
assert.equal( order.length, 0,
"Event handler should never execute since DOM ready has already passed" );
// Cleanup.
jQuery( document ).off( "ready.readytest" );
} );
} )();
|
;(function (globalObject) {
'use strict';
/*
* bignumber.js v6.0.0
* A JavaScript library for arbitrary-precision arithmetic.
* https://github.com/MikeMcl/bignumber.js
* Copyright (c) 2018 Michael Mclaughlin <[email protected]>
* MIT Licensed.
*
* BigNumber.prototype methods | BigNumber methods
* |
* absoluteValue abs | clone
* comparedTo | config set
* decimalPlaces dp | DECIMAL_PLACES
* dividedBy div | ROUNDING_MODE
* dividedToIntegerBy idiv | EXPONENTIAL_AT
* exponentiatedBy pow | RANGE
* integerValue | CRYPTO
* isEqualTo eq | MODULO_MODE
* isFinite | POW_PRECISION
* isGreaterThan gt | FORMAT
* isGreaterThanOrEqualTo gte | ALPHABET
* isInteger | isBigNumber
* isLessThan lt | maximum max
* isLessThanOrEqualTo lte | minimum min
* isNaN | random
* isNegative |
* isPositive |
* isZero |
* minus |
* modulo mod |
* multipliedBy times |
* negated |
* plus |
* precision sd |
* shiftedBy |
* squareRoot sqrt |
* toExponential |
* toFixed |
* toFormat |
* toFraction |
* toJSON |
* toNumber |
* toPrecision |
* toString |
* valueOf |
*
*/
var BigNumber,
isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,
mathceil = Math.ceil,
mathfloor = Math.floor,
bignumberError = '[BigNumber Error] ',
tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',
BASE = 1e14,
LOG_BASE = 14,
MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
// MAX_INT32 = 0x7fffffff, // 2^31 - 1
POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
SQRT_BASE = 1e7,
// EDITABLE
// The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
// the arguments to toExponential, toFixed, toFormat, and toPrecision.
MAX = 1E9; // 0 to MAX_INT32
/*
* Create and return a BigNumber constructor.
*/
function clone(configObject) {
var div, convertBase, parseNumeric,
P = BigNumber.prototype,
ONE = new BigNumber(1),
//----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------
// The default values below must be integers within the inclusive ranges stated.
// The values can also be changed at run-time using BigNumber.set.
// The maximum number of decimal places for operations involving division.
DECIMAL_PLACES = 20, // 0 to MAX
// The rounding mode used when rounding to the above decimal places, and when using
// toExponential, toFixed, toFormat and toPrecision, and round (default value).
// UP 0 Away from zero.
// DOWN 1 Towards zero.
// CEIL 2 Towards +Infinity.
// FLOOR 3 Towards -Infinity.
// HALF_UP 4 Towards nearest neighbour. If equidistant, up.
// HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
// HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
// HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
// HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
ROUNDING_MODE = 4, // 0 to 8
// EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
// The exponent value at and beneath which toString returns exponential notation.
// Number type: -7
TO_EXP_NEG = -7, // 0 to -MAX
// The exponent value at and above which toString returns exponential notation.
// Number type: 21
TO_EXP_POS = 21, // 0 to MAX
// RANGE : [MIN_EXP, MAX_EXP]
// The minimum exponent value, beneath which underflow to zero occurs.
// Number type: -324 (5e-324)
MIN_EXP = -1e7, // -1 to -MAX
// The maximum exponent value, above which overflow to Infinity occurs.
// Number type: 308 (1.7976931348623157e+308)
// For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
MAX_EXP = 1e7, // 1 to MAX
// Whether to use cryptographically-secure random number generation, if available.
CRYPTO = false, // true or false
// The modulo mode used when calculating the modulus: a mod n.
// The quotient (q = a / n) is calculated according to the corresponding rounding mode.
// The remainder (r) is calculated as: r = a - n * q.
//
// UP 0 The remainder is positive if the dividend is negative, else is negative.
// DOWN 1 The remainder has the same sign as the dividend.
// This modulo mode is commonly known as 'truncated division' and is
// equivalent to (a % n) in JavaScript.
// FLOOR 3 The remainder has the same sign as the divisor (Python %).
// HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
// EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
// The remainder is always positive.
//
// The truncated division, floored division, Euclidian division and IEEE 754 remainder
// modes are commonly used for the modulus operation.
// Although the other rounding modes can also be used, they may not give useful results.
MODULO_MODE = 1, // 0 to 9
// The maximum number of significant digits of the result of the exponentiatedBy operation.
// If POW_PRECISION is 0, there will be unlimited significant digits.
POW_PRECISION = 0, // 0 to MAX
// The format specification used by the BigNumber.prototype.toFormat method.
FORMAT = {
decimalSeparator: '.',
groupSeparator: ',',
groupSize: 3,
secondaryGroupSize: 0,
fractionGroupSeparator: '\xA0', // non-breaking space
fractionGroupSize: 0
},
// The alphabet used for base conversion.
// It must be at least 2 characters long, with no '.' or repeated character.
// '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
//------------------------------------------------------------------------------------------
// CONSTRUCTOR
/*
* The BigNumber constructor and exported function.
* Create and return a new instance of a BigNumber object.
*
* n {number|string|BigNumber} A numeric value.
* [b] {number} The base of n. Integer, 2 to ALPHABET.length inclusive.
*/
function BigNumber( n, b ) {
var alphabet, c, e, i, isNum, len, str,
x = this;
// Enable constructor usage without new.
if ( !( x instanceof BigNumber ) ) {
// Don't throw on constructor call without new (#81).
// '[BigNumber Error] Constructor call without new: {n}'
//throw Error( bignumberError + ' Constructor call without new: ' + n );
return new BigNumber( n, b );
}
if ( b == null ) {
// Duplicate.
if ( n instanceof BigNumber ) {
x.s = n.s;
x.e = n.e;
x.c = ( n = n.c ) ? n.slice() : n;
return;
}
isNum = typeof n == 'number';
if ( isNum && n * 0 == 0 ) {
// Use `1 / n` to handle minus zero also.
x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
// Faster path for integers.
if ( n === ~~n ) {
for ( e = 0, i = n; i >= 10; i /= 10, e++ );
x.e = e;
x.c = [n];
return;
}
str = n + '';
} else {
if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, isNum );
x.s = str.charCodeAt(0) == 45 ? ( str = str.slice(1), -1 ) : 1;
}
} else {
// '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'
intCheck( b, 2, ALPHABET.length, 'Base' );
str = n + '';
// Allow exponential notation to be used with base 10 argument, while
// also rounding to DECIMAL_PLACES as with other bases.
if ( b == 10 ) {
x = new BigNumber( n instanceof BigNumber ? n : str );
return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
}
isNum = typeof n == 'number';
if (isNum) {
// Avoid potential interpretation of Infinity and NaN as base 44+ values.
if ( n * 0 != 0 ) return parseNumeric( x, str, isNum, b );
x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
// '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'
if ( str.replace( /^0\.0*|\./, '' ).length > 15 ) {
throw Error
( tooManyDigits + n );
}
// Prevent later check for length on converted number.
isNum = false;
} else {
x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
// Allow e.g. hexadecimal 'FF' as well as 'ff'.
if ( b > 10 && b < 37 ) str = str.toLowerCase();
}
alphabet = ALPHABET.slice( 0, b );
e = i = 0;
// Check that str is a valid base b number.
// Don't use RegExp so alphabet can contain special characters.
for ( len = str.length; i < len; i++ ) {
if ( alphabet.indexOf( c = str.charAt(i) ) < 0 ) {
if ( c == '.' ) {
// If '.' is not the first character and it has not be found before.
if ( i > e ) {
e = len;
continue;
}
}
return parseNumeric( x, n + '', isNum, b );
}
}
str = convertBase( str, b, 10, x.s );
}
// Decimal point?
if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
// Exponential form?
if ( ( i = str.search( /e/i ) ) > 0 ) {
// Determine exponent.
if ( e < 0 ) e = i;
e += +str.slice( i + 1 );
str = str.substring( 0, i );
} else if ( e < 0 ) {
// Integer.
e = str.length;
}
// Determine leading zeros.
for ( i = 0; str.charCodeAt(i) === 48; i++ );
// Determine trailing zeros.
for ( len = str.length; str.charCodeAt(--len) === 48; );
str = str.slice( i, len + 1 );
if (str) {
len = str.length;
// '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'
if ( isNum && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) {
throw Error
( tooManyDigits + ( x.s * n ) );
}
e = e - i - 1;
// Overflow?
if ( e > MAX_EXP ) {
// Infinity.
x.c = x.e = null;
// Underflow?
} else if ( e < MIN_EXP ) {
// Zero.
x.c = [ x.e = 0 ];
} else {
x.e = e;
x.c = [];
// Transform base
// e is the base 10 exponent.
// i is where to slice str to get the first element of the coefficient array.
i = ( e + 1 ) % LOG_BASE;
if ( e < 0 ) i += LOG_BASE;
if ( i < len ) {
if (i) x.c.push( +str.slice( 0, i ) );
for ( len -= LOG_BASE; i < len; ) {
x.c.push( +str.slice( i, i += LOG_BASE ) );
}
str = str.slice(i);
i = LOG_BASE - str.length;
} else {
i -= len;
}
for ( ; i--; str += '0' );
x.c.push( +str );
}
} else {
// Zero.
x.c = [ x.e = 0 ];
}
}
// CONSTRUCTOR PROPERTIES
BigNumber.clone = clone;
BigNumber.ROUND_UP = 0;
BigNumber.ROUND_DOWN = 1;
BigNumber.ROUND_CEIL = 2;
BigNumber.ROUND_FLOOR = 3;
BigNumber.ROUND_HALF_UP = 4;
BigNumber.ROUND_HALF_DOWN = 5;
BigNumber.ROUND_HALF_EVEN = 6;
BigNumber.ROUND_HALF_CEIL = 7;
BigNumber.ROUND_HALF_FLOOR = 8;
BigNumber.EUCLID = 9;
/*
* Configure infrequently-changing library-wide settings.
*
* Accept an object with the following optional properties (if the value of a property is
* a number, it must be an integer within the inclusive range stated):
*
* DECIMAL_PLACES {number} 0 to MAX
* ROUNDING_MODE {number} 0 to 8
* EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]
* RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]
* CRYPTO {boolean} true or false
* MODULO_MODE {number} 0 to 9
* POW_PRECISION {number} 0 to MAX
* ALPHABET {string} A string of two or more unique characters, and not
* containing '.'. The empty string, null or undefined
* resets the alphabet to its default value.
* FORMAT {object} An object with some of the following properties:
* decimalSeparator {string}
* groupSeparator {string}
* groupSize {number}
* secondaryGroupSize {number}
* fractionGroupSeparator {string}
* fractionGroupSize {number}
*
* (The values assigned to the above FORMAT object properties are not checked for validity.)
*
* E.g.
* BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
*
* Ignore properties/parameters set to null or undefined, except for ALPHABET.
*
* Return an object with the properties current values.
*/
BigNumber.config = BigNumber.set = function (obj) {
var p, v;
if ( obj != null ) {
if ( typeof obj == 'object' ) {
// DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
// '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'
if ( obj.hasOwnProperty( p = 'DECIMAL_PLACES' ) ) {
v = obj[p];
intCheck( v, 0, MAX, p );
DECIMAL_PLACES = v;
}
// ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
// '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'
if ( obj.hasOwnProperty( p = 'ROUNDING_MODE' ) ) {
v = obj[p];
intCheck( v, 0, 8, p );
ROUNDING_MODE = v;
}
// EXPONENTIAL_AT {number|number[]}
// Integer, -MAX to MAX inclusive or
// [integer -MAX to 0 inclusive, 0 to MAX inclusive].
// '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'
if ( obj.hasOwnProperty( p = 'EXPONENTIAL_AT' ) ) {
v = obj[p];
if ( isArray(v) ) {
intCheck( v[0], -MAX, 0, p );
intCheck( v[1], 0, MAX, p );
TO_EXP_NEG = v[0];
TO_EXP_POS = v[1];
} else {
intCheck( v, -MAX, MAX, p );
TO_EXP_NEG = -( TO_EXP_POS = v < 0 ? -v : v );
}
}
// RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
// [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
// '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'
if ( obj.hasOwnProperty( p = 'RANGE' ) ) {
v = obj[p];
if ( isArray(v) ) {
intCheck( v[0], -MAX, -1, p );
intCheck( v[1], 1, MAX, p );
MIN_EXP = v[0];
MAX_EXP = v[1];
} else {
intCheck( v, -MAX, MAX, p );
if (v) {
MIN_EXP = -( MAX_EXP = v < 0 ? -v : v );
} else {
throw Error
( bignumberError + p + ' cannot be zero: ' + v );
}
}
}
// CRYPTO {boolean} true or false.
// '[BigNumber Error] CRYPTO not true or false: {v}'
// '[BigNumber Error] crypto unavailable'
if ( obj.hasOwnProperty( p = 'CRYPTO' ) ) {
v = obj[p];
if ( v === !!v ) {
if (v) {
if ( typeof crypto != 'undefined' && crypto &&
(crypto.getRandomValues || crypto.randomBytes) ) {
CRYPTO = v;
} else {
CRYPTO = !v;
throw Error
( bignumberError + 'crypto unavailable' );
}
} else {
CRYPTO = v;
}
} else {
throw Error
( bignumberError + p + ' not true or false: ' + v );
}
}
// MODULO_MODE {number} Integer, 0 to 9 inclusive.
// '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'
if ( obj.hasOwnProperty( p = 'MODULO_MODE' ) ) {
v = obj[p];
intCheck( v, 0, 9, p );
MODULO_MODE = v;
}
// POW_PRECISION {number} Integer, 0 to MAX inclusive.
// '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'
if ( obj.hasOwnProperty( p = 'POW_PRECISION' ) ) {
v = obj[p];
intCheck( v, 0, MAX, p );
POW_PRECISION = v;
}
// FORMAT {object}
// '[BigNumber Error] FORMAT not an object: {v}'
if ( obj.hasOwnProperty( p = 'FORMAT' ) ) {
v = obj[p];
if ( typeof v == 'object' ) FORMAT = v;
else throw Error
( bignumberError + p + ' not an object: ' + v );
}
// ALPHABET {string}
// '[BigNumber Error] ALPHABET invalid: {v}'
if ( obj.hasOwnProperty( p = 'ALPHABET' ) ) {
v = obj[p];
// Disallow if only one character, or contains '.' or a repeated character.
if ( typeof v == 'string' && !/^.$|\.|(.).*\1/.test(v) ) {
ALPHABET = v;
} else {
throw Error
( bignumberError + p + ' invalid: ' + v );
}
}
} else {
// '[BigNumber Error] Object expected: {v}'
throw Error
( bignumberError + 'Object expected: ' + obj );
}
}
return {
DECIMAL_PLACES: DECIMAL_PLACES,
ROUNDING_MODE: ROUNDING_MODE,
EXPONENTIAL_AT: [ TO_EXP_NEG, TO_EXP_POS ],
RANGE: [ MIN_EXP, MAX_EXP ],
CRYPTO: CRYPTO,
MODULO_MODE: MODULO_MODE,
POW_PRECISION: POW_PRECISION,
FORMAT: FORMAT,
ALPHABET: ALPHABET
};
};
/*
* Return true if v is a BigNumber instance, otherwise return false.
*
* v {any}
*/
BigNumber.isBigNumber = function (v) {
return v instanceof BigNumber || v && v._isBigNumber === true || false;
};
/*
* Return a new BigNumber whose value is the maximum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.maximum = BigNumber.max = function () {
return maxOrMin( arguments, P.lt );
};
/*
* Return a new BigNumber whose value is the minimum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.minimum = BigNumber.min = function () {
return maxOrMin( arguments, P.gt );
};
/*
* Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
* and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
* zeros are produced).
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
*
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'
* '[BigNumber Error] crypto unavailable'
*/
BigNumber.random = (function () {
var pow2_53 = 0x20000000000000;
// Return a 53 bit integer n, where 0 <= n < 9007199254740992.
// Check if Math.random() produces more than 32 bits of randomness.
// If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
// 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
? function () { return mathfloor( Math.random() * pow2_53 ); }
: function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
(Math.random() * 0x800000 | 0); };
return function (dp) {
var a, b, e, k, v,
i = 0,
c = [],
rand = new BigNumber(ONE);
if ( dp == null ) dp = DECIMAL_PLACES;
else intCheck( dp, 0, MAX );
k = mathceil( dp / LOG_BASE );
if (CRYPTO) {
// Browsers supporting crypto.getRandomValues.
if (crypto.getRandomValues) {
a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );
for ( ; i < k; ) {
// 53 bits:
// ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
// 11111 11111111 11111111 11111111 11100000 00000000 00000000
// ((Math.pow(2, 32) - 1) >>> 11).toString(2)
// 11111 11111111 11111111
// 0x20000 is 2^21.
v = a[i] * 0x20000 + (a[i + 1] >>> 11);
// Rejection sampling:
// 0 <= v < 9007199254740992
// Probability that v >= 9e15, is
// 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
if ( v >= 9e15 ) {
b = crypto.getRandomValues( new Uint32Array(2) );
a[i] = b[0];
a[i + 1] = b[1];
} else {
// 0 <= v <= 8999999999999999
// 0 <= (v % 1e14) <= 99999999999999
c.push( v % 1e14 );
i += 2;
}
}
i = k / 2;
// Node.js supporting crypto.randomBytes.
} else if (crypto.randomBytes) {
// buffer
a = crypto.randomBytes( k *= 7 );
for ( ; i < k; ) {
// 0x1000000000000 is 2^48, 0x10000000000 is 2^40
// 0x100000000 is 2^32, 0x1000000 is 2^24
// 11111 11111111 11111111 11111111 11111111 11111111 11111111
// 0 <= v < 9007199254740992
v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
if ( v >= 9e15 ) {
crypto.randomBytes(7).copy( a, i );
} else {
// 0 <= (v % 1e14) <= 99999999999999
c.push( v % 1e14 );
i += 7;
}
}
i = k / 7;
} else {
CRYPTO = false;
throw Error
( bignumberError + 'crypto unavailable' );
}
}
// Use Math.random.
if (!CRYPTO) {
for ( ; i < k; ) {
v = random53bitInt();
if ( v < 9e15 ) c[i++] = v % 1e14;
}
}
k = c[--i];
dp %= LOG_BASE;
// Convert trailing digits to zeros according to dp.
if ( k && dp ) {
v = POWS_TEN[LOG_BASE - dp];
c[i] = mathfloor( k / v ) * v;
}
// Remove trailing elements which are zero.
for ( ; c[i] === 0; c.pop(), i-- );
// Zero?
if ( i < 0 ) {
c = [ e = 0 ];
} else {
// Remove leading elements which are zero and adjust exponent accordingly.
for ( e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);
// Count the digits of the first element of c to determine leading zeros, and...
for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
// adjust the exponent accordingly.
if ( i < LOG_BASE ) e -= LOG_BASE - i;
}
rand.e = e;
rand.c = c;
return rand;
};
})();
// PRIVATE FUNCTIONS
// Called by BigNumber and BigNumber.prototype.toString.
convertBase = ( function () {
var decimal = '0123456789';
/*
* Convert string of baseIn to an array of numbers of baseOut.
* Eg. toBaseOut('255', 10, 16) returns [15, 15].
* Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].
*/
function toBaseOut( str, baseIn, baseOut, alphabet ) {
var j,
arr = [0],
arrL,
i = 0,
len = str.length;
for ( ; i < len; ) {
for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
arr[0] += alphabet.indexOf( str.charAt( i++ ) );
for ( j = 0; j < arr.length; j++ ) {
if ( arr[j] > baseOut - 1 ) {
if ( arr[j + 1] == null ) arr[j + 1] = 0;
arr[j + 1] += arr[j] / baseOut | 0;
arr[j] %= baseOut;
}
}
}
return arr.reverse();
}
// Convert a numeric string of baseIn to a numeric string of baseOut.
// If the caller is toString, we are converting from base 10 to baseOut.
// If the caller is BigNumber, we are converting from baseIn to base 10.
return function ( str, baseIn, baseOut, sign, callerIsToString ) {
var alphabet, d, e, k, r, x, xc, y,
i = str.indexOf( '.' ),
dp = DECIMAL_PLACES,
rm = ROUNDING_MODE;
// Non-integer.
if ( i >= 0 ) {
k = POW_PRECISION;
// Unlimited precision.
POW_PRECISION = 0;
str = str.replace( '.', '' );
y = new BigNumber(baseIn);
x = y.pow( str.length - i );
POW_PRECISION = k;
// Convert str as if an integer, then restore the fraction part by dividing the
// result by its base raised to a power.
y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e, '0' ),
10, baseOut, decimal );
y.e = y.c.length;
}
// Convert the number as integer.
xc = toBaseOut( str, baseIn, baseOut, callerIsToString
? ( alphabet = ALPHABET, decimal )
: ( alphabet = decimal, ALPHABET ) );
// xc now represents str as an integer and converted to baseOut. e is the exponent.
e = k = xc.length;
// Remove trailing zeros.
for ( ; xc[--k] == 0; xc.pop() );
// Zero?
if ( !xc[0] ) return alphabet.charAt(0);
// Does str represent an integer? If so, no need for the division.
if ( i < 0 ) {
--e;
} else {
x.c = xc;
x.e = e;
// The sign is needed for correct rounding.
x.s = sign;
x = div( x, y, dp, rm, baseOut );
xc = x.c;
r = x.r;
e = x.e;
}
// xc now represents str converted to baseOut.
// THe index of the rounding digit.
d = e + dp + 1;
// The rounding digit: the digit to the right of the digit that may be rounded up.
i = xc[d];
// Look at the rounding digits and mode to determine whether to round up.
k = baseOut / 2;
r = r || d < 0 || xc[d + 1] != null;
r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
: i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
rm == ( x.s < 0 ? 8 : 7 ) );
// If the index of the rounding digit is not greater than zero, or xc represents
// zero, then the result of the base conversion is zero or, if rounding up, a value
// such as 0.00001.
if ( d < 1 || !xc[0] ) {
// 1^-dp or 0
str = r ? toFixedPoint( alphabet.charAt(1), -dp, alphabet.charAt(0) )
: alphabet.charAt(0);
} else {
// Truncate xc to the required number of decimal places.
xc.length = d;
// Round up?
if (r) {
// Rounding up may mean the previous digit has to be rounded up and so on.
for ( --baseOut; ++xc[--d] > baseOut; ) {
xc[d] = 0;
if ( !d ) {
++e;
xc = [1].concat(xc);
}
}
}
// Determine trailing zeros.
for ( k = xc.length; !xc[--k]; );
// E.g. [4, 11, 15] becomes 4bf.
for ( i = 0, str = ''; i <= k; str += alphabet.charAt( xc[i++] ) );
// Add leading zeros, decimal point and trailing zeros as required.
str = toFixedPoint( str, e, alphabet.charAt(0) );
}
// The caller will add the sign.
return str;
};
})();
// Perform division in the specified base. Called by div and convertBase.
div = (function () {
// Assume non-zero x and k.
function multiply( x, k, base ) {
var m, temp, xlo, xhi,
carry = 0,
i = x.length,
klo = k % SQRT_BASE,
khi = k / SQRT_BASE | 0;
for ( x = x.slice(); i--; ) {
xlo = x[i] % SQRT_BASE;
xhi = x[i] / SQRT_BASE | 0;
m = khi * xlo + xhi * klo;
temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
x[i] = temp % base;
}
if (carry) x = [carry].concat(x);
return x;
}
function compare( a, b, aL, bL ) {
var i, cmp;
if ( aL != bL ) {
cmp = aL > bL ? 1 : -1;
} else {
for ( i = cmp = 0; i < aL; i++ ) {
if ( a[i] != b[i] ) {
cmp = a[i] > b[i] ? 1 : -1;
break;
}
}
}
return cmp;
}
function subtract( a, b, aL, base ) {
var i = 0;
// Subtract b from a.
for ( ; aL--; ) {
a[aL] -= i;
i = a[aL] < b[aL] ? 1 : 0;
a[aL] = i * base + a[aL] - b[aL];
}
// Remove leading zeros.
for ( ; !a[0] && a.length > 1; a.splice(0, 1) );
}
// x: dividend, y: divisor.
return function ( x, y, dp, rm, base ) {
var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
yL, yz,
s = x.s == y.s ? 1 : -1,
xc = x.c,
yc = y.c;
// Either NaN, Infinity or 0?
if ( !xc || !xc[0] || !yc || !yc[0] ) {
return new BigNumber(
// Return NaN if either NaN, or both Infinity or 0.
!x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
// Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
xc && xc[0] == 0 || !yc ? s * 0 : s / 0
);
}
q = new BigNumber(s);
qc = q.c = [];
e = x.e - y.e;
s = dp + e + 1;
if ( !base ) {
base = BASE;
e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
s = s / LOG_BASE | 0;
}
// Result exponent may be one less then the current value of e.
// The coefficients of the BigNumbers from convertBase may have trailing zeros.
for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
if ( yc[i] > ( xc[i] || 0 ) ) e--;
if ( s < 0 ) {
qc.push(1);
more = true;
} else {
xL = xc.length;
yL = yc.length;
i = 0;
s += 2;
// Normalise xc and yc so highest order digit of yc is >= base / 2.
n = mathfloor( base / ( yc[0] + 1 ) );
// Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
// if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
if ( n > 1 ) {
yc = multiply( yc, n, base );
xc = multiply( xc, n, base );
yL = yc.length;
xL = xc.length;
}
xi = yL;
rem = xc.slice( 0, yL );
remL = rem.length;
// Add zeros to make remainder as long as divisor.
for ( ; remL < yL; rem[remL++] = 0 );
yz = yc.slice();
yz = [0].concat(yz);
yc0 = yc[0];
if ( yc[1] >= base / 2 ) yc0++;
// Not necessary, but to prevent trial digit n > base, when using base 3.
// else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
do {
n = 0;
// Compare divisor and remainder.
cmp = compare( yc, rem, yL, remL );
// If divisor < remainder.
if ( cmp < 0 ) {
// Calculate trial digit, n.
rem0 = rem[0];
if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
// n is how many times the divisor goes into the current remainder.
n = mathfloor( rem0 / yc0 );
// Algorithm:
// 1. product = divisor * trial digit (n)
// 2. if product > remainder: product -= divisor, n--
// 3. remainder -= product
// 4. if product was < remainder at 2:
// 5. compare new remainder and divisor
// 6. If remainder > divisor: remainder -= divisor, n++
if ( n > 1 ) {
// n may be > base only when base is 3.
if (n >= base) n = base - 1;
// product = divisor * trial digit.
prod = multiply( yc, n, base );
prodL = prod.length;
remL = rem.length;
// Compare product and remainder.
// If product > remainder.
// Trial digit n too high.
// n is 1 too high about 5% of the time, and is not known to have
// ever been more than 1 too high.
while ( compare( prod, rem, prodL, remL ) == 1 ) {
n--;
// Subtract divisor from product.
subtract( prod, yL < prodL ? yz : yc, prodL, base );
prodL = prod.length;
cmp = 1;
}
} else {
// n is 0 or 1, cmp is -1.
// If n is 0, there is no need to compare yc and rem again below,
// so change cmp to 1 to avoid it.
// If n is 1, leave cmp as -1, so yc and rem are compared again.
if ( n == 0 ) {
// divisor < remainder, so n must be at least 1.
cmp = n = 1;
}
// product = divisor
prod = yc.slice();
prodL = prod.length;
}
if ( prodL < remL ) prod = [0].concat(prod);
// Subtract product from remainder.
subtract( rem, prod, remL, base );
remL = rem.length;
// If product was < remainder.
if ( cmp == -1 ) {
// Compare divisor and new remainder.
// If divisor < new remainder, subtract divisor from remainder.
// Trial digit n too low.
// n is 1 too low about 5% of the time, and very rarely 2 too low.
while ( compare( yc, rem, yL, remL ) < 1 ) {
n++;
// Subtract divisor from remainder.
subtract( rem, yL < remL ? yz : yc, remL, base );
remL = rem.length;
}
}
} else if ( cmp === 0 ) {
n++;
rem = [0];
} // else cmp === 1 and n will be 0
// Add the next digit, n, to the result array.
qc[i++] = n;
// Update the remainder.
if ( rem[0] ) {
rem[remL++] = xc[xi] || 0;
} else {
rem = [ xc[xi] ];
remL = 1;
}
} while ( ( xi++ < xL || rem[0] != null ) && s-- );
more = rem[0] != null;
// Leading zero?
if ( !qc[0] ) qc.splice(0, 1);
}
if ( base == BASE ) {
// To calculate q.e, first get the number of digits of qc[0].
for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
// Caller is convertBase.
} else {
q.e = e;
q.r = +more;
}
return q;
};
})();
/*
* Return a string representing the value of BigNumber n in fixed-point or exponential
* notation rounded to the specified decimal places or significant digits.
*
* n: a BigNumber.
* i: the index of the last digit required (i.e. the digit that may be rounded up).
* rm: the rounding mode.
* id: 1 (toExponential) or 2 (toPrecision).
*/
function format( n, i, rm, id ) {
var c0, e, ne, len, str;
if ( rm == null ) rm = ROUNDING_MODE;
else intCheck( rm, 0, 8 );
if ( !n.c ) return n.toString();
c0 = n.c[0];
ne = n.e;
if ( i == null ) {
str = coeffToString( n.c );
str = id == 1 || id == 2 && ne <= TO_EXP_NEG
? toExponential( str, ne )
: toFixedPoint( str, ne, '0' );
} else {
n = round( new BigNumber(n), i, rm );
// n.e may have changed if the value was rounded up.
e = n.e;
str = coeffToString( n.c );
len = str.length;
// toPrecision returns exponential notation if the number of significant digits
// specified is less than the number of digits necessary to represent the integer
// part of the value in fixed-point notation.
// Exponential notation.
if ( id == 1 || id == 2 && ( i <= e || e <= TO_EXP_NEG ) ) {
// Append zeros?
for ( ; len < i; str += '0', len++ );
str = toExponential( str, e );
// Fixed-point notation.
} else {
i -= ne;
str = toFixedPoint( str, e, '0' );
// Append zeros?
if ( e + 1 > len ) {
if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
} else {
i += e - len;
if ( i > 0 ) {
if ( e + 1 == len ) str += '.';
for ( ; i--; str += '0' );
}
}
}
}
return n.s < 0 && c0 ? '-' + str : str;
}
// Handle BigNumber.max and BigNumber.min.
function maxOrMin( args, method ) {
var m, n,
i = 0;
if ( isArray( args[0] ) ) args = args[0];
m = new BigNumber( args[0] );
for ( ; ++i < args.length; ) {
n = new BigNumber( args[i] );
// If any number is NaN, return NaN.
if ( !n.s ) {
m = n;
break;
} else if ( method.call( m, n ) ) {
m = n;
}
}
return m;
}
/*
* Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
* Called by minus, plus and times.
*/
function normalise( n, c, e ) {
var i = 1,
j = c.length;
// Remove trailing zeros.
for ( ; !c[--j]; c.pop() );
// Calculate the base 10 exponent. First get the number of digits of c[0].
for ( j = c[0]; j >= 10; j /= 10, i++ );
// Overflow?
if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
// Infinity.
n.c = n.e = null;
// Underflow?
} else if ( e < MIN_EXP ) {
// Zero.
n.c = [ n.e = 0 ];
} else {
n.e = e;
n.c = c;
}
return n;
}
// Handle values that fail the validity test in BigNumber.
parseNumeric = (function () {
var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,
dotAfter = /^([^.]+)\.$/,
dotBefore = /^\.([^.]+)$/,
isInfinityOrNaN = /^-?(Infinity|NaN)$/,
whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
return function ( x, str, isNum, b ) {
var base,
s = isNum ? str : str.replace( whitespaceOrPlus, '' );
// No exception on ±Infinity or NaN.
if ( isInfinityOrNaN.test(s) ) {
x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
x.c = x.e = null;
} else {
if ( !isNum ) {
// basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
s = s.replace( basePrefix, function ( m, p1, p2 ) {
base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
return !b || b == base ? p1 : m;
});
if (b) {
base = b;
// E.g. '1.' to '1', '.1' to '0.1'
s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
}
if ( str != s ) return new BigNumber( s, base );
}
// '[BigNumber Error] Not a number: {n}'
// '[BigNumber Error] Not a base {b} number: {n}'
throw Error
( bignumberError + 'Not a' + ( b ? ' base ' + b : '' ) + ' number: ' + str );
}
}
})();
/*
* Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
* If r is truthy, it is known that there are more digits after the rounding digit.
*/
function round( x, sd, rm, r ) {
var d, i, j, k, n, ni, rd,
xc = x.c,
pows10 = POWS_TEN;
// if x is not Infinity or NaN...
if (xc) {
// rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
// n is a base 1e14 number, the value of the element of array x.c containing rd.
// ni is the index of n within x.c.
// d is the number of digits of n.
// i is the index of rd within n including leading zeros.
// j is the actual index of rd within n (if < 0, rd is a leading zero).
out: {
// Get the number of digits of the first element of xc.
for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
i = sd - d;
// If the rounding digit is in the first element of xc...
if ( i < 0 ) {
i += LOG_BASE;
j = sd;
n = xc[ ni = 0 ];
// Get the rounding digit at index j of n.
rd = n / pows10[ d - j - 1 ] % 10 | 0;
} else {
ni = mathceil( ( i + 1 ) / LOG_BASE );
if ( ni >= xc.length ) {
if (r) {
// Needed by sqrt.
for ( ; xc.length <= ni; xc.push(0) );
n = rd = 0;
d = 1;
i %= LOG_BASE;
j = i - LOG_BASE + 1;
} else {
break out;
}
} else {
n = k = xc[ni];
// Get the number of digits of n.
for ( d = 1; k >= 10; k /= 10, d++ );
// Get the index of rd within n.
i %= LOG_BASE;
// Get the index of rd within n, adjusted for leading zeros.
// The number of leading zeros of n is given by LOG_BASE - d.
j = i - LOG_BASE + d;
// Get the rounding digit at index j of n.
rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
}
}
r = r || sd < 0 ||
// Are there any non-zero digits after the rounding digit?
// The expression n % pows10[ d - j - 1 ] returns all digits of n to the right
// of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
r = rm < 4
? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
: rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
// Check whether the digit to the left of the rounding digit is odd.
( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
rm == ( x.s < 0 ? 8 : 7 ) );
if ( sd < 1 || !xc[0] ) {
xc.length = 0;
if (r) {
// Convert sd to decimal places.
sd -= x.e + 1;
// 1, 0.1, 0.01, 0.001, 0.0001 etc.
xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ];
x.e = -sd || 0;
} else {
// Zero.
xc[0] = x.e = 0;
}
return x;
}
// Remove excess digits.
if ( i == 0 ) {
xc.length = ni;
k = 1;
ni--;
} else {
xc.length = ni + 1;
k = pows10[ LOG_BASE - i ];
// E.g. 56700 becomes 56000 if 7 is the rounding digit.
// j > 0 means i > number of leading zeros of n.
xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
}
// Round up?
if (r) {
for ( ; ; ) {
// If the digit to be rounded up is in the first element of xc...
if ( ni == 0 ) {
// i will be the length of xc[0] before k is added.
for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
j = xc[0] += k;
for ( k = 1; j >= 10; j /= 10, k++ );
// if i != k the length has increased.
if ( i != k ) {
x.e++;
if ( xc[0] == BASE ) xc[0] = 1;
}
break;
} else {
xc[ni] += k;
if ( xc[ni] != BASE ) break;
xc[ni--] = 0;
k = 1;
}
}
}
// Remove trailing zeros.
for ( i = xc.length; xc[--i] === 0; xc.pop() );
}
// Overflow? Infinity.
if ( x.e > MAX_EXP ) {
x.c = x.e = null;
// Underflow? Zero.
} else if ( x.e < MIN_EXP ) {
x.c = [ x.e = 0 ];
}
}
return x;
}
// PROTOTYPE/INSTANCE METHODS
/*
* Return a new BigNumber whose value is the absolute value of this BigNumber.
*/
P.absoluteValue = P.abs = function () {
var x = new BigNumber(this);
if ( x.s < 0 ) x.s = 1;
return x;
};
/*
* Return
* 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
* -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
* 0 if they have the same value,
* or null if the value of either is NaN.
*/
P.comparedTo = function ( y, b ) {
return compare( this, new BigNumber( y, b ) );
};
/*
* If dp is undefined or null or true or false, return the number of decimal places of the
* value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.
*
* Otherwise, if dp is a number, return a new BigNumber whose value is the value of this
* BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or
* ROUNDING_MODE if rm is omitted.
*
* [dp] {number} Decimal places: integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
*/
P.decimalPlaces = P.dp = function ( dp, rm ) {
var c, n, v,
x = this;
if ( dp != null ) {
intCheck( dp, 0, MAX );
if ( rm == null ) rm = ROUNDING_MODE;
else intCheck( rm, 0, 8 );
return round( new BigNumber(x), dp + x.e + 1, rm );
}
if ( !( c = x.c ) ) return null;
n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
// Subtract the number of trailing zeros of the last number.
if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
if ( n < 0 ) n = 0;
return n;
};
/*
* n / 0 = I
* n / N = N
* n / I = 0
* 0 / n = 0
* 0 / 0 = N
* 0 / N = N
* 0 / I = 0
* N / n = N
* N / 0 = N
* N / N = N
* N / I = N
* I / n = I
* I / 0 = I
* I / N = N
* I / I = N
*
* Return a new BigNumber whose value is the value of this BigNumber divided by the value of
* BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
*/
P.dividedBy = P.div = function ( y, b ) {
return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
};
/*
* Return a new BigNumber whose value is the integer part of dividing the value of this
* BigNumber by the value of BigNumber(y, b).
*/
P.dividedToIntegerBy = P.idiv = function ( y, b ) {
return div( this, new BigNumber( y, b ), 0, 1 );
};
/*
* Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
* otherwise return false.
*/
P.isEqualTo = P.eq = function ( y, b ) {
return compare( this, new BigNumber( y, b ) ) === 0;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to an integer
* using rounding mode rm, or ROUNDING_MODE if rm is omitted.
*
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'
*/
P.integerValue = function (rm) {
var n = new BigNumber(this);
if ( rm == null ) rm = ROUNDING_MODE;
else intCheck( rm, 0, 8 );
return round( n, n.e + 1, rm );
};
/*
* Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
* otherwise return false.
*/
P.isGreaterThan = P.gt = function ( y, b ) {
return compare( this, new BigNumber( y, b ) ) > 0;
};
/*
* Return true if the value of this BigNumber is greater than or equal to the value of
* BigNumber(y, b), otherwise return false.
*/
P.isGreaterThanOrEqualTo = P.gte = function ( y, b ) {
return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
};
/*
* Return true if the value of this BigNumber is a finite number, otherwise return false.
*/
P.isFinite = function () {
return !!this.c;
};
/*
* Return true if the value of this BigNumber is an integer, otherwise return false.
*/
P.isInteger = function () {
return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
};
/*
* Return true if the value of this BigNumber is NaN, otherwise return false.
*/
P.isNaN = function () {
return !this.s;
};
/*
* Return true if the value of this BigNumber is negative, otherwise return false.
*/
P.isNegative = function () {
return this.s < 0;
};
/*
* Return true if the value of this BigNumber is positive, otherwise return false.
*/
P.isPositive = function () {
return this.s > 0;
};
/*
* Return true if the value of this BigNumber is 0 or -0, otherwise return false.
*/
P.isZero = function () {
return !!this.c && this.c[0] == 0;
};
/*
* Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
* otherwise return false.
*/
P.isLessThan = P.lt = function ( y, b ) {
return compare( this, new BigNumber( y, b ) ) < 0;
};
/*
* Return true if the value of this BigNumber is less than or equal to the value of
* BigNumber(y, b), otherwise return false.
*/
P.isLessThanOrEqualTo = P.lte = function ( y, b ) {
return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
};
/*
* n - 0 = n
* n - N = N
* n - I = -I
* 0 - n = -n
* 0 - 0 = 0
* 0 - N = N
* 0 - I = -I
* N - n = N
* N - 0 = N
* N - N = N
* N - I = N
* I - n = I
* I - 0 = I
* I - N = N
* I - I = N
*
* Return a new BigNumber whose value is the value of this BigNumber minus the value of
* BigNumber(y, b).
*/
P.minus = function ( y, b ) {
var i, j, t, xLTy,
x = this,
a = x.s;
y = new BigNumber( y, b );
b = y.s;
// Either NaN?
if ( !a || !b ) return new BigNumber(NaN);
// Signs differ?
if ( a != b ) {
y.s = -b;
return x.plus(y);
}
var xe = x.e / LOG_BASE,
ye = y.e / LOG_BASE,
xc = x.c,
yc = y.c;
if ( !xe || !ye ) {
// Either Infinity?
if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
// Either zero?
if ( !xc[0] || !yc[0] ) {
// Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
// IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
ROUNDING_MODE == 3 ? -0 : 0 );
}
}
xe = bitFloor(xe);
ye = bitFloor(ye);
xc = xc.slice();
// Determine which is the bigger number.
if ( a = xe - ye ) {
if ( xLTy = a < 0 ) {
a = -a;
t = xc;
} else {
ye = xe;
t = yc;
}
t.reverse();
// Prepend zeros to equalise exponents.
for ( b = a; b--; t.push(0) );
t.reverse();
} else {
// Exponents equal. Check digit by digit.
j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
for ( a = b = 0; b < j; b++ ) {
if ( xc[b] != yc[b] ) {
xLTy = xc[b] < yc[b];
break;
}
}
}
// x < y? Point xc to the array of the bigger number.
if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
b = ( j = yc.length ) - ( i = xc.length );
// Append zeros to xc if shorter.
// No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
b = BASE - 1;
// Subtract yc from xc.
for ( ; j > a; ) {
if ( xc[--j] < yc[j] ) {
for ( i = j; i && !xc[--i]; xc[i] = b );
--xc[i];
xc[j] += BASE;
}
xc[j] -= yc[j];
}
// Remove leading zeros and adjust exponent accordingly.
for ( ; xc[0] == 0; xc.splice(0, 1), --ye );
// Zero?
if ( !xc[0] ) {
// Following IEEE 754 (2008) 6.3,
// n - n = +0 but n - n = -0 when rounding towards -Infinity.
y.s = ROUNDING_MODE == 3 ? -1 : 1;
y.c = [ y.e = 0 ];
return y;
}
// No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
// for finite x and y.
return normalise( y, xc, ye );
};
/*
* n % 0 = N
* n % N = N
* n % I = n
* 0 % n = 0
* -0 % n = -0
* 0 % 0 = N
* 0 % N = N
* 0 % I = 0
* N % n = N
* N % 0 = N
* N % N = N
* N % I = N
* I % n = N
* I % 0 = N
* I % N = N
* I % I = N
*
* Return a new BigNumber whose value is the value of this BigNumber modulo the value of
* BigNumber(y, b). The result depends on the value of MODULO_MODE.
*/
P.modulo = P.mod = function ( y, b ) {
var q, s,
x = this;
y = new BigNumber( y, b );
// Return NaN if x is Infinity or NaN, or y is NaN or zero.
if ( !x.c || !y.s || y.c && !y.c[0] ) {
return new BigNumber(NaN);
// Return x if y is Infinity or x is zero.
} else if ( !y.c || x.c && !x.c[0] ) {
return new BigNumber(x);
}
if ( MODULO_MODE == 9 ) {
// Euclidian division: q = sign(y) * floor(x / abs(y))
// r = x - qy where 0 <= r < abs(y)
s = y.s;
y.s = 1;
q = div( x, y, 0, 3 );
y.s = s;
q.s *= s;
} else {
q = div( x, y, 0, MODULO_MODE );
}
return x.minus( q.times(y) );
};
/*
* n * 0 = 0
* n * N = N
* n * I = I
* 0 * n = 0
* 0 * 0 = 0
* 0 * N = N
* 0 * I = N
* N * n = N
* N * 0 = N
* N * N = N
* N * I = N
* I * n = I
* I * 0 = N
* I * N = N
* I * I = I
*
* Return a new BigNumber whose value is the value of this BigNumber multiplied by the value
* of BigNumber(y, b).
*/
P.multipliedBy = P.times = function ( y, b ) {
var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
base, sqrtBase,
x = this,
xc = x.c,
yc = ( y = new BigNumber( y, b ) ).c;
// Either NaN, ±Infinity or ±0?
if ( !xc || !yc || !xc[0] || !yc[0] ) {
// Return NaN if either is NaN, or one is 0 and the other is Infinity.
if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
y.c = y.e = y.s = null;
} else {
y.s *= x.s;
// Return ±Infinity if either is ±Infinity.
if ( !xc || !yc ) {
y.c = y.e = null;
// Return ±0 if either is ±0.
} else {
y.c = [0];
y.e = 0;
}
}
return y;
}
e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
y.s *= x.s;
xcL = xc.length;
ycL = yc.length;
// Ensure xc points to longer array and xcL to its length.
if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
// Initialise the result array with zeros.
for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
base = BASE;
sqrtBase = SQRT_BASE;
for ( i = ycL; --i >= 0; ) {
c = 0;
ylo = yc[i] % sqrtBase;
yhi = yc[i] / sqrtBase | 0;
for ( k = xcL, j = i + k; j > i; ) {
xlo = xc[--k] % sqrtBase;
xhi = xc[k] / sqrtBase | 0;
m = yhi * xlo + xhi * ylo;
xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
zc[j--] = xlo % base;
}
zc[j] = c;
}
if (c) {
++e;
} else {
zc.splice(0, 1);
}
return normalise( y, zc, e );
};
/*
* Return a new BigNumber whose value is the value of this BigNumber negated,
* i.e. multiplied by -1.
*/
P.negated = function () {
var x = new BigNumber(this);
x.s = -x.s || null;
return x;
};
/*
* n + 0 = n
* n + N = N
* n + I = I
* 0 + n = n
* 0 + 0 = 0
* 0 + N = N
* 0 + I = I
* N + n = N
* N + 0 = N
* N + N = N
* N + I = N
* I + n = I
* I + 0 = I
* I + N = N
* I + I = I
*
* Return a new BigNumber whose value is the value of this BigNumber plus the value of
* BigNumber(y, b).
*/
P.plus = function ( y, b ) {
var t,
x = this,
a = x.s;
y = new BigNumber( y, b );
b = y.s;
// Either NaN?
if ( !a || !b ) return new BigNumber(NaN);
// Signs differ?
if ( a != b ) {
y.s = -b;
return x.minus(y);
}
var xe = x.e / LOG_BASE,
ye = y.e / LOG_BASE,
xc = x.c,
yc = y.c;
if ( !xe || !ye ) {
// Return ±Infinity if either ±Infinity.
if ( !xc || !yc ) return new BigNumber( a / 0 );
// Either zero?
// Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
}
xe = bitFloor(xe);
ye = bitFloor(ye);
xc = xc.slice();
// Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
if ( a = xe - ye ) {
if ( a > 0 ) {
ye = xe;
t = yc;
} else {
a = -a;
t = xc;
}
t.reverse();
for ( ; a--; t.push(0) );
t.reverse();
}
a = xc.length;
b = yc.length;
// Point xc to the longer array, and b to the shorter length.
if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
// Only start adding at yc.length - 1 as the further digits of xc can be ignored.
for ( a = 0; b; ) {
a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
}
if (a) {
xc = [a].concat(xc);
++ye;
}
// No need to check for zero, as +x + +y != 0 && -x + -y != 0
// ye = MAX_EXP + 1 possible
return normalise( y, xc, ye );
};
/*
* If sd is undefined or null or true or false, return the number of significant digits of
* the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.
* If sd is true include integer-part trailing zeros in the count.
*
* Otherwise, if sd is a number, return a new BigNumber whose value is the value of this
* BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or
* ROUNDING_MODE if rm is omitted.
*
* sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.
* boolean: whether to count integer-part trailing zeros: true or false.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'
*/
P.precision = P.sd = function ( sd, rm ) {
var c, n, v,
x = this;
if ( sd != null && sd !== !!sd ) {
intCheck( sd, 1, MAX );
if ( rm == null ) rm = ROUNDING_MODE;
else intCheck( rm, 0, 8 );
return round( new BigNumber(x), sd, rm );
}
if ( !( c = x.c ) ) return null;
v = c.length - 1;
n = v * LOG_BASE + 1;
if ( v = c[v] ) {
// Subtract the number of trailing zeros of the last element.
for ( ; v % 10 == 0; v /= 10, n-- );
// Add the number of digits of the first element.
for ( v = c[0]; v >= 10; v /= 10, n++ );
}
if ( sd && x.e + 1 > n ) n = x.e + 1;
return n;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber shifted by k places
* (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
*
* k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
*
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'
*/
P.shiftedBy = function (k) {
intCheck( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER );
return this.times( '1e' + k );
};
/*
* sqrt(-n) = N
* sqrt( N) = N
* sqrt(-I) = N
* sqrt( I) = I
* sqrt( 0) = 0
* sqrt(-0) = -0
*
* Return a new BigNumber whose value is the square root of the value of this BigNumber,
* rounded according to DECIMAL_PLACES and ROUNDING_MODE.
*/
P.squareRoot = P.sqrt = function () {
var m, n, r, rep, t,
x = this,
c = x.c,
s = x.s,
e = x.e,
dp = DECIMAL_PLACES + 4,
half = new BigNumber('0.5');
// Negative/NaN/Infinity/zero?
if ( s !== 1 || !c || !c[0] ) {
return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
}
// Initial estimate.
s = Math.sqrt( +x );
// Math.sqrt underflow/overflow?
// Pass x to Math.sqrt as integer, then adjust the exponent of the result.
if ( s == 0 || s == 1 / 0 ) {
n = coeffToString(c);
if ( ( n.length + e ) % 2 == 0 ) n += '0';
s = Math.sqrt(n);
e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
if ( s == 1 / 0 ) {
n = '1e' + e;
} else {
n = s.toExponential();
n = n.slice( 0, n.indexOf('e') + 1 ) + e;
}
r = new BigNumber(n);
} else {
r = new BigNumber( s + '' );
}
// Check for zero.
// r could be zero if MIN_EXP is changed after the this value was created.
// This would cause a division by zero (x/t) and hence Infinity below, which would cause
// coeffToString to throw.
if ( r.c[0] ) {
e = r.e;
s = e + dp;
if ( s < 3 ) s = 0;
// Newton-Raphson iteration.
for ( ; ; ) {
t = r;
r = half.times( t.plus( div( x, t, dp, 1 ) ) );
if ( coeffToString( t.c ).slice( 0, s ) === ( n =
coeffToString( r.c ) ).slice( 0, s ) ) {
// The exponent of r may here be one less than the final result exponent,
// e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
// are indexed correctly.
if ( r.e < e ) --s;
n = n.slice( s - 3, s + 1 );
// The 4th rounding digit may be in error by -1 so if the 4 rounding digits
// are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
// iteration.
if ( n == '9999' || !rep && n == '4999' ) {
// On the first iteration only, check to see if rounding up gives the
// exact result as the nines may infinitely repeat.
if ( !rep ) {
round( t, t.e + DECIMAL_PLACES + 2, 0 );
if ( t.times(t).eq(x) ) {
r = t;
break;
}
}
dp += 4;
s += 4;
rep = 1;
} else {
// If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
// result. If not, then there are further digits and m will be truthy.
if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
// Truncate to the first rounding digit.
round( r, r.e + DECIMAL_PLACES + 2, 1 );
m = !r.times(r).eq(x);
}
break;
}
}
}
}
return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
};
/*
* Return a string representing the value of this BigNumber in exponential notation and
* rounded using ROUNDING_MODE to dp fixed decimal places.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
*/
P.toExponential = function ( dp, rm ) {
if ( dp != null ) {
intCheck( dp, 0, MAX );
dp++;
}
return format( this, dp, rm, 1 );
};
/*
* Return a string representing the value of this BigNumber in fixed-point notation rounding
* to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
*
* Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
* but e.g. (-0.00001).toFixed(0) is '-0'.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
*/
P.toFixed = function ( dp, rm ) {
if ( dp != null ) {
intCheck( dp, 0, MAX );
dp = dp + this.e + 1;
}
return format( this, dp, rm );
};
/*
* Return a string representing the value of this BigNumber in fixed-point notation rounded
* using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
* of the FORMAT object (see BigNumber.set).
*
* FORMAT = {
* decimalSeparator : '.',
* groupSeparator : ',',
* groupSize : 3,
* secondaryGroupSize : 0,
* fractionGroupSeparator : '\xA0', // non-breaking space
* fractionGroupSize : 0
* };
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
*/
P.toFormat = function ( dp, rm ) {
var str = this.toFixed( dp, rm );
if ( this.c ) {
var i,
arr = str.split('.'),
g1 = +FORMAT.groupSize,
g2 = +FORMAT.secondaryGroupSize,
groupSeparator = FORMAT.groupSeparator,
intPart = arr[0],
fractionPart = arr[1],
isNeg = this.s < 0,
intDigits = isNeg ? intPart.slice(1) : intPart,
len = intDigits.length;
if (g2) i = g1, g1 = g2, g2 = i, len -= i;
if ( g1 > 0 && len > 0 ) {
i = len % g1 || g1;
intPart = intDigits.substr( 0, i );
for ( ; i < len; i += g1 ) {
intPart += groupSeparator + intDigits.substr( i, g1 );
}
if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
if (isNeg) intPart = '-' + intPart;
}
str = fractionPart
? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
'$&' + FORMAT.fractionGroupSeparator )
: fractionPart )
: intPart;
}
return str;
};
/*
* Return a string array representing the value of this BigNumber as a simple fraction with
* an integer numerator and an integer denominator. The denominator will be a positive
* non-zero value less than or equal to the specified maximum denominator. If a maximum
* denominator is not specified, the denominator will be the lowest value necessary to
* represent the number exactly.
*
* [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
*
* '[BigNumber Error] Argument {not an integer|out of range} : {md}'
*/
P.toFraction = function (md) {
var arr, d, d0, d1, d2, e, exp, n, n0, n1, q, s,
x = this,
xc = x.c;
if ( md != null ) {
n = new BigNumber(md);
if ( !n.isInteger() || n.lt(ONE) ) {
throw Error
( bignumberError + 'Argument ' +
( n.isInteger() ? 'out of range: ' : 'not an integer: ' ) + md );
}
}
if ( !xc ) return x.toString();
d = new BigNumber(ONE);
n1 = d0 = new BigNumber(ONE);
d1 = n0 = new BigNumber(ONE);
s = coeffToString(xc);
// Determine initial denominator.
// d is a power of 10 and the minimum max denominator that specifies the value exactly.
e = d.e = s.length - x.e - 1;
d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
md = !md || n.comparedTo(d) > 0 ? ( e > 0 ? d : n1 ) : n;
exp = MAX_EXP;
MAX_EXP = 1 / 0;
n = new BigNumber(s);
// n0 = d1 = 0
n0.c[0] = 0;
for ( ; ; ) {
q = div( n, d, 0, 1 );
d2 = d0.plus( q.times(d1) );
if ( d2.comparedTo(md) == 1 ) break;
d0 = d1;
d1 = d2;
n1 = n0.plus( q.times( d2 = n1 ) );
n0 = d2;
d = n.minus( q.times( d2 = d ) );
n = d2;
}
d2 = div( md.minus(d0), d1, 0, 1 );
n0 = n0.plus( d2.times(n1) );
d0 = d0.plus( d2.times(d1) );
n0.s = n1.s = x.s;
e *= 2;
// Determine which fraction is closer to x, n0/d0 or n1/d1
arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().comparedTo(
div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
? [ n1.toString(), d1.toString() ]
: [ n0.toString(), d0.toString() ];
MAX_EXP = exp;
return arr;
};
/*
* Return the value of this BigNumber converted to a number primitive.
*/
P.toNumber = function () {
return +this;
};
/*
* Return a BigNumber whose value is the value of this BigNumber exponentiated by n.
*
* If m is present, return the result modulo m.
* If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
* If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.
*
* The modular power operation works efficiently when x, n, and m are positive integers,
* otherwise it is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.
*
* n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
* [m] {number|string|BigNumber} The modulus.
*
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {n}'
*
* Performs 54 loop iterations for n of 9007199254740991.
*/
P.exponentiatedBy = P.pow = function ( n, m ) {
var i, k, y, z,
x = this;
intCheck( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER );
if ( m != null ) m = new BigNumber(m);
if (m) {
if ( n > 1 && x.gt(ONE) && x.isInteger() && m.gt(ONE) && m.isInteger() ) {
x = x.mod(m);
} else {
z = m;
// Nullify m so only a single mod operation is performed at the end.
m = null;
}
} else if (POW_PRECISION) {
// Truncating each coefficient array to a length of k after each multiplication
// equates to truncating significant digits to POW_PRECISION + [28, 41],
// i.e. there will be a minimum of 28 guard digits retained.
//k = mathceil( POW_PRECISION / LOG_BASE + 1.5 ); // gives [9, 21] guard digits.
k = mathceil( POW_PRECISION / LOG_BASE + 2 );
}
y = new BigNumber(ONE);
for ( i = mathfloor( n < 0 ? -n : n ); ; ) {
if ( i % 2 ) {
y = y.times(x);
if ( !y.c ) break;
if (k) {
if ( y.c.length > k ) y.c.length = k;
} else if (m) {
y = y.mod(m);
}
}
i = mathfloor( i / 2 );
if ( !i ) break;
x = x.times(x);
if (k) {
if ( x.c && x.c.length > k ) x.c.length = k;
} else if (m) {
x = x.mod(m);
}
}
if (m) return y;
if ( n < 0 ) y = ONE.div(y);
return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
};
/*
* Return a string representing the value of this BigNumber rounded to sd significant digits
* using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
* necessary to represent the integer part of the value in fixed-point notation, then use
* exponential notation.
*
* [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'
*/
P.toPrecision = function ( sd, rm ) {
if ( sd != null ) intCheck( sd, 1, MAX );
return format( this, sd, rm, 2 );
};
/*
* Return a string representing the value of this BigNumber in base b, or base 10 if b is
* omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
* ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
* that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
* TO_EXP_NEG, return exponential notation.
*
* [b] {number} Integer, 2 to ALPHABET.length inclusive.
*
* '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'
*/
P.toString = function (b) {
var str,
n = this,
s = n.s,
e = n.e;
// Infinity or NaN?
if ( e === null ) {
if (s) {
str = 'Infinity';
if ( s < 0 ) str = '-' + str;
} else {
str = 'NaN';
}
} else {
str = coeffToString( n.c );
if ( b == null ) {
str = e <= TO_EXP_NEG || e >= TO_EXP_POS
? toExponential( str, e )
: toFixedPoint( str, e, '0' );
} else {
intCheck( b, 2, ALPHABET.length, 'Base' );
str = convertBase( toFixedPoint( str, e, '0' ), 10, b, s, true );
}
if ( s < 0 && n.c[0] ) str = '-' + str;
}
return str;
};
/*
* Return as toString, but do not accept a base argument, and include the minus sign for
* negative zero.
*/
P.valueOf = P.toJSON = function () {
var str,
n = this,
e = n.e;
if ( e === null ) return n.toString();
str = coeffToString( n.c );
str = e <= TO_EXP_NEG || e >= TO_EXP_POS
? toExponential( str, e )
: toFixedPoint( str, e, '0' );
return n.s < 0 ? '-' + str : str;
};
P._isBigNumber = true;
if ( configObject != null ) BigNumber.set(configObject);
return BigNumber;
}
// PRIVATE HELPER FUNCTIONS
function bitFloor(n) {
var i = n | 0;
return n > 0 || n === i ? i : i - 1;
}
// Return a coefficient array as a string of base 10 digits.
function coeffToString(a) {
var s, z,
i = 1,
j = a.length,
r = a[0] + '';
for ( ; i < j; ) {
s = a[i++] + '';
z = LOG_BASE - s.length;
for ( ; z--; s = '0' + s );
r += s;
}
// Determine trailing zeros.
for ( j = r.length; r.charCodeAt(--j) === 48; );
return r.slice( 0, j + 1 || 1 );
}
// Compare the value of BigNumbers x and y.
function compare( x, y ) {
var a, b,
xc = x.c,
yc = y.c,
i = x.s,
j = y.s,
k = x.e,
l = y.e;
// Either NaN?
if ( !i || !j ) return null;
a = xc && !xc[0];
b = yc && !yc[0];
// Either zero?
if ( a || b ) return a ? b ? 0 : -j : i;
// Signs differ?
if ( i != j ) return i;
a = i < 0;
b = k == l;
// Either Infinity?
if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
// Compare exponents.
if ( !b ) return k > l ^ a ? 1 : -1;
j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
// Compare digit by digit.
for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
// Compare lengths.
return k == l ? 0 : k > l ^ a ? 1 : -1;
}
/*
* Check that n is a primitive number, an integer, and in range, otherwise throw.
*/
function intCheck( n, min, max, name ) {
if ( n < min || n > max || n !== ( n < 0 ? mathceil(n) : mathfloor(n) ) ) {
throw Error
( bignumberError + ( name || 'Argument' ) + ( typeof n == 'number'
? n < min || n > max ? ' out of range: ' : ' not an integer: '
: ' not a primitive number: ' ) + n );
}
}
function isArray(obj) {
return Object.prototype.toString.call(obj) == '[object Array]';
}
function toExponential( str, e ) {
return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
( e < 0 ? 'e' : 'e+' ) + e;
}
function toFixedPoint( str, e, z ) {
var len, zs;
// Negative exponent?
if ( e < 0 ) {
// Prepend zeros.
for ( zs = z + '.'; ++e; zs += z );
str = zs + str;
// Positive exponent
} else {
len = str.length;
// Append zeros.
if ( ++e > len ) {
for ( zs = z, e -= len; --e; zs += z );
str += zs;
} else if ( e < len ) {
str = str.slice( 0, e ) + '.' + str.slice(e);
}
}
return str;
}
// EXPORT
BigNumber = clone();
BigNumber['default'] = BigNumber.BigNumber = BigNumber;
// AMD.
if ( typeof define == 'function' && define.amd ) {
define( function () { return BigNumber; } );
// Node.js and other environments that support module.exports.
} else if ( typeof module != 'undefined' && module.exports ) {
module.exports = BigNumber;
// Browser.
} else {
if ( !globalObject ) {
globalObject = typeof self != 'undefined' ? self : Function('return this')();
}
globalObject.BigNumber = BigNumber;
}
})(this);
|
var config = require('../../config')
if(!config.tasks.iconFont) return
var gulp = require('gulp')
var iconfont = require('gulp-iconfont')
var generateIconSass = require('./generateIconSass')
var handleErrors = require('../../lib/handleErrors')
var package = require('../../../package.json')
var path = require('path')
var fontPath = path.join(config.root.dest, config.tasks.fonts.dest)
var cssPath = path.join(config.root.dest, config.tasks.css.dest)
var settings = {
name: package.name + ' icons',
src: path.join(config.root.src, config.tasks.iconFont.src, '/*.svg'),
dest: path.join(config.root.dest, config.tasks.iconFont.dest),
sassDest: path.join(config.root.src, config.tasks.css.src, config.tasks.iconFont.sassDest),
template: path.normalize('./gulpfile.js/tasks/iconFont/template.sass'),
sassOutputName: '_icons.sass',
fontPath: path.relative(cssPath, fontPath),
className: 'icon',
options: {
svg: true,
timestamp: 0, // see https://github.com/fontello/svg2ttf/issues/33
fontName: 'icons',
appendUnicode: true,
normalize: false
}
}
gulp.task('iconFont', function() {
return gulp.src(settings.src)
.pipe(iconfont(settings.options))
.on('glyphs', generateIconSass(settings))
.on('error', handleErrors)
.pipe(gulp.dest(settings.dest))
})
module.exports = settings
|
/*jshint newcap:false*/
import EmberView from 'ember-views/views/view';
import EmberObject from 'ember-runtime/system/object';
import { A } from 'ember-runtime/system/native_array';
import Ember from 'ember-metal/core';
import { get } from 'ember-metal/property_get';
import { set } from 'ember-metal/property_set';
import run from 'ember-metal/run_loop';
import compile from 'ember-template-compiler/system/compile';
import helpers from 'ember-htmlbars/helpers';
import registerBoundHelper from 'ember-htmlbars/compat/register-bound-helper';
import makeBoundHelper from 'ember-htmlbars/compat/make-bound-helper';
import { Registry } from 'ember-runtime/system/container';
import { runAppend, runDestroy } from 'ember-runtime/tests/utils';
function expectDeprecationInHTMLBars() {
// leave this as an empty function until we are ready to use it
// to enforce deprecation notice for old Handlebars versions
}
var view, lookup, registry, container;
var originalLookup = Ember.lookup;
QUnit.module('ember-htmlbars: {{#unbound}} helper', {
setup() {
Ember.lookup = lookup = { Ember: Ember };
view = EmberView.create({
template: compile('{{unbound foo}} {{unbound bar}}'),
context: EmberObject.create({
foo: 'BORK',
barBinding: 'foo'
})
});
runAppend(view);
},
teardown() {
runDestroy(view);
Ember.lookup = originalLookup;
}
});
QUnit.test('it should render the current value of a property on the context', function() {
equal(view.$().text(), 'BORK BORK', 'should render the current value of a property');
});
QUnit.test('it should not re-render if the property changes', function() {
run(function() {
view.set('context.foo', 'OOF');
});
equal(view.$().text(), 'BORK BORK', 'should not re-render if the property changes');
});
QUnit.test('it should re-render if the parent view rerenders', function() {
run(function() {
view.set('context.foo', 'OOF');
view.rerender();
});
equal(view.$().text(), 'OOF OOF', 'should re-render if the parent view rerenders');
});
QUnit.test('it should throw the helper missing error if multiple properties are provided', function() {
expectAssertion(function() {
runAppend(EmberView.create({
template: compile('{{unbound foo bar}}'),
context: EmberObject.create({
foo: 'BORK',
bar: 'foo'
})
}));
}, /A helper named 'foo' could not be found/);
});
QUnit.test('should property escape unsafe hrefs', function() {
/* jshint scripturl:true */
expect(3);
runDestroy(view);
view = EmberView.create({
template: compile('<ul>{{#each view.people as |person|}}<a href="{{unbound person.url}}">{{person.name}}</a>{{/each}}</ul>'),
people: A([{
name: 'Bob',
url: 'javascript:bob-is-cool'
}, {
name: 'James',
url: 'vbscript:james-is-cool'
}, {
name: 'Richard',
url: 'javascript:richard-is-cool'
}])
});
runAppend(view);
var links = view.$('a');
for (var i = 0, l = links.length; i < l; i++) {
var link = links[i];
equal(link.protocol, 'unsafe:', 'properly escaped');
}
});
QUnit.module('ember-htmlbars: {{#unbound}} helper with container present', {
setup() {
Ember.lookup = lookup = { Ember: Ember };
view = EmberView.create({
container: new Registry().container,
template: compile('{{unbound foo}}'),
context: EmberObject.create({
foo: 'bleep'
})
});
},
teardown() {
runDestroy(view);
Ember.lookup = originalLookup;
}
});
QUnit.test('it should render the current value of a property path on the context', function() {
runAppend(view);
equal(view.$().text(), 'bleep', 'should render the current value of a property path');
});
QUnit.module('ember-htmlbars: {{#unbound}} subexpression', {
setup() {
Ember.lookup = lookup = { Ember: Ember };
expectDeprecation('`Ember.Handlebars.registerBoundHelper` is deprecated. Please refactor to use `Ember.Helpers.helper`.');
registerBoundHelper('capitalize', function(value) {
return value.toUpperCase();
});
view = EmberView.create({
template: compile('{{capitalize (unbound foo)}}'),
context: EmberObject.create({
foo: 'bork'
})
});
runAppend(view);
},
teardown() {
delete helpers['capitalize'];
runDestroy(view);
Ember.lookup = originalLookup;
}
});
QUnit.test('it should render the current value of a property on the context', function() {
equal(view.$().text(), 'BORK', 'should render the current value of a property');
});
QUnit.test('it should not re-render if the property changes', function() {
run(function() {
view.set('context.foo', 'oof');
});
equal(view.$().text(), 'BORK', 'should not re-render if the property changes');
});
QUnit.test('it should re-render if the parent view rerenders', function() {
run(function() {
view.set('context.foo', 'oof');
view.rerender();
});
equal(view.$().text(), 'OOF', 'should re-render if the parent view rerenders');
});
QUnit.module('ember-htmlbars: {{#unbound}} subexpression - helper form', {
setup() {
Ember.lookup = lookup = { Ember: Ember };
expectDeprecation('`Ember.Handlebars.registerBoundHelper` is deprecated. Please refactor to use `Ember.Helpers.helper`.');
registerBoundHelper('capitalize', function(value) {
return value.toUpperCase();
});
registerBoundHelper('doublize', function(value) {
return `${value} ${value}`;
});
view = EmberView.create({
template: compile('{{capitalize (unbound doublize foo)}}'),
context: EmberObject.create({
foo: 'bork'
})
});
runAppend(view);
},
teardown() {
delete helpers['capitalize'];
delete helpers['doublize'];
runDestroy(view);
Ember.lookup = originalLookup;
}
});
QUnit.test('it should render the current value of a property on the context', function() {
equal(view.$().text(), 'BORK BORK', 'should render the current value of a property');
});
QUnit.test('it should not re-render if the property changes', function() {
run(function() {
view.set('context.foo', 'oof');
});
equal(view.$().text(), 'BORK BORK', 'should not re-render if the property changes');
});
QUnit.test('it should re-render if the parent view rerenders', function() {
run(function() {
view.set('context.foo', 'oof');
view.rerender();
});
equal(view.$().text(), 'OOF OOF', 'should re-render if the parent view rerenders');
});
QUnit.module('ember-htmlbars: {{#unbound boundHelper arg1 arg2... argN}} form: render unbound helper invocations', {
setup() {
Ember.lookup = lookup = { Ember: Ember };
expectDeprecationInHTMLBars();
expectDeprecation('`Ember.Handlebars.registerBoundHelper` is deprecated. Please refactor to use `Ember.Helpers.helper`.');
registerBoundHelper('surround', function(prefix, value, suffix) {
return prefix + '-' + value + '-' + suffix;
});
registerBoundHelper('capitalize', function(value) {
return value.toUpperCase();
});
registerBoundHelper('capitalizeName', function(value) {
return get(value, 'firstName').toUpperCase();
}, 'firstName');
registerBoundHelper('fauxconcat', function(value) {
return [].slice.call(arguments, 0, -1).join('');
});
registerBoundHelper('concatNames', function(value) {
return get(value, 'firstName') + get(value, 'lastName');
}, 'firstName', 'lastName');
},
teardown() {
delete helpers['surround'];
delete helpers['capitalize'];
delete helpers['capitalizeName'];
delete helpers['fauxconcat'];
delete helpers['concatNames'];
runDestroy(view);
Ember.lookup = originalLookup;
}
});
QUnit.test('should be able to render an unbound helper invocation', function() {
try {
registerBoundHelper('repeat', function(value, options) {
var count = options.hash.count;
var a = [];
while (a.length < count) {
a.push(value);
}
return a.join('');
});
view = EmberView.create({
template: compile('{{unbound repeat foo count=bar}} {{repeat foo count=bar}} {{unbound repeat foo count=2}} {{repeat foo count=4}}'),
context: EmberObject.create({
foo: 'X',
numRepeatsBinding: 'bar',
bar: 5
})
});
runAppend(view);
equal(view.$().text(), 'XXXXX XXXXX XX XXXX', 'first render is correct');
run(function() {
set(view, 'context.bar', 1);
});
equal(view.$().text(), 'XXXXX X XX XXXX', 'only unbound bound options changed');
} finally {
delete helpers['repeat'];
}
});
QUnit.test('should be able to render an unbound helper invocation with deprecated fooBinding [DEPRECATED]', function() {
try {
registerBoundHelper('repeat', function(value, options) {
var count = options.hash.count;
var a = [];
while (a.length < count) {
a.push(value);
}
return a.join('');
});
var template;
expectDeprecation(function() {
template = compile('{{unbound repeat foo countBinding="bar"}} {{repeat foo countBinding="bar"}} {{unbound repeat foo count=2}} {{repeat foo count=4}}');
}, /You're using legacy binding syntax/);
view = EmberView.create({
template,
context: EmberObject.create({
foo: 'X',
numRepeatsBinding: 'bar',
bar: 5
})
});
runAppend(view);
equal(view.$().text(), 'XXXXX XXXXX XX XXXX', 'first render is correct');
run(function() {
set(view, 'context.bar', 1);
});
equal(view.$().text(), 'XXXXX X XX XXXX', 'only unbound bound options changed');
} finally {
delete helpers['repeat'];
}
});
QUnit.test('should be able to render an bound helper invocation mixed with static values', function() {
view = EmberView.create({
template: compile('{{unbound surround prefix value "bar"}} {{surround prefix value "bar"}} {{unbound surround "bar" value suffix}} {{surround "bar" value suffix}}'),
context: EmberObject.create({
prefix: 'before',
value: 'core',
suffix: 'after'
})
});
runAppend(view);
equal(view.$().text(), 'before-core-bar before-core-bar bar-core-after bar-core-after', 'first render is correct');
run(function() {
set(view, 'context.prefix', 'beforeChanged');
set(view, 'context.value', 'coreChanged');
set(view, 'context.suffix', 'afterChanged');
});
equal(view.$().text(), 'before-core-bar beforeChanged-coreChanged-bar bar-core-after bar-coreChanged-afterChanged', 'only bound values change');
});
QUnit.test('should be able to render unbound forms of multi-arg helpers', function() {
view = EmberView.create({
template: compile('{{fauxconcat foo bar bing}} {{unbound fauxconcat foo bar bing}}'),
context: EmberObject.create({
foo: 'a',
bar: 'b',
bing: 'c'
})
});
runAppend(view);
equal(view.$().text(), 'abc abc', 'first render is correct');
run(function() {
set(view, 'context.bar', 'X');
});
equal(view.$().text(), 'aXc abc', 'unbound helpers/properties stayed the same');
});
QUnit.test('should be able to render an unbound helper invocation for helpers with dependent keys', function() {
view = EmberView.create({
template: compile('{{capitalizeName person}} {{unbound capitalizeName person}} {{concatNames person}} {{unbound concatNames person}}'),
context: EmberObject.create({
person: EmberObject.create({
firstName: 'shooby',
lastName: 'taylor'
})
})
});
runAppend(view);
equal(view.$().text(), 'SHOOBY SHOOBY shoobytaylor shoobytaylor', 'first render is correct');
run(function() {
set(view, 'context.person.firstName', 'sally');
});
equal(view.$().text(), 'SALLY SHOOBY sallytaylor shoobytaylor', 'only bound values change');
});
QUnit.test('should be able to render an unbound helper invocation in #each helper', function() {
view = EmberView.create({
template: compile(
['{{#each people as |person|}}',
'{{capitalize person.firstName}} {{unbound capitalize person.firstName}}',
'{{/each}}'].join('')),
context: {
people: Ember.A([
{
firstName: 'shooby',
lastName: 'taylor'
},
{
firstName: 'cindy',
lastName: 'taylor'
}
])
}
});
runAppend(view);
equal(view.$().text(), 'SHOOBY SHOOBYCINDY CINDY', 'unbound rendered correctly');
});
QUnit.test('should be able to render an unbound helper invocation with bound hash options', function() {
try {
Ember.Handlebars.registerBoundHelper('repeat', function(value) {
return [].slice.call(arguments, 0, -1).join('');
});
view = EmberView.create({
template: compile('{{capitalizeName person}} {{unbound capitalizeName person}} {{concatNames person}} {{unbound concatNames person}}'),
context: EmberObject.create({
person: EmberObject.create({
firstName: 'shooby',
lastName: 'taylor'
})
})
});
runAppend(view);
equal(view.$().text(), 'SHOOBY SHOOBY shoobytaylor shoobytaylor', 'first render is correct');
run(function() {
set(view, 'context.person.firstName', 'sally');
});
equal(view.$().text(), 'SALLY SHOOBY sallytaylor shoobytaylor', 'only bound values change');
} finally {
delete Ember.Handlebars.registerBoundHelper['repeat'];
}
});
QUnit.test('should be able to render bound form of a helper inside unbound form of same helper', function() {
view = EmberView.create({
template: compile(
['{{#unbound if foo}}',
'{{#if bar}}true{{/if}}',
'{{#unless bar}}false{{/unless}}',
'{{/unbound}}',
'{{#unbound unless notfoo}}',
'{{#if bar}}true{{/if}}',
'{{#unless bar}}false{{/unless}}',
'{{/unbound}}'].join('')),
context: EmberObject.create({
foo: true,
notfoo: false,
bar: true
})
});
runAppend(view);
equal(view.$().text(), 'truetrue', 'first render is correct');
run(function() {
set(view, 'context.bar', false);
});
equal(view.$().text(), 'falsefalse', 'bound if and unless inside unbound if/unless are updated');
});
QUnit.module('ember-htmlbars: {{#unbound}} helper -- Container Lookup', {
setup() {
Ember.lookup = lookup = { Ember: Ember };
registry = new Registry();
container = registry.container();
},
teardown() {
runDestroy(view);
runDestroy(container);
Ember.lookup = originalLookup;
registry = container = view = null;
}
});
QUnit.test('should lookup helpers in the container', function() {
expectDeprecationInHTMLBars();
expectDeprecation('Using Ember.Handlebars.makeBoundHelper is deprecated. Please refactor to using `Ember.Helper.helper`.');
registry.register('helper:up-case', makeBoundHelper(function(value) {
return value.toUpperCase();
}));
view = EmberView.create({
template: compile('{{unbound up-case displayText}}'),
container: container,
context: {
displayText: 'such awesome'
}
});
runAppend(view);
equal(view.$().text(), 'SUCH AWESOME', 'proper values were rendered');
run(function() {
set(view, 'context.displayText', 'no changes');
});
equal(view.$().text(), 'SUCH AWESOME', 'only bound values change');
});
QUnit.test('should be able to output a property without binding', function() {
var context = {
content: EmberObject.create({
anUnboundString: 'No spans here, son.'
})
};
view = EmberView.create({
context: context,
template: compile('<div id="first">{{unbound content.anUnboundString}}</div>')
});
runAppend(view);
equal(view.$('#first').html(), 'No spans here, son.');
});
QUnit.test('should be able to use unbound helper in #each helper', function() {
view = EmberView.create({
items: A(['a', 'b', 'c', 1, 2, 3]),
template: compile('<ul>{{#each view.items as |item|}}<li>{{unbound item}}</li>{{/each}}</ul>')
});
runAppend(view);
equal(view.$().text(), 'abc123');
equal(view.$('li').children().length, 0, 'No markers');
});
QUnit.test('should be able to use unbound helper in #each helper (with objects)', function() {
view = EmberView.create({
items: A([{ wham: 'bam' }, { wham: 1 }]),
template: compile('<ul>{{#each view.items as |item|}}<li>{{unbound item.wham}}</li>{{/each}}</ul>')
});
runAppend(view);
equal(view.$().text(), 'bam1');
equal(view.$('li').children().length, 0, 'No markers');
});
QUnit.test('should work properly with attributes', function() {
expect(4);
view = EmberView.create({
template: compile('<ul>{{#each view.people as |person|}}<li class="{{unbound person.cool}}">{{person.name}}</li>{{/each}}</ul>'),
people: A([{
name: 'Bob',
cool: 'not-cool'
}, {
name: 'James',
cool: 'is-cool'
}, {
name: 'Richard',
cool: 'is-cool'
}])
});
runAppend(view);
equal(view.$('li.not-cool').length, 1, 'correct number of not cool people');
equal(view.$('li.is-cool').length, 2, 'correct number of cool people');
run(function() {
set(view, 'people.firstObject.cool', 'is-cool');
});
equal(view.$('li.not-cool').length, 1, 'correct number of not cool people');
equal(view.$('li.is-cool').length, 2, 'correct number of cool people');
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _Statement2 = require('../Statement');
var _Statement3 = _interopRequireDefault(_Statement2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var TryStatement = function (_Statement) {
(0, _inherits3.default)(TryStatement, _Statement);
function TryStatement(childNodes) {
(0, _classCallCheck3.default)(this, TryStatement);
return (0, _possibleConstructorReturn3.default)(this, (0, _getPrototypeOf2.default)(TryStatement).call(this, 'TryStatement', childNodes));
}
(0, _createClass3.default)(TryStatement, [{
key: '_acceptChildren',
value: function _acceptChildren(children) {
children.passToken('Keyword', 'try');
children.skipNonCode();
var block = children.passStatement('BlockStatement');
children.skipNonCode();
var handler = null;
if (children.isNode('CatchClause')) {
handler = children.passNode();
}
var finalizer = null;
if (!children.isEnd) {
children.skipNonCode();
children.passToken('Keyword', 'finally');
children.skipNonCode();
finalizer = children.passStatement('BlockStatement');
}
children.assertEnd();
this.block = block;
this.finalizer = finalizer;
this.handler = handler;
}
}]);
return TryStatement;
}(_Statement3.default);
exports.default = TryStatement;
//# sourceMappingURL=TryStatement.js.map |
var _ = require('lodash');
function pathToArray(parts) {
var part = parts.shift();
if (parts.length > 0) {
var obj = {};
obj[part] = pathToArray(parts);
return obj;
} else {
return part;
}
}
module.exports = function(grunt) {
grunt.registerMultiTask('examples', 'Build examples site.', function() {
var options = this.options({
base: '',
excludes: []
});
this.files.forEach(function(f) {
if (grunt.option('verbose')) {
if (grunt.file.exists(f.dest)) {
grunt.verbose.writeln();
grunt.verbose.warn('Destination file "%s" will be overridden.', f.dest);
}
grunt.verbose.writeln();
}
var results = {};
var files = f.src.filter(function(filepath) {
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return options.excludes.every(function(dir) {
var keep = filepath.indexOf(options.base + '/' + dir + '/') < 0;
if (!keep) {
grunt.verbose.writeln('Skipping %s/%s/%s...', options.base, dir.inverse.red, filepath.substr(options.base.length + dir.length + 2));
}
return keep;
});
}
});
if (grunt.option('verbose')) {
grunt.verbose.writeln();
grunt.verbose.writeln('Found ' + files.length.toString().cyan + ' examples:');
files.forEach(function(file) {
grunt.verbose.writeln(' * '.cyan + file);
});
}
files.map(function(filepath) {
return pathToArray(filepath.substr(options.base.length + 1).split('/'));
}).forEach(function(parts) {
_.merge(results, parts, function(a, b) {
var example = {
file: encodeURIComponent(b).replace(/%20/g, '+'),
title: b.substr(0, b.length - 3)
};
return _.isArray(a) ? a.concat(example) : [example];
});
});
if (grunt.option('verbose')) {
var categories = Object.keys(results);
grunt.verbose.writeln();
grunt.verbose.writeln('Extracted ' + categories.length.toString().cyan + ' categories:');
categories.forEach(function(cat) {
grunt.verbose.writeln(' * '.cyan + cat);
});
}
grunt.verbose.writeln();
grunt.verbose.or.write('Writing ' + f.dest + '...');
grunt.file.write(f.dest, JSON.stringify(results, null, ' '));
grunt.verbose.or.ok();
});
});
};
|
'use strict';
const Utils = require('./../utils');
const Helpers = require('./helpers');
const _ = require('lodash');
const Association = require('./base');
/**
* One-to-many association
*
* In the API reference below, add the name of the association to the method, e.g. for `User.hasMany(Project)` the getter will be `user.getProjects()`.
* If the association is aliased, use the alias instead, e.g. `User.hasMany(Project, { as: 'jobs' })` will be `user.getJobs()`.
*
* @see {@link Model.hasMany}
*/
class HasMany extends Association {
constructor(source, target, options) {
super(source, target, options);
this.associationType = 'HasMany';
this.targetAssociation = null;
this.sequelize = source.sequelize;
this.through = options.through;
this.isMultiAssociation = true;
this.foreignKeyAttribute = {};
if (this.options.through) {
throw new Error('N:M associations are not supported with hasMany. Use belongsToMany instead');
}
/*
* If self association, this is the target association
*/
if (this.isSelfAssociation) {
this.targetAssociation = this;
}
if (this.as) {
this.isAliased = true;
if (_.isPlainObject(this.as)) {
this.options.name = this.as;
this.as = this.as.plural;
} else {
this.options.name = {
plural: this.as,
singular: Utils.singularize(this.as)
};
}
} else {
this.as = this.target.options.name.plural;
this.options.name = this.target.options.name;
}
/*
* Foreign key setup
*/
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else if (this.options.foreignKey) {
this.foreignKey = this.options.foreignKey;
}
if (!this.foreignKey) {
this.foreignKey = Utils.camelizeIf(
[
Utils.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
if (this.target.rawAttributes[this.foreignKey]) {
this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
this.foreignKeyField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
}
this.sourceKey = this.options.sourceKey || this.source.primaryKeyAttribute;
if (this.target.rawAttributes[this.sourceKey]) {
this.sourceKeyField = this.source.rawAttributes[this.sourceKey].field || this.sourceKey;
} else {
this.sourceKeyField = this.sourceKey;
}
if (this.source.fieldRawAttributesMap[this.sourceKey]) {
this.sourceKeyAttribute = this.source.fieldRawAttributesMap[this.sourceKey].fieldName;
} else {
this.sourceKeyAttribute = this.source.primaryKeyAttribute;
}
this.sourceIdentifier = this.sourceKey;
this.associationAccessor = this.as;
// Get singular and plural names, trying to uppercase the first letter, unless the model forbids it
const plural = Utils.uppercaseFirst(this.options.name.plural);
const singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
get: 'get' + plural,
set: 'set' + plural,
addMultiple: 'add' + plural,
add: 'add' + singular,
create: 'create' + singular,
remove: 'remove' + singular,
removeMultiple: 'remove' + plural,
hasSingle: 'has' + singular,
hasAll: 'has' + plural,
count: 'count' + plural
};
}
// the id is in the target table
// or in an extra table which connects two tables
injectAttributes() {
const newAttributes = {};
const constraintOptions = _.clone(this.options); // Create a new options object for use with addForeignKeyConstraints, to avoid polluting this.options in case it is later used for a n:m
newAttributes[this.foreignKey] = _.defaults({}, this.foreignKeyAttribute, {
type: this.options.keyType || this.source.rawAttributes[this.sourceKeyAttribute].type,
allowNull : true
});
if (this.options.constraints !== false) {
const target = this.target.rawAttributes[this.foreignKey] || newAttributes[this.foreignKey];
constraintOptions.onDelete = constraintOptions.onDelete || (target.allowNull ? 'SET NULL' : 'CASCADE');
constraintOptions.onUpdate = constraintOptions.onUpdate || 'CASCADE';
}
Helpers.addForeignKeyConstraints(newAttributes[this.foreignKey], this.source, this.target, constraintOptions, this.sourceKeyField);
Utils.mergeDefaults(this.target.rawAttributes, newAttributes);
this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
this.foreignKeyField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
this.target.refreshAttributes();
this.source.refreshAttributes();
Helpers.checkNamingCollision(this);
return this;
}
mixin(obj) {
const methods = ['get', 'count', 'hasSingle', 'hasAll', 'set', 'add', 'addMultiple', 'remove', 'removeMultiple', 'create'];
const aliases = {
hasSingle: 'has',
hasAll: 'has',
addMultiple: 'add',
removeMultiple: 'remove'
};
Helpers.mixinMethods(this, obj, methods, aliases);
}
/**
* Get everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @see {@link Model.findAll} for a full explanation of options
* @return {Promise<Array<Model>>}
*/
get(instances, options) {
const association = this;
const where = {};
let Model = association.target;
let instance;
let values;
if (!Array.isArray(instances)) {
instance = instances;
instances = undefined;
}
options = Utils.cloneDeep(options) || {};
if (association.scope) {
_.assign(where, association.scope);
}
if (instances) {
values = instances.map(instance => instance.get(association.sourceKey, {raw: true}));
if (options.limit && instances.length > 1) {
options.groupedLimit = {
limit: options.limit,
on: association,
values
};
delete options.limit;
} else {
where[association.foreignKey] = {
$in: values
};
delete options.groupedLimit;
}
} else {
where[association.foreignKey] = instance.get(association.sourceKey, {raw: true});
}
options.where = options.where ?
{$and: [where, options.where]} :
where;
if (options.hasOwnProperty('scope')) {
if (!options.scope) {
Model = Model.unscoped();
} else {
Model = Model.scope(options.scope);
}
}
if (options.hasOwnProperty('schema')) {
Model = Model.schema(options.schema, options.schemaDelimiter);
}
return Model.findAll(options).then(results => {
if (instance) return results;
const result = {};
for (const instance of instances) {
result[instance.get(association.sourceKey, {raw: true})] = [];
}
for (const instance of results) {
result[instance.get(association.foreignKey, {raw: true})].push(instance);
}
return result;
});
}
/**
* Count everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @return {Promise<Integer>}
*/
count(instance, options) {
const association = this;
const model = association.target;
const sequelize = model.sequelize;
options = Utils.cloneDeep(options);
options.attributes = [
[sequelize.fn('COUNT', sequelize.col(model.primaryKeyField)), 'count']
];
options.raw = true;
options.plain = true;
return association.get(instance, options).then(result => parseInt(result.count, 10));
}
/**
* Check if one or more rows are associated with `this`.
*
* @param {Model[]|Model|string[]|String|number[]|Number} [instance(s)]
* @param {Object} [options] Options passed to getAssociations
* @return {Promise}
*/
has(sourceInstance, targetInstances, options) {
const association = this;
const where = {};
if (!Array.isArray(targetInstances)) {
targetInstances = [targetInstances];
}
options = _.assign({}, options, {
scope: false,
raw: true
});
where.$or = targetInstances.map(instance => {
if (instance instanceof association.target) {
return instance.where();
} else {
const _where = {};
_where[association.target.primaryKeyAttribute] = instance;
return _where;
}
});
options.where = {
$and: [
where,
options.where
]
};
return association.get(sourceInstance, options).then(associatedObjects => associatedObjects.length === targetInstances.length);
}
/**
* Set the associated models by passing an array of persisted instances or their primary keys. Everything that is not in the passed array will be un-associated
*
* @param {Array<Model|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
* @param {Object} [options] Options passed to `target.findAll` and `update`.
* @param {Object} [options.validate] Run validation for the join model
* @return {Promise}
*/
set(sourceInstance, targetInstances, options) {
const association = this;
if (targetInstances === null) {
targetInstances = [];
} else {
targetInstances = association.toInstanceArray(targetInstances);
}
return association.get(sourceInstance, _.defaults({scope: false, raw: true}, options)).then(oldAssociations => {
const promises = [];
const obsoleteAssociations = oldAssociations.filter(old =>
!_.find(targetInstances, obj =>
obj[association.target.primaryKeyAttribute] === old[association.target.primaryKeyAttribute]
)
);
const unassociatedObjects = targetInstances.filter(obj =>
!_.find(oldAssociations, old =>
obj[association.target.primaryKeyAttribute] === old[association.target.primaryKeyAttribute]
)
);
let updateWhere;
let update;
if (obsoleteAssociations.length > 0) {
update = {};
update[association.foreignKey] = null;
updateWhere = {};
updateWhere[association.target.primaryKeyAttribute] = obsoleteAssociations.map(associatedObject =>
associatedObject[association.target.primaryKeyAttribute]
);
promises.push(association.target.unscoped().update(
update,
_.defaults({
where: updateWhere
}, options)
));
}
if (unassociatedObjects.length > 0) {
updateWhere = {};
update = {};
update[association.foreignKey] = sourceInstance.get(association.sourceKey);
_.assign(update, association.scope);
updateWhere[association.target.primaryKeyAttribute] = unassociatedObjects.map(unassociatedObject =>
unassociatedObject[association.target.primaryKeyAttribute]
);
promises.push(association.target.unscoped().update(
update,
_.defaults({
where: updateWhere
}, options)
));
}
return Utils.Promise.all(promises).return(sourceInstance);
});
}
/**
* Associate one or more target rows with `this`. This method accepts a Model / string / number to associate a single row,
* or a mixed array of Model / string / numbers to associate multiple rows.
*
* @param {Model[]|Model|string[]|string|number[]|number} [newAssociation(s)]
* @param {Object} [options] Options passed to `target.update`.
* @return {Promise}
*/
add(sourceInstance, targetInstances, options) {
if (!targetInstances) return Utils.Promise.resolve();
const association = this;
const update = {};
const where = {};
options = options || {};
targetInstances = association.toInstanceArray(targetInstances);
update[association.foreignKey] = sourceInstance.get(association.sourceKey);
_.assign(update, association.scope);
where[association.target.primaryKeyAttribute] = targetInstances.map(unassociatedObject =>
unassociatedObject.get(association.target.primaryKeyAttribute)
);
return association.target.unscoped().update(update, _.defaults({where}, options)).return(sourceInstance);
}
/**
* Un-associate one or several target rows.
*
* @param {Model[]|Model|String[]|string|Number[]|number} [oldAssociatedInstance(s)]
* @param {Object} [options] Options passed to `target.update`
* @return {Promise}
*/
remove(sourceInstance, targetInstances, options) {
const association = this;
const update = {};
const where = {};
options = options || {};
targetInstances = association.toInstanceArray(targetInstances);
update[association.foreignKey] = null;
where[association.foreignKey] = sourceInstance.get(association.sourceKey);
where[association.target.primaryKeyAttribute] = targetInstances.map(targetInstance =>
targetInstance.get(association.target.primaryKeyAttribute)
);
return association.target.unscoped().update(update, _.defaults({where}, options)).return(this);
}
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create`.
* @return {Promise}
*/
create(sourceInstance, values, options) {
const association = this;
options = options || {};
if (Array.isArray(options)) {
options = {
fields: options
};
}
if (values === undefined) {
values = {};
}
if (association.scope) {
for (const attribute of Object.keys(association.scope)) {
values[attribute] = association.scope[attribute];
if (options.fields) options.fields.push(attribute);
}
}
values[association.foreignKey] = sourceInstance.get(association.sourceKey);
if (options.fields) options.fields.push(association.foreignKey);
return association.target.create(values, options);
}
}
module.exports = HasMany;
module.exports.HasMany = HasMany;
module.exports.default = HasMany;
|
var task = require("@nathanfaucett/task"),
jshint = require("gulp-jshint"),
jsbeautifier = require("gulp-jsbeautifier");
task("jsbeautifier", "beautifier js files", task.parallel(
function taskfile() {
return (
task.src("./taskfile.js")
.pipe(jsbeautifier())
.pipe(task.dest("."))
);
},
function src() {
return (
task.src("./src/**/*.js")
.pipe(jsbeautifier())
.pipe(task.dest("./src"))
);
},
function test() {
return (
task.src("./test/**/*.js")
.pipe(jsbeautifier())
.pipe(task.dest("./test"))
);
}
));
task("jshint", "run jshint", function jsh() {
return (
task.src([
"./taskfile.js",
"./src/**/*.js",
"./test/**/*.js"
])
.pipe(jshint({
es3: true,
unused: true,
curly: true,
eqeqeq: true,
expr: true,
eqnull: true,
proto: true
}))
.pipe(jshint.reporter("default"))
);
});
task("default", task.series(
task("jsbeautifier"),
task("jshint")
)); |
/* http://keith-wood.name/countdown.html
* Slovenian localisation for the jQuery countdown extension
* Written by Borut Tomažin (debijan{at}gmail.com) (2011)
* updated by Jan Zavrl ([email protected]) (2015) */
(function($) {
'use strict';
$.countdown.regionalOptions.sl = {
labels: ['Let','Mesecev','Tednov','Dni','Ur','Minut','Sekund'], // Plurals
labels1: ['Leto','Mesec','Teden','Dan','Ura','Minuta','Sekunda'], // Singles
labels2: ['Leti','Meseca','Tedna','Dneva','Uri','Minuti','Sekundi'], // Doubles
labels3: ['Leta','Meseci','Tedni','Dnevi','Ure','Minute','Sekunde'], // 3's
labels4: ['Leta','Meseci','Tedni','Dnevi','Ure','Minute','Sekunde'], // 4's
compactLabels: ['l','m','t','d'],
whichLabels: function(amount) {
return (amount > 4 ? 0 : amount);
},
digits: ['0','1','2','3','4','5','6','7','8','9'],
timeSeparator: ':',
isRTL: false
};
$.countdown.setDefaults($.countdown.regionalOptions.sl);
})(jQuery);
|
module.exports={A:{A:{"2":"H E G C B A WB"},B:{"1":"g I J","2":"D u"},C:{"1":"0 1 2 3 4 5 6 a b c d N f M h i j k l m n o p q r s t y K","2":"UB x F L H E G C B A D u g I J Y O e P Q R S T U V W X v Z SB RB"},D:{"1":"0 1 2 3 4 5 6 i j k l m n o p q r s t y K GB AB CB VB DB EB","2":"F L H E G C B A D u g I J Y O e P Q R S T U V W X v Z a b c d N f M h"},E:{"1":"MB","2":"9 F L H E G C B A FB HB IB JB KB LB"},F:{"1":"V W X v Z a b c d N f M h i j k l m n o p q r s t","2":"7 8 C A D I J Y O e P Q R S T U NB OB PB QB TB w"},G:{"2":"9 G A BB z XB YB ZB aB bB cB dB eB"},H:{"2":"fB"},I:{"1":"K","2":"x F gB hB iB jB z kB lB"},J:{"2":"E B"},K:{"1":"M","2":"7 8 B A D w"},L:{"1":"AB"},M:{"1":"K"},N:{"2":"B A"},O:{"1":"mB"},P:{"1":"F L"},Q:{"1":"nB"},R:{"1":"oB"}},B:5,C:"Beacon API"};
|
/*
Copyright (c) 2008-2011, www.redips.net All rights reserved.
Code licensed under the BSD License: http://www.redips.net/license/
http://www.redips.net/javascript/drag-and-drop-table-content/
Version 5.0.5
Dec 27, 2012.
*/
var REDIPS=REDIPS||{};
REDIPS.drag=function(){var q,B,K,Aa,La,Ma,ca,da,ia,Ba,Ca,V,ja,Da,R,ka,Z,Ea,C,u,O,la,ma,na,Fa,oa,Ga,E,x,Ha,ea,fa,pa,Na,Oa,Ia,qa,ra,sa,ga,Ja,Pa,ta,Qa,n=null,G=0,H=0,ua=null,va=null,L=[],s=null,M=0,N=0,P=0,Q=0,S=0,T=0,$,f=[],aa,wa,p,I=[],m=[],y=null,D=null,W=0,X=0,Ra=0,Sa=0,ha=!1,Ka=!1,ba=!1,xa=[],h=null,t=null,z=null,j=null,v=null,J=null,k=null,A=null,U=null,i=!1,o=!1,r="cell",ya={div:[],cname:"only",other:"deny"},Ta={action:"deny",cname:"mark",exception:[]},l={},Ua={keyDiv:!1,keyRow:!1,sendBack:!1,
drop:!1};K=function(){return!1};q=function(a){var b,c,d,e,g;f.length=0;e=void 0===a?y.getElementsByTagName("table"):document.querySelectorAll(a);for(b=a=0;a<e.length;a++)if(!("redips_clone"===e[a].parentNode.id||-1<e[a].className.indexOf("nolayout"))){c=e[a].parentNode;d=0;do"TD"===c.nodeName&&d++,c=c.parentNode;while(c&&c!==y);f[b]=e[a];f[b].redips||(f[b].redips={});f[b].redips.container=y;f[b].redips.nestedLevel=d;f[b].redips.idx=b;xa[b]=0;d=f[b].getElementsByTagName("td");c=0;for(g=!1;c<d.length;c++)if(1<
d[c].rowSpan){g=!0;break}f[b].redips.rowspan=g;b++}a=0;for(e=aa=1;a<f.length;a++)if(0===f[a].redips.nestedLevel){f[a].redips.nestedGroup=e;f[a].redips.sort=100*aa;c=f[a].getElementsByTagName("table");for(b=0;b<c.length;b++)-1<c[b].className.indexOf("nolayout")||(c[b].redips.nestedGroup=e,c[b].redips.sort=100*aa+c[b].redips.nestedLevel);e++;aa++}};Aa=function(a){var b=a||window.event,c,d;if(!0===this.redips.animated)return!0;b.cancelBubble=!0;b.stopPropagation&&b.stopPropagation();Ka=b.shiftKey;a=
b.which?b.which:b.button;if(Ga(b)||!b.touches&&1!==a)return!0;if(window.getSelection)window.getSelection().removeAllRanges();else if(document.selection&&"Text"===document.selection.type)try{document.selection.empty()}catch(e){}b.touches?(a=W=b.touches[0].clientX,d=X=b.touches[0].clientY):(a=W=b.clientX,d=X=b.clientY);Ra=a;Sa=d;ha=!1;REDIPS.drag.objOld=o=i||this;REDIPS.drag.obj=i=this;ba=-1<i.className.indexOf("clone")?!0:!1;REDIPS.drag.tableSort&&Ma(i);y!==i.redips.container&&(y=i.redips.container,
q());-1===i.className.indexOf("row")?REDIPS.drag.mode=r="cell":(REDIPS.drag.mode=r="row",REDIPS.drag.obj=i=ga(i));u();!ba&&"cell"===r&&(i.style.zIndex=999);h=j=k=null;R();z=t=h;J=v=j;U=A=k;REDIPS.drag.td.source=l.source=x("TD",i);REDIPS.drag.td.current=l.current=l.source;REDIPS.drag.td.previous=l.previous=l.source;"cell"===r?REDIPS.drag.event.clicked(l.current):REDIPS.drag.event.rowClicked(l.current);if(null===h||null===j||null===k)if(R(),z=t=h,J=v=j,U=A=k,null===h||null===j||null===k)return!0;wa=
p=!1;REDIPS.event.add(document,"mousemove",da);REDIPS.event.add(document,"touchmove",da);REDIPS.event.add(document,"mouseup",ca);REDIPS.event.add(document,"touchend",ca);i.setCapture&&i.setCapture();null!==h&&(null!==j&&null!==k)&&($=Ea(h,j,k));c=E(f[z],"position");"fixed"!==c&&(c=E(f[z].parentNode,"position"));c=C(i,c);n=[d-c[0],c[1]-a,c[2]-d,a-c[3]];y.onselectstart=function(a){b=a||window.event;if(!Ga(b)){b.shiftKey&&document.selection.clear();return false}};return!1};La=function(){REDIPS.drag.event.dblClicked()};
Ma=function(a){var b;b=x("TABLE",a).redips.nestedGroup;for(a=0;a<f.length;a++)f[a].redips.nestedGroup===b&&(f[a].redips.sort=100*aa+f[a].redips.nestedLevel);f.sort(function(a,b){return b.redips.sort-a.redips.sort});aa++};ga=function(a,b){var c,d,e,g,f,w;if("DIV"===a.nodeName)return g=a,a=x("TR",a),void 0===a.redips&&(a.redips={}),a.redips.div=g,a;d=a;void 0===d.redips&&(d.redips={});a=x("TABLE",a);ba&&p&&(g=d.redips.div,g.className=ta(g.className.replace("clone","")));c=a.cloneNode(!0);ba&&p&&(g.className+=
" clone");e=c.rows.length-1;g="animated"===b?0===e?!0:!1:!0;for(f=e;0<=f;f--)if(f!==d.rowIndex){if(!0===g&&void 0===b){e=c.rows[f];for(w=0;w<e.cells.length;w++)if(-1<e.cells[w].className.indexOf("rowhandler")){g=!1;break}}c.deleteRow(f)}p||(d.redips.emptyRow=g);c.redips={};c.redips.container=a.redips.container;c.redips.sourceRow=d;Pa(d,c.rows[0]);Fa(d,c.rows[0]);document.getElementById("redips_clone").appendChild(c);d=C(d,"fixed");c.style.position="fixed";c.style.top=d[0]+"px";c.style.left=d[3]+"px";
c.style.width=d[1]-d[3]+"px";return c};Ja=function(a,b,c){var d=!1,e,g,za,w,j,F,Y,k;k=function(a){var b;void 0===a.redips||!a.redips.emptyRow?(b=x("TABLE",a),b.deleteRow(a.rowIndex)):sa(a,"empty",REDIPS.drag.style.rowEmptyColor)};void 0===c?c=i:d=!0;e=c.redips.sourceRow;g=e.rowIndex;za=x("TABLE",e);w=za.rows[0].parentNode;j=f[a];F=j.rows[b];Y=j.rows[0].parentNode;a=c.getElementsByTagName("tr")[0];c.parentNode.removeChild(c);!1!==REDIPS.drag.event.rowDroppedBefore(za,g)&&(!d&&-1<l.target.className.indexOf(REDIPS.drag.trash.className)?
p?REDIPS.drag.event.rowDeleted():REDIPS.drag.trash.questionRow?confirm(REDIPS.drag.trash.questionRow)?(k(e),REDIPS.drag.event.rowDeleted()):(delete o.redips.emptyRow,REDIPS.drag.event.rowUndeleted()):(k(e),REDIPS.drag.event.rowDeleted()):(b<j.rows.length?h===z?g>b?Y.insertBefore(a,F):Y.insertBefore(a,F.nextSibling):"after"===REDIPS.drag.rowDropMode?Y.insertBefore(a,F.nextSibling):Y.insertBefore(a,F):(Y.appendChild(a),F=j.rows[0]),F&&F.redips&&F.redips.emptyRow?Y.deleteRow(F.rowIndex):"overwrite"===
REDIPS.drag.rowDropMode?k(F):"switch"===REDIPS.drag.rowDropMode&&!p&&(w.insertBefore(F,e),void 0!==e.redips&&delete e.redips.emptyRow),(d||!p)&&k(e),delete a.redips.emptyRow,d||REDIPS.drag.event.rowDropped(a,za,g)),0<a.getElementsByTagName("table").length&&q())};Pa=function(a,b){var c,d,e,g=[],f=[];g[0]=a.getElementsByTagName("input");g[1]=a.getElementsByTagName("textarea");g[2]=a.getElementsByTagName("select");f[0]=b.getElementsByTagName("input");f[1]=b.getElementsByTagName("textarea");f[2]=b.getElementsByTagName("select");
for(c=0;c<g.length;c++)for(d=0;d<g[c].length;d++)switch(e=g[c][d].type,e){case "text":case "textarea":case "password":f[c][d].value=g[c][d].value;break;case "radio":case "checkbox":f[c][d].checked=g[c][d].checked;break;case "select-one":f[c][d].selectedIndex=g[c][d].selectedIndex;break;case "select-multiple":for(e=0;e<g[c][d].options.length;e++)f[c][d].options[e].selected=g[c][d].options[e].selected}};ca=function(a){var b=a||window.event,c,d,e,a=b.clientX;e=b.clientY;S=T=0;i.releaseCapture&&i.releaseCapture();
REDIPS.event.remove(document,"mousemove",da);REDIPS.event.remove(document,"touchmove",da);REDIPS.event.remove(document,"mouseup",ca);REDIPS.event.remove(document,"touchend",ca);y.onselectstart=null;Ca(i);ua=document.documentElement.scrollWidth;va=document.documentElement.scrollHeight;S=T=0;if(p&&"cell"===r&&(null===h||null===j||null===k))i.parentNode.removeChild(i),I[o.id]-=1,REDIPS.drag.event.notCloned();else if(null===h||null===j||null===k)REDIPS.drag.event.notMoved();else{h<f.length?(b=f[h],REDIPS.drag.td.target=
l.target=b.rows[j].cells[k],Z(h,j,k,$),c=h,d=j):null===t||null===v||null===A?(b=f[z],REDIPS.drag.td.target=l.target=b.rows[J].cells[U],Z(z,J,U,$),c=z,d=J):(b=f[t],REDIPS.drag.td.target=l.target=b.rows[v].cells[A],Z(t,v,A,$),c=t,d=v);if("row"===r)if(wa)if(z===c&&J===d){b=i.getElementsByTagName("tr")[0];o.style.backgroundColor=b.style.backgroundColor;for(a=0;a<b.cells.length;a++)o.cells[a].style.backgroundColor=b.cells[a].style.backgroundColor;i.parentNode.removeChild(i);delete o.redips.emptyRow;p?
REDIPS.drag.event.rowNotCloned():REDIPS.drag.event.rowDroppedSource(l.target)}else Ja(c,d);else REDIPS.drag.event.rowNotMoved();else if(!p&&!ha)REDIPS.drag.event.notMoved();else if(p&&z===h&&J===j&&U===k)i.parentNode.removeChild(i),I[o.id]-=1,REDIPS.drag.event.notCloned();else if(p&&!1===REDIPS.drag.clone.drop&&(a<b.redips.offset[3]||a>b.redips.offset[1]||e<b.redips.offset[0]||e>b.redips.offset[2]))i.parentNode.removeChild(i),I[o.id]-=1,REDIPS.drag.event.notCloned();else if(-1<l.target.className.indexOf(REDIPS.drag.trash.className))i.parentNode.removeChild(i),
REDIPS.drag.trash.question?setTimeout(function(){if(confirm(REDIPS.drag.trash.question))Ba();else{if(!p){f[z].rows[J].cells[U].appendChild(i);u()}REDIPS.drag.event.undeleted()}},20):Ba();else if("switch"===REDIPS.drag.dropMode)if(a=REDIPS.drag.event.droppedBefore(l.target),!1===a)ia(!1);else{i.parentNode.removeChild(i);b=l.target.getElementsByTagName("div");c=b.length;for(a=0;a<c;a++)void 0!==b[0]&&(REDIPS.drag.objOld=o=b[0],l.source.appendChild(o),V(o));ia();c&&REDIPS.drag.event.switched()}else"overwrite"===
REDIPS.drag.dropMode?(a=REDIPS.drag.event.droppedBefore(l.target),!1!==a&&fa(l.target)):a=REDIPS.drag.event.droppedBefore(l.target),ia(a);"cell"===r&&0<i.getElementsByTagName("table").length&&q();u();REDIPS.drag.event.finish()}t=v=A=null};ia=function(a){var b=null,c;if(!1!==a){if(!0===Ua.sendBack){a=l.target.getElementsByTagName("DIV");for(c=0;c<a.length;c++)if(i!==a[c]&&0===i.id.indexOf(a[c].id)){b=a[c];break}if(b){oa(b,1);i.parentNode.removeChild(i);return}}"shift"===REDIPS.drag.dropMode&&(Qa(l.target)||
"always"===REDIPS.drag.shift.after)&&pa(l.source,l.target);"top"===REDIPS.drag.multipleDrop&&l.target.hasChildNodes()?l.target.insertBefore(i,l.target.firstChild):l.target.appendChild(i);V(i);REDIPS.drag.event.dropped(l.target);p&&(REDIPS.drag.event.clonedDropped(l.target),oa(o,-1))}else p&&i.parentNode&&i.parentNode.removeChild(i)};V=function(a,b){!1===b?(a.onmousedown=null,a.ontouchstart=null,a.ondblclick=null):(a.onmousedown=Aa,a.ontouchstart=Aa,a.ondblclick=La)};Ca=function(a){a.style.top="";
a.style.left="";a.style.position="";a.style.zIndex=""};Ba=function(){var a;p&&oa(o,-1);if("shift"===REDIPS.drag.dropMode&&("delete"===REDIPS.drag.shift.after||"always"===REDIPS.drag.shift.after)){switch(REDIPS.drag.shift.mode){case "vertical2":a="lastInColumn";break;case "horizontal2":a="lastInRow";break;default:a="last"}pa(l.source,Ha(a,l.source)[2])}REDIPS.drag.event.deleted(p)};da=function(a){var a=a||window.event,b=REDIPS.drag.scroll.bound,c,d,e,g;a.touches?(d=W=a.touches[0].clientX,e=X=a.touches[0].clientY):
(d=W=a.clientX,e=X=a.clientY);c=Math.abs(Ra-d);g=Math.abs(Sa-e);if(!wa){if("cell"===r&&(ba||!0===REDIPS.drag.clone.keyDiv&&Ka))REDIPS.drag.objOld=o=i,REDIPS.drag.obj=i=na(i,!0),p=!0,REDIPS.drag.event.cloned();else{if("row"===r){if(ba||!0===REDIPS.drag.clone.keyRow&&Ka)p=!0;REDIPS.drag.objOld=o=i;REDIPS.drag.obj=i=ga(i);i.style.zIndex=999}i.setCapture&&i.setCapture();i.style.position="fixed";u();R();"row"===r&&(p?REDIPS.drag.event.rowCloned():REDIPS.drag.event.rowMoved())}ka();d>G-n[1]&&(i.style.left=
G-(n[1]+n[3])+"px");e>H-n[2]&&(i.style.top=H-(n[0]+n[2])+"px")}wa=!0;if("cell"===r&&(7<c||7<g)&&!ha)ha=!0,ka(),REDIPS.drag.event.moved(p);d>n[3]&&d<G-n[1]&&(i.style.left=d-n[3]+"px");e>n[0]&&e<H-n[2]&&(i.style.top=e-n[0]+"px");if(d<D[1]&&d>D[3]&&e<D[2]&&e>D[0]&&0===S&&0===T&&(m.containTable||d<m[3]||d>m[1]||e<m[0]||e>m[2]))R(),ja();if(REDIPS.drag.scroll.enable){M=b-(G/2>d?d-n[3]:G-d-n[1]);if(0<M){if(M>b&&(M=b),c=O()[0],M*=d<G/2?-1:1,!(0>M&&0>=c||0<M&&c>=ua-G)&&0===S++)REDIPS.event.remove(window,"scroll",
u),la(window)}else M=0;N=b-(H/2>e?e-n[0]:H-e-n[2]);if(0<N){if(N>b&&(N=b),c=O()[1],N*=e<H/2?-1:1,!(0>N&&0>=c||0<N&&c>=va-H)&&0===T++)REDIPS.event.remove(window,"scroll",u),ma(window)}else N=0;for(g=0;g<L.length;g++)if(c=L[g],c.autoscroll&&d<c.offset[1]&&d>c.offset[3]&&e<c.offset[2]&&e>c.offset[0]){P=b-(c.midstX>d?d-n[3]-c.offset[3]:c.offset[1]-d-n[1]);0<P?(P>b&&(P=b),P*=d<c.midstX?-1:1,0===S++&&(REDIPS.event.remove(c.div,"scroll",u),la(c.div))):P=0;Q=b-(c.midstY>e?e-n[0]-c.offset[0]:c.offset[2]-e-
n[2]);0<Q?(Q>b&&(Q=b),Q*=e<c.midstY?-1:1,0===T++&&(REDIPS.event.remove(c.div,"scroll",u),ma(c.div))):Q=0;break}else P=Q=0}a.cancelBubble=!0;a.stopPropagation&&a.stopPropagation()};ja=function(){if(h<f.length&&(h!==t||j!==v||k!==A))null!==t&&(null!==v&&null!==A)&&(Z(t,v,A,$),REDIPS.drag.td.previous=l.previous=f[t].rows[v].cells[A],REDIPS.drag.td.current=l.current=f[h].rows[j].cells[k],"switching"===REDIPS.drag.dropMode&&"cell"===r&&(ea(l.current,l.previous),u(),R()),"cell"===r?REDIPS.drag.event.changed(l.current):
"row"===r&&(h!==t||j!==v)&&REDIPS.drag.event.rowChanged(l.current)),ka()};Da=function(){if("number"===typeof window.innerWidth)G=window.innerWidth,H=window.innerHeight;else if(document.documentElement&&(document.documentElement.clientWidth||document.documentElement.clientHeight))G=document.documentElement.clientWidth,H=document.documentElement.clientHeight;else if(document.body&&(document.body.clientWidth||document.body.clientHeight))G=document.body.clientWidth,H=document.body.clientHeight;ua=document.documentElement.scrollWidth;
va=document.documentElement.scrollHeight;u()};R=function(){var a,b,c,d,e,g;c=[];a=function(){null!==t&&(null!==v&&null!==A)&&(h=t,j=v,k=A)};b=W;g=X;for(h=0;h<f.length;h++)if(!1!==f[h].redips.enabled&&(c[0]=f[h].redips.offset[0],c[1]=f[h].redips.offset[1],c[2]=f[h].redips.offset[2],c[3]=f[h].redips.offset[3],void 0!==f[h].sca&&(c[0]=c[0]>f[h].sca.offset[0]?c[0]:f[h].sca.offset[0],c[1]=c[1]<f[h].sca.offset[1]?c[1]:f[h].sca.offset[1],c[2]=c[2]<f[h].sca.offset[2]?c[2]:f[h].sca.offset[2],c[3]=c[3]>f[h].sca.offset[3]?
c[3]:f[h].sca.offset[3]),c[3]<b&&b<c[1]&&c[0]<g&&g<c[2])){c=f[h].redips.row_offset;for(j=0;j<c.length-1;j++)if(void 0!==c[j]){m[0]=c[j][0];if(void 0!==c[j+1])m[2]=c[j+1][0];else for(d=j+2;d<c.length;d++)if(void 0!==c[d]){m[2]=c[d][0];break}if(g<=m[2])break}d=j;j===c.length-1&&(m[0]=c[j][0],m[2]=f[h].redips.offset[2]);do for(k=e=f[h].rows[j].cells.length-1;0<=k&&!(m[3]=c[j][3]+f[h].rows[j].cells[k].offsetLeft,m[1]=m[3]+f[h].rows[j].cells[k].offsetWidth,m[3]<=b&&b<=m[1]);k--);while(f[h].redips.rowspan&&
-1===k&&0<j--);0>j||0>k?a():j!==d&&(m[0]=c[j][0],m[2]=m[0]+f[h].rows[j].cells[k].offsetHeight,(g<m[0]||g>m[2])&&a());b=f[h].rows[j].cells[k];m.containTable=0<b.childNodes.length&&0<b.getElementsByTagName("table").length?!0:!1;if(-1===b.className.indexOf(REDIPS.drag.trash.className))if(g=-1<b.className.indexOf(REDIPS.drag.only.cname)?!0:!1,!0===g){if(-1===b.className.indexOf(ya.div[i.id])){a();break}}else if(void 0!==ya.div[i.id]&&"deny"===ya.other){a();break}else if(g=-1<b.className.indexOf(REDIPS.drag.mark.cname)?
!0:!1,(!0===g&&"deny"===REDIPS.drag.mark.action||!1===g&&"allow"===REDIPS.drag.mark.action)&&-1===b.className.indexOf(Ta.exception[i.id])){a();break}g=-1<b.className.indexOf("single")?!0:!1;if("cell"===r){if(("single"===REDIPS.drag.dropMode||g)&&0<b.childNodes.length){if(1===b.childNodes.length&&3===b.firstChild.nodeType)break;g=!0;for(d=b.childNodes.length-1;0<=d;d--)if(b.childNodes[d].className&&-1<b.childNodes[d].className.indexOf("drag")){g=!1;break}if(!g&&(null!==t&&null!==v&&null!==A)&&(z!==
h||J!==j||U!==k)){a();break}}if(-1<b.className.indexOf("rowhandler")){a();break}if(b.parentNode.redips&&b.parentNode.redips.emptyRow){a();break}}break}};ka=function(){h<f.length&&(null!==h&&null!==j&&null!==k)&&($=Ea(h,j,k),Z(h,j,k),t=h,v=j,A=k)};Z=function(a,b,c,d){if("cell"===r&&ha)c=f[a].rows[b].cells[c].style,c.backgroundColor=void 0===d?REDIPS.drag.hover.colorTd:d.color[0].toString(),void 0!==REDIPS.drag.hover.borderTd&&(void 0===d?c.border=REDIPS.drag.hover.borderTd:(c.borderTopWidth=d.top[0][0],
c.borderTopStyle=d.top[0][1],c.borderTopColor=d.top[0][2],c.borderRightWidth=d.right[0][0],c.borderRightStyle=d.right[0][1],c.borderRightColor=d.right[0][2],c.borderBottomWidth=d.bottom[0][0],c.borderBottomStyle=d.bottom[0][1],c.borderBottomColor=d.bottom[0][2],c.borderLeftWidth=d.left[0][0],c.borderLeftStyle=d.left[0][1],c.borderLeftColor=d.left[0][2]));else if("row"===r){a=f[a].rows[b];for(b=0;b<a.cells.length;b++)c=a.cells[b].style,c.backgroundColor=void 0===d?REDIPS.drag.hover.colorTr:d.color[b].toString(),
void 0!==REDIPS.drag.hover.borderTr&&(void 0===d?h===z?j<J?c.borderTop=REDIPS.drag.hover.borderTr:c.borderBottom=REDIPS.drag.hover.borderTr:"before"===REDIPS.drag.rowDropMode?c.borderTop=REDIPS.drag.hover.borderTr:c.borderBottom=REDIPS.drag.hover.borderTr:(c.borderTopWidth=d.top[b][0],c.borderTopStyle=d.top[b][1],c.borderTopColor=d.top[b][2],c.borderBottomWidth=d.bottom[b][0],c.borderBottomStyle=d.bottom[b][1],c.borderBottomColor=d.bottom[b][2]))}};Ea=function(a,b,c){var d={color:[],top:[],right:[],
bottom:[],left:[]},e=function(a,b){var c="border"+b+"Style",d="border"+b+"Color";return[E(a,"border"+b+"Width"),E(a,c),E(a,d)]};if("cell"===r)c=f[a].rows[b].cells[c],d.color[0]=c.style.backgroundColor,void 0!==REDIPS.drag.hover.borderTd&&(d.top[0]=e(c,"Top"),d.right[0]=e(c,"Right"),d.bottom[0]=e(c,"Bottom"),d.left[0]=e(c,"Left"));else{a=f[a].rows[b];for(b=0;b<a.cells.length;b++)c=a.cells[b],d.color[b]=c.style.backgroundColor,void 0!==REDIPS.drag.hover.borderTr&&(d.top[b]=e(c,"Top"),d.bottom[b]=e(c,
"Bottom"))}return d};C=function(a,b,c){var d=0,e=0,g=a;"fixed"!==b&&(b=O(),d=0-b[0],e=0-b[1]);if(void 0===c||!0===c){do d+=a.offsetLeft-a.scrollLeft,e+=a.offsetTop-a.scrollTop,a=a.offsetParent;while(a&&"BODY"!==a.nodeName)}else{do d+=a.offsetLeft,e+=a.offsetTop,a=a.offsetParent;while(a&&"BODY"!==a.nodeName)}return[e,d+g.offsetWidth,e+g.offsetHeight,d]};u=function(){var a,b,c,d;for(a=0;a<f.length;a++){c=[];d=E(f[a],"position");"fixed"!==d&&(d=E(f[a].parentNode,"position"));for(b=f[a].rows.length-1;0<=
b;b--)"none"!==f[a].rows[b].style.display&&(c[b]=C(f[a].rows[b],d));f[a].redips.offset=C(f[a],d);f[a].redips.row_offset=c}D=C(y);for(a=0;a<L.length;a++)d=E(L[a].div,"position"),b=C(L[a].div,d,!1),L[a].offset=b,L[a].midstX=(b[1]+b[3])/2,L[a].midstY=(b[0]+b[2])/2};O=function(){var a,b;"number"===typeof window.pageYOffset?(a=window.pageXOffset,b=window.pageYOffset):document.body&&(document.body.scrollLeft||document.body.scrollTop)?(a=document.body.scrollLeft,b=document.body.scrollTop):document.documentElement&&
(document.documentElement.scrollLeft||document.documentElement.scrollTop)?(a=document.documentElement.scrollLeft,b=document.documentElement.scrollTop):a=b=0;return[a,b]};la=function(a){var b,c;b=W;c=X;0<S&&(u(),R(),b<D[1]&&(b>D[3]&&c<D[2]&&c>D[0])&&ja());"object"===typeof a&&(s=a);s===window?(a=O()[0],b=ua-G,c=M):(a=s.scrollLeft,b=s.scrollWidth-s.clientWidth,c=P);0<S&&(0>c&&0<a||0<c&&a<b)?(s===window?(window.scrollBy(c,0),O(),a=parseInt(i.style.left,10),isNaN(a)):s.scrollLeft+=c,setTimeout(la,REDIPS.drag.scroll.speed)):
(REDIPS.event.add(s,"scroll",u),S=0,m=[0,0,0,0])};ma=function(a){var b,c;b=W;c=X;0<T&&(u(),R(),b<D[1]&&(b>D[3]&&c<D[2]&&c>D[0])&&ja());"object"===typeof a&&(s=a);s===window?(a=O()[1],b=va-H,c=N):(a=s.scrollTop,b=s.scrollHeight-s.clientHeight,c=Q);0<T&&(0>c&&0<a||0<c&&a<b)?(s===window?(window.scrollBy(0,c),O(),a=parseInt(i.style.top,10),isNaN(a)):s.scrollTop+=c,setTimeout(ma,REDIPS.drag.scroll.speed)):(REDIPS.event.add(s,"scroll",u),T=0,m=[0,0,0,0])};na=function(a,b){var c=a.cloneNode(!0),d=c.className,
e,g;!0===b&&(document.getElementById("redips_clone").appendChild(c),c.style.zIndex=999,c.style.position="fixed",e=C(a),g=C(c),c.style.top=e[0]-g[0]+"px",c.style.left=e[3]-g[3]+"px");c.setCapture&&c.setCapture();d=d.replace("clone","");d=d.replace(/climit(\d)_(\d+)/,"");c.className=ta(d);void 0===I[a.id]&&(I[a.id]=0);c.id=a.id+"c"+I[a.id];I[a.id]+=1;Fa(a,c);return c};Fa=function(a,b){var c=[],d;c[0]=function(a,b){a.redips&&(b.redips={},b.redips.enabled=a.redips.enabled,b.redips.container=a.redips.container,
a.redips.enabled&&V(b))};c[1]=function(a,b){a.redips&&(b.redips={},b.redips.emptyRow=a.redips.emptyRow)};d=function(d){var g,f,w;f=["DIV","TR"];g=a.getElementsByTagName(f[d]);f=b.getElementsByTagName(f[d]);for(w=0;w<f.length;w++)c[d](g[w],f[w])};if("DIV"===a.nodeName)c[0](a,b);else if("TR"===a.nodeName)c[1](a,b);d(0);d(1)};oa=function(a,b){var c,d,e;e=a.className;c=e.match(/climit(\d)_(\d+)/);null!==c&&(d=parseInt(c[1],10),c=parseInt(c[2],10),0===c&&1===b&&(e+=" clone",2===d&&B(!0,a)),c+=b,e=e.replace(/climit\d_\d+/g,
"climit"+d+"_"+c),0>=c&&(e=e.replace("clone",""),2===d?(B(!1,a),REDIPS.drag.event.clonedEnd2()):REDIPS.drag.event.clonedEnd1()),a.className=ta(e))};Ga=function(a){var b=!1;a.srcElement?(b=a.srcElement.nodeName,a=a.srcElement.className):(b=a.target.nodeName,a=a.target.className);switch(b){case "A":case "INPUT":case "SELECT":case "OPTION":case "TEXTAREA":b=!0;break;default:b=/\bnodrag\b/i.test(a)?!0:!1}return b};B=function(a,b){var c,d,e,g=[],f=[],w,i,h,j,l=/\bdrag\b/i,k=/\bnoautoscroll\b/i;i=REDIPS.drag.style.opacityDisabled;
!0===a||"init"===a?(w=REDIPS.drag.style.borderEnabled,h="move",j=!0):(w=REDIPS.drag.style.borderDisabled,h="auto",j=!1);void 0===b?g=y.getElementsByTagName("div"):"string"===typeof b?g=document.querySelectorAll(b):"object"===typeof b&&("DIV"!==b.nodeName||-1===b.className.indexOf("drag"))?g=b.getElementsByTagName("div"):g[0]=b;for(d=c=0;c<g.length;c++)if(l.test(g[c].className))"init"===a||void 0===g[c].redips?(g[c].redips={},g[c].redips.container=y):!0===a&&"number"===typeof i?(g[c].style.opacity=
"",g[c].style.filter=""):!1===a&&"number"===typeof i&&(g[c].style.opacity=i/100,g[c].style.filter="alpha(opacity="+i+")"),V(g[c],j),g[c].style.borderStyle=w,g[c].style.cursor=h,g[c].redips.enabled=j;else if("init"===a&&(e=E(g[c],"overflow"),"visible"!==e)){REDIPS.event.add(g[c],"scroll",u);e=E(g[c],"position");f=C(g[c],e,!1);e=k.test(g[c].className)?!1:!0;L[d]={div:g[c],offset:f,midstX:(f[1]+f[3])/2,midstY:(f[0]+f[2])/2,autoscroll:e};f=g[c].getElementsByTagName("table");for(e=0;e<f.length;e++)f[e].sca=
L[d];d++}};E=function(a,b){var c;a&&a.currentStyle?c=a.currentStyle[b]:a&&window.getComputedStyle&&(c=document.defaultView.getComputedStyle(a,null)[b]);return c};x=function(a,b,c){b=b.parentNode;for(void 0===c&&(c=0);b&&b.nodeName!==a;)if((b=b.parentNode)&&b.nodeName===a&&0<c)c--,b=b.parentNode;return b};Ha=function(a,b){var c=x("TABLE",b),d,e;switch(a){case "firstInColumn":d=0;e=b.cellIndex;break;case "firstInRow":d=b.parentNode.rowIndex;e=0;break;case "lastInColumn":d=c.rows.length-1;e=b.cellIndex;
break;case "lastInRow":d=b.parentNode.rowIndex;e=c.rows[d].cells.length-1;break;case "last":d=c.rows.length-1;e=c.rows[d].cells.length-1;break;default:d=e=0}return[d,e,c.rows[d].cells[e]]};ea=function(a,b,c){var d,e,g;d=function(a,b){REDIPS.drag.event.relocateBefore(a,b);var c=REDIPS.drag.getPosition(b);REDIPS.drag.moveObject({obj:a,target:c,callback:function(a){var c=REDIPS.drag.findParent("TABLE",a),d=c.redips.idx;REDIPS.drag.event.relocateAfter(a,b);xa[d]--;0===xa[d]&&(REDIPS.drag.event.relocateEnd(),
REDIPS.drag.enableTable(!0,c))}})};if(a!==b&&!("object"!==typeof a||"object"!==typeof b))if(g=a.childNodes.length,"animation"===c){if(0<g){c=x("TABLE",b);e=c.redips.idx;REDIPS.drag.enableTable(!1,c);for(c=0;c<g;c++)1===a.childNodes[c].nodeType&&"DIV"===a.childNodes[c].nodeName&&(xa[e]++,d(a.childNodes[c],b))}}else for(d=c=0;c<g;c++)1===a.childNodes[d].nodeType&&"DIV"===a.childNodes[d].nodeName?(e=a.childNodes[d],REDIPS.drag.event.relocateBefore(e,b),b.appendChild(e),e.redips&&!1!==e.redips.enabled&&
V(e),REDIPS.drag.event.relocateAfter(e)):d++};fa=function(a,b){var c,d=[],e;if("TD"===a.nodeName){c=a.childNodes.length;if("test"===b)return c=l.source===a?void 0:0===a.childNodes.length||1===a.childNodes.length&&3===a.firstChild.nodeType?!0:!1;for(e=0;e<c;e++)d.push(a.childNodes[0]),a.removeChild(a.childNodes[0]);return d}};pa=function(a,b){var c,d,e,g,f,i,h,j,k,o,m,n,p=!1,q,r;q=function(a,b){REDIPS.drag.shift.animation?ea(a,b,"animation"):ea(a,b)};r=function(a){"delete"===REDIPS.drag.shift.overflow?
fa(a):"source"===REDIPS.drag.shift.overflow?q(a,l.source):"object"===typeof REDIPS.drag.shift.overflow&&q(a,REDIPS.drag.shift.overflow);p=!1;REDIPS.drag.event.shiftOverflow(a)};if(a!==b){f=REDIPS.drag.shift.mode;c=x("TABLE",a);d=x("TABLE",b);i=Na(d);e=c===d?[a.redips.rowIndex,a.redips.cellIndex]:[-1,-1];g=[b.redips.rowIndex,b.redips.cellIndex];m=d.rows.length;n=Oa(d);switch(f){case "vertical2":c=c===d&&a.redips.cellIndex===b.redips.cellIndex?e:[m,b.redips.cellIndex];break;case "horizontal2":c=c===
d&&a.parentNode.rowIndex===b.parentNode.rowIndex?e:[b.redips.rowIndex,n];break;default:c=c===d?e:[m,n]}"vertical1"===f||"vertical2"===f?(f=1E3*c[1]+c[0]<1E3*g[1]+g[0]?1:-1,d=m,m=0,n=1):(f=1E3*c[0]+c[1]<1E3*g[0]+g[1]?1:-1,d=n,m=1,n=0);for(c[0]!==e[0]&&c[1]!==e[1]&&(p=!0);c[0]!==g[0]||c[1]!==g[1];)(h=i[c[0]+"-"+c[1]],c[m]+=f,0>c[m]?(c[m]=d,c[n]--):c[m]>d&&(c[m]=0,c[n]++),e=i[c[0]+"-"+c[1]],void 0!==e&&(j=e),void 0!==h&&(k=h),void 0!==e&&void 0!==k||void 0!==j&&void 0!==h)?(e=-1===j.className.indexOf(REDIPS.drag.mark.cname)?
0:1,h=-1===k.className.indexOf(REDIPS.drag.mark.cname)?0:1,p&&0===e&&1===h&&r(j),1===e?0===h&&(o=k):(0===e&&1===h&&(k=o),q(j,k))):p&&(void 0!==j&&void 0===k)&&(e=-1===j.className.indexOf(REDIPS.drag.mark.cname)?0:1,0===e&&r(j))}};Na=function(a){var b=[],c,d={},e,g,f,i,h,j,k,l;i=a.rows;for(h=0;h<i.length;h++)for(j=0;j<i[h].cells.length;j++){c=i[h].cells[j];a=c.parentNode.rowIndex;e=c.rowSpan||1;g=c.colSpan||1;b[a]=b[a]||[];for(k=0;k<b[a].length+1;k++)if("undefined"===typeof b[a][k]){f=k;break}d[a+
"-"+f]=c;void 0===c.redips&&(c.redips={});c.redips.rowIndex=a;c.redips.cellIndex=f;for(k=a;k<a+e;k++){b[k]=b[k]||[];c=b[k];for(l=f;l<f+g;l++)c[l]="x"}}return d};Oa=function(a){var b=a.rows,c=0,d,e;"string"===typeof a&&document.getElementById(a);for(d=0;d<b.length;d++){for(e=a=0;e<b[d].cells.length;e++)a+=b[d].cells[e].colSpan||1;a>c&&(c=a)}return c};Ia=function(a,b){var c=(b.k1-b.k2*a)*(b.k1-b.k2*a),d,a=a+REDIPS.drag.animation.step*(4-3*c)*b.direction;d=b.m*a+b.b;"horizontal"===b.type?(b.obj.style.left=
a+"px",b.obj.style.top=d+"px"):(b.obj.style.left=d+"px",b.obj.style.top=a+"px");a<b.last&&0<b.direction||a>b.last&&0>b.direction?setTimeout(function(){Ia(a,b)},REDIPS.drag.animation.pause*c):(Ca(b.obj),b.obj.redips&&(b.obj.redips.animated=!1),"cell"===b.mode?(!0===b.overwrite&&fa(b.targetCell),b.targetCell.appendChild(b.obj),b.obj.redips&&!1!==b.obj.redips.enabled&&V(b.obj)):Ja(qa(b.target[0]),b.target[1],b.obj),"function"===typeof b.callback&&b.callback(b.obj))};ra=function(a){var b,c,d;b=[];b=c=
d=-1;if(void 0===a)b=h<f.length?f[h].redips.idx:null===t||null===v||null===A?f[z].redips.idx:f[t].redips.idx,c=f[z].redips.idx,b=[b,j,k,c,J,U];else{if(a="string"===typeof a?document.getElementById(a):a)"TD"!==a.nodeName&&(a=x("TD",a)),a&&"TD"===a.nodeName&&(b=a.cellIndex,c=a.parentNode.rowIndex,a=x("TABLE",a),d=a.redips.idx);b=[d,c,b]}return b};qa=function(a){var b;for(b=0;b<f.length&&f[b].redips.idx!==a;b++);return b};ta=function(a){void 0!==a&&(a=a.replace(/^\s+|\s+$/g,"").replace(/\s{2,}/g," "));
return a};Qa=function(a){var b;for(b=0;b<a.childNodes.length;b++)if(1===a.childNodes[b].nodeType)return!0;return!1};sa=function(a,b,c){var d,e;"string"===typeof a&&(a=document.getElementById(a),a=x("TABLE",a));if("TR"===a.nodeName){a=a.getElementsByTagName("td");for(d=0;d<a.length;d++)if(a[d].style.backgroundColor=c?c:"","empty"===b)a[d].innerHTML="";else for(e=0;e<a[d].childNodes.length;e++)1===a[d].childNodes[e].nodeType&&(a[d].childNodes[e].style.opacity=b/100,a[d].childNodes[e].style.filter="alpha(opacity="+
b+")")}else a.style.opacity=b/100,a.style.filter="alpha(opacity="+b+")",a.style.backgroundColor=c?c:""};return{obj:i,objOld:o,mode:r,td:l,hover:{colorTd:"#E7AB83",colorTr:"#E7AB83"},scroll:{enable:!0,bound:25,speed:20},only:ya,mark:Ta,style:{borderEnabled:"solid",borderDisabled:"dotted",opacityDisabled:"",rowEmptyColor:"white"},trash:{className:"trash",question:null,questionRow:null},saveParamName:"p",dropMode:"multiple",multipleDrop:"bottom",clone:Ua,animation:{pause:20,step:2,shift:!1},shift:{mode:"horizontal1",
after:"default",overflow:"bunch"},rowDropMode:"before",tableSort:!0,init:function(a){var b;if(void 0===a||"string"!==typeof a)a="drag";y=document.getElementById(a);document.getElementById("redips_clone")||(a=document.createElement("div"),a.id="redips_clone",a.style.width=a.style.height="1px",y.appendChild(a));B("init");q();Da();REDIPS.event.add(window,"resize",Da);b=y.getElementsByTagName("img");for(a=0;a<b.length;a++)REDIPS.event.add(b[a],"mousemove",K),REDIPS.event.add(b[a],"touchmove",K);REDIPS.event.add(window,
"scroll",u)},initTables:q,enableDrag:B,enableTable:function(a,b){var c;if("object"===typeof b&&"TABLE"===b.nodeName)b.redips.enabled=a;else for(c=0;c<f.length;c++)-1<f[c].className.indexOf(b)&&(f[c].redips.enabled=a)},cloneObject:na,saveContent:function(a,b){var c="",d,e,f,i,h,j,k,l=[],m=REDIPS.drag.saveParamName;"string"===typeof a&&(a=document.getElementById(a));if(void 0!==a&&"object"===typeof a&&"TABLE"===a.nodeName){d=a.rows.length;for(h=0;h<d;h++){e=a.rows[h].cells.length;for(j=0;j<e;j++)if(f=
a.rows[h].cells[j],0<f.childNodes.length)for(k=0;k<f.childNodes.length;k++)i=f.childNodes[k],"DIV"===i.nodeName&&-1<i.className.indexOf("drag")&&(c+=m+"[]="+i.id+"_"+h+"_"+j+"&",l.push([i.id,h,j]))}c="json"===b&&0<l.length?JSON.stringify(l):c.substring(0,c.length-1)}return c},relocate:ea,emptyCell:fa,moveObject:function(a){var b={direction:1},c,d,e,g,i,h;b.callback=a.callback;b.overwrite=a.overwrite;"string"===typeof a.id?b.obj=b.objOld=document.getElementById(a.id):"object"===typeof a.obj&&"DIV"===
a.obj.nodeName&&(b.obj=b.objOld=a.obj);if("row"===a.mode){b.mode="row";h=qa(a.source[0]);i=a.source[1];o=b.objOld=f[h].rows[i];if(o.redips&&!0===o.redips.emptyRow)return!1;b.obj=ga(b.objOld,"animated")}else if(b.obj&&-1<b.obj.className.indexOf("row")){b.mode="row";b.obj=b.objOld=o=x("TR",b.obj);if(o.redips&&!0===o.redips.emptyRow)return!1;b.obj=ga(b.objOld,"animated")}else b.mode="cell";if(!("object"!==typeof b.obj||null===b.obj))return b.obj.style.zIndex=999,b.obj.redips&&y!==b.obj.redips.container&&
(y=b.obj.redips.container,q()),h=C(b.obj),e=h[1]-h[3],g=h[2]-h[0],c=h[3],d=h[0],!0===a.clone&&"cell"===b.mode&&(b.obj=na(b.obj,!0),REDIPS.drag.event.cloned(b.obj)),void 0===a.target?a.target=ra():"object"===typeof a.target&&"TD"===a.target.nodeName&&(a.target=ra(a.target)),b.target=a.target,h=qa(a.target[0]),i=a.target[1],a=a.target[2],i>f[h].rows.length-1&&(i=f[h].rows.length-1),b.targetCell=f[h].rows[i].cells[a],"cell"===b.mode?(h=C(b.targetCell),i=h[1]-h[3],a=h[2]-h[0],e=h[3]+(i-e)/2,g=h[0]+(a-
g)/2):(h=C(f[h].rows[i]),e=h[3],g=h[0]),h=e-c,a=g-d,b.obj.style.position="fixed",Math.abs(h)>Math.abs(a)?(b.type="horizontal",b.m=a/h,b.b=d-b.m*c,b.k1=(c+e)/(c-e),b.k2=2/(c-e),c>e&&(b.direction=-1),h=c,b.last=e):(b.type="vertical",b.m=h/a,b.b=c-b.m*d,b.k1=(d+g)/(d-g),b.k2=2/(d-g),d>g&&(b.direction=-1),h=d,b.last=g),b.obj.redips&&(b.obj.redips.animated=!0),Ia(h,b),[b.obj,b.objOld]},shiftCells:pa,deleteObject:function(a){"object"===typeof a&&"DIV"===a.nodeName?a.parentNode.removeChild(a):"string"===
typeof a&&(a=document.getElementById(a))&&a.parentNode.removeChild(a)},getPosition:ra,rowOpacity:sa,rowEmpty:function(a,b,c){a=document.getElementById(a).rows[b];void 0===c&&(c=REDIPS.drag.style.rowEmptyColor);void 0===a.redips&&(a.redips={});a.redips.emptyRow=!0;sa(a,"empty",c)},getScrollPosition:O,getStyle:E,findParent:x,findCell:Ha,event:{changed:function(){},clicked:function(){},cloned:function(){},clonedDropped:function(){},clonedEnd1:function(){},clonedEnd2:function(){},dblClicked:function(){},
deleted:function(){},dropped:function(){},droppedBefore:function(){},finish:function(){},moved:function(){},notCloned:function(){},notMoved:function(){},shiftOverflow:function(){},relocateBefore:function(){},relocateAfter:function(){},relocateEnd:function(){},rowChanged:function(){},rowClicked:function(){},rowCloned:function(){},rowDeleted:function(){},rowDropped:function(){},rowDroppedBefore:function(){},rowDroppedSource:function(){},rowMoved:function(){},rowNotCloned:function(){},rowNotMoved:function(){},
rowUndeleted:function(){},switched:function(){},undeleted:function(){}}}}();REDIPS.event||(REDIPS.event=function(){return{add:function(q,B,K){q.addEventListener?q.addEventListener(B,K,!1):q.attachEvent?q.attachEvent("on"+B,K):q["on"+B]=K},remove:function(q,B,K){q.removeEventListener?q.removeEventListener(B,K,!1):q.detachEvent?q.detachEvent("on"+B,K):q["on"+B]=null}}}()); |
/**
* Module dependencies.
*/
var css = require('css');
/**
* Expose `rework`.
*/
exports = module.exports = rework;
/**
* Expose `visit` helpers.
*/
exports.visit = require('./visit');
/**
* Expose prefix properties.
*/
exports.properties = require('./properties');
/**
* Initialize a new stylesheet `Rework` with `str`.
*
* @param {String} str
* @return {Rework}
* @api public
*/
function rework(str) {
return new Rework(css.parse(str));
}
/**
* Initialize a new stylesheet `Rework` with `obj`.
*
* @param {Object} obj
* @api private
*/
function Rework(obj) {
this.obj = obj;
}
/**
* Use the given plugin `fn(style, rework)`.
*
* @param {Function} fn
* @return {Rework}
* @api public
*/
Rework.prototype.use = function(fn){
fn(this.obj.stylesheet, this);
return this;
};
/**
* Specify global vendor `prefixes`,
* explicit ones may still be passed
* to most plugins.
*
* @param {Array} prefixes
* @return {Rework}
* @api public
*/
Rework.prototype.vendors = function(prefixes){
this.prefixes = prefixes;
return this;
};
/**
* Stringify the stylesheet.
*
* @param {Object} options
* @return {String}
* @api public
*/
Rework.prototype.toString = function(options){
return css.stringify(this.obj, options);
};
/**
* Expose plugins.
*/
exports.mixin = exports.mixins = require('./plugins/mixin');
exports.function = exports.functions = require('./plugins/function');
exports.prefix = require('./plugins/prefix');
exports.colors = require('./plugins/colors');
exports.extend = require('rework-inherit');
exports.references = require('./plugins/references');
exports.prefixValue = require('./plugins/prefix-value');
exports.prefixSelectors = require('./plugins/prefix-selectors');
exports.keyframes = require('./plugins/keyframes');
exports.at2x = require('./plugins/at2x');
exports.url = require('./plugins/url');
exports.ease = require('./plugins/ease');
exports.vars = require('./plugins/vars');
/**
* Try/catch plugins unavailable in component.
*/
try {
exports.inline = require('./plugins/inline');
} catch (err) {};
|
import { get } from "ember-metal/property_get";
import run from "ember-metal/run_loop";
import EmberView from "ember-views/views/view";
import ContainerView from "ember-views/views/container_view";
var view;
QUnit.module("EmberView#destroyElement", {
teardown() {
run(function() {
view.destroy();
});
}
});
QUnit.test("if it has no element, does nothing", function() {
var callCount = 0;
view = EmberView.create({
willDestroyElement() { callCount++; }
});
ok(!get(view, 'element'), 'precond - does NOT have element');
run(function() {
view.destroyElement();
});
equal(callCount, 0, 'did not invoke callback');
});
QUnit.test("if it has a element, calls willDestroyElement on receiver and child views then deletes the element", function() {
expectDeprecation("Setting `childViews` on a Container is deprecated.");
var parentCount = 0;
var childCount = 0;
view = ContainerView.create({
willDestroyElement() { parentCount++; },
childViews: [ContainerView.extend({
// no willDestroyElement here... make sure no errors are thrown
childViews: [EmberView.extend({
willDestroyElement() { childCount++; }
})]
})]
});
run(function() {
view.createElement();
});
ok(get(view, 'element'), 'precond - view has element');
run(function() {
view.destroyElement();
});
equal(parentCount, 1, 'invoked destroy element on the parent');
equal(childCount, 1, 'invoked destroy element on the child');
ok(!get(view, 'element'), 'view no longer has element');
ok(!get(get(view, 'childViews').objectAt(0), 'element'), 'child no longer has an element');
});
QUnit.test("returns receiver", function() {
var ret;
view = EmberView.create();
run(function() {
view.createElement();
ret = view.destroyElement();
});
equal(ret, view, 'returns receiver');
});
QUnit.test("removes element from parentNode if in DOM", function() {
view = EmberView.create();
run(function() {
view.append();
});
var parent = view.$().parent();
ok(get(view, 'element'), 'precond - has element');
run(function() {
view.destroyElement();
});
equal(view.$(), undefined, 'view has no selector');
ok(!parent.find('#'+view.get('elementId')).length, 'element no longer in parent node');
});
|
/*
YUI 3.18.1 (build f7e7bcb)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('datasource-local', function (Y, NAME) {
/**
* The DataSource utility provides a common configurable interface for widgets to
* access a variety of data, from JavaScript arrays to online database servers.
*
* @module datasource
* @main datasource
*/
/**
* Provides the base DataSource implementation, which can be extended to
* create DataSources for specific data protocols, such as the IO Utility, the
* Get Utility, or custom functions.
*
* @module datasource
* @submodule datasource-local
*/
/**
* Base class for the DataSource Utility.
* @class DataSource.Local
* @extends Base
* @constructor
*/
var LANG = Y.Lang,
DSLocal = function() {
DSLocal.superclass.constructor.apply(this, arguments);
};
/////////////////////////////////////////////////////////////////////////////
//
// DataSource static properties
//
/////////////////////////////////////////////////////////////////////////////
Y.mix(DSLocal, {
/**
* Class name.
*
* @property NAME
* @type String
* @static
* @final
* @value "dataSourceLocal"
*/
NAME: "dataSourceLocal",
/////////////////////////////////////////////////////////////////////////////
//
// DataSource Attributes
//
/////////////////////////////////////////////////////////////////////////////
ATTRS: {
/**
* @attribute source
* @description Pointer to live data.
* @type MIXED
* @default null
*/
source: {
value: null
}
},
/**
* Global transaction counter.
*
* @property _tId
* @type Number
* @static
* @private
* @default 0
*/
_tId: 0,
/**
* Global in-progress transaction objects.
*
* @property transactions
* @type Object
* @static
*/
transactions: {},
/**
* Returns data to callback.
*
* @method issueCallback
* @param e {EventFacade} Event Facade.
* @param caller {DataSource} Calling DataSource instance.
* @static
*/
issueCallback: function (e, caller) {
var callbacks = e.on || e.callback,
callback = callbacks && callbacks.success,
payload = e.details[0];
payload.error = (e.error || e.response.error);
if (payload.error) {
caller.fire("error", payload);
callback = callbacks && callbacks.failure;
}
if (callback) {
//TODO: this should be executed from a specific context
callback(payload);
}
}
});
Y.extend(DSLocal, Y.Base, {
/**
* Internal init() handler.
*
* @method initializer
* @param config {Object} Config object.
* @private
*/
initializer: function(config) {
this._initEvents();
},
/**
* This method creates all the events for this module.
* @method _initEvents
* @private
*/
_initEvents: function() {
/**
* Fired when a data request is received.
*
* @event request
* @param e {EventFacade} Event Facade with the following properties:
* <dl>
* <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd>
* <dt>request (Object)</dt> <dd>The request.</dd>
* <dt>callback (Object)</dt> <dd>The callback object
* (deprecated, refer to <strong>on</strong></dd>
* <dt>on (Object)</dt> <dd>The map of configured callback
* functions.</dd>
* <dt>cfg (Object)</dt> <dd>Configuration object.</dd>
* </dl>
* @preventable _defRequestFn
*/
this.publish("request", {defaultFn: Y.bind("_defRequestFn", this), queuable:true});
/**
* Fired when raw data is received.
*
* @event data
* @param e {EventFacade} Event Facade with the following properties:
* <dl>
* <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd>
* <dt>request (Object)</dt> <dd>The request.</dd>
* <dt>callback (Object)</dt> <dd>Deprecated alias for the
* <strong>on</strong> property</dd>
* <dt>on (Object)</dt> <dd>The map of configured transaction
* callbacks. An object with the following properties:
* <dl>
* <dt>success (Function)</dt> <dd>Success handler.</dd>
* <dt>failure (Function)</dt> <dd>Failure handler.</dd>
* </dl>
* </dd>
* <dt>cfg (Object)</dt> <dd>Configuration object.</dd>
* <dt>data (Object)</dt> <dd>Raw data.</dd>
* </dl>
* @preventable _defDataFn
*/
this.publish("data", {defaultFn: Y.bind("_defDataFn", this), queuable:true});
/**
* Fired when response is returned.
*
* @event response
* @param e {EventFacade} Event Facade with the following properties:
* <dl>
* <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd>
* <dt>request (Object)</dt> <dd>The request.</dd>
* <dt>callback (Object)</dt> <dd>Deprecated alias for the
* <strong>on</strong> property</dd>
* <dt>on (Object)</dt> <dd>The map of configured transaction
* callbacks. An object with the following properties:
* <dl>
* <dt>success (Function)</dt> <dd>Success handler.</dd>
* <dt>failure (Function)</dt> <dd>Failure handler.</dd>
* </dl>
* </dd>
* <dt>cfg (Object)</dt> <dd>Configuration object.</dd>
* <dt>data (Object)</dt> <dd>Raw data.</dd>
* <dt>response (Object)</dt>
* <dd>Normalized response object with the following properties:
* <dl>
* <dt>results (Object)</dt> <dd>Parsed results.</dd>
* <dt>meta (Object)</dt> <dd>Parsed meta data.</dd>
* <dt>error (Boolean)</dt> <dd>Error flag.</dd>
* </dl>
* </dd>
* <dt>error</dt>
* <dd>Any error that occurred along the transaction lifecycle.</dd>
* </dl>
* @preventable _defResponseFn
*/
this.publish("response", {defaultFn: Y.bind("_defResponseFn", this), queuable:true});
/**
* Fired when an error is encountered.
*
* @event error
* @param e {EventFacade} Event Facade with the following properties:
* <dl>
* <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd>
* <dt>request (Object)</dt> <dd>The request.</dd>
* <dt>callback (Object)</dt> <dd>Deprecated alias for the
* <strong>on</strong> property</dd>
* <dt>on (Object)</dt> <dd>The map of configured transaction
* callbacks. An object with the following properties:
* <dl>
* <dt>success (Function)</dt> <dd>Success handler.</dd>
* <dt>failure (Function)</dt> <dd>Failure handler.</dd>
* </dl>
* </dd>
* <dt>cfg (Object)</dt> <dd>Configuration object.</dd>
* <dt>data (Object)</dt> <dd>Raw data.</dd>
* <dt>response (Object)</dt>
* <dd>Normalized response object with the following properties:
* <dl>
* <dt>results (Object)</dt> <dd>Parsed results.</dd>
* <dt>meta (Object)</dt> <dd>Parsed meta data.</dd>
* <dt>error (Object)</dt> <dd>Error object.</dd>
* </dl>
* </dd>
* <dt>error</dt>
* <dd>Any error that occurred along the transaction lifecycle.</dd>
* </dl>
*/
},
/**
* Manages request/response transaction. Must fire <code>response</code>
* event when response is received. This method should be implemented by
* subclasses to achieve more complex behavior such as accessing remote data.
*
* @method _defRequestFn
* @param e {EventFacade} Event Facadewith the following properties:
* <dl>
* <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd>
* <dt>request (Object)</dt> <dd>The request.</dd>
* <dt>callback (Object)</dt> <dd>Deprecated alias for the
* <strong>on</strong> property</dd>
* <dt>on (Object)</dt> <dd>The map of configured transaction
* callbacks. An object with the following properties:
* <dl>
* <dt>success (Function)</dt> <dd>Success handler.</dd>
* <dt>failure (Function)</dt> <dd>Failure handler.</dd>
* </dl>
* </dd>
* <dt>cfg (Object)</dt> <dd>Configuration object.</dd>
* </dl>
* @protected
*/
_defRequestFn: function(e) {
var data = this.get("source"),
payload = e.details[0];
// Problematic data
if(LANG.isUndefined(data)) {
payload.error = new Error("Local source undefined");
Y.log("Local source undefined", "error", "datasource-local");
}
payload.data = data;
this.fire("data", payload);
Y.log("Transaction " + e.tId + " complete. Request: " +
Y.dump(e.request) + " . Response: " + Y.dump(e.response), "info", "datasource-local");
},
/**
* Normalizes raw data into a response that includes results and meta properties.
*
* @method _defDataFn
* @param e {EventFacade} Event Facade with the following properties:
* <dl>
* <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd>
* <dt>request (Object)</dt> <dd>The request.</dd>
* <dt>callback (Object)</dt> <dd>Deprecated alias for the
* <strong>on</strong> property</dd>
* <dt>on (Object)</dt> <dd>The map of configured transaction
* callbacks. An object with the following properties:
* <dl>
* <dt>success (Function)</dt> <dd>Success handler.</dd>
* <dt>failure (Function)</dt> <dd>Failure handler.</dd>
* </dl>
* </dd>
* <dt>cfg (Object)</dt> <dd>Configuration object.</dd>
* <dt>data (Object)</dt> <dd>Raw data.</dd>
* </dl>
* @protected
*/
_defDataFn: function(e) {
var data = e.data,
meta = e.meta,
response = {
results: (LANG.isArray(data)) ? data : [data],
meta: (meta) ? meta : {}
},
payload = e.details[0];
payload.response = response;
this.fire("response", payload);
},
/**
* Sends data as a normalized response to callback.
*
* @method _defResponseFn
* @param e {EventFacade} Event Facade with the following properties:
* <dl>
* <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd>
* <dt>request (Object)</dt> <dd>The request.</dd>
* <dt>callback (Object)</dt> <dd>Deprecated alias for the
* <strong>on</strong> property</dd>
* <dt>on (Object)</dt> <dd>The map of configured transaction
* callbacks. An object with the following properties:
* <dl>
* <dt>success (Function)</dt> <dd>Success handler.</dd>
* <dt>failure (Function)</dt> <dd>Failure handler.</dd>
* </dl>
* </dd>
* <dt>cfg (Object)</dt> <dd>Configuration object.</dd>
* <dt>data (Object)</dt> <dd>Raw data.</dd>
* <dt>response (Object)</dt> <dd>Normalized response object with the following properties:
* <dl>
* <dt>results (Object)</dt> <dd>Parsed results.</dd>
* <dt>meta (Object)</dt> <dd>Parsed meta data.</dd>
* <dt>error (Boolean)</dt> <dd>Error flag.</dd>
* </dl>
* </dd>
* </dl>
* @protected
*/
_defResponseFn: function(e) {
// Send the response back to the callback
DSLocal.issueCallback(e, this);
},
/**
* Generates a unique transaction ID and fires <code>request</code> event.
* <strong>Note</strong>: the property <code>callback</code> is a
* deprecated alias for the <code>on</code> transaction configuration
* property described below.
*
* @method sendRequest
* @param [request] {Object} An object literal with the following properties:
* <dl>
* <dt><code>request</code></dt>
* <dd>The request to send to the live data source, if any.</dd>
* <dt><code>on</code></dt>
* <dd>An object literal with the following properties:
* <dl>
* <dt><code>success</code></dt>
* <dd>The function to call when the data is ready.</dd>
* <dt><code>failure</code></dt>
* <dd>The function to call upon a response failure condition.</dd>
* <dt><code>argument</code></dt>
* <dd>Arbitrary data payload that will be passed back to the success and failure handlers.</dd>
* </dl>
* </dd>
* <dt><code>cfg</code></dt>
* <dd>Configuration object, if any.</dd>
* </dl>
* @return {Number} Transaction ID.
*/
sendRequest: function(request) {
var tId = DSLocal._tId++,
callbacks;
request = request || {};
callbacks = request.on || request.callback;
this.fire("request", {
tId: tId,
request: request.request,
on: callbacks,
callback: callbacks,
cfg: request.cfg || {}
});
Y.log("Transaction " + tId + " sent request: " + Y.dump(request.request), "info", "datasource-local");
return tId;
}
});
Y.namespace("DataSource").Local = DSLocal;
}, '3.18.1', {"requires": ["base"]});
|
// Note that this file is required before we install our Babel hooks in
// ../tool-env/install-babel.js, so we can't use ES2015+ syntax here.
var fs = require("fs");
var path = require("path");
// The dev_bundle/bin command has to come immediately after the meteor
// command, as in `meteor npm` or `meteor node`, because we don't want to
// require("./main.js") for these commands.
var devBundleBinCommand = process.argv[2];
var args = process.argv.slice(3);
function getChildProcess() {
if (typeof devBundleBinCommand !== "string") {
return Promise.resolve(null);
}
var helpers = require("./dev-bundle-bin-helpers.js");
return Promise.all([
helpers.getDevBundle(),
helpers.getEnv()
]).then(function (devBundleAndEnv) {
var devBundleDir = devBundleAndEnv[0];
var cmd = helpers.getCommand(devBundleBinCommand, devBundleDir);
if (! cmd) {
return null;
}
var env = devBundleAndEnv[1];
var child = require("child_process").spawn(cmd, args, {
stdio: "inherit",
env: env
});
require("./flush-buffers-on-exit-in-windows.js");
child.on("error", function (error) {
console.log(error.stack || error);
});
child.on("exit", function (exitCode) {
process.exit(exitCode);
});
return child;
});
}
module.exports = getChildProcess();
|
module.exports={A:{A:{"2":"H E G C B A VB"},B:{"2":"D u g I J"},C:{"1":"0 1 2 3 4 5 6 s t y K","2":"TB x F L H E G C B A D u g I J Y O e P Q R S T U V W X v Z a b c d N f M h i j k l m n o p q r RB QB"},D:{"1":"1 2 4 5 6 K FB AB CB UB DB","2":"F L H E G C B A D u g I J Y O e P Q R S T U V W X v Z a b c d N f M h i j k l m n o p q r s t y","194":"0 3"},E:{"1":"B A KB LB","2":"9 F L H E G C EB GB HB IB JB"},F:{"1":"k l m n o p q r s t","2":"7 8 C A D I J Y O e P Q R S T U V W X v Z a b c d N f M h i MB NB OB PB SB w","194":"j"},G:{"1":"A cB dB","2":"9 G BB z WB XB YB ZB aB bB"},H:{"2":"eB"},I:{"1":"K","2":"x F fB gB hB iB z jB kB"},J:{"2":"E B"},K:{"2":"7 8 B A D M w"},L:{"1":"AB"},M:{"1":"K"},N:{"2":"B A"},O:{"2":"lB"},P:{"2":"F L"},Q:{"194":"mB"},R:{"2":"nB"}},B:1,C:"DOM manipulation convenience methods"};
|
import {KEY_CODES} from './../helpers/unicode';
import {extend} from './../helpers/object';
import {setCaretPosition} from './../helpers/dom/element';
import {stopImmediatePropagation, isImmediatePropagationStopped} from './../helpers/dom/event';
import {getEditor, registerEditor} from './../editors';
import {TextEditor} from './textEditor';
var HandsontableEditor = TextEditor.prototype.extend();
/**
* @private
* @editor HandsontableEditor
* @class HandsontableEditor
* @dependencies TextEditor
*/
HandsontableEditor.prototype.createElements = function() {
TextEditor.prototype.createElements.apply(this, arguments);
var DIV = document.createElement('DIV');
DIV.className = 'handsontableEditor';
this.TEXTAREA_PARENT.appendChild(DIV);
this.htContainer = DIV;
this.assignHooks();
};
HandsontableEditor.prototype.prepare = function(td, row, col, prop, value, cellProperties) {
TextEditor.prototype.prepare.apply(this, arguments);
var parent = this;
var options = {
startRows: 0,
startCols: 0,
minRows: 0,
minCols: 0,
className: 'listbox',
copyPaste: false,
autoColumnSize: false,
autoRowSize: false,
readOnly: true,
fillHandle: false,
afterOnCellMouseDown: function() {
var value = this.getValue();
// if the value is undefined then it means we don't want to set the value
if (value !== void 0) {
parent.setValue(value);
}
parent.instance.destroyEditor();
}
};
if (this.cellProperties.handsontable) {
extend(options, cellProperties.handsontable);
}
this.htOptions = options;
};
var onBeforeKeyDown = function(event) {
if (isImmediatePropagationStopped(event)) {
return;
}
var editor = this.getActiveEditor();
var innerHOT = editor.htEditor.getInstance(); //Handsontable.tmpHandsontable(editor.htContainer, 'getInstance');
var rowToSelect;
if (event.keyCode == KEY_CODES.ARROW_DOWN) {
if (!innerHOT.getSelected()) {
rowToSelect = 0;
} else {
var selectedRow = innerHOT.getSelected()[0];
var lastRow = innerHOT.countRows() - 1;
rowToSelect = Math.min(lastRow, selectedRow + 1);
}
} else if (event.keyCode == KEY_CODES.ARROW_UP) {
if (innerHOT.getSelected()) {
var selectedRow = innerHOT.getSelected()[0];
rowToSelect = selectedRow - 1;
}
}
if (rowToSelect !== void 0) {
if (rowToSelect < 0) {
innerHOT.deselectCell();
} else {
innerHOT.selectCell(rowToSelect, 0);
}
if (innerHOT.getData().length) {
event.preventDefault();
stopImmediatePropagation(event);
editor.instance.listen();
editor.TEXTAREA.focus();
}
}
};
HandsontableEditor.prototype.open = function() {
this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
TextEditor.prototype.open.apply(this, arguments);
if (this.htEditor) {
this.htEditor.destroy();
}
this.htEditor = new Handsontable(this.htContainer, this.htOptions);
if (this.cellProperties.strict) {
this.htEditor.selectCell(0, 0);
this.TEXTAREA.style.visibility = 'hidden';
} else {
this.htEditor.deselectCell();
this.TEXTAREA.style.visibility = 'visible';
}
setCaretPosition(this.TEXTAREA, 0, this.TEXTAREA.value.length);
};
HandsontableEditor.prototype.close = function() {
this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
this.instance.listen();
TextEditor.prototype.close.apply(this, arguments);
};
HandsontableEditor.prototype.focus = function() {
this.instance.listen();
TextEditor.prototype.focus.apply(this, arguments);
};
HandsontableEditor.prototype.beginEditing = function(initialValue) {
var onBeginEditing = this.instance.getSettings().onBeginEditing;
if (onBeginEditing && onBeginEditing() === false) {
return;
}
TextEditor.prototype.beginEditing.apply(this, arguments);
};
HandsontableEditor.prototype.finishEditing = function(isCancelled, ctrlDown) {
if (this.htEditor && this.htEditor.isListening()) { //if focus is still in the HOT editor
//if (Handsontable.tmpHandsontable(this.htContainer,'isListening')) { //if focus is still in the HOT editor
//if (this.$htContainer.handsontable('isListening')) { //if focus is still in the HOT editor
this.instance.listen(); //return the focus to the parent HOT instance
}
if (this.htEditor && this.htEditor.getSelected()) {
//if (Handsontable.tmpHandsontable(this.htContainer,'getSelected')) {
//if (this.$htContainer.handsontable('getSelected')) {
// var value = this.$htContainer.handsontable('getInstance').getValue();
var value = this.htEditor.getInstance().getValue();
//var value = Handsontable.tmpHandsontable(this.htContainer,'getInstance').getValue();
if (value !== void 0) { //if the value is undefined then it means we don't want to set the value
this.setValue(value);
}
}
return TextEditor.prototype.finishEditing.apply(this, arguments);
};
HandsontableEditor.prototype.assignHooks = function() {
var _this = this;
this.instance.addHook('afterDestroy', function() {
if (_this.htEditor) {
_this.htEditor.destroy();
}
});
};
export {HandsontableEditor};
registerEditor('handsontable', HandsontableEditor);
|
console.log(require("../dll/alpha"));
console.log(require("../dll/a"));
console.log(require("beta/beta"));
console.log(require("beta/b"));
console.log(require("module"));
|
import Ember from 'ember';
export default Ember.Controller.extend({
hasNoDependency: Ember.computed(function() {
return true;
}),
hasMultipleDependencies: Ember.computed('foo', 'bar', function() {
return this.getProperties('foo', 'bar');
}),
chainedCP: Ember.computed('foo', function() {
return false;
}).volatile().readOnly(),
isNotExtendingPrototype: Ember.computed(function() {
return true;
}),
isNotExtendingPrototypeWithDependencies: Ember.computed('foo', function() {
return this.get('foo');
}),
simpleObserver: Ember.observer('foo', function() {
this.set('bar', true);
}),
chainedObserver: Ember.on('init', Ember.observer('foo', 'bar', function(property) {
this.set('baz', true);
})),
onInit: Ember.on('init', function() {
this.set('foobar', true);
})
});
|
Subsets and Splits