code
stringlengths 2
1.05M
|
---|
/**
* # authActions.js
*
* All the request actions have 3 variations, the request, a success
* and a failure. They all follow the pattern that the request will
* set the ```isFetching``` to true and the whether it's successful or
* fails, setting it back to false.
*
*/
/**
* ## Imports
*
* The actions supported
*/
const {
LOGOUT,
REGISTER,
LOGIN,
FORGOT_PASSWORD,
MENU_ITEM_ADD_OR_EDIT_USER,
LOGOUT_REQUEST,
LOGOUT_SUCCESS,
LOGOUT_FAILURE,
LOGIN_REQUEST,
LOGIN_SUCCESS,
LOGIN_FAILURE,
ON_AUTH_FORM_FIELD_CHANGE,
SIGNUP_REQUEST,
SIGNUP_SUCCESS,
SIGNUP_FAILURE,
RESET_PASSWORD_REQUEST,
RESET_PASSWORD_SUCCESS,
RESET_PASSWORD_FAILURE,
SET_STATE
} = require('../../lib/constants').default
const _ = require('underscore')
/**
* ## State actions
* controls which form is displayed to the user
* as in login, register, logout or reset password
*/
export function logoutState() {
return {
type: LOGOUT
}
}
export function registerState() {
return {
type: REGISTER
}
}
export function loginState() {
return {
type: LOGIN
}
}
export function editUserState() {
return {
type: MENU_ITEM_ADD_OR_EDIT_USER
}
}
export function forgotPasswordState() {
return {
type: FORGOT_PASSWORD
}
}
/**
* ## Logout actions
*/
export function logoutRequest() {
return {
type: LOGOUT_REQUEST
}
}
export function logoutSuccess() {
return {
type: LOGOUT_SUCCESS
}
}
export function logoutFailure(error) {
return {
type: LOGOUT_FAILURE,
payload: error
}
}
/**
* ## onAuthFormFieldChange
* Set the payload so the reducer can work on it
*/
export function onAuthFormFieldChange(field, value) {
return {
type: ON_AUTH_FORM_FIELD_CHANGE,
payload: {field: field, value: value}
}
}
/**
* ## Signup actions
*/
export function signupRequest() {
return {
type: SIGNUP_REQUEST
}
}
export function signupSuccess(json) {
return {
type: SIGNUP_SUCCESS,
payload: json
}
}
export function signupFailure(error) {
return {
type: SIGNUP_FAILURE,
payload: error
}
}
/**
* ## signup
* @param {string} username - name of user
* @param {string} email - user's email
* @param {string} password - user's password
* @param {string} roleType - user's type, such as "admin","client","driver"
*
* Call the server signup and if good, save the sessionToken,
* set the state to logout and signal success
*
* Otherwise, dispatch the error so the user can see
*/
export function signup(username, email, password, roleType) {
return dispatch => {
dispatch(deleteTokenRequestSuccess())
}
}
export function deleteTokenRequestSuccess() {
return {
type: DELETE_TOKEN_SUCCESS
}
}
/**
* ## Login actions
*/
export function resetAuthorForm() {
return {
type: SET_STATE
}
}
/**
* ## Login actions
*/
export function loginRequest() {
return {
type: LOGIN_REQUEST
}
}
export function loginSuccess(json) {
return {
type: LOGIN_SUCCESS,
payload: json
}
}
export function loginFailure(error) {
return {
type: LOGIN_FAILURE,
payload: error
}
}
/**
* ## Login
* @param {string} username - user's name
* @param {string} password - user's password
*
* After calling Backend, if response is good, save the json
* which is the currentUser which contains the sessionToken
*
* If successful, set the state to logout
* otherwise, dispatch a failure
*/
export function login(username, password) {
return dispatch => {
dispatch(loginRequest())
}
}
/**
* ## ResetPassword actions
*/
export function resetPasswordRequest() {
return {
type: RESET_PASSWORD_REQUEST
}
}
export function resetPasswordSuccess() {
return {
type: RESET_PASSWORD_SUCCESS
}
}
export function resetPasswordFailure(error) {
return {
type: RESET_PASSWORD_FAILURE,
payload: error
}
}
/**
* ## ResetPassword
*
* @param {string} email - the email address to reset password
* *Note* There's no feedback to the user whether the email
* address is valid or not.
*
* This functionality depends on the server set
* up correctly ie, that emails are verified.
* With that enabled, an email can be sent w/ a
* form for setting the new password.
*/
export function resetPassword(email) {
return dispatch => {
return dispatch(resetPasswordRequest())
}
}
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@ag-grid-community/core");
var toolPanelColumnGroupComp_1 = require("./toolPanelColumnGroupComp");
var toolPanelColumnComp_1 = require("./toolPanelColumnComp");
var primaryColsHeaderPanel_1 = require("./primaryColsHeaderPanel");
var columnModelItem_1 = require("./columnModelItem");
var ColumnModel = /** @class */ (function () {
function ColumnModel(items) {
this.items = items;
}
ColumnModel.prototype.getRowCount = function () {
return this.items.length;
};
ColumnModel.prototype.getRow = function (index) {
return this.items[index];
};
return ColumnModel;
}());
var PrimaryColsListPanel = /** @class */ (function (_super) {
__extends(PrimaryColsListPanel, _super);
function PrimaryColsListPanel() {
var _this = _super.call(this, PrimaryColsListPanel.TEMPLATE) || this;
_this.destroyColumnItemFuncs = [];
return _this;
}
PrimaryColsListPanel.prototype.destroyColumnTree = function () {
this.allColsTree = [];
this.destroyColumnItemFuncs.forEach(function (f) { return f(); });
this.destroyColumnItemFuncs = [];
};
PrimaryColsListPanel.prototype.init = function (params, allowDragging, eventType) {
var _this = this;
this.params = params;
this.allowDragging = allowDragging;
this.eventType = eventType;
if (!this.params.suppressSyncLayoutWithGrid) {
this.addManagedListener(this.eventService, core_1.Events.EVENT_COLUMN_MOVED, this.onColumnsChanged.bind(this));
}
this.addManagedListener(this.eventService, core_1.Events.EVENT_NEW_COLUMNS_LOADED, this.onColumnsChanged.bind(this));
var eventsImpactingCheckedState = [
core_1.Events.EVENT_COLUMN_PIVOT_CHANGED,
core_1.Events.EVENT_COLUMN_PIVOT_MODE_CHANGED,
core_1.Events.EVENT_COLUMN_ROW_GROUP_CHANGED,
core_1.Events.EVENT_COLUMN_VALUE_CHANGED,
core_1.Events.EVENT_COLUMN_VISIBLE,
core_1.Events.EVENT_NEW_COLUMNS_LOADED
];
eventsImpactingCheckedState.forEach(function (event) {
// update header select all checkbox with current selection state
_this.addManagedListener(_this.eventService, event, _this.fireSelectionChangedEvent.bind(_this));
});
this.expandGroupsByDefault = !this.params.contractColumnSelection;
this.virtualList = this.createManagedBean(new core_1.VirtualList('column-select', 'tree'));
this.appendChild(this.virtualList.getGui());
this.virtualList.setComponentCreator(function (item, listItemElement) { return _this.createComponentFromItem(item, listItemElement); });
if (this.columnController.isReady()) {
this.onColumnsChanged();
}
};
PrimaryColsListPanel.prototype.createComponentFromItem = function (item, listItemElement) {
if (item.isGroup()) {
var renderedGroup = new toolPanelColumnGroupComp_1.ToolPanelColumnGroupComp(item, this.allowDragging, this.eventType, listItemElement);
this.getContext().createBean(renderedGroup);
return renderedGroup;
}
var columnComp = new toolPanelColumnComp_1.ToolPanelColumnComp(item.getColumn(), item.getDept(), this.allowDragging, this.groupsExist, listItemElement);
this.getContext().createBean(columnComp);
return columnComp;
};
PrimaryColsListPanel.prototype.onColumnsChanged = function () {
var expandedStates = this.getExpandedStates();
var pivotModeActive = this.columnController.isPivotMode();
var shouldSyncColumnLayoutWithGrid = !this.params.suppressSyncLayoutWithGrid && !pivotModeActive;
if (shouldSyncColumnLayoutWithGrid) {
this.buildTreeFromWhatGridIsDisplaying();
}
else {
this.buildTreeFromProvidedColumnDefs();
}
this.setExpandedStates(expandedStates);
this.markFilteredColumns();
this.flattenAndFilterModel();
};
PrimaryColsListPanel.prototype.getExpandedStates = function () {
if (!this.allColsTree) {
return {};
}
var res = {};
this.forEachItem(function (item) {
if (!item.isGroup()) {
return;
}
var colGroup = item.getColumnGroup();
if (colGroup) { // group should always exist, this is defensive
res[colGroup.getId()] = item.isExpanded();
}
});
return res;
};
PrimaryColsListPanel.prototype.setExpandedStates = function (states) {
if (!this.allColsTree) {
return;
}
this.forEachItem(function (item) {
if (!item.isGroup()) {
return;
}
var colGroup = item.getColumnGroup();
if (colGroup) { // group should always exist, this is defensive
var expanded = states[colGroup.getId()];
var groupExistedLastTime = expanded != null;
if (groupExistedLastTime) {
item.setExpanded(expanded);
}
}
});
};
PrimaryColsListPanel.prototype.buildTreeFromWhatGridIsDisplaying = function () {
this.colDefService.syncLayoutWithGrid(this.setColumnLayout.bind(this));
};
PrimaryColsListPanel.prototype.setColumnLayout = function (colDefs) {
var columnTree = this.colDefService.createColumnTree(colDefs);
this.buildListModel(columnTree);
// using col defs to check if groups exist as it could be a custom layout
this.groupsExist = colDefs.some(function (colDef) {
return colDef && typeof colDef.children !== 'undefined';
});
this.markFilteredColumns();
this.flattenAndFilterModel();
};
PrimaryColsListPanel.prototype.buildTreeFromProvidedColumnDefs = function () {
// add column / group comps to tool panel
this.buildListModel(this.columnController.getPrimaryColumnTree());
this.groupsExist = this.columnController.isPrimaryColumnGroupsPresent();
};
PrimaryColsListPanel.prototype.buildListModel = function (columnTree) {
var _this = this;
var columnExpandedListener = this.onColumnExpanded.bind(this);
var addListeners = function (item) {
item.addEventListener(columnModelItem_1.ColumnModelItem.EVENT_EXPANDED_CHANGED, columnExpandedListener);
var removeFunc = item.removeEventListener.bind(item, columnModelItem_1.ColumnModelItem.EVENT_EXPANDED_CHANGED, columnExpandedListener);
_this.destroyColumnItemFuncs.push(removeFunc);
};
var recursivelyBuild = function (tree, dept, parentList) {
tree.forEach(function (child) {
if (child instanceof core_1.OriginalColumnGroup) {
createGroupItem(child, dept, parentList);
}
else {
createColumnItem(child, dept, parentList);
}
});
};
var createGroupItem = function (columnGroup, dept, parentList) {
var columnGroupDef = columnGroup.getColGroupDef();
var skipThisGroup = columnGroupDef && columnGroupDef.suppressColumnsToolPanel;
if (skipThisGroup) {
return;
}
if (columnGroup.isPadding()) {
recursivelyBuild(columnGroup.getChildren(), dept, parentList);
return;
}
var displayName = _this.columnController.getDisplayNameForOriginalColumnGroup(null, columnGroup, _this.eventType);
var item = new columnModelItem_1.ColumnModelItem(displayName, columnGroup, dept, true, _this.expandGroupsByDefault);
parentList.push(item);
addListeners(item);
recursivelyBuild(columnGroup.getChildren(), dept + 1, item.getChildren());
};
var createColumnItem = function (column, dept, parentList) {
var skipThisColumn = column.getColDef() && column.getColDef().suppressColumnsToolPanel;
if (skipThisColumn) {
return;
}
var displayName = _this.columnController.getDisplayNameForColumn(column, 'columnToolPanel');
parentList.push(new columnModelItem_1.ColumnModelItem(displayName, column, dept));
};
this.destroyColumnTree();
recursivelyBuild(columnTree, 0, this.allColsTree);
};
PrimaryColsListPanel.prototype.onColumnExpanded = function () {
this.flattenAndFilterModel();
};
PrimaryColsListPanel.prototype.flattenAndFilterModel = function () {
var _this = this;
this.displayedColsList = [];
var recursiveFunc = function (item) {
if (!item.isPassesFilter()) {
return;
}
_this.displayedColsList.push(item);
if (item.isGroup() && item.isExpanded()) {
item.getChildren().forEach(recursiveFunc);
}
};
this.allColsTree.forEach(recursiveFunc);
this.virtualList.setModel(new ColumnModel(this.displayedColsList));
var focusedRow = this.virtualList.getLastFocusedRow();
this.virtualList.refresh();
if (focusedRow != null) {
this.focusRowIfAlive(focusedRow);
}
this.notifyListeners();
};
PrimaryColsListPanel.prototype.focusRowIfAlive = function (rowIndex) {
var _this = this;
window.setTimeout(function () {
if (_this.isAlive()) {
_this.virtualList.focusRow(rowIndex);
}
}, 0);
};
PrimaryColsListPanel.prototype.forEachItem = function (callback) {
var recursiveFunc = function (items) {
items.forEach(function (item) {
callback(item);
if (item.isGroup()) {
recursiveFunc(item.getChildren());
}
});
};
recursiveFunc(this.allColsTree);
};
PrimaryColsListPanel.prototype.doSetExpandedAll = function (value) {
this.forEachItem(function (item) {
if (item.isGroup()) {
item.setExpanded(value);
}
});
};
PrimaryColsListPanel.prototype.setGroupsExpanded = function (expand, groupIds) {
if (!groupIds) {
this.doSetExpandedAll(expand);
return;
}
var expandedGroupIds = [];
this.forEachItem(function (item) {
if (!item.isGroup()) {
return;
}
var groupId = item.getColumnGroup().getId();
if (groupIds.indexOf(groupId) >= 0) {
item.setExpanded(expand);
expandedGroupIds.push(groupId);
}
});
var unrecognisedGroupIds = groupIds.filter(function (groupId) { return !core_1._.includes(expandedGroupIds, groupId); });
if (unrecognisedGroupIds.length > 0) {
console.warn('AG Grid: unable to find group(s) for supplied groupIds:', unrecognisedGroupIds);
}
};
PrimaryColsListPanel.prototype.getExpandState = function () {
var expandedCount = 0;
var notExpandedCount = 0;
this.forEachItem(function (item) {
if (!item.isGroup()) {
return;
}
if (item.isExpanded()) {
expandedCount++;
}
else {
notExpandedCount++;
}
});
if (expandedCount > 0 && notExpandedCount > 0) {
return primaryColsHeaderPanel_1.ExpandState.INDETERMINATE;
}
if (notExpandedCount > 0) {
return primaryColsHeaderPanel_1.ExpandState.COLLAPSED;
}
return primaryColsHeaderPanel_1.ExpandState.EXPANDED;
};
PrimaryColsListPanel.prototype.doSetSelectedAll = function (selectAllChecked) {
this.modelItemUtils.selectAllChildren(this.allColsTree, selectAllChecked, this.eventType);
};
PrimaryColsListPanel.prototype.getSelectionState = function () {
var checkedCount = 0;
var uncheckedCount = 0;
var pivotMode = this.columnController.isPivotMode();
this.forEachItem(function (item) {
if (item.isGroup()) {
return;
}
if (!item.isPassesFilter()) {
return;
}
var column = item.getColumn();
var colDef = column.getColDef();
var checked;
if (pivotMode) {
var noPivotModeOptionsAllowed = !column.isAllowPivot() && !column.isAllowRowGroup() && !column.isAllowValue();
if (noPivotModeOptionsAllowed) {
return;
}
checked = column.isValueActive() || column.isPivotActive() || column.isRowGroupActive();
}
else {
if (colDef.lockVisible) {
return;
}
checked = column.isVisible();
}
checked ? checkedCount++ : uncheckedCount++;
});
if (checkedCount > 0 && uncheckedCount > 0) {
return undefined;
}
return !(checkedCount === 0 || uncheckedCount > 0);
};
PrimaryColsListPanel.prototype.setFilterText = function (filterText) {
this.filterText = core_1._.exists(filterText) ? filterText.toLowerCase() : null;
this.markFilteredColumns();
this.flattenAndFilterModel();
};
PrimaryColsListPanel.prototype.markFilteredColumns = function () {
var _this = this;
var passesFilter = function (item) {
if (!core_1._.exists(_this.filterText)) {
return true;
}
var displayName = item.getDisplayName();
return displayName == null || displayName.toLowerCase().indexOf(_this.filterText) !== -1;
};
var recursivelyCheckFilter = function (item, parentPasses) {
var atLeastOneChildPassed = false;
if (item.isGroup()) {
var groupPasses_1 = passesFilter(item);
item.getChildren().forEach(function (child) {
var childPasses = recursivelyCheckFilter(child, groupPasses_1 || parentPasses);
if (childPasses) {
atLeastOneChildPassed = childPasses;
}
});
}
var filterPasses = (parentPasses || atLeastOneChildPassed) ? true : passesFilter(item);
item.setPassesFilter(filterPasses);
return filterPasses;
};
this.allColsTree.forEach(function (item) { return recursivelyCheckFilter(item, false); });
};
PrimaryColsListPanel.prototype.notifyListeners = function () {
this.fireGroupExpandedEvent();
this.fireSelectionChangedEvent();
};
PrimaryColsListPanel.prototype.fireGroupExpandedEvent = function () {
var expandState = this.getExpandState();
this.dispatchEvent({ type: 'groupExpanded', state: expandState });
};
PrimaryColsListPanel.prototype.fireSelectionChangedEvent = function () {
var selectionState = this.getSelectionState();
this.dispatchEvent({ type: 'selectionChanged', state: selectionState });
};
PrimaryColsListPanel.TEMPLATE = "<div class=\"ag-column-select-list\" role=\"tree\"></div>";
__decorate([
core_1.Autowired('columnController')
], PrimaryColsListPanel.prototype, "columnController", void 0);
__decorate([
core_1.Autowired('toolPanelColDefService')
], PrimaryColsListPanel.prototype, "colDefService", void 0);
__decorate([
core_1.Autowired('columnApi')
], PrimaryColsListPanel.prototype, "columnApi", void 0);
__decorate([
core_1.Autowired('modelItemUtils')
], PrimaryColsListPanel.prototype, "modelItemUtils", void 0);
__decorate([
core_1.PreDestroy
], PrimaryColsListPanel.prototype, "destroyColumnTree", null);
return PrimaryColsListPanel;
}(core_1.Component));
exports.PrimaryColsListPanel = PrimaryColsListPanel;
//# sourceMappingURL=primaryColsListPanel.js.map
|
exports.init = function (req, res, next) {
res.send('You get wrong url !');
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var default_i18n_1 = require("./default-i18n");
var msg_formatter_1 = require("./formatters/msg-formatter");
exports.createFormatter = msg_formatter_1.createFormatter;
exports.default = default_i18n_1.createI18N;
//# sourceMappingURL=types.js.map
|
// curry :: ((a, b, c, ...) -> z) -> a -> b -> c -> ... -> z
export const curry = (fn, ...args) => args.length >= fn.length ? fn(...args) : curry.bind(null, fn, ...args)
// compose2 :: (b -> c) -> (a -> b) -> a -> c
const compose2 = (f, g) => x => f(g(x))
// compose :: (a -> c) -> [(a -> a)] -> (a -> c)
export const compose = (...fns) => fns.reduce(compose2)
// of :: a -> [b]
export const of = Array.of.bind(Array)
// id :: a -> a
export const id = x => x
|
module.exports = {
entry: './test/localforage.spec.ts',
output: {
filename: 'testbundle.js',
path: require('path').resolve(__dirname, 'dist'),
},
resolve: {
// Add '.ts' and '.tsx' as a resolvable extension.
extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js'],
},
module: {
loaders: [
// all files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'
{ test: /\.tsx?$/, loader: 'ts-loader' },
],
},
};
|
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var React = require('react');
var HiddenInput = (function (_React$Component) {
_inherits(HiddenInput, _React$Component);
function HiddenInput(props) {
_classCallCheck(this, HiddenInput);
_get(Object.getPrototypeOf(HiddenInput.prototype), 'constructor', this).call(this, props);
this.state = {
value: this.props.value
};
}
_createClass(HiddenInput, [{
key: 'render',
value: function render() {
return React.createElement('input', { type: 'hidden',
name: this.props.name,
value: this.state.value });
}
}]);
return HiddenInput;
})(React.Component);
;
HiddenInput.defaultProps = {
name: '',
value: ''
};
module.exports = HiddenInput;
|
datab = [{},{"Attribute":{"colspan":"1","rowspan":"1","text":"Annotation Position"},"Tag":{"colspan":"1","rowspan":"1","text":"(2030,0010)"},"Valid Range":{"colspan":"1","rowspan":"1","text":"0 - Max number of annotation strings defined for Annotation Format"},"Default Value if not sent by SCU or invalid value received":{"colspan":"1","rowspan":"1","text":"Mandatory, no default."},"Response to Invalid Value":{"colspan":"1","rowspan":"1","text":"Failure (0x0106)"}},{"Attribute":{"colspan":"1","rowspan":"1","text":"Text String"},"Tag":{"colspan":"1","rowspan":"1","text":"(2030,0020)"},"Valid Range":{"colspan":"1","rowspan":"1","text":"1-64 characters"},"Default Value if not sent by SCU or invalid value received":{"colspan":"1","rowspan":"1","text":"Null string"},"Response to Invalid Value":{"colspan":"1","rowspan":"1","text":"Warning (0x116)"}}];
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var phaser_1 = require("phaser");
var Components;
(function (Components) {
var Car = (function (_super) {
__extends(Car, _super);
function Car(game, x, y, key, frame) {
var _this = _super.call(this, game, x, y, key, frame) || this;
_this.angle = _super.prototype.angle;
_this.scale = _super.prototype.scale;
return _this;
}
return Car;
}(phaser_1.Phaser.Sprite));
Components.Car = Car;
var Ball = (function (_super) {
__extends(Ball, _super);
function Ball(game, x, y, key, frame) {
return _super.call(this, game, x, y, key, frame) || this;
}
return Ball;
}(phaser_1.Phaser.Sprite));
Components.Ball = Ball;
var Cannon = (function (_super) {
__extends(Cannon, _super);
function Cannon(game, x, y, key, frame) {
var _this = _super.call(this, game, x, y, key, frame) || this;
_this.angle = _super.prototype.angle;
_this.scale = _super.prototype.scale;
_this.angle = _super.prototype.angle;
_this.scale = _super.prototype.scale;
return _this;
}
return Cannon;
}(phaser_1.Phaser.Sprite));
Components.Cannon = Cannon;
})(Components = exports.Components || (exports.Components = {}));
|
var gulp = require('gulp');
var babel = require('gulp-babel');
var nodemon = require('gulp-nodemon');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var sequence = require('run-sequence');
gulp.task('copy', function () {
return gulp.src('src/**/*.html')
.pipe(gulp.dest('dist'));
});
gulp.task('compile', function () {
return gulp.src('src/**/*.js')
.pipe(babel())
.pipe(gulp.dest('dist'));
});
gulp.task('watch', function () {
gulp.watch('src/**/*.js', ['compile', 'bundle'])
gulp.watch('src/**/*.html', ['copy']);
});
gulp.task('bundle', function () {
var b = browserify({
entries: 'src/index.js',
debug: true,
transform: ['babelify']
});
return b.bundle()
.pipe(source('build/application.js'))
.pipe(gulp.dest('dist'));
});
gulp.task('start', function () {
nodemon({
watch: 'dist',
script: 'dist/index.js',
ext: 'js',
env: { 'NODE_ENV': 'development' }
});
});
gulp.task('default', function (callback) {
sequence(['compile', 'watch', 'copy', 'bundle'], 'start', callback);
});
|
var classoi_1_1_object_transformation =
[
[ "ObjectTransformation", "classoi_1_1_object_transformation.html#a40db375776b044de3c44e5c76a239332", null ],
[ "~ObjectTransformation", "classoi_1_1_object_transformation.html#aa2c5878f1ed730bfc8e790f39b2aca9e", null ],
[ "exec", "classoi_1_1_object_transformation.html#af15414ba56b699eebd11066ebde43004", null ],
[ "exec", "classoi_1_1_object_transformation.html#a57ed540437fa8976bab4223664e322d6", null ]
];
|
var conversionObject = {
special: {
"Temperature": {
"Kelvin": {
toKelvin: function (e) {
return e;
},
toCelsius: function (e) {
return (e - 273.15);
},
toFahrenheit: function (e) {
return (e * (9 / 5) - 459.67);
},
toRankine: function (e) {
return (e * (9 / 5));
}
},
"Celsius": {
toKelvin: function (e) {
return (e + 273.15);
},
toCelsius: function (e) {
return e;
},
toFahrenheit: function (e) {
return (e * (9 / 5) + 32);
},
toRankine: function (e) {
return ((e + 273.15) * (9 / 5));
}
},
"Fahrenheit": {
toKelvin: function (e) {
return ((e + 459.67) * 5 / 9);
},
toCelsius: function (e) {
return ((e - 32) * 5 / 9);
},
toFahrenheit: function (e) {
return e;
},
toRankine: function (e) {
return (e + 459.67);
}
},
"Rankine": {
toKelvin: function (e) {
return (e * 5 / 9);
},
toCelsius: function (e) {
return ((e - 491.67) * 5 / 9);
},
toFahrenheit: function (e) {
return e;
},
toRankine: function (e) {
return (e * 9 / 5);
}
}
}
},
master: {
"Acceleration": {
"Meter/Second": "1",
"Kilometer/Second": "0.001",
"Millimeter/Second": "1000",
"Micrometer/Second": "1000000",
"Nanometer/Second": "1000000000",
"Galileo": "100",
"Mile/Second": "0.000621371",
"Mile(nautical)/Second": "0.0007150611",
"Yard/Second": "1.093613298",
"Foot/Second": "3.280839895",
"Inch/Second": "39.37007874",
"Gravity": "0.101971621",
"Knots/Second": "1.94384"
},
"Angle": {
"Degree": "1",
"Grad": "1.11111",
"Mil": "17.7778",
"Radian": Math.PI / 180,
"Revolution": "0.00277778",
"Arcminute": "60",
"Arcsecond": "3600"
},
"Area": {
"Nanometer": "1000000000000000000",
"Micrometer": "1000000000000",
"Millimeter": "1000000",
"Centimeter": "10000",
"Decimeter": "100",
"Meter": "1",
"Dekameter": "0.01",
"Hectometer": "0.0001",
"Kilometer": "0.000001",
"Are": "0.01",
"Hectare": "0.0001",
"Inch": "1550.003100006",
"Feet": "10.763910417",
"Yard": "1.195990046",
"Mile": "0.000000386",
"Angstrom": "100000000000000000000.00",
"Millimicron": "1000000000000000000.00",
"Micron": "1000000000000",
"Acre": "0.000247105",
"Barn": "1e+28",
"Light-Year": "1.1173e-32",
"Astron.-Unit": "4.46837e-23",
"Li": "1.500",
"Fen": "0.15",
"Mu": "0.0015",
"Qing": "0.0149999992"
},
"Data": {
"Bit": "1",
"Kilobit": "0.001",
"Megabit": "0.000001",
"Gigabit": "1.0e-9",
"Terabit": "1.0e-12",
"Petabit": "1.0e-15",
"Exabit": "1.0e-18",
"Zettabit": "1.0e-21",
"Yottabit": "1.0e-24",
"Byte": "0.125",
"Kilobyte": "0.00012207",
"Megabyte": "1.1920929e-7",
"Gigabyte": "1.16415322e-10",
"Terabyte": "1.13686838e-13",
"Petabyte": "1.11022302e-16",
"Exabyte": "1.08420217e-19",
"Zettabyte": "1.05879118e-22",
"Yottabyte": "1.03397577e-25"
},
"Data Transfer": {
"Bit/Second": "1048576",
"Bit/Minute": "62914560",
"Bit/Hour": "3774873600",
"Byte/Second": "131072",
"Byte/Minute": "7864320",
"Byte/Hour": "471859200",
"Kilobit/Second": "1024",
"Kilobit/Minute": "61440",
"Kilobit/Hour": "3686400",
"Kilobyte/Second": "128",
"Kilobyte/Minute": "768",
"Kilobyte/Hour": "460800",
"Megabit/Second": "1",
"Megabit/Minute": "60",
"Megabit/Hour": "3600",
"Megabyte/Second": "0.125",
"Megabyte/Minute": "7.5",
"Megabyte/Hour": "450",
"Gigabit/Second": "0.000976563",
"Gigabit/Minute": "0.05859378",
"Gigabit/Hour": "3.5156268",
"Gigabyte/Second": "0.00012207",
"Gigabyte/Minute": "7.3242e-3",
"Gigabyte/Hour": "0.439452",
"Terabit/Second": "0.000000954",
"Terabit/Minute": "5.724e-5",
"Terabit/Hour": "3.4344e-3",
"Terabyte/Second": "0.000000119",
"Terabyte/Minute": "7.14e-6",
"Terabyte/Hour": "4.284e-4",
"Ethernet": "0.1048576",
"Ethernet(fast)": "0.01048576",
"Ethernet(Gigabit)": "0.001048576",
"ISDN(single)": "16.384",
"ISDN(dual)": "8.192",
"Modem(110)": "9532.509090909",
"Modem(300)": "3495.253333333",
"Modem(1200)": "873.8133333333",
"Modem(2400)": "436.9066666667",
"Modem(9600)": "109.2266666667",
"Modem(14.4k)": "72.8177777778",
"Modem(28.8k)": "36.4088888889",
"Modem(33.6k)": "31.207619048",
"Modem(56k)": "18.724571429",
"USB": "0.0873813333",
"Firewire(IEEE-1394)": "0.00262144"
},
"Density": {
"Kilogramm/Liter": "0.001",
"Gramm/Liter": "1",
"Milligramm/Liter": "1000",
"Microgramm/Liter": "1000000",
"Nanogramm/Liter": "1000000000",
"Kilogramm/Meter": "1",
"Gramm/Meter": "1000",
"Kilogramm/Centimeter": "0.000001",
"Gramm/Centimeter": "0.001",
"Gramm/Millimeter": "0.000001",
"Pound/Inch": "0.00003613",
"Pound/Foot": "0.06242796",
"Ounze/Inch": "0.00057804",
"Ounze/Foot": "0.99884737"
},
"Distance/Length": {
"Nanometer": "1e+09",
"Micrometer": "1e+06",
"Millimeter": "1000",
"Centimeter": "100",
"Decimeter": "10",
"Meter": "1.000",
"Kilometer": "0.001",
"Picometer": "1e+12",
"Femtometer": "1e+15",
"Attommeter": "1e+18",
"Zeptometer": "1e+21",
"Yoctometer": "1e+24",
"Inch": "39.3701",
"Feet": "3.28084",
"Yard": "1.09361",
"Mile": "0.000621371",
"Mile(nautical)": "0.000539957",
"Light-Year": "1.057e-16",
"Light-Day": "3.860e-14",
"Light-Min": "5.5594e-11",
"Light-Sec": "3.33564e-9",
"Astron. Unit": "6.68459e-12",
"Parsec": "3.24078e-17",
"Chain": "0.0497097",
"Furlong": "0.00497097",
"Point": "2834.64",
"Cun": "30",
"Chi": "3",
"Li": "3000",
"Gongli": "6000"
},
"Electrical Charge": {
"Coulomb": "1",
"Kilocoulomb": "1e-3",
"Megacoulomb": "1e-6",
"Abcoulomb": "0.1",
"Nanocoulomb": "1000000000",
"Microcoulomb": "1000000",
"Millicoulomb": "1000",
"Milliampere Hour": "0.277778",
"Ampere Hour": "0.00028",
"Faraday": "0.00001",
"Statcoulomb": "2997924580",
"Elementary Charge": "6.24151e+18"
},
"Energy & Work": {
"Joule": "1",
"Kilojoule": "0.001",
"Megajoule": "0.000001",
"Millijoule": "1000",
"Kilowatt Hour": "0.000000278",
"Kilowatt Second": "0.001",
"Watt Hour": "0.000277778",
"Watt Second": "1",
"Newton Meter": "1",
"Horsepower Hour": "0.00000037",
"Kilocalorie(int.)": "0.000238846",
"Kilocalorie(therm.)": "0.000239006",
"Calorie(int.)": "0.238845897",
"Calorie(therm.)": "0.239005736",
"Calorie(Nutrition)": "0.238845897",
"Kilocalorie(Nutrition)": "0.000238846",
"Hartree Energy": "2.293710449e+17",
"Rydberg": "4.587420897e+17",
"British Thermal Unit": "0.00094782",
"Erg": "10000000",
"Electron Volt": "6.24151154e+18",
"Foot Pound": "0.73756215"
},
"Flow Rate": {
"Meter/Second": "1",
"Meter/Minute": "60",
"Meter/Hour": "3600",
"Kilometer/Second": "1e-9",
"Kilometer/Minute": "6e-8",
"Kilometer/Hour": "0.000004",
"Decimeter/Second": "1000",
"Decimeter/Minute": "60000",
"Decimeter/Hour": "3600000",
"Centimeter/Second": "1000000",
"Centimeter/Minute": "60000000",
"Centimeter/Hour": "3600000000",
"Millimeter/Second": "1000000000",
"Millimeter/Minute": "60000000000",
"Millimeter/Hour": "3.6e+12",
"Foot/Second": "35.314667",
"Foot/Minute": "2118.880003",
"Foot/Hour": "1.271328e+5",
"Liter/Second": "1000",
"Liter/Minute": "60000",
"Liter/Hour": "3600000",
"Gallon(US)/Second": "264.172052",
"Gallon(US)/Minute": "15850.323141",
"Gallon(US)/Hour": "9.510194e+5",
"Gallon(Imperial)/Second": "219.969248",
"Gallon(Imperial)/Minute": "13198.154898",
"Gallon(Imperial)/Hour": "7.918893e+5",
"Morgen-Foot/Second": "0.000811",
"Morgen-Foot/Minute": "0.048643",
"Morgen-Foot/Hour": "2.918567",
"Scheffel(US)/Second": "28.377593",
"Scheffel(US)/Minute": "1702.655596",
"Scheffel(US)/Hour": "102159.33573",
"Scheffel(UK)/Second": "27.496156",
"Scheffel(UK)/Minute": "1649.769362",
"Scheffel(UK)/Hour": "98986.161735",
"Barrel(Oil)/Second": "6.289810771",
"Barrel(Oil)/Minute": "377.38864623",
"Barrel(Oil)/Hour": "22643.31877354"
},
"Force": {
"Newton": "1",
"Kilonewton": "0.001",
"Millinewton": "1000",
"Dyne": "100000",
"Joule/Meter": "1",
"Pond": "101.971621298",
"Kilopond": "0.101971621298"
},
"Fuel Consumption": {
"Miles/Liter": "1",
"Kilometer/Liter": "1.60934",
"Miles/Gallon(US)": "3.78517704",
"Miles/Gallon(UK)": "4.5463968",
"Kilometer/Gallon(US)": "6.09165188",
"Kilometer/Gallon(UK)": "7.31671632"
},
"Luminance": {
"Candela/Meter": "1",
"Kilocandela/Meter": "0.001",
"Candela/Centimeter": "0.0001",
"Candela/Foot": "0.09",
"Foot Lambert": "0.29",
"Lambert": "3.14e-4",
"Nit": "1",
"Stilb": "0.0001"
},
"Mass/Weight": {
"Microgramm": "1000000",
"Milligramm": "1000",
"Gramm": "1",
"Kilogramm": "0.001",
"Ton(US)": "1.10231131e-6",
"Ton(UK)": "9.84206528e-7",
"Ounce": "3.5273962e-2",
"Pound": "2.20462262e-3",
"Pound(metric)": "2e-3",
"Stone": "0.000157473",
"Carat": "5",
"Grain": "15.43236"
},
"Power": {
"Watt": "1",
"Milliwatt": "1000",
"Kilowatt": "0.001",
"Megawatt": "0.000001",
"Joule/Second": "1",
"Kilojoule/Second": "0.001",
"Horsepower": "0.001341",
"Horsepower(metric)": "0.0013596",
"Horsepower(Boiler)": "0.000102",
"Decibel Milliwatt": "30",
"Calories/Second": "0.238846",
"Calories/Hour": "859.8456",
"Kilocalories/Second": "0.000238846",
"Kilocalories/Hour": "0.8598456",
"Foot-Pound/Second": "0.737562",
"Foot-Pound/Hour": "2655.22",
"Newton Meter/Second": "1",
"Newton Meter/Hour": "3600",
"BTU/Second": "0.000947817",
"BTU/Minute": "0.056869",
"BTU/Hour": "3.41214"
},
"Pressure": {
"Pascal": "1.0",
"Kilopascal": "0.001",
"Hectopascal": "0.01",
"Millipascal": "1000",
"Newton/Meter": "1",
"Bar": "0.00001",
"Millibar": "0.01",
"Kip/Inch": "0.000000145",
"Pounds/Inch": "0.000145038",
"Torr": "0.007500617",
"Millimeter Mercury": "0.00750062",
"Inches Mercury": "0.000295301"
},
"Radioactivity": {
"Curie": "1",
"Kilocurie": "0.001",
"Millicurie": "1000",
"Microcurie": "1000000",
"Nanocurie": "1000000000",
"Picocurie": "1e+12",
"Becquerel": "3.7e+10",
"Terabecquerel": "0.037",
"Gigabecquerel": "37",
"Megabecquerel": "37000",
"Kilobecquerel": "37000000",
"Milliecquerel": "3.7e+13",
"Rutherford": "37000",
"1/Second": "3.7e+10",
"Disintegrations/Second": "3.7e+10",
"Disintegrations/Minute": "2.22e+12"
},
"Speed": {
"Meter/Second": "4.4704e-1",
"Meter/Hour": "1.609344e+3",
"Kilometer/Hour": "1.609344",
"Foot/Hour": "5.28e+3",
"Yard/Hour": "1.76e+3",
"Miles/Hour": "1",
"Knots": "8.68976242e-1",
"Mach(SI Standard)": "1.51515152e-3",
"Speed of Light": "1.49116493e-9"
},
"Temperature": {
"Celsius": "1",
"Kelvin": "1",
"Fahrenheit": "1",
"Rankine": "1"
},
"Time": {
"Millisecond": "604800000",
"Microsecond": "604800000000",
"Nanosecond": "604800000000000",
"Second": "604800",
"Minute": "10080",
"Hour": "168",
"Day": "7",
"Week": "1",
"Month(31)": "0.22580645",
"Month(30)": "0.2333333333",
"Month(29)": "0.24137931",
"Month(28)": "0.25",
"Year": "0.019165"
},
"Torque": {
"Newton Meter": "1",
"Newton Centimeter": "100",
"Newton Millimeter": "1000",
"Kilonewton Meter": "0.001",
"Meganewton Meter": "0.000001",
"Micronewton Meter": "1000000",
"Millinewton Meter": "1000",
"Pound-Force Foot": "0.73756",
"Pound-Force Inch": "8.85075",
"Ounce-Force Foot": "11.80097",
"Ounce-Force Inch": "141.61165",
"Kilogramm-Force Meter": "0.10197",
"Gramm-Force Centimeter": "10197.2",
"Dyne Meter": "100000",
"Dyne Centimeter": "10000000",
"Dyne Millimeter": "100000000"
},
"Volume": {
"Barrel(Oil)": "6.28981",
"Foot": "35.31466621",
"Inch": "61023.74409473",
"Yard": "1.30796773",
"Millimeter": "1000000000",
"Centimeter": "1000000",
"Meter": "1",
"Fluid Ounze(US)": "33814.02220161",
"Gallon(US)": "264.17205124",
"Liter": "1000",
"Milliliter": "1e+6",
"Centiliter": "100000",
"Deciliter": "10000",
"Hectoliter": "10",
"Pint(UK)": "1759.75",
"Pint(US)": "2113.38",
"Tablespoon(US)": "67613.3",
"Tablespoon(UK)": "66666.7",
"Teaspoon(US)": "202840",
"Teaspoon(UK)": "200000",
"Cup(US)": "4226.72",
"Cup(UK)": "3519.89"
}
},
functions: {
converter: function (context, from, to, subject) {
context = context.toUpperCase().substring(0, 1) + context.substring(1);
to = to.toUpperCase().substring(0, 1) + to.substring(1);
from = from.toUpperCase().substring(0, 1) + from.substring(1);
subject = parseInt(subject);
var specialTest = false;
for (var i in conversionObject.special) {
if (i == context) {
specialTest = i;
}
}
if (specialTest !== false) {
if (typeof conversionObject.special[specialTest][from] !== "undefined") {
return conversionObject.special[specialTest][from]["to" + to](subject);
}
return false;
}
return conversionObject.master[context][to] / conversionObject.master[context][from] * subject;
}
}
}
|
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
moduleType: 'locale',
name: 'fr-CH',
dictionary: {},
format: {
days: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
shortDays: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
months: [
'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin',
'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'
],
shortMonths: [
'Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Jun',
'Jul', 'Aoû', 'Sep', 'Oct', 'Nov', 'Déc'
],
date: '%d.%m.%Y'
}
};
|
/* eslint-env browser */
import Decorator from '../decorator';
import ContentAssist from '../../components/content-assist/content-assist';
import React from 'react'; // eslint-disable-line
import PropTypes from 'prop-types';
class CursorDecorator extends Decorator {
componentWillReceiveProps (nextProps) {
this.setState({
popupVisible: nextProps.suggestions.length > 0,
popup: <ContentAssist suggestions={nextProps.suggestions} />
});
}
};
CursorDecorator.breakable = false;
CursorDecorator.propType = {
suggestions: PropTypes.array
};
CursorDecorator.defaultProps = {
className: 'cursor',
suggestions: []
};
export default CursorDecorator;
|
// Comby - yet another parser combinator library for JavaScript
// For more info see README.md or Wikipedia: https://en.wikipedia.org/wiki/Parser_combinator
// Copyright (c) 2016 Crystalline Emerald
// Licensed under MIT license.
var C = require('./comby.js');
var util = require('./util.js');
var pr = console.log;
var $ = C.$;
var SEQ = C.SEQ;
var ALT = C.ALT;
var REP = C.REP;
var LIST = C.LIST;
var FIND = C.FIND;
var T = C.T;
var OPT = C.OPT;
var OPTREM = C.OPTREM;
var END = C.END;
var tokenizer = C.tokenizer;
var wrap = C.wrap;
var isDigit = C.isDigit;
var isNumber = C.isNumber;
var isWhitespace = C.isWhitespace;
var isAlpha = C.isAlpha;
var isAlphaNum = C.isAlphaNum;
var pState = C.pState;
function runTests(tests, opt) {
opt = opt || {};
pr('RUNNING TESTS'+(opt.name ? ': '+opt.name : ''));
var t = Date.now();
var failed = [];
tests.map(function (test, i) {
var input = (opt.prepInput && opt.prepInput(test[0])) || test[0];
var _ret = test[1](input);
var ret = _ret;
if (opt.procResult) ret = opt.procResult(_ret);
var compareTo = (opt.prepCompare && opt.prepCompare(test[2])) || test[2];
var compare = opt.compare || ((a,b) => (a === b)||(isNaN(a)&&isNaN(b)));
if (compare(ret, compareTo)) {
if (!opt.concise) pr('TEST',i,'PASSED');
} else {
var fhret;
if (opt.onFail) {
fhret = opt.onFail(test[0], test[1], test[2]);
}
pr('TEST',i,'FAILED EXPECT:',compareTo,'GOT:',ret,(fhret ? ('|' + fhret) : ''));
failed.push(i);
}
});
var tStr = '@ TIME: '+util.timeDiff(t, 3);
if (failed.length) {
pr('SOME TESTS FAILED:', failed, tStr);
} else {
pr('ALL '+tests.length+' TESTS PASSED', tStr);
}
return failed;
}
// Basic tests of simplest parsers
var pCombTests = [
['1', $('1'), true],
['12', SEQ('1', '2'), true],
['13', SEQ('1', '2'), false],
['12', SEQ('1', '2', END), true],
['123', SEQ('1', '2', END), false],
['12212121221', SEQ(REP(ALT('1', '2')), END), true],
['12212321221', SEQ(REP(ALT('1', '2')), END), false],
['1', SEQ('1', OPT('2'), END), true],
['1', $(isDigit), true],
['1+5', SEQ($(isDigit), '+', $(isDigit)), true],
['1', ALT($(isDigit), SEQ($(isDigit), '+', $(isDigit))), true],
['+5', REP( '+', '5' ), true],
['+5', REP( '+', $(isDigit) ), true],
['+5+1', REP( '+', $(isDigit) ), true],
['1+5',
ALT( SEQ( $(isDigit), REP('+', $(isDigit))),
$(isDigit)
),
true],
['1+5+123+54+123',
ALT( SEQ( REP($(isDigit)), REP('+', REP($(isDigit)))),
REP($(isDigit))
),
true],
['1,2', LIST($(isDigit), ','), true],
['1', LIST($(isDigit), ','), true],
['(1,2)', SEQ('(', LIST($(isDigit), ','), ')'), true],
['()', SEQ('(', LIST($(isDigit), ','), ')'), false],
['()', SEQ('(', LIST($(isDigit), ',', true), ')'), true],
['(1)', SEQ('(', LIST($(isDigit), ','), ')'), true]
]
function runExampleTests() {
var p0 = C.$("hello");
var p1 = C.SEQ("hel", "lo");
var p2 = C.SEQ("h","e","l","l","o");
var p3 = C.SEQ("h","e",SEQ("l","l"),"o");
var wp2 = C.wrap(p2);
var p4 = C.SEQ(C.ALT("H","h"), "ello"); var wp4 = C.wrap(p4);
var p5 = T(p4, function (arr) { return arr.join('') }); var wp5 = C.wrap(p5);
var fail = false;
var tests = [[wp2("helo"), undefined],
[wp2("hello"), [ 'h', 'e', 'l', 'l', 'o' ]],
[wp4("Hello"), [ 'H', 'ello' ]],
[wp5("Hello"), [ 'Hello' ]],
[wp5("hello"), [ 'hello' ]]].forEach((elem, i) => { if (JSON.stringify(elem[0]) !== JSON.stringify(elem[1])) { pr('FAILED:', i); fail = true } });
if (fail) { pr('EXAMPLE TESTS FAILED') }
else { pr('EXAMPLE TESTS PASSED') }
}
// Arithmetic expression parser/evaluator test
// Tests and test generator
function prepArithTests(tests) {
return tests.map(x => [x[0], arithSolve, x[1]]);
}
var basicArithTests = [
['10', 10],
['-10', -10],
['-(10)', -10],
['10+35', 45],
['10+2*35', 80],
['(10+2)*35', 420],
['97-24*2-84', -35]
];
function _genRandArithExprs(N, enParens, enFns, enVar) {
var ops = '+-*/';
var unOps = '-';
var unP = 0.1;
var parenP = 0.1;
var varP = 0.2;
var out = [];
var fns1 = 'sin cos log sqrt'.split(' ').map(name => {global[name] = Math[name]; return name});
var fn1p = 0.3;
for (var i=0; i<N; i++) {
var expr = '';
var num = false;
var pN = util.randInt(1,N);
for (var j=0; j<pN; j++) {
if (num) {
expr += util.randItem(ops);
} else {
if (Math.random() < unP) {
var unop = util.randItem(unOps);
if (expr.length && expr[expr.length-1] !== unop) {
expr += unop;
}
}
if (enParens && Math.random() < parenP) {
expr += '('+util.randItem(_genRandArithExprs(4))+')';
} else if (enFns && Math.random() < fn1p) {
if (!enVar || Math.random() < 0.5)
expr += util.randItem(fns1)+'('+util.randItem(_genRandArithExprs(6))+')';
else
expr += util.randItem(fns1)+'('+enVar+'*'+util.randItem(_genRandArithExprs(6))+')';
} else if (enVar && Math.random() < varP) {
expr += enVar;
} else {
expr += util.randInt();
}
}
num = !num;
}
if (!num) {
expr += util.randInt();
}
out.push(expr);
}
return out;
}
function genRandArithTests(N, enParens, enFns) {
return _genRandArithExprs(N, enParens, enFns).map(expr => [expr, eval(expr)]);
}
var simpleArithTests = [].concat(basicArithTests, genRandArithTests(100));
var advancedArithTests = [].concat(basicArithTests, genRandArithTests(100, true, true));
function prepArithTests(tests, solver) {
return tests.map(x => [x[0], solver, x[1]]);
}
var deriveTests = ['1+x+1+sin(cos(log(sqrt(2*x+40)+30)*7))'].concat(_genRandArithExprs(50, true, true, 'x'));
function prepDeriveTests(tests) {
return tests.filter(expr => !isNaN(advancedSolver_T(expr, {x:10}))).map(x => [x, function (expr) {
var x = Math.random()*10.0+2;
var num = numericDerive(expr, 'x', x);
var sym = symbolicDerive(expr, 'x', x);
var deNom = 0.5*(Math.abs(num)+Math.abs(sym));
if (deNom === 0) deNom = 1;
var diff = Math.abs(num - sym)/deNom;
if (isNaN(num)) { pr('Ignoring NaN in Derive test'); return 0 }
if (isNaN(diff) || diff > 0.1) {
pr('EXPR:',expr,'NUM:',num,'SYM:',sym,'deNom:',deNom);
}
return diff;
}, true]);
}
function prepSimplifyTests(tests) {
return tests.filter(expr => !isNaN(advancedSolver_T(expr, {x:10}))).map(x => [x, function (expr) {
var val = Math.random()*10.0+2;
var ret = advancedSolver_T(expr, {x:val});
if (isNaN(ret)) { pr('Ignoring NaN in Simplify test'); return 0 }
var sret = advancedSolver_T(simplify(calcParser(expr)), {x:val});
return Math.abs(sret - ret);
}, true]);
}
//pr(SEQ('(',LIST($(isDigit),','),')')(new pState('(1,2,3)',0)));
//return;
var listTests = [
['', wrap(LIST($(isDigit),',')), undefined],
['', wrap(LIST($(isDigit),',', true)), []],
['1', wrap(LIST($(isDigit),',')), [ '1' ]],
['1,', wrap(LIST($(isDigit),',')), undefined],
['1,2', wrap(LIST($(isDigit),',')), [ '1', '2' ]],
['1,2,3', wrap(LIST($(isDigit),',')), [ '1', '2', '3' ]],
['(1,2,3)', wrap(SEQ('(', LIST($(isDigit),','), ')')), [ '(', '1', '2', '3', ')' ]],
['1,2,3', wrap(LIST($(isDigit),',')), [ '1', '2', '3' ]],
];
findTests = [
['', wrap(FIND(LIST($(isDigit),','))), undefined],
['1,2', wrap(FIND(LIST($(isDigit),','))), [ '1', '2' ]],
['1,2 a,g', wrap(FIND(LIST($(isDigit),','))), [ '1', '2' ]]
]
var simplecalc = require('./example_simplecalc.js');
var engcalc = require('./example_engcalc.js');
var derivecalc = require('./example_derive.js');
var numericDerive = derivecalc.numericDerive;
var symbolicDerive = derivecalc.symbolicDerive;
var simplify = derivecalc.simplify;
var calcParser = derivecalc.calcParser;
// Tests of simple|advanced, tokenized|untokenized calculators and symbolic differentiator
// _T means "tokenized version", it uses tokenizer and thus supports whitespace
var simpleSolver = simplecalc._calc;
runTests(listTests, {name: 'LIST', compare: (a,b) => JSON.stringify(a) === JSON.stringify(b), concise: true});
runTests(findTests, {name: 'FIND', compare: (a,b) => JSON.stringify(a) === JSON.stringify(b), concise: true});
runTests(pCombTests, {
name: 'SHORT',
prepInput: x => new pState(x, 0),
compare: function (a,b) {
if (b === true || b === false) {
return (a && (a.s.length === a.i)) === b;
} else {
return a && (a.s.length === a.i) && a === b;
}
},
onFail: (_0, _1, _2) => _0,
concise: true
});
runExampleTests();
runTests(prepArithTests(simpleArithTests, simpleSolver), {
name: 'SIMPLE CALCULATOR (NO TOKENIZER)',
concise: true
});
var simpleSolver_T = simplecalc._calc_T;
runTests(prepArithTests(simpleArithTests, simpleSolver_T), {
name: 'SIMPLE CALCULATOR (USE TOKENIZER)',
concise: true
});
var advancedSolver = engcalc._calc;
var eng_computeTree = engcalc.computeTree;
runTests(prepArithTests(advancedArithTests, advancedSolver), {
name: 'ADVANCED CALCULATOR (NO TOKENIZER)',
concise: true
});
var advancedSolver_T = engcalc._calc_T;
runTests(prepArithTests(advancedArithTests, advancedSolver_T), {
name: 'ADVANCED CALCULATOR (USE TOKENIZER)',
concise: true
});
runTests(prepSimplifyTests(deriveTests), {
name: 'SYMBOLIC SIMPLIFICATION',
concise: true,
compare: (diff) => (diff < 0.01)
});
runTests(prepDeriveTests(deriveTests), {
name: 'SYMBOLIC DERIVATIVE',
concise: true,
compare: (diff) => (diff < 0.01)
});
|
'use strict';
const valueParser = require('postcss-value-parser');
const declarationValueIndex = require('../../utils/declarationValueIndex');
const getDeclarationValue = require('../../utils/getDeclarationValue');
const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const setDeclarationValue = require('../../utils/setDeclarationValue');
const validateOptions = require('../../utils/validateOptions');
const ruleName = 'color-hex-case';
const messages = ruleMessages(ruleName, {
expected: (actual, expected) => `Expected "${actual}" to be "${expected}"`,
});
const meta = {
url: 'https://stylelint.io/user-guide/rules/list/color-hex-case',
};
const HEX = /^#[0-9A-Za-z]+/;
const IGNORED_FUNCTIONS = new Set(['url']);
/** @type {import('stylelint').Rule} */
const rule = (primary, _secondaryOptions, context) => {
return (root, result) => {
const validOptions = validateOptions(result, ruleName, {
actual: primary,
possible: ['lower', 'upper'],
});
if (!validOptions) {
return;
}
root.walkDecls((decl) => {
const parsedValue = valueParser(getDeclarationValue(decl));
let needsFix = false;
parsedValue.walk((node) => {
const { value } = node;
if (isIgnoredFunction(node)) return false;
if (!isHexColor(node)) return;
const expected = primary === 'lower' ? value.toLowerCase() : value.toUpperCase();
if (value === expected) return;
if (context.fix) {
node.value = expected;
needsFix = true;
return;
}
report({
message: messages.expected(value, expected),
node: decl,
index: declarationValueIndex(decl) + node.sourceIndex,
result,
ruleName,
});
});
if (needsFix) {
setDeclarationValue(decl, parsedValue.toString());
}
});
};
};
/**
* @param {import('postcss-value-parser').Node} node
*/
function isIgnoredFunction({ type, value }) {
return type === 'function' && IGNORED_FUNCTIONS.has(value.toLowerCase());
}
/**
* @param {import('postcss-value-parser').Node} node
*/
function isHexColor({ type, value }) {
return type === 'word' && HEX.test(value);
}
rule.ruleName = ruleName;
rule.messages = messages;
rule.meta = meta;
module.exports = rule;
|
import React from 'react';
import PropTypes from 'prop-types';
import { mount, shallow } from 'enzyme';
import {
Avatar,
BaseAvatar,
EntityAvatar,
UserAvatar,
getInitials,
} from '../Avatar';
import { Icon } from '../../Icon';
describe('getInitials()', () => {
it('returns an empty string when passed an empty string or a non-string argument', () => {
expect(getInitials({})).toEqual('');
expect(getInitials(null)).toEqual('');
expect(getInitials('')).toEqual('');
});
it('returns an empty string when passed a string without words', () => {
expect(getInitials(', ? !')).toEqual('');
});
it('returns uppercased initials when two words or more are passed', () => {
expect(getInitials('John Doe')).toEqual('JD');
expect(getInitials('JohnDoe')).toEqual('JD');
expect(getInitials('John Doe Jr.')).toEqual('JD');
});
it('returns titleCased initials when one word is passed', () => {
expect(getInitials('John')).toEqual('Jo');
});
});
describe('<BaseAvatar />', () => {
const sampleChild = <p>Sample</p>;
const getComponent = (props = {}) => shallow(
<BaseAvatar {...props} renderFallback={() => sampleChild} />
);
it('renders an image if present', () => {
const mounted = getComponent({ image: sampleChild });
expect(mounted.find('.slds-avatar').contains(sampleChild)).toBeTruthy();
});
it('renders a fallback if not', () => {
const mounted = getComponent();
expect(mounted.find('.slds-avatar').contains(sampleChild)).toBeTruthy();
});
it('renders different size variants', () => {
const mounted = getComponent({ size: 'large' });
expect(mounted.find('.slds-avatar').hasClass('slds-avatar_large')).toBeTruthy();
});
it('renders a rounded variant', () => {
const mounted = getComponent({ round: true });
expect(mounted.find('.slds-avatar').hasClass('slds-avatar_circle')).toBeTruthy();
});
it('applies rest props and classnames to span', () => {
const mounted = getComponent({ className: 'foo', 'aria-hidden': true });
const avatar = mounted.find('.slds-avatar');
expect(avatar.hasClass('foo')).toBeTruthy();
expect(avatar.prop('aria-hidden')).toBeTruthy();
});
});
describe('<EntityAvatar />', () => {
const getComponent = (props = {}) => mount(
<EntityAvatar
name="Account"
icon={{ icon: 'account', sprite: 'standard' }}
{...props}
/>
);
it('renders an icon by default', () => {
const mounted = getComponent();
expect(mounted.find(Icon).prop('icon')).toEqual('account');
});
it('renders initials', () => {
const mounted = getComponent({ displayType: 'initials' });
expect(mounted.find('abbr').hasClass('slds-avatar__initials')).toBeTruthy();
});
it('passes props to BaseAvatar', () => {
const mounted = getComponent({ className: 'foo', round: true });
const baseAvatar = mounted.find(BaseAvatar);
expect(baseAvatar.prop('image')).toBeNull();
expect(baseAvatar.prop('className')).toEqual('foo');
expect(baseAvatar.prop('round')).toBeTruthy();
});
});
describe('<UserAvatar />', () => {
const getComponent = (props = {}) => mount(
<UserAvatar name="John Doe" {...props} />
);
it('renders an image when imageSrc is set', () => {
const mounted = getComponent({ imageSrc: 'foo' });
expect(mounted.find('img').exists()).toBeTruthy();
});
it('renders css image fallbacks', () => {
const expectClass = (cmp, className) => {
const avatar = cmp.find('.slds-avatar');
expect(avatar.hasClass(className)).toBeTruthy();
};
const mounted = getComponent({ fallbackType: 'profile-image' });
expect(mounted.find('.slds-avatar').prop('title')).toEqual('John Doe');
expectClass(mounted, 'slds-avatar_profile-image-large');
mounted.setProps({ fallbackType: 'group-image' });
expectClass(mounted, 'slds-avatar_group-image-large');
});
it('renders an icon fallback', () => {
const mounted = getComponent({ fallbackType: 'icon', round: false });
expect(mounted.find(BaseAvatar).prop('round')).toBeTruthy();
const icon = mounted.find(Icon);
expect(icon.prop('icon')).toEqual('user');
expect(icon.prop('title')).toEqual('John Doe');
});
it('renders initials fallbacks', () => {
const expectClass = (cmp, className) => {
expect(cmp.find('.slds-avatar__initials').hasClass(className)).toBeTruthy();
};
const mounted = getComponent({ fallbackType: 'initials', round: false });
expect(mounted.find(BaseAvatar).prop('round')).toBeTruthy();
expectClass(mounted, 'slds-icon-standard-user');
mounted.setProps({ fallbackType: 'initials-inverse' });
expectClass(mounted, 'slds-avatar__initials_inverse');
});
it('allows to set title, falls back to name', () => {
const expectTitle = (cmp, title) => {
expect(cmp.find('img').prop('title')).toEqual(title);
};
const mounted = getComponent({ imageSrc: 'foo' });
expectTitle(mounted, 'John Doe');
mounted.setProps({ title: 'foo' });
expectTitle(mounted, 'foo');
});
it('passes props to BaseAvatar', () => {});
});
describe('<Avatar />', () => {
let mounted = null;
let props = {};
const context = { assetBasePath: '/' };
const childContextTypes = { assetBasePath: PropTypes.string };
const options = { context, childContextTypes };
beforeEach(() => {
props = {
src: 'foo',
alt: 'bar',
title: 'myTitle'
};
mounted = shallow(<Avatar {...props} />, options);
});
it('renders the correct markup', () => {
expect(mounted.find('.slds-avatar').length).toBe(1);
expect(mounted.find('img').length).toBe(1);
});
it('renders different sizes', () => {
mounted.setProps({ size: 'large' });
expect(mounted.find('.slds-avatar').first().hasClass('slds-avatar_large')).toBeTruthy();
});
it('renders a src', () => {
expect(mounted.find('img').first().props().src).toBe(props.src);
});
it('renders an alt', () => {
expect(mounted.find('img').first().props().alt).toBe(props.alt);
});
it('renders a title', () => {
expect(mounted.find('img').first().props().title).toBe(props.title);
});
it('renders an empty avatar', () => {
mounted.setProps({ src: undefined, alt: undefined });
expect(mounted.find('img').length).toBe(0);
expect(mounted.find('.slds-avatar').hasClass('slds-avatar_empty')).toBeTruthy();
});
it('applies className and rest-properties', () => {
mounted.setProps({ className: 'foo', 'data-test': 'bar' });
expect(mounted.find('.slds-avatar').hasClass('foo')).toBeTruthy();
expect(mounted.find('.slds-avatar').prop('data-test')).toEqual('bar');
});
});
|
var express = require('express')
, midware = require('./lib/midware')
var app = exports.app = express();
app.configure(function(){
app.use(express.favicon());
//app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
app.all('*', midware.header);
app.options('/api/*', function(req,res){
res.send(200);
});
app.all('/api/*', midware.authentication);
//API
require('./api/user')(app);
require('./api/auth')(app);
require('./api/vehicle')(app);
app.listen(5002, '0.0.0.0');
console.log("Express server listening...");
|
import React from 'react';
import { NavLink, Switch, Route } from 'react-router-dom';
import Bip44Demo from './RichTestPage';
import BitcoinJSHowToPage from './BitcoinJSHowToPage';
import FuelSavings from './FuelSavingsPage';
const HomePage = () => {
return (
<div>
<h1>HomePage</h1>
<p>Just a sandbox for Rich</p>
<p><div className="row">
<div className="col-md-3"><b><NavLink to="/bip44-demo">BIP44 Account Generator:</NavLink></b></div>
<div className="col-md-9">Utilizes Redux Sagas with mocked async calls to generate BIP44 Bitcoin accounts and derive external addresses</div>
</div>
</p>
<p><div className="row">
<div className="col-md-3"><b><NavLink exact to="bip44-howto">BIP 44 HowTo</NavLink></b></div>
<div className="col-md-9">Just a simple code memo on BIP44</div>
</div>
</p>
<p><div className="row">
<div className="col-md-3"><b><NavLink to="fuel-savings">Fuel Savings Calculator</NavLink></b></div>
<div className="col-md-9">Cory House's original raw Redux demo</div>
</div>
</p>
<Switch>
<Route exact path="/bip44-demo" component={Bip44Demo} />
<Route exact path="/bip44-howto" component={BitcoinJSHowToPage} />
<Route exact path="/fuel-savings" component={FuelSavings} />
</Switch>
</div>
);
};
export default HomePage;
|
"use strict";
/*
* TopJs Framework (http://www.topjs.org/)
*
* @link http://github.com/qcoreteam/topjs for the canonical source repository
* @copyright Copyright (c) 2016-2017 QCoreTeam (http://www.qcoreteam.org)
* @license http://www.topjs.org/license/new-bsd New BSD License
*/
TopJs.namespace("TopJs.stdlib");
/**
* @alias TopJs.stdlib.Heap
* @author https://github.com/vovazolotoy/TypeScript-STL
*/
class Heap {
constructor(type)
{
/**
* Binary tree storage array
*
* @property {Array} tree
* @private
*/
this.tree = [];
if (type != Heap.MAX && type != Heap.MIN) {
type = Heap.MAX;
}
this.type = type;
}
/**
* Get index of left child element in binary tree stored in array
*
* @param {Number} n
* @return {Number}
* @private
*/
child(n)
{
return 2 * n + 1;
}
/**
* Get index of parent element in binary tree stored in array
*
* @param {Number} n
* @return {Number}
* @private
*/
parent(n)
{
return Math.floor((n - 1) / 2);
}
/**
* Swap 2 elements in binary tree
*
* @param {Number} left
* @param {Number} right
* @private
*/
swap(left, right)
{
let swap = this.tree[left];
this.tree[left] = this.tree[right];
this.tree[right] = swap;
}
/**
* Sift elements in binary tree
*
* @param {Number} i
* @private
*/
siftUp(i)
{
while (i > 0) {
let parent = this.parent(i);
if (this.compare(this.tree[i], this.tree[parent]) * this.type > 0) {
this.swap(i, parent);
i = parent;
} else {
break;
}
}
}
/**
* Sift down elements in binary tree
*
* @param {Number} i
* @private
*/
siftDown(i)
{
while (i < this.tree.length) {
let left = this.child(i);
let right = left + 1;
if ((left < this.tree.length) && (right < this.tree.length) &&
(this.compare(this.tree[i], this.tree[left]) * this.type < 0 ||
this.compare(this.tree[i], this.tree[right]) * this.type < 0)) {
// there is 2 children and one of them must be swapped
// get correct element to sift down
let sift = left;
if (this.compare(this.tree[left], this.tree[right]) * this.type < 0) {
sift = right;
}
this.swap(i, sift);
i = sift;
} else if (left < this.tree.length &&
this.compare(this.tree[i], this.tree[left]) * this.type < 0) {
// only one child exists
this.swap(i, left);
i = left;
} else {
break;
}
}
}
/**
* Extracts a node from top of the heap and sift up
*
* @return any The value of the extracted node.
*/
extract()
{
if (this.tree.length === 0) {
TopJs.raise("Can't extract from an empty data structure");
}
let extracted = this.tree[0];
if (this.tree.length === 1) {
this.tree = [];
} else {
this.tree[0] = this.tree.pop();
this.siftDown(0);
}
return extracted;
}
/**
* Inserts an element in the heap by sifting it up
*
* @param {Object} value The value to insert.
* @return {void}
*/
insert(value)
{
this.tree.push(value);
this.siftUp(this.tree.length - 1);
}
/**
* Peeks at the node from the top of the heap
*
* @return any The value of the node on the top.
*/
top()
{
if (this.tree.length === 0) {
TopJs.raise("Can't peek at an empty heap");
}
return this.tree[0];
}
/**
* Counts the number of elements in the heap
*
* @return {Number} the number of elements in the heap.
*/
count()
{
return this.tree.length;
}
/**
* return true is heap is empty
*
* @return {Boolean}
*/
empty()
{
return (this.tree.length === 0);
}
/**
* Compare elements in order to place them correctly in the heap while sifting up.
*
* @param {Number} left The value of the first node being compared.
* @param {Number} right The value of the second node being compared.
* @return number Result of the comparison, positive integer if first is greater than second, 0 if they are equal, negative integer otherwise.
* Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.
*/
compare(left, right)
{
if (left > right) {
return 1;
} else if (left == right) {
return 0;
} else {
return -1;
}
}
/**
* Visually display heap tree
*
* @param {Object} node
* @param prefix
* @param last
* @return String
* @private
*/
displayNode(node, prefix, last)
{
if (prefix === void 0) {
prefix = '';
}
if (last === void 0) {
last = true;
}
let line = prefix;
// get child indexes
let left = this.child(node);
let right = left + 1;
if (last) {
line += (prefix ? '└─' : ' ');
} else {
line += '├─';
}
line += this.tree[node];
prefix += (last ? ' ' : '│ ');
if (left < this.tree.length) {
line += '\n' + this.displayNode(left, prefix, (this.tree[right] === undefined));
}
if (right < this.tree.length) {
line += '\n' + this.displayNode(right, prefix, true);
}
return line;
}
/**
* Serializes the heap to string
*
* @return string The serialized string.
*/
toString()
{
return this.displayNode(0);
}
/**
* Serializes the heap to array
*
* @return {Array}
*/
toArray()
{
return this.tree;
}
[Symbol.iterator]()
{
let length = this.tree.length;
let tree = this.tree;
return {
current: 0,
next ()
{
if (this.current < length) {
let item = [this.current, tree[this.current]];
this.current++;
return {
value: item,
done: false
};
} else {
return {
value: undefined,
done: true
};
}
}
};
}
}
TopJs.apply(Heap, {
/**
* Max heap flag
*
* @memberOf TopJs.stdlib.Heap
* @property {Symbol} MAX
* @static
*/
MAX: 1,
/**
* Min heap flag
*
* @memberOf TopJs.stdlib.Heap
* @property {Symbol} MIN
* @static
*/
MIN: -1
});
TopJs.registerClass("TopJs.stdlib.Heap", Heap);
module.exports = Heap;
|
/**
* Gumby InView
* http://github.com/GumbyFramework/InView v1.0.3
*/
!function($) {
'use strict';
function InViewWatcher($el){
Gumby.debug('Initializing InViewWatcher', $el);
//store the element inside this class
this.$el = $el;
var scope = this;
this.setup();
// re-initialize module
this.$el.on('gumby.initialize', function() {
Gumby.debug('Re-initializing InViewWatcher', scope.$el);
scope.setup();
});
}
InViewWatcher.prototype.setup = function(){
Gumby.debug('Setting up instance of InViewWatcher', this.$el);
this.targets = this.parseTargets();
var classname = Gumby.selectAttr.apply(this.$el, ['classname']);
//at this point the classname is either a string, or false;
//if its false, easy.
if(!classname){
this.classname = "active";
this.classnameBottom = "";
this.classnameTop = "";
}else{
//if its a string, it could be seperated by a pipe
if(classname.indexOf("|") > -1){
classname = classname.split("|");
//now classname is an array
this.classname = classname[0];
this.classnameBottom = classname[1] || "";
this.classnameTop = classname[2] || classname[1] || "";
}else{
//if no pipe, then use only classname
this.classname = classname;
this.classnameBottom = "";
this.classnameTop = "";
}
}
//evaluate offsets
var offset = Gumby.selectAttr.apply(this.$el, ['offset']);
if(offset != false){
offset = offset.split("|");
}else{
offset = 0;
}
this.offset = offset[0] || 0;
this.offsetTop = offset[1] || offset[0] || 0;
this.offsetBottom = this.offset;
};
// parse data-for attribute
InViewWatcher.prototype.parseTargets = function() {
var targetStr = Gumby.selectAttr.apply(this.$el, ['target']);
// no targets so return false
if(!targetStr) {
return false;
}
//are there secondary targets?
var secondaryTargets = targetStr.split('|');
// no secondary targets specified so return single target
if(secondaryTargets.length === 1) {
return $(secondaryTargets[0]);
}
// return all targets
return $(secondaryTargets.join(", "));
};
/*
Utility Method for managing Scrolling
*/
//Variables for Initialization
var t, k, tmp, tar, ot, oh, offt, offb, wh = $(window).height(), watchers = [];
//on scroll - loop through elements
// if the element is on the screen, give it the class
// if its off, take it's class away
$(window).on('scroll', function(e){
t = $(this).scrollTop();
for(k = 0; k < watchers.length; k++){
tmp = watchers[k];
tar = tmp.targets || tmp.$el;
//keep 'hidden' elements from breaking the plugin
if(tmp.$el.css('display') == 'none'){
break;
}
//element's offset top and height
ot = tmp.$el.offset().top;
oh = tmp.$el.height();
//how much on the screen before we apply the class
offt = tmp.offsetTop;
offb = tmp.offsetBottom;
//if above bottom and below top, you're on the screen
var below = ot > (t - offb) + wh;
var above = ot + oh - offt < t;
if(!above && !below){
if(tar.hasClass(tmp.classnameTop)){
tar.removeClass(tmp.classnameTop);
}
if(tar.hasClass(tmp.classnameBottom)){
tar.removeClass(tmp.classnameBottom);
}
if(!tar.hasClass(tmp.classname)){
tar.addClass(tmp.classname);
tar.trigger("gumby.inview");
}
}else if(above && !below){
if(tar.hasClass(tmp.classname)){
tar.removeClass(tmp.classname);
}
if(tar.hasClass(tmp.classnameBottom)){
tar.removeClass(tmp.classnameBottom);
}
if(!tar.hasClass(tmp.classnameTop)){
tar.addClass(tmp.classnameTop);
tar.trigger("gumby.offtop");
}
}else if(below && !above){
if(tar.hasClass(tmp.classname)){
tar.removeClass(tmp.classname);
}
if(tar.hasClass(tmp.classnameTop)){
tar.removeClass(tmp.classnameTop);
}
if(!tar.hasClass(tmp.classnameBottom)){
tar.addClass(tmp.classnameBottom);
tar.trigger("gumby.offbottom");
}
}
}
});
//on resize - update window height reference
//and trigger scroll
$(window).on('resize', function(){
wh = $(this).height();
$(window).trigger('scroll');
});
// add toggle Initialization
Gumby.addInitalisation('inview', function(all) {
$('.inview').each(function() {
var $this = $(this);
// this element has already been initialized
// and we're only initialization new modules
if($this.data('isInView') && !all) {
return true;
// this element has already been initialized
// and we need to reinitialize it
} else if($this.data('isInView') && all) {
$this.trigger('gumby.initialize');
}
// mark element as initialized
$this.data('isInView', true);
watchers.push(new InViewWatcher($this));
});
$(window).trigger('scroll');
});
// register UI module
Gumby.UIModule({
module: 'inview',
events: ['initialize', 'trigger', 'onTrigger'],
init: function() {
// Run initialize methods
Gumby.initialize('inview');
}
});
}(jQuery);
|
define(['skeleton', 'config', './VcbEntry'],
function(sk, config, VcbEntry) {
var Collection = sk.Collection.extend({
model: VcbEntry,
url: '/words',
configure: function(){
},
select: function(specific, wordId, down){
this.active = wordId;
this.trigger('select', specific, wordId, down); //specific, wordId, down
},
emptyFn: function(){}
});
return Collection;
});
|
import * as React from 'react';
import clsx from 'clsx';
import { makeStyles } from '@material-ui/core/styles';
import Link from 'docs/src/modules/components/Link';
import { useTranslate } from 'docs/src/modules/utils/i18n';
const useStyles = makeStyles(
(theme) => ({
root: {
padding: theme.spacing(1, 2, 1, 2),
right: 0,
left: 0,
color: theme.palette.common.white,
backgroundColor: '#626980',
position: 'relative',
display: 'none',
[theme.breakpoints.up('sm')]: {
display: 'flex',
top: 100,
left: 'auto',
position: 'absolute',
borderBottomLeftRadius: 36 / 2,
borderTopLeftRadius: 36 / 2,
},
},
}),
{ name: 'Pro' },
);
export default function Pro() {
const classes = useStyles();
const t = useTranslate();
return (
<Link
variant="body2"
className={clsx(classes.root, 'mui-fixed')}
href="/getting-started/support/#professional-support-premium"
>
{t('getProfessionalSupport')}
</Link>
);
}
|
angular.module('chatty')
.directive('keepScroll', function($window) {
return {
controller: function($scope) {
$scope.element = 0
$scope.lastHeight = null
this.setElement = function(el) {
$scope.element = el
$scope.$watch('element.scrollHeight', function() {
$scope.lastHeight = $scope.element.scrollHeight
}, true)
}
this.itemChanged = function(item) {
if ((item.offsetTop <= $window.scrollY) && $window.scrollY > 0) {
if ($scope.element.scrollHeight !== $scope.lastHeight) {
var diff = $scope.element.scrollHeight - $scope.lastHeight
$window.scrollTo($window.scrollX, $window.scrollY + diff)
}
}
$scope.lastHeight = $scope.element.scrollHeight
}
},
link: {
pre: function(scope, element, attr, ctrl) {
ctrl.setElement(element[0])
}
}
}
})
|
const log4js = require("log4js");
const logger = log4js.getLogger();
const taskController = require('../controllers/taskController');
const userController = require('../controllers/userController');
const ruleController = require('../controllers/ruleController');
const userManager = require('./user/userManager');
const seatManager = require('./seat/seatManager');
const mailSender = require('./mail/mailSender');
const date = require('./Date');
let tokenForBootstrapCount = 1;
class TaskManager {
constructor() {
}
executeSeatTask(job, done) {
const queue = require('./queue');
return new Promise((resolve, reject) => {
//TODO:
const {
token,
date,
seat,
startTime,
endTime
} = job.data;
try {
const bookStatus = seatManager.bookSeat(token, date, seat, startTime, endTime);
//TODO:
if (bookStatus) {
logger.debug("book seat success date:[%d] from:[%d] to:[%d]", date, startTime, endTime);
} else {
//失败重新添加到任务队列
}
resolve();
} catch (e) {
reject(e);
}
})
}
executeEmailTask(job, done) {
return new Promise((resolve, reject) => {
const {
to,
text
} = job.data;
//TODO:
new mailSender().send(to, "图书馆座位预约", text);
})
}
executeLoginTask(job, done) {
const queue = require('./queue');
return new Promise((resolve, reject) => {
const {
userId,
username,
password
} = job.data;
try {
const tokenPromise = userManager.login(username, password);
//TODO:结果处理,登录成功后创建seat任务开始抢座
tokenPromise.then(async (token) => {
if (token) {
logger.debug("login success user:[%s]", username);
await userController.saveToken(userId, token);
//在这里登陆成功要创建 SeatBootstrap 任务检测是否到开始选座的时间,检测没到时间要继续创建该任务执行,直到检测到了时间才能 process seat task
if(tokenForBootstrapCount){
queue.create("seatBootstrap",{
id:2,
token
})
.save();
tokenForBootstrapCount--;
}
// 根据userid查询当前用户的抢座任务(用户通过邮件创建的)
ruleController.getComputedRule(userId).then(function (rule) {
const during = rule[(new Date()).toString().slice(0, 3).toLowerCase()];
if (!during) {
return;
}
const [startHour, startMin, endHour, endMin] = during.split(' ').map((item) => {
return parseInt(item);
});
queue.create('seat', {
token,
date: date.prototype.getAnyDay(1).Format('yyyy-MM-dd'),
seat: JSON.parse(rule.preferSeat),//TODO:传入选座数组,里面有多个座位,从第一个座位开始请求,如果成功那么发送成功邮件,如果失败继续选第二个座位,以此类推
startTime: startHour * 60 + startMin,
endTime: endHour * 60 + endMin
})
});
} else {
logger.debug("login failed user:[%s]", username);
}
})
} catch (e) {
reject(e);
}
})
}
/**
* 新用户验证task
*
* @param {any} job
* @returns
* @memberof TaskManager
*/
executeVerifyTask(job, done) {
return new Promise(async(resolve, reject) => {
const {
email,
username,
password
} = job.data;
try {
const token = await userManager.login(username, password);
if (token) {
const userModel = await userManager.createUser(email, username, password);
queue.create('email', {
to: userModel.email,
text: ''
})
} else {
queue.create('email', {
to: userModel.email,
text: ''
})
}
resolve();
} catch (e) {
reject(e)
}
})
}
executeSeatBootstrapTask(job, done) {
const queue = require('./queue');
return new Promise(async(resolve, reject)=>{
const {
token
} = job.data;
try{
if(!token){
reject("no token");
}
userManager.getStartTime(token).then((data)=>{
if(data){
/**因为登录成功后可能还没到抢座开始时间,
* 所以需要检测能否开始抢座,可以之后再处理“seat”类任务
* 没有采用推迟queue.create 推迟创建任务的方式,而是推迟process */
queue.process('seat', 15, async (job, done) => {
try {
await taskManager.executeSeatTask(job);
} catch (e) {
}
done();
});
resolve();
return;
}
queue.create('seatBootstrap',{
token
}).save();
})
}catch(e){
reject(e);
}
})
}
}
const taskManager = new TaskManager();
module.exports = taskManager;
|
var optparse = require('..');
var parse = new optparse(process.argv, 'ab:c:de:');
console.log("optind: " + parse.getoptind());
console.log("---------------------------------");
var opt;
while ((opt = parse.getopt()) !== undefined) {
console.log("optind: " + parse.getoptind() + ", argv[]:" + process.argv[parse.getoptind()]);
switch (opt.option) {
case 'a':
console.log("hava option: -a");
break;
case 'b':
console.log("hava option: -b");
console.log("The argument of -b is " + opt.arg);
break;
case 'c':
console.log("hava option: -c");
console.log("The argument of -c is " + opt.arg);
break;
case 'd':
console.log("hava option: -d");
break;
case 'e':
console.log("hava option: -e");
console.log("The argument of -e is " + opt.arg);
break;
case '?':
console.log("unknown option: " + opt.option);
break;
}
console.log("");
}
console.log("---------------------------------");
console.log("optind: " + parse.getoptind() + ", argv[]:" + process.argv[parse.getoptind()]);
|
/* eslint-env mocha */
/* global expect:false */
import {
addComicToPullList,
removeComicFromPullList,
removeComicFromPullListWithUndo,
undoRemoveComicFromPullList
} from './pullList.actions'
import { comicsMinimalInfoSelector } from './pullList.selectors'
import { normalizeComics } from '~/src/features/Common/Helpers/comicsNormalizer'
import createStore from '~/src/store/createStore'
import { mockComics } from '~/tests/testUtilities'
describe('PullList duck tests', function() {
const {
comicIds: mockComicIds,
comicEntities: mockComicEntities
} = normalizeComics(mockComics)
describe('action: addComicToPullList; selector: pullList.comicsMinimalInfoSelector', function() {
it('should add a comic to the pull list', function() {
const testComicId = mockComicIds[0]
const initialState = {
comics: mockComicEntities,
pullList: {
comicIds: []
}
}
const store = createStore(initialState)
store.dispatch(addComicToPullList(testComicId))
const minimalInfo = comicsMinimalInfoSelector(store.getState())
expect(minimalInfo.length).to.equal(1)
expect(minimalInfo[0].id).to.equal(testComicId)
})
})
describe('action: removeComicFromPullList; selector: pullList.comicsMinimalInfoSelector', function() {
it('should remove a comic from the pull list', function() {
const testComicId = mockComicIds[0]
const initialState = {
comics: mockComicEntities,
pullList: {
comicIds: [testComicId]
}
}
const store = createStore(initialState)
store.dispatch(removeComicFromPullList(testComicId))
const minimalInfo = comicsMinimalInfoSelector(store.getState())
expect(minimalInfo.length).to.equal(0)
})
})
describe('action: removeComicFromPullListWithUndo; selector: pullList.comicsMinimalInfoSelector', function() {
it('should remove a comic from the pull list', function() {
const testComicId = mockComicIds[0]
const testEventId = 123
const initialState = {
comics: mockComicEntities,
pullList: {
comicIds: [testComicId]
}
}
const store = createStore(initialState)
store.dispatch(removeComicFromPullListWithUndo(testComicId, testEventId))
const minimalInfo = comicsMinimalInfoSelector(store.getState())
expect(minimalInfo.length).to.equal(0)
})
})
describe('action: undoRemoveComicFromPullList; selector: pullList.comicsMinimalInfoSelector', function() {
it('should add the specified comic to the pull list', function() {
const testComicId = mockComicIds[0]
const testEventId = 123
const initialState = {
comics: mockComicEntities,
pullList: {
comicIds: []
}
}
const store = createStore(initialState)
store.dispatch(undoRemoveComicFromPullList(testComicId, testEventId))
const minimalInfo = comicsMinimalInfoSelector(store.getState())
expect(minimalInfo.length).to.equal(1)
expect(minimalInfo[0].id).to.equal(testComicId)
})
})
})
|
export default (str) => {
const newArr = []
let arr = str.split('')
arr.map( x => {
let number = x.charCodeAt()
if ( (number > 64) && (number < 91) ) {
let lower = String.fromCharCode( number + 32 )
newArr.push( lower )
} else {
newArr.push( x )
}
})
console.log (newArr.join(''))
return newArr.join('')
}
|
// Currently this only works on the issue page itself. Will look into allowing on dashboards and/or kanban boards later. Perhaps a setting for it?
var title = document.getElementById("summary-val");
var anchor = document.createElement("a");
anchor.setAttribute("id", "jira-grabber-button");
anchor.setAttribute("href", "#");
var img = document.createElement("img");
img.setAttribute("src", chrome.extension.getURL("jira-grab/icons/link.png"));
img.setAttribute("alt", "Click to copy issue key and summary");
img.setAttribute("aria-label", "Copy issue key and summary");
img.style.marginTop = "4px";
img.style.marginLeft = "4px";
img.addEventListener("click", function () {
try {
var copySupported = document.queryCommandSupported("copy");
if (copySupported === true) {
var parsedIssue = parseIssue(); // change me when support for pages outside the issue page are done
if(parsedIssue !== "") {
console.log("Parsed as \"" + parsedIssue + "\"");
// can't copy in a content script, have to dispatch to the background page to do this
var status = execCopy(parsedIssue);
console.log(status);
if (status === true) {
displayNotification({"type": "notify", "status": "success", "text": parsedIssue});
} else {
console.error("Failed to copy");
}
} else {
console.error("Failed to parse issue because the key or summary fields were not found. " +
"Expected #key-val or #issuekey-val, and #summary-val");
}
} else {
console.error("Copy command not supported.");
}
} catch (err) {
console.error("Unable to copy to clipboard. Here's the error reported: " + err);
}
});
anchor.appendChild(img);
title.parentNode.appendChild(anchor);
/**
* Parse the issue key and summary.
*
* @return string the parsed issue string or empty string if one of the fields were not found
*/
function parseIssue() {
var key, summary;
if (document.getElementById("key-val") !== null) {
key = document.getElementById("key-val").textContent.trim();
} else if (document.getElementById("issuekey-val") !== null) {
key = document.getElementById("key-val").textContent.trim();
} else {
return "";
}
if(document.getElementById("summary-val") !== null) {
summary = document.getElementById("summary-val").textContent.trim();
} else {
return "";
}
return [key, summary].join(" ");
}
function execCopy(text) {
var copySupported = document.queryCommandSupported("copy");
if (copySupported === false) {
console.error("Copy is not supported");
}
var textArea = document.createElement("textarea");
document.body.appendChild(textArea);
textArea.focus();
textArea.value = text;
textArea.select();
var success = document.execCommand("Copy");
textArea.remove();
return success;
}
function displayNotification(msg) {
var n;
if (window.Notification && window.Notification.permission === "granted") {
if (msg.status === "success") {
n = new Notification("Copied to clipboard: " + msg.text);
} else {
n = new Notification("Failed to copy to clipboard.");
}
} else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
if (permission === "granted") {
if (msg.status === "success") {
n = new Notification("Copied to clipboard: " + msg.text);
} else {
n = new Notification("Failed to copy to clipboard.");
}
}
});
}
setTimeout(n.close.bind(n), 3000);
}
window.addEventListener('load', function () {
// At first, let's check if we have permission for notification
// If not, let's ask for it
if (window.Notification && Notification.permission !== "granted") {
Notification.requestPermission();
}
});
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.m.Input.
sap.ui.define(['jquery.sap.global', './Bar', './Dialog', './InputBase', './List', './Popover', './StandardListItem', './Table', './Toolbar', './ToolbarSpacer', './library', 'sap/ui/core/IconPool', 'jquery.sap.strings'],
function(jQuery, Bar, Dialog, InputBase, List, Popover, StandardListItem, Table, Toolbar, ToolbarSpacer, library, IconPool/* , jQuerySap */) {
"use strict";
/**
* Constructor for a new Input.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Enables users to input data.
* @extends sap.m.InputBase
*
* @author SAP SE
* @version 1.38.4
*
* @constructor
* @public
* @alias sap.m.Input
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var Input = InputBase.extend("sap.m.Input", /** @lends sap.m.Input.prototype */ { metadata : {
library : "sap.m",
properties : {
/**
* HTML type of the internal <code>input</code> tag (e.g. Text, Number, Email, Phone).
* The particular effect of this property differs depending on the browser and the current language settings,
* especially for the type Number.<br>
* This parameter is intended to be used with touch devices that use different soft keyboard layouts depending on the given input type.<br>
* Only the default value <code>sap.m.InputType.Text</code> may be used in combination with data model formats.
* <code>sap.ui.model</code> defines extended formats that are mostly incompatible with normal HTML
* representations for numbers and dates.
*/
type : {type : "sap.m.InputType", group : "Data", defaultValue : sap.m.InputType.Text},
/**
* Maximum number of characters. Value '0' means the feature is switched off.
* This parameter is not compatible with the input type <code>sap.m.InputType.Number</code>.
* If the input type is set to <code>Number</code>, the <code>maxLength</code> value is ignored.
*/
maxLength : {type : "int", group : "Behavior", defaultValue : 0},
/**
* Only used if type=date and no datepicker is available.
* The data is displayed and the user input is parsed according to this format.
* NOTE: The value property is always of the form RFC 3339 (YYYY-MM-dd).
* @deprecated Since version 1.9.1.
* <code>sap.m.DatePicker</code>, <code>sap.m.TimePicher</code> or <code>sap.m.DateTimePicker</code> should be used for date/time inputs and formating.
*/
dateFormat : {type : "string", group : "Misc", defaultValue : 'YYYY-MM-dd', deprecated: true},
/**
* If set to true, a value help indicator will be displayed inside the control. When clicked the event "valueHelpRequest" will be fired.
* @since 1.16
*/
showValueHelp : {type : "boolean", group : "Behavior", defaultValue : false},
/**
* If this is set to true, suggest event is fired when user types in the input. Changing the suggestItems aggregation in suggest event listener will show suggestions within a popup. When runs on phone, input will first open a dialog where the input and suggestions are shown. When runs on a tablet, the suggestions are shown in a popup next to the input.
* @since 1.16.1
*/
showSuggestion : {type : "boolean", group : "Behavior", defaultValue : false},
/**
* If set to true, direct text input is disabled and the control will trigger the event "valueHelpRequest" for all user interactions. The properties "showValueHelp", "editable", and "enabled" must be set to true, otherwise the property will have no effect
* @since 1.21.0
*/
valueHelpOnly : {type : "boolean", group : "Behavior", defaultValue : false},
/**
* Defines whether to filter the provided suggestions before showing them to the user.
*/
filterSuggests : {type : "boolean", group : "Behavior", defaultValue : true},
/**
* If set, the value of this parameter will control the horizontal size of the suggestion list to display more data. This allows suggestion lists to be wider than the input field if there is enough space available. By default, the suggestion list is always as wide as the input field.
* Note: The value will be ignored if the actual width of the input field is larger than the specified parameter value.
* @since 1.21.1
*/
maxSuggestionWidth : {type : "sap.ui.core.CSSSize", group : "Appearance", defaultValue : null},
/**
* Minimum length of the entered text in input before suggest event is fired. The default value is 1 which means the suggest event is fired after user types in input. When it's set to 0, suggest event is fired when input with no text gets focus.
* @since 1.21.2
*/
startSuggestion : {type : "int", group : "Behavior", defaultValue : 1},
/**
* For tabular suggestions, this flag will show/hide the button at the end of the suggestion table that triggers the event "valueHelpRequest" when pressed. The default value is true.
*
* NOTE: If suggestions are not tabular or no suggestions are used, the button will not be displayed and this flag is without effect.
* @since 1.22.1
*/
showTableSuggestionValueHelp : {type : "boolean", group : "Behavior", defaultValue : true},
/**
* The description is a text after the input field, e.g. units of measurement, currencies.
*/
description : {type : "string", group : "Misc", defaultValue : null},
/**
* This property only takes effect if the description property is set. It controls the distribution of space between the input field and the description text. The default value is 50% leaving the other 50% for the description.
*/
fieldWidth : {type : "sap.ui.core.CSSSize", group : "Appearance", defaultValue : '50%'},
/**
* Indicates when the value gets updated with the user changes: At each keystroke (true) or first when the user presses enter or tabs out (false).
* @since 1.24
*/
valueLiveUpdate : {type : "boolean", group : "Behavior", defaultValue : false}
},
defaultAggregation : "suggestionItems",
aggregations : {
/**
* SuggestItems are the items which will be shown in the suggestion popup. Changing this aggregation (by calling addSuggestionItem, insertSuggestionItem, removeSuggestionItem, removeAllSuggestionItems, destroySuggestionItems) after input is rendered will open/close the suggestion popup. o display suggestions with two text values, it is also possible to add sap.ui.core/ListItems as SuggestionItems (since 1.21.1). For the selected ListItem, only the first value is returned to the input field.
* @since 1.16.1
*/
suggestionItems : {type : "sap.ui.core.Item", multiple : true, singularName : "suggestionItem"},
/**
* The suggestionColumns and suggestionRows are for tabular input suggestions. This aggregation allows for binding the table columns; for more details see the aggregation "suggestionRows".
* @since 1.21.1
*/
suggestionColumns : {type : "sap.m.Column", multiple : true, singularName : "suggestionColumn", bindable : "bindable"},
/**
* The suggestionColumns and suggestionRows are for tabular input suggestions. This aggregation allows for binding the table cells.
* The items of this aggregation are to be bound directly or to set in the suggest event method.
* Note: If this aggregation is filled, the aggregation suggestionItems will be ignored.
* @since 1.21.1
*/
suggestionRows : {type : "sap.m.ColumnListItem", multiple : true, singularName : "suggestionRow", bindable : "bindable"}
},
events : {
/**
* This event is fired when the value of the input is changed - e.g. at each keypress
*/
liveChange : {
parameters : {
/**
* The new value of the input.
*/
value : {type : "string"}
}
},
/**
* When the value help indicator is clicked, this event will be fired.
* @since 1.16
*/
valueHelpRequest : {
parameters : {
/**
* The event parameter is set to true, when the button at the end of the suggestion table is clicked, otherwise false. It can be used to determine whether the "value help" trigger or the "show all items" trigger has been pressed.
*/
fromSuggestions : {type : "boolean"}
}
},
/**
* This event is fired when user types in the input and showSuggestion is set to true. Changing the suggestItems aggregation will show the suggestions within a popup.
* @since 1.16.1
*/
suggest : {
parameters : {
/**
* The current value which has been typed in the input.
*/
suggestValue : {type : "string"},
/**
* The suggestion list is passed to this event for convenience. If you use list-based or tabular suggestions, fill the suggestionList with the items you want to suggest. Otherwise, directly add the suggestions to the "suggestionItems" aggregation of the input control.
*/
suggestionColumns : {type : "sap.m.ListBase"}
}
},
/**
* This event is fired when suggestionItem shown in suggestion popup are selected. This event is only fired when showSuggestion is set to true and there are suggestionItems shown in the suggestion popup.
* @since 1.16.3
*/
suggestionItemSelected : {
parameters : {
/**
* This is the item selected in the suggestion popup for one and two-value suggestions. For tabular suggestions, this value will not be set.
*/
selectedItem : {type : "sap.ui.core.Item"},
/**
* This is the row selected in the tabular suggestion popup represented as a ColumnListItem. For one and two-value suggestions, this value will not be set.
*
* Note: The row result function to select a result value for the string is already executed at this time. To pick different value for the input field or to do follow up steps after the item has been selected.
* @since 1.21.1
*/
selectedRow : {type : "sap.m.ColumnListItem"}
}
},
/**
* This event is fired when user presses the <code>Enter</code> key on the input.
*
* <b>Note:</b>
* The event is fired independent of whether there was a change before or not. If a change was performed the event is fired after the change event.
* The event is also fired when an item of the select list is selected via <code>Enter</code>.
* The event is only fired on an input which allows text input (<code>editable</code>, <code>enabled</code> and not <code>valueHelpOnly</code>).
*
* @since 1.33.0
*/
submit : {
parameters: {
/**
* The new value of the input.
*/
value: { type: "string" }
}
}
}
}});
IconPool.insertFontFaceStyle();
/**
* The default filter function for one and two-value. It checks whether the item text begins with the typed value.
* @param {string} sValue the current filter string
* @param {sap.ui.core.Item} oItem the filtered list item
* @private
* @returns {boolean} true for items that start with the parameter sValue, false for non matching items
*/
Input._DEFAULTFILTER = function(sValue, oItem) {
return jQuery.sap.startsWithIgnoreCase(oItem.getText(), sValue);
};
/**
* The default filter function for tabular suggestions. It checks whether the first item text begins with the typed value.
* @param {string} sValue the current filter string
* @param {sap.m.ColumnListItem} oColumnListItem the filtered list item
* @private
* @returns {boolean} true for items that start with the parameter sValue, false for non matching items
*/
Input._DEFAULTFILTER_TABULAR = function(sValue, oColumnListItem) {
var aCells = oColumnListItem.getCells(),
i = 0;
for (; i < aCells.length; i++) {
// take first cell with a text method and compare value
if (aCells[i].getText) {
return jQuery.sap.startsWithIgnoreCase(aCells[i].getText(), sValue);
}
}
return false;
};
/**
* The default result function for tabular suggestions. It returns the value of the first cell with a "text" property
* @param {sap.m.ColumnListItem} oColumnListItem the selected list item
* @private
* @returns {string} the value to be displayed in the input field
*/
Input._DEFAULTRESULT_TABULAR = function (oColumnListItem) {
var aCells = oColumnListItem.getCells(),
i = 0;
for (; i < aCells.length; i++) {
// take first cell with a text method and compare value
if (aCells[i].getText) {
return aCells[i].getText();
}
}
return "";
};
/**
* Initializes the control
* @private
*/
Input.prototype.init = function() {
InputBase.prototype.init.call(this);
this._fnFilter = Input._DEFAULTFILTER;
// Show suggestions in a dialog on phones:
this._bUseDialog = sap.ui.Device.system.phone;
// Show suggestions in a full screen dialog on phones:
this._bFullScreen = sap.ui.Device.system.phone;
// Counter for concurrent issues with setValue:
this._iSetCount = 0;
};
/**
* Destroys the control
* @private
*/
Input.prototype.exit = function() {
this._deregisterEvents();
// clear delayed calls
this.cancelPendingSuggest();
if (this._iRefreshListTimeout) {
jQuery.sap.clearDelayedCall(this._iRefreshListTimeout);
this._iRefreshListTimeout = null;
}
if (this._oSuggestionPopup) {
this._oSuggestionPopup.destroy();
this._oSuggestionPopup = null;
}
// CSN# 1404088/2014: list is not destroyed when it has not been attached to the popup yet
if (this._oList) {
this._oList.destroy();
this._oList = null;
}
if (this._oValueHelpIcon) {
this._oValueHelpIcon.destroy();
this._oValueHelpIcon = null;
}
if (this._oSuggestionTable) {
this._oSuggestionTable.destroy();
this._oSuggestionTable = null;
}
if (this._oButtonToolbar) {
this._oButtonToolbar.destroy();
this._oButtonToolbar = null;
}
if (this._oShowMoreButton) {
this._oShowMoreButton.destroy();
this._oShowMoreButton = null;
}
};
/**
* Resizes the popup to the input width and makes sure that the input is never bigger as the popup
* @private
*/
Input.prototype._resizePopup = function() {
var that = this;
if (this._oList && this._oSuggestionPopup) {
if (this.getMaxSuggestionWidth()) {
this._oSuggestionPopup.setContentWidth(this.getMaxSuggestionWidth());
} else {
this._oSuggestionPopup.setContentWidth((this.$().outerWidth()) + "px");
}
// resize suggestion popup to minimum size of the input field
setTimeout(function() {
if (that._oSuggestionPopup && that._oSuggestionPopup.isOpen() && that._oSuggestionPopup.$().outerWidth() < that.$().outerWidth()) {
that._oSuggestionPopup.setContentWidth((that.$().outerWidth()) + "px");
}
}, 0);
}
};
Input.prototype.onBeforeRendering = function() {
InputBase.prototype.onBeforeRendering.call(this);
this._deregisterEvents();
};
Input.prototype.onAfterRendering = function() {
var that = this;
InputBase.prototype.onAfterRendering.call(this);
if (!this._bFullScreen) {
this._resizePopup();
this._sPopupResizeHandler = sap.ui.core.ResizeHandler.register(this.getDomRef(), function() {
that._resizePopup();
});
}
if (this._bUseDialog) {
// click event has to be used in order to focus on the input in dialog
// do not open suggestion dialog by click over the value help icon
this.$().on("click", jQuery.proxy(function (oEvent) {
if (this.getShowSuggestion() && this._oSuggestionPopup && oEvent.target.id != this.getId() + "__vhi") {
this._oSuggestionPopup.open();
}
}, this));
}
};
/**
* Returns/Instantiates the value help icon control when needed
* @private
*/
Input.prototype._getValueHelpIcon = function () {
var that = this;
if (!this._oValueHelpIcon) {
var sURI = IconPool.getIconURI("value-help");
this._oValueHelpIcon = IconPool.createControlByURI({
id: this.getId() + "__vhi",
src: sURI,
useIconTooltip: false,
noTabStop: true
});
this._oValueHelpIcon.addStyleClass("sapMInputValHelpInner");
this._oValueHelpIcon.attachPress(function (evt) {
// if the property valueHelpOnly is set to true, the event is triggered in the ontap function
if (!that.getValueHelpOnly()) {
that.fireValueHelpRequest({fromSuggestions: false});
}
});
}
return this._oValueHelpIcon;
};
/**
* Fire valueHelpRequest event if conditions for ValueHelpOnly property are met
* @private
*/
Input.prototype._fireValueHelpRequestForValueHelpOnly = function() {
// if all the named properties are set to true, the control triggers "valueHelpRequest" for all user interactions
if (this.getEnabled() && this.getEditable() && this.getShowValueHelp() && this.getValueHelpOnly()) {
this.fireValueHelpRequest({fromSuggestions: false});
}
};
/**
* Fire valueHelpRequest event on tap
* @public
* @param {jQuery.Event} oEvent
*/
Input.prototype.ontap = function(oEvent) {
InputBase.prototype.ontap.call(this, oEvent);
this._fireValueHelpRequestForValueHelpOnly();
};
/**
* Defines the width of the input. Default value is 100%
* @public
* @param {string} sWidth
*/
Input.prototype.setWidth = function(sWidth) {
return InputBase.prototype.setWidth.call(this, sWidth || "100%");
};
/**
* Returns the width of the input.
* @public
* @return {string} The current width or 100% as default
*/
Input.prototype.getWidth = function() {
return this.getProperty("width") || "100%";
};
/**
* Sets a custom filter function for suggestions. The default is to check whether the first item text begins with the typed value. For one and two-value suggestions this callback function will operate on sap.ui.core.Item types, for tabular suggestions the function will operate on sap.m.ColumnListItem types.
* @param {function} fnFilter The filter function is called when displaying suggestion items and has two input parameters: the first one is the string that is currently typed in the input field and the second one is the item that is being filtered. Returning true will add this item to the popup, returning false will not display it.
* @returns {sap.m.Input} this pointer for chaining
* @since 1.16.1
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
Input.prototype.setFilterFunction = function(fnFilter) {
// reset to default function when calling with null or undefined
if (fnFilter === null || fnFilter === undefined) {
this._fnFilter = Input._DEFAULTFILTER;
return this;
}
// set custom function
jQuery.sap.assert(typeof (fnFilter) === "function", "Input.setFilterFunction: first argument fnFilter must be a function on " + this);
this._fnFilter = fnFilter;
return this;
};
/**
* Sets a custom result filter function for tabular suggestions to select the text that is passed to the input field. Default is to check whether the first cell with a "text" property begins with the typed value. For one value and two-value suggestions this callback function is not called.
* @param {function} fnFilter The result function is called with one parameter: the sap.m.ColumnListItem that is selected. The function must return a result string that will be displayed as the input field's value.
* @returns {sap.m.Input} this pointer for chaining
* @public
* @since 1.21.1
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
Input.prototype.setRowResultFunction = function(fnFilter) {
// reset to default function when calling with null or undefined
if (fnFilter === null || fnFilter === undefined) {
this._fnRowResultFilter = Input._DEFAULTRESULT_TABULAR;
return this;
}
// set custom function
jQuery.sap.assert(typeof (fnFilter) === "function", "Input.setRowResultFunction: first argument fnFilter must be a function on " + this);
this._fnRowResultFilter = fnFilter;
return this;
};
Input.prototype.setShowValueHelp = function(bShowValueHelp) {
this.setProperty("showValueHelp", bShowValueHelp);
if (bShowValueHelp && !Input.prototype._sAriaValueHelpLabelId) {
// create an F4 ARIA announcement and remember its ID for later use in the renderer:
Input.prototype._sAriaValueHelpLabelId = new sap.ui.core.InvisibleText({
text: sap.ui.getCore().getLibraryResourceBundle("sap.m").getText("INPUT_VALUEHELP")
}).toStatic().getId();
}
return this;
};
Input.prototype.setValueHelpOnly = function(bValueHelpOnly) {
this.setProperty("valueHelpOnly", bValueHelpOnly);
if (bValueHelpOnly && !Input.prototype._sAriaInputDisabledLabelId) {
// create an F4 ARIA announcement and remember its ID for later use in the renderer:
Input.prototype._sAriaInputDisabledLabelId = new sap.ui.core.InvisibleText({
text: sap.ui.getCore().getLibraryResourceBundle("sap.m").getText("INPUT_DISABLED")
}).toStatic().getId();
}
return this;
};
/**
* Selects the text of the InputDomRef in the given range
* @param {int} [iStart=0] start position of the text selection
* @param {int} [iEnd=<length of text>] end position of the text selection
* @return {sap.m.Input} this Input instance for chaining
* @private
*/
Input.prototype._doSelect = function(iStart, iEnd) {
if (sap.ui.Device.support.touch) {
return;
}
var oDomRef = this._$input[0];
if (oDomRef) {
// if no Dom-Ref - no selection (Maybe popup closed)
var $Ref = this._$input;
oDomRef.focus();
$Ref.selectText(iStart ? iStart : 0, iEnd ? iEnd : $Ref.val().length);
}
return this;
};
Input.prototype._scrollToItem = function(iIndex) {
var oPopup = this._oSuggestionPopup,
oList = this._oList,
oScrollDelegate,
oPopupRect,
oItemRect,
iTop,
iBottom;
if (!(oPopup instanceof Popover) || !oList) {
return;
}
oScrollDelegate = oPopup.getScrollDelegate();
if (!oScrollDelegate) {
return;
}
var oListItem = oList.getItems()[iIndex],
oListItemDom = oListItem && oListItem.getDomRef();
if (!oListItemDom) {
return;
}
oPopupRect = oPopup.getDomRef("cont").getBoundingClientRect();
oItemRect = oListItemDom.getBoundingClientRect();
iTop = oPopupRect.top - oItemRect.top;
iBottom = oItemRect.bottom - oPopupRect.bottom;
if (iTop > 0) {
oScrollDelegate.scrollTo(oScrollDelegate._scrollX, Math.max(oScrollDelegate._scrollY - iTop, 0));
} else if (iBottom > 0) {
oScrollDelegate.scrollTo(oScrollDelegate._scrollX, oScrollDelegate._scrollY + iBottom);
}
};
// helper method for keyboard navigation in suggestion items
Input.prototype._isSuggestionItemSelectable = function(oItem) {
// CSN# 1390866/2014: The default for ListItemBase type is "Inactive", therefore disabled entries are only supported for single and two-value suggestions
// for tabular suggestions: only check visible
// for two-value and single suggestions: check also if item is not inactive
return oItem.getVisible() && (this._hasTabularSuggestions() || oItem.getType() !== sap.m.ListType.Inactive);
};
Input.prototype._onsaparrowkey = function(oEvent, sDir, iItems) {
if (!this.getEnabled() || !this.getEditable()) {
return;
}
if (!this._oSuggestionPopup || !this._oSuggestionPopup.isOpen()) {
return;
}
if (sDir !== "up" && sDir !== "down") {
return;
}
oEvent.preventDefault();
oEvent.stopPropagation();
var bFirst = false,
oList = this._oList,
aItems = this.getSuggestionItems(),
aListItems = oList.getItems(),
iSelectedIndex = this._iPopupListSelectedIndex,
sNewValue,
iOldIndex = iSelectedIndex;
if (sDir === "up" && iSelectedIndex === 0) {
// if key is 'up' and selected Item is first -> do nothing
return;
}
if (sDir == "down" && iSelectedIndex === aListItems.length - 1) {
//if key is 'down' and selected Item is last -> do nothing
return;
}
var iStopIndex;
if (iItems > 1) {
// if iItems would go over the borders, search for valid item in other direction
if (sDir == "down" && iSelectedIndex + iItems >= aListItems.length) {
sDir = "up";
iItems = 1;
aListItems[iSelectedIndex].setSelected(false);
iStopIndex = iSelectedIndex;
iSelectedIndex = aListItems.length - 1;
bFirst = true;
} else if (sDir == "up" && iSelectedIndex - iItems < 0){
sDir = "down";
iItems = 1;
aListItems[iSelectedIndex].setSelected(false);
iStopIndex = iSelectedIndex;
iSelectedIndex = 0;
bFirst = true;
}
}
// always select the first item from top when nothing is selected so far
if (iSelectedIndex === -1) {
iSelectedIndex = 0;
if (this._isSuggestionItemSelectable(aListItems[iSelectedIndex])) {
// if first item is visible, don't go into while loop
iOldIndex = iSelectedIndex;
bFirst = true;
} else {
// detect first visible item with while loop
sDir = "down";
}
}
if (sDir === "down") {
while (iSelectedIndex < aListItems.length - 1 && (!bFirst || !this._isSuggestionItemSelectable(aListItems[iSelectedIndex]))) {
aListItems[iSelectedIndex].setSelected(false);
iSelectedIndex = iSelectedIndex + iItems;
bFirst = true;
iItems = 1; // if wanted item is not selectable just search the next one
if (iStopIndex === iSelectedIndex) {
break;
}
}
} else {
while (iSelectedIndex > 0 && (!bFirst || !aListItems[iSelectedIndex].getVisible() || !this._isSuggestionItemSelectable(aListItems[iSelectedIndex]))) {
aListItems[iSelectedIndex].setSelected(false);
iSelectedIndex = iSelectedIndex - iItems;
bFirst = true;
iItems = 1; // if wanted item is not selectable just search the next one
if (iStopIndex === iSelectedIndex) {
break;
}
}
}
if (!this._isSuggestionItemSelectable(aListItems[iSelectedIndex])) {
// if no further visible item can be found -> do nothing (e.g. set the old item as selected again)
if (iOldIndex >= 0) {
aListItems[iOldIndex].setSelected(true).updateAccessibilityState();
this.$("inner").attr("aria-activedescendant", aListItems[iOldIndex].getId());
}
return;
} else {
aListItems[iSelectedIndex].setSelected(true).updateAccessibilityState();
this.$("inner").attr("aria-activedescendant", aListItems[iSelectedIndex].getId());
}
if (sap.ui.Device.system.desktop) {
this._scrollToItem(iSelectedIndex);
}
// make sure the value doesn't exceed the maxLength
if (sap.m.ColumnListItem && aListItems[iSelectedIndex] instanceof sap.m.ColumnListItem) {
// for tabular suggestions we call a result filter function
sNewValue = this._getInputValue(this._fnRowResultFilter(aListItems[iSelectedIndex]));
} else {
var bListItem = (aItems[0] instanceof sap.ui.core.ListItem ? true : false);
if (bListItem) {
// for two value suggestions we use the item label
sNewValue = this._getInputValue(aListItems[iSelectedIndex].getLabel());
} else {
// otherwise we use the item title
sNewValue = this._getInputValue(aListItems[iSelectedIndex].getTitle());
}
}
// setValue isn't used because here is too early to modify the lastValue of input
this._$input.val(sNewValue);
// memorize the value set by calling jQuery.val, because browser doesn't fire a change event when the value is set programmatically.
this._sSelectedSuggViaKeyboard = sNewValue;
this._doSelect();
this._iPopupListSelectedIndex = iSelectedIndex;
};
Input.prototype.onsapup = function(oEvent) {
this._onsaparrowkey(oEvent, "up", 1);
};
Input.prototype.onsapdown = function(oEvent) {
this._onsaparrowkey(oEvent, "down", 1);
};
Input.prototype.onsappageup = function(oEvent) {
this._onsaparrowkey(oEvent, "up", 5);
};
Input.prototype.onsappagedown = function(oEvent) {
this._onsaparrowkey(oEvent, "down", 5);
};
Input.prototype.onsaphome = function(oEvent) {
if (this._oList) {
this._onsaparrowkey(oEvent, "up", this._oList.getItems().length);
}
};
Input.prototype.onsapend = function(oEvent) {
if (this._oList) {
this._onsaparrowkey(oEvent, "down", this._oList.getItems().length);
}
};
Input.prototype.onsapescape = function(oEvent) {
var lastValue;
if (this._oSuggestionPopup && this._oSuggestionPopup.isOpen()) {
// mark the event as already handled
oEvent.originalEvent._sapui_handledByControl = true;
this._iPopupListSelectedIndex = -1;
this._closeSuggestionPopup();
// restore the initial value that was there before suggestion dialog
if (this._sBeforeSuggest !== undefined) {
if (this._sBeforeSuggest !== this.getValue()) {
lastValue = this._lastValue;
this.setValue(this._sBeforeSuggest);
this._lastValue = lastValue; // override InputBase.onsapescape()
}
this._sBeforeSuggest = undefined;
}
return; // override InputBase.onsapescape()
}
if (InputBase.prototype.onsapescape) {
InputBase.prototype.onsapescape.apply(this, arguments);
}
};
Input.prototype.onsapenter = function(oEvent) {
if (InputBase.prototype.onsapenter) {
InputBase.prototype.onsapenter.apply(this, arguments);
}
// when enter is pressed before the timeout of suggestion delay, suggest event is cancelled
this.cancelPendingSuggest();
if (this._oSuggestionPopup && this._oSuggestionPopup.isOpen()) {
if (this._iPopupListSelectedIndex >= 0) {
this._fireSuggestionItemSelectedEvent();
this._doSelect();
this._iPopupListSelectedIndex = -1;
}
this._closeSuggestionPopup();
}
if (this.getEnabled() && this.getEditable() && !(this.getValueHelpOnly() && this.getShowValueHelp())) {
this.fireSubmit({value: this.getValue()});
}
};
Input.prototype.onsapfocusleave = function(oEvent) {
var oPopup = this._oSuggestionPopup;
if (oPopup instanceof Popover) {
if (oEvent.relatedControlId && jQuery.sap.containsOrEquals(oPopup.getDomRef(), sap.ui.getCore().byId(oEvent.relatedControlId).getFocusDomRef())) {
// Force the focus to stay in input
this._bPopupHasFocus = true;
this.focus();
} else {
// When the input still has the value of the last jQuery.val call, a change event has to be
// fired manually because browser doesn't fire an input event in this case.
if (this._$input.val() === this._sSelectedSuggViaKeyboard) {
this._sSelectedSuggViaKeyboard = null;
}
}
}
// Inform InputBase to fire the change event on Input only when focus doesn't go into the suggestion popup
var oFocusedControl = sap.ui.getCore().byId(oEvent.relatedControlId);
if (!(oPopup
&& oFocusedControl
&& jQuery.sap.containsOrEquals(oPopup.getDomRef(), oFocusedControl.getFocusDomRef())
)) {
InputBase.prototype.onsapfocusleave.apply(this, arguments);
}
};
Input.prototype.onmousedown = function(oEvent) {
var oPopup = this._oSuggestionPopup;
if ((oPopup instanceof Popover) && oPopup.isOpen()) {
oEvent.stopPropagation();
}
};
Input.prototype._deregisterEvents = function() {
if (this._sPopupResizeHandler) {
sap.ui.core.ResizeHandler.deregister(this._sPopupResizeHandler);
this._sPopupResizeHandler = null;
}
if (this._bUseDialog && this._oSuggestionPopup) {
this.$().off("click");
}
};
Input.prototype.updateSuggestionItems = function() {
this.updateAggregation("suggestionItems");
this._refreshItemsDelayed();
return this;
};
Input.prototype.cancelPendingSuggest = function() {
if (this._iSuggestDelay) {
jQuery.sap.clearDelayedCall(this._iSuggestDelay);
this._iSuggestDelay = null;
}
};
Input.prototype._triggerSuggest = function(sValue) {
this.cancelPendingSuggest();
if (!sValue) {
sValue = "";
}
if (sValue.length >= this.getStartSuggestion()) {
this._iSuggestDelay = jQuery.sap.delayedCall(300, this, function(){
this._bBindingUpdated = false;
this.fireSuggest({
suggestValue: sValue
});
// if binding is updated during suggest event, the list items don't need to be refreshed here
// because they will be refreshed in updateItems function.
// This solves the popup blinking problem
if (!this._bBindingUpdated) {
this._refreshItemsDelayed();
}
});
} else if (this._bUseDialog) {
if (this._oList instanceof Table) {
// CSN# 1421140/2014: hide the table for empty/initial results to not show the table columns
this._oList.addStyleClass("sapMInputSuggestionTableHidden");
} else if (this._oList && this._oList.destroyItems) {
this._oList.destroyItems();
}
} else if (this._oSuggestionPopup && this._oSuggestionPopup.isOpen()) {
this._iPopupListSelectedIndex = -1;
this._closeSuggestionPopup();
}
};
(function(){
Input.prototype.setShowSuggestion = function(bValue){
this.setProperty("showSuggestion", bValue, true);
this._iPopupListSelectedIndex = -1;
if (bValue) {
this._lazyInitializeSuggestionPopup(this);
} else {
destroySuggestionPopup(this);
}
return this;
};
Input.prototype.setShowTableSuggestionValueHelp = function(bValue) {
this.setProperty("showTableSuggestionValueHelp", bValue, true);
if (!this._oSuggestionPopup) {
return this;
}
if (bValue) {
this._addShowMoreButton();
} else {
this._removeShowMoreButton();
}
return this;
};
Input.prototype._getShowMoreButton = function() {
var that = this,
oMessageBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m");
return this._oShowMoreButton || (this._oShowMoreButton = new sap.m.Button({
text : oMessageBundle.getText("INPUT_SUGGESTIONS_SHOW_ALL"),
press : function() {
if (that.getShowTableSuggestionValueHelp()) {
that.fireValueHelpRequest({fromSuggestions: true});
that._iPopupListSelectedIndex = -1;
that._closeSuggestionPopup();
}
}
}));
};
Input.prototype._getButtonToolbar = function() {
var oShowMoreButton = this._getShowMoreButton();
return this._oButtonToolbar || (this._oButtonToolbar = new Toolbar({
content: [
new ToolbarSpacer(),
oShowMoreButton
]
}));
};
/*
* Adds a more button to the footer of the tabular suggestion popup/dialog
* @param{boolean} [bTabular] optional parameter to force override the tabular suggestions check
*/
Input.prototype._addShowMoreButton = function(bTabular) {
if (!this._oSuggestionPopup || !bTabular && !this._hasTabularSuggestions()) {
return;
}
if (this._oSuggestionPopup instanceof Dialog) {
// phone variant, use endButton (beginButton is close)
var oShowMoreButton = this._getShowMoreButton();
this._oSuggestionPopup.setEndButton(oShowMoreButton);
} else {
var oButtonToolbar = this._getButtonToolbar();
// desktop/tablet variant, use popover footer
this._oSuggestionPopup.setFooter(oButtonToolbar);
}
};
/*
* Removes the more button from the footer of the tabular suggestion popup/dialog
*/
Input.prototype._removeShowMoreButton = function() {
if (!this._oSuggestionPopup || !this._hasTabularSuggestions()) {
return;
}
if (this._oSuggestionPopup instanceof Dialog) {
this._oSuggestionPopup.setEndButton(null);
} else {
this._oSuggestionPopup.setFooter(null);
}
};
Input.prototype.oninput = function(oEvent) {
InputBase.prototype.oninput.call(this, oEvent);
if (oEvent.isMarked("invalid")) {
return;
}
var value = this._$input.val();
// add maxlength support for all types except for the type Number
// TODO: type number add min and max properties
if (this.getMaxLength() > 0 && this.getType() !== sap.m.InputType.Number && value.length > this.getMaxLength()) {
value = value.substring(0, this.getMaxLength());
this._$input.val(value);
}
if (this.getValueLiveUpdate()) {
this.setProperty("value",value, true);
}
this.fireLiveChange({
value: value,
// backwards compatibility
newValue: value
});
// No need to fire suggest event when suggestion feature isn't enabled or runs on the phone.
// Because suggest event should only be fired by the input in dialog when runs on the phone.
if (this.getShowSuggestion() && !this._bUseDialog) {
this._triggerSuggest(value);
}
};
Input.prototype.getValue = function(){
return this.getDomRef("inner") ? this._$input.val() : this.getProperty("value");
};
Input.prototype._refreshItemsDelayed = function() {
jQuery.sap.clearDelayedCall(this._iRefreshListTimeout);
this._iRefreshListTimeout = jQuery.sap.delayedCall(0, this, refreshListItems, [ this ]);
};
Input.prototype.addSuggestionItem = function(oItem) {
this.addAggregation("suggestionItems", oItem, true);
this._refreshItemsDelayed();
createSuggestionPopupContent(this);
return this;
};
Input.prototype.insertSuggestionItem = function(oItem, iIndex) {
this.insertAggregation("suggestionItems", iIndex, oItem, true);
this._refreshItemsDelayed();
createSuggestionPopupContent(this);
return this;
};
Input.prototype.removeSuggestionItem = function(oItem) {
var res = this.removeAggregation("suggestionItems", oItem, true);
this._refreshItemsDelayed();
return res;
};
Input.prototype.removeAllSuggestionItems = function() {
var res = this.removeAllAggregation("suggestionItems", true);
this._refreshItemsDelayed();
return res;
};
Input.prototype.destroySuggestionItems = function() {
this.destroyAggregation("suggestionItems", true);
this._refreshItemsDelayed();
return this;
};
Input.prototype.addSuggestionRow = function(oItem) {
oItem.setType(sap.m.ListType.Active);
this.addAggregation("suggestionRows", oItem);
this._refreshItemsDelayed();
createSuggestionPopupContent(this);
return this;
};
Input.prototype.insertSuggestionRow = function(oItem, iIndex) {
oItem.setType(sap.m.ListType.Active);
this.insertAggregation("suggestionRows", iIndex, oItem);
this._refreshItemsDelayed();
createSuggestionPopupContent(this);
return this;
};
Input.prototype.removeSuggestionRow = function(oItem) {
var res = this.removeAggregation("suggestionRows", oItem);
this._refreshItemsDelayed();
return res;
};
Input.prototype.removeAllSuggestionRows = function() {
var res = this.removeAllAggregation("suggestionRows");
this._refreshItemsDelayed();
return res;
};
Input.prototype.destroySuggestionRows = function() {
this.destroyAggregation("suggestionRows");
this._refreshItemsDelayed();
return this;
};
/**
* Forwards aggregations with the name of items or columns to the internal table.
* @overwrite
* @public
* @param {string} sAggregationName the name for the binding
* @param {object} oBindingInfo the configuration parameters for the binding
* @returns {sap.m.Input} this pointer for chaining
*/
Input.prototype.bindAggregation = function() {
var args = Array.prototype.slice.call(arguments);
if (args[0] === "suggestionRows" || args[0] === "suggestionColumns" || args[0] === "suggestionItems") {
createSuggestionPopupContent(this, args[0] === "suggestionRows" || args[0] === "suggestionColumns");
this._bBindingUpdated = true;
}
// propagate the bind aggregation function to list
this._callMethodInManagedObject.apply(this, ["bindAggregation"].concat(args));
return this;
};
Input.prototype._lazyInitializeSuggestionPopup = function() {
if (!this._oSuggestionPopup) {
createSuggestionPopup(this);
}
};
Input.prototype._closeSuggestionPopup = function() {
if (this._oSuggestionPopup) {
this.cancelPendingSuggest();
this._oSuggestionPopup.close();
this.$("SuggDescr").text(""); // initialize suggestion ARIA text
this.$("inner").removeAttr("aria-haspopup");
this.$("inner").removeAttr("aria-activedescendant");
}
};
function createSuggestionPopup(oInput) {
var oMessageBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m");
if (oInput._bUseDialog) {
oInput._oPopupInput = new Input(oInput.getId() + "-popup-input", {
width : "100%",
valueLiveUpdate: true,
showValueHelp: oInput.getShowValueHelp(),
valueHelpRequest: function(oEvent) {
// it is the same behavior as by ShowMoreButton:
oInput.fireValueHelpRequest({fromSuggestions: true});
oInput._iPopupListSelectedIndex = -1;
oInput._closeSuggestionPopup();
},
liveChange : function(oEvent) {
var sValue = oEvent.getParameter("newValue");
// call _getInputValue to apply the maxLength to the typed value
oInput._$input.val(oInput
._getInputValue(oInput._oPopupInput
.getValue()));
oInput._triggerSuggest(sValue);
// make sure the live change handler on the original input is also called
oInput.fireLiveChange({
value: sValue,
// backwards compatibility
newValue: sValue
});
}
}).addStyleClass("sapMInputSuggInDialog");
}
oInput._oSuggestionPopup = !oInput._bUseDialog ?
(new Popover(oInput.getId() + "-popup", {
showArrow: false,
showHeader : false,
placement : sap.m.PlacementType.Vertical,
initialFocus : oInput
}).attachAfterClose(function() {
if (oInput._iPopupListSelectedIndex >= 0) {
oInput._fireSuggestionItemSelectedEvent();
}
// only destroy items in simple suggestion mode
if (oInput._oList instanceof Table) {
oInput._oList.removeSelections(true);
} else {
oInput._oList.destroyItems();
}
}).attachBeforeOpen(function() {
oInput._sBeforeSuggest = oInput.getValue();
}))
:
(new Dialog(oInput.getId() + "-popup", {
beginButton : new sap.m.Button(oInput.getId()
+ "-popup-closeButton", {
text : oMessageBundle.getText("MSGBOX_CLOSE"),
press : function() {
oInput._closeSuggestionPopup();
}
}),
stretch : oInput._bFullScreen,
contentHeight : oInput._bFullScreen ? undefined : "20rem",
customHeader : new Bar(oInput.getId()
+ "-popup-header", {
contentMiddle : oInput._oPopupInput.addEventDelegate({onsapenter: function(){
if (!(sap.m.MultiInput && oInput instanceof sap.m.MultiInput)) {
oInput._closeSuggestionPopup();
}
}}, this)
}),
horizontalScrolling : false,
initialFocus : oInput._oPopupInput
}).attachBeforeOpen(function() {
// set the same placeholder and maxLength as the original input
oInput._oPopupInput.setPlaceholder(oInput.getPlaceholder());
oInput._oPopupInput.setMaxLength(oInput.getMaxLength());
}).attachBeforeClose(function(){
// call _getInputValue to apply the maxLength to the typed value
oInput._$input.val(oInput
._getInputValue(oInput._oPopupInput
.getValue()));
oInput.onChange();
if (oInput instanceof sap.m.MultiInput ) {
oInput._validateCurrentText();
}
}).attachAfterClose(function() {
if (oInput instanceof sap.m.MultiInput && oInput._isMultiLineMode) {
oInput._updateTokenizerInMultiInput();
oInput._tokenizerInPopup.destroy();
oInput._showIndicator();
setTimeout(function() {
oInput._setContainerSizes();
}, 0);
}
// only destroy items in simple suggestion mode
if (oInput._oList) {
if (Table && !(oInput._oList instanceof Table)) {
oInput._oList.destroyItems();
} else {
oInput._oList.removeSelections(true);
}
}
}).attachAfterOpen(function() {
var sValue = oInput.getValue();
oInput._oPopupInput.setValue(sValue);
oInput._triggerSuggest(sValue);
refreshListItems(oInput);
}));
oInput._oSuggestionPopup.addStyleClass("sapMInputSuggestionPopup");
// add popup as dependent to also propagate the model and bindings to the content of the popover
oInput.addDependent(oInput._oSuggestionPopup);
if (!oInput._bUseDialog) {
overwritePopover(oInput._oSuggestionPopup, oInput);
}
if (oInput._oList) {
oInput._oSuggestionPopup.addContent(oInput._oList);
}
if (oInput.getShowTableSuggestionValueHelp()) {
oInput._addShowMoreButton();
}
}
function createSuggestionPopupContent(oInput, bTabular) {
// only initialize the content once
if (oInput._oList) {
return;
}
if (!oInput._hasTabularSuggestions() && !bTabular) {
oInput._oList = new List(oInput.getId() + "-popup-list", {
width : "100%",
showNoData : false,
mode : sap.m.ListMode.SingleSelectMaster,
rememberSelections : false,
itemPress : function(oEvent) {
var oListItem = oEvent.getParameter("listItem"),
iCount = oInput._iSetCount,
sNewValue;
// fire suggestion item select event
oInput.fireSuggestionItemSelected({
selectedItem: oListItem._oItem
});
// choose which field should be used for the value
if (iCount !== oInput._iSetCount) {
// if the event handler modified the input value we take this one as new value
sNewValue = oInput.getValue();
} else if (oListItem instanceof sap.m.DisplayListItem) {
// use label for two value suggestions
sNewValue = oListItem.getLabel();
} else {
// otherwise use title
sNewValue = oListItem.getTitle();
}
// update the input field
if (oInput._bUseDialog) {
oInput._oPopupInput.setValue(sNewValue);
oInput._oPopupInput._doSelect();
} else {
// call _getInputValue to apply the maxLength to the typed value
oInput._$input.val(oInput._getInputValue(sNewValue));
oInput.onChange();
}
oInput._iPopupListSelectedIndex = -1;
if (!(oInput._bUseDialog && oInput instanceof sap.m.MultiInput && oInput._isMultiLineMode)) {
oInput._closeSuggestionPopup();
}
if (!sap.ui.Device.support.touch) {
oInput._doSelect();
}
}
});
} else {
// tabular suggestions
// if no custom filter is set we replace the default filter function here
if (oInput._fnFilter === Input._DEFAULTFILTER) {
oInput._fnFilter = Input._DEFAULTFILTER_TABULAR;
}
// if not custom row result function is set we set the default one
if (!oInput._fnRowResultFilter) {
oInput._fnRowResultFilter = Input._DEFAULTRESULT_TABULAR;
}
oInput._oList = oInput._getSuggestionsTable();
if (oInput.getShowTableSuggestionValueHelp()) {
oInput._addShowMoreButton(bTabular);
}
}
if (oInput._oSuggestionPopup) {
if (oInput._bUseDialog) {
// oInput._oList needs to be manually rendered otherwise it triggers a rerendering of the whole
// dialog and may close the opened on screen keyboard
oInput._oSuggestionPopup.addAggregation("content", oInput._oList, true);
var oRenderTarget = oInput._oSuggestionPopup.$("scrollCont")[0];
if (oRenderTarget) {
var rm = sap.ui.getCore().createRenderManager();
rm.renderControl(oInput._oList);
rm.flush(oRenderTarget);
rm.destroy();
}
} else {
oInput._oSuggestionPopup.addContent(oInput._oList);
}
}
}
function destroySuggestionPopup(oInput) {
if (oInput._oSuggestionPopup) {
// if the table is not removed before destroying the popup the table is also destroyed (table needs to stay because we forward the column and row aggregations to the table directly, they would be destroyed as well)
if (oInput._oList instanceof Table) {
oInput._oSuggestionPopup.removeAllContent();
// also remove the button/toolbar aggregation
oInput._removeShowMoreButton();
}
oInput._oSuggestionPopup.destroy();
oInput._oSuggestionPopup = null;
}
// CSN# 1404088/2014: list is not destroyed when it has not been attached to the popup yet
if (oInput._oList instanceof List) {
oInput._oList.destroy();
oInput._oList = null;
}
}
function overwritePopover(oPopover, oInput) {
oPopover.open = function() {
this.openBy(oInput, false, true);
};
// remove animation from popover
oPopover.oPopup.setAnimations(function($Ref, iRealDuration, fnOpened) {
fnOpened();
}, function($Ref, iRealDuration, fnClosed) {
fnClosed();
});
}
function refreshListItems(oInput) {
var bShowSuggestion = oInput.getShowSuggestion();
oInput._iPopupListSelectedIndex = -1;
if (!(bShowSuggestion
&& oInput.getDomRef()
&& (oInput._bUseDialog || oInput.$().hasClass("sapMInputFocused")))
) {
return false;
}
var oItem,
aItems = oInput.getSuggestionItems(),
aTabularRows = oInput.getSuggestionRows(),
sTypedChars = oInput._$input.val() || "",
oList = oInput._oList,
bFilter = oInput.getFilterSuggests(),
aHitItems = [],
iItemsLength = 0,
oPopup = oInput._oSuggestionPopup,
oListItemDelegate = {
ontouchstart : function(oEvent) {
(oEvent.originalEvent || oEvent)._sapui_cancelAutoClose = true;
}
},
oListItem,
i;
// only destroy items in simple suggestion mode
if (oInput._oList) {
if (oInput._oList instanceof Table) {
oList.removeSelections(true);
} else {
//TODO: avoid flickering when !bFilter
oList.destroyItems();
}
}
// hide suggestions list/table if the number of characters is smaller than limit
if (sTypedChars.length < oInput.getStartSuggestion()) {
// when the input has no value, close the Popup when not runs on the phone because the opened dialog on phone shouldn't be closed.
if (!oInput._bUseDialog) {
oInput._iPopupListSelectedIndex = -1;
this.cancelPendingSuggest();
oPopup.close();
} else {
// hide table on phone when value is empty
if (oInput._hasTabularSuggestions() && oInput._oList) {
oInput._oList.addStyleClass("sapMInputSuggestionTableHidden");
}
}
oInput.$("SuggDescr").text(""); // clear suggestion text
oInput.$("inner").removeAttr("aria-haspopup");
oInput.$("inner").removeAttr("aria-activedescendant");
return false;
}
if (oInput._hasTabularSuggestions()) {
// show list on phone (is hidden when search string is empty)
if (oInput._bUseDialog && oInput._oList) {
oInput._oList.removeStyleClass("sapMInputSuggestionTableHidden");
}
// filter tabular items
for (i = 0; i < aTabularRows.length; i++) {
if (!bFilter || oInput._fnFilter(sTypedChars, aTabularRows[i])) {
aTabularRows[i].setVisible(true);
aHitItems.push(aTabularRows[i]);
} else {
aTabularRows[i].setVisible(false);
}
}
} else {
// filter standard items
var bListItem = (aItems[0] instanceof sap.ui.core.ListItem ? true : false);
for (i = 0; i < aItems.length; i++) {
oItem = aItems[i];
if (!bFilter || oInput._fnFilter(sTypedChars, oItem)) {
if (bListItem) {
oListItem = new sap.m.DisplayListItem(oItem.getId() + "-dli");
oListItem.setLabel(oItem.getText());
oListItem.setValue(oItem.getAdditionalText());
} else {
oListItem = new StandardListItem(oItem.getId() + "-sli");
oListItem.setTitle(oItem.getText());
}
oListItem.setType(oItem.getEnabled() ? sap.m.ListType.Active : sap.m.ListType.Inactive);
oListItem._oItem = oItem;
oListItem.addEventDelegate(oListItemDelegate);
aHitItems.push(oListItem);
}
}
}
iItemsLength = aHitItems.length;
var sAriaText = "";
if (iItemsLength > 0) {
// add items to list
if (iItemsLength == 1) {
sAriaText = sap.ui.getCore().getLibraryResourceBundle("sap.m").getText("INPUT_SUGGESTIONS_ONE_HIT");
} else {
sAriaText = sap.ui.getCore().getLibraryResourceBundle("sap.m").getText("INPUT_SUGGESTIONS_MORE_HITS", iItemsLength);
}
oInput.$("inner").attr("aria-haspopup", "true");
if (!oInput._hasTabularSuggestions()) {
for (i = 0; i < iItemsLength; i++) {
oList.addItem(aHitItems[i]);
}
}
if (!oInput._bUseDialog) {
if (oInput._sCloseTimer) {
clearTimeout(oInput._sCloseTimer);
oInput._sCloseTimer = null;
}
if (!oPopup.isOpen() && !oInput._sOpenTimer && (this.getValue().length >= this.getStartSuggestion())) {
oInput._sOpenTimer = setTimeout(function() {
oInput._resizePopup();
oInput._sOpenTimer = null;
oPopup.open();
}, 0);
}
}
} else {
sAriaText = sap.ui.getCore().getLibraryResourceBundle("sap.m").getText("INPUT_SUGGESTIONS_NO_HIT");
oInput.$("inner").removeAttr("aria-haspopup");
oInput.$("inner").removeAttr("aria-activedescendant");
if (!oInput._bUseDialog) {
if (oPopup.isOpen()) {
oInput._sCloseTimer = setTimeout(function() {
oInput._iPopupListSelectedIndex = -1;
oInput.cancelPendingSuggest();
oPopup.close();
}, 0);
}
} else {
// hide table on phone when there are no items to display
if (oInput._hasTabularSuggestions() && oInput._oList) {
oInput._oList.addStyleClass("sapMInputSuggestionTableHidden");
}
}
}
// update Accessibility text for suggestion
oInput.$("SuggDescr").text(sAriaText);
}
})();
Input.prototype.onfocusin = function(oEvent) {
InputBase.prototype.onfocusin.apply(this, arguments);
this.$().addClass("sapMInputFocused");
// fires suggest event when startSuggestion is set to 0 and input has no text
if (!this._bPopupHasFocus && !this.getStartSuggestion() && !this.getValue()) {
this._triggerSuggest(this.getValue());
}
this._bPopupHasFocus = undefined;
};
/**
* Register F4 to trigger the valueHelpRequest event
* @private
*/
Input.prototype.onsapshow = function (oEvent) {
if (!this.getEnabled() || !this.getEditable() || !this.getShowValueHelp()) {
return;
}
this.fireValueHelpRequest({fromSuggestions: false});
oEvent.preventDefault();
oEvent.stopPropagation();
};
Input.prototype.onsaphide = Input.prototype.onsapshow;
Input.prototype.onsapselect = function(oEvent) {
this._fireValueHelpRequestForValueHelpOnly();
};
Input.prototype.onfocusout = function(oEvent) {
InputBase.prototype.onfocusout.apply(this, arguments);
this.$().removeClass("sapMInputFocused");
this.closeValueStateMessage(this);
};
Input.prototype._hasTabularSuggestions = function() {
return !!(this.getAggregation("suggestionColumns") && this.getAggregation("suggestionColumns").length);
};
/* lazy loading of the suggestions table */
Input.prototype._getSuggestionsTable = function() {
var that = this;
if (!this._oSuggestionTable) {
this._oSuggestionTable = new Table(this.getId() + "-popup-table", {
mode: sap.m.ListMode.SingleSelectMaster,
showNoData: false,
showSeparators: "All",
width: "100%",
enableBusyIndicator: false,
rememberSelections : false,
selectionChange: function (oEvent) {
var oInput = that,
iCount = oInput._iSetCount,
oSelectedListItem = oEvent.getParameter("listItem"),
sNewValue;
// fire suggestion item select event
that.fireSuggestionItemSelected({
selectedRow : oSelectedListItem
});
// choose which field should be used for the value
if (iCount !== oInput._iSetCount) {
// if the event handler modified the input value we take this one as new value
sNewValue = oInput.getValue();
} else {
// for tabular suggestions we call a result filter function
sNewValue = that._fnRowResultFilter(oSelectedListItem);
}
// update the input field
if (that._bUseDialog) {
that._oPopupInput.setValue(sNewValue);
that._oPopupInput._doSelect();
} else {
// call _getInputValue to apply the maxLength to the typed value
that._$input.val(that._getInputValue(sNewValue));
that.onChange();
}
that._iPopupListSelectedIndex = -1;
if (!(oInput._bUseDialog && oInput instanceof sap.m.MultiInput && oInput._isMultiLineMode)) {
oInput._closeSuggestionPopup();
}
if (!sap.ui.Device.support.touch) {
that._doSelect();
}
}
});
// initially hide the table on phone
if (this._bUseDialog) {
this._oSuggestionTable.addStyleClass("sapMInputSuggestionTableHidden");
}
this._oSuggestionTable.updateItems = function() {
Table.prototype.updateItems.apply(this, arguments);
that._refreshItemsDelayed();
return this;
};
}
return this._oSuggestionTable;
};
Input.prototype._fireSuggestionItemSelectedEvent = function () {
if (this._iPopupListSelectedIndex >= 0) {
var oSelectedListItem = this._oList.getItems()[this._iPopupListSelectedIndex];
if (oSelectedListItem) {
if (sap.m.ColumnListItem && oSelectedListItem instanceof sap.m.ColumnListItem) {
this.fireSuggestionItemSelected({selectedRow : oSelectedListItem});
} else {
this.fireSuggestionItemSelected({selectedItem : oSelectedListItem._oItem});
}
}
this._iPopupListSelectedIndex = -1;
}
};
/* =========================================================== */
/* begin: forward aggregation methods to table */
/* =========================================================== */
/*
* Forwards a function call to a managed object based on the aggregation name.
* If the name is items, it will be forwarded to the table, otherwise called
* locally
* @private
* @param {string} sFunctionName the name of the function to be called
* @param {string} sAggregationName the name of the aggregation asociated
* @returns {mixed} the return type of the called function
*/
Input.prototype._callMethodInManagedObject = function(sFunctionName, sAggregationName) {
var aArgs = Array.prototype.slice.call(arguments),
oSuggestionsTable;
if (sAggregationName === "suggestionColumns") {
// apply to the internal table (columns)
oSuggestionsTable = this._getSuggestionsTable();
return oSuggestionsTable[sFunctionName].apply(oSuggestionsTable, ["columns"].concat(aArgs.slice(2)));
} else if (sAggregationName === "suggestionRows") {
// apply to the internal table (rows = table items)
oSuggestionsTable = this._getSuggestionsTable();
return oSuggestionsTable[sFunctionName].apply(oSuggestionsTable, ["items"].concat(aArgs.slice(2)));
} else {
// apply to this control
return sap.ui.core.Control.prototype[sFunctionName].apply(this, aArgs .slice(1));
}
};
Input.prototype.validateAggregation = function(sAggregationName, oObject, bMultiple) {
return this._callMethodInManagedObject("validateAggregation", sAggregationName, oObject, bMultiple);
};
Input.prototype.setAggregation = function(sAggregationName, oObject, bSuppressInvalidate) {
this._callMethodInManagedObject("setAggregation", sAggregationName, oObject, bSuppressInvalidate);
return this;
};
Input.prototype.getAggregation = function(sAggregationName, oDefaultForCreation) {
return this._callMethodInManagedObject("getAggregation", sAggregationName, oDefaultForCreation);
};
Input.prototype.indexOfAggregation = function(sAggregationName, oObject) {
return this._callMethodInManagedObject("indexOfAggregation", sAggregationName, oObject);
};
Input.prototype.insertAggregation = function(sAggregationName, oObject, iIndex, bSuppressInvalidate) {
this._callMethodInManagedObject("insertAggregation", sAggregationName, oObject, iIndex, bSuppressInvalidate);
return this;
};
Input.prototype.addAggregation = function(sAggregationName, oObject, bSuppressInvalidate) {
this._callMethodInManagedObject("addAggregation", sAggregationName,oObject, bSuppressInvalidate);
return this;
};
Input.prototype.removeAggregation = function(sAggregationName, oObject, bSuppressInvalidate) {
return this._callMethodInManagedObject("removeAggregation", sAggregationName, oObject, bSuppressInvalidate);
};
Input.prototype.removeAllAggregation = function(sAggregationName, bSuppressInvalidate) {
return this._callMethodInManagedObject("removeAllAggregation", sAggregationName, bSuppressInvalidate);
};
Input.prototype.destroyAggregation = function(sAggregationName, bSuppressInvalidate) {
this._callMethodInManagedObject("destroyAggregation", sAggregationName, bSuppressInvalidate);
return this;
};
Input.prototype.getBinding = function(sAggregationName) {
return this._callMethodInManagedObject("getBinding", sAggregationName);
};
Input.prototype.getBindingInfo = function(sAggregationName) {
return this._callMethodInManagedObject("getBindingInfo", sAggregationName);
};
Input.prototype.getBindingPath = function(sAggregationName) {
return this._callMethodInManagedObject("getBindingPath", sAggregationName);
};
Input.prototype.clone = function() {
var oInputClone = sap.ui.core.Control.prototype.clone.apply(this, arguments),
bindingInfo;
// add suggestion columns
bindingInfo = this.getBindingInfo("suggestionColumns");
if (bindingInfo) {
oInputClone.bindAggregation("suggestionColumns", bindingInfo);
} else {
this.getSuggestionColumns().forEach(function(oColumn){
oInputClone.addSuggestionColumn(oColumn.clone(), true);
});
}
// add suggestion rows
bindingInfo = this.getBindingInfo("suggestionRows");
if (bindingInfo) {
oInputClone.bindAggregation("suggestionRows", bindingInfo);
} else {
this.getSuggestionRows().forEach(function(oRow){
oInputClone.addSuggestionRow(oRow.clone(), true);
});
}
return oInputClone;
};
/* =========================================================== */
/* end: forward aggregation methods to table */
/* =========================================================== */
/**
* Setter for property <code>value</code>.
*
* Default value is empty/<code>undefined</code>.
*
* @param {string} sValue New value for property <code>value</code>.
* @return {sap.m.Input} <code>this</code> to allow method chaining.
* @public
*/
Input.prototype.setValue = function(sValue) {
this._iSetCount++;
InputBase.prototype.setValue.call(this, sValue);
return this;
};
/**
* @see {sap.ui.core.Control#getAccessibilityInfo}
* @protected
*/
Input.prototype.getAccessibilityInfo = function() {
var oInfo = InputBase.prototype.getAccessibilityInfo.apply(this, arguments);
oInfo.description = ((oInfo.description || "") + " " + this.getDescription()).trim();
return oInfo;
};
/**
* Getter for property <code>valueStateText</code>.
* The text which is shown in the value state message popup. If not specfied a default text is shown. This property is already available for sap.m.Input since 1.16.0.
*
* Default value is empty/<code>undefined</code>
*
* @return {string} the value of property <code>valueStateText</code>
* @public
* @since 1.16
* @name sap.m.Input#getValueStateText
* @function
*/
/**
* Setter for property <code>valueStateText</code>.
*
* Default value is empty/<code>undefined</code>
*
* @param {string} sValueStateText new value for property <code>valueStateText</code>
* @return {sap.m.InputBase} <code>this</code> to allow method chaining
* @public
* @since 1.16
* @name sap.m.Input#setValueStateText
* @function
*/
/**
* Getter for property <code>showValueStateMessage</code>.
* Whether the value state message should be shown. This property is already available for sap.m.Input since 1.16.0.
*
* Default value is <code>true</code>
*
* @return {boolean} the value of property <code>showValueStateMessage</code>
* @public
* @since 1.16
* @name sap.m.Input#getShowValueStateMessage
* @function
*/
/**
* Setter for property <code>showValueStateMessage</code>.
*
* Default value is <code>true</code>
*
* @param {boolean} bShowValueStateMessage new value for property <code>showValueStateMessage</code>
* @return {sap.m.InputBase} <code>this</code> to allow method chaining
* @public
* @since 1.16
* @name sap.m.Input#setShowValueStateMessage
* @function
*/
return Input;
}, /* bExport= */ true);
|
/**
* Module dependencies.
*/
var start = require('./common')
, should = require('should')
, mongoose = require('./common').mongoose
, Schema = mongoose.Schema
, random = require('../lib/utils').random
, MongooseBuffer = mongoose.Types.Buffer;
// can't index Buffer fields yet
function valid (v) {
return !v || v.length > 10;
}
var subBuf = new Schema({
name: String
, buf: { type: Buffer, validate: [valid, 'valid failed'], required: true }
});
var UserBuffer = new Schema({
name: String
, serial: Buffer
, array: [Buffer]
, required: { type: Buffer, required: true, index: true }
, sub: [subBuf]
});
// Dont put indexed models on the default connection, it
// breaks index.test.js tests on a "pure" default conn.
// mongoose.model('UserBuffer', UserBuffer);
/**
* Test.
*/
module.exports = {
'test that a mongoose buffer behaves and quacks like an buffer': function(){
var a = new MongooseBuffer;
a.should.be.an.instanceof(Buffer);
a.should.be.an.instanceof(MongooseBuffer);
Buffer.isBuffer(a).should.be.true;
var a = new MongooseBuffer([195, 188, 98, 101, 114]);
var b = new MongooseBuffer("buffer shtuffs are neat");
var c = new MongooseBuffer('aGVsbG8gd29ybGQ=', 'base64');
a.toString('utf8').should.equal('über');
b.toString('utf8').should.equal('buffer shtuffs are neat');
c.toString('utf8').should.equal('hello world');
},
'buffer validation': function () {
var db = start()
, User = db.model('UserBuffer', UserBuffer, 'usersbuffer_' + random());
User.on('index', function () {
var t = new User({
name: 'test validation'
});
t.validate(function (err) {
err.message.should.eql('Validation failed');
err.errors.required.type.should.equal('required');
t.required = 20;
t.save(function (err) {
err.name.should.eql('CastError');
err.type.should.eql('buffer');
err.value.should.equal(20);
err.message.should.eql('Cast to buffer failed for value "20"');
t.required = new Buffer("hello");
t.sub.push({ name: 'Friday Friday' });
t.save(function (err) {
err.message.should.eql('Validation failed');
err.errors.buf.type.should.equal('required');
t.sub[0].buf = new Buffer("well well");
t.save(function (err) {
err.message.should.eql('Validation failed');
err.errors.buf.type.should.equal('valid failed');
t.sub[0].buf = new Buffer("well well well");
t.validate(function (err) {
db.close();
should.strictEqual(null, err);
});
});
});
});
});
})
},
'buffer storage': function(){
var db = start()
, User = db.model('UserBuffer', UserBuffer, 'usersbuffer_' + random());
User.on('index', function () {
var sampleBuffer = new Buffer([123, 223, 23, 42, 11]);
var tj = new User({
name: 'tj'
, serial: sampleBuffer
, required: new Buffer(sampleBuffer)
});
tj.save(function (err) {
should.equal(null, err);
User.find({}, function (err, users) {
db.close();
should.equal(null, err);
users.should.have.length(1);
var user = users[0];
var base64 = sampleBuffer.toString('base64');
should.equal(base64,
user.serial.toString('base64'), 'buffer mismatch');
should.equal(base64,
user.required.toString('base64'), 'buffer mismatch');
});
});
});
},
'test write markModified': function(){
var db = start()
, User = db.model('UserBuffer', UserBuffer, 'usersbuffer_' + random());
User.on('index', function () {
var sampleBuffer = new Buffer([123, 223, 23, 42, 11]);
var tj = new User({
name: 'tj'
, serial: sampleBuffer
, required: sampleBuffer
});
tj.save(function (err) {
should.equal(null, err);
tj.serial.write('aa', 1, 'ascii');
tj.isModified('serial').should.be.true;
tj.save(function (err) {
should.equal(null, err);
User.findById(tj._id, function (err, user) {
db.close();
should.equal(null, err);
var expectedBuffer = new Buffer([123, 97, 97, 42, 11]);
should.equal(expectedBuffer.toString('base64'),
user.serial.toString('base64'), 'buffer mismatch');
tj.isModified('required').should.be.false;
tj.serial.copy(tj.required, 1);
tj.isModified('required').should.be.true;
should.equal('e3thYSo=', tj.required.toString('base64'));
// buffer method tests
var fns = {
'writeUInt8': function () {
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeUInt8(0x3, 0, 'big');
tj.isModified('required').should.be.true;
}
, 'writeUInt16': function () {
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeUInt16(0xbeef, 0, 'little');
tj.isModified('required').should.be.true;
}
, 'writeUInt16LE': function () {
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeUInt16LE(0xbeef, 0);
tj.isModified('required').should.be.true;
}
, 'writeUInt16BE': function () {
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeUInt16BE(0xbeef, 0);
tj.isModified('required').should.be.true;
}
, 'writeUInt32': function () {
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeUInt32(0xfeedface, 0, 'little');
tj.isModified('required').should.be.true;
}
, 'writeUInt32LE': function () {
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeUInt32LE(0xfeedface, 0);
tj.isModified('required').should.be.true;
}
, 'writeUInt32BE': function () {
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeUInt32BE(0xfeedface, 0);
tj.isModified('required').should.be.true;
}
, 'writeInt8': function () {
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeInt8(-5, 0, 'big');
tj.isModified('required').should.be.true;
}
, 'writeInt16': function () {
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeInt16(0x0023, 2, 'little');
tj.isModified('required').should.be.true;
tj.required[2].should.eql(0x23);
tj.required[3].should.eql(0x00);
}
, 'writeInt16LE': function () {
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeInt16LE(0x0023, 2);
tj.isModified('required').should.be.true;
tj.required[2].should.eql(0x23);
tj.required[3].should.eql(0x00);
}
, 'writeInt16BE': function () {
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeInt16BE(0x0023, 2);
tj.isModified('required').should.be.true;
}
, 'writeInt32': function () {
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeInt32(0x23, 0, 'big');
tj.isModified('required').should.be.true;
tj.required[0].should.eql(0x00);
tj.required[1].should.eql(0x00);
tj.required[2].should.eql(0x00);
tj.required[3].should.eql(0x23);
tj.required = new Buffer(8);
}
, 'writeInt32LE': function () {
tj.required = new Buffer(8);
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeInt32LE(0x23, 0);
tj.isModified('required').should.be.true;
}
, 'writeInt32BE': function () {
tj.required = new Buffer(8);
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeInt32BE(0x23, 0);
tj.isModified('required').should.be.true;
tj.required[0].should.eql(0x00);
tj.required[1].should.eql(0x00);
tj.required[2].should.eql(0x00);
tj.required[3].should.eql(0x23);
}
, 'writeFloat': function () {
tj.required = new Buffer(16);
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeFloat(2.225073858507201e-308, 0, 'big');
tj.isModified('required').should.be.true;
tj.required[0].should.eql(0x00);
tj.required[1].should.eql(0x0f);
tj.required[2].should.eql(0xff);
tj.required[3].should.eql(0xff);
tj.required[4].should.eql(0xff);
tj.required[5].should.eql(0xff);
tj.required[6].should.eql(0xff);
tj.required[7].should.eql(0xff);
}
, 'writeFloatLE': function () {
tj.required = new Buffer(16);
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeFloatLE(2.225073858507201e-308, 0);
tj.isModified('required').should.be.true;
}
, 'writeFloatBE': function () {
tj.required = new Buffer(16);
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeFloatBE(2.225073858507201e-308, 0);
tj.isModified('required').should.be.true;
}
, 'writeDoubleLE': function () {
tj.required = new Buffer(8);
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeDoubleLE(0xdeadbeefcafebabe, 0);
tj.isModified('required').should.be.true;
}
, 'writeDoubleBE': function () {
tj.required = new Buffer(8);
reset(tj);
tj.isModified('required').should.be.false;
tj.required.writeDoubleBE(0xdeadbeefcafebabe, 0);
tj.isModified('required').should.be.true;
}
, 'fill': function () {
tj.required = new Buffer(8);
reset(tj);
tj.isModified('required').should.be.false;
tj.required.fill(0);
tj.isModified('required').should.be.true;
for (var i = 0; i < tj.required.length; i++) {
tj.required[i].should.eql(0);
}
}
, 'set': function () {
reset(tj);
tj.isModified('required').should.be.false;
tj.required.set(0, 1);
tj.isModified('required').should.be.true;
}
};
var keys = Object.keys(fns)
, i = keys.length
, key
while (i--) {
key = keys[i];
if (Buffer.prototype[key]) {
fns[key]();
}
}
});
});
});
});
function reset (model) {
// internal
model._activePaths.clear('modify');
model.schema.requiredPaths.forEach(function (path) {
model._activePaths.require(path);
});
}
}
};
|
/**
* 303 (See Other) Handler for Rstudio-api (passes parameters)
*
* Usage:
* return res.rstudio_redirect(uri)
*
* e.g.:
* ```
* return res.rstudio_redirect(uri)
* ```
*
* NOTE:
* This response is needed if the viewer_pane parameter, the Rstudio_port and/or the session_shared_secret for Rstudio or important
* This is for example the case when refering to topics, as topic/show.ejs has viewer_pane-specifid code.
*/
module.exports = function rstudio_redirect(code,uri) {
// Get access to `req`, `res`, & `sails`
var req = this.req;
var res = this.res;
var sails = req._sails;
var fromRstudio = req.headers['x-rstudio-ajax'] === 'true';
var urlParams= ['viewer_pane'].map(function(p) {
return req.param(p) ? p + '=' + encodeURIComponent(req.param(p)) : '';
}).filter(function(p) {
return p !== '';
}).join('&');
if(uri.indexOf('?')>0){
var redirectURL = uri.substring(0,uri.indexOf('?'))
}
else{
var redirectURL = uri
}
sails.log.silly('res.rstudio_redirect() :: Sending '+code+ ' (redirect) response');
if(fromRstudio) {
res.location(redirectURL);
res.set('X-RStudio-Redirect', redirectURL);
res.json({ status: 'success'});
} else {
res.redirect(code,uri+ (urlParams.length > 0 ? "?"+ urlParams : ""));
}
};
|
var myFSAPI = require('./myFSapi');
var champions = require('./champions.json');
var config = require('./../config.json');
function getChampion(id) {
var name = '';
Object.keys(champions.data).forEach(function(key) {
if (champions.data[key].key == id) {
name = champions.data[key].id;
}
});
return name;
}
function writeResult(myjson, file, cb) {
myFSAPI.writeFile(file, myjson, function(err) {
if (err) {
throw err;
}
console.log('saved');
cb();
});
}
module.exports = {
start: start
};
function MyAfter(amount, cb) {
this.amount = amount;
this.cb = cb;
this.current = 0;
this.called = function () {
this.current++;
if (this.current === this.amount) {
cb();
}
};
}
function start(users, next) {
console.log('testssssssssss');
var MyRequestCounter = new MyAfter(users.length, function () {
myFSAPI.readFile(config.team_stats.fileData.outputFilePath + 'tmpTeamResult' + config.request.teamid + '.json', function(err, data) {
if (err) {
throw err;
}
var myDataTwo = JSON.parse(data);
if (myDataTwo.additionaldata.bans.length) {
for (var i = 0; i < myDataTwo.additionaldata.bans.length; i++) {
if (myDataTwo.additionaldata.bans[i] && myDataTwo.additionaldata.bans[i].length) {
for (var k = 0; k < myDataTwo.additionaldata.bans[i].length; k++) {
myDataTwo.additionaldata.bans[i][k].championId = getChampion(myDataTwo.additionaldata.bans[i][k].championId);
}
}
}
}
writeResult(myDataTwo, config.team_stats.fileData.superOutputFilePath + 'StatsForTeam' + config.request.teamid + '.json', function () {
console.log('Done writing team stats');
next(users);
// here
});
});
});
users.forEach(function (user, index) {
myFSAPI.readFile(config.player_stats.fileData.outputFilePath + 'tmpUserResult' + user.user + '.json', function(err, data) {
if (err) {
throw err;
}
var myData = JSON.parse(data);
for (var i = 0; i < myData.additionaldata.championId.length; i++) {
myData.additionaldata.championId[i] = getChampion(myData.additionaldata.championId[i]);
}
writeResult(myData, config.player_stats.fileData.superOutputFilePath + 'StatsForUser' + user.user + '.json', function() {
MyRequestCounter.called();
console.log('Done writing user stats', user.user);
});
});
});
}
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/**
* SCEditor
* http://www.sceditor.com/
*
* Copyright (C) 2014, Sam Clarke (samclarke.com)
*
* SCEditor is licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* @fileoverview SCEditor - A lightweight WYSIWYG BBCode and HTML editor
* @author Sam Clarke
* @requires jQuery
*/
!(__WEBPACK_AMD_DEFINE_RESULT__ = function (require) {
'use strict';
var $ = __webpack_require__(1);
var SCEditor = __webpack_require__(2);
var PluginManager = __webpack_require__(3);
var browser = __webpack_require__(6);
var escape = __webpack_require__(7);
// For backwards compatibility
$.sceditor = SCEditor;
SCEditor.commands = __webpack_require__(9);
SCEditor.defaultOptions = __webpack_require__(10);
SCEditor.RangeHelper = __webpack_require__(4);
SCEditor.dom = __webpack_require__(5);
SCEditor.ie = browser.ie;
SCEditor.ios = browser.ios;
SCEditor.isWysiwygSupported = browser.isWysiwygSupported;
SCEditor.regexEscape = escape.regex;
SCEditor.escapeEntities = escape.entities;
SCEditor.escapeUriScheme = escape.uriScheme;
SCEditor.PluginManager = PluginManager;
SCEditor.plugins = PluginManager.plugins;
/**
* Creates an instance of sceditor on all textareas
* matched by the jQuery selector.
*
* If options is set to "state" it will return bool value
* indicating if the editor has been initialised on the
* matched textarea(s). If there is only one textarea
* it will return the bool value for that textarea.
* If more than one textarea is matched it will
* return an array of bool values for each textarea.
*
* If options is set to "instance" it will return the
* current editor instance for the textarea(s). Like the
* state option, if only one textarea is matched this will
* return just the instance for that textarea. If more than
* one textarea is matched it will return an array of
* instances each textarea.
*
* @param {Object|String} options Should either be an Object of options or
* the strings "state" or "instance"
* @return {this|Array|jQuery.sceditor|Bool}
*/
$.fn.sceditor = function (options) {
var $this, instance,
ret = [];
options = options || {};
if (!options.runWithoutWysiwygSupport && !browser.isWysiwygSupported) {
return;
}
this.each(function () {
$this = this.jquery ? this : $(this);
instance = $this.data('sceditor');
// Don't allow the editor to be initialised
// on it's own source editor
if ($this.parents('.sceditor-container').length > 0) {
return;
}
// Add state of instance to ret if that is what options is set to
if (options === 'state') {
ret.push(!!instance);
} else if (options === 'instance') {
ret.push(instance);
} else if (!instance) {
/*jshint -W031*/
(new SCEditor(this, options));
}
});
// If nothing in the ret array then must be init so return this
if (!ret.length) {
return this;
}
return ret.length === 1 ? ret[0] : $(ret);
};
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = jQuery;
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_RESULT__ = function (require) {
'use strict';
var $ = __webpack_require__(1);
var PluginManager = __webpack_require__(3);
var RangeHelper = __webpack_require__(4);
var dom = __webpack_require__(5);
var escape = __webpack_require__(7);
var browser = __webpack_require__(6);
var _tmpl = __webpack_require__(8);
var globalWin = window;
var globalDoc = document;
var $globalWin = $(globalWin);
var $globalDoc = $(globalDoc);
var IE_VER = browser.ie;
// In IE < 11 a BR at the end of a block level element
// causes a line break. In all other browsers it's collapsed.
var IE_BR_FIX = IE_VER && IE_VER < 11;
/**
* SCEditor - A lightweight WYSIWYG editor
*
* @param {Element} el The textarea to be converted
* @return {Object} options
* @class sceditor
* @name jQuery.sceditor
*/
var SCEditor = function (el, options) {
/**
* Alias of this
*
* @private
*/
var base = this;
/**
* The textarea element being replaced
*
* @private
*/
var original = el.get ? el.get(0) : el;
var $original = $(original);
/**
* The div which contains the editor and toolbar
*
* @private
*/
var $editorContainer;
/**
* The editors toolbar
*
* @private
*/
var $toolbar;
/**
* The editors iframe which should be in design mode
*
* @private
*/
var $wysiwygEditor;
var wysiwygEditor;
/**
* The WYSIWYG editors body element
*
* @private
*/
var $wysiwygBody;
/**
* The WYSIWYG editors document
*
* @private
*/
var $wysiwygDoc;
/**
* The editors textarea for viewing source
*
* @private
*/
var $sourceEditor;
var sourceEditor;
/**
* The current dropdown
*
* @private
*/
var $dropdown;
/**
* Store the last cursor position. Needed for IE because it forgets
*
* @private
*/
var lastRange;
/**
* The editors locale
*
* @private
*/
var locale;
/**
* Stores a cache of preloaded images
*
* @private
* @type {Array}
*/
var preLoadCache = [];
/**
* The editors rangeHelper instance
*
* @type {jQuery.sceditor.rangeHelper}
* @private
*/
var rangeHelper;
/**
* Tags which require the new line fix
*
* @type {Array}
* @private
*/
var requireNewLineFix = [];
/**
* An array of button state handlers
*
* @type {Array}
* @private
*/
var btnStateHandlers = [];
/**
* Plugin manager instance
*
* @type {jQuery.sceditor.PluginManager}
* @private
*/
var pluginManager;
/**
* The current node containing the selection/caret
*
* @type {Node}
* @private
*/
var currentNode;
/**
* The first block level parent of the current node
*
* @type {node}
* @private
*/
var currentBlockNode;
/**
* The current node selection/caret
*
* @type {Object}
* @private
*/
var currentSelection;
/**
* Used to make sure only 1 selection changed
* check is called every 100ms.
*
* Helps improve performance as it is checked a lot.
*
* @type {Boolean}
* @private
*/
var isSelectionCheckPending;
/**
* If content is required (equivalent to the HTML5 required attribute)
*
* @type {Boolean}
* @private
*/
var isRequired;
/**
* The inline CSS style element. Will be undefined
* until css() is called for the first time.
*
* @type {HTMLElement}
* @private
*/
var inlineCss;
/**
* Object containing a list of shortcut handlers
*
* @type {Object}
* @private
*/
var shortcutHandlers = {};
/**
* An array of all the current emoticons.
*
* Only used or populated when emoticonsCompat is enabled.
*
* @type {Array}
* @private
*/
var currentEmoticons = [];
/**
* Cache of the current toolbar buttons
*
* @type {Object}
* @private
*/
var toolbarButtons = {};
/**
* If the current autoUpdate action is canceled.
*
* @type {Boolean}
* @private
*/
var autoUpdateCanceled;
/**
* Private functions
* @private
*/
var init,
replaceEmoticons,
handleCommand,
saveRange,
initEditor,
initPlugins,
initLocale,
initToolBar,
initOptions,
initEvents,
initCommands,
initResize,
initEmoticons,
getWysiwygDoc,
handlePasteEvt,
handlePasteData,
handleKeyDown,
handleBackSpace,
handleKeyPress,
handleFormReset,
handleMouseDown,
handleEvent,
handleDocumentClick,
handleWindowResize,
updateToolBar,
updateActiveButtons,
sourceEditorSelectedText,
appendNewLine,
checkSelectionChanged,
checkNodeChanged,
autofocus,
emoticonsKeyPress,
emoticonsCheckWhitespace,
currentStyledBlockNode,
triggerValueChanged,
valueChangedBlur,
valueChangedKeyUp,
autoUpdate;
/**
* All the commands supported by the editor
* @name commands
* @memberOf jQuery.sceditor.prototype
*/
base.commands = $.extend(
true,
{},
(options.commands || SCEditor.commands)
);
/**
* Options for this editor instance
* @name opts
* @memberOf jQuery.sceditor.prototype
*/
base.opts = options = $.extend({}, SCEditor.defaultOptions, options);
/**
* Creates the editor iframe and textarea
* @private
*/
init = function () {
$original.data('sceditor', base);
// Clone any objects in options
$.each(options, function (key, val) {
if ($.isPlainObject(val)) {
options[key] = $.extend(true, {}, val);
}
});
// Load locale
if (options.locale && options.locale !== 'en') {
initLocale();
}
$editorContainer = $('<div class="sceditor-container" />')
.insertAfter($original)
.css('z-index', options.zIndex);
// Add IE version to the container to allow IE specific CSS
// fixes without using CSS hacks or conditional comments
if (IE_VER) {
$editorContainer.addClass('ie ie' + IE_VER);
}
isRequired = !!$original.attr('required');
$original.removeAttr('required');
// create the editor
initPlugins();
initEmoticons();
initToolBar();
initEditor(!!options.startInSourceMode);
initCommands();
initOptions();
initEvents();
// force into source mode if is a browser that can't handle
// full editing
if (!browser.isWysiwygSupported) {
base.toggleSourceMode();
}
updateActiveButtons();
var loaded = function () {
$globalWin.off('load', loaded);
if (options.autofocus) {
autofocus();
}
if (options.autoExpand) {
base.expandToContent();
}
// Page width might have changed after CSS is loaded so
// call handleWindowResize to update any % based dimensions
handleWindowResize();
pluginManager.call('ready');
};
$globalWin.on('load', loaded);
if (globalDoc.readyState && globalDoc.readyState === 'complete') {
loaded();
}
};
initPlugins = function () {
var plugins = options.plugins;
plugins = plugins ? plugins.toString().split(',') : [];
pluginManager = new PluginManager(base);
$.each(plugins, function (idx, plugin) {
pluginManager.register($.trim(plugin));
});
};
/**
* Init the locale variable with the specified locale if possible
* @private
* @return void
*/
initLocale = function () {
var lang;
locale = SCEditor.locale[options.locale];
if (!locale) {
lang = options.locale.split('-');
locale = SCEditor.locale[lang[0]];
}
// Locale DateTime format overrides any specified in the options
if (locale && locale.dateFormat) {
options.dateFormat = locale.dateFormat;
}
};
/**
* Creates the editor iframe and textarea
* @param {boolean} startInSourceMode Force loading the editor in this
* mode
* @private
*/
initEditor = function (startInSourceMode) {
var doc, tabIndex;
$sourceEditor = $('<textarea></textarea>');
$wysiwygEditor = $(
'<iframe frameborder="0" allowfullscreen="true"></iframe>'
);
/* This needs to be done right after they are created because,
* for any reason, the user may not want the value to be tinkered
* by any filters.
*/
if (startInSourceMode) {
$editorContainer.addClass('sourceMode');
$wysiwygEditor.hide();
} else {
$editorContainer.addClass('wysiwygMode');
$sourceEditor.hide();
}
if (!options.spellcheck) {
$sourceEditor.attr('spellcheck', 'false');
}
/*jshint scripturl: true*/
if (globalWin.location.protocol === 'https:') {
$wysiwygEditor.attr('src', 'javascript:false');
}
// Add the editor to the container
$editorContainer.append($wysiwygEditor).append($sourceEditor);
wysiwygEditor = $wysiwygEditor[0];
sourceEditor = $sourceEditor[0];
base.dimensions(
options.width || $original.width(),
options.height || $original.height()
);
doc = getWysiwygDoc();
doc.open();
doc.write(_tmpl('html', {
// Add IE version class to the HTML element so can apply
// conditional styling without CSS hacks
attrs: IE_VER ? ' class="ie ie' + IE_VER + '"' : '',
spellcheck: options.spellcheck ? '' : 'spellcheck="false"',
charset: options.charset,
style: options.style
}));
doc.close();
$wysiwygDoc = $(doc);
$wysiwygBody = $(doc.body);
base.readOnly(!!options.readOnly);
// iframe overflow fix for iOS, also fixes an IE issue with the
// editor not getting focus when clicking inside
if (browser.ios || IE_VER) {
$wysiwygBody.height('100%');
if (!IE_VER) {
$wysiwygBody.on('touchend', base.focus);
}
}
tabIndex = $original.attr('tabindex');
$sourceEditor.attr('tabindex', tabIndex);
$wysiwygEditor.attr('tabindex', tabIndex);
rangeHelper = new RangeHelper(wysiwygEditor.contentWindow);
// load any textarea value into the editor
base.val($original.hide().val());
};
/**
* Initialises options
* @private
*/
initOptions = function () {
// auto-update original textbox on blur if option set to true
if (options.autoUpdate) {
$wysiwygBody.on('blur', autoUpdate);
$sourceEditor.on('blur', autoUpdate);
}
if (options.rtl === null) {
options.rtl = $sourceEditor.css('direction') === 'rtl';
}
base.rtl(!!options.rtl);
if (options.autoExpand) {
$wysiwygDoc.on('keyup', base.expandToContent);
}
if (options.resizeEnabled) {
initResize();
}
$editorContainer.attr('id', options.id);
base.emoticons(options.emoticonsEnabled);
};
/**
* Initialises events
* @private
*/
initEvents = function () {
var CHECK_SELECTION_EVENTS = IE_VER ?
'selectionchange' :
'keyup focus blur contextmenu mouseup touchend click';
var EVENTS_TO_FORWARD = 'keydown keyup keypress ' +
'focus blur contextmenu';
$globalDoc.click(handleDocumentClick);
$(original.form)
.on('reset', handleFormReset)
.submit(base.updateOriginal);
$globalWin.on('resize orientationChanged', handleWindowResize);
$wysiwygBody
.keypress(handleKeyPress)
.keydown(handleKeyDown)
.keydown(handleBackSpace)
.keyup(appendNewLine)
.blur(valueChangedBlur)
.keyup(valueChangedKeyUp)
.on('paste', handlePasteEvt)
.on(CHECK_SELECTION_EVENTS, checkSelectionChanged)
.on(EVENTS_TO_FORWARD, handleEvent);
if (options.emoticonsCompat && globalWin.getSelection) {
$wysiwygBody.keyup(emoticonsCheckWhitespace);
}
$sourceEditor
.blur(valueChangedBlur)
.keyup(valueChangedKeyUp)
.keydown(handleKeyDown)
.on(EVENTS_TO_FORWARD, handleEvent);
$wysiwygDoc
.mousedown(handleMouseDown)
.blur(valueChangedBlur)
.on(CHECK_SELECTION_EVENTS, checkSelectionChanged)
.on('beforedeactivate keyup mouseup', saveRange)
.keyup(appendNewLine)
.focus(function () {
lastRange = null;
});
$editorContainer
.on('selectionchanged', checkNodeChanged)
.on('selectionchanged', updateActiveButtons)
.on('selectionchanged valuechanged nodechanged', handleEvent);
};
/**
* Creates the toolbar and appends it to the container
* @private
*/
initToolBar = function () {
var $group,
commands = base.commands,
exclude = (options.toolbarExclude || '').split(','),
groups = options.toolbar.split('|');
$toolbar = $('<div class="sceditor-toolbar" unselectable="on" />');
$.each(groups, function (idx, group) {
$group = $('<div class="sceditor-group" />');
$.each(group.split(','), function (idx, commandName) {
var $button, shortcut,
command = commands[commandName];
// The commandName must be a valid command and not excluded
if (!command || $.inArray(commandName, exclude) > -1) {
return;
}
shortcut = command.shortcut;
$button = _tmpl('toolbarButton', {
name: commandName,
dispName: base._(command.name ||
command.tooltip || commandName)
}, true);
$button
.data('sceditor-txtmode', !!command.txtExec)
.data('sceditor-wysiwygmode', !!command.exec)
.toggleClass('disabled', !command.exec)
.mousedown(function () {
// IE < 8 supports unselectable attribute
// so don't need this
if (!IE_VER || IE_VER < 9) {
autoUpdateCanceled = true;
}
})
.click(function () {
var $this = $(this);
if (!$this.hasClass('disabled')) {
handleCommand($this, command);
}
updateActiveButtons();
return false;
});
if (command.tooltip) {
$button.attr(
'title',
base._(command.tooltip) +
(shortcut ? ' (' + shortcut + ')' : '')
);
}
if (shortcut) {
base.addShortcut(shortcut, commandName);
}
if (command.state) {
btnStateHandlers.push({
name: commandName,
state: command.state
});
// exec string commands can be passed to queryCommandState
} else if (typeof command.exec === 'string') {
btnStateHandlers.push({
name: commandName,
state: command.exec
});
}
$group.append($button);
toolbarButtons[commandName] = $button;
});
// Exclude empty groups
if ($group[0].firstChild) {
$toolbar.append($group);
}
});
// Append the toolbar to the toolbarContainer option if given
$(options.toolbarContainer || $editorContainer).append($toolbar);
};
/**
* Creates an array of all the key press functions
* like emoticons, ect.
* @private
*/
initCommands = function () {
$.each(base.commands, function (name, cmd) {
if (cmd.forceNewLineAfter && $.isArray(cmd.forceNewLineAfter)) {
requireNewLineFix = $.merge(
requireNewLineFix,
cmd.forceNewLineAfter
);
}
});
appendNewLine();
};
/**
* Creates the resizer.
* @private
*/
initResize = function () {
var minHeight, maxHeight, minWidth, maxWidth,
mouseMoveFunc, mouseUpFunc,
$grip = $('<div class="sceditor-grip" />'),
// Cover is used to cover the editor iframe so document
// still gets mouse move events
$cover = $('<div class="sceditor-resize-cover" />'),
moveEvents = 'touchmove mousemove',
endEvents = 'touchcancel touchend mouseup',
startX = 0,
startY = 0,
newX = 0,
newY = 0,
startWidth = 0,
startHeight = 0,
origWidth = $editorContainer.width(),
origHeight = $editorContainer.height(),
isDragging = false,
rtl = base.rtl();
minHeight = options.resizeMinHeight || origHeight / 1.5;
maxHeight = options.resizeMaxHeight || origHeight * 2.5;
minWidth = options.resizeMinWidth || origWidth / 1.25;
maxWidth = options.resizeMaxWidth || origWidth * 1.25;
mouseMoveFunc = function (e) {
// iOS uses window.event
if (e.type === 'touchmove') {
e = globalWin.event;
newX = e.changedTouches[0].pageX;
newY = e.changedTouches[0].pageY;
} else {
newX = e.pageX;
newY = e.pageY;
}
var newHeight = startHeight + (newY - startY),
newWidth = rtl ?
startWidth - (newX - startX) :
startWidth + (newX - startX);
if (maxWidth > 0 && newWidth > maxWidth) {
newWidth = maxWidth;
}
if (minWidth > 0 && newWidth < minWidth) {
newWidth = minWidth;
}
if (!options.resizeWidth) {
newWidth = false;
}
if (maxHeight > 0 && newHeight > maxHeight) {
newHeight = maxHeight;
}
if (minHeight > 0 && newHeight < minHeight) {
newHeight = minHeight;
}
if (!options.resizeHeight) {
newHeight = false;
}
if (newWidth || newHeight) {
base.dimensions(newWidth, newHeight);
// The resize cover will not fill the container
// in IE6 unless a height is specified.
if (IE_VER < 7) {
$editorContainer.height(newHeight);
}
}
e.preventDefault();
};
mouseUpFunc = function (e) {
if (!isDragging) {
return;
}
isDragging = false;
$cover.hide();
$editorContainer.removeClass('resizing').height('auto');
$globalDoc.off(moveEvents, mouseMoveFunc);
$globalDoc.off(endEvents, mouseUpFunc);
e.preventDefault();
};
$editorContainer.append($grip);
$editorContainer.append($cover.hide());
$grip.on('touchstart mousedown', function (e) {
// iOS uses window.event
if (e.type === 'touchstart') {
e = globalWin.event;
startX = e.touches[0].pageX;
startY = e.touches[0].pageY;
} else {
startX = e.pageX;
startY = e.pageY;
}
startWidth = $editorContainer.width();
startHeight = $editorContainer.height();
isDragging = true;
$editorContainer.addClass('resizing');
$cover.show();
$globalDoc.on(moveEvents, mouseMoveFunc);
$globalDoc.on(endEvents, mouseUpFunc);
// The resize cover will not fill the container in
// IE6 unless a height is specified.
if (IE_VER < 7) {
$editorContainer.height(startHeight);
}
e.preventDefault();
});
};
/**
* Prefixes and preloads the emoticon images
* @private
*/
initEmoticons = function () {
var emoticon,
emoticons = options.emoticons,
root = options.emoticonsRoot;
if (!$.isPlainObject(emoticons) || !options.emoticonsEnabled) {
return;
}
$.each(emoticons, function (idx, val) {
$.each(val, function (key, url) {
// Prefix emoticon root to emoticon urls
if (root) {
url = {
url: root + (url.url || url),
tooltip: url.tooltip || key
};
emoticons[idx][key] = url;
}
// Preload the emoticon
emoticon = globalDoc.createElement('img');
emoticon.src = url.url || url;
preLoadCache.push(emoticon);
});
});
};
/**
* Autofocus the editor
* @private
*/
autofocus = function () {
var range, txtPos,
doc = $wysiwygDoc[0],
body = $wysiwygBody[0],
node = body.firstChild,
focusEnd = !!options.autofocusEnd;
// Can't focus invisible elements
if (!$editorContainer.is(':visible')) {
return;
}
if (base.sourceMode()) {
txtPos = focusEnd ? sourceEditor.value.length : 0;
if (sourceEditor.setSelectionRange) {
sourceEditor.setSelectionRange(txtPos, txtPos);
} else {
range = sourceEditor.createTextRange();
range.moveEnd('character', txtPos);
range.collapse(false);
range.select();
}
return;
}
dom.removeWhiteSpace(body);
if (focusEnd) {
if (!(node = body.lastChild)) {
node = doc.createElement('p');
$wysiwygBody.append(node);
}
while (node.lastChild) {
node = node.lastChild;
// IE < 11 should place the cursor after the <br> as
// it will show it as a newline. IE >= 11 and all
// other browsers should place the cursor before.
if (!IE_BR_FIX && $(node).is('br') &&
node.previousSibling) {
node = node.previousSibling;
}
}
}
if (doc.createRange) {
range = doc.createRange();
if (!dom.canHaveChildren(node)) {
range.setStartBefore(node);
if (focusEnd) {
range.setStartAfter(node);
}
} else {
range.selectNodeContents(node);
}
} else {
range = body.createTextRange();
range.moveToElementText(node.nodeType !== 3 ?
node : node.parentNode);
}
range.collapse(!focusEnd);
rangeHelper.selectRange(range);
currentSelection = range;
if (focusEnd) {
$wysiwygDoc.scrollTop(body.scrollHeight);
$wysiwygBody.scrollTop(body.scrollHeight);
}
base.focus();
};
/**
* Gets if the editor is read only
*
* @since 1.3.5
* @function
* @memberOf jQuery.sceditor.prototype
* @name readOnly
* @return {Boolean}
*/
/**
* Sets if the editor is read only
*
* @param {boolean} readOnly
* @since 1.3.5
* @function
* @memberOf jQuery.sceditor.prototype
* @name readOnly^2
* @return {this}
*/
base.readOnly = function (readOnly) {
if (typeof readOnly !== 'boolean') {
return $sourceEditor.attr('readonly') === 'readonly';
}
$wysiwygBody[0].contentEditable = !readOnly;
if (!readOnly) {
$sourceEditor.removeAttr('readonly');
} else {
$sourceEditor.attr('readonly', 'readonly');
}
updateToolBar(readOnly);
return base;
};
/**
* Gets if the editor is in RTL mode
*
* @since 1.4.1
* @function
* @memberOf jQuery.sceditor.prototype
* @name rtl
* @return {Boolean}
*/
/**
* Sets if the editor is in RTL mode
*
* @param {boolean} rtl
* @since 1.4.1
* @function
* @memberOf jQuery.sceditor.prototype
* @name rtl^2
* @return {this}
*/
base.rtl = function (rtl) {
var dir = rtl ? 'rtl' : 'ltr';
if (typeof rtl !== 'boolean') {
return $sourceEditor.attr('dir') === 'rtl';
}
$wysiwygBody.attr('dir', dir);
$sourceEditor.attr('dir', dir);
$editorContainer
.removeClass('rtl')
.removeClass('ltr')
.addClass(dir);
return base;
};
/**
* Updates the toolbar to disable/enable the appropriate buttons
* @private
*/
updateToolBar = function (disable) {
var mode = base.inSourceMode() ? 'txtmode' : 'wysiwygmode';
$.each(toolbarButtons, function (idx, $button) {
if (disable === true || !$button.data('sceditor-' + mode)) {
$button.addClass('disabled');
} else {
$button.removeClass('disabled');
}
});
};
/**
* Gets the width of the editor in pixels
*
* @since 1.3.5
* @function
* @memberOf jQuery.sceditor.prototype
* @name width
* @return {int}
*/
/**
* Sets the width of the editor
*
* @param {int} width Width in pixels
* @since 1.3.5
* @function
* @memberOf jQuery.sceditor.prototype
* @name width^2
* @return {this}
*/
/**
* Sets the width of the editor
*
* The saveWidth specifies if to save the width. The stored width can be
* used for things like restoring from maximized state.
*
* @param {int} width Width in pixels
* @param {boolean} [saveWidth=true] If to store the width
* @since 1.4.1
* @function
* @memberOf jQuery.sceditor.prototype
* @name width^3
* @return {this}
*/
base.width = function (width, saveWidth) {
if (!width && width !== 0) {
return $editorContainer.width();
}
base.dimensions(width, null, saveWidth);
return base;
};
/**
* Returns an object with the properties width and height
* which are the width and height of the editor in px.
*
* @since 1.4.1
* @function
* @memberOf jQuery.sceditor.prototype
* @name dimensions
* @return {object}
*/
/**
* <p>Sets the width and/or height of the editor.</p>
*
* <p>If width or height is not numeric it is ignored.</p>
*
* @param {int} width Width in px
* @param {int} height Height in px
* @since 1.4.1
* @function
* @memberOf jQuery.sceditor.prototype
* @name dimensions^2
* @return {this}
*/
/**
* <p>Sets the width and/or height of the editor.</p>
*
* <p>If width or height is not numeric it is ignored.</p>
*
* <p>The save argument specifies if to save the new sizes.
* The saved sizes can be used for things like restoring from
* maximized state. This should normally be left as true.</p>
*
* @param {int} width Width in px
* @param {int} height Height in px
* @param {boolean} [save=true] If to store the new sizes
* @since 1.4.1
* @function
* @memberOf jQuery.sceditor.prototype
* @name dimensions^3
* @return {this}
*/
base.dimensions = function (width, height, save) {
// IE6 & IE7 add 2 pixels to the source mode textarea
// height which must be ignored.
// Doesn't seem to be any way to fix it with only CSS
var ieBorder = IE_VER < 8 || globalDoc.documentMode < 8 ? 2 : 0;
var undef;
// set undefined width/height to boolean false
width = (!width && width !== 0) ? false : width;
height = (!height && height !== 0) ? false : height;
if (width === false && height === false) {
return { width: base.width(), height: base.height() };
}
if ($wysiwygEditor.data('outerWidthOffset') === undef) {
base.updateStyleCache();
}
if (width !== false) {
if (save !== false) {
options.width = width;
}
// This is the problem
if (height === false) {
height = $editorContainer.height();
save = false;
}
$editorContainer.width(width);
if (width && width.toString().indexOf('%') > -1) {
width = $editorContainer.width();
}
$wysiwygEditor.width(
width - $wysiwygEditor.data('outerWidthOffset')
);
$sourceEditor.width(
width - $sourceEditor.data('outerWidthOffset')
);
// Fix overflow issue with iOS not
// breaking words unless a width is set
if (browser.ios && $wysiwygBody) {
$wysiwygBody.width(
width - $wysiwygEditor.data('outerWidthOffset') -
($wysiwygBody.outerWidth(true) - $wysiwygBody.width())
);
}
}
if (height !== false) {
if (save !== false) {
options.height = height;
}
// Convert % based heights to px
if (height && height.toString().indexOf('%') > -1) {
height = $editorContainer.height(height).height();
$editorContainer.height('auto');
}
height -= !options.toolbarContainer ?
$toolbar.outerHeight(true) : 0;
$wysiwygEditor.height(
height - $wysiwygEditor.data('outerHeightOffset')
);
$sourceEditor.height(
height - ieBorder - $sourceEditor.data('outerHeightOffset')
);
}
return base;
};
/**
* Updates the CSS styles cache.
*
* This shouldn't be needed unless changing the editors theme.
*F
* @since 1.4.1
* @function
* @memberOf jQuery.sceditor.prototype
* @name updateStyleCache
* @return {int}
*/
base.updateStyleCache = function () {
// caching these improves FF resize performance
$wysiwygEditor.data(
'outerWidthOffset',
$wysiwygEditor.outerWidth(true) - $wysiwygEditor.width()
);
$sourceEditor.data(
'outerWidthOffset',
$sourceEditor.outerWidth(true) - $sourceEditor.width()
);
$wysiwygEditor.data(
'outerHeightOffset',
$wysiwygEditor.outerHeight(true) - $wysiwygEditor.height()
);
$sourceEditor.data(
'outerHeightOffset',
$sourceEditor.outerHeight(true) - $sourceEditor.height()
);
};
/**
* Gets the height of the editor in px
*
* @since 1.3.5
* @function
* @memberOf jQuery.sceditor.prototype
* @name height
* @return {int}
*/
/**
* Sets the height of the editor
*
* @param {int} height Height in px
* @since 1.3.5
* @function
* @memberOf jQuery.sceditor.prototype
* @name height^2
* @return {this}
*/
/**
* Sets the height of the editor
*
* The saveHeight specifies if to save the height.
*
* The stored height can be used for things like
* restoring from maximized state.
*
* @param {int} height Height in px
* @param {boolean} [saveHeight=true] If to store the height
* @since 1.4.1
* @function
* @memberOf jQuery.sceditor.prototype
* @name height^3
* @return {this}
*/
base.height = function (height, saveHeight) {
if (!height && height !== 0) {
return $editorContainer.height();
}
base.dimensions(null, height, saveHeight);
return base;
};
/**
* Gets if the editor is maximised or not
*
* @since 1.4.1
* @function
* @memberOf jQuery.sceditor.prototype
* @name maximize
* @return {boolean}
*/
/**
* Sets if the editor is maximised or not
*
* @param {boolean} maximize If to maximise the editor
* @since 1.4.1
* @function
* @memberOf jQuery.sceditor.prototype
* @name maximize^2
* @return {this}
*/
base.maximize = function (maximize) {
if (typeof maximize === 'undefined') {
return $editorContainer.is('.sceditor-maximize');
}
maximize = !!maximize;
// IE 6 fix
if (IE_VER < 7) {
$('html, body').toggleClass('sceditor-maximize', maximize);
}
$editorContainer.toggleClass('sceditor-maximize', maximize);
base.width(maximize ? '100%' : options.width, false);
base.height(maximize ? '100%' : options.height, false);
return base;
};
/**
* Expands the editors height to the height of it's content
*
* Unless ignoreMaxHeight is set to true it will not expand
* higher than the maxHeight option.
*
* @since 1.3.5
* @param {Boolean} [ignoreMaxHeight=false]
* @function
* @name expandToContent
* @memberOf jQuery.sceditor.prototype
* @see #resizeToContent
*/
base.expandToContent = function (ignoreMaxHeight) {
var currentHeight = $editorContainer.height(),
padding = (currentHeight - $wysiwygEditor.height()),
height = $wysiwygBody[0].scrollHeight ||
$wysiwygDoc[0].documentElement.scrollHeight,
maxHeight = options.resizeMaxHeight ||
((options.height || $original.height()) * 2);
height += padding;
if ((ignoreMaxHeight === true || height <= maxHeight) &&
height > currentHeight) {
base.height(height);
}
};
/**
* Destroys the editor, removing all elements and
* event handlers.
*
* Leaves only the original textarea.
*
* @function
* @name destroy
* @memberOf jQuery.sceditor.prototype
*/
base.destroy = function () {
// Don't destroy if the editor has already been destroyed
if (!pluginManager) {
return;
}
pluginManager.destroy();
rangeHelper = null;
lastRange = null;
pluginManager = null;
if ($dropdown) {
$dropdown.off().remove();
}
$globalDoc.off('click', handleDocumentClick);
$globalWin.off('resize orientationChanged', handleWindowResize);
$(original.form)
.off('reset', handleFormReset)
.off('submit', base.updateOriginal);
$wysiwygBody.off();
$wysiwygDoc.off().find('*').remove();
$sourceEditor.off().remove();
$toolbar.remove();
$editorContainer.off().find('*').off().remove();
$editorContainer.remove();
$original
.removeData('sceditor')
.removeData('sceditorbbcode')
.show();
if (isRequired) {
$original.attr('required', 'required');
}
};
/**
* Creates a menu item drop down
*
* @param {HTMLElement} menuItem The button to align the dropdown with
* @param {string} name Used for styling the dropdown, will be
* a class sceditor-name
* @param {HTMLElement} content The HTML content of the dropdown
* @param {bool} ieFix If to add the unselectable attribute
* to all the contents elements. Stops
* IE from deselecting the text in the
* editor
* @function
* @name createDropDown
* @memberOf jQuery.sceditor.prototype
*/
base.createDropDown = function (menuItem, name, content, ieFix) {
// first click for create second click for close
var dropDownCss,
cssClass = 'sceditor-' + name,
onlyclose = $dropdown && $dropdown.is('.' + cssClass);
// Will re-focus the editor. This is needed for IE
// as it has special logic to save/restore the selection
base.closeDropDown(true);
if (onlyclose) {
return;
}
// IE needs unselectable attr to stop it from
// unselecting the text in the editor.
// SCEditor can cope if IE does unselect the
// text it's just not nice.
if (ieFix !== false) {
$(content)
.find(':not(input,textarea)')
.filter(function () {
return this.nodeType === 1;
})
.attr('unselectable', 'on');
}
dropDownCss = {
top: menuItem.offset().top,
left: menuItem.offset().left,
marginTop: menuItem.outerHeight()
};
$.extend(dropDownCss, options.dropDownCss);
$dropdown = $('<div class="sceditor-dropdown ' + cssClass + '" />')
.css(dropDownCss)
.append(content)
.appendTo($('body'))
.on('click focusin', function (e) {
// stop clicks within the dropdown from being handled
e.stopPropagation();
});
// If try to focus the first input immediately IE will
// place the cursor at the start of the editor instead
// of focusing on the input.
setTimeout(function () {
if ($dropdown) {
$dropdown.find('input,textarea').first().focus();
}
});
};
/**
* Handles any document click and closes the dropdown if open
* @private
*/
handleDocumentClick = function (e) {
// ignore right clicks
if (e.which !== 3 && $dropdown) {
autoUpdate();
base.closeDropDown();
}
};
/**
* Handles the WYSIWYG editors paste event
* @private
*/
handlePasteEvt = function (e) {
var html, handlePaste, scrollTop,
elm = $wysiwygBody[0],
doc = $wysiwygDoc[0],
checkCount = 0,
pastearea = globalDoc.createElement('div'),
prePasteContent = doc.createDocumentFragment(),
clipboardData = e ? e.clipboardData : false;
if (options.disablePasting) {
return false;
}
if (!options.enablePasteFiltering) {
return;
}
rangeHelper.saveRange();
globalDoc.body.appendChild(pastearea);
if (clipboardData && clipboardData.getData) {
if ((html = clipboardData.getData('text/html')) ||
(html = clipboardData.getData('text/plain'))) {
pastearea.innerHTML = html;
handlePasteData(elm, pastearea);
return false;
}
}
// Save the scroll position so can be restored
// when contents is restored
scrollTop = $wysiwygBody.scrollTop() || $wysiwygDoc.scrollTop();
while (elm.firstChild) {
prePasteContent.appendChild(elm.firstChild);
}
// try make pastearea contenteditable and redirect to that? Might work.
// Check the tests if still exist, if not re-0create
handlePaste = function (elm, pastearea) {
if (elm.childNodes.length > 0 || checkCount > 25) {
while (elm.firstChild) {
pastearea.appendChild(elm.firstChild);
}
while (prePasteContent.firstChild) {
elm.appendChild(prePasteContent.firstChild);
}
$wysiwygBody.scrollTop(scrollTop);
$wysiwygDoc.scrollTop(scrollTop);
if (pastearea.childNodes.length > 0) {
handlePasteData(elm, pastearea);
} else {
rangeHelper.restoreRange();
}
} else {
// Allow max 25 checks before giving up.
// Needed in case an empty string is pasted or
// something goes wrong.
checkCount++;
setTimeout(function () {
handlePaste(elm, pastearea);
}, 20);
}
};
handlePaste(elm, pastearea);
base.focus();
return true;
};
/**
* Gets the pasted data, filters it and then inserts it.
* @param {Element} elm
* @param {Element} pastearea
* @private
*/
handlePasteData = function (elm, pastearea) {
// fix any invalid nesting
dom.fixNesting(pastearea);
// TODO: Trigger custom paste event to allow filtering
// (pre and post converstion?)
var pasteddata = pastearea.innerHTML;
if (pluginManager.hasHandler('toSource')) {
pasteddata = pluginManager.callOnlyFirst(
'toSource', pasteddata, $(pastearea)
);
}
pastearea.parentNode.removeChild(pastearea);
if (pluginManager.hasHandler('toWysiwyg')) {
pasteddata = pluginManager.callOnlyFirst(
'toWysiwyg', pasteddata, true
);
}
rangeHelper.restoreRange();
base.wysiwygEditorInsertHtml(pasteddata, null, true);
};
/**
* Closes any currently open drop down
*
* @param {bool} [focus=false] If to focus the editor
* after closing the drop down
* @function
* @name closeDropDown
* @memberOf jQuery.sceditor.prototype
*/
base.closeDropDown = function (focus) {
if ($dropdown) {
$dropdown.off().remove();
$dropdown = null;
}
if (focus === true) {
base.focus();
}
};
/**
* Gets the WYSIWYG editors document
* @private
*/
getWysiwygDoc = function () {
if (wysiwygEditor.contentDocument) {
return wysiwygEditor.contentDocument;
}
if (wysiwygEditor.contentWindow &&
wysiwygEditor.contentWindow.document) {
return wysiwygEditor.contentWindow.document;
}
return wysiwygEditor.document;
};
/**
* <p>Inserts HTML into WYSIWYG editor.</p>
*
* <p>If endHtml is specified, any selected text will be placed
* between html and endHtml. If there is no selected text html
* and endHtml will just be concatenate together.</p>
*
* @param {string} html
* @param {string} [endHtml=null]
* @param {boolean} [overrideCodeBlocking=false] If to insert the html
* into code tags, by
* default code tags only
* support text.
* @function
* @name wysiwygEditorInsertHtml
* @memberOf jQuery.sceditor.prototype
*/
base.wysiwygEditorInsertHtml = function (
html, endHtml, overrideCodeBlocking
) {
var $marker, scrollTop, scrollTo,
editorHeight = $wysiwygEditor.height();
base.focus();
// TODO: This code tag should be configurable and
// should maybe convert the HTML into text instead
// Don't apply to code elements
if (!overrideCodeBlocking && ($(currentBlockNode).is('code') ||
$(currentBlockNode).parents('code').length !== 0)) {
return;
}
// Insert the HTML and save the range so the editor can be scrolled
// to the end of the selection. Also allows emoticons to be replaced
// without affecting the cursor position
rangeHelper.insertHTML(html, endHtml);
rangeHelper.saveRange();
replaceEmoticons($wysiwygBody[0]);
// Scroll the editor after the end of the selection
$marker = $wysiwygBody.find('#sceditor-end-marker').show();
scrollTop = $wysiwygBody.scrollTop() || $wysiwygDoc.scrollTop();
scrollTo = (dom.getOffset($marker[0]).top +
($marker.outerHeight(true) * 1.5)) - editorHeight;
$marker.hide();
// Only scroll if marker isn't already visible
if (scrollTo > scrollTop || scrollTo + editorHeight < scrollTop) {
$wysiwygBody.scrollTop(scrollTo);
$wysiwygDoc.scrollTop(scrollTo);
}
triggerValueChanged(false);
rangeHelper.restoreRange();
// Add a new line after the last block element
// so can always add text after it
appendNewLine();
};
/**
* Like wysiwygEditorInsertHtml except it will convert any HTML
* into text before inserting it.
*
* @param {String} text
* @param {String} [endText=null]
* @function
* @name wysiwygEditorInsertText
* @memberOf jQuery.sceditor.prototype
*/
base.wysiwygEditorInsertText = function (text, endText) {
base.wysiwygEditorInsertHtml(
escape.entities(text), escape.entities(endText)
);
};
/**
* <p>Inserts text into the WYSIWYG or source editor depending on which
* mode the editor is in.</p>
*
* <p>If endText is specified any selected text will be placed between
* text and endText. If no text is selected text and endText will
* just be concatenate together.</p>
*
* @param {String} text
* @param {String} [endText=null]
* @since 1.3.5
* @function
* @name insertText
* @memberOf jQuery.sceditor.prototype
*/
base.insertText = function (text, endText) {
if (base.inSourceMode()) {
base.sourceEditorInsertText(text, endText);
} else {
base.wysiwygEditorInsertText(text, endText);
}
return base;
};
/**
* <p>Like wysiwygEditorInsertHtml but inserts text into the
* source mode editor instead.</p>
*
* <p>If endText is specified any selected text will be placed between
* text and endText. If no text is selected text and endText will
* just be concatenate together.</p>
*
* <p>The cursor will be placed after the text param. If endText is
* specified the cursor will be placed before endText, so passing:<br />
*
* '[b]', '[/b]'</p>
*
* <p>Would cause the cursor to be placed:<br />
*
* [b]Selected text|[/b]</p>
*
* @param {String} text
* @param {String} [endText=null]
* @since 1.4.0
* @function
* @name sourceEditorInsertText
* @memberOf jQuery.sceditor.prototype
*/
base.sourceEditorInsertText = function (text, endText) {
var range, scrollTop, currentValue,
startPos = sourceEditor.selectionStart,
endPos = sourceEditor.selectionEnd;
scrollTop = sourceEditor.scrollTop;
sourceEditor.focus();
// All browsers except IE < 9
if (typeof startPos !== 'undefined') {
currentValue = sourceEditor.value;
if (endText) {
text += currentValue.substring(startPos, endPos) + endText;
}
sourceEditor.value = currentValue.substring(0, startPos) +
text +
currentValue.substring(endPos, currentValue.length);
sourceEditor.selectionStart = (startPos + text.length) -
(endText ? endText.length : 0);
sourceEditor.selectionEnd = sourceEditor.selectionStart;
// IE < 9
} else {
range = globalDoc.selection.createRange();
if (endText) {
text += range.text + endText;
}
range.text = text;
if (endText) {
range.moveEnd('character', 0 - endText.length);
}
range.moveStart('character', range.End - range.Start);
range.select();
}
sourceEditor.scrollTop = scrollTop;
sourceEditor.focus();
triggerValueChanged();
};
/**
* Gets the current instance of the rangeHelper class
* for the editor.
*
* @return jQuery.sceditor.rangeHelper
* @function
* @name getRangeHelper
* @memberOf jQuery.sceditor.prototype
*/
base.getRangeHelper = function () {
return rangeHelper;
};
/**
* Gets the source editors textarea.
*
* This shouldn't be used to insert text
*
* @return {jQuery}
* @function
* @since 1.4.5
* @name sourceEditorCaret
* @memberOf jQuery.sceditor.prototype
*/
base.sourceEditorCaret = function (position) {
var range,
ret = {};
sourceEditor.focus();
// All browsers except IE <= 8
if (typeof sourceEditor.selectionStart !== 'undefined') {
if (position) {
sourceEditor.selectionStart = position.start;
sourceEditor.selectionEnd = position.end;
} else {
ret.start = sourceEditor.selectionStart;
ret.end = sourceEditor.selectionEnd;
}
// IE8 and below
} else {
range = globalDoc.selection.createRange();
if (position) {
range.moveEnd('character', position.end);
range.moveStart('character', position.start);
range.select();
} else {
ret.start = range.Start;
ret.end = range.End;
}
}
return position ? this : ret;
};
/**
* <p>Gets the value of the editor.</p>
*
* <p>If the editor is in WYSIWYG mode it will return the filtered
* HTML from it (converted to BBCode if using the BBCode plugin).
* It it's in Source Mode it will return the unfiltered contents
* of the source editor (if using the BBCode plugin this will be
* BBCode again).</p>
*
* @since 1.3.5
* @return {string}
* @function
* @name val
* @memberOf jQuery.sceditor.prototype
*/
/**
* <p>Sets the value of the editor.</p>
*
* <p>If filter set true the val will be passed through the filter
* function. If using the BBCode plugin it will pass the val to
* the BBCode filter to convert any BBCode into HTML.</p>
*
* @param {String} val
* @param {Boolean} [filter=true]
* @return {this}
* @since 1.3.5
* @function
* @name val^2
* @memberOf jQuery.sceditor.prototype
*/
base.val = function (val, filter) {
if (typeof val !== 'string') {
return base.inSourceMode() ?
base.getSourceEditorValue(false) :
base.getWysiwygEditorValue(filter);
}
if (!base.inSourceMode()) {
if (filter !== false &&
pluginManager.hasHandler('toWysiwyg')) {
val = pluginManager.callOnlyFirst('toWysiwyg', val);
}
base.setWysiwygEditorValue(val);
} else {
base.setSourceEditorValue(val);
}
return base;
};
/**
* <p>Inserts HTML/BBCode into the editor</p>
*
* <p>If end is supplied any selected text will be placed between
* start and end. If there is no selected text start and end
* will be concatenate together.</p>
*
* <p>If the filter param is set to true, the HTML/BBCode will be
* passed through any plugin filters. If using the BBCode plugin
* this will convert any BBCode into HTML.</p>
*
* @param {String} start
* @param {String} [end=null]
* @param {Boolean} [filter=true]
* @param {Boolean} [convertEmoticons=true] If to convert emoticons
* @return {this}
* @since 1.3.5
* @function
* @name insert
* @memberOf jQuery.sceditor.prototype
*/
/**
* <p>Inserts HTML/BBCode into the editor</p>
*
* <p>If end is supplied any selected text will be placed between
* start and end. If there is no selected text start and end
* will be concatenate together.</p>
*
* <p>If the filter param is set to true, the HTML/BBCode will be
* passed through any plugin filters. If using the BBCode plugin
* this will convert any BBCode into HTML.</p>
*
* <p>If the allowMixed param is set to true, HTML any will not be
* escaped</p>
*
* @param {String} start
* @param {String} [end=null]
* @param {Boolean} [filter=true]
* @param {Boolean} [convertEmoticons=true] If to convert emoticons
* @param {Boolean} [allowMixed=false]
* @return {this}
* @since 1.4.3
* @function
* @name insert^2
* @memberOf jQuery.sceditor.prototype
*/
base.insert = function (
/*jshint maxparams: false */
start, end, filter, convertEmoticons, allowMixed
) {
if (base.inSourceMode()) {
base.sourceEditorInsertText(start, end);
return base;
}
// Add the selection between start and end
if (end) {
var html = rangeHelper.selectedHtml(),
$div = $('<div>').appendTo($('body')).hide().html(html);
if (filter !== false && pluginManager.hasHandler('toSource')) {
html = pluginManager.callOnlyFirst('toSource', html, $div);
}
$div.remove();
start += html + end;
}
// TODO: This filter should allow empty tags as it's inserting.
if (filter !== false && pluginManager.hasHandler('toWysiwyg')) {
start = pluginManager.callOnlyFirst('toWysiwyg', start, true);
}
// Convert any escaped HTML back into HTML if mixed is allowed
if (filter !== false && allowMixed === true) {
start = start.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&');
}
base.wysiwygEditorInsertHtml(start);
return base;
};
/**
* Gets the WYSIWYG editors HTML value.
*
* If using a plugin that filters the Ht Ml like the BBCode plugin
* it will return the result of the filtering (BBCode) unless the
* filter param is set to false.
*
* @param {bool} [filter=true]
* @return {string}
* @function
* @name getWysiwygEditorValue
* @memberOf jQuery.sceditor.prototype
*/
base.getWysiwygEditorValue = function (filter) {
var html;
// Create a tmp node to store contents so it can be modified
// without affecting anything else.
var $tmp = $('<div>')
.appendTo(document.body)
.append($($wysiwygBody[0].childNodes).clone());
dom.fixNesting($tmp[0]);
html = $tmp.html();
// filter the HTML and DOM through any plugins
if (filter !== false && pluginManager.hasHandler('toSource')) {
html = pluginManager.callOnlyFirst('toSource', html, $tmp);
}
$tmp.remove();
return html;
};
/**
* Gets the WYSIWYG editor's iFrame Body.
*
* @return {jQuery}
* @function
* @since 1.4.3
* @name getBody
* @memberOf jQuery.sceditor.prototype
*/
base.getBody = function () {
return $wysiwygBody;
};
/**
* Gets the WYSIWYG editors container area (whole iFrame).
*
* @return {Node}
* @function
* @since 1.4.3
* @name getContentAreaContainer
* @memberOf jQuery.sceditor.prototype
*/
base.getContentAreaContainer = function () {
return $wysiwygEditor;
};
/**
* Gets the text editor value
*
* If using a plugin that filters the text like the BBCode plugin
* it will return the result of the filtering which is BBCode to
* HTML so it will return HTML. If filter is set to false it will
* just return the contents of the source editor (BBCode).
*
* @param {bool} [filter=true]
* @return {string}
* @function
* @since 1.4.0
* @name getSourceEditorValue
* @memberOf jQuery.sceditor.prototype
*/
base.getSourceEditorValue = function (filter) {
var val = $sourceEditor.val();
if (filter !== false && pluginManager.hasHandler('toWysiwyg')) {
val = pluginManager.callOnlyFirst('toWysiwyg', val);
}
return val;
};
/**
* Sets the WYSIWYG HTML editor value. Should only be the HTML
* contained within the body tags
*
* @param {string} value
* @function
* @name setWysiwygEditorValue
* @memberOf jQuery.sceditor.prototype
*/
base.setWysiwygEditorValue = function (value) {
if (!value) {
value = '<p>' + (IE_VER ? '' : '<br />') + '</p>';
}
$wysiwygBody[0].innerHTML = value;
replaceEmoticons($wysiwygBody[0]);
appendNewLine();
triggerValueChanged();
};
/**
* Sets the text editor value
*
* @param {string} value
* @function
* @name setSourceEditorValue
* @memberOf jQuery.sceditor.prototype
*/
base.setSourceEditorValue = function (value) {
$sourceEditor.val(value);
triggerValueChanged();
};
/**
* Updates the textarea that the editor is replacing
* with the value currently inside the editor.
*
* @function
* @name updateOriginal
* @since 1.4.0
* @memberOf jQuery.sceditor.prototype
*/
base.updateOriginal = function () {
$original.val(base.val());
};
/**
* Replaces any emoticon codes in the passed HTML
* with their emoticon images
* @private
*/
replaceEmoticons = function (node) {
// TODO: Make this tag configurable.
if (!options.emoticonsEnabled || $(node).parents('code').length) {
return;
}
var doc = node.ownerDocument,
whitespace = '\\s|\xA0|\u2002|\u2003|\u2009| ',
emoticonCodes = [],
emoticonRegex = [],
emoticons = $.extend(
{},
options.emoticons.more,
options.emoticons.dropdown,
options.emoticons.hidden
);
// TODO: cache the emoticonCodes and emoticonCodes objects and share them with
// the AYT converstion
$.each(emoticons, function (key) {
if (options.emoticonsCompat) {
emoticonRegex[key] = new RegExp(
'(>|^|' + whitespace + ')' +
escape.regex(key) +
'($|<|' + whitespace + ')'
);
}
emoticonCodes.push(key);
});
// TODO: tidy below
var convertEmoticons = function (node) {
node = node.firstChild;
while (node) {
var parts, key, emoticon, parsedHtml,
emoticonIdx, nextSibling, matchPos,
nodeParent = node.parentNode,
nodeValue = node.nodeValue;
// All none textnodes
if (node.nodeType !== 3) {
// TODO: Make this tag configurable.
if (!$(node).is('code')) {
convertEmoticons(node);
}
} else if (nodeValue) {
emoticonIdx = emoticonCodes.length;
while (emoticonIdx--) {
key = emoticonCodes[emoticonIdx];
matchPos = options.emoticonsCompat ?
nodeValue.search(emoticonRegex[key]) :
nodeValue.indexOf(key);
if (matchPos > -1) {
nextSibling = node.nextSibling;
emoticon = emoticons[key];
parts = nodeValue
.substr(matchPos).split(key);
nodeValue = nodeValue
.substr(0, matchPos) + parts.shift();
node.nodeValue = nodeValue;
parsedHtml = dom.parseHTML(_tmpl('emoticon', {
key: key,
url: emoticon.url || emoticon,
tooltip: emoticon.tooltip || key
}), doc);
nodeParent.insertBefore(
parsedHtml[0],
nextSibling
);
nodeParent.insertBefore(
doc.createTextNode(parts.join(key)),
nextSibling
);
}
}
}
node = node.nextSibling;
}
};
convertEmoticons(node);
if (options.emoticonsCompat) {
currentEmoticons = $wysiwygBody
.find('img[data-sceditor-emoticon]');
}
};
/**
* If the editor is in source code mode
*
* @return {bool}
* @function
* @name inSourceMode
* @memberOf jQuery.sceditor.prototype
*/
base.inSourceMode = function () {
return $editorContainer.hasClass('sourceMode');
};
/**
* Gets if the editor is in sourceMode
*
* @return boolean
* @function
* @name sourceMode
* @memberOf jQuery.sceditor.prototype
*/
/**
* Sets if the editor is in sourceMode
*
* @param {bool} enable
* @return {this}
* @function
* @name sourceMode^2
* @memberOf jQuery.sceditor.prototype
*/
base.sourceMode = function (enable) {
var inSourceMode = base.inSourceMode();
if (typeof enable !== 'boolean') {
return inSourceMode;
}
if ((inSourceMode && !enable) || (!inSourceMode && enable)) {
base.toggleSourceMode();
}
return base;
};
/**
* Switches between the WYSIWYG and source modes
*
* @function
* @name toggleSourceMode
* @since 1.4.0
* @memberOf jQuery.sceditor.prototype
*/
base.toggleSourceMode = function () {
var sourceMode = base.inSourceMode();
// don't allow switching to WYSIWYG if doesn't support it
if (!browser.isWysiwygSupported && sourceMode) {
return;
}
if (!sourceMode) {
rangeHelper.saveRange();
rangeHelper.clear();
}
base.blur();
if (sourceMode) {
base.setWysiwygEditorValue(base.getSourceEditorValue());
} else {
base.setSourceEditorValue(base.getWysiwygEditorValue());
}
lastRange = null;
$sourceEditor.toggle();
$wysiwygEditor.toggle();
$editorContainer
.toggleClass('wysiwygMode', sourceMode)
.toggleClass('sourceMode', !sourceMode);
updateToolBar();
updateActiveButtons();
};
/**
* Gets the selected text of the source editor
* @return {String}
* @private
*/
sourceEditorSelectedText = function () {
sourceEditor.focus();
if (typeof sourceEditor.selectionStart !== 'undefined') {
return sourceEditor.value.substring(
sourceEditor.selectionStart,
sourceEditor.selectionEnd
);
} else {
return globalDoc.selection.createRange().text;
}
};
/**
* Handles the passed command
* @private
*/
handleCommand = function (caller, cmd) {
// check if in text mode and handle text commands
if (base.inSourceMode()) {
if (cmd.txtExec) {
if ($.isArray(cmd.txtExec)) {
base.sourceEditorInsertText.apply(base, cmd.txtExec);
} else {
cmd.txtExec.call(
base,
caller,
sourceEditorSelectedText()
);
}
}
} else if (cmd.exec) {
if ($.isFunction(cmd.exec)) {
cmd.exec.call(base, caller);
} else {
base.execCommand(
cmd.exec,
cmd.hasOwnProperty('execParam') ?
cmd.execParam : null
);
}
}
};
/**
* Saves the current range. Needed for IE because it forgets
* where the cursor was and what was selected
* @private
*/
saveRange = function () {
/* this is only needed for IE */
if (IE_VER) {
lastRange = rangeHelper.selectedRange();
}
};
/**
* Executes a command on the WYSIWYG editor
*
* @param {String} command
* @param {String|Boolean} [param]
* @function
* @name execCommand
* @memberOf jQuery.sceditor.prototype
*/
base.execCommand = function (command, param) {
var executed = false,
commandObj = base.commands[command],
$parentNode = $(rangeHelper.parentNode());
base.focus();
// TODO: make configurable
// don't apply any commands to code elements
if ($parentNode.is('code') ||
$parentNode.parents('code').length !== 0) {
return;
}
try {
executed = $wysiwygDoc[0].execCommand(command, false, param);
} catch (ex) {}
// show error if execution failed and an error message exists
if (!executed && commandObj && commandObj.errorMessage) {
/*global alert:false*/
alert(base._(commandObj.errorMessage));
}
updateActiveButtons();
};
/**
* Checks if the current selection has changed and triggers
* the selectionchanged event if it has.
*
* In browsers other than IE, it will check at most once every 100ms.
* This is because only IE has a selection changed event.
* @private
*/
checkSelectionChanged = function () {
function check () {
// rangeHelper could be null if editor was destroyed
// before the timeout had finished
if (rangeHelper && !rangeHelper.compare(currentSelection)) {
currentSelection = rangeHelper.cloneSelected();
$editorContainer.trigger($.Event('selectionchanged'));
}
isSelectionCheckPending = false;
}
if (isSelectionCheckPending) {
return;
}
isSelectionCheckPending = true;
// In IE, this is only called on the selectionchange event so no
// need to limit checking as it should always be valid to do.
if (IE_VER) {
check();
} else {
setTimeout(check, 100);
}
};
/**
* Checks if the current node has changed and triggers
* the nodechanged event if it has
* @private
*/
checkNodeChanged = function () {
// check if node has changed
var oldNode,
node = rangeHelper.parentNode();
if (currentNode !== node) {
oldNode = currentNode;
currentNode = node;
currentBlockNode = rangeHelper.getFirstBlockParent(node);
$editorContainer.trigger($.Event('nodechanged', {
oldNode: oldNode,
newNode: currentNode
}));
}
};
/**
* <p>Gets the current node that contains the selection/caret in
* WYSIWYG mode.</p>
*
* <p>Will be null in sourceMode or if there is no selection.</p>
* @return {Node}
* @function
* @name currentNode
* @memberOf jQuery.sceditor.prototype
*/
base.currentNode = function () {
return currentNode;
};
/**
* <p>Gets the first block level node that contains the
* selection/caret in WYSIWYG mode.</p>
*
* <p>Will be null in sourceMode or if there is no selection.</p>
* @return {Node}
* @function
* @name currentBlockNode
* @memberOf jQuery.sceditor.prototype
* @since 1.4.4
*/
base.currentBlockNode = function () {
return currentBlockNode;
};
/**
* Updates if buttons are active or not
* @private
*/
updateActiveButtons = function (e) {
var firstBlock, parent;
var activeClass = 'active';
var doc = $wysiwygDoc[0];
var isSource = base.sourceMode();
if (base.readOnly()) {
$toolbar.find(activeClass).removeClass(activeClass);
return;
}
if (!isSource) {
parent = e ? e.newNode : rangeHelper.parentNode();
firstBlock = rangeHelper.getFirstBlockParent(parent);
}
for (var i = 0; i < btnStateHandlers.length; i++) {
var state = 0;
var $btn = toolbarButtons[btnStateHandlers[i].name];
var stateFn = btnStateHandlers[i].state;
var isDisabled = (isSource && !$btn.data('sceditor-txtmode')) ||
(!isSource && !$btn.data('sceditor-wysiwygmode'));
if (typeof stateFn === 'string') {
if (!isSource) {
try {
state = doc.queryCommandEnabled(stateFn) ? 0 : -1;
/*jshint maxdepth: false*/
if (state > -1) {
state = doc.queryCommandState(stateFn) ? 1 : 0;
}
} catch (ex) {}
}
} else if (!isDisabled) {
state = stateFn.call(base, parent, firstBlock);
}
$btn
.toggleClass('disabled', isDisabled || state < 0)
.toggleClass(activeClass, state > 0);
}
};
/**
* Handles any key press in the WYSIWYG editor
*
* @private
*/
handleKeyPress = function (e) {
var $closestTag, br, brParent, lastChild;
// TODO: improve this so isn't set list, probably should just use
// dom.hasStyling to all block parents and if one does insert a br
var DUPLICATED_TAGS = 'code,blockquote,pre';
var LIST_TAGS = 'li,ul,ol';
// FF bug: https://bugzilla.mozilla.org/show_bug.cgi?id=501496
if (e.originalEvent.defaultPrevented) {
return;
}
base.closeDropDown();
$closestTag = $(currentBlockNode)
.closest(DUPLICATED_TAGS + ',' + LIST_TAGS)
.first();
// "Fix" (OK it's a cludge) for blocklevel elements being
// duplicated in some browsers when enter is pressed instead
// of inserting a newline
if (e.which === 13 && $closestTag.length &&
!$closestTag.is(LIST_TAGS)) {
lastRange = null;
br = $wysiwygDoc[0].createElement('br');
rangeHelper.insertNode(br);
// Last <br> of a block will be collapsed unless it is
// IE < 11 so need to make sure the <br> that was inserted
// isn't the last node of a block.
if (!IE_BR_FIX) {
brParent = br.parentNode;
lastChild = brParent.lastChild;
// Sometimes an empty next node is created after the <br>
if (lastChild && lastChild.nodeType === 3 &&
lastChild.nodeValue === '') {
brParent.removeChild(lastChild);
lastChild = brParent.lastChild;
}
// If this is the last BR of a block and the previous
// sibling is inline then will need an extra BR. This
// is needed because the last BR of a block will be
// collapsed. Fixes issue #248
if (!dom.isInline(brParent, true) && lastChild === br &&
dom.isInline(br.previousSibling)) {
rangeHelper.insertHTML('<br>');
}
}
return false;
}
};
/**
* Makes sure that if there is a code or quote tag at the
* end of the editor, that there is a new line after it.
*
* If there wasn't a new line at the end you wouldn't be able
* to enter any text after a code/quote tag
* @return {void}
* @private
*/
appendNewLine = function () {
var name, requiresNewLine, paragraph,
body = $wysiwygBody[0];
dom.rTraverse(body, function (node) {
name = node.nodeName.toLowerCase();
// TODO: Replace requireNewLineFix with just a block level fix for any
// block that has styling and any block that isn't a plain <p> or <div>
if ($.inArray(name, requireNewLineFix) > -1) {
requiresNewLine = true;
}
// TODO: tidy this up
// find the last non-empty text node or line break.
if ((node.nodeType === 3 && !/^\s*$/.test(node.nodeValue)) ||
name === 'br' || (IE_BR_FIX && !node.firstChild &&
!dom.isInline(node, false))) {
// this is the last text or br node, if its in a code or
// quote tag then add a newline to the end of the editor
if (requiresNewLine) {
paragraph = $wysiwygDoc[0].createElement('p');
paragraph.className = 'sceditor-nlf';
paragraph.innerHTML = !IE_BR_FIX ? '<br />' : '';
body.appendChild(paragraph);
}
return false;
}
});
};
/**
* Handles form reset event
* @private
*/
handleFormReset = function () {
base.val($original.val());
};
/**
* Handles any mousedown press in the WYSIWYG editor
* @private
*/
handleMouseDown = function () {
base.closeDropDown();
lastRange = null;
};
/**
* Handles the window resize event. Needed to resize then editor
* when the window size changes in fluid designs.
* @ignore
*/
handleWindowResize = function () {
var height = options.height,
width = options.width;
if (!base.maximize()) {
if ((height && height.toString().indexOf('%') > -1) ||
(width && width.toString().indexOf('%') > -1)) {
base.dimensions(width, height);
}
} else {
base.dimensions('100%', '100%', false);
}
};
/**
* Translates the string into the locale language.
*
* Replaces any {0}, {1}, {2}, ect. with the params provided.
*
* @param {string} str
* @param {...String} args
* @return {string}
* @function
* @name _
* @memberOf jQuery.sceditor.prototype
*/
base._ = function () {
var undef,
args = arguments;
if (locale && locale[args[0]]) {
args[0] = locale[args[0]];
}
return args[0].replace(/\{(\d+)\}/g, function (str, p1) {
return args[p1 - 0 + 1] !== undef ?
args[p1 - 0 + 1] :
'{' + p1 + '}';
});
};
/**
* Passes events on to any handlers
* @private
* @return void
*/
handleEvent = function (e) {
// Send event to all plugins
pluginManager.call(e.type + 'Event', e, base);
// convert the event into a custom event to send
var prefix = e.target === sourceEditor ? 'scesrc' : 'scewys';
var customEvent = $.Event(e);
customEvent.type = prefix + e.type;
$editorContainer.trigger(customEvent, base);
};
/**
* <p>Binds a handler to the specified events</p>
*
* <p>This function only binds to a limited list of
* supported events.<br />
* The supported events are:
* <ul>
* <li>keyup</li>
* <li>keydown</li>
* <li>Keypress</li>
* <li>blur</li>
* <li>focus</li>
* <li>nodechanged<br />
* When the current node containing the selection changes
* in WYSIWYG mode</li>
* <li>contextmenu</li>
* <li>selectionchanged</li>
* <li>valuechanged</li>
* </ul>
* </p>
*
* <p>The events param should be a string containing the event(s)
* to bind this handler to. If multiple, they should be separated
* by spaces.</p>
*
* @param {String} events
* @param {Function} handler
* @param {Boolean} excludeWysiwyg If to exclude adding this handler
* to the WYSIWYG editor
* @param {Boolean} excludeSource if to exclude adding this handler
* to the source editor
* @return {this}
* @function
* @name bind
* @memberOf jQuery.sceditor.prototype
* @since 1.4.1
*/
base.bind = function (events, handler, excludeWysiwyg, excludeSource) {
events = events.split(' ');
var i = events.length;
while (i--) {
if ($.isFunction(handler)) {
// Use custom events to allow passing the instance as the
// 2nd argument.
// Also allows unbinding without unbinding the editors own
// event handlers.
if (!excludeWysiwyg) {
$editorContainer.on('scewys' + events[i], handler);
}
if (!excludeSource) {
$editorContainer.on('scesrc' + events[i], handler);
}
// Start sending value changed events
if (events[i] === 'valuechanged') {
triggerValueChanged.hasHandler = true;
}
}
}
return base;
};
/**
* Unbinds an event that was bound using bind().
*
* @param {String} events
* @param {Function} handler
* @param {Boolean} excludeWysiwyg If to exclude unbinding this
* handler from the WYSIWYG editor
* @param {Boolean} excludeSource if to exclude unbinding this
* handler from the source editor
* @return {this}
* @function
* @name unbind
* @memberOf jQuery.sceditor.prototype
* @since 1.4.1
* @see bind
*/
base.unbind = function (
events, handler, excludeWysiwyg, excludeSource
) {
events = events.split(' ');
var i = events.length;
while (i--) {
if ($.isFunction(handler)) {
if (!excludeWysiwyg) {
$editorContainer.off('scewys' + events[i], handler);
}
if (!excludeSource) {
$editorContainer.off('scesrc' + events[i], handler);
}
}
}
return base;
};
/**
* Blurs the editors input area
*
* @return {this}
* @function
* @name blur
* @memberOf jQuery.sceditor.prototype
* @since 1.3.6
*/
/**
* Adds a handler to the editors blur event
*
* @param {Function} handler
* @param {Boolean} excludeWysiwyg If to exclude adding this handler
* to the WYSIWYG editor
* @param {Boolean} excludeSource if to exclude adding this handler
* to the source editor
* @return {this}
* @function
* @name blur^2
* @memberOf jQuery.sceditor.prototype
* @since 1.4.1
*/
base.blur = function (handler, excludeWysiwyg, excludeSource) {
if ($.isFunction(handler)) {
base.bind('blur', handler, excludeWysiwyg, excludeSource);
} else if (!base.sourceMode()) {
$wysiwygBody.blur();
} else {
$sourceEditor.blur();
}
return base;
};
/**
* Focuses the editors input area
*
* @return {this}
* @function
* @name focus
* @memberOf jQuery.sceditor.prototype
*/
/**
* Adds an event handler to the focus event
*
* @param {Function} handler
* @param {Boolean} excludeWysiwyg If to exclude adding this handler
* to the WYSIWYG editor
* @param {Boolean} excludeSource if to exclude adding this handler
* to the source editor
* @return {this}
* @function
* @name focus^2
* @memberOf jQuery.sceditor.prototype
* @since 1.4.1
*/
base.focus = function (handler, excludeWysiwyg, excludeSource) {
if ($.isFunction(handler)) {
base.bind('focus', handler, excludeWysiwyg, excludeSource);
} else if (!base.inSourceMode()) {
var container,
rng = rangeHelper.selectedRange();
// Fix FF bug where it shows the cursor in the wrong place
// if the editor hasn't had focus before. See issue #393
if (!currentSelection && !rangeHelper.hasSelection()) {
autofocus();
}
// Check if cursor is set after a BR when the BR is the only
// child of the parent. In Firefox this causes a line break
// to occur when something is typed. See issue #321
if (!IE_BR_FIX && rng && rng.endOffset === 1 && rng.collapsed) {
container = rng.endContainer;
if (container && container.childNodes.length === 1 &&
$(container.firstChild).is('br')) {
rng.setStartBefore(container.firstChild);
rng.collapse(true);
rangeHelper.selectRange(rng);
}
}
wysiwygEditor.contentWindow.focus();
$wysiwygBody[0].focus();
// Needed for IE < 9
if (lastRange) {
rangeHelper.selectRange(lastRange);
// remove the stored range after being set.
// If the editor loses focus it should be
// saved again.
lastRange = null;
}
} else {
sourceEditor.focus();
}
updateActiveButtons();
return base;
};
/**
* Adds a handler to the key down event
*
* @param {Function} handler
* @param {Boolean} excludeWysiwyg If to exclude adding this handler
* to the WYSIWYG editor
* @param {Boolean} excludeSource If to exclude adding this handler
* to the source editor
* @return {this}
* @function
* @name keyDown
* @memberOf jQuery.sceditor.prototype
* @since 1.4.1
*/
base.keyDown = function (handler, excludeWysiwyg, excludeSource) {
return base.bind('keydown', handler, excludeWysiwyg, excludeSource);
};
/**
* Adds a handler to the key press event
*
* @param {Function} handler
* @param {Boolean} excludeWysiwyg If to exclude adding this handler
* to the WYSIWYG editor
* @param {Boolean} excludeSource If to exclude adding this handler
* to the source editor
* @return {this}
* @function
* @name keyPress
* @memberOf jQuery.sceditor.prototype
* @since 1.4.1
*/
base.keyPress = function (handler, excludeWysiwyg, excludeSource) {
return base
.bind('keypress', handler, excludeWysiwyg, excludeSource);
};
/**
* Adds a handler to the key up event
*
* @param {Function} handler
* @param {Boolean} excludeWysiwyg If to exclude adding this handler
* to the WYSIWYG editor
* @param {Boolean} excludeSource If to exclude adding this handler
* to the source editor
* @return {this}
* @function
* @name keyUp
* @memberOf jQuery.sceditor.prototype
* @since 1.4.1
*/
base.keyUp = function (handler, excludeWysiwyg, excludeSource) {
return base.bind('keyup', handler, excludeWysiwyg, excludeSource);
};
/**
* <p>Adds a handler to the node changed event.</p>
*
* <p>Happens whenever the node containing the selection/caret
* changes in WYSIWYG mode.</p>
*
* @param {Function} handler
* @return {this}
* @function
* @name nodeChanged
* @memberOf jQuery.sceditor.prototype
* @since 1.4.1
*/
base.nodeChanged = function (handler) {
return base.bind('nodechanged', handler, false, true);
};
/**
* <p>Adds a handler to the selection changed event</p>
*
* <p>Happens whenever the selection changes in WYSIWYG mode.</p>
*
* @param {Function} handler
* @return {this}
* @function
* @name selectionChanged
* @memberOf jQuery.sceditor.prototype
* @since 1.4.1
*/
base.selectionChanged = function (handler) {
return base.bind('selectionchanged', handler, false, true);
};
/**
* <p>Adds a handler to the value changed event</p>
*
* <p>Happens whenever the current editor value changes.</p>
*
* <p>Whenever anything is inserted, the value changed or
* 1.5 secs after text is typed. If a space is typed it will
* cause the event to be triggered immediately instead of
* after 1.5 seconds</p>
*
* @param {Function} handler
* @param {Boolean} excludeWysiwyg If to exclude adding this handler
* to the WYSIWYG editor
* @param {Boolean} excludeSource If to exclude adding this handler
* to the source editor
* @return {this}
* @function
* @name valueChanged
* @memberOf jQuery.sceditor.prototype
* @since 1.4.5
*/
base.valueChanged = function (handler, excludeWysiwyg, excludeSource) {
return base
.bind('valuechanged', handler, excludeWysiwyg, excludeSource);
};
/**
* Emoticons keypress handler
* @private
*/
emoticonsKeyPress = function (e) {
var replacedEmoticon,
cachePos = 0,
emoticonsCache = base.emoticonsCache,
curChar = String.fromCharCode(e.which);
// TODO: Make configurable
if ($(currentBlockNode).is('code') ||
$(currentBlockNode).parents('code').length) {
return;
}
if (!emoticonsCache) {
emoticonsCache = [];
$.each($.extend(
{},
options.emoticons.more,
options.emoticons.dropdown,
options.emoticons.hidden
), function (key, url) {
emoticonsCache[cachePos++] = [
key,
_tmpl('emoticon', {
key: key,
url: url.url || url,
tooltip: url.tooltip || key
})
];
});
emoticonsCache.sort(function (a, b) {
return a[0].length - b[0].length;
});
base.emoticonsCache = emoticonsCache;
base.longestEmoticonCode =
emoticonsCache[emoticonsCache.length - 1][0].length;
}
replacedEmoticon = rangeHelper.replaceKeyword(
base.emoticonsCache,
true,
true,
base.longestEmoticonCode,
options.emoticonsCompat,
curChar
);
if (replacedEmoticon && options.emoticonsCompat) {
currentEmoticons = $wysiwygBody
.find('img[data-sceditor-emoticon]');
return /^\s$/.test(curChar);
}
return !replacedEmoticon;
};
/**
* Makes sure emoticons are surrounded by whitespace
* @private
*/
emoticonsCheckWhitespace = function () {
if (!currentEmoticons.length) {
return;
}
var prev, next, parent, range, previousText, rangeStartContainer,
currentBlock = base.currentBlockNode(),
rangeStart = false,
noneWsRegex = /[^\s\xA0\u2002\u2003\u2009\u00a0]+/;
currentEmoticons = $.map(currentEmoticons, function (emoticon) {
// Ignore emoticons that have been removed from DOM
if (!emoticon || !emoticon.parentNode) {
return null;
}
if (!$.contains(currentBlock, emoticon)) {
return emoticon;
}
prev = emoticon.previousSibling;
next = emoticon.nextSibling;
previousText = prev.nodeValue;
// For IE's HTMLPhraseElement
if (previousText === null) {
previousText = prev.innerText || '';
}
if ((!prev || !noneWsRegex.test(prev.nodeValue.slice(-1))) &&
(!next || !noneWsRegex.test((next.nodeValue || '')[0]))) {
return emoticon;
}
parent = emoticon.parentNode;
range = rangeHelper.cloneSelected();
rangeStartContainer = range.startContainer;
previousText = previousText +
$(emoticon).data('sceditor-emoticon');
// Store current caret position
if (rangeStartContainer === next) {
rangeStart = previousText.length + range.startOffset;
} else if (rangeStartContainer === currentBlock &&
currentBlock.childNodes[range.startOffset] === next) {
rangeStart = previousText.length;
} else if (rangeStartContainer === prev) {
rangeStart = range.startOffset;
}
if (!next || next.nodeType !== 3) {
next = parent.insertBefore(
parent.ownerDocument.createTextNode(''), next
);
}
next.insertData(0, previousText);
parent.removeChild(prev);
parent.removeChild(emoticon);
// Need to update the range starting
// position if it has been modified
if (rangeStart !== false) {
range.setStart(next, rangeStart);
range.collapse(true);
rangeHelper.selectRange(range);
}
return null;
});
};
/**
* Gets if emoticons are currently enabled
* @return {boolean}
* @function
* @name emoticons
* @memberOf jQuery.sceditor.prototype
* @since 1.4.2
*/
/**
* Enables/disables emoticons
*
* @param {boolean} enable
* @return {this}
* @function
* @name emoticons^2
* @memberOf jQuery.sceditor.prototype
* @since 1.4.2
*/
base.emoticons = function (enable) {
if (!enable && enable !== false) {
return options.emoticonsEnabled;
}
options.emoticonsEnabled = enable;
if (enable) {
$wysiwygBody.keypress(emoticonsKeyPress);
if (!base.sourceMode()) {
rangeHelper.saveRange();
replaceEmoticons($wysiwygBody[0]);
currentEmoticons = $wysiwygBody
.find('img[data-sceditor-emoticon]');
triggerValueChanged(false);
rangeHelper.restoreRange();
}
} else {
$wysiwygBody
.find('img[data-sceditor-emoticon]')
.replaceWith(function () {
return $(this).data('sceditor-emoticon');
});
currentEmoticons = [];
$wysiwygBody.off('keypress', emoticonsKeyPress);
triggerValueChanged();
}
return base;
};
/**
* Gets the current WYSIWYG editors inline CSS
*
* @return {string}
* @function
* @name css
* @memberOf jQuery.sceditor.prototype
* @since 1.4.3
*/
/**
* Sets inline CSS for the WYSIWYG editor
*
* @param {string} css
* @return {this}
* @function
* @name css^2
* @memberOf jQuery.sceditor.prototype
* @since 1.4.3
*/
base.css = function (css) {
if (!inlineCss) {
inlineCss = $('<style id="#inline" />', $wysiwygDoc[0])
.appendTo($wysiwygDoc.find('head'))[0];
}
if (typeof css !== 'string') {
return inlineCss.styleSheet ?
inlineCss.styleSheet.cssText : inlineCss.innerHTML;
}
if (inlineCss.styleSheet) {
inlineCss.styleSheet.cssText = css;
} else {
inlineCss.innerHTML = css;
}
return base;
};
/**
* Handles the keydown event, used for shortcuts
* @private
*/
handleKeyDown = function (e) {
var shortcut = [],
SHIFT_KEYS = {
'`': '~',
'1': '!',
'2': '@',
'3': '#',
'4': '$',
'5': '%',
'6': '^',
'7': '&',
'8': '*',
'9': '(',
'0': ')',
'-': '_',
'=': '+',
';': ': ',
'\'': '"',
',': '<',
'.': '>',
'/': '?',
'\\': '|',
'[': '{',
']': '}'
},
SPECIAL_KEYS = {
8: 'backspace',
9: 'tab',
13: 'enter',
19: 'pause',
20: 'capslock',
27: 'esc',
32: 'space',
33: 'pageup',
34: 'pagedown',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
45: 'insert',
46: 'del',
91: 'win',
92: 'win',
93: 'select',
96: '0',
97: '1',
98: '2',
99: '3',
100: '4',
101: '5',
102: '6',
103: '7',
104: '8',
105: '9',
106: '*',
107: '+',
109: '-',
110: '.',
111: '/',
112: 'f1',
113: 'f2',
114: 'f3',
115: 'f4',
116: 'f5',
117: 'f6',
118: 'f7',
119: 'f8',
120: 'f9',
121: 'f10',
122: 'f11',
123: 'f12',
144: 'numlock',
145: 'scrolllock',
186: ';',
187: '=',
188: ',',
189: '-',
190: '.',
191: '/',
192: '`',
219: '[',
220: '\\',
221: ']',
222: '\''
},
NUMPAD_SHIFT_KEYS = {
109: '-',
110: 'del',
111: '/',
96: '0',
97: '1',
98: '2',
99: '3',
100: '4',
101: '5',
102: '6',
103: '7',
104: '8',
105: '9'
},
which = e.which,
character = SPECIAL_KEYS[which] ||
String.fromCharCode(which).toLowerCase();
if (e.ctrlKey || e.metaKey) {
shortcut.push('ctrl');
}
if (e.altKey) {
shortcut.push('alt');
}
if (e.shiftKey) {
shortcut.push('shift');
if (NUMPAD_SHIFT_KEYS[which]) {
character = NUMPAD_SHIFT_KEYS[which];
} else if (SHIFT_KEYS[character]) {
character = SHIFT_KEYS[character];
}
}
// Shift is 16, ctrl is 17 and alt is 18
if (character && (which < 16 || which > 18)) {
shortcut.push(character);
}
shortcut = shortcut.join('+');
if (shortcutHandlers[shortcut]) {
return shortcutHandlers[shortcut].call(base);
}
};
/**
* Adds a shortcut handler to the editor
* @param {String} shortcut
* @param {String|Function} cmd
* @return {jQuery.sceditor}
*/
base.addShortcut = function (shortcut, cmd) {
shortcut = shortcut.toLowerCase();
if (typeof cmd === 'string') {
shortcutHandlers[shortcut] = function () {
handleCommand(
toolbarButtons[cmd],
base.commands[cmd]
);
return false;
};
} else {
shortcutHandlers[shortcut] = cmd;
}
return base;
};
/**
* Removes a shortcut handler
* @param {String} shortcut
* @return {jQuery.sceditor}
*/
base.removeShortcut = function (shortcut) {
delete shortcutHandlers[shortcut.toLowerCase()];
return base;
};
/**
* Handles the backspace key press
*
* Will remove block styling like quotes/code ect if at the start.
* @private
*/
handleBackSpace = function (e) {
var node, offset, tmpRange, range, parent;
// 8 is the backspace key
if (options.disableBlockRemove || e.which !== 8 ||
!(range = rangeHelper.selectedRange())) {
return;
}
if (!globalWin.getSelection) {
node = range.parentElement();
tmpRange = $wysiwygDoc[0].selection.createRange();
// Select the entire parent and set the end
// as start of the current range
tmpRange.moveToElementText(node);
tmpRange.setEndPoint('EndToStart', range);
// Number of characters selected is the start offset
// relative to the parent node
offset = tmpRange.text.length;
} else {
node = range.startContainer;
offset = range.startOffset;
}
if (offset !== 0 || !(parent = currentStyledBlockNode())) {
return;
}
while (node !== parent) {
while (node.previousSibling) {
node = node.previousSibling;
// Everything but empty text nodes before the cursor
// should prevent the style from being removed
if (node.nodeType !== 3 || node.nodeValue) {
return;
}
}
if (!(node = node.parentNode)) {
return;
}
}
if (!parent || $(parent).is('body')) {
return;
}
// The backspace was pressed at the start of
// the container so clear the style
base.clearBlockFormatting(parent);
return false;
};
/**
* Gets the first styled block node that contains the cursor
* @return {HTMLElement}
*/
currentStyledBlockNode = function () {
var block = currentBlockNode;
while (!dom.hasStyling(block) || dom.isInline(block, true)) {
if (!(block = block.parentNode) || $(block).is('body')) {
return;
}
}
return block;
};
/**
* Clears the formatting of the passed block element.
*
* If block is false, if will clear the styling of the first
* block level element that contains the cursor.
* @param {HTMLElement} block
* @since 1.4.4
*/
base.clearBlockFormatting = function (block) {
block = block || currentStyledBlockNode();
if (!block || $(block).is('body')) {
return base;
}
rangeHelper.saveRange();
block.className = '';
lastRange = null;
$(block).attr('style', '');
if (!$(block).is('p,div,td')) {
dom.convertElement(block, 'p');
}
rangeHelper.restoreRange();
return base;
};
/**
* Triggers the valueChanged signal if there is
* a plugin that handles it.
*
* If rangeHelper.saveRange() has already been
* called, then saveRange should be set to false
* to prevent the range being saved twice.
*
* @since 1.4.5
* @param {Boolean} saveRange If to call rangeHelper.saveRange().
* @private
*/
triggerValueChanged = function (saveRange) {
if (!pluginManager ||
(!pluginManager.hasHandler('valuechangedEvent') &&
!triggerValueChanged.hasHandler)) {
return;
}
var currentHtml,
sourceMode = base.sourceMode(),
hasSelection = !sourceMode && rangeHelper.hasSelection();
// Don't need to save the range if sceditor-start-marker
// is present as the range is already saved
saveRange = saveRange !== false &&
!$wysiwygDoc[0].getElementById('sceditor-start-marker');
// Clear any current timeout as it's now been triggered
if (valueChangedKeyUp.timer) {
clearTimeout(valueChangedKeyUp.timer);
valueChangedKeyUp.timer = false;
}
if (hasSelection && saveRange) {
rangeHelper.saveRange();
}
currentHtml = sourceMode ?
$sourceEditor.val() :
$wysiwygBody.html();
// Only trigger if something has actually changed.
if (currentHtml !== triggerValueChanged.lastHtmlValue) {
triggerValueChanged.lastHtmlValue = currentHtml;
$editorContainer.trigger($.Event('valuechanged', {
rawValue: sourceMode ? base.val() : currentHtml
}));
}
if (hasSelection && saveRange) {
rangeHelper.removeMarkers();
}
};
/**
* Should be called whenever there is a blur event
* @private
*/
valueChangedBlur = function () {
if (valueChangedKeyUp.timer) {
triggerValueChanged();
}
};
/**
* Should be called whenever there is a keypress event
* @param {Event} e The keypress event
* @private
*/
valueChangedKeyUp = function (e) {
var which = e.which,
lastChar = valueChangedKeyUp.lastChar,
lastWasSpace = (lastChar === 13 || lastChar === 32),
lastWasDelete = (lastChar === 8 || lastChar === 46);
valueChangedKeyUp.lastChar = which;
// 13 = return & 32 = space
if (which === 13 || which === 32) {
if (!lastWasSpace) {
triggerValueChanged();
} else {
valueChangedKeyUp.triggerNextChar = true;
}
// 8 = backspace & 46 = del
} else if (which === 8 || which === 46) {
if (!lastWasDelete) {
triggerValueChanged();
} else {
valueChangedKeyUp.triggerNextChar = true;
}
} else if (valueChangedKeyUp.triggerNextChar) {
triggerValueChanged();
valueChangedKeyUp.triggerNextChar = false;
}
// Clear the previous timeout and set a new one.
if (valueChangedKeyUp.timer) {
clearTimeout(valueChangedKeyUp.timer);
}
// Trigger the event 1.5s after the last keypress if space
// isn't pressed. This might need to be lowered, will need
// to look into what the slowest average Chars Per Min is.
valueChangedKeyUp.timer = setTimeout(function () {
triggerValueChanged();
}, 1500);
};
autoUpdate = function () {
if (!autoUpdateCanceled) {
base.updateOriginal();
}
autoUpdateCanceled = false;
};
// run the initializer
init();
};
/**
* Map containing the loaded SCEditor locales
* @type {Object}
* @name locale
* @memberOf jQuery.sceditor
*/
SCEditor.locale = {};
/**
* Static command helper class
* @class command
* @name jQuery.sceditor.command
*/
SCEditor.command =
/** @lends jQuery.sceditor.command */
{
/**
* Gets a command
*
* @param {String} name
* @return {Object|null}
* @since v1.3.5
*/
get: function (name) {
return SCEditor.commands[name] || null;
},
/**
* <p>Adds a command to the editor or updates an existing
* command if a command with the specified name already exists.</p>
*
* <p>Once a command is add it can be included in the toolbar by
* adding it's name to the toolbar option in the constructor. It
* can also be executed manually by calling
* {@link jQuery.sceditor.execCommand}</p>
*
* @example
* SCEditor.command.set("hello",
* {
* exec: function () {
* alert("Hello World!");
* }
* });
*
* @param {String} name
* @param {Object} cmd
* @return {this|false} Returns false if name or cmd is false
* @since v1.3.5
*/
set: function (name, cmd) {
if (!name || !cmd) {
return false;
}
// merge any existing command properties
cmd = $.extend(SCEditor.commands[name] || {}, cmd);
cmd.remove = function () {
SCEditor.command.remove(name);
};
SCEditor.commands[name] = cmd;
return this;
},
/**
* Removes a command
*
* @param {String} name
* @return {this}
* @since v1.3.5
*/
remove: function (name) {
if (SCEditor.commands[name]) {
delete SCEditor.commands[name];
}
return this;
}
};
return SCEditor;
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_RESULT__ = function () {
'use strict';
var plugins = {};
/**
* Plugin Manager class
* @class PluginManager
* @name PluginManager
*/
var PluginManager = function (thisObj) {
/**
* Alias of this
*
* @private
* @type {Object}
*/
var base = this;
/**
* Array of all currently registered plugins
*
* @type {Array}
* @private
*/
var registeredPlugins = [];
/**
* Changes a signals name from "name" into "signalName".
*
* @param {String} signal
* @return {String}
* @private
*/
var formatSignalName = function (signal) {
return 'signal' + signal.charAt(0).toUpperCase() + signal.slice(1);
};
/**
* Calls handlers for a signal
*
* @see call()
* @see callOnlyFirst()
* @param {Array} args
* @param {Boolean} returnAtFirst
* @return {Mixed}
* @private
*/
var callHandlers = function (args, returnAtFirst) {
args = [].slice.call(args);
var idx, ret,
signal = formatSignalName(args.shift());
for (idx = 0; idx < registeredPlugins.length; idx++) {
if (signal in registeredPlugins[idx]) {
ret = registeredPlugins[idx][signal].apply(thisObj, args);
if (returnAtFirst) {
return ret;
}
}
}
};
/**
* Calls all handlers for the passed signal
*
* @param {String} signal
* @param {...String} args
* @return {Void}
* @function
* @name call
* @memberOf PluginManager.prototype
*/
base.call = function () {
callHandlers(arguments, false);
};
/**
* Calls the first handler for a signal, and returns the
*
* @param {String} signal
* @param {...String} args
* @return {Mixed} The result of calling the handler
* @function
* @name callOnlyFirst
* @memberOf PluginManager.prototype
*/
base.callOnlyFirst = function () {
return callHandlers(arguments, true);
};
/**
* Checks if a signal has a handler
*
* @param {String} signal
* @return {Boolean}
* @function
* @name hasHandler
* @memberOf PluginManager.prototype
*/
base.hasHandler = function (signal) {
var i = registeredPlugins.length;
signal = formatSignalName(signal);
while (i--) {
if (signal in registeredPlugins[i]) {
return true;
}
}
return false;
};
/**
* Checks if the plugin exists in plugins
*
* @param {String} plugin
* @return {Boolean}
* @function
* @name exists
* @memberOf PluginManager.prototype
*/
base.exists = function (plugin) {
if (plugin in plugins) {
plugin = plugins[plugin];
return typeof plugin === 'function' &&
typeof plugin.prototype === 'object';
}
return false;
};
/**
* Checks if the passed plugin is currently registered.
*
* @param {String} plugin
* @return {Boolean}
* @function
* @name isRegistered
* @memberOf PluginManager.prototype
*/
base.isRegistered = function (plugin) {
if (base.exists(plugin)) {
var idx = registeredPlugins.length;
while (idx--) {
if (registeredPlugins[idx] instanceof plugins[plugin]) {
return true;
}
}
}
return false;
};
/**
* Registers a plugin to receive signals
*
* @param {String} plugin
* @return {Boolean}
* @function
* @name register
* @memberOf PluginManager.prototype
*/
base.register = function (plugin) {
if (!base.exists(plugin) || base.isRegistered(plugin)) {
return false;
}
plugin = new plugins[plugin]();
registeredPlugins.push(plugin);
if ('init' in plugin) {
plugin.init.call(thisObj);
}
return true;
};
/**
* Deregisters a plugin.
*
* @param {String} plugin
* @return {Boolean}
* @function
* @name deregister
* @memberOf PluginManager.prototype
*/
base.deregister = function (plugin) {
var removedPlugin,
pluginIdx = registeredPlugins.length,
removed = false;
if (!base.isRegistered(plugin)) {
return removed;
}
while (pluginIdx--) {
if (registeredPlugins[pluginIdx] instanceof plugins[plugin]) {
removedPlugin = registeredPlugins.splice(pluginIdx, 1)[0];
removed = true;
if ('destroy' in removedPlugin) {
removedPlugin.destroy.call(thisObj);
}
}
}
return removed;
};
/**
* Clears all plugins and removes the owner reference.
*
* Calling any functions on this object after calling
* destroy will cause a JS error.
*
* @name destroy
* @memberOf PluginManager.prototype
*/
base.destroy = function () {
var i = registeredPlugins.length;
while (i--) {
if ('destroy' in registeredPlugins[i]) {
registeredPlugins[i].destroy.call(thisObj);
}
}
registeredPlugins = [];
thisObj = null;
};
};
PluginManager.plugins = plugins;
return PluginManager;
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_RESULT__ = function (require) {
'use strict';
var $ = __webpack_require__(1);
var dom = __webpack_require__(5);
var escape = __webpack_require__(7);
var browser = __webpack_require__(6);
var IE_VER = browser.ie;
// In IE < 11 a BR at the end of a block level element
// causes a line break. In all other browsers it's collapsed.
var IE_BR_FIX = IE_VER && IE_VER < 11;
var _nodeToHtml = function (node) {
return $('<p>', node.ownerDocument).append(node).html();
};
/**
* Gets the text, start/end node and offset for
* length chars left or right of the passed node
* at the specified offset.
*
* @param {Node} node
* @param {Number} offset
* @param {Boolean} isLeft
* @param {Number} length
* @return {Object}
* @private
*/
var outerText = function (range, isLeft, length) {
var nodeValue, remaining, start, end, node,
text = '',
next = range.startContainer,
offset = range.startOffset;
// Handle cases where node is a paragraph and offset
// refers to the index of a text node.
// 3 = text node
if (next && next.nodeType !== 3) {
next = next.childNodes[offset];
offset = 0;
}
start = end = offset;
while (length > text.length && next && next.nodeType === 3) {
nodeValue = next.nodeValue;
remaining = length - text.length;
// If not the first node, start and end should be at their
// max values as will be updated when getting the text
if (node) {
end = nodeValue.length;
start = 0;
}
node = next;
if (isLeft) {
start = Math.max(end - remaining, 0);
offset = start;
text = nodeValue.substr(start, end - start) + text;
next = node.previousSibling;
} else {
end = Math.min(remaining, nodeValue.length);
offset = start + end;
text += nodeValue.substr(start, end);
next = node.nextSibling;
}
}
return {
node: node || next,
offset: offset,
text: text
};
};
var RangeHelper = function (w, d) {
var _createMarker, _isOwner, _prepareInput,
doc = d || w.contentDocument || w.document,
win = w,
isW3C = !!w.getSelection,
startMarker = 'sceditor-start-marker',
endMarker = 'sceditor-end-marker',
CHARACTER = 'character', // Used to improve minification
base = this;
/**
* <p>Inserts HTML into the current range replacing any selected
* text.</p>
*
* <p>If endHTML is specified the selected contents will be put between
* html and endHTML. If there is nothing selected html and endHTML are
* just concatenate together.</p>
*
* @param {string} html
* @param {string} endHTML
* @return False on fail
* @function
* @name insertHTML
* @memberOf RangeHelper.prototype
*/
base.insertHTML = function (html, endHTML) {
var node, div,
range = base.selectedRange();
if (!range) {
return false;
}
if (isW3C) {
if (endHTML) {
html += base.selectedHtml() + endHTML;
}
div = doc.createElement('p');
node = doc.createDocumentFragment();
div.innerHTML = html;
while (div.firstChild) {
node.appendChild(div.firstChild);
}
base.insertNode(node);
} else {
range.pasteHTML(_prepareInput(html, endHTML, true));
base.restoreRange();
}
};
/**
* Prepares HTML to be inserted by adding a zero width space
* if the last child is empty and adding the range start/end
* markers to the last child.
*
* @param {Node|string} node
* @param {Node|string} endNode
* @param {boolean} returnHtml
* @return {Node|string}
* @private
*/
_prepareInput = function (node, endNode, returnHtml) {
var lastChild, $lastChild,
div = doc.createElement('div'),
$div = $(div);
if (typeof node === 'string') {
if (endNode) {
node += base.selectedHtml() + endNode;
}
$div.html(node);
} else {
$div.append(node);
if (endNode) {
$div
.append(base.selectedRange().extractContents())
.append(endNode);
}
}
if (!(lastChild = div.lastChild)) {
return;
}
while (!dom.isInline(lastChild.lastChild, true)) {
lastChild = lastChild.lastChild;
}
if (dom.canHaveChildren(lastChild)) {
$lastChild = $(lastChild);
// IE <= 8 and Webkit won't allow the cursor to be placed
// inside an empty tag, so add a zero width space to it.
if (!lastChild.lastChild) {
$lastChild.append('\u200B');
}
}
// Needed so IE <= 8 can place the cursor after emoticons and images
if (IE_VER && IE_VER < 9 && $(lastChild).is('img')) {
$div.append('\u200B');
}
base.removeMarkers();
// Append marks to last child so when restored cursor will be in
// the right place
($lastChild || $div)
.append(_createMarker(startMarker))
.append(_createMarker(endMarker));
if (returnHtml) {
return $div.html();
}
return $(doc.createDocumentFragment()).append($div.contents())[0];
};
/**
* <p>The same as insertHTML except with DOM nodes instead</p>
*
* <p><strong>Warning:</strong> the nodes must belong to the
* document they are being inserted into. Some browsers
* will throw exceptions if they don't.</p>
*
* @param {Node} node
* @param {Node} endNode
* @return False on fail
* @function
* @name insertNode
* @memberOf RangeHelper.prototype
*/
base.insertNode = function (node, endNode) {
if (isW3C) {
var input = _prepareInput(node, endNode),
range = base.selectedRange(),
parent = range.commonAncestorContainer;
if (!input) {
return false;
}
range.deleteContents();
// FF allows <br /> to be selected but inserting a node
// into <br /> will cause it not to be displayed so must
// insert before the <br /> in FF.
// 3 = TextNode
if (parent && parent.nodeType !== 3 &&
!dom.canHaveChildren(parent)) {
parent.parentNode.insertBefore(input, parent);
} else {
range.insertNode(input);
}
base.restoreRange();
} else {
base.insertHTML(
_nodeToHtml(node),
endNode ? _nodeToHtml(endNode) : null
);
}
};
/**
* <p>Clones the selected Range</p>
*
* <p>IE <= 8 will return a TextRange, all other browsers
* will return a Range object.</p>
*
* @return {Range|TextRange}
* @function
* @name cloneSelected
* @memberOf RangeHelper.prototype
*/
base.cloneSelected = function () {
var range = base.selectedRange();
if (range) {
return isW3C ? range.cloneRange() : range.duplicate();
}
};
/**
* <p>Gets the selected Range</p>
*
* <p>IE <= 8 will return a TextRange, all other browsers
* will return a Range object.</p>
*
* @return {Range|TextRange}
* @function
* @name selectedRange
* @memberOf RangeHelper.prototype
*/
base.selectedRange = function () {
var range, firstChild,
sel = isW3C ? win.getSelection() : doc.selection;
if (!sel) {
return;
}
// When creating a new range, set the start to the first child
// element of the body element to avoid errors in FF.
if (sel.getRangeAt && sel.rangeCount <= 0) {
firstChild = doc.body;
while (firstChild.firstChild) {
firstChild = firstChild.firstChild;
}
range = doc.createRange();
// Must be setStartBefore otherwise it can cause infinite
// loops with lists in WebKit. See issue 442
range.setStartBefore(firstChild);
sel.addRange(range);
}
if (isW3C && sel.rangeCount > 0) {
range = sel.getRangeAt(0);
}
if (!isW3C && sel.type !== 'Control') {
range = sel.createRange();
}
// IE fix to make sure only return selections that
// are part of the WYSIWYG iframe
return _isOwner(range) ? range : null;
};
/**
* Checks if an IE TextRange range belongs to
* this document or not.
*
* Returns true if the range isn't an IE range or
* if the range is null.
*
* @private
*/
_isOwner = function (range) {
var parent;
if (range && !isW3C) {
parent = range.parentElement();
}
// IE fix to make sure only return selections
// that are part of the WYSIWYG iframe
return parent ?
parent.ownerDocument === doc :
true;
};
/**
* Gets if there is currently a selection
*
* @return {boolean}
* @function
* @name hasSelection
* @since 1.4.4
* @memberOf RangeHelper.prototype
*/
base.hasSelection = function () {
var sel = isW3C ? win.getSelection() : doc.selection;
if (isW3C || !sel) {
return sel && sel.rangeCount > 0;
}
return sel.type !== 'None' && _isOwner(sel.createRange());
};
/**
* Gets the currently selected HTML
*
* @return {string}
* @function
* @name selectedHtml
* @memberOf RangeHelper.prototype
*/
base.selectedHtml = function () {
var div,
range = base.selectedRange();
if (range) {
// IE9+ and all other browsers
if (isW3C) {
div = doc.createElement('p');
div.appendChild(range.cloneContents());
return div.innerHTML;
// IE < 9
} else if (range.text !== '' && range.htmlText) {
return range.htmlText;
}
}
return '';
};
/**
* Gets the parent node of the selected contents in the range
*
* @return {HTMLElement}
* @function
* @name parentNode
* @memberOf RangeHelper.prototype
*/
base.parentNode = function () {
var range = base.selectedRange();
if (range) {
return range.parentElement ?
range.parentElement() :
range.commonAncestorContainer;
}
};
/**
* Gets the first block level parent of the selected
* contents of the range.
*
* @return {HTMLElement}
* @function
* @name getFirstBlockParent
* @memberOf RangeHelper.prototype
*/
/**
* Gets the first block level parent of the selected
* contents of the range.
*
* @param {Node} n The element to get the first block level parent from
* @return {HTMLElement}
* @function
* @name getFirstBlockParent^2
* @since 1.4.1
* @memberOf RangeHelper.prototype
*/
base.getFirstBlockParent = function (n) {
var func = function (node) {
if (!dom.isInline(node, true)) {
return node;
}
node = node ? node.parentNode : null;
return node ? func(node) : node;
};
return func(n || base.parentNode());
};
/**
* Inserts a node at either the start or end of the current selection
*
* @param {Bool} start
* @param {Node} node
* @function
* @name insertNodeAt
* @memberOf RangeHelper.prototype
*/
base.insertNodeAt = function (start, node) {
var currentRange = base.selectedRange(),
range = base.cloneSelected();
if (!range) {
return false;
}
range.collapse(start);
if (isW3C) {
range.insertNode(node);
} else {
range.pasteHTML(_nodeToHtml(node));
}
// Reselect the current range.
// Fixes issue with Chrome losing the selection. Issue#82
base.selectRange(currentRange);
};
/**
* Creates a marker node
*
* @param {string} id
* @return {Node}
* @private
*/
_createMarker = function (id) {
base.removeMarker(id);
var marker = doc.createElement('span');
marker.id = id;
marker.style.lineHeight = '0';
marker.style.display = 'none';
marker.className = 'sceditor-selection sceditor-ignore';
marker.innerHTML = ' ';
return marker;
};
/**
* Inserts start/end markers for the current selection
* which can be used by restoreRange to re-select the
* range.
*
* @memberOf RangeHelper.prototype
* @function
* @name insertMarkers
*/
base.insertMarkers = function () {
base.insertNodeAt(true, _createMarker(startMarker));
base.insertNodeAt(false, _createMarker(endMarker));
};
/**
* Gets the marker with the specified ID
*
* @param {string} id
* @return {Node}
* @function
* @name getMarker
* @memberOf RangeHelper.prototype
*/
base.getMarker = function (id) {
return doc.getElementById(id);
};
/**
* Removes the marker with the specified ID
*
* @param {string} id
* @function
* @name removeMarker
* @memberOf RangeHelper.prototype
*/
base.removeMarker = function (id) {
var marker = base.getMarker(id);
if (marker) {
marker.parentNode.removeChild(marker);
}
};
/**
* Removes the start/end markers
*
* @function
* @name removeMarkers
* @memberOf RangeHelper.prototype
*/
base.removeMarkers = function () {
base.removeMarker(startMarker);
base.removeMarker(endMarker);
};
/**
* Saves the current range location. Alias of insertMarkers()
*
* @function
* @name saveRage
* @memberOf RangeHelper.prototype
*/
base.saveRange = function () {
base.insertMarkers();
};
/**
* Select the specified range
*
* @param {Range|TextRange} range
* @function
* @name selectRange
* @memberOf RangeHelper.prototype
*/
base.selectRange = function (range) {
if (isW3C) {
var lastChild;
var sel = win.getSelection();
var container = range.endContainer;
// Check if cursor is set after a BR when the BR is the only
// child of the parent. In Firefox this causes a line break
// to occur when something is typed. See issue #321
if (!IE_BR_FIX && range.collapsed && container &&
!dom.isInline(container, true)) {
lastChild = container.lastChild;
while (lastChild && $(lastChild).is('.sceditor-ignore')) {
lastChild = lastChild.previousSibling;
}
if ($(lastChild).is('br')) {
var rng = doc.createRange();
rng.setEndAfter(lastChild);
rng.collapse(false);
if (base.compare(range, rng)) {
range.setStartBefore(lastChild);
range.collapse(true);
}
}
}
if (sel) {
base.clear();
sel.addRange(range);
}
} else {
range.select();
}
};
/**
* Restores the last range saved by saveRange() or insertMarkers()
*
* @function
* @name restoreRange
* @memberOf RangeHelper.prototype
*/
base.restoreRange = function () {
var marker, isCollapsed, previousSibling,
range = base.selectedRange(),
start = base.getMarker(startMarker),
end = base.getMarker(endMarker);
if (!start || !end || !range) {
return false;
}
isCollapsed = start.nextSibling === end;
if (!isW3C) {
range = doc.body.createTextRange();
marker = doc.body.createTextRange();
// IE < 9 cannot set focus after a BR so need to insert
// a dummy char after it to allow the cursor to be placed
previousSibling = start.previousSibling;
if (start.nextSibling === end && (!previousSibling ||
!dom.isInline(previousSibling, true) ||
$(previousSibling).is('br'))) {
$(start).before('\u200B');
}
marker.moveToElementText(start);
range.setEndPoint('StartToStart', marker);
range.moveStart(CHARACTER, 0);
marker.moveToElementText(end);
range.setEndPoint('EndToStart', marker);
range.moveEnd(CHARACTER, 0);
} else {
range = doc.createRange();
range.setStartBefore(start);
range.setEndAfter(end);
}
if (isCollapsed) {
range.collapse(true);
}
base.selectRange(range);
base.removeMarkers();
};
/**
* Selects the text left and right of the current selection
*
* @param {int} left
* @param {int} right
* @since 1.4.3
* @function
* @name selectOuterText
* @memberOf RangeHelper.prototype
*/
base.selectOuterText = function (left, right) {
var start, end,
range = base.cloneSelected();
if (!range) {
return false;
}
range.collapse(false);
if (!isW3C) {
range.moveStart(CHARACTER, 0 - left);
range.moveEnd(CHARACTER, right);
} else {
start = outerText(range, true, left);
end = outerText(range, false, right);
range.setStart(start.node, start.offset);
range.setEnd(end.node, end.offset);
}
base.selectRange(range);
};
/**
* Gets the text left or right of the current selection
*
* @param {boolean} before
* @param {number} length
* @since 1.4.3
* @function
* @name selectOuterText
* @memberOf RangeHelper.prototype
*/
base.getOuterText = function (before, length) {
var range = base.cloneSelected();
if (!range) {
return '';
}
range.collapse(!before);
if (!isW3C) {
if (before) {
range.moveStart(CHARACTER, 0 - length);
} else {
range.moveEnd(CHARACTER, length);
}
return range.text;
}
return outerText(range, before, length).text;
};
/**
* Replaces keywords with values based on the current caret position
*
* @param {Array} keywords
* @param {boolean} includeAfter If to include the text after the
* current caret position or just
* text before
* @param {boolean} keywordsSorted If the keywords array is pre
* sorted shortest to longest
* @param {number} longestKeyword Length of the longest keyword
* @param {boolean} requireWhitespace If the key must be surrounded
* by whitespace
* @param {string} keypressChar If this is being called from
* a keypress event, this should be
* set to the pressed character
* @return {boolean}
* @function
* @name replaceKeyword
* @memberOf RangeHelper.prototype
*/
/*jshint maxparams: false*/
base.replaceKeyword = function (
keywords,
includeAfter,
keywordsSorted,
longestKeyword,
requireWhitespace,
keypressChar
) {
if (!keywordsSorted) {
keywords.sort(function (a, b) {
return a[0].length - b[0].length;
});
}
var outerText, matchPos, startIndex, leftLen,
charsLeft, keyword, keywordLen,
whitespaceRegex = '[\\s\xA0\u2002\u2003\u2009]',
keywordIdx = keywords.length,
whitespaceLen = requireWhitespace ? 1 : 0,
maxKeyLen = longestKeyword ||
keywords[keywordIdx - 1][0].length;
if (requireWhitespace) {
// requireWhitespace doesn't work with textRanges as they
// select text on the other side of elements causing
// space-img-key to match when it shouldn't.
if (!isW3C) {
return false;
}
maxKeyLen++;
}
keypressChar = keypressChar || '';
outerText = base.getOuterText(true, maxKeyLen);
leftLen = outerText.length;
outerText += keypressChar;
if (includeAfter) {
outerText += base.getOuterText(false, maxKeyLen);
}
while (keywordIdx--) {
keyword = keywords[keywordIdx][0];
keywordLen = keyword.length;
startIndex = Math.max(0, leftLen - keywordLen - whitespaceLen);
if (requireWhitespace) {
matchPos = outerText
.substr(startIndex)
.search(new RegExp(
'(?:' + whitespaceRegex + ')' +
escape.regex(keyword) +
'(?=' + whitespaceRegex + ')'
));
} else {
matchPos = outerText.indexOf(keyword, startIndex);
}
if (matchPos > -1) {
// Add the length of the text that was removed by substr()
// when matching and also add 1 for the whitespace
if (requireWhitespace) {
matchPos += startIndex + 1;
}
// Make sure the match is between before and
// after, not just entirely in one side or the other
if (matchPos <= leftLen &&
matchPos + keywordLen + whitespaceLen >= leftLen) {
charsLeft = leftLen - matchPos;
// If the keypress char is white space then it should
// not be replaced, only chars that are part of the
// key should be replaced.
base.selectOuterText(
charsLeft,
keywordLen - charsLeft -
(/^\S/.test(keypressChar) ? 1 : 0)
);
base.insertHTML(keywords[keywordIdx][1]);
return true;
}
}
}
return false;
};
/**
* Compares two ranges.
*
* If rangeB is undefined it will be set to
* the current selected range
*
* @param {Range|TextRange} rangeA
* @param {Range|TextRange} rangeB
* @return {boolean}
*/
base.compare = function (rangeA, rangeB) {
var END_TO_END = isW3C ? Range.END_TO_END : 'EndToEnd',
START_TO_START = isW3C ? Range.START_TO_START : 'StartToStart',
comparePoints = isW3C ?
'compareBoundaryPoints' :
'compareEndPoints';
if (!rangeB) {
rangeB = base.selectedRange();
}
if (!rangeA || !rangeB) {
return !rangeA && !rangeB;
}
return _isOwner(rangeA) && _isOwner(rangeB) &&
rangeA[comparePoints](END_TO_END, rangeB) === 0 &&
rangeA[comparePoints](START_TO_START, rangeB) === 0;
};
/**
* Removes any current selection
*
* @since 1.4.6
*/
base.clear = function () {
var sel = isW3C ? win.getSelection() : doc.selection;
if (sel) {
if (sel.removeAllRanges) {
sel.removeAllRanges();
} else if (sel.empty) {
sel.empty();
}
}
};
};
return RangeHelper;
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_RESULT__ = function (require) {
'use strict';
var $ = __webpack_require__(1);
var browser = __webpack_require__(6);
var _propertyNameCache = {};
var dom = {
/**
* Loop all child nodes of the passed node
*
* The function should accept 1 parameter being the node.
* If the function returns false the loop will be exited.
*
* @param {HTMLElement} node
* @param {Function} func Callback which is called with every
* child node as the first argument.
* @param {bool} innermostFirst If the innermost node should be passed
* to the function before it's parents.
* @param {bool} siblingsOnly If to only traverse the nodes siblings
* @param {bool} reverse If to traverse the nodes in reverse
*/
/*jshint maxparams: false*/
traverse: function (node, func, innermostFirst, siblingsOnly, reverse) {
if (node) {
node = reverse ? node.lastChild : node.firstChild;
while (node) {
var next = reverse ?
node.previousSibling :
node.nextSibling;
if (
(!innermostFirst && func(node) === false) ||
(!siblingsOnly && dom.traverse(
node, func, innermostFirst, siblingsOnly, reverse
) === false) ||
(innermostFirst && func(node) === false)
) {
return false;
}
// move to next child
node = next;
}
}
},
/**
* Like traverse but loops in reverse
* @see traverse
*/
rTraverse: function (node, func, innermostFirst, siblingsOnly) {
this.traverse(node, func, innermostFirst, siblingsOnly, true);
},
/**
* Parses HTML
*
* @param {String} html
* @param {Document} context
* @since 1.4.4
* @return {Array}
*/
parseHTML: function (html, context) {
var ret = [],
tmp = (context || document).createElement('div');
tmp.innerHTML = html;
$.merge(ret, tmp.childNodes);
return ret;
},
/**
* Checks if an element has any styling.
*
* It has styling if it is not a plain <div> or <p> or
* if it has a class, style attribute or data.
*
* @param {HTMLElement} elm
* @return {Boolean}
* @since 1.4.4
*/
hasStyling: function (elm) {
var $elm = $(elm);
return elm && (!$elm.is('p,div') || elm.className ||
$elm.attr('style') || !$.isEmptyObject($elm.data()));
},
/**
* Converts an element from one type to another.
*
* For example it can convert the element <b> to <strong>
*
* @param {HTMLElement} oldElm
* @param {String} toTagName
* @return {HTMLElement}
* @since 1.4.4
*/
convertElement: function (oldElm, toTagName) {
var child, attr,
oldAttrs = oldElm.attributes,
attrsIdx = oldAttrs.length,
newElm = oldElm.ownerDocument.createElement(toTagName);
while (attrsIdx--) {
attr = oldAttrs[attrsIdx];
// IE < 8 returns all possible attributes instead of just
// the specified ones so have to check it is specified.
if (!browser.ie || attr.specified) {
// IE < 8 doesn't return the CSS for the style attribute
// so must copy it manually
if (browser.ie < 8 && /style/i.test(attr.name)) {
dom.copyCSS(oldElm, newElm);
} else {
// Some browsers parse invalid attributes names like
// 'size"2' which throw an exception when set, just
// ignore these.
try {
newElm.setAttribute(attr.name, attr.value);
} catch (ex) {}
}
}
}
while ((child = oldElm.firstChild)) {
newElm.appendChild(child);
}
oldElm.parentNode.replaceChild(newElm, oldElm);
return newElm;
},
/**
* List of block level elements separated by bars (|)
* @type {string}
*/
blockLevelList: '|body|hr|p|div|h1|h2|h3|h4|h5|h6|address|pre|form|' +
'table|tbody|thead|tfoot|th|tr|td|li|ol|ul|blockquote|center|',
/**
* List of elements that do not allow children separated by bars (|)
*
* @param {Node} node
* @return {bool}
* @since 1.4.5
*/
canHaveChildren: function (node) {
// 1 = Element
// 9 = Document
// 11 = Document Fragment
if (!/11?|9/.test(node.nodeType)) {
return false;
}
// List of empty HTML tags separated by bar (|) character.
// Source: http://www.w3.org/TR/html4/index/elements.html
// Source: http://www.w3.org/TR/html5/syntax.html#void-elements
return ('|iframe|area|base|basefont|br|col|frame|hr|img|input|wbr' +
'|isindex|link|meta|param|command|embed|keygen|source|track|' +
'object|').indexOf('|' + node.nodeName.toLowerCase() + '|') < 0;
},
/**
* Checks if an element is inline
*
* @return {bool}
*/
isInline: function (elm, includeCodeAsBlock) {
var tagName,
nodeType = (elm || {}).nodeType || 3;
if (nodeType !== 1) {
return nodeType === 3;
}
tagName = elm.tagName.toLowerCase();
if (tagName === 'code') {
return !includeCodeAsBlock;
}
return dom.blockLevelList.indexOf('|' + tagName + '|') < 0;
},
/**
* <p>Copys the CSS from 1 node to another.</p>
*
* <p>Only copies CSS defined on the element e.g. style attr.</p>
*
* @param {HTMLElement} from
* @param {HTMLElement} to
*/
copyCSS: function (from, to) {
to.style.cssText = from.style.cssText + to.style.cssText;
},
/**
* Fixes block level elements inside in inline elements.
*
* @param {HTMLElement} node
*/
fixNesting: function (node) {
var getLastInlineParent = function (node) {
while (dom.isInline(node.parentNode, true)) {
node = node.parentNode;
}
return node;
};
dom.traverse(node, function (node) {
// Any blocklevel element inside an inline element needs fixing.
if (node.nodeType === 1 && !dom.isInline(node, true) &&
dom.isInline(node.parentNode, true)) {
var parent = getLastInlineParent(node),
rParent = parent.parentNode,
before = dom.extractContents(parent, node),
middle = node;
// copy current styling so when moved out of the parent
// it still has the same styling
dom.copyCSS(parent, middle);
rParent.insertBefore(before, parent);
rParent.insertBefore(middle, parent);
}
});
},
/**
* Finds the common parent of two nodes
*
* @param {HTMLElement} node1
* @param {HTMLElement} node2
* @return {HTMLElement}
*/
findCommonAncestor: function (node1, node2) {
// Not as fast as making two arrays of parents and comparing
// but is a lot smaller and as it's currently only used with
// fixing invalid nesting it doesn't need to be very fast
return $(node1).parents().has($(node2)).first();
},
getSibling: function (node, previous) {
if (!node) {
return null;
}
return (previous ? node.previousSibling : node.nextSibling) ||
dom.getSibling(node.parentNode, previous);
},
/**
* Removes unused whitespace from the root and all it's children
*
* @name removeWhiteSpace^1
* @param {HTMLElement} root
*/
/**
* Removes unused whitespace from the root and all it's children.
*
* If preserveNewLines is true, new line characters will not be removed
*
* @name removeWhiteSpace^2
* @param {HTMLElement} root
* @param {boolean} preserveNewLines
* @since 1.4.3
*/
removeWhiteSpace: function (root, preserveNewLines) {
var nodeValue, nodeType, next, previous, previousSibling,
cssWhiteSpace, nextNode, trimStart,
getSibling = dom.getSibling,
isInline = dom.isInline,
node = root.firstChild;
while (node) {
nextNode = node.nextSibling;
nodeValue = node.nodeValue;
nodeType = node.nodeType;
// 1 = element
if (nodeType === 1 && node.firstChild) {
cssWhiteSpace = $(node).css('whiteSpace');
// Skip all pre & pre-wrap with any vendor prefix
if (!/pre(\-wrap)?$/i.test(cssWhiteSpace)) {
dom.removeWhiteSpace(
node,
/line$/i.test(cssWhiteSpace)
);
}
}
// 3 = textnode
if (nodeType === 3 && nodeValue) {
next = getSibling(node);
previous = getSibling(node, true);
trimStart = false;
while ($(previous).hasClass('sceditor-ignore')) {
previous = getSibling(previous, true);
}
// If previous sibling isn't inline or is a textnode that
// ends in whitespace, time the start whitespace
if (isInline(node) && previous) {
previousSibling = previous;
while (previousSibling.lastChild) {
previousSibling = previousSibling.lastChild;
}
trimStart = previousSibling.nodeType === 3 ?
/[\t\n\r ]$/.test(previousSibling.nodeValue) :
!isInline(previousSibling);
}
// Clear zero width spaces
nodeValue = nodeValue.replace(/\u200B/g, '');
// Strip leading whitespace
if (!previous || !isInline(previous) || trimStart) {
nodeValue = nodeValue.replace(
preserveNewLines ? /^[\t ]+/ : /^[\t\n\r ]+/,
''
);
}
// Strip trailing whitespace
if (!next || !isInline(next)) {
nodeValue = nodeValue.replace(
preserveNewLines ? /[\t ]+$/ : /[\t\n\r ]+$/,
''
);
}
// Remove empty text nodes
if (!nodeValue.length) {
root.removeChild(node);
} else {
node.nodeValue = nodeValue.replace(
preserveNewLines ? /[\t ]+/g : /[\t\n\r ]+/g,
' '
);
}
}
node = nextNode;
}
},
/**
* Extracts all the nodes between the start and end nodes
*
* @param {HTMLElement} startNode The node to start extracting at
* @param {HTMLElement} endNode The node to stop extracting at
* @return {DocumentFragment}
*/
extractContents: function (startNode, endNode) {
var extract,
commonAncestor = dom
.findCommonAncestor(startNode, endNode)
.get(0),
startReached = false,
endReached = false;
extract = function (root) {
var clone,
docFrag = startNode.ownerDocument.createDocumentFragment();
dom.traverse(root, function (node) {
// if end has been reached exit loop
if (endReached || node === endNode) {
endReached = true;
return false;
}
if (node === startNode) {
startReached = true;
}
// if the start has been reached and this elm contains
// the end node then clone it
// if this node contains the start node then add it
if ($.contains(node, startNode) ||
(startReached && $.contains(node, endNode))) {
clone = node.cloneNode(false);
clone.appendChild(extract(node));
docFrag.appendChild(clone);
// otherwise move it if its parent isn't already part of it
} else if (startReached && !$.contains(docFrag, node)) {
docFrag.appendChild(node);
}
}, false);
return docFrag;
};
return extract(commonAncestor);
},
/**
* Gets the offset position of an element
*
* @param {HTMLElement} obj
* @return {Object} An object with left and top properties
*/
getOffset: function (obj) {
var pLeft = 0,
pTop = 0;
while (obj) {
pLeft += obj.offsetLeft;
pTop += obj.offsetTop;
obj = obj.offsetParent;
}
return {
left: pLeft,
top: pTop
};
},
/**
* Gets the value of a CSS property from the elements style attribute
*
* @param {HTMLElement} elm
* @param {String} property
* @return {String}
*/
getStyle: function (elm, property) {
var $elm, direction, styleValue,
elmStyle = elm.style;
if (!elmStyle) {
return '';
}
if (!_propertyNameCache[property]) {
_propertyNameCache[property] = $.camelCase(property);
}
property = _propertyNameCache[property];
styleValue = elmStyle[property];
// Add an exception for text-align
if ('textAlign' === property) {
$elm = $(elm);
direction = elmStyle.direction;
styleValue = styleValue || $elm.css(property);
if ($elm.parent().css(property) === styleValue ||
$elm.css('display') !== 'block' ||
$elm.is('hr') || $elm.is('th')) {
return '';
}
// check all works with changes and merge with prev?
// IE changes text-align to the same as the current direction
// so skip unless its not the same
if ((/right/i.test(styleValue) && direction === 'rtl') ||
(/left/i.test(styleValue) && direction === 'ltr')) {
return '';
}
}
return styleValue;
},
/**
* Tests if an element has a style.
*
* If values are specified it will check that the styles value
* matches one of the values
*
* @param {HTMLElement} elm
* @param {String} property
* @param {String|Array} values
* @return {Boolean}
*/
hasStyle: function (elm, property, values) {
var styleValue = dom.getStyle(elm, property);
if (!styleValue) {
return false;
}
return !values || styleValue === values ||
($.isArray(values) && $.inArray(styleValue, values) > -1);
}
};
return dom;
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_RESULT__ = function (require, exports) {
'use strict';
var $ = __webpack_require__(1);
var USER_AGENT = navigator.userAgent;
/**
* Detects the version of IE is being used if any.
*
* Will be the IE version number or undefined if the
* browser is not IE.
*
* Source: https://gist.github.com/527683 with extra code
* for IE 10 & 11 detection.
*
* @function
* @name ie
* @type {int}
*/
exports.ie = (function () {
var undef,
v = 3,
doc = document,
div = doc.createElement('div'),
all = div.getElementsByTagName('i');
do {
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->';
} while (all[0]);
// Detect IE 10 as it doesn't support conditional comments.
if ((doc.documentMode && doc.all && window.atob)) {
v = 10;
}
// Detect IE 11
if (v === 4 && doc.documentMode) {
v = 11;
}
return v > 4 ? v : undef;
}());
/**
* <p>Detects if the browser is iOS</p>
*
* <p>Needed to fix iOS specific bugs/</p>
*
* @function
* @name ios
* @memberOf jQuery.sceditor
* @type {Boolean}
*/
exports.ios = /iPhone|iPod|iPad| wosbrowser\//i.test(USER_AGENT);
/**
* If the browser supports WYSIWYG editing (e.g. older mobile browsers).
*
* @function
* @name isWysiwygSupported
* @return {Boolean}
*/
exports.isWysiwygSupported = (function () {
var match, isUnsupported, undef,
editableAttr = $('<p contenteditable="true">')[0].contentEditable;
// Check if the contenteditable attribute is supported
if (editableAttr === undef || editableAttr === 'inherit') {
return false;
}
// I think blackberry supports contentEditable or will at least
// give a valid value for the contentEditable detection above
// so it isn't included in the below tests.
// I hate having to do UA sniffing but some mobile browsers say they
// support contentediable when it isn't usable, i.e. you can't enter
// text.
// This is the only way I can think of to detect them which is also how
// every other editor I've seen deals with this issue.
// Exclude Opera mobile and mini
isUnsupported = /Opera Mobi|Opera Mini/i.test(USER_AGENT);
if (/Android/i.test(USER_AGENT)) {
isUnsupported = true;
if (/Safari/.test(USER_AGENT)) {
// Android browser 534+ supports content editable
// This also matches Chrome which supports content editable too
match = /Safari\/(\d+)/.exec(USER_AGENT);
isUnsupported = (!match || !match[1] ? true : match[1] < 534);
}
}
// The current version of Amazon Silk supports it, older versions didn't
// As it uses webkit like Android, assume it's the same and started
// working at versions >= 534
if (/ Silk\//i.test(USER_AGENT)) {
match = /AppleWebKit\/(\d+)/.exec(USER_AGENT);
isUnsupported = (!match || !match[1] ? true : match[1] < 534);
}
// iOS 5+ supports content editable
if (exports.ios) {
// Block any version <= 4_x(_x)
isUnsupported = /OS [0-4](_\d)+ like Mac/i.test(USER_AGENT);
}
// FireFox does support WYSIWYG on mobiles so override
// any previous value if using FF
if (/Firefox/i.test(USER_AGENT)) {
isUnsupported = false;
}
if (/OneBrowser/i.test(USER_AGENT)) {
isUnsupported = false;
}
// UCBrowser works but doesn't give a unique user agent
if (navigator.vendor === 'UCWEB') {
isUnsupported = false;
}
return !isUnsupported;
}());
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_RESULT__ = function (require, exports) {
'use strict';
var VALID_SCHEME_REGEX =
/^(?:https?|s?ftp|mailto|spotify|skype|ssh|teamspeak|tel):|(?:\/\/)/i;
/**
* Escapes a string so it's safe to use in regex
*
* @param {String} str
* @return {String}
* @name regex
*/
exports.regex = function (str) {
return str.replace(/([\-.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
};
/**
* Escapes all HTML entities in a string
*
* If noQuotes is set to false, all single and double
* quotes will also be escaped
*
* @param {String} str
* @param {Boolean} [noQuotes=false]
* @return {String}
* @name entities
* @since 1.4.1
*/
exports.entities = function (str, noQuotes) {
if (!str) {
return str;
}
var replacements = {
'&': '&',
'<': '<',
'>': '>',
' ': ' ',
'\r\n': '\n',
'\r': '\n',
'\n': '<br />'
};
if (noQuotes !== false) {
replacements['"'] = '"';
replacements['\''] = ''';
replacements['`'] = '`';
}
str = str.replace(/ {2}|\r\n|[&<>\r\n'"`]/g, function (match) {
return replacements[match] || match;
});
return str;
};
/**
* Escape URI scheme.
*
* Appends the current URL to a url if it has a scheme that is not:
*
* http
* https
* sftp
* ftp
* mailto
* spotify
* skype
* ssh
* teamspeak
* tel
* //
*
* **IMPORTANT**: This does not escape any HTML in a url, for
* that use the escape.entities() method.
*
* @param {String} url
* @return {String}
* @name escapeUriScheme
* @memberOf jQuery.sceditor
* @since 1.4.5
*/
exports.uriScheme = function (url) {
/*jshint maxlen:false*/
var path,
// If there is a : before a / then it has a scheme
hasScheme = /^[^\/]*:/i,
location = window.location;
// Has no scheme or a valid scheme
if ((!url || !hasScheme.test(url)) || VALID_SCHEME_REGEX.test(url)) {
return url;
}
path = location.pathname.split('/');
path.pop();
return location.protocol + '//' +
location.host +
path.join('/') + '/' +
url;
};
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_RESULT__ = function () {
'use strict';
/**
* HTML templates used by the editor and default commands
* @type {Object}
* @private
*/
var _templates = {
html:
'<!DOCTYPE html>' +
'<html{attrs}>' +
'<head>' +
// TODO: move these styles into the CSS file
'<style>.ie * {min-height: auto !important} ' +
'.ie table td {height:15px} ' +
// Target Edge (fixes edge issues)
'@supports (-ms-ime-align:auto) { ' +
'* { min-height: auto !important; } ' +
'}' +
'</style>' +
'<meta http-equiv="Content-Type" ' +
'content="text/html;charset={charset}" />' +
'<link rel="stylesheet" type="text/css" href="{style}" />' +
'</head>' +
'<body contenteditable="true" {spellcheck}><p></p></body>' +
'</html>',
toolbarButton: '<a class="sceditor-button sceditor-button-{name}" ' +
'data-sceditor-command="{name}" unselectable="on">' +
'<div unselectable="on">{dispName}</div></a>',
emoticon: '<img src="{url}" data-sceditor-emoticon="{key}" ' +
'alt="{key}" title="{tooltip}" />',
fontOpt: '<a class="sceditor-font-option" href="#" ' +
'data-font="{font}"><font face="{font}">{font}</font></a>',
sizeOpt: '<a class="sceditor-fontsize-option" data-size="{size}" ' +
'href="#"><font size="{size}">{size}</font></a>',
pastetext:
'<div><label for="txt">{label}</label> ' +
'<textarea cols="20" rows="7" id="txt"></textarea></div>' +
'<div><input type="button" class="button" value="{insert}" />' +
'</div>',
table:
'<div><label for="rows">{rows}</label><input type="text" ' +
'id="rows" value="2" /></div>' +
'<div><label for="cols">{cols}</label><input type="text" ' +
'id="cols" value="2" /></div>' +
'<div><input type="button" class="button" value="{insert}"' +
' /></div>',
image:
'<div><label for="link">{url}</label> ' +
'<input type="text" id="image" placeholder="http://" /></div>' +
'<div><label for="width">{width}</label> ' +
'<input type="text" id="width" size="2" /></div>' +
'<div><label for="height">{height}</label> ' +
'<input type="text" id="height" size="2" /></div>' +
'<div><input type="button" class="button" value="{insert}" />' +
'</div>',
email:
'<div><label for="email">{label}</label> ' +
'<input type="text" id="email" /></div>' +
'<div><label for="des">{desc}</label> ' +
'<input type="text" id="des" /></div>' +
'<div><input type="button" class="button" value="{insert}" />' +
'</div>',
link:
'<div><label for="link">{url}</label> ' +
'<input type="text" id="link" placeholder="http://" /></div>' +
'<div><label for="des">{desc}</label> ' +
'<input type="text" id="des" /></div>' +
'<div><input type="button" class="button" value="{ins}" /></div>',
youtubeMenu:
'<div><label for="link">{label}</label> ' +
'<input type="text" id="link" placeholder="https://" /></div>' +
'<div><input type="button" class="button" value="{insert}" />' +
'</div>',
youtube:
'<iframe width="560" height="315" ' +
'src="https://www.youtube.com/embed/{id}?wmode=opaque" ' +
'data-youtube-id="{id}" frameborder="0" allowfullscreen></iframe>'
};
/**
* <p>Replaces any params in a template with the passed params.</p>
*
* <p>If createHtml is passed it will use jQuery to create the HTML. The
* same as doing: $(editor.tmpl("html", {params...}));</p>
*
* @param {string} name
* @param {Object} params
* @param {Boolean} createHtml
* @private
*/
return function (name, params, createHtml) {
var template = _templates[name];
$.each(params, function (name, val) {
template = template.replace(
new RegExp('\\{' + name + '\\}', 'g'), val
);
});
if (createHtml) {
template = $(template);
}
return template;
};
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_RESULT__ = function (require) {
'use strict';
var $ = __webpack_require__(1);
var IE_VER = __webpack_require__(6).ie;
var _tmpl = __webpack_require__(8);
// In IE < 11 a BR at the end of a block level element
// causes a line break. In all other browsers it's collapsed.
var IE_BR_FIX = IE_VER && IE_VER < 11;
/**
* Map of all the commands for SCEditor
* @type {Object}
* @name commands
* @memberOf jQuery.sceditor
*/
var defaultCommnds = {
// START_COMMAND: Bold
bold: {
exec: 'bold',
tooltip: 'Bold',
shortcut: 'Ctrl+B'
},
// END_COMMAND
// START_COMMAND: Italic
italic: {
exec: 'italic',
tooltip: 'Italic',
shortcut: 'Ctrl+I'
},
// END_COMMAND
// START_COMMAND: Underline
underline: {
exec: 'underline',
tooltip: 'Underline',
shortcut: 'Ctrl+U'
},
// END_COMMAND
// START_COMMAND: Strikethrough
strike: {
exec: 'strikethrough',
tooltip: 'Strikethrough'
},
// END_COMMAND
// START_COMMAND: Subscript
subscript: {
exec: 'subscript',
tooltip: 'Subscript'
},
// END_COMMAND
// START_COMMAND: Superscript
superscript: {
exec: 'superscript',
tooltip: 'Superscript'
},
// END_COMMAND
// START_COMMAND: Left
left: {
exec: 'justifyleft',
tooltip: 'Align left'
},
// END_COMMAND
// START_COMMAND: Centre
center: {
exec: 'justifycenter',
tooltip: 'Center'
},
// END_COMMAND
// START_COMMAND: Right
right: {
exec: 'justifyright',
tooltip: 'Align right'
},
// END_COMMAND
// START_COMMAND: Justify
justify: {
exec: 'justifyfull',
tooltip: 'Justify'
},
// END_COMMAND
// START_COMMAND: Font
font: {
_dropDown: function (editor, caller, callback) {
var fontIdx = 0,
fonts = editor.opts.fonts.split(','),
content = $('<div />'),
/** @private */
clickFunc = function () {
callback($(this).data('font'));
editor.closeDropDown(true);
return false;
};
for (; fontIdx < fonts.length; fontIdx++) {
content.append(
_tmpl('fontOpt', {
font: fonts[fontIdx]
}, true).click(clickFunc)
);
}
editor.createDropDown(caller, 'font-picker', content);
},
exec: function (caller) {
var editor = this;
defaultCommnds.font._dropDown(
editor,
caller,
function (fontName) {
editor.execCommand('fontname', fontName);
}
);
},
tooltip: 'Font Name'
},
// END_COMMAND
// START_COMMAND: Size
size: {
_dropDown: function (editor, caller, callback) {
var content = $('<div />'),
/** @private */
clickFunc = function (e) {
callback($(this).data('size'));
editor.closeDropDown(true);
e.preventDefault();
};
for (var i = 1; i <= 7; i++) {
content.append(_tmpl('sizeOpt', {
size: i
}, true).click(clickFunc));
}
editor.createDropDown(caller, 'fontsize-picker', content);
},
exec: function (caller) {
var editor = this;
defaultCommnds.size._dropDown(
editor,
caller,
function (fontSize) {
editor.execCommand('fontsize', fontSize);
}
);
},
tooltip: 'Font Size'
},
// END_COMMAND
// START_COMMAND: Colour
color: {
_dropDown: function (editor, caller, callback) {
var i, x, color, colors,
genColor = {r: 255, g: 255, b: 255},
content = $('<div />'),
colorColumns = editor.opts.colors ?
editor.opts.colors.split('|') : new Array(21),
// IE is slow at string concatenation so use an array
html = [],
cmd = defaultCommnds.color;
if (!cmd._htmlCache) {
for (i = 0; i < colorColumns.length; ++i) {
colors = colorColumns[i] ?
colorColumns[i].split(',') : new Array(21);
html.push('<div class="sceditor-color-column">');
for (x = 0; x < colors.length; ++x) {
// use pre defined colour if can otherwise use the
// generated color
color = colors[x] || '#' +
genColor.r.toString(16) +
genColor.g.toString(16) +
genColor.b.toString(16);
html.push(
'<a href="#" class="sceditor-color-option"' +
' style="background-color: ' + color + '"' +
' data-color="' + color + '"></a>'
);
if (x % 5 === 0) {
genColor.g -= 51;
genColor.b = 255;
} else {
genColor.b -= 51;
}
}
html.push('</div>');
if (i % 5 === 0) {
genColor.r -= 51;
genColor.g = 255;
genColor.b = 255;
} else {
genColor.g = 255;
genColor.b = 255;
}
}
cmd._htmlCache = html.join('');
}
content.append(cmd._htmlCache)
.find('a')
.click(function (e) {
callback($(this).attr('data-color'));
editor.closeDropDown(true);
e.preventDefault();
});
editor.createDropDown(caller, 'color-picker', content);
},
exec: function (caller) {
var editor = this;
defaultCommnds.color._dropDown(
editor,
caller,
function (color) {
editor.execCommand('forecolor', color);
}
);
},
tooltip: 'Font Color'
},
// END_COMMAND
// START_COMMAND: Remove Format
removeformat: {
exec: 'removeformat',
tooltip: 'Remove Formatting'
},
// END_COMMAND
// START_COMMAND: Cut
cut: {
exec: 'cut',
tooltip: 'Cut',
errorMessage: 'Your browser does not allow the cut command. ' +
'Please use the keyboard shortcut Ctrl/Cmd-X'
},
// END_COMMAND
// START_COMMAND: Copy
copy: {
exec: 'copy',
tooltip: 'Copy',
errorMessage: 'Your browser does not allow the copy command. ' +
'Please use the keyboard shortcut Ctrl/Cmd-C'
},
// END_COMMAND
// START_COMMAND: Paste
paste: {
exec: 'paste',
tooltip: 'Paste',
errorMessage: 'Your browser does not allow the paste command. ' +
'Please use the keyboard shortcut Ctrl/Cmd-V'
},
// END_COMMAND
// START_COMMAND: Paste Text
pastetext: {
exec: function (caller) {
var val, content,
editor = this;
content = _tmpl('pastetext', {
label: editor._(
'Paste your text inside the following box:'
),
insert: editor._('Insert')
}, true);
content.find('.button').click(function (e) {
val = content.find('#txt').val();
if (val) {
editor.wysiwygEditorInsertText(val);
}
editor.closeDropDown(true);
e.preventDefault();
});
editor.createDropDown(caller, 'pastetext', content);
},
tooltip: 'Paste Text'
},
// END_COMMAND
// START_COMMAND: Bullet List
bulletlist: {
exec: 'insertunorderedlist',
tooltip: 'Bullet list'
},
// END_COMMAND
// START_COMMAND: Ordered List
orderedlist: {
exec: 'insertorderedlist',
tooltip: 'Numbered list'
},
// END_COMMAND
// START_COMMAND: Indent
indent: {
state: function (parents, firstBlock) {
// Only works with lists, for now
// This is a nested list, so it will always work
var range, startParent, endParent,
$firstBlock = $(firstBlock),
parentLists = $firstBlock.parents('ul,ol,menu'),
parentList = parentLists.first();
// in case it's a list with only a single <li>
if (parentLists.length > 1 ||
parentList.children().length > 1) {
return 0;
}
if ($firstBlock.is('ul,ol,menu')) {
// if the whole list is selected, then this must be
// invalidated because the browser will place a
// <blockquote> there
range = this.getRangeHelper().selectedRange();
if (window.Range && range instanceof Range) {
startParent = range.startContainer.parentNode;
endParent = range.endContainer.parentNode;
// TODO: could use nodeType for this?
// Maybe just check the firstBlock contains both the start and end containers
// Select the tag, not the textNode
// (that's why the parentNode)
if (startParent !==
startParent.parentNode.firstElementChild ||
// work around a bug in FF
($(endParent).is('li') && endParent !==
endParent.parentNode.lastElementChild)) {
return 0;
}
// it's IE... As it is impossible to know well when to
// accept, better safe than sorry
} else {
return $firstBlock.is('li,ul,ol,menu') ? 0 : -1;
}
}
return -1;
},
exec: function () {
var editor = this,
$elm = $(editor.getRangeHelper().getFirstBlockParent());
editor.focus();
// An indent system is quite complicated as there are loads
// of complications and issues around how to indent text
// As default, let's just stay with indenting the lists,
// at least, for now.
if ($elm.parents('ul,ol,menu')) {
editor.execCommand('indent');
}
},
tooltip: 'Add indent'
},
// END_COMMAND
// START_COMMAND: Outdent
outdent: {
state: function (parents, firstBlock) {
return $(firstBlock).is('ul,ol,menu') ||
$(firstBlock).parents('ul,ol,menu').length > 0 ? 0 : -1;
},
exec: function () {
var editor = this,
$elm = $(editor.getRangeHelper().getFirstBlockParent());
if ($elm.parents('ul,ol,menu')) {
editor.execCommand('outdent');
}
},
tooltip: 'Remove one indent'
},
// END_COMMAND
// START_COMMAND: Table
table: {
forceNewLineAfter: ['table'],
exec: function (caller) {
var editor = this,
content = _tmpl('table', {
rows: editor._('Rows:'),
cols: editor._('Cols:'),
insert: editor._('Insert')
}, true);
content.find('.button').click(function (e) {
var row, col,
rows = content.find('#rows').val() - 0,
cols = content.find('#cols').val() - 0,
html = '<table>';
if (rows < 1 || cols < 1) {
return;
}
for (row = 0; row < rows; row++) {
html += '<tr>';
for (col = 0; col < cols; col++) {
html += '<td>' +
(IE_BR_FIX ? '' : '<br />') +
'</td>';
}
html += '</tr>';
}
html += '</table>';
editor.wysiwygEditorInsertHtml(html);
editor.closeDropDown(true);
e.preventDefault();
});
editor.createDropDown(caller, 'inserttable', content);
},
tooltip: 'Insert a table'
},
// END_COMMAND
// START_COMMAND: Horizontal Rule
horizontalrule: {
exec: 'inserthorizontalrule',
tooltip: 'Insert a horizontal rule'
},
// END_COMMAND
// START_COMMAND: Code
code: {
forceNewLineAfter: ['code'],
exec: function () {
this.wysiwygEditorInsertHtml(
'<code>',
(IE_BR_FIX ? '' : '<br />') + '</code>'
);
},
tooltip: 'Code'
},
// END_COMMAND
// START_COMMAND: Image
image: {
exec: function (caller) {
var editor = this,
content = _tmpl('image', {
url: editor._('URL:'),
width: editor._('Width (optional):'),
height: editor._('Height (optional):'),
insert: editor._('Insert')
}, true);
content.find('.button').click(function (e) {
var val = content.find('#image').val(),
width = content.find('#width').val(),
height = content.find('#height').val(),
attrs = '';
if (width) {
attrs += ' width="' + width + '"';
}
if (height) {
attrs += ' height="' + height + '"';
}
if (val) {
editor.wysiwygEditorInsertHtml(
'<img' + attrs + ' src="' + val + '" />'
);
}
editor.closeDropDown(true);
e.preventDefault();
});
editor.createDropDown(caller, 'insertimage', content);
},
tooltip: 'Insert an image'
},
// END_COMMAND
// START_COMMAND: E-mail
email: {
exec: function (caller) {
var editor = this,
content = _tmpl('email', {
label: editor._('E-mail:'),
desc: editor._('Description (optional):'),
insert: editor._('Insert')
}, true);
content.find('.button').click(function (e) {
var val = content.find('#email').val(),
description = content.find('#des').val();
if (val) {
// needed for IE to reset the last range
editor.focus();
if (!editor.getRangeHelper().selectedHtml() ||
description) {
description = description || val;
editor.wysiwygEditorInsertHtml(
'<a href="' + 'mailto:' + val + '">' +
description +
'</a>'
);
} else {
editor.execCommand('createlink', 'mailto:' + val);
}
}
editor.closeDropDown(true);
e.preventDefault();
});
editor.createDropDown(caller, 'insertemail', content);
},
tooltip: 'Insert an email'
},
// END_COMMAND
// START_COMMAND: Link
link: {
exec: function (caller) {
var editor = this,
content = _tmpl('link', {
url: editor._('URL:'),
desc: editor._('Description (optional):'),
ins: editor._('Insert')
}, true);
content.find('.button').click(function (e) {
var val = content.find('#link').val(),
description = content.find('#des').val();
if (val) {
// needed for IE to restore the last range
editor.focus();
// If there is no selected text then must set the URL as
// the text. Most browsers do this automatically, sadly
// IE doesn't.
if (!editor.getRangeHelper().selectedHtml() ||
description) {
description = description || val;
editor.wysiwygEditorInsertHtml(
'<a href="' + val + '">' + description + '</a>'
);
} else {
editor.execCommand('createlink', val);
}
}
editor.closeDropDown(true);
e.preventDefault();
});
editor.createDropDown(caller, 'insertlink', content);
},
tooltip: 'Insert a link'
},
// END_COMMAND
// START_COMMAND: Unlink
unlink: {
state: function () {
var $current = $(this.currentNode());
return $current.is('a') ||
$current.parents('a').length > 0 ? 0 : -1;
},
exec: function () {
var $current = $(this.currentNode()),
$anchor = $current.is('a') ? $current :
$current.parents('a').first();
if ($anchor.length) {
$anchor.replaceWith($anchor.contents());
}
},
tooltip: 'Unlink'
},
// END_COMMAND
// START_COMMAND: Quote
quote: {
forceNewLineAfter: ['blockquote'],
exec: function (caller, html, author) {
var before = '<blockquote>',
end = '</blockquote>';
// if there is HTML passed set end to null so any selected
// text is replaced
if (html) {
author = (author ? '<cite>' + author + '</cite>' : '');
before = before + author + html + end;
end = null;
// if not add a newline to the end of the inserted quote
} else if (this.getRangeHelper().selectedHtml() === '') {
end = (IE_BR_FIX ? '' : '<br />') + end;
}
this.wysiwygEditorInsertHtml(before, end);
},
tooltip: 'Insert a Quote'
},
// END_COMMAND
// START_COMMAND: Emoticons
emoticon: {
exec: function (caller) {
var editor = this;
var createContent = function (includeMore) {
var $moreLink,
emoticonsCompat = editor.opts.emoticonsCompat,
rangeHelper = editor.getRangeHelper(),
startSpace = emoticonsCompat &&
rangeHelper.getOuterText(true, 1) !== ' ' ?
' ' : '',
endSpace = emoticonsCompat &&
rangeHelper.getOuterText(false, 1) !== ' ' ?
' ' : '',
$content = $('<div />'),
$line = $('<div />').appendTo($content),
perLine = 0,
emoticons = $.extend(
{},
editor.opts.emoticons.dropdown,
includeMore ? editor.opts.emoticons.more : {}
);
$.each(emoticons, function () {
perLine++;
});
perLine = Math.sqrt(perLine);
$.each(emoticons, function (code, emoticon) {
$line.append(
$('<img />').attr({
src: emoticon.url || emoticon,
alt: code,
title: emoticon.tooltip || code
}).click(function () {
editor.insert(startSpace + $(this).attr('alt') +
endSpace, null, false).closeDropDown(true);
return false;
})
);
if ($line.children().length >= perLine) {
$line = $('<div />').appendTo($content);
}
});
if (!includeMore && editor.opts.emoticons.more) {
$moreLink = $(
'<a class="sceditor-more">' +
editor._('More') + '</a>'
).click(function () {
editor.createDropDown(
caller,
'more-emoticons',
createContent(true)
);
return false;
});
$content.append($moreLink);
}
return $content;
};
editor.createDropDown(
caller,
'emoticons',
createContent(false)
);
},
txtExec: function (caller) {
defaultCommnds.emoticon.exec.call(this, caller);
},
tooltip: 'Insert an emoticon'
},
// END_COMMAND
// START_COMMAND: YouTube
youtube: {
_dropDown: function (editor, caller, handleIdFunc) {
var matches,
content = _tmpl('youtubeMenu', {
label: editor._('Video URL:'),
insert: editor._('Insert')
}, true);
content.find('.button').click(function (e) {
var val = content
.find('#link')
.val();
if (val) {
matches = val.match(
/(?:v=|v\/|embed\/|youtu.be\/)(.{11})/
);
if (matches) {
val = matches[1];
}
if (/^[a-zA-Z0-9_\-]{11}$/.test(val)) {
handleIdFunc(val);
} else {
/*global alert:false*/
alert('Invalid YouTube video');
}
}
editor.closeDropDown(true);
e.preventDefault();
});
editor.createDropDown(caller, 'insertlink', content);
},
exec: function (caller) {
var editor = this;
defaultCommnds.youtube._dropDown(
editor,
caller,
function (id) {
editor.wysiwygEditorInsertHtml(_tmpl('youtube', {
id: id
}));
}
);
},
tooltip: 'Insert a YouTube video'
},
// END_COMMAND
// START_COMMAND: Date
date: {
_date: function (editor) {
var now = new Date(),
year = now.getYear(),
month = now.getMonth() + 1,
day = now.getDate();
if (year < 2000) {
year = 1900 + year;
}
if (month < 10) {
month = '0' + month;
}
if (day < 10) {
day = '0' + day;
}
return editor.opts.dateFormat
.replace(/year/i, year)
.replace(/month/i, month)
.replace(/day/i, day);
},
exec: function () {
this.insertText(defaultCommnds.date._date(this));
},
txtExec: function () {
this.insertText(defaultCommnds.date._date(this));
},
tooltip: 'Insert current date'
},
// END_COMMAND
// START_COMMAND: Time
time: {
_time: function () {
var now = new Date(),
hours = now.getHours(),
mins = now.getMinutes(),
secs = now.getSeconds();
if (hours < 10) {
hours = '0' + hours;
}
if (mins < 10) {
mins = '0' + mins;
}
if (secs < 10) {
secs = '0' + secs;
}
return hours + ':' + mins + ':' + secs;
},
exec: function () {
this.insertText(defaultCommnds.time._time());
},
txtExec: function () {
this.insertText(defaultCommnds.time._time());
},
tooltip: 'Insert current time'
},
// END_COMMAND
// START_COMMAND: Ltr
ltr: {
state: function (parents, firstBlock) {
return firstBlock && firstBlock.style.direction === 'ltr';
},
exec: function () {
var editor = this,
elm = editor.getRangeHelper().getFirstBlockParent(),
$elm = $(elm);
editor.focus();
if (!elm || $elm.is('body')) {
editor.execCommand('formatBlock', 'p');
elm = editor.getRangeHelper().getFirstBlockParent();
$elm = $(elm);
if (!elm || $elm.is('body')) {
return;
}
}
if ($elm.css('direction') === 'ltr') {
$elm.css('direction', '');
} else {
$elm.css('direction', 'ltr');
}
},
tooltip: 'Left-to-Right'
},
// END_COMMAND
// START_COMMAND: Rtl
rtl: {
state: function (parents, firstBlock) {
return firstBlock && firstBlock.style.direction === 'rtl';
},
exec: function () {
var editor = this,
elm = editor.getRangeHelper().getFirstBlockParent(),
$elm = $(elm);
editor.focus();
if (!elm || $elm.is('body')) {
editor.execCommand('formatBlock', 'p');
elm = editor.getRangeHelper().getFirstBlockParent();
$elm = $(elm);
if (!elm || $elm.is('body')) {
return;
}
}
if ($elm.css('direction') === 'rtl') {
$elm.css('direction', '');
} else {
$elm.css('direction', 'rtl');
}
},
tooltip: 'Right-to-Left'
},
// END_COMMAND
// START_COMMAND: Print
print: {
exec: 'print',
tooltip: 'Print'
},
// END_COMMAND
// START_COMMAND: Maximize
maximize: {
state: function () {
return this.maximize();
},
exec: function () {
this.maximize(!this.maximize());
},
txtExec: function () {
this.maximize(!this.maximize());
},
tooltip: 'Maximize',
shortcut: 'Ctrl+Shift+M'
},
// END_COMMAND
// START_COMMAND: Source
source: {
state: function () {
return this.sourceMode();
},
exec: function () {
this.toggleSourceMode();
},
txtExec: function () {
this.toggleSourceMode();
},
tooltip: 'View source',
shortcut: 'Ctrl+Shift+S'
},
// END_COMMAND
// this is here so that commands above can be removed
// without having to remove the , after the last one.
// Needed for IE.
ignore: {}
};
return defaultCommnds;
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_RESULT__ = function (require) {
'use strict';
var $ = __webpack_require__(1);
/**
* Default options for SCEditor
* @type {Object}
*/
return {
/** @lends jQuery.sceditor.defaultOptions */
/**
* Toolbar buttons order and groups. Should be comma separated and
* have a bar | to separate groups
*
* @type {String}
*/
toolbar: 'bold,italic,underline,strike,subscript,superscript|' +
'left,center,right,justify|font,size,color,removeformat|' +
'cut,copy,paste,pastetext|bulletlist,orderedlist,indent,outdent|' +
'table|code,quote|horizontalrule,image,email,link,unlink|' +
'emoticon,youtube,date,time|ltr,rtl|print,maximize,source',
/**
* Comma separated list of commands to excludes from the toolbar
*
* @type {String}
*/
toolbarExclude: null,
/**
* Stylesheet to include in the WYSIWYG editor. This is what will style
* the WYSIWYG elements
*
* @type {String}
*/
style: 'jquery.sceditor.default.css',
/**
* Comma separated list of fonts for the font selector
*
* @type {String}
*/
fonts: 'Arial,Arial Black,Comic Sans MS,Courier New,Georgia,Impact,' +
'Sans-serif,Serif,Times New Roman,Trebuchet MS,Verdana',
/**
* Colors should be comma separated and have a bar | to signal a new
* column.
*
* If null the colors will be auto generated.
*
* @type {string}
*/
colors: null,
/**
* The locale to use.
* @type {String}
*/
locale: $('html').attr('lang') || 'en',
/**
* The Charset to use
* @type {String}
*/
charset: 'utf-8',
/**
* Compatibility mode for emoticons.
*
* Helps if you have emoticons such as :/ which would put an emoticon
* inside http://
*
* This mode requires emoticons to be surrounded by whitespace or end of
* line chars. This mode has limited As You Type emoticon conversion
* support. It will not replace AYT for end of line chars, only
* emoticons surrounded by whitespace. They will still be replaced
* correctly when loaded just not AYT.
*
* @type {Boolean}
*/
emoticonsCompat: false,
/**
* If to enable emoticons. Can be changes at runtime using the
* emoticons() method.
*
* @type {Boolean}
* @since 1.4.2
*/
emoticonsEnabled: true,
/**
* Emoticon root URL
*
* @type {String}
*/
emoticonsRoot: '',
emoticons: {
dropdown: {
':)': 'emoticons/smile.png',
':angel:': 'emoticons/angel.png',
':angry:': 'emoticons/angry.png',
'8-)': 'emoticons/cool.png',
':\'(': 'emoticons/cwy.png',
':ermm:': 'emoticons/ermm.png',
':D': 'emoticons/grin.png',
'<3': 'emoticons/heart.png',
':(': 'emoticons/sad.png',
':O': 'emoticons/shocked.png',
':P': 'emoticons/tongue.png',
';)': 'emoticons/wink.png'
},
more: {
':alien:': 'emoticons/alien.png',
':blink:': 'emoticons/blink.png',
':blush:': 'emoticons/blush.png',
':cheerful:': 'emoticons/cheerful.png',
':devil:': 'emoticons/devil.png',
':dizzy:': 'emoticons/dizzy.png',
':getlost:': 'emoticons/getlost.png',
':happy:': 'emoticons/happy.png',
':kissing:': 'emoticons/kissing.png',
':ninja:': 'emoticons/ninja.png',
':pinch:': 'emoticons/pinch.png',
':pouty:': 'emoticons/pouty.png',
':sick:': 'emoticons/sick.png',
':sideways:': 'emoticons/sideways.png',
':silly:': 'emoticons/silly.png',
':sleeping:': 'emoticons/sleeping.png',
':unsure:': 'emoticons/unsure.png',
':woot:': 'emoticons/w00t.png',
':wassat:': 'emoticons/wassat.png'
},
hidden: {
':whistling:': 'emoticons/whistling.png',
':love:': 'emoticons/wub.png'
}
},
/**
* Width of the editor. Set to null for automatic with
*
* @type {int}
*/
width: null,
/**
* Height of the editor including toolbar. Set to null for automatic
* height
*
* @type {int}
*/
height: null,
/**
* If to allow the editor to be resized
*
* @type {Boolean}
*/
resizeEnabled: true,
/**
* Min resize to width, set to null for half textarea width or -1 for
* unlimited
*
* @type {int}
*/
resizeMinWidth: null,
/**
* Min resize to height, set to null for half textarea height or -1 for
* unlimited
*
* @type {int}
*/
resizeMinHeight: null,
/**
* Max resize to height, set to null for double textarea height or -1
* for unlimited
*
* @type {int}
*/
resizeMaxHeight: null,
/**
* Max resize to width, set to null for double textarea width or -1 for
* unlimited
*
* @type {int}
*/
resizeMaxWidth: null,
/**
* If resizing by height is enabled
*
* @type {Boolean}
*/
resizeHeight: true,
/**
* If resizing by width is enabled
*
* @type {Boolean}
*/
resizeWidth: true,
/**
* Date format, will be overridden if locale specifies one.
*
* The words year, month and day will be replaced with the users current
* year, month and day.
*
* @type {String}
*/
dateFormat: 'year-month-day',
/**
* Element to inset the toolbar into.
*
* @type {HTMLElement}
*/
toolbarContainer: null,
/**
* If to enable paste filtering. This is currently experimental, please
* report any issues.
*
* @type {Boolean}
*/
enablePasteFiltering: false,
/**
* If to completely disable pasting into the editor
*
* @type {Boolean}
*/
disablePasting: false,
/**
* If the editor is read only.
*
* @type {Boolean}
*/
readOnly: false,
/**
* If to set the editor to right-to-left mode.
*
* If set to null the direction will be automatically detected.
*
* @type {Boolean}
*/
rtl: false,
/**
* If to auto focus the editor on page load
*
* @type {Boolean}
*/
autofocus: false,
/**
* If to auto focus the editor to the end of the content
*
* @type {Boolean}
*/
autofocusEnd: true,
/**
* If to auto expand the editor to fix the content
*
* @type {Boolean}
*/
autoExpand: false,
/**
* If to auto update original textbox on blur
*
* @type {Boolean}
*/
autoUpdate: false,
/**
* If to enable the browsers built in spell checker
*
* @type {Boolean}
*/
spellcheck: true,
/**
* If to run the source editor when there is no WYSIWYG support. Only
* really applies to mobile OS's.
*
* @type {Boolean}
*/
runWithoutWysiwygSupport: false,
/**
* If to load the editor in source mode and still allow switching
* between WYSIWYG and source mode
*
* @type {Boolean}
*/
startInSourceMode: false,
/**
* Optional ID to give the editor.
*
* @type {String}
*/
id: null,
/**
* Comma separated list of plugins
*
* @type {String}
*/
plugins: '',
/**
* z-index to set the editor container to. Needed for jQuery UI dialog.
*
* @type {Int}
*/
zIndex: null,
/**
* If to trim the BBCode. Removes any spaces at the start and end of the
* BBCode string.
*
* @type {Boolean}
*/
bbcodeTrim: false,
/**
* If to disable removing block level elements by pressing backspace at
* the start of them
*
* @type {Boolean}
*/
disableBlockRemove: false,
/**
* BBCode parser options, only applies if using the editor in BBCode
* mode.
*
* See SCEditor.BBCodeParser.defaults for list of valid options
*
* @type {Object}
*/
parserOptions: { },
/**
* CSS that will be added to the to dropdown menu (eg. z-index)
*
* @type {Object}
*/
dropDownCss: { }
};
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ }
/******/ ]);
|
// app.js
var app = angular.module('app', []);
app.controller('MainController', function($scope) {
$scope.num = 0
$scope.nums = []
$scope.increment = function() {
$scope.num++;
}
// $scope.$watch('num', function() {
// $scope.nums.push($scope.num)
// })
$scope.stopWatch = $scope.$watch('num', function() {
$scope.nums.push($scope.num)
})
})
|
__req.define([
"lib/Class",
"src/NJModule"
], function( Class, NJModule ) {
var NJGoogleAnalytics = Class( NJModule, function( cls, parent ){
cls.constructor = function(){
parent.constructor.apply(this,arguments);
};
cls.installTo = function( ctx ) {
}
cls.initJs = function( ctx ) {
ctx.googleAnalytics = new GA();
}
} );
var GA = Class( Object, function( cls, parent ){
cls.constructor = function(){
parent.constructor.apply(this,arguments);
};
cls.init = function( ua ) {
// TODO
}
cls.screen = function( name ) {
// TODO
}
cls.event = function() {
// TODO
}
} )
return NJGoogleAnalytics;
});
|
function init() {
selectize = $("#userid").selectize({
create: true
});
}
window.addEventListener('load', init);
|
window.MetaMaskProvider = null;
// External Web3 Injection Support (MetaMask)
if (typeof window.web3 === 'undefined') {
var web3 = new Web3();
} else {
var web3 = new Web3();
window.MetaMaskProvider = window.web3.currentProvider;
web3.setProvider(window.web3.currentProvider);
}
// Set Web3
window.web3 = web3;
|
import React from 'react';
import PropTypes from 'prop-types';
import { COLORS, TYPEOGRAPHY, TEXTSIZE } from '../../lib/styles';
const H6 = ({ children, light, style }) => {
const color = light ? COLORS.texts.primary.light : COLORS.texts.primary.dark;
return (
<h6 style={style} >
{children}
<style jsx>
{`
h6 {
font-family: ${TYPEOGRAPHY.header.title};
font-size: ${TEXTSIZE.md};
color: ${color}
line-height: 1.6;
margin: .65rem 0 .50rem 0;
font-weight: 300;
}
`}
</style>
</h6>
);
};
H6.propTypes = {
children: PropTypes.node.isRequired,
light: PropTypes.bool,
style: PropTypes.object,
};
export default H6;
|
import Pricing from './components/pricing';
import Autocomplete from './components/autocomplete';
import Toggler from './components/toggler';
(function(){
Pricing.search();
Autocomplete.google();
Toggler.addToggleHandler();
})();
|
/*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
Licensed under the MIT license.
*/
/**
Grid represents a data grid that has a header, body and an optional footer.
By default, a Grid treats each model in a collection as a row, and each
attribute in a model as a column. To render a grid you must provide a list of
column metadata and a collection to the Grid constructor. Just like any
Backbone.View class, the grid is rendered as a DOM node fragment when you
call render().
var grid = Backgrid.Grid({
columns: [{ name: "id", label: "ID", type: "string" },
// ...
],
collections: books
});
$("#table-container").append(grid.render().el);
Optionally, if you want to customize the rendering of the grid's header and
footer, you may choose to extend Backgrid.Header and Backgrid.Footer, and
then supply that class or an instance of that class to the Grid constructor.
See the documentation for Header and Footer for further details.
var grid = Backgrid.Grid({
columns: [{ name: "id", label: "ID", type: "string" }],
collections: books,
header: Backgrid.Header.extend({
//...
}),
footer: Backgrid.Paginator
});
Finally, if you want to override how the rows are rendered in the table body,
you can supply a Body subclass as the `body` attribute that uses a different
Row class.
@class Backgrid.Grid
@extends Backbone.View
See:
- Backgrid.Column
- Backgrid.Header
- Backgrid.Body
- Backgrid.Row
- Backgrid.Footer
*/
var Grid = Backgrid.Grid = Backbone.View.extend({
/** @property */
tagName: "table",
/** @property */
className: "backgrid",
/** @property */
header: Header,
/** @property */
body: Body,
/** @property */
footer: null,
/**
Initializes a Grid instance.
@param {Object} options
@param {Backbone.Collection.<Backgrid.Columns>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
@param {Backbone.Collection} options.collection The collection of tabular model data to display.
@param {Backgrid.Header} [options.header=Backgrid.Header] An optional Header class to override the default.
@param {Backgrid.Body} [options.body=Backgrid.Body] An optional Body class to override the default.
@param {Backgrid.Row} [options.row=Backgrid.Row] An optional Row class to override the default.
@param {Backgrid.Footer} [options.footer=Backgrid.Footer] An optional Footer class.
*/
initialize: function (options) {
// Convert the list of column objects here first so the subviews don't have
// to.
if (!(options.columns instanceof Backbone.Collection)) {
options.columns = new Columns(options.columns || this.columns);
}
this.columns = options.columns;
var filteredOptions = _.omit(options, ["el", "id", "attributes",
"className", "tagName", "events"]);
// must construct body first so it listens to backgrid:sort first
this.body = options.body || this.body;
this.body = new this.body(filteredOptions);
this.header = options.header || this.header;
if (this.header) {
this.header = new this.header(filteredOptions);
}
this.footer = options.footer || this.footer;
if (this.footer) {
this.footer = new this.footer(filteredOptions);
}
this.listenTo(this.columns, "reset", function () {
if (this.header) {
this.header = new (this.header.remove().constructor)(filteredOptions);
}
this.body = new (this.body.remove().constructor)(filteredOptions);
if (this.footer) {
this.footer = new (this.footer.remove().constructor)(filteredOptions);
}
this.render();
});
},
/**
Delegates to Backgrid.Body#insertRow.
*/
insertRow: function () {
this.body.insertRow.apply(this.body, arguments);
return this;
},
/**
Delegates to Backgrid.Body#removeRow.
*/
removeRow: function () {
this.body.removeRow.apply(this.body, arguments);
return this;
},
/**
Delegates to Backgrid.Columns#add for adding a column. Subviews can listen
to the `add` event from their internal `columns` if rerendering needs to
happen.
@param {Object} [options] Options for `Backgrid.Columns#add`.
*/
insertColumn: function () {
this.columns.add.apply(this.columns, arguments);
return this;
},
/**
Delegates to Backgrid.Columns#remove for removing a column. Subviews can
listen to the `remove` event from the internal `columns` if rerendering
needs to happen.
@param {Object} [options] Options for `Backgrid.Columns#remove`.
*/
removeColumn: function () {
this.columns.remove.apply(this.columns, arguments);
return this;
},
/**
Delegates to Backgrid.Body#sort.
*/
sort: function () {
this.body.sort.apply(this.body, arguments);
return this;
},
/**
Renders the grid's header, then footer, then finally the body. Triggers a
Backbone `backgrid:rendered` event along with a reference to the grid when
the it has successfully been rendered.
*/
render: function () {
this.$el.empty();
if (this.header) {
this.$el.append(this.header.render().$el);
}
this.$el.append(this.body.render().$el);
if (this.footer) {
this.$el.append(this.footer.render().$el);
}
this.delegateEvents();
this.trigger("backgrid:rendered", this);
return this;
},
/**
Clean up this grid and its subviews.
@chainable
*/
remove: function () {
this.header && this.header.remove.apply(this.header, arguments);
this.body.remove.apply(this.body, arguments);
this.footer && this.footer.remove.apply(this.footer, arguments);
return Backbone.View.prototype.remove.apply(this, arguments);
}
});
|
'use strict';
// Include gulp
var gulp = require('gulp');
// Include plugins
var sass = require('gulp-sass'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify'),
minify = require('gulp-minify-css'),
sourcemaps = require('gulp-sourcemaps'),
concat = require('gulp-concat'),
jade = require('gulp-jade'),
autoprefixer = require('gulp-autoprefixer');
var conf = {
css: {
wrkPath: ['bower_components/reset/index.css', 'content/source/*.scss'],
optPath: 'content/build/css',
optName: 'all.css',
optNameMin: 'all.min.css'
},
js: {
wrkPath: [
'bower_components/jquery/dist/jquery.js',
'bower_components/fastclick/lib/fastclick.js',
'content/source/Store.js',
'content/source/Cell.js',
'content/source/Game.js',
'content/source/index.js'
],
optPath: 'content/build/js',
optName: 'all.js',
optNameMin: 'all.min.js'
},
jade: {
wrkPath: 'content/source/*.jade',
optPath: 'content/build',
optName: 'index.html'
}
}
// Compile and minify css
gulp.task('css', function() {
return gulp.src(conf.css.wrkPath)
.pipe(sourcemaps.init())
.pipe(concat(conf.css.optName))
.pipe(sass({
outputStyle: 'expanded'
}))
.pipe(autoprefixer({
browsers: ['> 1%', 'last 2 versions', 'IE 7'],
cascade: false
}))
.pipe(gulp.dest(conf.css.optPath))
.pipe(minify({
advanced: false,
compatibility: 'ie7'
}))
.pipe(rename(conf.css.optNameMin))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(conf.css.optPath));
});
// Minify js
gulp.task('js', function() {
return gulp.src(conf.js.wrkPath)
.pipe(concat(conf.js.optName))
.pipe(gulp.dest(conf.js.optPath))
.pipe(uglify({
mangle: false
}))
.pipe(rename(conf.js.optNameMin))
.pipe(gulp.dest(conf.js.optPath));
});
// Compile jade
gulp.task('jade', function() {
return gulp.src(conf.jade.wrkPath)
.pipe(jade())
.pipe(rename(conf.jade.optName))
.pipe(gulp.dest(conf.jade.optPath));
});
// Watch files
gulp.task('watch', function() {
gulp.watch(conf.css.wrkPath, ['css']);
gulp.watch(conf.js.wrkPath, ['js']);
gulp.watch(conf.jade.wrkPath, ['jade']);
});
// Default task
gulp.task('default', ['css', 'js', 'jade']);
|
/*
* Knapsack
* For the full copyright and license information, please view the LICENSE.txt file.
*/
/* jslint node: true */
'use strict';
// Init the module
module.exports = function() {
// Resolves the given problem
var resolve = function resolve(capacity, items) {
var result = [],
leftCap = capacity,
itemsFiltered;
if(typeof capacity !== 'number')
return false;
if(!items || !(items instanceof Array))
return false;
// Resolve
var item,
itemKey,
itemVal,
itemObj;
itemsFiltered = items.filter(function(value) {
itemVal = (typeof value === 'object') ? value[Object.keys(value)[0]] : null;
if(!isNaN(itemVal) && itemVal > 0 && itemVal <= capacity) {
return true;
} else {
return false;
}
});
itemsFiltered.sort(function(a, b) { return a[Object.keys(a)[0]] < b[Object.keys(b)[0]]; });
for(item in itemsFiltered) {
if(itemsFiltered.hasOwnProperty(item)) {
itemKey = Object.keys(itemsFiltered[item])[0];
itemVal = itemsFiltered[item][itemKey];
if((leftCap-itemVal) >= 0) {
leftCap = leftCap-itemVal;
itemObj = Object.create(null);
itemObj[itemKey] = itemVal;
result.push(itemObj);
delete itemsFiltered[item];
if(leftCap <= 0) break;
}
}
}
return result;
};
// Return
return {
resolve: resolve
};
}();
|
import includes from "lodash/collection/includes";
import traverse from "../index";
import defaults from "lodash/object/defaults";
import * as messages from "../../messages";
import Binding from "./binding";
import globals from "globals";
import flatten from "lodash/array/flatten";
import extend from "lodash/object/extend";
import object from "../../helpers/object";
import * as t from "../../types";
var collectorVisitor = {
For(node, parent, scope) {
for (var key of (t.FOR_INIT_KEYS: Array)) {
var declar = this.get(key);
if (declar.isVar()) scope.getFunctionParent().registerBinding("var", declar);
}
},
Declaration(node, parent, scope) {
// delegate block scope handling to the `blockVariableVisitor`
if (this.isBlockScoped()) return;
// this will be hit again once we traverse into it after this iteration
if (this.isExportDeclaration() && this.get("declaration").isDeclaration()) return;
// we've ran into a declaration!
scope.getFunctionParent().registerDeclaration(this);
},
ReferencedIdentifier(node, parent, scope) {
var bindingInfo = scope.getBinding(node.name);
if (bindingInfo) {
bindingInfo.reference();
} else {
scope.getProgramParent().addGlobal(node);
}
},
ForXStatement(node, parent, scope) {
var left = this.get("left");
if (left.isPattern() || left.isIdentifier()) {
scope.registerConstantViolation(left);
}
},
Scopable(node, parent, scope) {
for (var name in scope.bindings) {
scope.getProgramParent().references[name] = true;
}
},
ExportDeclaration: {
exit(node, parent, scope) {
var declar = node.declaration;
if (t.isClassDeclaration(declar) || t.isFunctionDeclaration(declar)) {
scope.getBinding(declar.id.name).reference();
} else if (t.isVariableDeclaration(declar)) {
for (var decl of (declar.declarations: Array)) {
var ids = t.getBindingIdentifiers(decl);
for (var name in ids) {
scope.getBinding(name).reference();
}
}
}
}
},
LabeledStatement(node, parent, scope) {
scope.getProgramParent().addGlobal(node);
},
AssignmentExpression(node, parent, scope) {
scope.registerConstantViolation(this.get("left"), this.get("right"));
},
UpdateExpression(node, parent, scope) {
scope.registerConstantViolation(this.get("argument"), null);
},
UnaryExpression(node, parent, scope) {
if (node.operator === "delete") scope.registerConstantViolation(this.get("left"), null);
},
BlockScoped(node, parent, scope) {
if (scope.path === this) scope = scope.parent;
scope.getBlockParent().registerDeclaration(this);
}
};
var renameVisitor = {
ReferencedIdentifier(node, parent, scope, state) {
if (node.name === state.oldName) {
node.name = state.newName;
}
},
Declaration(node, parent, scope, state) {
var ids = this.getBindingIdentifiers();
for (var name in ids) {
if (name === state.oldName) ids[name].name = state.newName;
}
},
Scope(node, parent, scope, state) {
if (!scope.bindingIdentifierEquals(state.oldName, state.binding)) {
this.skip();
}
}
};
export default class Scope {
/**
* This searches the current "scope" and collects all references/bindings
* within.
*/
constructor(path: NodePath, parent?: Scope, file?: File) {
if (parent && parent.block === path.node) {
return parent;
}
var cached = path.getData("scope");
if (cached && cached.parent === parent) {
return cached;
} else {
path.setData("scope", this);
}
this.parent = parent;
this.file = parent ? parent.file : file;
this.parentBlock = path.parent;
this.block = path.node;
this.path = path;
}
static globals = flatten([globals.builtin, globals.browser, globals.node].map(Object.keys));
static contextVariables = ["this", "arguments", "super", "undefined"];
/**
* Description
*/
traverse(node: Object, opts: Object, state?) {
traverse(node, opts, this, state, this.path);
}
/**
* Since `Scope` instances are unique to their traversal we need some other
* way to compare if scopes are the same. Here we just compare `this.bindings`
* as it will be the same across all instances.
*/
is(scope) {
return this.bindings === scope.bindings;
}
/**
* Description
*/
generateDeclaredUidIdentifier(name: string = "temp") {
var id = this.generateUidIdentifier(name);
this.push({ id });
return id;
}
/**
* Description
*/
generateUidIdentifier(name: string) {
return t.identifier(this.generateUid(name));
}
/**
* Description
*/
generateUid(name: string) {
name = t.toIdentifier(name).replace(/^_+/, "");
var uid;
var i = 0;
do {
uid = this._generateUid(name, i);
i++;
} while (this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid));
var program = this.getProgramParent();
program.references[uid] = true;
program.uids[uid] = true;
return uid;
}
_generateUid(name, i) {
var id = name;
if (i > 1) id += i;
return `_${id}`;
}
/*
* Description
*/
generateUidIdentifierBasedOnNode(parent: Object, defaultName?: String): Object {
var node = parent;
if (t.isAssignmentExpression(parent)) {
node = parent.left;
} else if (t.isVariableDeclarator(parent)) {
node = parent.id;
} else if (t.isProperty(node)) {
node = node.key;
}
var parts = [];
var add = function (node) {
if (t.isModuleDeclaration(node)) {
if (node.source) {
add(node.source);
} else if (node.specifiers && node.specifiers.length) {
for (var specifier of (node.specifiers: Array)) {
add(specifier);
}
} else if (node.declaration) {
add(node.declaration);
}
} else if (t.isModuleSpecifier(node)) {
add(node.local);
} else if (t.isMemberExpression(node)) {
add(node.object);
add(node.property);
} else if (t.isIdentifier(node)) {
parts.push(node.name);
} else if (t.isLiteral(node)) {
parts.push(node.value);
} else if (t.isCallExpression(node)) {
add(node.callee);
} else if (t.isObjectExpression(node) || t.isObjectPattern(node)) {
for (var prop of (node.properties: Array)) {
add(prop.key || prop.argument);
}
}
};
add(node);
var id = parts.join("$");
id = id.replace(/^_/, "") || defaultName || "ref";
return this.generateUidIdentifier(id);
}
/**
* Determine whether evaluating the specific input `node` is a consequenceless reference. ie.
* evaluating it wont result in potentially arbitrary code from being ran. The following are
* whitelisted and determined not cause side effects:
*
* - `this` expressions
* - `super` expressions
* - Bound identifiers
*/
isStatic(node: Object): boolean {
if (t.isThisExpression(node) || t.isSuper(node)) {
return true;
}
if (t.isIdentifier(node) && this.hasBinding(node.name)) {
return true;
}
return false;
}
/**
* Description
*/
maybeGenerateMemoised(node: Object, dontPush?: boolean): ?Object {
if (this.isStatic(node)) {
return null;
} else {
var id = this.generateUidIdentifierBasedOnNode(node);
if (!dontPush) this.push({ id });
return id;
}
}
/**
* Description
*/
checkBlockScopedCollisions(local, kind: string, name: string, id: Object) {
// ignore parameters
if (kind === "param") return;
// ignore hoisted functions if there's also a local let
if (kind === "hoisted" && local.kind === "let") return;
var duplicate = false;
// don't allow duplicate bindings to exist alongside
if (!duplicate) duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module";
// don't allow a local of param with a kind of let
if (!duplicate) duplicate = local.kind === "param" && (kind === "let" || kind === "const");
if (duplicate) {
throw this.file.errorWithNode(id, messages.get("scopeDuplicateDeclaration", name), TypeError);
}
}
/**
* Description
*/
rename(oldName: string, newName: string, block?) {
newName = newName || this.generateUidIdentifier(oldName).name;
var info = this.getBinding(oldName);
if (!info) return;
var state = {
newName: newName,
oldName: oldName,
binding: info.identifier,
info: info
};
var scope = info.scope;
scope.traverse(block || scope.block, renameVisitor, state);
if (!block) {
scope.removeOwnBinding(oldName);
scope.bindings[newName] = info;
state.binding.name = newName;
}
var file = this.file;
if (file) {
this._renameFromMap(file.moduleFormatter.localImports, oldName, newName, state.binding);
//this._renameFromMap(file.moduleFormatter.localExports, oldName, newName);
}
}
_renameFromMap(map, oldName, newName, value) {
if (map[oldName]) {
map[newName] = value;
map[oldName] = null;
}
}
/**
* Description
*/
dump() {
var scope = this;
do {
console.log(scope.block.type, "Bindings:", Object.keys(scope.bindings));
} while(scope = scope.parent);
console.log("-------------");
}
/**
* Description
*/
toArray(node: Object, i?: number) {
var file = this.file;
if (t.isIdentifier(node)) {
var binding = this.getBinding(node.name);
if (binding && binding.constant && binding.path.isTypeAnnotationGeneric("Array")) return node;
}
if (t.isArrayExpression(node)) {
return node;
}
if (t.isIdentifier(node, { name: "arguments" })) {
return t.callExpression(t.memberExpression(file.addHelper("slice"), t.identifier("call")), [node]);
}
var helperName = "to-array";
var args = [node];
if (i === true) {
helperName = "to-consumable-array";
} else if (i) {
args.push(t.literal(i));
helperName = "sliced-to-array";
if (this.file.isLoose("es6.forOf")) helperName += "-loose";
}
return t.callExpression(file.addHelper(helperName), args);
}
/**
* Description
*/
registerDeclaration(path: NodePath) {
var node = path.node;
if (t.isFunctionDeclaration(node)) {
this.registerBinding("hoisted", path);
} else if (t.isVariableDeclaration(node)) {
var declarations = path.get("declarations");
for (var declar of (declarations: Array)) {
this.registerBinding(node.kind, declar);
}
} else if (t.isClassDeclaration(node)) {
this.registerBinding("let", path);
} else if (t.isImportDeclaration(node) || t.isExportDeclaration(node)) {
this.registerBinding("module", path);
} else {
this.registerBinding("unknown", path);
}
}
/**
* Description
*/
registerConstantViolation(left: NodePath, right: NodePath) {
var ids = left.getBindingIdentifiers();
for (var name in ids) {
var binding = this.getBinding(name);
if (!binding) continue;
if (right) {
var rightType = right.typeAnnotation;
if (rightType && binding.isCompatibleWithType(rightType)) continue;
}
binding.reassign(left, right);
}
}
/**
* Description
*/
registerBinding(kind: string, path: NodePath) {
if (!kind) throw new ReferenceError("no `kind`");
if (path.isVariableDeclaration()) {
var declarators = path.get("declarations");
for (var declar of (declarators: Array)) {
this.registerBinding(kind, declar);
}
return;
}
var ids = path.getBindingIdentifiers();
for (var name in ids) {
var id = ids[name];
var local = this.getOwnBindingInfo(name);
if (local) {
if (local.identifier === id) continue;
this.checkBlockScopedCollisions(local, kind, name, id);
}
this.bindings[name] = new Binding({
identifier: id,
scope: this,
path: path,
kind: kind
});
}
}
/**
* Description
*/
addGlobal(node: Object) {
this.globals[node.name] = node;
}
/**
* Description
*/
hasUid(name): boolean {
var scope = this;
do {
if (scope.uids[name]) return true;
} while (scope = scope.parent);
return false;
}
/**
* Description
*/
hasGlobal(name: string): boolean {
var scope = this;
do {
if (scope.globals[name]) return true;
} while (scope = scope.parent);
return false;
}
/**
* Description
*/
hasReference(name: string): boolean {
var scope = this;
do {
if (scope.references[name]) return true;
} while (scope = scope.parent);
return false;
}
/**
* Description
*/
recrawl() {
this.path.setData("scopeInfo", null);
this.crawl();
}
/**
* Description
*/
isPure(node, constantsOnly) {
if (t.isIdentifier(node)) {
var bindingInfo = this.getBinding(node.name);
return !!bindingInfo && (!constantsOnly || (constantsOnly && bindingInfo.constant));
} else if (t.isClass(node)) {
return !node.superClass;
} else if (t.isBinary(node)) {
return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly);
} else {
return t.isPure(node);
}
}
/**
* Description
*/
init() {
if (!this.references) this.crawl();
}
/**
* Description
*/
crawl() {
var path = this.path;
//
var info = this.block._scopeInfo;
if (info) return extend(this, info);
info = this.block._scopeInfo = {
references: object(),
bindings: object(),
globals: object(),
uids: object(),
};
extend(this, info);
// ForStatement - left, init
if (path.isLoop()) {
for (let key of (t.FOR_INIT_KEYS: Array)) {
var node = path.get(key);
if (node.isBlockScoped()) this.registerBinding(node.node.kind, node);
}
}
// FunctionExpression - id
if (path.isFunctionExpression() && path.has("id")) {
if (!t.isProperty(path.parent, { method: true })) {
this.registerBinding("var", path);
}
}
// Class
if (path.isClassDeclaration()) {
var name = path.node.id.name;
this.bindings[name] = this.parent.bindings[name];
}
if (path.isClassExpression() && path.has("id")) {
this.registerBinding("var", path);
}
// Function - params, rest
if (path.isFunction()) {
var params = path.get("params");
for (let param of (params: Array)) {
this.registerBinding("param", param);
}
}
// CatchClause - param
if (path.isCatchClause()) {
this.registerBinding("let", path);
}
// ComprehensionExpression - blocks
if (path.isComprehensionExpression()) {
this.registerBinding("let", path);
}
// Program
var parent = this.getProgramParent();
if (parent.crawling) return;
this.crawling = true;
path.traverse(collectorVisitor);
this.crawling = false;
}
/**
* Description
*/
push(opts: Object) {
var path = this.path;
if (path.isSwitchStatement()) {
path = this.getFunctionParent().path;
}
if (path.isLoop() || path.isCatchClause() || path.isFunction()) {
t.ensureBlock(path.node);
path = path.get("body");
}
if (!path.isBlockStatement() && !path.isProgram()) {
path = this.getBlockParent().path;
}
var unique = opts.unique;
var kind = opts.kind || "var";
var dataKey = `declaration:${kind}`;
var declar = !unique && path.getData(dataKey);
if (!declar) {
declar = t.variableDeclaration(kind, []);
declar._generated = true;
declar._blockHoist = 2;
this.file.attachAuxiliaryComment(declar);
var [declarPath] = path.unshiftContainer("body", [declar]);
this.registerBinding(kind, declarPath);
if (!unique) path.setData(dataKey, declar);
}
declar.declarations.push(t.variableDeclarator(opts.id, opts.init));
}
/**
* Walk up to the top of the scope tree and get the `Program`.
*/
getProgramParent() {
var scope = this;
do {
if (scope.path.isProgram()) {
return scope;
}
} while (scope = scope.parent);
throw new Error("We couldn't find a Function or Program...");
}
/**
* Walk up the scope tree until we hit either a Function or reach the
* very top and hit Program.
*/
getFunctionParent() {
var scope = this;
do {
if (scope.path.isFunctionParent()) {
return scope;
}
} while (scope = scope.parent);
throw new Error("We couldn't find a Function or Program...");
}
/**
* Walk up the scope tree until we hit either a BlockStatement/Loop/Program/Function/Switch or reach the
* very top and hit Program.
*/
getBlockParent() {
var scope = this;
do {
if (scope.path.isBlockParent()) {
return scope;
}
} while (scope = scope.parent);
throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...");
}
/**
* Walks the scope tree and gathers **all** bindings.
*/
getAllBindings(): Object {
var ids = object();
var scope = this;
do {
defaults(ids, scope.bindings);
scope = scope.parent;
} while (scope);
return ids;
}
/**
* Walks the scope tree and gathers all declarations of `kind`.
*/
getAllBindingsOfKind(): Object {
var ids = object();
for (let kind of (arguments: Array)) {
var scope = this;
do {
for (var name in scope.bindings) {
var binding = scope.bindings[name];
if (binding.kind === kind) ids[name] = binding;
}
scope = scope.parent;
} while (scope);
}
return ids;
}
/**
* Description
*/
bindingIdentifierEquals(name: string, node: Object): boolean {
return this.getBindingIdentifier(name) === node;
}
/**
* Description
*/
getBinding(name: string) {
var scope = this;
do {
var binding = scope.getOwnBindingInfo(name);
if (binding) return binding;
} while (scope = scope.parent);
}
/**
* Description
*/
getOwnBindingInfo(name: string) {
return this.bindings[name];
}
/**
* Description
*/
getBindingIdentifier(name: string) {
var info = this.getBinding(name);
return info && info.identifier;
}
/**
* Description
*/
getOwnBindingIdentifier(name: string) {
var binding = this.bindings[name];
return binding && binding.identifier;
}
/**
* Description
*/
hasOwnBinding(name: string) {
return !!this.getOwnBindingInfo(name);
}
/**
* Description
*/
hasBinding(name: string) {
if (!name) return false;
if (this.hasOwnBinding(name)) return true;
if (this.parentHasBinding(name)) return true;
if (this.hasUid(name)) return true;
if (includes(Scope.globals, name)) return true;
if (includes(Scope.contextVariables, name)) return true;
return false;
}
/**
* Description
*/
parentHasBinding(name: string) {
return this.parent && this.parent.hasBinding(name);
}
/**
* Move a binding of `name` to another `scope`.
*/
moveBindingTo(name, scope) {
var info = this.getBinding(name);
if (info) {
info.scope.removeOwnBinding(name);
info.scope = scope;
scope.bindings[name] = info;
}
}
/**
* Description
*/
removeOwnBinding(name: string) {
delete this.bindings[name];
}
/**
* Description
*/
removeBinding(name: string) {
var info = this.getBinding(name);
if (info) info.scope.removeOwnBinding(name);
}
}
|
/**
* @hidden
* Removes from an array the element at the specified index.
* @param xs Array or array like object from which to remove value.
* @param index The index to remove.
* @return True if an element was removed.
*/
export default function removeAt(xs, index) {
// use generic form of splice
// splice returns the removed items and if successful the length of that
// will be 1
return Array.prototype.splice.call(xs, index, 1).length === 1;
}
|
/**
* @since 14/12/2017 12:05
* @author vivaxy
*/
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/sw.js').then(
function (registration) {
// Registration was successful
},
function (err) {
// registration failed :(
},
);
});
}
|
var assert = require('assert'),
gabencoin = require('../'),
config = require('./config'),
commands = require('../lib/commands');
var getHelpCommands = function(client, cb) {
var commandRegex = /^([a-z]+)/;
client.cmd('help', function(err, commandList) {
if (err) return cb(err);
var helpCommands = [];
// split up the command list by newlines
var commandListLines = commandList.split('\n');
var result;
for (var i in commandListLines) {
result = commandRegex.exec(commandListLines[i]);
if (!result) {
return cb(new Error('command list line failed to match regex: ' + commandListLines[i]));
}
helpCommands.push(result[1]);
}
cb(null, helpCommands);
});
};
describe('Client Commands', function() {
it('should have all the commands listed by `help`', function(done) {
var client = new gabencoin.Client(config);
getHelpCommands(client, function(err, helpCommands) {
assert.ifError(err);
for (var i in helpCommands) {
var found = true;
for (var j in commands) {
if (commands[j] === helpCommands[i]) {
found = true;
break;
}
}
assert.ok(found, 'missing command found in `help`: ' + helpCommands[i]);
}
done();
});
});
it('should not have any commands not listed by `help`', function(done) {
var client = new gabencoin.Client(config);
getHelpCommands(client, function(err, helpCommands) {
assert.ifError(err);
for (var i in commands) {
var found = false;
for (var j in helpCommands) {
if (commands[i] === helpCommands[j]) {
found = true;
break;
}
}
// ignore commands not found in help because they are hidden
// if the wallet isn't encrypted
var ignore = ['walletlock', 'walletpassphrase', 'walletpassphrasechange'];
if (~ignore.indexOf(commands[i])) {
assert.ok(!found, 'command found in `help`: ' + commands[i]);
} else {
assert.ok(found, 'command not found in `help`: ' + commands[i]);
}
}
done();
});
});
});
|
//@flow
import React, { PureComponent } from "react";
import raf from "raf";
import hoistNonReactStatics from "hoist-non-react-statics";
// NB this is only an utility for the examples
export default (
C: ReactClass<*>,
{ refreshRate = 60 }: { refreshRate?: number } = {}
): ReactClass<*> => {
class TL extends PureComponent {
static displayName = `timeLoop(${C.displayName || C.name || ""})`;
state: { time: number };
state = {
time: 0,
tick: 0,
};
_r: any;
componentDidMount() {
let startTime: number, lastTime: number;
let interval = 1000 / refreshRate;
lastTime = -interval;
const loop = (t: number) => {
this._r = raf(loop);
if (!startTime) startTime = t;
if (t - lastTime > interval) {
lastTime = t;
this.setState({
time: t - startTime,
tick: this.state.tick + 1,
});
}
};
this._r = raf(loop);
}
componentWillUnmount() {
raf.cancel(this._r);
}
render() {
return <C {...this.props} {...this.state} />;
}
}
hoistNonReactStatics(TL, C);
return TL;
};
|
/**
* Created by ben on 11/22/16.
*/
String.prototype.isEmpty = function() {
return this == null || this == '';
};
RegExp.escape = function(val) {
return val.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
};
|
module.exports = class App
{
constructor(dir)
{
const Fs = require('./fs/Main.js');
const Root = require('./fs/Root.js');
const Directory = require('./fs/Directory.js');
let fs = new Fs;
let root = new Root(fs);
root.base = dir;
fs.root = root;
this.fs = fs;
this.device = null;
this.sql = null;
this.isBrowser = typeof window !== 'undefined';
}
call (path)
{
let content = this.fs.scripts[path];
if (!content)
{
throw new Error('No content to eval in script : ' + path);
}
return this.eval(content);
}
eval (content)
{
var script = eval('(function(app) { ' + content + ' })');
let result = script(this);
return result;
}
}
|
const {getPackages} = require('@commitlint/config-lerna-scopes').utils;
module.exports = {
extends: ['@commitlint/config-angular'],
rules: {
'header-max-length': [2, 'always', 140],
'scope-enum': () => [2, 'always', [...getPackages(), 'all']],
'subject-case': [2, 'always', ['lower-case', 'kebab-case']]
}
};
|
// -----------------------------------------------------------------------------
// Name: /handlers/get.js
// Author: Adam Barreiro Costa
// Description: Sets all the GET request handlers
// -----------------------------------------------------------------------------
var handler = require('./general.js');
/**
* Sets the response to the index page request.
*/
function getIndex() {
app.get('/', handler.csrf, function (req, res){
if (req.session.user) {
if (req.session.admin) {
res.redirect('/admin');
} else {
res.redirect('/game');
}
} else {
res.redirect('/login');
}
});
}
exports.getIndex = getIndex;
/**
* Sets the response to the login page request.
*/
function getLogin() {
app.get('/login', handler.csrf, function (req, res) {
if (req.session.user) {
if (req.session.admin) {
res.redirect('/admin');
} else {
res.redirect('/');
}
} else {
res.set('token',res.locals.token);
res.sendfile('public/html/login.html');
}
});
}
exports.getLogin = getLogin;
/**
* Sets the response to the register page request.
*/
function getRegister(){
app.get('/register', handler.csrf, function (req, res) {
if (req.session.user) {
if (req.session.admin) {
res.redirect('/admin');
} else {
res.redirect('/');
}
} else {
res.sendfile('public/html/register.html');
}
});
}
exports.getRegister = getRegister;
/**
* Sets the response to the admin page request.
*/
function getAdmin() {
app.get('/admin', handler.csrf, function (req, res) {
if (req.session.user) {
if (req.session.admin) {
res.sendfile('public/html/admin.html');
}
else {
res.redirect('/');
}
} else {
res.redirect('/');
}
});
}
exports.getAdmin = getAdmin;
/**
* Sets the response to the level editor page request.
*/
function getEditor() {
app.get('/editor', function (req, res) {
if (req.session.user) {
if (req.session.admin) {
res.sendfile('public/html/editor.html');
}
else {
res.redirect('/');
}
} else {
res.redirect('/');
}
});
}
exports.getEditor = getEditor;
/**
* Sets the response to the game page request.
*/
function getGame() {
app.get('/game', function (req, res) {
if (req.session.user) {
res.sendfile('public/html/polynomial.html');
} else {
res.redirect('/');
}
});
}
exports.getGame = getGame;
/**
* Sets the response to the logout request.
*/
function getLogout() {
app.get('/signout', function(req, res){
req.session.destroy(function(){
res.clearCookie("token");
res.clearCookie('savegame');
res.redirect('/');
});
});
}
exports.getLogout = getLogout;
/**
* Inits the admin account
*/
var adminModel = require('../models/admin.js');
function initAdmin(){
app.get('/lavidaesunalentejaolatomasoladejas', function (req, res){
adminModel.initAdmin(function() {
res.redirect('/admin?adminInit');
});
});
}
exports.initAdmin = initAdmin;
|
'use strict';
var escapeStringRegexp = require('escape-string-regexp');
var ansiStyles = require('ansi-styles');
var supportsColor = require('supports-color');
var defineProps = Object.defineProperties;
var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM);
function Chalk(options) {
// detect mode if not set manually
this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled;
}
// use bright blue on Windows as the normal blue color is illegible
if (isSimpleWindowsTerm) {
ansiStyles.blue.open = '\u001b[94m';
}
var styles = (function () {
var ret = {};
Object.keys(ansiStyles).forEach(function (key) {
ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
ret[key] = {
get: function () {
return build.call(this, this._styles.concat(key));
}
};
});
return ret;
})();
var proto = defineProps(function chalk() {}, styles);
function build(_styles) {
var builder = function () {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
builder.enabled = this.enabled;
// __proto__ is used because we must return a function, but there is
// no way to create a function with a different prototype.
/* eslint-disable no-proto */
builder.__proto__ = proto;
return builder;
}
function applyStyle() {
// support varags, but simply cast to string in case there's only one arg
var args = arguments;
var argsLen = args.length;
var str = argsLen !== 0 && String(arguments[0]);
if (argsLen > 1) {
// don't slice `arguments`, it prevents v8 optimizations
for (var a = 1; a < argsLen; a++) {
str += ' ' + args[a];
}
}
if (!this.enabled || !str) {
return str;
}
var nestedStyles = this._styles;
var i = nestedStyles.length;
// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
// see https://github.com/chalk/chalk/issues/58
// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
var originalDim = ansiStyles.dim.open;
if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) {
ansiStyles.dim.open = '';
}
while (i--) {
var code = ansiStyles[nestedStyles[i]];
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
str = code.open + str.replace(code.closeRe, code.open) + code.close;
}
// Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue.
ansiStyles.dim.open = originalDim;
return str;
}
function init() {
var ret = {};
Object.keys(styles).forEach(function (name) {
ret[name] = {
get: function () {
return build.call(this, [name]);
}
};
});
return ret;
}
defineProps(Chalk.prototype, init());
module.exports = new Chalk();
module.exports.styles = ansiStyles;
module.exports.supportsColor = supportsColor;
|
$(function(){
var socket = null;
var msgBox = $("#chatbox textarea");
var messages = $("#messages");
$("#chatbox").submit(function(){
if (!msgBox.val()) return false;
if (!socket) {
alert("Error: There is no socket connection.");
return false;
}
socket.send(msgBox.val());
msgBox.val("");
return false;
});
if (!window["WebSocket"]) {
alert("Error: Your browser does not support web sockets.")
} else {
socket = new WebSocket("ws://{{.Host}}/room");
socket.onclose = function() {
alert("Connection has been closed.");
};
socket.onmessage = function(e) {
messages.append($("<li>").text(e.data));
}
}
});
|
var eelmail = require('../');
var level = require('level-party');
var db = level('./data/db');
var em = eelmail(db, { dir: './data' });
em.createServer('smtp').listen(25);
em.createServer('imap').listen(143);
|
var im = require('simple-imagemagick');
var fs = require('fs');
var async = require('async');
// still need to figure out what '+repage' does, but it fixes a lot of issues :p
// orientates the image correctly
function autoOrient (inputfile, outputfile, callback) {
im.convert([
inputfile,
'+repage' ,
'-auto-orient',
outputfile
], function (err, stdout, stderr){
if (err) return callback(err);
return callback(null, stdout);
});
}
function crop (inputfile, width, heigth, outputfile, callback) {
im.convert([
inputfile,
'+repage' ,
'-resize' , width+'x'+heigth+'^',
'-gravity' , 'center',
'-crop' , width+'x'+heigth+'+0+0',
outputfile
], function (err, stdout, stderr){
if (err) return callback(err);
return callback(null, stdout);
});
}
function readAllPixels_old (inputfile, width, height, callback) {
// build command
// convert ninepixels.png -colorspace HSB -format "%[pixel:p{0,1}];%[pixel:p{3}]\n" info:
var pixelArrayFormat = [];
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
pixelArrayFormat.push('%[pixel:p{' + x + ',' + y + '}]');
};
};
im.convert([
inputfile,
'+repage' ,
'-colorspace' , 'HSB',
'-format' , pixelArrayFormat.join(';'),
'info:'
], function (err, stdout, stderr){
if (err) return callback(err);
var pixels = [];
var dataArray = stdout.split(';');
for (var i = 0; i < dataArray.length; i++) {
var match = dataArray[i].match(/hsb\((.+)?\%,(.+)?\%,(.+)?\%\)/);
pixels.push({
// string: hsb,
h: parseFloat(match[1]),
s: parseFloat(match[2]),
b: parseFloat(match[3])
});
};
return callback(null, pixels);
});
}
function readAllPixels (inputfile, width, height, callback) {
// build command
// convert ninepixels.png -colorspace HSB -format "%[pixel:p{0,1}];%[pixel:p{3}]\n" info:
var pixelArrayFormat = [];
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var p = 'p{'+x+','+y+'}';
pixelArrayFormat.push('%[fx:'+p+'.r*100];%[fx:'+p+'.g*100];%[fx:'+p+'.b*100]');
};
};
im.convert([
inputfile,
'+repage' ,
'-colorspace' , 'HSB',
'-format' , pixelArrayFormat.join('|'),
'info:'
], function (err, stdout, stderr){
if (err) return callback(err);
var pixels = [];
var dataArray = stdout.split('|');
for (var i = 0; i < dataArray.length; i++) {
var values = dataArray[i].split(';');
pixels.push({
h: parseFloat(values[0]),
s: parseFloat(values[1]),
b: parseFloat(values[2])
});
};
return callback(null, pixels);
});
}
function resize (inputfile, width, heigth, outputfile, callback) {
// test data, value is differenceCount in mosaic.js
// Average 1782
// Average4
// Average9 1714
// Average16 1503
// Background 3333
// Bilinear 1700
// Blend 1782
// Integer 1874
// Mesh 1782
// Nearest 1865
// NearestNeighbor 1865
// Spline 1748
// (normal) -resize 1275 (BEST)
// -adaptive-resize 1782
// -sample 1865
im.convert([
inputfile,
'+repage' ,
'-resize' , width+'x'+heigth,
outputfile
], function (err, stdout, stderr){
if (err) return callback(err);
return callback(null, stdout);
});
}
function slice (inputfile, width, heigth, outputfiles, callback) {
// convert out/tree_1200x1000.png +gravity -crop 100x100 out/tree_%03d.png
im.convert([
inputfile,
'+repage' ,
'-crop' , width+'x'+heigth,
outputfiles
], function (err, stdout, stderr){
if (err) return callback(err);
return callback(null, stdout);
});
}
function getAverageHSBColor_old(inputfile, callback){
im.convert([
inputfile,
'+repage' ,
'-colorspace' , 'HSB',
'-scale' , '1x1',
'-format' , '\'%[pixel:u]\'',
'info:'
], function (err, stdout, stderr){
if (err) return callback(err);
var hsb = stdout.replace(/'(.+)'/, '$1');
console.log(hsb);
var match = hsb.match(/hsb\((.+)?\%,(.+)?\%,(.+)?\%\)/);
var hsb = {
// string: hsb,
h: parseFloat(match[1]),
s: parseFloat(match[2]),
b: parseFloat(match[3])
}
return callback(null, hsb);
});
}
function getAverageHSBColor(inputfile, callback){
im.convert([
inputfile,
'+repage' ,
'-colorspace' , 'HSB',
'-scale' , '1x1',
'-format' , '%[fx:r*100];%[fx:g*100];%[fx:b*100]',
'info:'
], function (err, stdout, stderr){
if (err) return callback(err);
var values = stdout.split(';');
var hsb = {
h: parseFloat(values[0]),
s: parseFloat(values[1]),
b: parseFloat(values[2])
};
return callback(null, hsb);
});
}
function getAverageColor(inputfile, callback){
var res = {};
getAverageRGBColor(inputfile, function (err, rgb){
if(err) return callback(err);
res.rgb = rgb;
getAverageHSBColor(inputfile, function (err, hsb){
if(err) return callback(err);
res.hsb = hsb;
return callback(null, res);
});
});
}
function createSolidImage(size, rgb, outputfile, callback){
im.convert([
'+repage' ,
'-size' , size,
'xc:' + rgb,
outputfile,
], function (err, stdout, stderr){
if (err) return callback(err);
return callback(null, stdout);
});
}
function modulate(inputfile, h, b, s, outputfile, callback){
im.convert([
inputfile,
'+repage' ,
'-modulate' , b+','+s+','+h,
outputfile
], function (err, stdout, stderr){
if (err) return callback(err);
return callback(null, stdout);
});
}
function stitchImages (inputfiles, tilesWide, tilesHeigh, outputfile, callback) {
// montage img1.png img2.png img3.png -tile 12x10 -geometry +0+0 out/tree_stitched_back_together.png
var parameters = [
'-tile' , tilesWide+'x'+tilesHeigh,
'-geometry' , '+0+0',
outputfile
];
parameters = inputfiles.concat(parameters); // begin the parameters with the input files
im.montage(parameters, function (err, stdout, stderr){
if (err) return callback(err);
return callback(null, stdout);
});
}
function overlayImages (inputimage1, inputimage2, outputfile, callback){
// composite -compose Multiply -gravity center img1.png img2 compose_multiply.png
im.composite([
'+repage' ,
'-compose' , 'Multiply',
'-gravity' , 'center',
inputimage1,
inputimage2,
outputfile
], function (err, stdout, stderr){
if (err) return callback(err);
return callback(null, stdout);
});
}
function addOverlay (inputfile, overlay, offsetX, offsetY, outputfile, callback) {
async.waterfall([
function ($) {
// get width and height of overlay:
im.identify(overlay, $)
},
function (imagedata, $) {
// convert rose: -extent -background none 600x600-4-50\! crop_vp_all.gif
// put it in a larger canvas (size of the overlay):
im.convert([
inputfile,
'+repage' ,
'-background' , 'none',
'-extent' , imagedata.width+'x'+imagedata.height+'-'+offsetX+'-'+offsetY+'\!',
outputfile
], $);
},
function (stdout, stderr, $) {
// overlay it with overlay:
im.composite([
overlay,
outputfile,
outputfile
], $);
}
], callback);
}
function getImageSize (inputfile, callback) {
im.identify(overlay, function (err, data) {
if(err) return callback(err);
return callback(null, data);
});
}
exports.autoOrient = autoOrient;
exports.crop = crop;
exports.slice = slice;
exports.getAverageHSBColor_old = getAverageHSBColor_old;
exports.getAverageHSBColor = getAverageHSBColor;
exports.getAverageColor = getAverageColor;
exports.createSolidImage = createSolidImage;
exports.modulate = modulate;
exports.stitchImages = stitchImages;
exports.overlayImages = overlayImages;
exports.resize = resize;
exports.readAllPixels_old = readAllPixels_old;
exports.readAllPixels = readAllPixels;
exports.addOverlay = addOverlay;
exports.getImageSize = getImageSize;
|
/**
* Module dependencies.
*/
var Route = require('./route')
, utils = require('./utils')
, debug = require('debug')('kerouac');
/**
* Initialize a new `Router`.
*
* @api private
*/
function Router() {
var self = this;
this._routes = [];
this.middleware = function(page, next) {
self._dispatch(page, next);
};
}
/**
* Route `path` to one or more callbacks.
*
* @param {String} path
* @param {Function|Array} fns
* @return {Route}
* @api protected
*/
Router.prototype.route = function(path, fns) {
var fns = utils.flatten([].slice.call(arguments, 1));
debug('defined %s', path);
var route = new Route(path, fns);
this._routes.push(route);
return route;
}
/**
* Route dispatcher, aka the router "middleware".
*
* @param {Page} page
* @param {Function} next
* @api private
*/
Router.prototype._dispatch = function(page, next) {
var self = this;
debug('dispatching %s %s', page.path);
// route dispatch
(function pass(i, err) {
function nextRoute(err) {
pass(page._route_index + 1, err);
}
// match route
var route = self._match(page, i);
// no route
if (!route) { return next(err); }
debug('matched %s', route.path);
page.params = route.params;
// invoke route callbacks
var i = 0;
function callbacks(err) {
var fn = route.fns[i++];
try {
if ('route' == err) {
nextRoute();
} else if (err && fn) {
if (fn.length < 3) { return callbacks(err); }
debug('applying %s %s', page.path, fn.name || 'anonymous');
fn(err, page, callbacks);
} else if (fn) {
if (fn.length < 3) {
debug('applying %s %s', page.path, fn.name || 'anonymous');
return fn(page, callbacks);
}
callbacks();
} else {
nextRoute(err);
}
} catch (err) {
callbacks(err);
}
}
callbacks();
})(0);
}
/**
* Attempt to match a route for `page`
* with optional starting index of `i`
* defaulting to 0.
*
* @param {Page} page
* @param {Number} i
* @return {Route}
* @api private
*/
Router.prototype._match = function(page, i) {
var path = page.path
, routes = this._routes
, i = i || 0
, route;
// matching routes
for (var len = routes.length; i < len; ++i) {
route = routes[i];
if (route.match(path)) {
page._route_index = i;
return route;
}
}
}
/**
* Expose `Router`.
*/
module.exports = Router;
|
import * as Require from './require';
import parseExpression from './expression';
import parseCompound from './compound';
export default tokens => {
Require.variable(tokens.peek());
const variable = {
type: tokens.pop().type,
value: undefined
};
if (Require.isIdentifier(tokens.peek())) {
variable.name = tokens.pop().value;
} else {
Require.isCompoundStart(tokens.peek());
variable.names = parseCompound(tokens);
}
if (Require.isAssignment(tokens.peek())) {
tokens.pop();
variable.value = parseExpression(tokens);
}
return variable;
}
|
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { RouteTransition } from 'react-router-transition';
import base from '../base';
import paths from '../paths';
import Icon from './Icon';
class PageTemplate extends Component {
constructor(props) {
super(props);
this.onSignOutClick = this.onSignOutClick.bind(this);
}
onSignOutClick(event) {
base.unauth();
event.preventDefault();
}
render() {
const { children, location, user } = this.props;
return (
<div className="pagetemplate">
{ !user.isLoading && user.email ? (
<header className="pageheader">
<nav>
<span>undermud</span>
<Link to={ paths.characters() }><Icon name="users" /></Link>
<a onClick={ this.onSignOutClick } href="javascript:void(0)"><Icon name="sign-out" /></a>
</nav>
</header>
) : null }
<RouteTransition
className="routetransition"
pathname={location.pathname}
atEnter={{ opacity: 0 }}
atLeave={{ opacity: 0 }}
atActive={{ opacity: 1 }}
>
{children}
</RouteTransition>
</div>
);
}
}
PageTemplate.propTypes = {
children: PropTypes.oneOfType([
PropTypes.node,
PropTypes.arrayOf(PropTypes.node),
]),
};
export default connect(
(state) => ({
user: state.user,
})
)(PageTemplate);
|
const fs = require('fs');
function DirectoryExistenceChecker(path, directory) {
this.perform = () => {
const directoryToCheck = `${path}/${directory}`;
try {
fs.accessSync(directoryToCheck, fs.F_OK);
return true;
} catch (error) {
return false;
}
};
}
module.exports = DirectoryExistenceChecker;
|
import Ember from 'ember'
const { computed, get } = Ember
export default Ember.Component.extend({
name: '',
computedValue: computed('value', 'options', function () {
const value = get(this, 'value')
return value == null ? null : get(this, 'options').find(option => option.value === value)
}),
options: computed('value', 'disabled', function () {
return [
{
value: true,
label: 'Yes',
disabled: get(this, 'disabled')
},
{
value: false,
label: 'No',
disabled: get(this, 'disabled')
}
]
}),
actions: {
onChange (selectedValue) {
get(this, 'update')(get(selectedValue, 'value'))
}
}
})
|
(function($) {
// This is the connector function.
// It connects one item from the navigation carousel to one item from the
// stage carousel.
// The default behaviour is, to connect items with the same index from both
// carousels. This might _not_ work with circular carousels!
var connector = function(itemNavigation, carouselStage) {
return carouselStage.jcarousel('items').eq(itemNavigation.index());
};
$(function() {
// Setup the carousels. Adjust the options for both carousels here.
var carouselStage = $('.carousel-stage').jcarousel();
var carouselNavigation = $('.carousel-navigation').jcarousel();
// We loop through the items of the navigation carousel and set it up
// as a control for an item from the stage carousel.
carouselNavigation.jcarousel('items').each(function() {
var item = $(this);
// This is where we actually connect to items.
var target = connector(item, carouselStage);
item
.on('jcarouselcontrol:active', function() {
carouselNavigation.jcarousel('scrollIntoView', this);
item.addClass('active');
})
.on('jcarouselcontrol:inactive', function() {
item.removeClass('active');
})
.jcarouselControl({
target: target,
carousel: carouselStage
});
});
$('.prev-navigation').click(function(){
carouselStage.jcarousel('scroll', '-=1');
});
$('.next-navigation').click(function(){
carouselStage.jcarousel('scroll', '+=1');
});
});
})(jQuery);
|
version https://git-lfs.github.com/spec/v1
oid sha256:ffe868bf6da30bd52339eec5ee64ade17f53afffe5019315f5b37d2c61b5818e
size 2193
|
var gulp = require('gulp');
var browserSync = require('browser-sync');
var plumber = require('gulp-plumber');
var watch = require('gulp-watch');
var bower = require('main-bower-files');
var concat = require('gulp-concat');
// for compass
var compass = require('gulp-compass');
// for webpack
var webpack = require('gulp-webpack');
var webpackConfig = require('./config/webpack.js');
gulp.task('html-copy', function() {
gulp.src('./src/html/**/*.html')
.pipe(gulp.dest('./build/'));
});
gulp.task('cgi-bin-copy', function() {
gulp.src('./src/cgi-bin/**/*.cgi')
.pipe(gulp.dest('./build/cgi-bin/'));
});
gulp.task('font-copy', function() {
gulp.src('./src/font/**/*.ttf')
.pipe(gulp.dest('./build/font/'));
});
gulp.task('image-copy', function() {
gulp.src([
'./src/images/**/*.png',
'./src/images/**/*.jpg'
])
.pipe(gulp.dest('./build/images/'));
});
gulp.task('compass', function() {
gulp.src('./src/sass/**/*.scss')
.pipe(plumber())
.pipe(compass({
config_file: './config/compass.rb',
comments: false,
css: './build/css/',
sass: './src/sass/'
}));
});
gulp.task('copy-js-ext', function() {
gulp.src(bower())
.pipe(concat('ext-lib.js'))
.pipe(gulp.dest('./build/js/ext/'));
});
gulp.task('copy-js', function() {
gulp.src('./src/js/**/*.js')
.pipe(concat('bundle.js'))
.pipe(gulp.dest('./build/js/'));
});
// gulp.task('webpack', function () {
// gulp.src(['./src/ts/*.ts'])
// .pipe(webpack(webpackConfig))
// .pipe(gulp.dest('./build/js/'));
// });
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: './build/'
}
});
});
gulp.task('bs-reload', function() {
browserSync.reload();
});
gulp.task('watch', function() {
watch('src/html/**/*.html', function(event) {
gulp.start('html-copy');
});
watch('src/cgi-bin/**/*.cgi', function(event) {
gulp.start('cgi-bin-copy');
});
watch('src/font/**/*.ttf', function(event) {
gulp.start('font-copy');
});
watch([
'src/images/**/*.png',
'src/images/**/*.jpg'
],function(event) {
gulp.start('image-copy');
});
watch('src/sass/**/*.scss', function(event) {
gulp.start('compass');
});
watch([
'./src/ts/**/*.ts',
'!./node_modules/**'
], function(event) {
gulp.start('webpack');
});
watch('./bower_components/**/*.js', function(event) {
gulp.start('copy-js-ext');
});
watch('./src/js/**/*.js', function(event) {
gulp.start('copy-js');
});
watch('./build/**', function(event) {
gulp.start('bs-reload');
});
});
gulp.task('default', [
'html-copy',
'cgi-bin-copy',
'font-copy',
'image-copy',
'compass',
'copy-js-ext',
'copy-js',
'browser-sync',
'watch'
]);
gulp.task('copy', [
'html-copy',
'cgi-bin-copy',
'font-copy',
'image-copy',
'compass',
'copy-js-ext',
'copy-js'
]);
|
import FizzBuzz from '../src/FizzBuzz';
describe('FizzBuzz', () => {
let game = new FizzBuzz();
it('returns 1 for 1', () => {
expect(game.for(1)).toBe('1');
});
it('returns 2 for 2', () => {
expect(game.for(2)).toBe('2');
});
it('returns Fizz for 3', () => {
expect(game.for(3)).toBe('Fizz');
});
it('returns 4 for 4', () => {
expect(game.for(4)).toBe('4');
});
it('returns Buzz for 5', () => {
expect(game.for(5)).toBe('Buzz');
});
it('returns Fizz for 6', () => {
expect(game.for(6)).toBe('Fizz');
});
it('returns FizzBuzz for 15', () => {
expect(game.for(15)).toBe('FizzBuzz');
});
});
|
'use strict';
const line = require('@line/bot-sdk');
const express = require('express');
// create LINE SDK config from env variables
const config = {
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
channelSecret: process.env.CHANNEL_SECRET,
};
// create LINE SDK client
const client = new line.Client(config);
// create Express app
// about Express itself: https://expressjs.com/
const app = express();
// register a webhook handler with middleware
// about the middleware, please refer to doc
app.post('/webhook', line.middleware(config), (req, res) => {
Promise
.all(req.body.events.map(handleEvent))
.then((result) => res.json(result))
.catch((err) => {
console.log(err);
});
});
// event handler
function handleEvent(event) {
if (event.type !== 'message' || event.message.type !== 'text') {
// ignore non-text-message event
return Promise.resolve(null);
}
// create a echoing text message
const echo = { type: 'text', text: event.message.text };
// use reply API
return client.replyMessage(event.replyToken, echo);
}
// listen on port
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`listening on ${port}`);
});
|
import Model, { attr } from '@ember-data/model';
import { computed } from '@ember/object';
import { equal, or } from '@ember/object/computed';
export default Model.extend({
name: attr('string'),
startingPrice: attr('number'),
startingUsers: attr('number'),
privateCredits: attr('number'),
publicCredits: attr('number'),
concurrencyLimit: attr('number'),
planType: attr('string'),
availableStandaloneAddons: attr(),
annual: attr('boolean'),
autoRefillThresholds: attr(),
autoRefillAmounts: attr(),
trialPlan: attr(),
isFree: equal('startingPrice', 0),
isTrial: equal('trialPlan', true),
isUnlimitedUsers: equal('startingUsers', 999999),
isAnnual: equal('annual', true),
privateCreditsTotal: computed('privateCredits', 'isAnnual', function () {
return this.isAnnual ? this.privateCredits * 12 : this.privateCredits;
}),
addonConfigs: attr(),
hasCreditAddons: computed('addonConfigs', 'addonConfigs.@each.type', function () {
return this.addonConfigs.filter(addon => addon.type === 'credit_private').length > 0;
}),
hasOSSCreditAddons: computed('addonConfigs', 'addonConfigs.@each.type', function () {
return this.addonConfigs.filter(addon => addon.type === 'credit_public').length > 0;
}),
hasUserLicenseAddons: computed('addonConfigs', 'addonConfigs.@each.type', function () {
return this.addonConfigs.filter(addon => addon.type === 'user_license').length > 0;
}),
hasCredits: or('hasCreditAddons', 'hasOSSCreditAddons')
});
|
'use strict'
const curryRight = require('lodash/curryRight')
const pMap = curryRight(require('p-map'), 2)
const findConfig = require('cordova-find-config')
const {
parseConfig,
extractExcludePatterns,
buildDeletionJobs,
processDeletionJob,
} = require('./util')
const deletionJobBuilderFor = curryRight(buildDeletionJobs)
module.exports = function(context) {
return findConfig(context.opts.projectRoot)
.then(parseConfig)
.then(extractExcludePatterns)
.then(deletionJobBuilderFor(context))
.then(pMap(processDeletionJob))
}
|
const click = () => console.log('clicked...')
module.exports = [
{
description: 'Invisible item.',
input: ['Show', click, { visible: false }],
output: { label: 'Show', visible: false, click }
}
]
|
$.readline.prompt($.preserveCursor || undefined);
output.readline = $.get('readline');
|
var webpack = require('webpack');
var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
var path = require('path');
var env = require('yargs').argv.mode;
var libraryName = 'web-notifications';
var plugins = [], outputFile;
if (env === 'build') {
plugins.push(new UglifyJsPlugin({ minimize: true }));
outputFile = libraryName + '.min.js';
} else {
outputFile = libraryName + '.js';
}
var config = {
entry: __dirname + '/src/index.js',
devtool: 'source-map',
output: {
path: __dirname + '/lib',
filename: outputFile,
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
loaders: [
{
test: /(\.jsx|\.js)$/,
loader: 'babel',
exclude: /(node_modules|bower_components)/
}
]
},
resolve: {
root: path.resolve('./src'),
extensions: ['', '.js']
},
plugins: plugins
};
module.exports = config;
|
'use strict';
// Setting up route
angular.module('core').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// Redirect to home view when route not found
$urlRouterProvider.otherwise('/');
// Home state routing
$stateProvider.
state('home', {
url: '/',
templateUrl: 'modules/core/views/home.client.view.html'
}).
state('aboutus', {
url: '/aboutus',
templateUrl: 'modules/core/views/aboutus.client.view.html'
});
}
]);
|
var url = require("url");
var URL = url.URL;
var http = require("http");
var https = require("https");
var assert = require("assert");
var Writable = require("stream").Writable;
var debug = require("debug")("follow-redirects");
// RFC7231§4.2.1: Of the request methods defined by this specification,
// the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe.
var SAFE_METHODS = { GET: true, HEAD: true, OPTIONS: true, TRACE: true };
// Create handlers that pass events from native requests
var eventHandlers = Object.create(null);
["abort", "aborted", "error", "socket", "timeout"].forEach(function (event) {
eventHandlers[event] = function (arg) {
this._redirectable.emit(event, arg);
};
});
// An HTTP(S) request that can be redirected
function RedirectableRequest(options, responseCallback) {
// Initialize the request
Writable.call(this);
this._sanitizeOptions(options);
this._options = options;
this._ended = false;
this._ending = false;
this._redirectCount = 0;
this._redirects = [];
this._requestBodyLength = 0;
this._requestBodyBuffers = [];
// Attach a callback if passed
if (responseCallback) {
this.on("response", responseCallback);
}
// React to responses of native requests
var self = this;
this._onNativeResponse = function (response) {
self._processResponse(response);
};
// Perform the first request
this._performRequest();
}
RedirectableRequest.prototype = Object.create(Writable.prototype);
// Writes buffered data to the current native request
RedirectableRequest.prototype.write = function (data, encoding, callback) {
// Writing is not allowed if end has been called
if (this._ending) {
throw new Error("write after end");
}
// Validate input and shift parameters if necessary
if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) {
throw new Error("data should be a string, Buffer or Uint8Array");
}
if (typeof encoding === "function") {
callback = encoding;
encoding = null;
}
// Ignore empty buffers, since writing them doesn't invoke the callback
// https://github.com/nodejs/node/issues/22066
if (data.length === 0) {
if (callback) {
callback();
}
return;
}
// Only write when we don't exceed the maximum body length
if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
this._requestBodyLength += data.length;
this._requestBodyBuffers.push({ data: data, encoding: encoding });
this._currentRequest.write(data, encoding, callback);
}
// Error when we exceed the maximum body length
else {
this.emit("error", new Error("Request body larger than maxBodyLength limit"));
this.abort();
}
};
// Ends the current native request
RedirectableRequest.prototype.end = function (data, encoding, callback) {
// Shift parameters if necessary
if (typeof data === "function") {
callback = data;
data = encoding = null;
}
else if (typeof encoding === "function") {
callback = encoding;
encoding = null;
}
// Write data if needed and end
if (!data) {
this._ended = this._ending = true;
this._currentRequest.end(null, null, callback);
}
else {
var self = this;
var currentRequest = this._currentRequest;
this.write(data, encoding, function () {
self._ended = true;
currentRequest.end(null, null, callback);
});
this._ending = true;
}
};
// Sets a header value on the current native request
RedirectableRequest.prototype.setHeader = function (name, value) {
this._options.headers[name] = value;
this._currentRequest.setHeader(name, value);
};
// Clears a header value on the current native request
RedirectableRequest.prototype.removeHeader = function (name) {
delete this._options.headers[name];
this._currentRequest.removeHeader(name);
};
// Global timeout for all underlying requests
RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
if (callback) {
this.once("timeout", callback);
}
if (this.socket) {
startTimer(this, msecs);
}
else {
var self = this;
this._currentRequest.once("socket", function () {
startTimer(self, msecs);
});
}
this.once("response", clearTimer);
this.once("error", clearTimer);
return this;
};
function startTimer(request, msecs) {
clearTimeout(request._timeout);
request._timeout = setTimeout(function () {
request.emit("timeout");
}, msecs);
}
function clearTimer() {
clearTimeout(this._timeout);
}
// Proxy all other public ClientRequest methods
[
"abort", "flushHeaders", "getHeader",
"setNoDelay", "setSocketKeepAlive",
].forEach(function (method) {
RedirectableRequest.prototype[method] = function (a, b) {
return this._currentRequest[method](a, b);
};
});
// Proxy all public ClientRequest properties
["aborted", "connection", "socket"].forEach(function (property) {
Object.defineProperty(RedirectableRequest.prototype, property, {
get: function () { return this._currentRequest[property]; },
});
});
RedirectableRequest.prototype._sanitizeOptions = function (options) {
// Ensure headers are always present
if (!options.headers) {
options.headers = {};
}
// Since http.request treats host as an alias of hostname,
// but the url module interprets host as hostname plus port,
// eliminate the host property to avoid confusion.
if (options.host) {
// Use hostname if set, because it has precedence
if (!options.hostname) {
options.hostname = options.host;
}
delete options.host;
}
// Complete the URL object when necessary
if (!options.pathname && options.path) {
var searchPos = options.path.indexOf("?");
if (searchPos < 0) {
options.pathname = options.path;
}
else {
options.pathname = options.path.substring(0, searchPos);
options.search = options.path.substring(searchPos);
}
}
};
// Executes the next native request (initial or redirect)
RedirectableRequest.prototype._performRequest = function () {
// Load the native protocol
var protocol = this._options.protocol;
var nativeProtocol = this._options.nativeProtocols[protocol];
if (!nativeProtocol) {
this.emit("error", new Error("Unsupported protocol " + protocol));
return;
}
// If specified, use the agent corresponding to the protocol
// (HTTP and HTTPS use different types of agents)
if (this._options.agents) {
var scheme = protocol.substr(0, protocol.length - 1);
this._options.agent = this._options.agents[scheme];
}
// Create the native request
var request = this._currentRequest =
nativeProtocol.request(this._options, this._onNativeResponse);
this._currentUrl = url.format(this._options);
// Set up event handlers
request._redirectable = this;
for (var event in eventHandlers) {
/* istanbul ignore else */
if (event) {
request.on(event, eventHandlers[event]);
}
}
// End a redirected request
// (The first request must be ended explicitly with RedirectableRequest#end)
if (this._isRedirect) {
// Write the request entity and end.
var i = 0;
var self = this;
var buffers = this._requestBodyBuffers;
(function writeNext(error) {
// Only write if this request has not been redirected yet
/* istanbul ignore else */
if (request === self._currentRequest) {
// Report any write errors
/* istanbul ignore if */
if (error) {
self.emit("error", error);
}
// Write the next buffer if there are still left
else if (i < buffers.length) {
var buffer = buffers[i++];
/* istanbul ignore else */
if (!request.finished) {
request.write(buffer.data, buffer.encoding, writeNext);
}
}
// End the request if `end` has been called on us
else if (self._ended) {
request.end();
}
}
}());
}
};
// Processes a response from the current native request
RedirectableRequest.prototype._processResponse = function (response) {
// Store the redirected response
var statusCode = response.statusCode;
if (this._options.trackRedirects) {
this._redirects.push({
url: this._currentUrl,
headers: response.headers,
statusCode: statusCode,
});
}
// RFC7231§6.4: The 3xx (Redirection) class of status code indicates
// that further action needs to be taken by the user agent in order to
// fulfill the request. If a Location header field is provided,
// the user agent MAY automatically redirect its request to the URI
// referenced by the Location field value,
// even if the specific status code is not understood.
var location = response.headers.location;
if (location && this._options.followRedirects !== false &&
statusCode >= 300 && statusCode < 400) {
// Abort the current request
this._currentRequest.removeAllListeners();
this._currentRequest.on("error", noop);
this._currentRequest.abort();
// Discard the remainder of the response to avoid waiting for data
response.destroy();
// RFC7231§6.4: A client SHOULD detect and intervene
// in cyclical redirections (i.e., "infinite" redirection loops).
if (++this._redirectCount > this._options.maxRedirects) {
this.emit("error", new Error("Max redirects exceeded."));
return;
}
// RFC7231§6.4: Automatic redirection needs to done with
// care for methods not known to be safe […],
// since the user might not wish to redirect an unsafe request.
// RFC7231§6.4.7: The 307 (Temporary Redirect) status code indicates
// that the target resource resides temporarily under a different URI
// and the user agent MUST NOT change the request method
// if it performs an automatic redirection to that URI.
var header;
var headers = this._options.headers;
if (statusCode !== 307 && !(this._options.method in SAFE_METHODS)) {
this._options.method = "GET";
// Drop a possible entity and headers related to it
this._requestBodyBuffers = [];
for (header in headers) {
if (/^content-/i.test(header)) {
delete headers[header];
}
}
}
// Drop the Host header, as the redirect might lead to a different host
if (!this._isRedirect) {
for (header in headers) {
if (/^host$/i.test(header)) {
delete headers[header];
}
}
}
// Perform the redirected request
var redirectUrl = url.resolve(this._currentUrl, location);
debug("redirecting to", redirectUrl);
Object.assign(this._options, url.parse(redirectUrl));
if (typeof this._options.beforeRedirect === "function") {
try {
this._options.beforeRedirect.call(null, this._options);
}
catch (err) {
this.emit("error", err);
return;
}
this._sanitizeOptions(this._options);
}
this._isRedirect = true;
this._performRequest();
}
else {
// The response is not a redirect; return it as-is
response.responseUrl = this._currentUrl;
response.redirects = this._redirects;
this.emit("response", response);
// Clean up
this._requestBodyBuffers = [];
}
};
// Wraps the key/value object of protocols with redirect functionality
function wrap(protocols) {
// Default settings
var exports = {
maxRedirects: 21,
maxBodyLength: 10 * 1024 * 1024,
};
// Wrap each protocol
var nativeProtocols = {};
Object.keys(protocols).forEach(function (scheme) {
var protocol = scheme + ":";
var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
// Executes a request, following redirects
wrappedProtocol.request = function (input, options, callback) {
// Parse parameters
if (typeof input === "string") {
var urlStr = input;
try {
input = urlToOptions(new URL(urlStr));
}
catch (err) {
/* istanbul ignore next */
input = url.parse(urlStr);
}
}
else if (URL && (input instanceof URL)) {
input = urlToOptions(input);
}
else {
callback = options;
options = input;
input = { protocol: protocol };
}
if (typeof options === "function") {
callback = options;
options = null;
}
// Set defaults
options = Object.assign({
maxRedirects: exports.maxRedirects,
maxBodyLength: exports.maxBodyLength,
}, input, options);
options.nativeProtocols = nativeProtocols;
assert.equal(options.protocol, protocol, "protocol mismatch");
debug("options", options);
return new RedirectableRequest(options, callback);
};
// Executes a GET request, following redirects
wrappedProtocol.get = function (input, options, callback) {
var request = wrappedProtocol.request(input, options, callback);
request.end();
return request;
};
});
return exports;
}
/* istanbul ignore next */
function noop() { /* empty */ }
// from https://github.com/nodejs/node/blob/master/lib/internal/url.js
function urlToOptions(urlObject) {
var options = {
protocol: urlObject.protocol,
hostname: urlObject.hostname.startsWith("[") ?
/* istanbul ignore next */
urlObject.hostname.slice(1, -1) :
urlObject.hostname,
hash: urlObject.hash,
search: urlObject.search,
pathname: urlObject.pathname,
path: urlObject.pathname + urlObject.search,
href: urlObject.href,
};
if (urlObject.port !== "") {
options.port = Number(urlObject.port);
}
return options;
}
// Exports
module.exports = wrap({ http: http, https: https });
module.exports.wrap = wrap;
|
/* eslint-disable react/destructuring-assignment */
import smoothscroll from 'smoothscroll-polyfill';
import React from 'react';
import PropTypes from 'prop-types';
const Element = (props) => props.children;
class Scroll extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
smoothscroll.polyfill();
}
handleClick(e) {
e.preventDefault();
let elem = 0;
let scroll = true;
const { type, element, offset, timeout } = this.props;
if (type && element) {
switch (type) {
case 'class':
// eslint-disable-next-line prefer-destructuring
elem = document.getElementsByClassName(element)[0];
scroll = !!elem;
break;
case 'id':
elem = document.getElementById(element);
scroll = !!elem;
break;
default:
}
}
// eslint-disable-next-line no-unused-expressions
scroll
? this.scrollTo(elem, offset, timeout)
: console.log(`Element not found: ${element}`);
}
// eslint-disable-next-line class-methods-use-this
scrollTo(element, offSet = 0, timeout = null) {
const elemPos = element
? element.getBoundingClientRect().top + window.pageYOffset
: 0;
if (timeout) {
setTimeout(() => {
window.scroll({ top: elemPos + offSet, left: 0, behavior: 'smooth' });
}, timeout);
} else {
window.scroll({ top: elemPos + offSet, left: 0, behavior: 'smooth' });
}
}
render() {
return (
<Element>
{typeof this.props.children === 'object' ? (
React.cloneElement(this.props.children, { onClick: this.handleClick })
) : (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
<span onClick={this.handleClick}>{this.props.children}</span>
)}
</Element>
);
}
}
Scroll.propTypes = {
type: PropTypes.string,
element: PropTypes.string,
offset: PropTypes.number,
timeout: PropTypes.number,
children: PropTypes.node.isRequired,
};
export default Scroll;
|
window.esdocSearchIndex = [
[
"hoist-connector-xero/src/views/edit.js~editform",
"class/src/views/edit.js~EditForm.html",
"<span>EditForm</span> <span class=\"search-result-import-path\">hoist-connector-xero/src/views/edit.js</span>",
"class"
],
[
"builtinexternal/ecmascriptexternal.js~array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~arraybuffer",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~ArrayBuffer",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~boolean",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Boolean",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~dataview",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~DataView",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~date",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Date",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~error",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Error",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~evalerror",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~EvalError",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~float32array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Float32Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~float64array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Float64Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~function",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Function",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~generator",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Generator",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~generatorfunction",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~GeneratorFunction",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~infinity",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Infinity",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~int16array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Int16Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~int32array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Int32Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~int8array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Int8Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~internalerror",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~InternalError",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~json",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~JSON",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~map",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Map",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~nan",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~NaN",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~number",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Number",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~object",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Object",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~promise",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Promise",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~proxy",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Proxy",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~rangeerror",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~RangeError",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~referenceerror",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~ReferenceError",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~reflect",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Reflect",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~regexp",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~RegExp",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~set",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Set",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~string",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~String",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~symbol",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Symbol",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~syntaxerror",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~SyntaxError",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~typeerror",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~TypeError",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~urierror",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~URIError",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~uint16array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Uint16Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~uint32array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Uint32Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~uint8array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Uint8Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~uint8clampedarray",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Uint8ClampedArray",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~weakmap",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~WeakMap",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~weakset",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~WeakSet",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~boolean",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~boolean",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~function",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~function",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~null",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~null",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~number",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~number",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~object",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~object",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~string",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~string",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~undefined",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~undefined",
"external"
],
[
"builtinexternal/webapiexternal.js~audiocontext",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~AudioContext",
"external"
],
[
"builtinexternal/webapiexternal.js~canvasrenderingcontext2d",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~CanvasRenderingContext2D",
"external"
],
[
"builtinexternal/webapiexternal.js~documentfragment",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~DocumentFragment",
"external"
],
[
"builtinexternal/webapiexternal.js~element",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~Element",
"external"
],
[
"builtinexternal/webapiexternal.js~event",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~Event",
"external"
],
[
"builtinexternal/webapiexternal.js~node",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~Node",
"external"
],
[
"builtinexternal/webapiexternal.js~nodelist",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~NodeList",
"external"
],
[
"builtinexternal/webapiexternal.js~xmlhttprequest",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~XMLHttpRequest",
"external"
],
[
"",
"test-file/tests/unit_tests/bounce_tests.js.html#lineNumber7",
"Xero Connector",
"test"
],
[
"",
"test-file/tests/unit_tests/bounce_tests.js.html#lineNumber8",
"Xero Connector Public app",
"test"
],
[
"",
"test-file/tests/unit_tests/bounce_tests.js.html#lineNumber9",
"Xero Connector Public app #receiveBounce",
"test"
],
[
"",
"test-file/tests/unit_tests/bounce_tests.js.html#lineNumber10",
"Xero Connector Public app #receiveBounce first bounce",
"test"
],
[
"",
"test-file/tests/unit_tests/bounce_tests.js.html#lineNumber27",
"Xero Connector Public app #receiveBounce first bounce redirects to xero",
"test"
],
[
"",
"test-file/tests/unit_tests/bounce_tests.js.html#lineNumber32",
"Xero Connector Public app #receiveBounce first bounce saves request token",
"test"
],
[
"",
"test-file/tests/unit_tests/bounce_tests.js.html#lineNumber36",
"Xero Connector Public app #receiveBounce first bounce saves request token secret",
"test"
],
[
"",
"test-file/tests/unit_tests/bounce_tests.js.html#lineNumber41",
"Xero Connector Public app #receiveBounce on return from Xero",
"test"
],
[
"",
"test-file/tests/unit_tests/bounce_tests.js.html#lineNumber65",
"Xero Connector Public app #receiveBounce on return from Xero redirects back to app",
"test"
],
[
"",
"test-file/tests/unit_tests/bounce_tests.js.html#lineNumber74",
"Xero Connector Public app #receiveBounce on return from Xero saves access token",
"test"
],
[
"",
"test-file/tests/unit_tests/bounce_tests.js.html#lineNumber78",
"Xero Connector Public app #receiveBounce on return from Xero saves access token secret",
"test"
],
[
"",
"test-file/tests/unit_tests/bounce_tests.js.html#lineNumber70",
"Xero Connector Public app #receiveBounce on return from Xero sends correct params to get access token",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber9",
"XeroConnector",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber20",
"XeroConnector #get",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber30",
"XeroConnector #get calls #request",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber164",
"XeroConnector #getUrl",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber165",
"XeroConnector #getUrl with private auth",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber200",
"XeroConnector #getUrl with private auth with partner auth",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber201",
"XeroConnector #getUrl with private auth with partner auth with runscope on",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber213",
"XeroConnector #getUrl with private auth with partner auth with runscope on should return standard url",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber217",
"XeroConnector #getUrl with private auth with partner auth without runscope",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber228",
"XeroConnector #getUrl with private auth with partner auth without runscope should return standard url",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber167",
"XeroConnector #getUrl with private auth with runscope on",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber179",
"XeroConnector #getUrl with private auth with runscope on should return runscope url",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber183",
"XeroConnector #getUrl with private auth with runscope on without runscope",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber195",
"XeroConnector #getUrl with private auth with runscope on without runscope should return standard url",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber53",
"XeroConnector #post",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber64",
"XeroConnector #post calls #request",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber36",
"XeroConnector #put",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber47",
"XeroConnector #put calls #request",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber70",
"XeroConnector #request",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber71",
"XeroConnector #request with GET",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber88",
"XeroConnector #request with GET calls underlying auth library",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber92",
"XeroConnector #request with GET returns json",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber132",
"XeroConnector #request with POST",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber150",
"XeroConnector #request with POST calls underlying auth library",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber154",
"XeroConnector #request with POST returns json",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber101",
"XeroConnector #request with PUT",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber119",
"XeroConnector #request with PUT calls underlying auth library",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber123",
"XeroConnector #request with PUT returns json",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber235",
"XeroConnector setup",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber236",
"XeroConnector setup generating defaults",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber237",
"XeroConnector setup generating defaults Private connector",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber246",
"XeroConnector setup generating defaults Private connector returns a public key",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber251",
"XeroConnector setup generating defaults Public connector",
"test"
],
[
"",
"test-file/tests/unit_tests/connector_tests.js.html#lineNumber260",
"XeroConnector setup generating defaults Public connector returns an empty object",
"test"
],
[
"",
"test-file/tests/integration_tests/partner_auth_tests.js.html#lineNumber88",
"get contacts",
"test"
],
[
"",
"test-file/tests/integration_tests/partner_auth_tests.js.html#lineNumber126",
"get contacts should",
"test"
],
[
"",
"test-file/tests/integration_tests/partner_auth_tests.js.html#lineNumber20",
"initial bounce",
"test"
],
[
"",
"test-file/tests/integration_tests/partner_auth_tests.js.html#lineNumber44",
"initial bounce should do some redirect",
"test"
],
[
"",
"test-file/tests/integration_tests/partner_auth_tests.js.html#lineNumber48",
"second bounce",
"test"
],
[
"",
"test-file/tests/integration_tests/partner_auth_tests.js.html#lineNumber84",
"second bounce should do some redirect",
"test"
],
[
"src/auth_config.js",
"file/src/auth_config.js.html",
"src/auth_config.js",
"file"
],
[
"src/connector.js",
"file/src/connector.js.html",
"src/connector.js",
"file"
],
[
"src/key_pair_generator.js",
"file/src/key_pair_generator.js.html",
"src/key_pair_generator.js",
"file"
],
[
"src/open_ssl.js",
"file/src/open_ssl.js.html",
"src/open_ssl.js",
"file"
],
[
"src/poll.js",
"file/src/poll.js.html",
"src/poll.js",
"file"
],
[
"src/views/edit.js",
"file/src/views/edit.js.html",
"src/views/edit.js",
"file"
],
[
"src/views/edit.js~editform#connect",
"class/src/views/edit.js~EditForm.html#instance-method-connect",
"src/views/edit.js~EditForm#connect",
"method"
],
[
"src/views/edit.js~editform#constructor",
"class/src/views/edit.js~EditForm.html#instance-constructor-constructor",
"src/views/edit.js~EditForm#constructor",
"method"
],
[
"src/views/edit.js~editform#render",
"class/src/views/edit.js~EditForm.html#instance-method-render",
"src/views/edit.js~EditForm#render",
"method"
],
[
"src/views/edit.js~editform#state",
"class/src/views/edit.js~EditForm.html#instance-member-state",
"src/views/edit.js~EditForm#state",
"member"
],
[
"tests/integration_tests/partner_auth_tests.js",
"test-file/tests/integration_tests/partner_auth_tests.js.html",
"tests/integration_tests/partner_auth_tests.js",
"testFile"
],
[
"tests/integration_tests/poll_tests.js",
"test-file/tests/integration_tests/poll_tests.js.html",
"tests/integration_tests/poll_tests.js",
"testFile"
],
[
"tests/unit_tests/bounce_tests.js",
"test-file/tests/unit_tests/bounce_tests.js.html",
"tests/unit_tests/bounce_tests.js",
"testFile"
],
[
"tests/unit_tests/connector_tests.js",
"test-file/tests/unit_tests/connector_tests.js.html",
"tests/unit_tests/connector_tests.js",
"testFile"
],
[
"tests/unit_tests/poll_tests.js",
"test-file/tests/unit_tests/poll_tests.js.html",
"tests/unit_tests/poll_tests.js",
"testFile"
]
]
|
import Renderer from './3d_viewer';
export default () => {
const viewer = new Renderer(document.getElementById('js-stl-viewer'));
[].slice.call(document.querySelectorAll('.js-material-changer')).forEach((el) => {
el.addEventListener('click', (e) => {
const { target } = e;
e.preventDefault();
document.querySelector('.js-material-changer.active').classList.remove('active');
target.classList.add('active');
target.blur();
viewer.changeObjectMaterials(target.dataset.type);
});
});
};
|
(function() {
"use strict";
//use this if you have under 400 markers, 1000 is pushing it, 10,000 becomes unresponsive
angular.module('chGoogleMap.models').directive("marker",['$timeout', 'chCoordiante', 'chMarker', function($timeout, chCoordiante, chMarker){
return {
restrict:'AE',
scope: {
position:'=',
icon:'=?',
options:'=?',
events:'=?',
},
require:'^map',
link: function($scope, element, attrs, mapController){
$scope.marker = chMarker.fromAttrs($scope).$googleMarker(mapController.getMap(), $scope, $scope.events);
element.on('$destroy', function(s) {
if($scope.marker.$label) $scope.marker.$label.set('map', null);
$scope.marker.setMap(null);
$scope.marker = null;
});
if($scope.$watchGroup) {
$scope.$watchGroup(["position", "icon"], function(newValue, oldValue){
$timeout(function(){
if(!$scope.marker) return;
if(angular.isDefined(newValue[0])){
var newCoord = chCoordiante.fromAttr(newValue[0]).$googleCoord();
$scope.marker.setPosition(newCoord);
}
$scope.marker.setIcon(newValue[1]);
});
});
} else {
$scope.$watch("icon", function(newValue, oldValue){
$timeout(function(){
if(!$scope.marker) return;
$scope.marker.setIcon(newValue);
});
});
$scope.$watch("position", function(newValue, oldValue){
$timeout(function(){
if(!$scope.marker) return;
if(angular.isDefined(newValue)){
var newCoord = chCoordiante.fromAttr(newValue).$googleCoord();
$scope.marker.setPosition(newCoord);
}
});
});
}
$scope.$watchCollection("options", function(newValue, oldValue){
if(angular.equals(newValue,oldValue)) return;
$timeout(function(){
$scope.marker.setOptions(newValue);
});
});
},
}
}])
})();
|
import { expect } from 'chai'
import { storage, setStorage, scheduler } from 'react-easy-params'
const STORAGE_NAME = 'REACT_EASY_STORAGE'
describe('storage synchronization', () => {
afterEach(async () => {
setStorage({})
await scheduler.processing()
})
it('should initialize from localStorage', () => {
expect(JSON.parse(localStorage.getItem(STORAGE_NAME))).to.eql({
initial: true
})
expect(storage).to.eql({ initial: true })
})
it('should sync the localStorage with the storage object', async () => {
storage.user = {
name: 'Bob',
age: 34
}
await scheduler.processing()
expect(storage.user).to.eql({
name: 'Bob',
age: 34
})
expect(JSON.parse(localStorage.getItem(STORAGE_NAME))).to.eql({
user: {
name: 'Bob',
age: 34
}
})
delete storage.user.name
await scheduler.processing()
expect(storage.user).to.eql({
age: 34
})
expect(JSON.parse(localStorage.getItem(STORAGE_NAME))).to.eql({
user: { age: 34 }
})
})
it('setStorage should shallow replace storage with the passed one', async () => {
storage.user = {
name: 'Bob',
age: 34
}
await scheduler.processing()
expect(storage.user).to.eql({
name: 'Bob',
age: 34
})
expect(JSON.parse(localStorage.getItem(STORAGE_NAME))).to.eql({
user: {
name: 'Bob',
age: 34
}
})
setStorage({ userLoaded: false })
await scheduler.processing()
expect(storage).to.eql({
userLoaded: false
})
expect(JSON.parse(localStorage.getItem(STORAGE_NAME))).to.eql({
userLoaded: false
})
})
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:7fa2310ab91313ebf25d03d0c4592d1f2bc45e1d378396b6764aeef56ce38d61
size 681
|
'use strict';
/*
*
* Reducer of IncomeStatsPage
*
*/
import * as IncomeStatsPageActionTypes from '../actiontypes/incomeStatsPage';
const initialState = {
year: '', // @TODO: remove hardcode
amountByCat: [],
amountByMember: [],
amountByDate: [],
amountByDateAndMember: [],
amountByCatAndMember: []
};
function incomeStatsReducer(state = initialState, action = {}) {
switch (action.type) {
case IncomeStatsPageActionTypes.SELECT_YEAR:
return {
...state,
year: action.year
};
break;
case IncomeStatsPageActionTypes.AMOUNT_BY_DATE_RECEIVED:
return {
...state,
amountByDate: action.amountByDate
};
break;
case IncomeStatsPageActionTypes.AMOUNT_BY_MEMBER_RECEIVED:
return {
...state,
amountByMember: action.amountByMember
};
break;
case IncomeStatsPageActionTypes.AMOUNT_BY_CAT_RECEIVED:
return {
...state,
amountByCat: action.amountByCat
};
break;
case IncomeStatsPageActionTypes.AMOUNT_BY_DATE_MEMBER_RECEIVED:
return {
...state,
amountByDateAndMember: action.amountByDateAndMember
};
break;
case IncomeStatsPageActionTypes.AMOUNT_BY_CAT_MEMBER_RECEIVED:
return {
...state,
amountByCatAndMember: action.amountByCatAndMember
};
break;
default:
return state;
}
}
export default incomeStatsReducer;
|
export default {
* index(next) {
return 'comments#index'
},
* create(next) {
let name = 'trek'
let age = 233
return { name, age }
},
* ['new'](next) {
this.body = 'comments#new'
},
* show(next) {
this.body = 'comments#show'
},
* update(next) {
this.body = 'comments#update'
},
* destroy(next) {
this.body = 'comments#destroy'
}
}
|
/*
* Globalize Culture pa-IN
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator * Portions (c) Corporate Web Solutions Ltd.
*/
(function( window, undefined ) {
var Globalize;
if ( typeof require !== "undefined" &&
typeof exports !== "undefined" &&
typeof module !== "undefined" ) {
// Assume CommonJS
Globalize = require( "globalize" );
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo( "pa-IN", "default", {
name: "pa-IN",
englishName: "Punjabi (India)",
nativeName: "ਪੰਜਾਬੀ (ਭਾਰਤ)",
language: "pa",
numberFormat: {
groupSizes: [3,2],
percent: {
groupSizes: [3,2]
},
currency: {
pattern: ["$ -n","$ n"],
groupSizes: [3,2],
symbol: "ਰੁ"
}
},
calendars: {
standard: {
"/": "-",
firstDay: 1,
days: {
names: ["ਐਤਵਾਰ","ਸੋਮਵਾਰ","ਮੰਗਲਵਾਰ","ਬੁੱਧਵਾਰ","ਵੀਰਵਾਰ","ਸ਼ੁੱਕਰਵਾਰ","ਸ਼ਨਿੱਚਰਵਾਰ"],
namesAbbr: ["ਐਤ.","ਸੋਮ.","ਮੰਗਲ.","ਬੁੱਧ.","ਵੀਰ.","ਸ਼ੁਕਰ.","ਸ਼ਨਿੱਚਰ."],
namesShort: ["ਐ","ਸ","ਮ","ਬ","ਵ","ਸ਼","ਸ਼"]
},
months: {
names: ["ਜਨਵਰੀ","ਫ਼ਰਵਰੀ","ਮਾਰਚ","ਅਪ੍ਰੈਲ","ਮਈ","ਜੂਨ","ਜੁਲਾਈ","ਅਗਸਤ","ਸਤੰਬਰ","ਅਕਤੂਬਰ","ਨਵੰਬਰ","ਦਸੰਬਰ",""],
namesAbbr: ["ਜਨਵਰੀ","ਫ਼ਰਵਰੀ","ਮਾਰਚ","ਅਪ੍ਰੈਲ","ਮਈ","ਜੂਨ","ਜੁਲਾਈ","ਅਗਸਤ","ਸਤੰਬਰ","ਅਕਤੂਬਰ","ਨਵੰਬਰ","ਦਸੰਬਰ",""]
},
AM: ["ਸਵੇਰ","ਸਵੇਰ","ਸਵੇਰ"],
PM: ["ਸ਼ਾਮ","ਸ਼ਾਮ","ਸ਼ਾਮ"],
patterns: {
d: "dd-MM-yy",
D: "dd MMMM yyyy dddd",
t: "tt hh:mm",
T: "tt hh:mm:ss",
f: "dd MMMM yyyy dddd tt hh:mm",
F: "dd MMMM yyyy dddd tt hh:mm:ss",
M: "dd MMMM"
}
}
}
});
}( this ));
|
import React from 'react';
import PropTypes from 'prop-types';
import { Button, FormGroup, FormControl, ControlLabel } from 'react-bootstrap';
import './Login.css';
export default function LoginForm(props) {
return (
<div className="Login">
<form onSubmit={props.handleSubmit}>
<FormGroup controlId="username" bsSize="large">
<ControlLabel>Username</ControlLabel>
<FormControl
autoFocus
type="text"
value={props.username}
onChange={props.handleChange}
disabled={props.disabledInput}
/>
</FormGroup>
<FormGroup controlId="password" bsSize="large">
<ControlLabel>Password</ControlLabel>
<FormControl
value={props.password}
onChange={props.handleChange}
disabled={props.disabledInput}
type="password"
/>
</FormGroup>
<Button
block
bsSize="large"
disabled={!props.validateForm()}
type="submit"
>
{props.buttonText}
</Button>
<Button
block
bsSize="large"
onClick={() => props.toRegisterUser()}
>
Create Account
</Button>
</form>
</div>
);
}
LoginForm.propTypes = {
username: PropTypes.string.isRequired,
password: PropTypes.string.isRequired,
buttonText: PropTypes.string.isRequired,
handleSubmit: PropTypes.func.isRequired,
handleChange: PropTypes.func.isRequired,
validateForm: PropTypes.func.isRequired,
toRegisterUser: PropTypes.func.isRequired,
disabledInput: PropTypes.bool.isRequired
};
|
// !LOCNS:galactic_war
define(['shared/gw_common'], function (GW) {
return {
visible: function(params) { return true; },
describe: function(params) {
return '!LOC:Orbital Combat Tech increases speed of all orbital units by 50%, health by 50%, and damage by 25%';
},
summarize: function(params) {
return '!LOC:Orbital Combat Tech';
},
icon: function(params) {
return 'coui://ui/main/game/galactic_war/gw_play/img/tech/gwc_orbital.png';
},
audio: function (parms) {
return {
found: 'PA/VO/Computer/gw/board_tech_available_combat'
}
},
getContext: function (galaxy) {
return {
totalSize: galaxy.stars().length
};
},
deal: function (system, context, inventory) {
var chance = 0;
var dist = system.distance();
if (dist > 0) {
if (context.totalSize <= GW.balance.numberOfSystems[0]) {
chance = 28;
if (dist > 4)
chance = 142;
}
else if (context.totalSize <= GW.balance.numberOfSystems[1]) {
chance = 25;
if (dist > 6)
chance = 75;
}
else if (context.totalSize <= GW.balance.numberOfSystems[2]) {
chance = 28;
if (dist > 9)
chance = 142;
}
else if (context.totalSize <= GW.balance.numberOfSystems[3]) {
chance = 28;
if (dist > 11)
chance = 142;
}
else {
chance = 28;
if (dist > 13)
chance = 142;
}
}
return { chance: chance };
},
buff: function(inventory, params) {
var units = [
'/pa/units/orbital/orbital_fighter/orbital_fighter.json',
'/pa/units/orbital/orbital_lander/orbital_lander.json',
'/pa/units/orbital/radar_satellite/radar_satellite.json',
'/pa/units/orbital/solar_array/solar_array.json',
'/pa/units/orbital/defense_satellite/defense_satellite.json',
'/pa/units/orbital/orbital_laser/orbital_laser.json',
'/pa/units/orbital/radar_satellite_adv/radar_satellite_adv.json',
'/pa/units/orbital/orbital_factory/orbital_factory.json',
'/pa/units/orbital/orbital_fabrication_bot/orbital_fabrication_bot.json',
'/pa/units/orbital/mining_platform/mining_platform.json',
'/pa/units/orbital/orbital_probe/orbital_probe.json',
'/pa/units/orbital/orbital_railgun/orbital_railgun.json',
'/pa/units/orbital/orbital_battleship/orbital_battleship.json'
];
var mods = [];
var modUnit = function (unit) {
mods.push({
file: unit,
path: 'navigation.move_speed',
op: 'multiply',
value: 1.5
});
mods.push({
file: unit,
path: 'navigation.brake',
op: 'multiply',
value: 1.5
});
mods.push({
file: unit,
path: 'navigation.acceleration',
op: 'multiply',
value: 1.5
});
mods.push({
file: unit,
path: 'navigation.turn_speed',
op: 'multiply',
value: 1.5
});
mods.push({
file: unit,
path: 'max_health',
op: 'multiply',
value: 1.5
});
};
_.forEach(units, modUnit);
var ammos = [
'/pa/units/orbital/orbital_fighter/orbital_fighter_ammo.json',
'/pa/units/orbital/defense_satellite/defense_satellite_ammo_ground.json',
'/pa/units/orbital/orbital_laser/orbital_laser_ammo.json',
'/pa/units/orbital/orbital_railgun/orbital_railgun_ammo.json',
'/pa/units/orbital/defense_satellite/defense_satellite_ammo_orbital.json',
'/pa/units/orbital/orbital_battleship/orbital_battleship_ammo_ground.json'
];
var modAmmo = function (ammo) {
mods.push({
file: ammo,
path: 'damage',
op: 'multiply',
value: 1.25
});
};
_.forEach(ammos, modAmmo);
inventory.addMods(mods);
},
dull: function(inventory) {
}
};
});
|
(function() {
var SCOPE_OPENERS,
__indexOf = Array.prototype.indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
SCOPE_OPENERS = ['FOR', 'WHILE', 'UNTIL', 'LOOP', 'IF', 'POST_IF', 'SWITCH', 'WHEN', 'CLASS', 'TRY', 'CATCH', 'FINALLY'];
self.JSREPLEngine = (function() {
function JSREPLEngine(input, output, result, error, sandbox, ready) {
this.result = result;
this.error = error;
this.sandbox = sandbox;
this.inspect = this.sandbox.console.inspect;
this.CoffeeScript = this.sandbox.CoffeeScript;
this.sandbox.__eval = this.sandbox.eval;
ready();
}
JSREPLEngine.prototype.Eval = function(command) {
var compiled, result;
try {
compiled = this.CoffeeScript.compile(command, {
globals: true,
bare: true
});
result = this.sandbox.__eval(compiled);
return this.result(result === void 0 ? '' : this.inspect(result));
} catch (e) {
return this.error(e);
}
};
JSREPLEngine.prototype.RawEval = function(command) {
var compiled, result;
try {
compiled = this.CoffeeScript.compile(command, {
globals: true,
bare: true
});
result = this.sandbox.__eval(compiled);
return this.result(result);
} catch (e) {
return this.error(e);
}
};
JSREPLEngine.prototype.GetNextLineIndent = function(command) {
var all_tokens, index, last_line, last_line_tokens, next, scopes, token, _i, _len, _len2, _ref;
last_line = command.split('\n').slice(-1)[0];
if (/([-=]>|[\[\{\(]|\belse)$/.test(last_line)) {
return 1;
} else {
try {
all_tokens = this.CoffeeScript.tokens(command);
last_line_tokens = this.CoffeeScript.tokens(last_line);
} catch (e) {
return 0;
}
try {
this.CoffeeScript.compile(command);
if (/^\s+/.test(last_line)) {
return 0;
} else {
for (index = 0, _len = all_tokens.length; index < _len; index++) {
token = all_tokens[index];
next = all_tokens[index + 1];
if (token[0] === 'REGEX' && token[1] === '/(?:)/' && next[0] === 'MATH' && next[1] === '/') {
return 0;
}
}
return false;
}
} catch (e) {
scopes = 0;
for (_i = 0, _len2 = last_line_tokens.length; _i < _len2; _i++) {
token = last_line_tokens[_i];
if (_ref = token[0], __indexOf.call(SCOPE_OPENERS, _ref) >= 0) {
scopes++;
} else if (token.fromThen) {
scopes--;
}
}
if (scopes > 0) {
return 1;
} else {
return 0;
}
}
}
};
return JSREPLEngine;
})();
}).call(this);
|
function CTextButton(iXPos,iYPos,oSprite,szText,szFont,szColor,iFontSize,bAttach){
var _aCbCompleted;
var _aCbOwner;
var _oButton;
this._init =function(iXPos,iYPos,oSprite,szText,szFont,szColor,iFontSize,bAttach){
_aCbCompleted=new Array();
_aCbOwner =new Array();
var oButtonBg = new createjs.Bitmap( oSprite);
var iStepShadow = Math.ceil(iFontSize/30);
var oTextBack = new createjs.Text(szText,iFontSize+"px "+szFont, "#000000");
oTextBack.textAlign = "center";
oTextBack.textBaseline = "middle";
oTextBack.lineHeight = 1;
var oBounds = oTextBack.getBounds();
oTextBack.x = oSprite.width/2 + iStepShadow;
oTextBack.y = Math.floor((oSprite.height)/2) +(oBounds.height/3) + iStepShadow;
var oText = new createjs.Text(szText,iFontSize+"px "+szFont, szColor);
oText.textAlign = "center";
oText.textBaseline = "middle";
oText.lineHeight = 1;
var oBounds = oText.getBounds();
oText.x = oSprite.width/2;
oText.y = Math.floor((oSprite.height)/2) +(oBounds.height/3);
_oButton = new createjs.Container();
_oButton.x = iXPos;
_oButton.y = iYPos;
_oButton.regX = oSprite.width/2;
_oButton.regY = oSprite.height/2;
_oButton.addChild(oButtonBg,oTextBack,oText);
if(bAttach !== false){
s_oStage.addChild(_oButton);
}
this._initListener();
};
this.unload = function(){
_oButton.off("mousedown");
_oButton.off("pressup");
s_oStage.removeChild(_oButton);
};
this.setVisible = function(bVisible){
_oButton.visible = bVisible;
};
this._initListener = function(){
oParent = this;
_oButton.on("mousedown", this.buttonDown);
_oButton.on("pressup" , this.buttonRelease);
};
this.addEventListener = function( iEvent,cbCompleted, cbOwner ){
_aCbCompleted[iEvent]=cbCompleted;
_aCbOwner[iEvent] = cbOwner;
};
this.buttonRelease = function(){
if(DISABLE_SOUND_MOBILE === false || s_bMobile === false){
createjs.Sound.play("click");
}
_oButton.scaleX = 1;
_oButton.scaleY = 1;
if(_aCbCompleted[ON_MOUSE_UP]){
_aCbCompleted[ON_MOUSE_UP].call(_aCbOwner[ON_MOUSE_UP]);
}
};
this.buttonDown = function(){
_oButton.scaleX = 0.9;
_oButton.scaleY = 0.9;
if(_aCbCompleted[ON_MOUSE_DOWN]){
_aCbCompleted[ON_MOUSE_DOWN].call(_aCbOwner[ON_MOUSE_DOWN]);
}
};
this.setPosition = function(iXPos,iYPos){
_oButton.x = iXPos;
_oButton.y = iYPos;
};
this.setX = function(iXPos){
_oButton.x = iXPos;
};
this.setY = function(iYPos){
_oButton.y = iYPos;
};
this.getButtonImage = function(){
return _oButton;
};
this.getX = function(){
return _oButton.x;
};
this.getY = function(){
return _oButton.y;
};
this.getSprite = function(){
return _oButton;
};
this._init(iXPos,iYPos,oSprite,szText,szFont,szColor,iFontSize,bAttach);
return this;
}
|
/*global require, module*/
var Promise = require('bluebird'),
aws = require('aws-sdk'),
find = require('../util/find');
module.exports = function allowApiInvocation(functionName, functionVersion, restApiId, ownerId, awsRegion, path) {
'use strict';
var lambda = Promise.promisifyAll(new aws.Lambda({region: awsRegion}), {suffix: 'Promise'}),
activePath = path || '*/*/*',
policy = {
Action: 'lambda:InvokeFunction',
FunctionName: functionName,
Principal: 'apigateway.amazonaws.com',
SourceArn: 'arn:aws:execute-api:' + awsRegion + ':' + ownerId + ':' + restApiId + '/' + activePath,
Qualifier: functionVersion,
StatementId: 'web-api-access-' + functionVersion + '-' + Date.now()
},
matchesPolicy = function (statement) {
return statement.Action === policy.Action &&
statement.Principal && statement.Principal.Service === policy.Principal &&
statement.Condition && statement.Condition.ArnLike &&
statement.Condition.ArnLike['AWS:SourceArn'] === policy.SourceArn &&
statement.Effect === 'Allow';
};
return lambda.getPolicyPromise({
FunctionName: functionName,
Qualifier: functionVersion
}).then(function (policyResponse) {
return policyResponse && policyResponse.Policy && JSON.parse(policyResponse.Policy);
}).then(function (currentPolicy) {
var statements = (currentPolicy && currentPolicy.Statement) || [];
if (!find(statements, matchesPolicy)) {
return lambda.addPermissionPromise(policy);
}
}, function (e) {
if (e && e.code === 'ResourceNotFoundException') {
return lambda.addPermissionPromise(policy);
} else {
return Promise.reject(e);
}
});
};
|
// Mix all threejs plugins here, provide a unified interface
define( ["threejs"], function( threeCore ) {
return threeCore;
} );
|
'use strict';
var fsAutocomplete = require('vorpal-autocomplete-fs');
var delimiter = require('./../delimiter');
var interfacer = require('./../util/interfacer');
var preparser = require('./../preparser');
var cd = {
exec: function exec(dir, options) {
var self = this;
var vpl = options.vorpal;
options = options || {};
dir = !dir ? delimiter.getHomeDir() : dir;
// Allow Windows drive letter changes
dir = dir && dir.length === 2 && dir[1] === '/' ? dir[0] + ':' : dir;
try {
process.chdir(dir);
if (vpl) {
delimiter.refresh(vpl);
}
return 0;
} catch (e) {
return cd.error.call(self, e, dir);
}
},
error: function error(e, dir) {
var status = void 0;
var stdout = void 0;
if (e.code === 'ENOENT' && e.syscall === 'uv_chdir') {
status = 1;
stdout = '-bash: cd: ' + dir + ': No such file or directory';
} else {
status = 2;
stdout = e.stack;
}
this.log(stdout);
return status;
}
};
module.exports = function (vorpal) {
if (vorpal === undefined) {
return cd;
}
vorpal.api.cd = cd;
vorpal.command('cd [dir]').parse(preparser).autocomplete(fsAutocomplete({ directory: true })).action(function (args, callback) {
args.options = args.options || {};
args.options.vorpal = vorpal;
return interfacer.call(this, {
command: cd,
args: args.dir,
options: args.options,
callback: callback
});
});
};
|
const express = require("express");
const app = express();
const server = require("http").Server(app);
const path = require("path");
const bodyParser = require("body-parser");
const swig = require("swig");
const React = require("react");
const ReactDOM = require("react-dom/server");
const Router = require("react-router");
const RoutingContext = Router.RoutingContext;
const routes = require("./app/routes");
const moment = require("moment");
const cache = require("apicache").middleware;
const mysql = require("mysql");
const fs = require("fs");
// open mysql connection pool
var pool = mysql.createPool({
host: "mysql",
user: "root",
port: 3306,
password: "npm2017",
database: "npm-trending",
connectionLimit: 100
});
// read queries
var trendingQuery = fs.readFileSync("./queries/trending.sql", "utf8");
var historyQuery = fs.readFileSync("./queries/history.sql", "utf8");
// config express
app.set("port", process.env.PORT || 3000);
app.use(
bodyParser.json({
limit: "20mb"
})
);
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(express.static(path.join(__dirname, "public")));
// TRENDS
app.get("/trends", cache("5 minutes"), (req, res) => {
// get mysql connection
pool.getConnection((err, conn) => {
// query for trends
conn.query(trendingQuery, (error, results, fields) => {
return res.send(results);
});
});
});
// TRENDS / :ID / DAYS / :DAYS
app.get("/trends/:id/days/:days", cache("1 hour"), (req, res) => {
// get mysql connection
pool.getConnection((err, conn) => {
// query for history of a package
conn.query(
historyQuery,
[parseInt(req.params.id), parseInt(req.params.days) * -1],
(error, results, fields) => {
// return the package id and download values
return res.send({
id: req.params.id,
values: results.map(d => {
return d.downloads;
})
});
}
);
});
});
// REACT.JS
app.use((req, res) => {
Router.match(
{ routes: routes, location: req.url },
(err, redirectLocation, renderProps) => {
// error
if (err) {
return res.status(500).send(err.message);
} else if (redirectLocation) {
// redirect
return res
.status(302)
.redirect(
redirectLocation.pathname + redirectLocation.search
);
} else if (renderProps) {
// render
var html = ReactDOM.renderToString(
<RoutingContext {...renderProps} />
);
var page = swig.renderFile("views/index.html", { html: html });
return res.status(200).send(page);
} else {
// not found
return res.status(404).send("Page Not Found");
}
}
);
});
// EXPRESS.JS
server.listen(app.get("port"), () => {
console.log("NPM Trending server listening on port " + app.get("port"));
});
|
angular.module("lcars").directive("lcarsIndicator", function() {
return {
"templateUrl": "templates/indication.html",
"controller" : "indication",
"scope": {
}
};
});
|
module.exports = require('yeoman-generator').Base.extend({
do: require('../generate')({
category: 'components',
templateFileName: '_component.js'
})
})
|
import {Text, View, TouchableOpacity, TouchableHighlight, ListView, Image, StyleSheet, Dimensions} from 'react-native';
import React, {Component} from 'react';
import Icon from 'react-native-vector-icons/Ionicons';
import Detail from '../creation/Detail';
export default class Questions extends Component {
constructor(props) {
super(props);
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows([
{
time: '2016-11-11 11:11:11',
content: '不包邮'
},
{
time: '2016-12-12 12:12:12',
content: '不议价'
}
])
};
}
render() {
return (
<View style={styles.container}>
<View style={[styles.header, styles.border_bottom]}>
<TouchableOpacity style={styles.header_back_box} onPress={this._goBack.bind(this)}>
<Icon style={styles.back_icon} name="ios-arrow-back"/>
<Text style={styles.back_text}>返回</Text>
</TouchableOpacity>
<Text style={styles.header_title}>留言详情</Text>
</View>
<View style={styles.body}>
<View style={[styles.info, styles.border_bottom]}>
<View style={styles.info_messager}>
<View style={styles.info_messager_avatar}></View>
<View style={styles.info_messager_desc}>
<Text style={styles.info_messager_nickname}>奥特曼</Text>
<Text style={styles.info_messager_time}>2016-11-11 11:11:11</Text>
</View>
</View>
<TouchableHighlight underlayColor="#fff" onPress={this._gotoView.bind(this, 'detail')}>
<View style={styles.info_info}>
<Image style={styles.info_image} source={require('../../assets/images/creation/list_item.jpg')}/>
<Text style={styles.info_desc} numberOfLines={3}>
苹果MacBook Pro 13.3英寸笔记本电脑 深空灰色(Core i5处理器/256G SSD闪存)
</Text>
</View>
</TouchableHighlight>
</View>
<View style={[styles.question, styles.backgound_white, styles.border_bottom, styles.padding_left_and_right]}>
<Text style={styles.quesion_text}>问: 是否包邮?</Text>
</View>
<View style={[styles.question, styles.margin_top, styles.backgound_white, styles.border_top,
styles.border_bottom, styles.padding_left_and_right]}>
<Text style={styles.quesion_text}>答: 共两条回复</Text>
</View>
<View style={styles.border_bottom}>
<ListView dataSource={this.state.dataSource} enableEmptySections={true}
automaticallyAdjustContentInsets={false} showsVerticalScrollIndicator={false}
renderRow={(rowData) => this._renderItem(rowData)}
/>
</View>
</View>
</View>
);
}
_renderItem(rowData) {
return (
<View style={[styles.item, styles.backgound_white]}>
<View style={[styles.item_container]}>
<Text style={styles.item_time}>{rowData.time}</Text>
<Text style={styles.item_content}>{rowData.content}</Text>
</View>
</View>
);
}
_goBack() {
const {navigator} = this.props;
if (navigator) {
navigator.pop();
}
}
_gotoView() {
}
}
const width = Dimensions.get('window').width;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff'
},
border_top: {
borderTopWidth: 1,
borderTopColor: '#000'
},
border_bottom: {
borderBottomWidth: 1,
borderBottomColor: '#000'
},
margin_top: {
marginTop: 10
},
backgound_white: {
backgroundColor: '#fff'
},
header: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
width: width,
height: 64,
paddingTop: 20,
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#fff'
},
header_back_box: {
position: 'absolute',
left: 12,
top: 32,
width: 50,
flexDirection: 'row',
alignItems: 'center'
},
header_title: {
width: width - 120,
textAlign: 'center',
fontSize: 16
},
back_icon: {
color: '#999',
fontSize: 20,
marginRight: 5
},
back_text: {
color: '#999',
fontSize: 16,
},
body: {
flex: 1,
backgroundColor: '#ddd'
},
info: {
padding: 10,
backgroundColor: '#fff'
},
info_messager: {
flexDirection: 'row'
},
info_messager_avatar: {
width: 40,
height: 40,
backgroundColor: '#ee735c',
borderRadius: 20
},
info_messager_desc: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginLeft: 10
},
info_messager_nickname: {
fontSize: 15,
fontWeight: '600'
},
info_messager_time: {
fontSize: 15,
color: '#666'
},
info_info: {
marginTop: 10,
flexDirection: 'row',
alignItems: 'center'
},
info_image: {
width: 150,
height: 73
},
info_desc: {
fontSize: 16,
flex: 1,
fontWeight: '400'
},
question: {
padding: 10,
justifyContent: 'center'
},
quesion_text: {
fontSize: 18
},
item: {
padding: 10
},
item_container: {
borderBottomWidth: 1,
borderBottomColor: '#ddd',
paddingBottom: 10
},
item_time: {
fontSize: 15,
color: '#666'
},
item_content: {
fontSize: 18,
marginTop: 10
}
});
|
// flow-typed signature: 2b2b61dd4598299ed3177dba0b9b1b1d
// flow-typed version: <<STUB>>/redux-thunk_v2.1.0/flow_v0.38.0
/**
* This is an autogenerated libdef stub for:
*
* 'redux-thunk'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'redux-thunk' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'redux-thunk/dist/redux-thunk' {
declare module.exports: any;
}
declare module 'redux-thunk/dist/redux-thunk.min' {
declare module.exports: any;
}
declare module 'redux-thunk/es/index' {
declare module.exports: any;
}
declare module 'redux-thunk/lib/index' {
declare module.exports: any;
}
declare module 'redux-thunk/src/index' {
declare module.exports: any;
}
// Filename aliases
declare module 'redux-thunk/dist/redux-thunk.js' {
declare module.exports: $Exports<'redux-thunk/dist/redux-thunk'>;
}
declare module 'redux-thunk/dist/redux-thunk.min.js' {
declare module.exports: $Exports<'redux-thunk/dist/redux-thunk.min'>;
}
declare module 'redux-thunk/es/index.js' {
declare module.exports: $Exports<'redux-thunk/es/index'>;
}
declare module 'redux-thunk/lib/index.js' {
declare module.exports: $Exports<'redux-thunk/lib/index'>;
}
declare module 'redux-thunk/src/index.js' {
declare module.exports: $Exports<'redux-thunk/src/index'>;
}
|
//Workflow to simulate the taking of a pizza order
var workflowDefinition = {
Name: "ProcessOrder",
Parameters: [
{ name: "deliveryType", displayName: "Delivery Type", parameterType:"Select", options: [{ name: "Delivery" }, {name:"Takeout"}] },
{ name: "name", displayName: "Customer Name", parameterType:"Input" },
{ name: "address", displayName: "Customer Address", parameterType:"Input" },
{ name: "city", displayName: "City", parameterType:"Input" },
{ name: "phone", displayName: "Phone", parameterType:"Input" },
{ name: "order", displayName: "Pizza Order", parameterType:"Input" }
],
Steps: [
{ Name: "Step0",
Type: "Init",
args:
{ status: "Ordered", currentStepName: "OrderReceived", deliveryType: "Delivery" }
},
{ Name: "OrderReceived",
Type: "writeConsoleActivity",
args:
{ text: "Workflow has been started" },
nextStep: "EnterIntoComputer"
},
{ Name: "EnterIntoComputer",
Type: "writeConsoleActivity",
args:
{ text: "Workflow has been started2" },
nextStep: "SendToCook"
},
{ Name: "SendToCook",
Type: "createChildWorkflow",
args:
{ workflowDefinition: "PizzaOrdering/cookWorkflow" },
nextStep: "WaitForCooking"
},
{ Name: "WaitForCooking",
Type: "waitForActivity",
args:
{ Condition: "workflow.status=='Cooked'" },
nextStep: "CookingComplete"
},
{ Name: "CookingComplete",
Type: "ifElseActivity",
args:
{ text: "ifElse activity Step",
branches: [
{ Condition: "workflow.deliveryType=='Delivery'", Step: "SendForDelivery" },
{ Condition: "workflow.deliveryType=='Takeout'", Step: "WaitForCustomer" },
{ Condition: null, Step: "WaitForCustomer"} //Default
]
},
nextStep: null
},
{ Name: "SendForDelivery",
Type: "createChildWorkflow",
args:
{ workflowDefinition: "PizzaOrdering/deliveryWorkflow" },
nextStep: "WaitForDelivery"
},
{ Name: "WaitForDelivery",
Type: "waitForActivity",
args:
{ Condition: "workflow.status=='Delivered'" },
nextStep: "WaitForCustomer"
},
{ Name: "WaitForCustomer",
Type: "writeConsoleActivity",
args:
{ text: "Waiting for Customer Pickup" },
nextStep: "Complete"
},
{ Name: "Complete",
Type: "completeWorkflow",
args:
{},
nextStep: null
}
]
}
exports.workflowDefinition = workflowDefinition;
|
import insertImage from './insertImage'
export default {
type: 'drop-asset',
match(params) {
// Mime-type starts with 'image/'
let isImage = params.file.type.indexOf('image/') === 0
return params.type === 'file' && isImage
},
drop(tx, params) {
insertImage(tx, params.file)
}
}
|
export default {
default: {},
};
|
var classRespuestaDelChat =
[
[ "RespuestaDelChat", "classRespuestaDelChat.html#abb7c0f529be82c2396ff54ebb2289d1a", null ],
[ "~RespuestaDelChat", "classRespuestaDelChat.html#a7f33fe070472b44067617e554dbad28a", null ],
[ "setRespuestaGCM", "classRespuestaDelChat.html#a53a20f3049b1a7fa51a9a19500184810", null ]
];
|
'use strict';
module.exports = {
db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/foodie',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.min.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
],
js: [
'public/lib/angular/angular.min.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-ui-router/release/angular-ui-router.min.js',
'public/lib/angular-ui-utils/ui-utils.min.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js'
]
},
css: 'public/dist/application.min.css',
js: 'public/dist/application.min.js'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: '/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: '/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
/**
* @license Handlebars hbs 0.8.1 - Alex Sexton, but Handlebars has its own licensing junk
*
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/require-cs for details on the plugin this was based off of
*/
/* Yes, deliciously evil. */
/*jslint evil: true, strict: false, plusplus: false, regexp: false */
/*global require: false, XMLHttpRequest: false, ActiveXObject: false,
define: false, process: false, window: false */
define([
//>>excludeStart('excludeHbs', pragmas.excludeHbs)
'hbs/handlebars', 'hbs/underscore', 'hbs/i18nprecompile', 'hbs/json2'
//>>excludeEnd('excludeHbs')
], function (
//>>excludeStart('excludeHbs', pragmas.excludeHbs)
Handlebars, _, precompile, JSON
//>>excludeEnd('excludeHbs')
) {
//>>excludeStart('excludeHbs', pragmas.excludeHbs)
var fs;
var getXhr;
var progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
var fetchText = function () {
throw new Error('Environment unsupported.');
};
var buildMap = [];
var filecode = 'w+';
var templateExtension = 'hbs';
var customNameExtension = '@hbs';
var devStyleDirectory = '/styles/';
var buildStyleDirectory = '/demo-build/styles/';
var helperDirectory = 'templates/helpers/';
var i18nDirectory = 'templates/i18n/';
var buildCSSFileName = 'screen.build.css';
var onHbsReadMethod = "onHbsRead";
Handlebars.registerHelper('$', function() {
//placeholder for translation helper
});
if (typeof window !== 'undefined' && window.navigator && window.document && !window.navigator.userAgent.match(/Node.js/)) {
// Browser action
getXhr = function () {
// Would love to dump the ActiveX crap in here. Need IE 6 to die first.
var xhr;
var i;
var progId;
if (typeof XMLHttpRequest !== 'undefined') {
return ((arguments[0] === true)) ? new XDomainRequest() : new XMLHttpRequest();
}
else {
for (i = 0; i < 3; i++) {
progId = progIds[i];
try {
xhr = new ActiveXObject(progId);
}
catch (e) {}
if (xhr) {
// Faster next time
progIds = [progId];
break;
}
}
}
if (!xhr) {
throw new Error('getXhr(): XMLHttpRequest not available');
}
return xhr;
};
// Returns the version of Windows Internet Explorer or a -1
// (indicating the use of another browser).
// Note: this is only for development mode. Does not run in production.
getIEVersion = function(){
// Return value assumes failure.
var rv = -1;
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp('MSIE ([0-9]{1,}[\.0-9]{0,})');
if (re.exec(ua) != null) {
rv = parseFloat( RegExp.$1 );
}
}
return rv;
};
fetchText = function (url, callback) {
var xdm = false;
// If url is a fully qualified URL, it might be a cross domain request. Check for that.
// IF url is a relative url, it cannot be cross domain.
if (url.indexOf('http') != 0 ){
xdm = false;
}else{
var uidx = (url.substr(0,5) === 'https') ? 8 : 7;
var hidx = (window.location.href.substr(0,5) === 'https') ? 8 : 7;
var dom = url.substr(uidx).split('/').shift();
var msie = getIEVersion();
xdm = ( dom != window.location.href.substr(hidx).split('/').shift() ) && (msie >= 7);
}
if ( xdm ) {
var xdr = getXhr(true);
xdr.open('GET', url);
xdr.onload = function() {
callback(xdr.responseText, url);
};
xdr.onprogress = function(){};
xdr.ontimeout = function(){};
xdr.onerror = function(){};
setTimeout(function(){
xdr.send();
}, 0);
}
else {
var xhr = getXhr();
xhr.open('GET', url, true);
xhr.onreadystatechange = function (evt) {
//Do not explicitly handle errors, those should be
//visible via console output in the browser.
if (xhr.readyState === 4) {
callback(xhr.responseText, url);
}
};
xhr.send(null);
}
};
}
else if (
typeof process !== 'undefined' &&
process.versions &&
!!process.versions.node
) {
//Using special require.nodeRequire, something added by r.js.
fs = require.nodeRequire('fs');
fetchText = function ( path, callback ) {
var body = fs.readFileSync(path, 'utf8') || '';
// we need to remove BOM stuff from the file content
body = body.replace(/^\uFEFF/, '');
callback(body, path);
};
}
else if (typeof java !== 'undefined' && typeof java.io !== 'undefined') {
fetchText = function(path, callback) {
var fis = new java.io.FileInputStream(path);
var streamReader = new java.io.InputStreamReader(fis, "UTF-8");
var reader = new java.io.BufferedReader(streamReader);
var line;
var text = '';
while ((line = reader.readLine()) !== null) {
text += new String(line) + '\n';
}
reader.close();
callback(text, path);
};
}
var cache = {};
var fetchOrGetCached = function ( path, callback ){
if ( cache[path] ){
callback(cache[path]);
}
else {
fetchText(path, function(data, path){
cache[path] = data;
callback.call(this, data);
});
}
};
var styleList = [];
var styleMap = {};
//>>excludeEnd('excludeHbs')
return {
get: function () {
return Handlebars;
},
write: function (pluginName, name, write) {
if ( (name + customNameExtension ) in buildMap) {
var text = buildMap[name + customNameExtension];
write.asModule(pluginName + '!' + name, text);
}
},
version: '0.8.1',
load: function (name, parentRequire, load, config) {
//>>excludeStart('excludeHbs', pragmas.excludeHbs)
var compiledName = name + customNameExtension;
config.hbs = config.hbs || {};
var disableI18n = !(config.hbs.i18n == true); // by default we disable i18n unless config.hbs.i18n is true
var disableHelpers = (config.hbs.helpers == false); // be default we enable helpers unless config.hbs.helpers is false
var partialsUrl = '';
if(config.hbs.partialsUrl) {
partialsUrl = config.hbs.partialsUrl;
if(!partialsUrl.match(/\/$/)) partialsUrl += '/';
}
// Let redefine default fetchText
if(config.hbs.fetchText) {
fetchText = config.hbs.fetchText;
}
var partialDeps = [];
function recursiveNodeSearch( statements, res ) {
_(statements).forEach(function ( statement ) {
if ( statement && statement.type && statement.type === 'partial' ) {
res.push(statement.partialName.name);
}
if ( statement && statement.program && statement.program.statements ) {
recursiveNodeSearch( statement.program.statements, res );
}
if ( statement && statement.program && statement.program.inverse && statement.program.inverse.statements ) {
recursiveNodeSearch( statement.program.inverse.statements, res );
}
});
return res;
}
// TODO :: use the parser to do this!
function findPartialDeps( nodes ) {
var res = [];
if ( nodes && nodes.statements ) {
res = recursiveNodeSearch( nodes.statements, [] );
}
return _.unique(res);
}
// See if the first item is a comment that's json
function getMetaData( nodes ) {
var statement, res, test;
if ( nodes && nodes.statements ) {
statement = nodes.statements[0];
if ( statement && statement.type === 'comment' ) {
try {
res = ( statement.comment ).replace(new RegExp('^[\\s]+|[\\s]+$', 'g'), '');
test = JSON.parse(res);
return res;
}
catch (e) {
return JSON.stringify({
description: res
});
}
}
}
return '{}';
}
function composeParts ( parts ) {
if ( !parts ) {
return [];
}
var res = [parts[0]];
var cur = parts[0];
var i;
for (i = 1; i < parts.length; ++i) {
if ( parts.hasOwnProperty(i) ) {
cur += '.' + parts[i];
res.push( cur );
}
}
return res;
}
function recursiveVarSearch( statements, res, prefix, helpersres ) {
prefix = prefix ? prefix + '.' : '';
var newprefix = '';
var flag = false;
// loop through each statement
_(statements).forEach(function(statement) {
var parts;
var part;
var sideways;
// if it's a mustache block
if ( statement && statement.type && statement.type === 'mustache' ) {
// If it has params, the first part is a helper or something
if ( !statement.params || ! statement.params.length ) {
parts = composeParts( statement.id.parts );
for( part in parts ) {
if ( parts[ part ] ) {
newprefix = parts[ part ] || newprefix;
res.push( prefix + parts[ part ] );
}
}
res.push(prefix + statement.id.string);
}
var paramsWithoutParts = ['this', '.', '..', './..', '../..', '../../..'];
// grab the params
if ( statement.params && typeof Handlebars.helpers[statement.id.string] === 'undefined') {
_(statement.params).forEach(function(param) {
if ( _(paramsWithoutParts).contains(param.original)
|| param instanceof Handlebars.AST.StringNode
|| param instanceof Handlebars.AST.IntegerNode
|| param instanceof Handlebars.AST.BooleanNode
|| param instanceof Handlebars.AST.DataNode
|| param instanceof Handlebars.AST.SexprNode
) {
helpersres.push(statement.id.string);
// Look into the params to find subexpressions
if (typeof statement.params !== 'undefined') {
_(statement.params).forEach(function(param) {
if (param.type === 'sexpr' && param.isHelper === true) {
// Found subexpression in params
helpersres.push(param.id.string);
}
});
}
// Look in the hash to find sub expressions
if (typeof statement.hash !== 'undefined' && typeof statement.hash.pairs !== 'undefined') {
_(statement.hash.pairs).forEach(function(pair) {
var pairName = pair[0],
pairValue = pair[1];
if (pairValue.type === 'sexpr' && pairValue.isHelper === true) {
// Found subexpression in hash params
helpersres.push(pairValue.id.string);
}
});
}
}
parts = composeParts( param.parts );
for(var part in parts ) {
if ( parts[ part ] ) {
newprefix = parts[part] || newprefix;
helpersres.push(statement.id.string);
res.push( prefix + parts[ part ] );
}
}
});
if (typeof statement.hash !== 'undefined' && typeof statement.hash.pairs !== 'undefined') {
//Even if it has no regular params, it may be a helper with hash params
_(statement.hash.pairs).forEach(function(pair) {
var pairValue = pair[1];
if (pairValue instanceof Handlebars.AST.StringNode
|| pairValue instanceof Handlebars.AST.IntegerNode
|| pairValue instanceof Handlebars.AST.BooleanNode
//TODO: Add support for subexpressions here?
) {
helpersres.push(statement.id.string);
}
});
}
}
}
// If it's a meta block
if ( statement && statement.mustache ) {
recursiveVarSearch( [statement.mustache], res, prefix + newprefix, helpersres );
}
// if it's a whole new program
if ( statement && statement.program && statement.program.statements ) {
sideways = recursiveVarSearch([statement.mustache],[], '', helpersres)[0] || '';
if ( statement.program.inverse && statement.program.inverse.statements ) {
recursiveVarSearch( statement.program.inverse.statements, res, prefix + newprefix + (sideways ? (prefix+newprefix) ? '.'+sideways : sideways : ''), helpersres);
}
recursiveVarSearch( statement.program.statements, res, prefix + newprefix + (sideways ? (prefix+newprefix) ? '.'+sideways : sideways : ''), helpersres);
}
});
return res;
}
// This finds the Helper dependencies since it's soooo similar
function getExternalDeps( nodes ) {
var res = [];
var helpersres = [];
if ( nodes && nodes.statements ) {
res = recursiveVarSearch( nodes.statements, [], undefined, helpersres );
}
var defaultHelpers = [
'helperMissing',
'blockHelperMissing',
'each',
'if',
'unless',
'with'
];
return {
vars: _(res).chain().unique().map(function(e) {
if ( e === '' ) {
return '.';
}
if ( e.length && e[e.length-1] === '.' ) {
return e.substr(0,e.length-1) + '[]';
}
return e;
}).value(),
helpers: _(helpersres).chain().unique().map(function(e){
if ( _(defaultHelpers).contains(e) ) {
return undefined;
}
return e;
}).compact().value()
};
}
function cleanPath(path) {
var tokens = path.split('/');
for(var i=0;i<tokens.length; i++) {
if(tokens[i] == '..') {
delete tokens[i-1];
delete tokens[i];
}
}
return tokens.join('/').replace(/\/\/+/g,'/');
};
function fetchAndRegister(langMap) {
fetchText(path, function(text, path) {
var readCallback = (config.isBuild && config[onHbsReadMethod]) ? config[onHbsReadMethod]: function(name,path,text){return text} ;
// for some reason it doesn't include hbs _first_ when i don't add it here...
var nodes = Handlebars.parse( readCallback(name, path, text));
var partials = findPartialDeps( nodes );
var meta = getMetaData( nodes );
var extDeps = getExternalDeps( nodes );
var vars = extDeps.vars;
var helps = (extDeps.helpers || []);
var debugOutputStart = '';
var debugOutputEnd = '';
var debugProperties = '';
var deps = [];
var depStr, helpDepStr, metaObj, head, linkElem;
var baseDir = name.substr(0,name.lastIndexOf('/')+1);
require.config.hbs = require.config.hbs || {};
require.config.hbs._partials = require.config.hbs._partials || {};
if(meta !== '{}') {
try {
metaObj = JSON.parse(meta);
} catch(e) {
console.log('couldn\'t parse meta for %s', path);
}
}
for ( var i in partials ) {
if ( partials.hasOwnProperty(i) && typeof partials[i] === 'string') { // make sure string, because we're iterating over all props
var partialReference = partials[i];
var path;
if(partialReference.match(/^(\.|\/)+/)) {
// relative path
path = cleanPath(baseDir + partialReference)
}
else {
// absolute path relative to config.hbs.partialsUrl if defined
path = cleanPath(partialsUrl + partialReference);
}
require.config.hbs._partials[path] = require.config.hbs._partials[path] || [];
// we can reference a same template with different paths (with absolute or relative)
require.config.hbs._partials[path].references = require.config.hbs._partials[path].references || [];
require.config.hbs._partials[path].references.push(partialReference);
require.config.hbs._loadedDeps = require.config.hbs._loadedDeps || {};
deps[i] = "hbs!"+path;
}
}
depStr = deps.join("', '");
helps = helps.concat((metaObj && metaObj.helpers) ? metaObj.helpers : []);
helpDepStr = disableHelpers ?
'' : (function (){
var i;
var paths = [];
var pathGetter = config.hbs && config.hbs.helperPathCallback
? config.hbs.helperPathCallback
: function (name){
return (config.hbs && config.hbs.helperDirectory ? config.hbs.helperDirectory : helperDirectory) + name;
};
for ( i = 0; i < helps.length; i++ ) {
paths[i] = "'" + pathGetter(helps[i], path) + "'"
}
return paths;
})().join(',');
if ( helpDepStr ) {
helpDepStr = ',' + helpDepStr;
}
if (metaObj) {
try {
if (metaObj.styles) {
styleList = _.union(styleList, metaObj.styles);
// In dev mode in the browser
if ( require.isBrowser && ! config.isBuild ) {
head = document.head || document.getElementsByTagName('head')[0];
_(metaObj.styles).forEach(function (style) {
if ( !styleMap[style] ) {
linkElem = document.createElement('link');
linkElem.href = config.baseUrl + devStyleDirectory + style + '.css';
linkElem.media = 'all';
linkElem.rel = 'stylesheet';
linkElem.type = 'text/css';
head.appendChild(linkElem);
styleMap[style] = linkElem;
}
});
}
else if ( config.isBuild ) {
(function(){
var fs = require.nodeRequire('fs');
var str = _(metaObj.styles).map(function (style) {
if (!styleMap[style]) {
styleMap[style] = true;
return '@import url('+style+'.css);\n';
}
return '';
}).join('\n');
// I write out my import statements to a file in order to help me build stuff.
// Then I use a tool to inline my import statements afterwards. (you can run r.js on it too)
fs.open(__dirname + buildStyleDirectory + buildCSSFileName, filecode, '0666', function( e, id ) {
fs.writeSync(id, str, null, encoding='utf8');
fs.close(id);
});
filecode = 'a';
})();
}
}
}
catch(e){
console.log('error injecting styles');
}
}
if ( ! config.isBuild && ! config.serverRender ) {
debugOutputStart = '<!-- START - ' + name + ' -->';
debugOutputEnd = '<!-- END - ' + name + ' -->';
debugProperties = 't.meta = ' + meta + ';\n' +
't.helpers = ' + JSON.stringify(helps) + ';\n' +
't.deps = ' + JSON.stringify(deps) + ';\n' +
't.vars = ' + JSON.stringify(vars) + ';\n';
}
var mapping = disableI18n? false : _.extend( langMap, config.localeMapping );
var configHbs = config.hbs || {};
var options = _.extend(configHbs.compileOptions || {}, { originalKeyFallback: configHbs.originalKeyFallback });
var prec = precompile( text, mapping, options);
var tmplName = config.isBuild ? '' : "'" + name + "',";
if(depStr) depStr = ", '"+depStr+"'";
var partialReferences = [];
if(require.config.hbs._partials[name])
partialReferences = require.config.hbs._partials[name].references;
text = '/* START_TEMPLATE */\n' +
'define('+tmplName+"['hbs','hbs/handlebars'"+depStr+helpDepStr+'], function( hbs, Handlebars ){ \n' +
'var t = Handlebars.template(' + prec + ');\n' +
"Handlebars.registerPartial('" + name + "', t);\n";
for(var i=0; i<partialReferences.length;i++)
text += "Handlebars.registerPartial('" + partialReferences[i] + "', t);\n";
text += debugProperties +
'return t;\n' +
'});\n' +
'/* END_TEMPLATE */\n';
//Hold on to the transformed text if a build.
if (config.isBuild) {
buildMap[compiledName] = text;
}
//IE with conditional comments on cannot handle the
//sourceURL trick, so skip it if enabled.
/*@if (@_jscript) @else @*/
if (!config.isBuild) {
text += '\r\n//@ sourceURL=' + path;
}
/*@end@*/
if ( !config.isBuild ) {
require( deps, function (){
load.fromText(text);
//Give result to load. Need to wait until the module
//is fully parse, which will happen after this
//execution.
parentRequire([name], function (value) {
load(value);
});
});
}
else {
load.fromText(name, text);
//Give result to load. Need to wait until the module
//is fully parse, which will happen after this
//execution.
parentRequire([name], function (value) {
load(value);
});
}
if ( config.removeCombined && path ) {
fs.unlinkSync(path);
}
});
}
var path;
var omitExtension = config.hbs && config.hbs.templateExtension === false;
if (omitExtension) {
path = parentRequire.toUrl(name);
}
else {
path = parentRequire.toUrl(name +'.'+ (config.hbs && config.hbs.templateExtension ? config.hbs.templateExtension : templateExtension));
}
if (disableI18n){
fetchAndRegister(false);
}
else {
// Workaround until jam is able to pass config info or we move i18n to a separate module.
// This logs a warning and disables i18n if there's an error loading the language file
var langMapPath = (config.hbs && config.hbs.i18nDirectory ? config.hbs.i18nDirectory : i18nDirectory) + (config.locale || 'en_us') + '.json';
try {
fetchOrGetCached(parentRequire.toUrl(langMapPath), function (langMap) {
fetchAndRegister(JSON.parse(langMap));
});
}
catch(er) {
// if there's no configuration at all, log a warning and disable i18n for this and subsequent templates
if(!config.hbs) {
console.warn('hbs: Error reading ' + langMapPath + ', disabling i18n. Ignore this if you\'re using jam, otherwise check your i18n configuration.\n');
config.hbs = {i18n: false, helpers: true};
fetchAndRegister(false);
}
else {
throw er;
}
}
}
//>>excludeEnd('excludeHbs')
}
};
});
/* END_hbs_PLUGIN */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.