hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1307d680123d9b1697241539f4294cd1e6b81baa | 1,317 | js | JavaScript | lib/directive/Display/Hint.js | bricklazy/bot-sdk-node.js | 53a31e83981196f5fca58938dce5a1a6592225e4 | [
"Apache-2.0"
] | 121 | 2017-11-18T04:15:14.000Z | 2021-09-05T19:25:28.000Z | lib/directive/Display/Hint.js | bricklazy/bot-sdk-node.js | 53a31e83981196f5fca58938dce5a1a6592225e4 | [
"Apache-2.0"
] | 13 | 2017-12-06T15:06:34.000Z | 2021-05-17T01:44:16.000Z | lib/directive/Display/Hint.js | bricklazy/bot-sdk-node.js | 53a31e83981196f5fca58938dce5a1a6592225e4 | [
"Apache-2.0"
] | 63 | 2017-12-29T11:51:26.000Z | 2021-06-03T06:20:21.000Z | /**
* @file 用于生成Hint指令的类
* @author yelvye@baidu.com
*/
/**
* Copyright (c) 2017 Baidu, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/**
* @class Hint 用于生成Hint指令的类
* @extends {BaseDirective}
*/
let BaseDirective = require('../BaseDirective');
class Hint extends BaseDirective {
/**
* Hint 构造函数.
*
* @param {Mixed} text 提示文本
*/
constructor(text) {
super('Hint');
if (text && typeof text === 'string') {
text = [text];
}
if (text instanceof Array) {
this.data.hints = text.map(function (item) {
return {
type: 'PlainText',
text: item
};
});
}
}
}
module.exports = Hint;
| 23.517857 | 75 | 0.594533 |
13084718e2cb9efb071d0e4d1cb0e1280a74f28f | 133 | js | JavaScript | src/uiConstants.js | futurewei-cloud/hafgufa | c7b4e1dd2774f1c8c10b6f4bb0ab11556eedcb5d | [
"MIT"
] | 2 | 2019-03-18T18:37:26.000Z | 2019-03-20T03:13:16.000Z | src/uiConstants.js | futurewei-cloud/hafgufa | c7b4e1dd2774f1c8c10b6f4bb0ab11556eedcb5d | [
"MIT"
] | 3 | 2020-02-11T19:27:56.000Z | 2022-02-12T07:30:55.000Z | src/uiConstants.js | futurewei-cloud/hafgufa | c7b4e1dd2774f1c8c10b6f4bb0ab11556eedcb5d | [
"MIT"
] | 1 | 2019-12-20T01:32:57.000Z | 2019-12-20T01:32:57.000Z | import { Enum } from 'type-enforcer-ui';
export const ORIENTATION = new Enum({
VERTICAL: 'vertical',
HORIZONTAL: 'horizontal'
});
| 19 | 40 | 0.699248 |
1308ab96cc6daaa5abe98ba5313b6f46cffa4c06 | 1,384 | js | JavaScript | src/containers/App.js | v16-04/bitg-webwallet | 23c4d5191d46c40773d2f066c988d2ad5ef2a0a7 | [
"MIT"
] | null | null | null | src/containers/App.js | v16-04/bitg-webwallet | 23c4d5191d46c40773d2f066c988d2ad5ef2a0a7 | [
"MIT"
] | null | null | null | src/containers/App.js | v16-04/bitg-webwallet | 23c4d5191d46c40773d2f066c988d2ad5ef2a0a7 | [
"MIT"
] | 1 | 2020-09-15T03:41:49.000Z | 2020-09-15T03:41:49.000Z | import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { store } from 'core';
import RoutesContainer from 'containers/RoutesContainer/RoutesContainer';
import PrivateRoute from 'components/PrivateRoute/PrivateRoute';
import PageNotFound from 'components/PageNotFound/PageNotFound';
import LoginContainer from 'containers/LoginContainer/LoginContainer';
import WalletConfirmContainer from 'containers/WalletConfirmContainer/WalletConfirmContainer';
import KeystoreUploadContainer from 'containers/KeystoreUploadContainer/KeystoreUploadContainer';
import 'css/App.less';
class App extends Component {
render() {
return (
<Provider store={store}>
<Router>
<div className="App">
<div className="content">
<Switch>
<Route path="/login" exact component={LoginContainer} />
<Route exact path="/create" component={WalletConfirmContainer} />
<Route exact path="/unlock" component={KeystoreUploadContainer} />
<Route exact path="/404" component={PageNotFound} />
<PrivateRoute path="/" component={RoutesContainer} />
</Switch>
</div>
</div>
</Router>
</Provider>
);
}
}
export default App;
| 37.405405 | 97 | 0.669798 |
130a2aef5729f31f32b604f426b5521ee392efd9 | 249 | js | JavaScript | packages/schematics/src/lib/type/files/js/__name__.type.js | Stradivario/gapi | 5a0f2dc5677a402eb07d3411b3da647b2a2ab1b3 | [
"MIT"
] | 25 | 2018-03-09T18:59:23.000Z | 2022-03-29T14:21:17.000Z | packages/schematics/src/lib/type/files/js/__name__.type.js | Stradivario/gapi | 5a0f2dc5677a402eb07d3411b3da647b2a2ab1b3 | [
"MIT"
] | 43 | 2020-07-17T12:18:06.000Z | 2022-01-22T21:29:21.000Z | packages/schematics/src/lib/type/files/js/__name__.type.js | Stradivario/gapi | 5a0f2dc5677a402eb07d3411b3da647b2a2ab1b3 | [
"MIT"
] | 3 | 2018-03-09T18:59:30.000Z | 2018-07-14T07:51:39.000Z | import { GraphQLString, GraphQLObjectType } from '@gapi/core';
export const <%= classify(name) %>Type = new GraphQLObjectType({
name: '<%= classify(name) %>Type',
fields: {
init: {
type: GraphQLString
}
}
}); | 24.9 | 64 | 0.570281 |
130b6cbce1642e10cd8807847d19a42427633926 | 77 | js | JavaScript | tasks/helpers/onError.js | Lausselloic/a11y.css | fc61c7648368a3b4d79fc6fe882c6c8be59c93a2 | [
"MIT"
] | 1,395 | 2015-01-02T13:55:16.000Z | 2022-03-21T10:10:37.000Z | tasks/helpers/onError.js | Lausselloic/a11y.css | fc61c7648368a3b4d79fc6fe882c6c8be59c93a2 | [
"MIT"
] | 315 | 2015-01-02T11:57:07.000Z | 2022-03-16T11:29:35.000Z | tasks/helpers/onError.js | Lausselloic/a11y.css | fc61c7648368a3b4d79fc6fe882c6c8be59c93a2 | [
"MIT"
] | 124 | 2015-01-05T10:22:57.000Z | 2022-03-25T11:41:16.000Z | module.exports = function (err) {
console.log(err);
this.emit('end');
};
| 15.4 | 33 | 0.623377 |
130b934117f56fcf4ac3fedf940312a7ad464580 | 208 | js | JavaScript | test/index.js | mintrupt/riccardo | 648d61425f3e3672c5efa1ba8ae8cddc1474fdc4 | [
"MIT"
] | 2 | 2016-07-28T00:43:27.000Z | 2018-12-07T10:17:00.000Z | test/index.js | mintrupt/riccardo | 648d61425f3e3672c5efa1ba8ae8cddc1474fdc4 | [
"MIT"
] | null | null | null | test/index.js | mintrupt/riccardo | 648d61425f3e3672c5efa1ba8ae8cddc1474fdc4 | [
"MIT"
] | null | null | null | describe('riccardo', function () {
require('./injector');
require('./factory');
require('./capitalizer');
require('./scan');
require('./update');
require('./reverse');
require('./annotate');
}); | 23.111111 | 34 | 0.596154 |
130ba1f976c930ac11b2120e0e2e4baa9ef59177 | 313 | js | JavaScript | app/rsvp/rsvp_test.js | mattj415/wedding | 4f340a6808e5bb2b8531e6aa445e4f337f2ea46d | [
"MIT"
] | null | null | null | app/rsvp/rsvp_test.js | mattj415/wedding | 4f340a6808e5bb2b8531e6aa445e4f337f2ea46d | [
"MIT"
] | null | null | null | app/rsvp/rsvp_test.js | mattj415/wedding | 4f340a6808e5bb2b8531e6aa445e4f337f2ea46d | [
"MIT"
] | null | null | null | 'use strict';
describe('myApp.rsvp module', function() {
beforeEach(module('myApp.rsvp'));
describe('rsvp controller', function(){
it('should ....', inject(function($controller) {
//spec body
var rsvpCtrl = $controller('rsvpCtrl');
expect(rsvpCtrl).toBeDefined();
}));
});
}); | 19.5625 | 52 | 0.603834 |
130be0b2953a468bbf5c669c6326c9559eaeff6e | 740 | js | JavaScript | 2-resources/BLOG/ciriculumn/week-2/week2/scope_project/test/09-closure-sandwiches-spec.js | impastasyndrome/Lambda-Resource-Static-Assets | 7070672038620d29844991250f2476d0f1a60b0a | [
"MIT"
] | null | null | null | 2-resources/BLOG/ciriculumn/week-2/week2/scope_project/test/09-closure-sandwiches-spec.js | impastasyndrome/Lambda-Resource-Static-Assets | 7070672038620d29844991250f2476d0f1a60b0a | [
"MIT"
] | null | null | null | 2-resources/BLOG/ciriculumn/week-2/week2/scope_project/test/09-closure-sandwiches-spec.js | impastasyndrome/Lambda-Resource-Static-Assets | 7070672038620d29844991250f2476d0f1a60b0a | [
"MIT"
] | 1 | 2021-11-05T07:48:26.000Z | 2021-11-05T07:48:26.000Z | const assert = require("assert");
const chai = require("chai");
const expect = chai.expect;
const spies = require("chai-spies");
chai.use(spies);
const sandwichMaker = require("../problems/09-closure-sandwiches.js");
describe("sandwichMaker()", function () {
it("should return a function that accepts new arguments for the order", function () {
let sandwich = sandwichMaker();
let result1 = "One sandwich with tomato and spinach";
let result2 = "One sandwich with tomato and spinach and jelly";
let result3 = "One sandwich with tomato and spinach and jelly and bread";
assert.equal(sandwich("spinach"), result1);
assert.equal(sandwich("jelly"), result2);
assert.equal(sandwich("bread"), result3);
});
});
| 35.238095 | 87 | 0.698649 |
130c563d7245a06817ace97842d8250d26b120f9 | 91 | js | JavaScript | packages/plugin-monorepo-readmes/__tests__/mock-fs/simple/typedoc.js | KnodesCommunity/typedoc-plugins | 7788b74beb849536bce0a564a58ca6a274d100e3 | [
"MIT"
] | null | null | null | packages/plugin-monorepo-readmes/__tests__/mock-fs/simple/typedoc.js | KnodesCommunity/typedoc-plugins | 7788b74beb849536bce0a564a58ca6a274d100e3 | [
"MIT"
] | 4 | 2022-02-23T11:11:34.000Z | 2022-03-31T23:48:54.000Z | packages/plugin-monorepo-readmes/__tests__/mock-fs/simple/typedoc.js | KnodesCommunity/typedoc-plugins | 7788b74beb849536bce0a564a58ca6a274d100e3 | [
"MIT"
] | null | null | null | module.exports = {
entryPoints: [
'packages/*',
],
entryPointStrategy: 'packages',
};
| 13 | 32 | 0.637363 |
130d01046fb7e5925615fb9b6cc36fc182ffefc6 | 1,475 | js | JavaScript | auth/auth.spec.js | bw-www/Back-end | c8c1535de414e97e690f462057d043c7a20d3672 | [
"MIT"
] | null | null | null | auth/auth.spec.js | bw-www/Back-end | c8c1535de414e97e690f462057d043c7a20d3672 | [
"MIT"
] | 2 | 2021-05-11T12:14:23.000Z | 2021-09-02T10:27:50.000Z | auth/auth.spec.js | bw-www/Back-end | c8c1535de414e97e690f462057d043c7a20d3672 | [
"MIT"
] | 1 | 2020-04-27T19:04:42.000Z | 2020-04-27T19:04:42.000Z | const request = require("supertest");
const server = require("../api/server.js");
const db = require("../database/dbConfig.js");
describe("Auth Router", () => {
// describe("POST /api/auth/register", () => {
// beforeEach(async () => {
// await db("users").truncate();
// });
// it("Return 201 on success", () => {
// return request(server)
// .post("/api/auth/register")
// .send({ username: "myself", password: "pass" })
// .then((res) => {
// expect(res.status).toBe(201);
// });
// });
// });
describe("POST /api/auth/register", () => {
it("Return 500 on failure", () => {
return request(server)
.post("/api/auth/register")
.send({ username: "myself" })
.then((res) => {
expect(res.status).toBe(500);
});
});
});
describe("POST /api/auth/login", () => {
// it("Return 200 on success", () => {
// return request(server)
// .post("/api/auth/login")
// .send({ username: "myself", password: "pass" })
// .then((res) => {
// expect(res.status).toBe(200);
// });
// });
it("Return 401 on failure", () => {
return request(server)
.post("/api/auth/login")
.send({ username: "myself", password: "pppasss" })
.then((res) => {
expect(res.status).toBe(401);
});
});
});
});
| 27.830189 | 59 | 0.456271 |
130d06ba5478dfed4f38278b24eaf8f67ea70c37 | 15,017 | js | JavaScript | index.js | zwaldowski/homebridge-satellite-fan | a677f004f2cc2054bee1ed2ded1faeca1b35a6f2 | [
"MIT"
] | 5 | 2018-02-20T20:40:15.000Z | 2021-11-29T06:21:01.000Z | index.js | zwaldowski/homebridge-satellite-fan | a677f004f2cc2054bee1ed2ded1faeca1b35a6f2 | [
"MIT"
] | 13 | 2017-09-23T21:45:12.000Z | 2021-08-05T22:39:54.000Z | index.js | zwaldowski/homebridge-satellite-fan | a677f004f2cc2054bee1ed2ded1faeca1b35a6f2 | [
"MIT"
] | 3 | 2018-02-13T23:58:56.000Z | 2020-01-27T03:05:38.000Z | 'use strict'
const plugin = require('./package'),
Noble = require('@abandonware/noble'),
EventEmitter = require('events').EventEmitter
var Homebridge, Service, Characteristic
module.exports = function(homebridge) {
console.log("Homebridge API version: " + homebridge.version)
Homebridge = homebridge
Service = homebridge.hap.Service
Characteristic = homebridge.hap.Characteristic
homebridge.registerAccessory(plugin.name, "satellite-fan", FanLightAccessory)
}
function trimAddress(address) {
return address.toLowerCase().replace(/:/g, "")
}
function trimUUID(uuid) {
return uuid.toLowerCase().replace(/:/g, "").replace(/-/g, "")
}
// MARK: -
class FanRequest {
writeInto(buffer) {
throw new TypeError('Must override method')
}
toPrefixedBuffer(prefix) {
var buffer
if (prefix > 0) {
buffer = new Buffer(13)
buffer.writeUInt8(prefix)
this.writeInto(buffer.slice(1))
} else {
buffer = new Buffer(12)
this.writeInto(buffer)
}
const checksum = buffer.slice(0, buffer.length - 1).reduce(function(a, b){
return a + b
}, 0) & 255
buffer.writeUInt8(checksum, buffer.length - 1)
return buffer
}
}
class FanGetStateRequest extends FanRequest {
writeInto(buffer) {
buffer.fill(0)
buffer.writeUInt8(160)
}
}
Math.clamp = function(number, min, max) {
return Math.max(min, Math.min(number, max))
}
class FanUpdateLightRequest extends FanRequest {
constructor(isOn, level) {
super()
this.on = isOn ? 1 : 0
this.level = Math.clamp(level, 0, 100)
}
writeInto(buffer) {
buffer.fill(0)
buffer.writeUInt8(161)
buffer.writeUInt8(255, 4)
buffer.writeUInt8(100, 5)
buffer.writeUInt8((this.on << 7) | this.level, 6)
buffer.fill(255, 7, 10)
}
}
class FanUpdateLevelRequest extends FanRequest {
constructor(level) {
super()
this.level = Math.clamp(level, 0, 3)
}
writeInto(buffer) {
buffer.fill(0)
buffer.writeUInt8(161)
buffer.writeUInt8(this.level, 4)
buffer.fill(255, 5, 10)
}
}
class FanResponse {
static get Keys() { return {
FAN_LEVEL: 'fanLevel',
FAN_SPEED: 'fanSpeed',
LIGHT_ON: 'lightIsOn',
LIGHT_BRIGHTNESS: 'lightBrightness'
} }
static fromPrefixedBuffer(prefix, buffer) {
if (prefix > 0) {
buffer = buffer.slice(1)
}
if (buffer.readUInt8(0) != 176) { return null }
const response = new FanResponse()
const windVelocity = buffer.readUInt8(2)
response.fanLevelMaximum = windVelocity & 0b00011111
const currentWindVelocity = buffer.readUInt8(4)
response.fanLevel = currentWindVelocity & 0b00011111
const currentBrightness = buffer.readUInt8(6)
response.lightIsOn = (currentBrightness & 0b10000000) != 0
response.lightBrightness = (currentBrightness & 0b01111111)
return response
}
get fanSpeed() {
return (this.fanLevel / this.fanLevelMaximum) * 100
}
}
// MARK: -
class FanLightAccessory extends EventEmitter {
constructor (log, config) {
super()
this.onDiscover = this.onDiscover.bind(this)
this.log = log
this.name = config.name || "Ceiling Fan"
if (!config.address) {
throw new Error(this.prefix + " Missing mandatory config 'address'")
}
this.address = trimAddress(config.address)
if (!config.ble) {
throw new Error(this.prefix + " Missing mandatory config 'ble'")
}
this.manufacturerPrefix = config.ble.prefix || 0
if (!config.ble.serviceUUID) {
throw new Error(this.prefix + " Missing mandatory config 'ble.serviceUUID'")
}
this.serviceUUID = trimUUID(config.ble.serviceUUID)
if (!config.ble.writeCharacteristicUUID) {
throw new Error(this.prefix + " Missing mandatory config 'ble.writeCharacteristicUUID'")
}
this.writeCharacteristicUUID = trimUUID(config.ble && config.ble.writeCharacteristicUUID)
this.writeCharacteristic = null
if (!config.ble.notifyCharacteristicUUID) {
throw new Error(this.prefix + " Missing mandatory config 'ble.notifyCharacteristicUUID'")
}
this.notifyCharacteristicUUID = trimUUID(config.ble && config.ble.notifyCharacteristicUUID)
this.notifyCharacteristic = null
this.informationService = this.makeInformationService(config)
this.fanService = this.makeFanService(config)
this.lightService = this.makeLightService(config)
this.fanLevelMaximum = 3
Homebridge.on('didFinishLaunching', this.onDidFinishLaunching.bind(this))
}
identify (callback) {
this.log('Device identified!')
callback()
}
startScanningWithTimeout() {
Noble.startScanning([], true)
setTimeout(function() {
if (Noble.listenerCount('discover') == 0) { return }
this.log.debug('Discovery timeout')
Noble.stopScanning()
}.bind(this), 12500)
}
stopScanning() {
Noble.removeListener('discover', this.onDiscover)
if (Noble.listenerCount('discover') == 0) {
Noble.removeAllListeners('scanStop')
Noble.stopScanning()
}
}
fanSpeedToLevel(value) {
return Math.ceil(value * (this.fanLevelMaximum / 100))
}
sendCommand(command, callback) {
if (!this.notifyCharacteristic || !this.writeCharacteristic) {
this.log.info('waiting on connect...')
this.once('ready', function() {
this.sendCommand(command, callback)
}.bind(this))
return
}
const buffer = command.toPrefixedBuffer(this.manufacturerPrefix)
this.log.debug('will send', this.manufacturerPrefix, buffer)
this.writeCharacteristic.write(buffer, false, function(error){
if (!error) {
this.log.debug('sent')
}
callback(error)
}.bind(this))
}
sendUpdateStateRequest() {
this.log.info('coalesced update request')
const command = new FanGetStateRequest()
this.sendCommand(command, function(error){
if (!error) { return }
this.emit('updateState', error)
}.bind(this))
}
// MARK: -
onDidFinishLaunching() {
this.log.info("Received did finish launching")
Noble.on('stateChange', this.onAdapterChange.bind(this))
}
onAdapterChange(state) {
Noble.removeAllListeners('scanStop')
Noble.stopScanning()
if (state != 'poweredOn') {
this.log.debug("Stopped scanning: " + state)
return
}
this.log.debug('Starting scan')
Noble.on('scanStop', function() {
setTimeout(function() {
this.log.debug('Restart from scan stop')
this.startScanningWithTimeout()
}.bind(this), 2500)
}.bind(this))
Noble.on('discover', this.onDiscover)
this.log.debug('discover count ', Noble.listenerCount('discover'))
this.startScanningWithTimeout()
}
onDiscover(peripheral) {
if (trimAddress(peripheral.address) !== this.address || (this.writeCharacteristic && this.notifyCharacteristic)) {
this.log.debug("Ignoring " + peripheral.address + " (RSSI " + peripheral.rssi + "dB)")
return
}
this.log.debug("Found " + peripheral.address + " (RSSI " + peripheral.rssi + "dB)")
this.stopScanning()
peripheral.connect(function(error) {
this.onConnect(error, peripheral)
}.bind(this))
}
onConnect(error, peripheral) {
if (error) {
this.log.error("Connecting to " + peripheral.address + " failed: " + error)
this.onDisconnect(error, peripheral)
return
}
this.log.debug("Connected to " + peripheral.address)
peripheral.discoverSomeServicesAndCharacteristics([ this.serviceUUID ], [ this.writeCharacteristicUUID, this.notifyCharacteristicUUID ], this.onDiscoverCharacteristics.bind(this));
peripheral.once('disconnect', function(error) {
this.onDisconnect(error, peripheral)
}.bind(this))
}
onDisconnect(error, peripheral) {
if (this.writeCharacteristic) {
this.writeCharacteristic.removeAllListeners('set')
}
this.writeCharacteristic = null
if (this.notifyCharacteristic) {
this.notifyCharacteristic.unsubscribe(null)
this.notifyCharacteristic.removeAllListeners('data')
}
this.notifyCharacteristic = null
peripheral.removeAllListeners()
this.log.info("Disconnected")
this.onDiscover(peripheral)
if (this.listenerCount('updateState') != 0) {
this.sendUpdateStateRequest()
}
}
onDiscoverCharacteristics(error, services, characteristics) {
if (error || characteristics.count < 2) {
this.log.error(this.prefix, "Discover services failed: " + error)
return
}
const writeCharacteristic = characteristics[0],
notifyCharacteristic = characteristics[1]
notifyCharacteristic.on('data', this.onNotify.bind(this))
notifyCharacteristic.subscribe(function (error) {
if (error) {
this.log.warn("Subscribe to notify characteristic failed")
}
this.writeCharacteristic = writeCharacteristic
this.notifyCharacteristic = notifyCharacteristic
this.log.info("Ready")
this.emit('ready')
}.bind(this))
}
onNotify(data, isNotification) {
const response = FanResponse.fromPrefixedBuffer(this.manufacturerPrefix, data)
if (!response) { return }
this.log.debug('received fan state')
this.fanLevelMaximum = response.fanLevelMaximum
this.emit('updateState', null, response)
if (response.fanLevel != 0) {
this.fanService.getCharacteristic(Characteristic.On).updateValue(true)
this.fanService.getCharacteristic(Characteristic.RotationSpeed).updateValue(response.fanSpeed)
} else {
this.fanService.getCharacteristic(Characteristic.On).updateValue(false)
}
if (this.lightService) {
this.lightService.getCharacteristic(Characteristic.On).updateValue(response.lightIsOn)
this.lightService.getCharacteristic(Characteristic.Brightness).updateValue(response.lightBrightness)
}
}
// MARK: -
getNextValueForFanState(key, callback) {
const shouldSend = this.listenerCount('updateState') == 0
this.once('updateState', function(error, response) {
if (error) {
callback(error, null)
} else {
callback(null, response[key])
}
})
if (shouldSend) {
this.sendUpdateStateRequest()
} else {
this.log.debug('Skipping send update')
}
}
enqueueWriteForDependentValue(service, characteristic, produceCommand, callback) {
if (!this.notifyCharacteristic || !this.writeCharacteristic) {
this.log.debug('Defer write for ready')
this.once('ready', function() {
this.log.debug('Dequeue write from ready')
this.enqueueWriteForDependentValue(service, characteristic, produceCommand, callback)
}.bind(this))
return
}
if (this.listenerCount('updateState') != 0) {
this.log.debug('Defer write for update state')
this.once('updateState', function() {
this.log.debug('Dequeuing write from update state')
this.enqueueWriteForDependentValue(service, characteristic, produceCommand, callback)
}.bind(this))
return
}
if (this.writeCharacteristic.listenerCount('write') >= 1) {
this.log.debug('Defer write for active write')
this.writeCharacteristic.once('write', function() {
this.log.debug('Dequeue write from active write')
this.enqueueWriteForDependentValue(service, characteristic, produceCommand, callback)
}.bind(this))
return
}
const command = produceCommand(service.getCharacteristic(characteristic).value)
this.sendCommand(command, callback)
}
getFanOn(callback) {
this.getNextValueForFanState(FanResponse.Keys.FAN_LEVEL, function(error, level) {
callback(error, error ? null : level != 0)
}.bind(this))
}
setFanOn(newValue, callback) {
this.log.info('Fan on: ' + newValue)
if (!newValue) {
const command = new FanUpdateLevelRequest(0)
this.sendCommand(command, callback)
return
}
this.enqueueWriteForDependentValue(this.fanService, Characteristic.RotationSpeed, function(currentSpeed){
const level = this.fanSpeedToLevel(currentSpeed)
this.log.debug('Using current level: ' + level)
return new FanUpdateLevelRequest(level)
}.bind(this), callback)
}
getFanRotationSpeed(callback) {
this.getNextValueForFanState(FanResponse.Keys.FAN_SPEED, callback)
}
setFanRotationSpeed(newValue, callback) {
const level = this.fanSpeedToLevel(newValue)
this.log.info('Fan speed: ' + level)
const command = new FanUpdateLevelRequest(level)
this.sendCommand(command, callback)
}
getLightOn(callback) {
this.getNextValueForFanState(FanResponse.Keys.LIGHT_ON, callback)
}
setLightOn(newValue, callback) {
this.log.info('Light on: ' + newValue)
this.enqueueWriteForDependentValue(this.lightService, Characteristic.Brightness, function(currentBrightness) {
this.log.debug('Using current brightness: ' + currentBrightness)
return new FanUpdateLightRequest(newValue, currentBrightness)
}.bind(this), callback)
}
getLightBrightness(callback) {
this.getNextValueForFanState(FanResponse.Keys.LIGHT_BRIGHTNESS, callback)
}
setLightBrightness(newValue, callback) {
this.log.info('Light brightness: ' + newValue)
this.enqueueWriteForDependentValue(this.lightService, Characteristic.On, function(currentlyOn) {
return new FanUpdateLightRequest(currentlyOn, newValue)
}, callback)
}
// MARK: -
makeInformationService(config) {
const service = new Service.AccessoryInformation()
service
.setCharacteristic(Characteristic.Manufacturer, config.device && config.device.manufacturer)
.setCharacteristic(Characteristic.Model, config.device && config.device.model)
.setCharacteristic(Characteristic.SerialNumber, config.device && config.device.serial)
.setCharacteristic(Characteristic.FirmwareRevision, (config.device && config.device.revision) || plugin.version)
return service
}
makeFanService(config) {
const service = new Service.Fan(this.name)
service.getCharacteristic(Characteristic.On)
.on('get', this.getFanOn.bind(this))
.on('set', this.setFanOn.bind(this))
service.getCharacteristic(Characteristic.RotationSpeed)
.setProps({
maxValue: 99,
minStep: 33
})
.on('get', this.getFanRotationSpeed.bind(this))
.on('set', this.setFanRotationSpeed.bind(this))
return service
}
makeLightService(config) {
if (config.light === false) { return null }
const service = new Service.Lightbulb(this.name)
service.getCharacteristic(Characteristic.On)
.on('get', this.getLightOn.bind(this))
.on('set', this.setLightOn.bind(this))
service.getCharacteristic(Characteristic.Brightness)
.on('get', this.getLightBrightness.bind(this))
.on('set', this.setLightBrightness.bind(this))
return service
}
getServices () {
return [ this.informationService, this.fanService, this.lightService ].filter(Boolean)
}
}
| 28.495256 | 184 | 0.684291 |
130e2d42a66629f45d477ad424bfe06568e6fac7 | 65 | js | JavaScript | node_modules/@vaadin/vaadin-notification/theme/lumo/vaadin-notification.js | kirillovme/ContactList | 71f8d805d1731dfb1376fecfcf6d8a27698934f1 | [
"Unlicense"
] | null | null | null | node_modules/@vaadin/vaadin-notification/theme/lumo/vaadin-notification.js | kirillovme/ContactList | 71f8d805d1731dfb1376fecfcf6d8a27698934f1 | [
"Unlicense"
] | null | null | null | node_modules/@vaadin/vaadin-notification/theme/lumo/vaadin-notification.js | kirillovme/ContactList | 71f8d805d1731dfb1376fecfcf6d8a27698934f1 | [
"Unlicense"
] | null | null | null | import '@vaadin/notification/theme/lumo/vaadin-notification.js';
| 32.5 | 64 | 0.815385 |
130f43f635b05271f3984cc209437db4301737e1 | 32 | js | JavaScript | node_modules/_proxy-addr@2.0.4@proxy-addr/node_modules/ipaddr.js | ian-kevin126/TravelProject | 1bda73f8eb150d567e282233faa13f70d1a4b8bb | [
"MIT"
] | null | null | null | node_modules/_proxy-addr@2.0.4@proxy-addr/node_modules/ipaddr.js | ian-kevin126/TravelProject | 1bda73f8eb150d567e282233faa13f70d1a4b8bb | [
"MIT"
] | null | null | null | node_modules/_proxy-addr@2.0.4@proxy-addr/node_modules/ipaddr.js | ian-kevin126/TravelProject | 1bda73f8eb150d567e282233faa13f70d1a4b8bb | [
"MIT"
] | null | null | null | ../../_ipaddr.js@1.8.0@ipaddr.js | 32 | 32 | 0.625 |
13119cd7ca675d9da20ccd2b5b0e32deb10aa615 | 171 | js | JavaScript | src/config/messages.config.js | jackson-elfers/twilight-storm | f63ac62b9ad41f9c6875020f614338aaf7514409 | [
"MIT"
] | null | null | null | src/config/messages.config.js | jackson-elfers/twilight-storm | f63ac62b9ad41f9c6875020f614338aaf7514409 | [
"MIT"
] | 11 | 2020-07-30T17:57:45.000Z | 2022-02-19T06:06:04.000Z | src/config/messages.config.js | jackson-elfers/twilight-storm | f63ac62b9ad41f9c6875020f614338aaf7514409 | [
"MIT"
] | null | null | null | module.exports = {
user: { login: "Please check your username or password! 👍" },
serverError: "Oops, that's a server error, please let us know so we can fix it! 👍"
};
| 34.2 | 84 | 0.666667 |
1312dbfeb29effc009be52fe86698b8506fafd97 | 1,120 | js | JavaScript | src/index.js | NikolayKovzik/brackets | e9b223d29b22023aca24e334f9ac767bf888f88a | [
"MIT"
] | null | null | null | src/index.js | NikolayKovzik/brackets | e9b223d29b22023aca24e334f9ac767bf888f88a | [
"MIT"
] | null | null | null | src/index.js | NikolayKovzik/brackets | e9b223d29b22023aca24e334f9ac767bf888f88a | [
"MIT"
] | null | null | null | module.exports = function check(str, bracketsConfig) {
let openings= Array.from(new Map( bracketsConfig).keys());
let closings = Array.from(new Map( bracketsConfig).values());
let arr = str.split('');
let stack = [];
let twins = [];
openings.forEach((item) => closings.includes(item) ? twins.push(item) : item);
let twinsCounter = {};
let unicIndicador;
if(openings.includes(arr[arr.length-1]) && !twins.includes(arr[arr.length-1]))
return false;
for(let i = 0; i < arr.length; i++) {
if(twins.includes(arr[i]) ) {
if(twinsCounter[arr[i]])
twinsCounter[arr[i]] += 1;
else
twinsCounter[arr[i]] = 1;
unicIndicador = false;
}
else
unicIndicador = true;
if(closings.indexOf(arr[i]) === -1 || (twinsCounter[arr[i]]%2 !== 0 && unicIndicador!==true)) {
stack.push(arr[i])
} else if( closings.indexOf(arr[i]) !== openings.indexOf(stack.pop()) ){
return false;
}
}
return true;
}
| 28 | 103 | 0.526786 |
1313bb4b0119c72026542f5b5ac18e0adb5c6bdc | 68 | js | JavaScript | js-test-suite/testsuite/618278c7605fa57ad6c93eeb37456fff.js | hao-wang/Montage | d1c98ec7dbe20d0449f0d02694930cf1f69a5cea | [
"MIT"
] | 16 | 2020-03-23T12:53:10.000Z | 2021-10-11T02:31:50.000Z | js-test-suite/testsuite/618278c7605fa57ad6c93eeb37456fff.js | hao-wang/Montage | d1c98ec7dbe20d0449f0d02694930cf1f69a5cea | [
"MIT"
] | null | null | null | js-test-suite/testsuite/618278c7605fa57ad6c93eeb37456fff.js | hao-wang/Montage | d1c98ec7dbe20d0449f0d02694930cf1f69a5cea | [
"MIT"
] | 1 | 2020-08-17T14:06:59.000Z | 2020-08-17T14:06:59.000Z | loadRelativeToScript("../../tests/js1_8_5/reflect-parse/Match.js");
| 34 | 67 | 0.75 |
1313fc6b983372631c23fdceecbc8044e95adcf7 | 1,132 | js | JavaScript | miniprogram/pages/team-tab/team-tab.js | eddy20001118/Towero | 511375714f2cdda8e8bc772692bcab7594e4bf28 | [
"MIT"
] | 2 | 2019-10-18T07:15:30.000Z | 2019-11-01T15:16:28.000Z | miniprogram/pages/team-tab/team-tab.js | eddy20001118/Towero | 511375714f2cdda8e8bc772692bcab7594e4bf28 | [
"MIT"
] | 2 | 2021-05-10T13:41:13.000Z | 2021-05-10T13:52:50.000Z | miniprogram/pages/team-tab/team-tab.js | eddy20001118/Towero | 511375714f2cdda8e8bc772692bcab7594e4bf28 | [
"MIT"
] | null | null | null | // 搜索队伍页
import { utils } from '/utils.js';
Page({
data: {
isIphoneX: false, //为iPhone X做底部tabbar适配
scrollIndex: 0, // 第几次触碰到页面底部计数,默认为0,不为空
isSearch: false, // 是否处于搜索状态,决定要加载的数组,以及loading组件
searchValue: String, // 搜索数据字符串
lastSearchFinish: false, // 上一次搜索是否完成
lastLoadFinish: false, // 上一次懒加载是否完成(若未完成,在这期间的触底不加入计数)
defaultTeamArray: new Array(), // 默认显示的teamInfo数组,一次50个,懒加载,必须初始化
searchTeamArray: Array // 搜索结果返回的teamInfo数组,无需初始化,因为每次都会给赋值一个数组
},
// 生命周期函数--监听页面加载
onLoad: function(options) {
utils.load(options, this);
var index = this.data.scrollIndex;
utils.getTeams(this, index);
},
// 生命周期函数--监听页面显示
onShow: function() {
this.getTabBar().init(); // 更新tab-bar选中态
},
// 触底自动触发函数
onReachBottom: function() {
utils.reachBottom(this);
},
// 搜索事件触发函数
onSearch: function(event) {
utils.search(event, this);
},
// 取消搜索触发函数
onSearchCanel: function() {
utils.searchCancel(this);
},
// 点击team-card触发事件
onTeamCardClick: function(event) {
utils.teamCardClick(event);
},
// 用户点击右上角分享
onShareAppMessage: function() {}
});
| 21.769231 | 69 | 0.660777 |
131402ac11a7848757684d689eb6688ddbd3f2fa | 907,535 | js | JavaScript | ne-modules-all.js | nodejs-enterprise/angular-modules | 86d5ffc22c231232f83cbf80214cf358349ed6d6 | [
"MIT"
] | 1 | 2015-12-24T10:57:27.000Z | 2015-12-24T10:57:27.000Z | ne-modules-all.js | nodejs-enterprise/angular-modules | 86d5ffc22c231232f83cbf80214cf358349ed6d6 | [
"MIT"
] | null | null | null | ne-modules-all.js | nodejs-enterprise/angular-modules | 86d5ffc22c231232f83cbf80214cf358349ed6d6 | [
"MIT"
] | null | null | null |
/**
* NE CONTENT EDITORS
* ***************************************************************************************************************************
*/
angular.module('neContentEditors',[])
.factory('neMarkdown', ['$document','NeRemarked', 'neMarked', function($document, ReMarked, marked){
var md = {}; // markdown instance
var reMarkedOptions = {
link_list:false, // render links as references, create link list as appendix
h1_setext:false, // underline h1 headers
h2_setext:false, // underline h2 headers
h_atx_suf:false, // header suffixes (###)
gfm_code:false, // gfm code blocks (```)
li_bullet:"*", // list item bullet style
hr_char:"-", // hr style
indnt_str:" ", // indentation string
bold_char:"*", // char used for strong
emph_char:"_", // char used for em
gfm_del:true, // ~~strikeout~~ for <del>strikeout</del>
gfm_tbls:true, // markdown-extra tables
tbl_edges:false, // show side edges on tables
hash_lnks:false, // anchors w/hash hrefs as links
br_only:false // avoid using " " as line break indicator
};
var reMarker = new ReMarked(reMarkedOptions);
md.parseHTML = function(htmlString){
return reMarker.render(htmlString || '');
};
var markedOptions = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false
};
marked.setOptions(markedOptions);
md.renderHTML = function(mdString){
return marked(mdString || '');
};
// editor methods
function isAlreadyWrapped(selection, before, after){
var beforeSel = selection.inputValue.substring(selection.start - before.length, selection.start);
var afterSel = selection.inputValue.substring(selection.end, selection.end + after.length);
return (beforeSel===before && afterSel===after);
}
function wrapText(before, after, defaultValue, mode){
mode = mode || 'toggle'; // 'add', 'remove'
return function(selection){
var value = '';
before = before || '';
after = after || '';
if(selection && (selection.end > selection.start) && mode!=='replace'){
if(mode==='remove' || (mode==='toggle' && isAlreadyWrapped(selection, before, after))){
// remove before & after
value = selection.inputValue.substring(0, selection.start - before.length) + selection.value + selection.inputValue.substring(selection.end + after.length, selection.inputValue.length);
selection.select(selection.start - before.length, selection.end - before.length);
}
else {
// add before & after
value = before + selection.value + after;
value = selection.inputValue.substring(0, selection.start) + value + selection.inputValue.substring(selection.end, selection.inputValue.length);
selection.select(selection.start + before.length, selection.end + before.length);
}
}
else if(selection && (defaultValue || defaultValue==='')) {
value = selection.inputValue.substring(0, selection.start) + before + defaultValue + after + selection.inputValue.substring(selection.end, selection.inputValue.length);
selection.select(selection.start + before.length, selection.start + defaultValue.length + before.length);
}
return value;
};
}
md.editor = {
// TODO: undo, redo
//undo: formatDoc('undo'),
//redo: formatDoc('redo'),
bold: wrapText('**','**','bold text'),
italic: wrapText('*','*','italic text'),
strikethrough: wrapText('~~','~~','strikethrough text'),
h1: wrapText('\n# ','','headline 1'),
h2: wrapText('\n## ','','headline 2'),
h3: wrapText('\n### ','','headline 3'),
h4: wrapText('\n#### ','','headline 4'),
h5: wrapText('\n##### ','','headline 5'),
h6: wrapText('\n###### ','','headline 6'),
ol: wrapText('\n1. ','','numbered list'),
ul: wrapText('\n- ','','bulleted list'),
indent: wrapText(' ','','','replace'),
dedent: wrapText(' ','','','remove'),
blocquote: wrapText('\n> ','','blocquote text'),
hr: wrapText('\n\n-----\n\n','','','replace'),
link: function(selection, url, name){ // selection, [url || usePrompt]
if(!(url || url==='')){
url = prompt('Please enter link url','http://');
}
if(url) return wrapText('', '[ ' +(name || 'link text')+ ' ]( ' +url+ ' )' ,'','replace')(selection);
else return '';
},
image: function(selection, url){ // selection, [url || usePrompt]
if(!(url || url==='')){
url = prompt('Please enter image url','http://');
}
if(url) return wrapText('', '' ,'','replace')(selection);
else return '';
},
table: function(selection, cols, rows){
cols = parseInt(cols, 10);
rows = parseInt(rows, 10);
if(cols>0 && rows>0) return wrapText('', tableMD(cols, rows),'','add')(selection);
else return selection.inputValue;
}
};
function tableMD(cols, rows){
var mdTable = '\n';
for(var r=1;r<rows+3;r++){
for(var c=1;c<cols+1;c++){
if(c===1) mdTable+='\n';
else mdTable+=' | ';
if(r===1) mdTable+='col '+c;
else if(r===2) mdTable+='-----';
else mdTable+='row '+(r-2);
}
}
//return '\n\ncol 1 | col 2 | col 3' +
//'\n----- | ----- | -----' +
//'\nrow 1 | row 1 | row 1' +
//'\nrow 2 | row 2 | row 2' +
//'\nrow 3 | row 3 | row 3\n';
return mdTable+'\n';
}
return md;
}])
.controller('NeMdCtrl', ['$scope', 'neMarkdown', function($scope, markdown){
$scope.editor = markdown.editor;
}])
.controller('NeWsCtrl', ['$scope', 'neWysiwyg', function($scope, wysiwyg){
$scope.editor = wysiwyg.editor;
}])
.factory('neWysiwyg', ['$document', 'neModals', function($document, modals){
function insertNodeAtSelection(selection, insertNode){
// get current selection
var sel = window.getSelection();
// get the first range of the selection
// (there's almost always only one range)
var range = selection.range;
// deselect everything
sel.removeAllRanges();
// remove content of current selection from document
range.deleteContents();
// get location of current selection
var container = range.startContainer;
var pos = range.startOffset;
// make a new range for the new selection
range=document.createRange();
if (container.nodeType===3 && insertNode.nodeType===3) {
// if we insert text in a textnode, do optimized insertion
container.insertData(pos, insertNode.nodeValue);
// put cursor after inserted text
range.setEnd(container, pos+insertNode.length);
range.setStart(container, pos+insertNode.length);
}
else {
var afterNode;
if (container.nodeType===3) {
// when inserting into a textnode
// we create 2 new textnodes
// and put the insertNode in between
var textNode = container;
container = textNode.parentNode;
var text = textNode.nodeValue;
// text before the split
var textBefore = text.substr(0,pos);
// text after the split
var textAfter = text.substr(pos);
var beforeNode = document.createTextNode(textBefore);
afterNode = document.createTextNode(textAfter);
// insert the 3 new nodes before the old one
container.insertBefore(afterNode, textNode);
container.insertBefore(insertNode, afterNode);
container.insertBefore(beforeNode, insertNode);
// remove the old node
container.removeChild(textNode);
}
else {
// else simply insert the node
afterNode = container.childNodes[pos];
container.insertBefore(insertNode, afterNode);
}
range.setEnd(afterNode, 0);
range.setStart(afterNode, 0);
}
sel.addRange(range);
}
function formatDoc(sCmd, sValue){
return function(selection){
$document[0].execCommand(sCmd, false, sValue);
//selection.select(selection.start, selection.end);
return selection.parent.html();
};
}
var colors = ['#ffffff','#ffccc9','#ffce93','#fffc9e','#ffffc7','#9aff99','#96fffb','#cdffff','#cbcefb','#cfcfcf','#fd6864','#fe996b','#fffe65','#fcff2f','#67fd9a','#38fff8','#68fdff','#9698ed','#c0c0c0','#fe0000','#f8a102','#ffcc67','#f8ff00','#34ff34','#68cbd0','#34cdf9','#6665cd','#9b9b9b','#cb0000','#f56b00','#ffcb2f','#ffc702','#32cb00','#00d2cb','#3166ff','#6434fc','#656565','#9a0000','#ce6301','#cd9934','#999903','#009901','#329a9d','#3531ff','#6200c9','#343434','#680100','#963400','#986536','#646809','#036400','#34696d','#00009b','#303498','#000000','#330001','#643403','#663234','#343300','#013300','#003532','#010066','#340096'];
var fontSizes = [
{name: 'Extra Small', css: 'xx-small', value: '1'},
{name: 'Small', css: 'x-small', value: '2'},
{name: 'Medium', css: 'small', value: '3'},
{name: 'Large', css: 'medium', value: '4'},
{name: 'Extra Large', css: 'large', value: '5'},
{name: 'Huge', css: 'x-large', value: '6'}
];
var editor = {
undo: formatDoc('undo'),
redo: formatDoc('redo'),
bold: formatDoc('bold'),
italic: formatDoc('italic'),
strikethrough: formatDoc('strikeThrough'),
underline: formatDoc('underline'),
quote: formatDoc('quote'),
h1: formatDoc('formatblock','<h1>'),
h2: formatDoc('formatblock','<h2>'),
h3: formatDoc('formatblock','<h3>'),
h4: formatDoc('formatblock','<h4>'),
h5: formatDoc('formatblock','<h5>'),
h6: formatDoc('formatblock','<h6>'),
fontSizes: fontSizes,
fontSize: function(selection, size){
return formatDoc('fontsize', size)(selection);
},
colors: colors,
color: function(selection, color){
return formatDoc('forecolor', color)(selection);
},
bgColor: function(selection, color){
return formatDoc('hilitecolor', color)(selection);
},
justifyLeft: formatDoc('justifyleft'),
justifyCenter: formatDoc('justifycenter'),
justifyRight: formatDoc('justifyright'),
justifyFull: formatDoc('justifyfull'),
ol: formatDoc('insertorderedlist'),
ul: formatDoc('insertunorderedlist'),
indent: formatDoc('indent'),
outdent: formatDoc('outdent'),
unlink: formatDoc('unlink'),
link: function(selection, url, name){ // selection, [url || usePrompt]
if(!(url || url==='')){
url = prompt('Please enter link url','http://');
}
if(url) {
var link = angular.element('<a href="' +url+ '">' +(name || url)+ '</a>');
insertNodeAtSelection(selection, link[0]);
return selection.parent.html();
}
else return '';
},
image: function(selection, url){ // selection, [url || usePrompt]
if(!(url || url==='')){
url = prompt('Please enter image url','http://');
}
if(url) {
var img = angular.element('<img src="' +url+ '">');
insertNodeAtSelection(selection, img[0]);
return selection.parent.html();
}
else return '';
},
table: function(selection, cols, rows){
rows = parseInt(rows,10);
cols = parseInt(cols,10);
var doc = $document[0];
if ((rows > 0) && (cols > 0)) {
var table = doc.createElement('table');
var thead = doc.createElement('thead');
var tbody = doc.createElement('tbody');
var th,tr,td,br;
tr = doc.createElement('tr');
for (var j=0; j < cols; j++) {
th = doc.createElement('th');
th.innerHTML = 'col '+(j+1);
br = doc.createElement('br');
th.appendChild(br);
tr.appendChild(th);
}
thead.appendChild(tr);
for (var i=0; i < rows; i++) {
tr = doc.createElement('tr');
for (var j=0; j < cols; j++) {
td = doc.createElement('td');
td.innerHTML = 'row '+(i+1);
br = doc.createElement('br');
td.appendChild(br);
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(thead);
table.appendChild(tbody);
insertNodeAtSelection(selection, table);
}
return selection.parent.html();
},
hr: formatDoc('inserthorizontalrule')
// TODO:
// blocquote: wrapText('\n> ','','blocquote text'),
};
this.editor = editor;
return this;
}])
.directive('neContenteditable', ['$sce', function($sce) {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
if(!attrs['contenteditable']) element.attr('contenteditable', 'true');
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$apply(read);
});
read(true); // initialize
// Write data to the model
function read(firstTime) {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if(attrs.stripBr && html === '<br>') {
html = '';
}
// set model value from inner html only if value is not already set
if((firstTime && html) || !firstTime) ngModel.$setViewValue(html);
}
}
};
}])
.directive('neSelectionModel', [function(){
return {
restrict:'A',
require:'^ngModel',
scope:{ neSelectionModel:'=' },
link: function(scope, element, attrs, ctrl){
if(element[0].nodeName !== 'TEXTAREA' && attrs.contenteditable!=='true'){
throw new Error('neSelectionModel directive can be used only on <textarea> or contentEditable="true" element');
}
function TextAreaSelection(){
function setSelection(e, start, end){
e.focus();
if(e.setSelectionRange)
e.setSelectionRange(start, end);
else if(e.createTextRange) {
e = e.createTextRange();
e.collapse(true);
e.moveEnd('character', end);
e.moveStart('character', start);
e.select();
}
}
function getSelection(){
var textarea = this;
var selStart = textarea.selectionStart;
var selEnd = textarea.selectionEnd;
scope.$apply(function(){
scope.neSelectionModel = {
parent: angular.element(textarea),
value: textarea.value.substring(selStart, selEnd),
inputValue: textarea.value,
start: selStart,
end: selEnd,
select: function(start, end){
setTimeout(function(){
setSelection(textarea, start, end);
getSelection.call(textarea);
},0);
}
};
});
}
this.setSelection = setSelection;
this.getSelection = getSelection;
}
function closestElement(el, fn) {
while (el) {
if (fn(el)) return el;
el = el.parentNode;
}
}
function ContentEditSelection(element){
function setSelection(e, start, end){
// TODO: implement restore selection on change
//var range = document.createRange();
//range.setStart(e, start);
//range.setEnd(e, end);
////range.collapse(true);
//var sel = window.getSelection();
//sel.removeAllRanges();
//sel.addRange(range);
//e.focus();
// http://stackoverflow.com/questions/16095155/javascript-contenteditable-set-cursor-caret-to-index
// http://stackoverflow.com/questions/1125292/how-to-move-cursor-to-end-of-contenteditable-entity
// or use rangy
}
function getSelection(){
var elm = this;
var doc = closestElement(angular.element(elm)[0], function(elm){ return elm.tagName === 'HTML'; }).parentNode;
var sel = doc.getSelection();
var selStart = sel.getRangeAt(0).startOffset;
var selEnd = sel.getRangeAt(0).endOffset;
var parent = angular.element(elm);
scope.$apply(function(){
scope.neSelectionModel = {
range: sel.getRangeAt(0),
parent: parent,
value: parent.html().substring(selStart, selEnd),
inputValue: parent.html(),
start: selStart,
startElement: sel.getRangeAt(0).startContainer,
end: selEnd,
endElement: sel.getRangeAt(0).endContainer,
select: function(start, end, startElement, endElement){
var startElm = startElement || this.startElement;
var endElm = endElement || this.endElement;
setTimeout(function(){
setSelection(elm, start, end, startElm, endElm);
//getSelection.call(elm);
},0);
}
}
});
}
this.setSelection = setSelection;
this.getSelection = getSelection;
}
var selModel = element[0].nodeName === 'TEXTAREA' ? new TextAreaSelection() : new ContentEditSelection();
element.on('mouseup keyup', selModel.getSelection);
scope.$on('$destroy', function(){
element.unbind('mouseup keyup', selModel.getSelection);
scope.neSelectionModel = null;
});
}
};
}])
.factory('NeRemarked', [function(){
/**
* Copyright (c) 2013, Leon Sorokin
* All rights reserved. (MIT Licensed)
*
* reMarked.js - DOM > markdown
*/
var ReMarked = function(opts) {
var links = [];
var cfg = {
link_list: false, // render links as references, create link list as appendix
// link_near: // cite links immediately after blocks
h1_setext: true, // underline h1 headers
h2_setext: true, // underline h2 headers
h_atx_suf: false, // header suffix (###)
// h_compact: true, // compact headers (except h1)
gfm_code: false, // render code blocks as via ``` delims
li_bullet: "*-+"[0], // list item bullet style
// list_indnt: // indent top-level lists
hr_char: "-_*"[0], // hr style
indnt_str: [" ","\t"," "][0], // indentation string
bold_char: "*_"[0], // char used for strong
emph_char: "*_"[1], // char used for em
gfm_del: true, // ~~strikeout~~ for <del>strikeout</del>
gfm_tbls: true, // markdown-extra tables
tbl_edges: false, // show side edges on tables
hash_lnks: false, // anchors w/hash hrefs as links
br_only: false, // avoid using " " as line break indicator
col_pre: "col ", // column prefix to use when creating missing headers for tables
// comp_style: false, // use getComputedStyle instead of hardcoded tag list to discern block/inline
unsup_tags: { // handling of unsupported tags, defined in terms of desired output style. if not listed, output = outerHTML
// no output
ignore: "script style noscript",
// eg: "<tag>some content</tag>"
inline: "span sup sub i u b center big",
// eg: "\n<tag>\n\tsome content\n</tag>"
// block1: "",
// eg: "\n\n<tag>\n\tsome content\n</tag>"
block2: "div form fieldset dl header footer address article aside figure hgroup section",
// eg: "\n<tag>some content</tag>"
block1c: "dt dd caption legend figcaption output",
// eg: "\n\n<tag>some content</tag>"
block2c: "canvas audio video iframe",
},
tag_remap: { // remap of variants or deprecated tags to internal classes
"i": "em",
"b": "strong"
}
};
extend(cfg, opts);
function extend(a, b) {
if (!b) return a;
for (var i in a) {
if (typeOf(b[i]) == "Object")
extend(a[i], b[i]);
else if (typeof b[i] !== "undefined")
a[i] = b[i];
}
}
function typeOf(val) {
return Object.prototype.toString.call(val).slice(8,-1);
}
function rep(str, num) {
var s = "";
while (num-- > 0)
s += str;
return s;
}
function trim12(str) {
var str = str.replace(/^\s\s*/, ''),
ws = /\s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
}
function lpad(targ, padStr, len) {
return rep(padStr, len - targ.length) + targ;
}
function rpad(targ, padStr, len) {
return targ + rep(padStr, len - targ.length);
}
function otag(tag, e) {
if (!tag) return "";
var buf = "<" + tag;
for (var attr, i = 0; i < e.attributes.length; i++) {
attr = e.attributes.item(i);
buf += " " + attr.nodeName + '="' + attr.nodeValue + '"';
}
return buf + ">";
}
function ctag(tag) {
if (!tag) return "";
return "</" + tag + ">";
}
function pfxLines(txt, pfx) {
return txt.replace(/^/gm, pfx);
}
function nodeName(e) {
return (e.nodeName == "#text" ? "txt" : e.nodeName).toLowerCase();
}
function wrap(str, opts) {
var pre, suf;
if (opts instanceof Array) {
pre = opts[0];
suf = opts[1];
}
else
pre = suf = opts;
pre = pre instanceof Function ? pre.call(this, str) : pre;
suf = suf instanceof Function ? suf.call(this, str) : suf;
return pre + str + suf;
}
// http://stackoverflow.com/a/3819589/973988
function outerHTML(node) {
// if IE, Chrome take the internal method otherwise build one
return node.outerHTML || (
function(n){
var div = document.createElement('div'), h;
div.appendChild( n.cloneNode(true) );
h = div.innerHTML;
div = null;
return h;
})(node);
}
this.render = function(ctr) {
links = [];
if (typeof ctr == "string") {
var htmlstr = ctr;
ctr = document.createElement("div");
ctr.innerHTML = htmlstr;
}
var s = new lib.tag(ctr, null, 0);
var re = s.rend().replace(/^[\t ]+\n/gm, "\n");
if (cfg.link_list && links.length > 0) {
// hack
re += "\n\n";
var maxlen = 0;
// get longest link href with title, TODO: use getAttribute?
for (var y = 0; y < links.length; y++) {
if (!links[y].e.title) continue;
var len = links[y].e.href.length;
if (len && len > maxlen)
maxlen = len;
}
for (var k = 0; k < links.length; k++) {
var title = links[k].e.title ? rep(" ", (maxlen + 2) - links[k].e.href.length) + '"' + links[k].e.title + '"' : "";
re += " [" + (+k+1) + "]: " + (nodeName(links[k].e) == "a" ? links[k].e.href : links[k].e.src) + title + "\n";
}
}
return re.replace(/^[\t ]+\n/gm, "\n");
};
var lib = {};
lib.tag = klass({
wrap: "",
lnPfx: "", // only block
lnInd: 0, // only block
init: function(e, p, i)
{
this.e = e;
this.p = p;
this.i = i;
this.c = [];
this.tag = nodeName(e);
this.initK();
},
initK: function()
{
var i;
if (this.e.hasChildNodes()) {
// inline elems allowing adjacent whitespace text nodes to be rendered
var inlRe = cfg.unsup_tags.inline, n, name;
// if no thead exists, detect header rows or make fake cols
if (nodeName(this.e) == "table") {
if (this.e.hasChildNodes() && !this.e.tHead) {
var thead = document.createElement("thead");
var tbody0 = this.e.tBodies[0],
row0 = tbody0.rows[0],
cell0 = row0.cells[0];
if (nodeName(cell0) == "th")
thead.appendChild(row0);
else {
var hcell,
i = 0,
len = row0.cells.length,
hrow = thead.insertRow();
while (i++ < len) {
hcell = document.createElement("th");
hcell.textContent = cfg.col_pre + i;
hrow.appendChild(hcell);
}
}
this.e.insertBefore(thead, tbody0);
}
}
for (i in this.e.childNodes) {
if (!/\d+/.test(i)) continue;
n = this.e.childNodes[i];
name = nodeName(n);
// remap of variants
if (name in cfg.tag_remap)
name = cfg.tag_remap[name];
// ignored tags
if (cfg.unsup_tags.ignore.test(name))
continue;
// empty whitespace handling
if (name == "txt" && /^\s+$/.test(n.textContent)) {
// ignore if first or last child (trim)
if (i == 0 || i == this.e.childNodes.length - 1)
continue;
// only ouput when has an adjacent inline elem
var prev = this.e.childNodes[i-1],
next = this.e.childNodes[i+1];
if (prev && !nodeName(prev).match(inlRe) || next && !nodeName(next).match(inlRe))
continue;
}
var wrap = null;
if (!lib[name]) {
var unsup = cfg.unsup_tags;
if (unsup.inline.test(name))
name = "tinl";
else if (unsup.block2.test(name))
name = "tblk";
else if (unsup.block1c.test(name))
name = "ctblk";
else if (unsup.block2c.test(name)) {
name = "ctblk";
wrap = ["\n\n", ""];
}
else
name = "rawhtml";
}
var node = new lib[name](n, this, this.c.length);
if (wrap)
node.wrap = wrap;
if (node instanceof lib.a && n.href || node instanceof lib.img) {
node.lnkid = links.length;
links.push(node);
}
this.c.push(node);
}
}
},
rend: function()
{
return this.rendK().replace(/\n{3,}/gm, "\n\n"); // can screw up pre and code :(
},
rendK: function()
{
var n, buf = "";
for (var i = 0; i < this.c.length; i++) {
n = this.c[i];
buf += (n.bef || "") + n.rend() + (n.aft || "");
}
return buf.replace(/^\n+|\n+$/, "");
}
});
lib.blk = lib.tag.extend({
wrap: ["\n\n", ""],
wrapK: null,
tagr: false,
lnInd: null,
init: function(e, p ,i) {
this.supr(e,p,i);
// kids indented
if (this.lnInd === null) {
if (this.p && this.tagr && this.c[0] instanceof lib.blk)
this.lnInd = 4;
else
this.lnInd = 0;
}
// kids wrapped?
if (this.wrapK === null) {
if (this.tagr && this.c[0] instanceof lib.blk)
this.wrapK = "\n";
else
this.wrapK = "";
}
},
rend: function()
{
return wrap.call(this, (this.tagr ? otag(this.tag, this.e) : "") + wrap.call(this, pfxLines(pfxLines(this.rendK(), this.lnPfx), rep(" ", this.lnInd)), this.wrapK) + (this.tagr ? ctag(this.tag) : ""), this.wrap);
},
rendK: function()
{
var kids = this.supr();
// remove min uniform leading spaces from block children. marked.js's list outdent algo sometimes leaves these
if (this.p instanceof lib.li) {
var repl = null, spcs = kids.match(/^[\t ]+/gm);
if (!spcs) return kids;
for (var i = 0; i < spcs.length; i++) {
if (repl === null || spcs[i][0].length < repl.length)
repl = spcs[i][0];
}
return kids.replace(new RegExp("^" + repl), "");
}
return kids;
}
});
lib.tblk = lib.blk.extend({tagr: true});
lib.cblk = lib.blk.extend({wrap: ["\n", ""]});
lib.ctblk = lib.cblk.extend({tagr: true});
lib.inl = lib.tag.extend({
rend: function()
{
return wrap.call(this, this.rendK(), this.wrap);
}
});
lib.tinl = lib.inl.extend({
tagr: true,
rend: function()
{
return otag(this.tag, this.e) + wrap.call(this, this.rendK(), this.wrap) + ctag(this.tag);
}
});
lib.p = lib.blk.extend({
rendK: function() {
return this.supr().replace(/^\s+/gm, "");
}
});
lib.list = lib.blk.extend({
expn: false,
wrap: [function(){return this.p instanceof lib.li ? "\n" : "\n\n";}, ""]
});
lib.ul = lib.list.extend({});
lib.ol = lib.list.extend({});
lib.li = lib.cblk.extend({
wrap: ["\n", function(kids) {
return this.p.expn || kids.match(/\n{2}/gm) ? "\n" : ""; // || this.kids.match(\n)
}],
wrapK: [function() {
return this.p.tag == "ul" ? cfg.li_bullet + " " : (this.i + 1) + ". ";
}, ""],
rendK: function() {
return this.supr().replace(/\n([^\n])/gm, "\n" + cfg.indnt_str + "$1");
}
});
lib.hr = lib.blk.extend({
wrap: ["\n\n", rep(cfg.hr_char, 3)]
});
lib.h = lib.blk.extend({});
lib.h_setext = lib.h.extend({});
cfg.h1_setext && (lib.h1 = lib.h_setext.extend({
wrapK: ["", function(kids) {
return "\n" + rep("=", kids.length);
}]
}));
cfg.h2_setext && (lib.h2 = lib.h_setext.extend({
wrapK: ["", function(kids) {
return "\n" + rep("-", kids.length);
}]
}));
lib.h_atx = lib.h.extend({
wrapK: [
function(kids) {
return rep("#", this.tag[1]) + " ";
},
function(kids) {
return cfg.h_atx_suf ? " " + rep("#", this.tag[1]) : "";
}
]
});
!cfg.h1_setext && (lib.h1 = lib.h_atx.extend({}));
!cfg.h2_setext && (lib.h2 = lib.h_atx.extend({}));
lib.h3 = lib.h_atx.extend({});
lib.h4 = lib.h_atx.extend({});
lib.h5 = lib.h_atx.extend({});
lib.h6 = lib.h_atx.extend({});
lib.a = lib.inl.extend({
lnkid: null,
rend: function() {
var kids = this.rendK(),
href = this.e.getAttribute("href"),
title = this.e.title ? ' "' + this.e.title + '"' : "";
if (!href || href == kids || href[0] == "#" && !cfg.hash_lnks)
return kids;
if (cfg.link_list)
return "[" + kids + "] [" + (this.lnkid + 1) + "]";
return "[" + kids + "](" + href + title + ")";
}
});
// almost identical to links, maybe merge
lib.img = lib.inl.extend({
lnkid: null,
rend: function() {
var kids = this.e.alt,
src = this.e.getAttribute("src");
if (cfg.link_list)
return "![" + kids + "] [" + (this.lnkid + 1) + "]";
var title = this.e.title ? ' "'+ this.e.title + '"' : "";
return "";
}
});
lib.em = lib.inl.extend({wrap: cfg.emph_char});
lib.del = cfg.gfm_del ? lib.inl.extend({wrap: "~~"}) : lib.tinl.extend();
lib.br = lib.inl.extend({
wrap: ["", function() {
var end = cfg.br_only ? "<br>" : " ";
// br in headers output as html
return this.p instanceof lib.h ? "<br>" : end + "\n";
}]
});
lib.strong = lib.inl.extend({wrap: rep(cfg.bold_char, 2)});
lib.blockquote = lib.blk.extend({
lnPfx: "> ",
rend: function() {
return this.supr().replace(/>[ \t]$/gm, ">");
}
});
// can render with or without tags
lib.pre = lib.blk.extend({
tagr: true,
wrapK: "\n",
lnInd: 0
});
// can morph into inline based on context
lib.code = lib.blk.extend({
tagr: false,
wrap: "",
wrapK: function(kids) {
return kids.indexOf("`") !== -1 ? "``" : "`"; // esc double backticks
},
lnInd: 0,
init: function(e, p, i) {
this.supr(e, p, i);
if (this.p instanceof lib.pre) {
this.p.tagr = false;
if (cfg.gfm_code) {
var cls = this.e.getAttribute("class");
cls = (cls || "").split(" ")[0];
if (cls.indexOf("lang-") === 0) // marked uses "lang-" prefix now
cls = cls.substr(5);
this.wrapK = ["```" + cls + "\n", "\n```"];
}
else {
this.wrapK = "";
this.p.lnInd = 4;
}
}
}
});
lib.table = cfg.gfm_tbls ? lib.blk.extend({
cols: [],
init: function(e, p, i) {
this.supr(e, p, i);
this.cols = [];
},
rend: function() {
// run prep on all cells to get max col widths
for (var tsec = 0; tsec < this.c.length; tsec++)
for (var row = 0; row < this.c[tsec].c.length; row++)
for (var cell = 0; cell < this.c[tsec].c[row].c.length; cell++)
this.c[tsec].c[row].c[cell].prep();
return this.supr();
}
}) : lib.tblk.extend();
lib.thead = cfg.gfm_tbls ? lib.cblk.extend({
wrap: ["\n", function(kids) {
var buf = "";
for (var i = 0; i < this.p.cols.length; i++) {
var col = this.p.cols[i],
al = col.a[0] == "c" ? ":" : " ",
ar = col.a[0] == "r" || col.a[0] == "c" ? ":" : " ";
buf += (i == 0 && cfg.tbl_edges ? "|" : "") + al + rep("-", col.w) + ar + (i < this.p.cols.length-1 || cfg.tbl_edges ? "|" : "");
}
return "\n" + trim12(buf);
}]
}) : lib.ctblk.extend();
lib.tbody = cfg.gfm_tbls ? lib.cblk.extend() : lib.ctblk.extend();
lib.tfoot = cfg.gfm_tbls ? lib.cblk.extend() : lib.ctblk.extend();
lib.tr = cfg.gfm_tbls ? lib.cblk.extend({
wrapK: [cfg.tbl_edges ? "| " : "", cfg.tbl_edges ? " |" : ""],
}) : lib.ctblk.extend();
lib.th = cfg.gfm_tbls ? lib.inl.extend({
guts: null,
// TODO: DRY?
wrap: [function() {
var col = this.p.p.p.cols[this.i],
spc = this.i == 0 ? "" : " ",
pad, fill = col.w - this.guts.length;
switch (col.a[0]) {
case "r": pad = rep(" ", fill); break;
case "c": pad = rep(" ", Math.floor(fill/2)); break;
default: pad = "";
}
return spc + pad;
}, function() {
var col = this.p.p.p.cols[this.i],
edg = this.i == this.p.c.length - 1 ? "" : " |",
pad, fill = col.w - this.guts.length;
switch (col.a[0]) {
case "r": pad = ""; break;
case "c": pad = rep(" ", Math.ceil(fill/2)); break;
default: pad = rep(" ", fill);
}
return pad + edg;
}],
prep: function() {
this.guts = this.rendK(); // pre-render
this.rendK = function() {return this.guts};
var cols = this.p.p.p.cols;
if (!cols[this.i])
cols[this.i] = {w: null, a: ""}; // width and alignment
var col = cols[this.i];
col.w = Math.max(col.w || 0, this.guts.length);
if (this.e.align)
col.a = this.e.align;
},
}) : lib.ctblk.extend();
lib.td = lib.th.extend();
lib.txt = lib.inl.extend({
initK: function()
{
this.c = this.e.textContent.split(/^/gm);
},
rendK: function()
{
var kids = this.c.join("").replace(/\r/gm, "");
// this is strange, cause inside of code, inline should not be processed, but is?
if (!(this.p instanceof lib.code || this.p instanceof lib.pre)) {
kids = kids
.replace(/^\s*#/gm,"\\#")
.replace(/\*/gm,"\\*");
}
if (this.i == 0)
kids = kids.replace(/^\n+/, "");
if (this.i == this.p.c.length - 1)
kids = kids.replace(/\n+$/, "");
return kids;
}
});
lib.rawhtml = lib.blk.extend({
initK: function()
{
this.guts = outerHTML(this.e);
},
rendK: function()
{
return this.guts;
}
});
// compile regexes
for (var i in cfg.unsup_tags)
cfg.unsup_tags[i] = new RegExp("^(?:" + (i == "inline" ? "a|em|strong|img|code|del|" : "") + cfg.unsup_tags[i].replace(/\s/g, "|") + ")$");
};
return ReMarked;
}])
.factory('neMarked', [function(){
/**
* marked - a markdown parser
* Copyright (c) 2011-2013, Christopher Jeffrey. (MIT Licensed)
* https://github.com/chjj/marked
*/
;(function() {
/**
* Block-Level Grammar
*/
var block = {
newline: /^\n+/,
code: /^( {4}[^\n]+\n*)+/,
fences: noop,
hr: /^( *[-*_]){3,} *(?:\n+|$)/,
heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
nptable: noop,
lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
blockquote: /^( *>[^\n]+(\n[^\n]+)*\n*)+/,
list: /^( *)(bull) [\s\S]+?(?:hr|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
html: /^ *(?:comment|closed|closing) *(?:\n{2,}|\s*$)/,
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
table: noop,
paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
text: /^[^\n]+/
};
block.bullet = /(?:[*+-]|\d+\.)/;
block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block.item = replace(block.item, 'gm')
(/bull/g, block.bullet)
();
block.list = replace(block.list)
(/bull/g, block.bullet)
('hr', /\n+(?=(?: *[-*_]){3,} *(?:\n+|$))/)
();
block._tag = '(?!(?:'
+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
+ '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
+ '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|@)\\b';
block.html = replace(block.html)
('comment', /<!--[\s\S]*?-->/)
('closed', /<(tag)[\s\S]+?<\/\1>/)
('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
(/tag/g, block._tag)
();
block.paragraph = replace(block.paragraph)
('hr', block.hr)
('heading', block.heading)
('lheading', block.lheading)
('blockquote', block.blockquote)
('tag', '<' + block._tag)
('def', block.def)
();
/**
* Normal Block Grammar
*/
block.normal = merge({}, block);
/**
* GFM Block Grammar
*/
block.gfm = merge({}, block.normal, {
fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/,
paragraph: /^/
});
block.gfm.paragraph = replace(block.paragraph)
('(?!', '(?!'
+ block.gfm.fences.source.replace('\\1', '\\2') + '|'
+ block.list.source.replace('\\1', '\\3') + '|')
();
/**
* GFM + Tables Block Grammar
*/
block.tables = merge({}, block.gfm, {
nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
});
/**
* Block Lexer
*/
function Lexer(options) {
this.tokens = [];
this.tokens.links = {};
this.options = options || marked.defaults;
this.rules = block.normal;
if (this.options.gfm) {
if (this.options.tables) {
this.rules = block.tables;
} else {
this.rules = block.gfm;
}
}
}
/**
* Expose Block Rules
*/
Lexer.rules = block;
/**
* Static Lex Method
*/
Lexer.lex = function(src, options) {
var lexer = new Lexer(options);
return lexer.lex(src);
};
/**
* Preprocessing
*/
Lexer.prototype.lex = function(src) {
src = src
.replace(/\r\n|\r/g, '\n')
.replace(/\t/g, ' ')
.replace(/\u00a0/g, ' ')
.replace(/\u2424/g, '\n');
return this.token(src, true);
};
/**
* Lexing
*/
Lexer.prototype.token = function(src, top) {
var src = src.replace(/^ +$/gm, '')
, next
, loose
, cap
, bull
, b
, item
, space
, i
, l;
while (src) {
// newline
if (cap = this.rules.newline.exec(src)) {
src = src.substring(cap[0].length);
if (cap[0].length > 1) {
this.tokens.push({
type: 'space'
});
}
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
cap = cap[0].replace(/^ {4}/gm, '');
this.tokens.push({
type: 'code',
text: !this.options.pedantic
? cap.replace(/\n+$/, '')
: cap
});
continue;
}
// fences (gfm)
if (cap = this.rules.fences.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'code',
lang: cap[2],
text: cap[3]
});
continue;
}
// heading
if (cap = this.rules.heading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[1].length,
text: cap[2]
});
continue;
}
// table no leading pipe (gfm)
if (top && (cap = this.rules.nptable.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i].split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// lheading
if (cap = this.rules.lheading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[2] === '=' ? 1 : 2,
text: cap[1]
});
continue;
}
// hr
if (cap = this.rules.hr.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'hr'
});
continue;
}
// blockquote
if (cap = this.rules.blockquote.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'blockquote_start'
});
cap = cap[0].replace(/^ *> ?/gm, '');
// Pass `top` to keep the current
// "toplevel" state. This is exactly
// how markdown.pl works.
this.token(cap, top);
this.tokens.push({
type: 'blockquote_end'
});
continue;
}
// list
if (cap = this.rules.list.exec(src)) {
src = src.substring(cap[0].length);
bull = cap[2];
this.tokens.push({
type: 'list_start',
ordered: bull.length > 1
});
// Get each top-level item.
cap = cap[0].match(this.rules.item);
next = false;
l = cap.length;
i = 0;
for (; i < l; i++) {
item = cap[i];
// Remove the list item's bullet
// so it is seen as the next token.
space = item.length;
item = item.replace(/^ *([*+-]|\d+\.) +/, '');
// Outdent whatever the
// list item contains. Hacky.
if (~item.indexOf('\n ')) {
space -= item.length;
item = !this.options.pedantic
? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
: item.replace(/^ {1,4}/gm, '');
}
// Determine whether the next list item belongs here.
// Backpedal if it does not belong in this list.
if (this.options.smartLists && i !== l - 1) {
b = block.bullet.exec(cap[i + 1])[0];
if (bull !== b && !(bull.length > 1 && b.length > 1)) {
src = cap.slice(i + 1).join('\n') + src;
i = l - 1;
}
}
// Determine whether item is loose or not.
// Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
// for discount behavior.
loose = next || /\n\n(?!\s*$)/.test(item);
if (i !== l - 1) {
next = item.charAt(item.length - 1) === '\n';
if (!loose) loose = next;
}
this.tokens.push({
type: loose
? 'loose_item_start'
: 'list_item_start'
});
// Recurse.
this.token(item, false);
this.tokens.push({
type: 'list_item_end'
});
}
this.tokens.push({
type: 'list_end'
});
continue;
}
// html
if (cap = this.rules.html.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: this.options.sanitize
? 'paragraph'
: 'html',
pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',
text: cap[0]
});
continue;
}
// def
if (top && (cap = this.rules.def.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.links[cap[1].toLowerCase()] = {
href: cap[2],
title: cap[3]
};
continue;
}
// table (gfm)
if (top && (cap = this.rules.table.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i]
.replace(/^ *\| *| *\| *$/g, '')
.split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// top-level paragraph
if (top && (cap = this.rules.paragraph.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'paragraph',
text: cap[1].charAt(cap[1].length - 1) === '\n'
? cap[1].slice(0, -1)
: cap[1]
});
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
// Top-level should never reach here.
src = src.substring(cap[0].length);
this.tokens.push({
type: 'text',
text: cap[0]
});
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return this.tokens;
};
/**
* Inline-Level Grammar
*/
var inline = {
escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
url: noop,
tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
link: /^!?\[(inside)\]\(href\)/,
reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
br: /^ {2,}\n(?!\s*$)/,
del: noop,
text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
};
inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
inline.link = replace(inline.link)
('inside', inline._inside)
('href', inline._href)
();
inline.reflink = replace(inline.reflink)
('inside', inline._inside)
();
/**
* Normal Inline Grammar
*/
inline.normal = merge({}, inline);
/**
* Pedantic Inline Grammar
*/
inline.pedantic = merge({}, inline.normal, {
strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
});
/**
* GFM Inline Grammar
*/
inline.gfm = merge({}, inline.normal, {
escape: replace(inline.escape)('])', '~|])')(),
url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
del: /^~~(?=\S)([\s\S]*?\S)~~/,
text: replace(inline.text)
(']|', '~]|')
('|', '|https?://|')
()
});
/**
* GFM + Line Breaks Inline Grammar
*/
inline.breaks = merge({}, inline.gfm, {
br: replace(inline.br)('{2,}', '*')(),
text: replace(inline.gfm.text)('{2,}', '*')()
});
/**
* Inline Lexer & Compiler
*/
function InlineLexer(links, options) {
this.options = options || marked.defaults;
this.links = links;
this.rules = inline.normal;
this.renderer = this.options.renderer || new Renderer;
if (!this.links) {
throw new
Error('Tokens array requires a `links` property.');
}
if (this.options.gfm) {
if (this.options.breaks) {
this.rules = inline.breaks;
} else {
this.rules = inline.gfm;
}
} else if (this.options.pedantic) {
this.rules = inline.pedantic;
}
}
/**
* Expose Inline Rules
*/
InlineLexer.rules = inline;
/**
* Static Lexing/Compiling Method
*/
InlineLexer.output = function(src, links, options) {
var inline = new InlineLexer(links, options);
return inline.output(src);
};
/**
* Lexing/Compiling
*/
InlineLexer.prototype.output = function(src) {
var out = ''
, link
, text
, href
, cap;
while (src) {
// escape
if (cap = this.rules.escape.exec(src)) {
src = src.substring(cap[0].length);
out += cap[1];
continue;
}
// autolink
if (cap = this.rules.autolink.exec(src)) {
src = src.substring(cap[0].length);
if (cap[2] === '@') {
text = cap[1].charAt(6) === ':'
? this.mangle(cap[1].substring(7))
: this.mangle(cap[1]);
href = this.mangle('mailto:') + text;
} else {
text = escape(cap[1]);
href = text;
}
out += this.renderer.link(href, null, text);
continue;
}
// url (gfm)
if (cap = this.rules.url.exec(src)) {
src = src.substring(cap[0].length);
text = escape(cap[1]);
href = text;
out += this.renderer.link(href, null, text);
continue;
}
// tag
if (cap = this.rules.tag.exec(src)) {
src = src.substring(cap[0].length);
out += this.options.sanitize
? escape(cap[0])
: cap[0];
continue;
}
// link
if (cap = this.rules.link.exec(src)) {
src = src.substring(cap[0].length);
out += this.outputLink(cap, {
href: cap[2],
title: cap[3]
});
continue;
}
// reflink, nolink
if ((cap = this.rules.reflink.exec(src))
|| (cap = this.rules.nolink.exec(src))) {
src = src.substring(cap[0].length);
link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
link = this.links[link.toLowerCase()];
if (!link || !link.href) {
out += cap[0].charAt(0);
src = cap[0].substring(1) + src;
continue;
}
out += this.outputLink(cap, link);
continue;
}
// strong
if (cap = this.rules.strong.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.strong(this.output(cap[2] || cap[1]));
continue;
}
// em
if (cap = this.rules.em.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.em(this.output(cap[2] || cap[1]));
continue;
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.codespan(escape(cap[2], true));
continue;
}
// br
if (cap = this.rules.br.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.br();
continue;
}
// del (gfm)
if (cap = this.rules.del.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.del(this.output(cap[1]));
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
src = src.substring(cap[0].length);
out += escape(this.smartypants(cap[0]));
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return out;
};
/**
* Compile Link
*/
InlineLexer.prototype.outputLink = function(cap, link) {
var href = escape(link.href)
, title = link.title ? escape(link.title) : null;
if (cap[0].charAt(0) !== '!') {
return this.renderer.link(href, title, this.output(cap[1]));
} else {
return this.renderer.image(href, title, escape(cap[1]));
}
};
/**
* Smartypants Transformations
*/
InlineLexer.prototype.smartypants = function(text) {
if (!this.options.smartypants) return text;
return text
// em-dashes
.replace(/--/g, '\u2014')
// opening singles
.replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
// closing singles & apostrophes
.replace(/'/g, '\u2019')
// opening doubles
.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
// closing doubles
.replace(/"/g, '\u201d')
// ellipses
.replace(/\.{3}/g, '\u2026');
};
/**
* Mangle Links
*/
InlineLexer.prototype.mangle = function(text) {
var out = ''
, l = text.length
, i = 0
, ch;
for (; i < l; i++) {
ch = text.charCodeAt(i);
if (Math.random() > 0.5) {
ch = 'x' + ch.toString(16);
}
out += '&#' + ch + ';';
}
return out;
};
/**
* Renderer
*/
function Renderer() {}
Renderer.prototype.code = function(code, lang) {
if (!lang) {
return '<pre><code>'
+ escape(code, true)
+ '\n</code></pre>';
}
return '<pre><code class="'
+ 'lang-'
+ lang
+ '">'
+ escape(code)
+ '\n</code></pre>\n';
};
Renderer.prototype.blockquote = function(quote) {
return '<blockquote>\n' + quote + '</blockquote>\n';
};
Renderer.prototype.html = function(html) {
return html;
};
Renderer.prototype.heading = function(text, level, raw, options) {
return '<h'
+ level
+ '>'
+ text
+ '</h'
+ level
+ '>\n';
};
Renderer.prototype.hr = function() {
return '<hr>\n';
};
Renderer.prototype.list = function(body, ordered) {
var type = ordered ? 'ol' : 'ul';
return '<' + type + '>\n' + body + '</' + type + '>\n';
};
Renderer.prototype.listitem = function(text) {
return '<li>' + text + '</li>\n';
};
Renderer.prototype.paragraph = function(text) {
return '<p>' + text + '</p>\n';
};
Renderer.prototype.table = function(header, body) {
return '<table>\n'
+ '<thead>\n'
+ header
+ '</thead>\n'
+ '<tbody>\n'
+ body
+ '</tbody>\n'
+ '</table>\n';
};
Renderer.prototype.tablerow = function(content) {
return '<tr>\n' + content + '</tr>\n';
};
Renderer.prototype.tablecell = function(content, flags) {
var type = flags.header ? 'th' : 'td';
var tag = flags.align
? '<' + type + ' style="text-align:' + flags.align + '">'
: '<' + type + '>';
return tag + content + '</' + type + '>\n';
};
// span level renderer
Renderer.prototype.strong = function(text) {
return '<strong>' + text + '</strong>';
};
Renderer.prototype.em = function(text) {
return '<em>' + text + '</em>';
};
Renderer.prototype.codespan = function(text) {
return '<code>' + text + '</code>';
};
Renderer.prototype.br = function() {
return '<br>';
};
Renderer.prototype.del = function(text) {
return '<del>' + text + '</del>';
};
Renderer.prototype.link = function(href, title, text) {
var out = '<a href="' + href + '"';
if (title) {
out += ' title="' + title + '"';
}
out += '>' + text + '</a>';
return out;
};
Renderer.prototype.image = function(href, title, text) {
var out = '<img src="' + href + '" alt="' + text + '"';
if (title) {
out += ' title="' + title + '"';
}
out += '>';
return out;
};
/**
* Parsing & Compiling
*/
function Parser(options) {
this.tokens = [];
this.token = null;
this.options = options || marked.defaults;
this.options.renderer = this.options.renderer || new Renderer;
this.renderer = this.options.renderer;
}
/**
* Static Parse Method
*/
Parser.parse = function(src, options, renderer) {
var parser = new Parser(options, renderer);
return parser.parse(src);
};
/**
* Parse Loop
*/
Parser.prototype.parse = function(src) {
this.inline = new InlineLexer(src.links, this.options, this.renderer);
this.tokens = src.reverse();
var out = '';
while (this.next()) {
out += this.tok();
}
return out;
};
/**
* Next Token
*/
Parser.prototype.next = function() {
return this.token = this.tokens.pop();
};
/**
* Preview Next Token
*/
Parser.prototype.peek = function() {
return this.tokens[this.tokens.length - 1] || 0;
};
/**
* Parse Text Tokens
*/
Parser.prototype.parseText = function() {
var body = this.token.text;
while (this.peek().type === 'text') {
body += '\n' + this.next().text;
}
return this.inline.output(body);
};
/**
* Parse Current Token
*/
Parser.prototype.tok = function() {
switch (this.token.type) {
case 'space': {
return '';
}
case 'hr': {
return this.renderer.hr();
}
case 'heading': {
return this.renderer.heading(
this.inline.output(this.token.text),
this.token.depth
);
}
case 'code': {
return this.renderer.code(this.token.text, this.token.lang);
}
case 'table': {
var header = ''
, body = ''
, i
, row
, cell
, flags
, j;
// header
cell = '';
for (i = 0; i < this.token.header.length; i++) {
flags = { header: true, align: this.token.align[i] };
cell += this.renderer.tablecell(
this.inline.output(this.token.header[i]),
{ header: true, align: this.token.align[i] }
);
}
header += this.renderer.tablerow(cell);
for (i = 0; i < this.token.cells.length; i++) {
row = this.token.cells[i];
cell = '';
for (j = 0; j < row.length; j++) {
cell += this.renderer.tablecell(
this.inline.output(row[j]),
{ header: false, align: this.token.align[j] }
);
}
body += this.renderer.tablerow(cell);
}
return this.renderer.table(header, body);
}
case 'blockquote_start': {
var body = '';
while (this.next().type !== 'blockquote_end') {
body += this.tok();
}
return this.renderer.blockquote(body);
}
case 'list_start': {
var body = ''
, ordered = this.token.ordered;
while (this.next().type !== 'list_end') {
body += this.tok();
}
return this.renderer.list(body, ordered);
}
case 'list_item_start': {
var body = '';
while (this.next().type !== 'list_item_end') {
body += this.token.type === 'text'
? this.parseText()
: this.tok();
}
return this.renderer.listitem(body);
}
case 'loose_item_start': {
var body = '';
while (this.next().type !== 'list_item_end') {
body += this.tok();
}
return this.renderer.listitem(body);
}
case 'html': {
var html = !this.token.pre && !this.options.pedantic
? this.inline.output(this.token.text)
: this.token.text;
return this.renderer.html(html);
}
case 'paragraph': {
return this.renderer.paragraph(this.inline.output(this.token.text));
}
case 'text': {
return this.renderer.paragraph(this.parseText());
}
}
};
/**
* Helpers
*/
function escape(html, encode) {
return html
.replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function replace(regex, opt) {
regex = regex.source;
opt = opt || '';
return function self(name, val) {
if (!name) return new RegExp(regex, opt);
val = val.source || val;
val = val.replace(/(^|[^\[])\^/g, '$1');
regex = regex.replace(name, val);
return self;
};
}
function noop() {}
noop.exec = noop;
function merge(obj) {
var i = 1
, target
, key;
for (; i < arguments.length; i++) {
target = arguments[i];
for (key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
obj[key] = target[key];
}
}
}
return obj;
}
/**
* Marked
*/
function marked(src, opt, callback) {
if (callback || typeof opt === 'function') {
if (!callback) {
callback = opt;
opt = null;
}
opt = merge({}, marked.defaults, opt || {});
var highlight = opt.highlight
, tokens
, pending
, i = 0;
try {
tokens = Lexer.lex(src, opt)
} catch (e) {
return callback(e);
}
pending = tokens.length;
var done = function() {
var out, err;
try {
out = Parser.parse(tokens, opt);
} catch (e) {
err = e;
}
opt.highlight = highlight;
return err
? callback(err)
: callback(null, out);
};
return done();
}
try {
if (opt) opt = merge({}, marked.defaults, opt);
return Parser.parse(Lexer.lex(src, opt), opt);
} catch (e) {
e.message += '\nPlease report this to https://github.com/chjj/marked.';
if ((opt || marked.defaults).silent) {
return '<p>An error occured:</p><pre>'
+ escape(e.message + '', true)
+ '</pre>';
}
throw e;
}
}
/**
* Options
*/
marked.options =
marked.setOptions = function(opt) {
merge(marked.defaults, opt);
return marked;
};
marked.defaults = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: false,
silent: false,
smartypants: false,
renderer: new Renderer
};
/**
* Expose
*/
marked.Parser = Parser;
marked.parser = Parser.parse;
marked.Renderer = Renderer;
marked.Lexer = Lexer;
marked.lexer = Lexer.lex;
marked.InlineLexer = InlineLexer;
marked.inlineLexer = InlineLexer.output;
marked.parse = marked;
if (typeof exports === 'object') {
module.exports = marked;
} else if (typeof define === 'function' && define.amd) {
define(function() { return marked; });
} else {
this.marked = marked;
}
}).call(function() {
return this || (typeof window !== 'undefined' ? window : global);
}());
return marked;
}]);
/*!
* klass: a classical JS OOP façade
* https://github.com/ded/klass
* License MIT (c) Dustin Diaz & Jacob Thornton 2012
*/
!function(a,b){typeof define=="function"?define(b):typeof module!="undefined"?module.exports=b():this[a]=b()}("klass",function(){function f(a){return j.call(g(a)?a:function(){},a,1)}function g(a){return typeof a===c}function h(a,b,c){return function(){var d=this.supr;this.supr=c[e][a];var f=b.apply(this,arguments);return this.supr=d,f}}function i(a,b,c){for(var f in b)b.hasOwnProperty(f)&&(a[f]=g(b[f])&&g(c[e][f])&&d.test(b[f])?h(f,b[f],c):b[f])}function j(a,b){function c(){}function l(){this.init?this.init.apply(this,arguments):(b||h&&d.apply(this,arguments),j.apply(this,arguments))}c[e]=this[e];var d=this,f=new c,h=g(a),j=h?a:this,k=h?{}:a;return l.methods=function(a){return i(f,a,d),l[e]=f,this},l.methods.call(l,k).prototype.constructor=l,l.extend=arguments.callee,l[e].implement=l.statics=function(a,b){return a=typeof a=="string"?function(){var c={};return c[a]=b,c}():a,i(this,a,d),this},l}var a=this,b=a.klass,c="function",d=/xyz/.test(function(){xyz})?/\bsupr\b/:/.*/,e="prototype";return f.noConflict=function(){return a.klass=b,this},a.klass=f,f});
/**
* NE DIRECTIVES
* ***************************************************************************************************************************
*/
angular.module('neDirectives',['neObject'])
.directive('neInitData', [ function() {
return {
priority: 1000,
restrict: 'AE',
compile: function(){
return {
pre: function(scope, element, attrs){
if(attrs.neInitData) {
scope.$eval((attrs.neInitAs ? attrs.neInitAs+'=' : '')+attrs.neInitData);
}
else if(element.html()){
scope.$eval((attrs.neInitAs ? attrs.neInitAs+'=' : '')+element.html());
}
if(attrs.neInitDone) {
scope.$eval(attrs.neInitDone);
}
}
};
}
};
}])
.service('neKeyPressHandler', [function(){
return function(attrName, keyCode, preventDefault){
return function(scope, element, attrs) {
var target;
if(element[0].nodeName === 'INPUT') target = element;
else target = angular.element(document);
target.bind('keydown keypress', keyPressed);
function keyPressed(event) {
if(event.which === keyCode) {
scope.$apply(function (){
scope.$eval(attrs[ attrName ]);
});
if(preventDefault) event.preventDefault();
}
}
scope.$on('$destroy', function(){
target.unbind('keydown keypress', keyPressed);
});
};
};
}])
.directive('neKeypressEnter', [ 'neKeyPressHandler', function(keyPressHandler) {
return keyPressHandler('neKeypressEnter', 13, true);
}])
.directive('neKeypressEscape', [ 'neKeyPressHandler', function(keyPressHandler) {
return keyPressHandler('neKeypressEscape', 27, true);
}])
.directive('neKeypressRight', [ 'neKeyPressHandler', function(keyPressHandler) {
return keyPressHandler('neKeypressRight', 39);
}])
.directive('neKeypressLeft', [ 'neKeyPressHandler', function(keyPressHandler) {
return keyPressHandler('neKeypressLeft', 37);
}])
.directive('neKeypressUp', [ 'neKeyPressHandler', function(keyPressHandler) {
return keyPressHandler('neKeypressUp', 38);
}])
.directive('neKeypressDown', [ 'neKeyPressHandler', function(keyPressHandler) {
return keyPressHandler('neKeypressDown', 40);
}])
.directive('neKeypressBackspace', [ 'neKeyPressHandler', function(keyPressHandler) {
return keyPressHandler('neKeypressBackspace', 8);
}])
.directive('neLoadingStart', ['$timeout', function($timeout){
return function(scope, element, attrs) {
if(element[0].nodeName !== 'IMG') return;
attrs.$observe('src', function(){
$timeout(function (){
scope.$eval(attrs.neLoadingStart);
});
});
};
}])
.directive('neLoadingEnd', ['$timeout', function($timeout){
return function(scope, element, attrs) {
if(element[0].nodeName !== 'IMG') return;
element.bind('load', onLoad);
function onLoad(event) {
$timeout(function (){
scope.$eval(attrs.neLoadingEnd);
},5);
event.preventDefault();
}
scope.$on('$destroy', function(){
element.unbind('load', onLoad);
});
};
}])
.directive('neStatusIcon', [function() {
return {
restrict: 'A',
compile: function(element, attrs){
// create template
var template = '<div class="right-inner-addon">' +
(attrs.neStatusIcon!=='reverse' ? '<i class="fa fa-check text-success" ng-show="' +element.attr('ng-model')+ '"></i>' : '') +
(attrs.neStatusIcon==='reverse' ? '<i class="fa fa-times text-danger" ng-show="!' +element.attr('ng-model')+ '"></i>' : '') +
'</div>';
// wrap element
element.wrap(template);
// prevent infinite wrapping
element.removeAttr('status-icon');
}
};
}])
.directive('neMatchHrefPath', [ '$window','$location', function($window, $location) {
return {
priority:-100,
link: function (scope, element, attrs) {
var className = scope.$eval(attrs.neMatchHrefPath) || attrs.neMatchHrefPath;
if(!className) return;
var href;
if(attrs.href) {
try { href = scope.$eval(attrs.href); }
catch(err){ href = attrs.href; }
}
else {
var link = element.find('a')[0];
href = link ? link.getAttribute('href') : null;
if(link && href) {
try { href = scope.$eval(href.replace('{{','').replace('}}','')); }
catch(err){ href = href; }
}
}
if(href && href.indexOf('#')===-1) {
href = href.replace(/^http:/g,'').replace(/^https:/g,'').replace($window.location.hostname,'').replace(/\/+/g,'/');
if(($window.location.pathname+'/').match(new RegExp('^' +href+ '[\/\#\?].*'))) {
element.addClass(className);
}
else element.removeClass(className);
}
else if(href) {
href = href.match(/^([^\#]*)\#([^\#\?]*).*$/); // /catalog#/muzi
href = href ? href[href.length-1] : null;
if(href) scope.$on('$locationChangeSuccess', checkMatch);
checkMatch();
}
function checkMatch(){
if(($location.path()+'/').match(new RegExp('^' +href+ '[\/\#\?].*'))) {
element.addClass(className);
}
else element.removeClass(className);
}
}
};
}])
.directive('neFile', [function() {
return {
restrict: 'E',
template: '<input type="file" />',
replace: true,
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
var listener = function() {
scope.$apply(function() {
if(attr.multiple || attr.multiple===''){
var files = [];
for(var i=0;i<element[0].files.length;i++) files.push(element[0].files[i]);
ctrl.$setViewValue(files);
}
else {
ctrl.$setViewValue(element[0].files[0]);
}
});
};
element.attr('accept', attr.accept);
element.bind('change', listener);
}
};
}])
.constant('neFileDropAreaSystemFiles',[
'thumbs.db',
'desktop.ini',
'.DS_Store'
])
.service('neFileDropArea', ['$q', 'neFileDropAreaSystemFiles', function ($q, systemFiles) {
this.bind = function (elm, afterDrop, readAs, onError) { // readAsDataURL, readAsText, readAsArrayBuffer
var dropbox = elm[0];
var dragover = false;
// Setup drag and drop handlers.
dropbox.addEventListener('dragenter', addDragClass, false);
dropbox.addEventListener('dragover', addDragClass, false);
dropbox.addEventListener('dragleave', removeDragClass, false);
dropbox.addEventListener('drop', onDrop, false);
function stopDefault(e) {
e.stopPropagation();
e.preventDefault();
}
function addDragClass(e) {
stopDefault(e);
if (!dragover) {
elm.addClass('ne-dragover');
dragover = true;
}
}
function removeDragClass(e) {
stopDefault(e);
elm.removeClass('ne-dragover');
dragover = false;
}
function getFilePromise(entry) {
return $q(function (resolve, reject) {
entry.file(resolve, reject);
});
}
function readEntriesPromise(directoryReader) {
return $q(function (resolve, reject) {
directoryReader.readEntries(resolve, reject);
});
}
function getFilesRecursively(entry, filterOSTempFiles) {
if (entry.isFile) {
// filter OS temp metadata files
if(filterOSTempFiles && systemFiles.indexOf(entry.name) > -1) return;
else return getFilePromise(entry);
}
else if(entry.isDirectory) {
return readEntriesPromise(entry.createReader()).then(function (entries) {
var promises = [], filePromise;
for (var i = 0; i < entries.length; i++) {
filePromise = getFilesRecursively(entries[i], true);
if(filePromise) promises.push(filePromise);
}
return $q.all(promises).then(function (arrays) {
return [].concat.apply([], arrays);
});
});
}
}
function getFilesPromise(e) {
var items = e.dataTransfer.items;
if (!items) return $q.resolve(e.dataTransfer.files);
if (!items[0].webkitGetAsEntry) return $q.resolve(e.dataTransfer.files);
var files = [];
var promises = [], filePromise;
for (var i = 0; i < items.length; i++) {
filePromise = getFilesRecursively(items[i].webkitGetAsEntry());
if(filePromise) promises.push(filePromise);
}
return $q.all(promises).then(function (arrays) {
files = [].concat.apply([], arrays);
return $q.resolve(files);
})
}
function onDrop(e) {
removeDragClass(e);
getFilesPromise(e).then(function (files) {
var readFileSize = 0;
var file = files[0];
if (!file) return; // nothing is dropped
readFileSize += file.fileSize;
if (readAs) {
var reader = new FileReader();
reader.onerror = function (e) {
alert('Cannot read file: ' + e.target.error);
};
// Create a closure to capture the file information.
reader.onload = (function (aFile) {
return function (evt) {
afterDrop(evt.target.result);
};
})(file);
// readAsDataURL, readAsText, readAsArrayBuffer, e.g. read image file as a data url
reader[readAs](file);
}
else afterDrop(files);
})
.catch(onError);
}
return {
unbind: function () {
dragover = null;
// Remove drag and drop handlers.
dropbox.removeEventListener('dragenter', addDragClass, false);
dropbox.removeEventListener('dragover', addDragClass, false);
dropbox.removeEventListener('dragleave', removeDragClass, false);
dropbox.removeEventListener('drop', onDrop, false);
}
};
};
return this;
}])
.directive('neFileDropArea', ['neFileDropArea', function (fileDropArea) {
return {
restrict: 'A',
scope: {
'onError': '&neFileDropOnError',
'onDrop': '&neFileDrop',
'onDropAlias1': '&neFilesDrop',
'onDropAlias2': '&ondrop'
},
link: function (scope, element, attrs, ctrl) {
var typeRegexp = attrs.neFileDropArea ? new RegExp(attrs.neFileDropArea) : null;
var area = fileDropArea.bind(element, function(files) {
var filesArray = [];
for (var i = 0; i < files.length; i++) {
if (!typeRegexp || files[i].type.match(typeRegexp)) filesArray.push(files[i]);
}
if(filesArray.length) {
scope.onDrop({ files: filesArray });
scope.onDropAlias1({ files: filesArray });
scope.onDropAlias2({ files: filesArray });
}
},
null,
function(error) {
scope.onError({ error: error });
});
scope.$on('$destroy', area.unbind);
}
};
}])
.directive('neCopy',[function() {
return {
restrict: 'A',
link: function(scope, element, attrs, ctrl) {
var original = scope.$eval(attrs.neCopy);
var propName = scope.alias || attrs.neCopyAlias || '$copy';
function rollback(){
scope[ propName ] = angular.copy(original);
}
function commit(){
var copy = scope[ propName ];
// replace all original properties by copy
for(var key in copy) {
if(copy.hasOwnProperty(key) && !(key[0]==='$' && key[1]==='$')){ // dont copy $$ prefixed props
original[key] = copy[key];
}
}
}
scope.$rollback = rollback;
scope.$commit = commit;
original.$commit = commit;
original.$rollback = rollback;
scope.$rollback();
}
};
}])
.directive('neFormChange',[function() {
return {
restrict: 'A',
require:'^form',
link: function(scope, element, attrs, formCtrl) {
scope.$watch(function(){
return formCtrl.$valid;
}, function(isValid){
scope.$valid = scope.$isValid = isValid;
scope.$eval(attrs.neFormChange);
});
}
};
}])
.directive('neBindHtml',['$sce', function($sce) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
attrs.$observe('neBindHtml', function(htmlText){
element.html(htmlText);
});
}
};
}])
.filter('html', ['$sce', function ($sce) {
return function (text) {
return $sce.trustAsHtml(text);
};
}])
.filter('trusted', ['$sce', function ($sce) { // alias for html
return function (text) {
return $sce.trustAsHtml(text);
};
}]);/**
* NE DRAG DROP
* ***************************************************************************************************************************
*/
angular.module('neDragdrop',[])
.directive('draggable', [function() {
return function(scope, element, attrs) {
// this gives us the native JS object
var el = element[0];
function preventDrag(e) {
e.preventDefault();
return false;
}
function addDragClass(e) {
var dragData;
// exec drag start expression
if(attrs.drag) dragData = scope.$apply(attrs.drag);
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', JSON.stringify(dragData || new Date()));
this.classList.add('dragged');
return false;
}
function removeDragClass(e) {
this.classList.remove('dragged');
// exec drag end expression
if(attrs.dragEnd) scope.$apply(attrs.dragEnd);
return false;
}
if(attrs.draggable === 'false'){
el.addEventListener('dragstart', preventDrag);
scope.$on('$destroy', function(){
el.removeEventListener('dragstart', preventDrag);
});
}
else {
el.draggable = true;
el.addEventListener('dragstart', addDragClass);
el.addEventListener('dragend', removeDragClass);
scope.$on('$destroy', function(){
el.removeEventListener('dragstart', addDragClass);
el.removeEventListener('dragend', removeDragClass);
});
}
};
}])
.directive('droppable', [function() {
return function(scope, element, attrs) {
// again we need the native object
var el = element[0];
function dragover(e) {
e.dataTransfer.dropEffect = 'move';
// allows us to drop
if (e.preventDefault) e.preventDefault();
if(!attrs.droppable || (attrs.droppable && scope.$apply(attrs.droppable))) {
this.classList.add('dragover');
}
return false;
}
el.addEventListener('dragover', dragover);
function dragenter(e) {
if(!attrs.droppable || (attrs.droppable && scope.$apply(attrs.droppable))) {
this.classList.add('dragover');
}
return false;
}
el.addEventListener('dragenter', dragenter);
function dragleave(e) {
this.classList.remove('dragover');
return false;
}
el.addEventListener('dragleave', dragleave);
function drop(e) {
// Stops some browsers from redirecting.
if(e.stopPropagation) e.stopPropagation();
e.preventDefault();
this.classList.remove('dragover');
var data;
try {
data = JSON.parse(e.dataTransfer.getData('text')+'');
}
catch(err){}
// call the passed drop function
if(attrs.drop && (!attrs.droppable || (attrs.droppable && scope.$eval(attrs.droppable)))) {
scope.$eval(attrs.drop, { data:data });
scope.$apply();
}
return false;
}
el.addEventListener('drop', drop);
scope.$on('$destroy', function(){
el.removeEventListener('dragover', dragover);
el.removeEventListener('dragenter', dragenter);
el.removeEventListener('dragleave', dragleave);
el.removeEventListener('drop', drop);
});
};
}]);
/**
* NE GRID
* ***************************************************************************************************************************
*/
/*
* GRID Constructor
*
* Usage:
* var myGrid = new Grid({
* id: 'products',
* restResource: products,
* loadOnChange:true,
* limit:20
* });
*
*/
angular.module('neGrid',['neObject','neLocal'])
.run(['$templateCache', function($templateCache) {
$templateCache.put('neGrid/pagination.html',
'<div ng-if="!paginationDisabled" class="row text-{{fontSize}}">' +
' <div class="col-xs-12 col-sm-9 col-md-10 text-center">' +
' <div class="btn-group btn-group-{{size}}">'+
' <button class="btn btn-default" ng-disabled="grid.prevDisabled" ng-click="grid.setPage(\'first\')"><span class="fa fa-fast-backward"></span></button>' +
' <button class="btn btn-default" ng-disabled="grid.prevDisabled" ng-click="grid.setPage(\'prev\')"><span class="fa fa-backward"></span></button>' +
' </div>'+
' <span>'+
' <span ng-if="grid.pagesCount"> {{\'page\'|translate}} </span>' +
' <input type="number" class="input-{{size}} width-sm" ng-model="grid.pagination.page" min="1" max="{{grid.pagination.pages||\'\'}}" ne-keypress-enter="grid.setPage(grid.pagination.page)">' +
' <span ng-if="grid.pagesCount"> {{\'of\'|translate}} {{grid.pagesCount}} </span>' +
' <span ng-if="grid.pagesCount" class="hidden-xs">({{grid.pagination.count}} {{\'items\'|translate}})</span>'+
' </span>' +
' <div class="btn-group btn-group-{{size}}">'+
' <button class="btn btn-default" ng-disabled="grid.nextDisabled" ng-click="grid.setPage(\'next\')"><span class="fa fa-forward"></span></button>' +
' <button class="btn btn-default" ng-disabled="grid.nextDisabled || !grid.pagesCount" ng-click="grid.setPage(\'last\')"><span class="fa fa-fast-forward"></span></button>' +
' </div>' +
' </div>' +
' <div class="col-sm-3 col-md-2 text-right hidden-xs">' +
' <div class="input-group">'+
' <input class="input-{{size}} width-sm" type="number" ng-model="grid.limit" ne-keypress-enter="grid.setPage(\'first\')" min="1" max="{{grid.maxLimit}}">' +
' <span class="input-group-btn">' +
' <button class="btn btn-default btn-{{size}}" ng-click="grid.setPage(\'first\')"><span class="fa fa-refresh"></span></button>' +
' </span>' +
' </div>' +
' </div>' +
'</div>');
}])
.directive('neGridPagination', [function(){
return {
templateUrl:'neGrid/pagination.html',
scope:{ grid:'=neGridPagination' },
link: function(scope, elm, attrs){
scope.size = attrs.neGridPaginationSize || 'sm';
scope.fontSize = 'base';
if(scope.size === 'xs') scope.fontSize = 'sm';
if(scope.size === 'lg') scope.fontSize = 'lg';
}
};
}])
.directive('neGridUpdateBlur', ['$timeout','neObject', function($timeout, object){
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
//scope:{ blurUpdate:'=' },
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
var dirty_class = attrs.dirtyClass || 'is-dirty';
if(dirty_class==='ng-dirty')
throw new Error('dirtyClass cannot be equal to "ng-dirty", it is angular reserved class name');
var names = (attrs.neGridUpdateBlur || '').split(',');
var gridName = names[0] || 'grid';
var itemName = names[1] || 'item';
var grid = object.deepGet(scope, gridName);
var item = object.deepGet(scope, itemName);
if(!grid) throw new Error('Scope has not grid with name "'+gridName+'"');
if(!item) throw new Error('Scope has not grid item with name "'+itemName+'"');
var isDirty = false;
function setDirty(dirty){
isDirty = dirty;
if(isDirty) element.addClass(dirty_class);
else element.removeClass(dirty_class);
}
function reset(){
scope.$apply(function(){
ngModel.$setViewValue('firstValue');
setDirty(false);
});
}
function afterUpdate(updatedItem){
setPristine();
if(attrs.afterUpdate) scope.$eval(attrs.gridAfterUpdate);
}
function setPristine(){
setDirty(false);
firstValue = ngModel.$viewValue;
}
element.on('blur', function(){
if(isDirty) grid.updateItem(item, afterUpdate);
});
element.bind("keydown keypress", function (event) {
if(event.which === 13 && isDirty && element[0].nodeName==='INPUT') {
grid.updateItem(item, afterUpdate);
event.preventDefault();
}
//if(event.which === 27 && isDirty) {
// reset();
// event.preventDefault();
//}
});
// catch the init value
var firstValue = '';
scope.$watch(ngModel.$viewValue, function(){
firstValue = ngModel.$viewValue;
});
ngModel.$viewChangeListeners.push(function(){
if(firstValue !== ngModel.$viewValue) setDirty(true);
else setDirty(false);
});
}
};
}])
.factory('NeGrid',['$timeout','neObject', function($timeout, object){
function Grid(settings){
var args = [ {}, Grid.defaults ];
for(var i=0;i<arguments.length;i++) args.push(arguments[i]);
settings = angular.merge.apply(angular, args);
// init values
this.id = settings.id;
this.idKey = settings.idKey || 'id';
this.defaultLimit = settings.defaultLimit || 10;
this.limit = settings.limit || this.defaultLimit; //default page size
this.maxLimit = settings.maxLimit || 100; //max page size
this.defaultQuery = settings.defaultQuery || {};
this.defaultSort = settings.defaultSort || {};
this.interceptLoad = settings.interceptLoad || settings.beforeLoad || settings.loadInterceptor;
this.onQuery = settings.onQueryChange || settings.onQuery || settings.onFilter;
this.onLoad = settings.onLoad; // onLoad(items, pagination)
this.onFill = settings.onFill || settings.onData;
this.onSelect = settings.onSelect;
this.onFocus = settings.onFocus;
this.onUpdate = settings.onUpdate;
this.onCreate = settings.onCreate;
this.onRemove = settings.onRemove;
this.resource = settings.restResource || settings.resource;
this.getResourceMethod = settings.getResourceMethod || settings.resourceMethod || (typeof this.resource === 'function' ? this.resource : null) || getResourceMethod; // getResourceMethod(opType, item)
this.autoLoad = settings.autoLoad || settings.loadOnChange;
this.multiSelect = settings.multiSelect || settings.multiselect || false;
// if(!this.resource) throw new Error('neGrid: restResource is undefined');
// if(!this.id) throw new Error('neGrid: grid must have an id');
// defaults
this.silentMode = false;
this.pagination = { page: settings.page || this.defaultQuery.$page || 1 };
this.page = this.pagination.page;
this.pagesCount = 1;
this.query = object.extend('data', {}, settings.query || {}, { $page:this.page, $limit:this.limit }, this.defaultQuery);
this.sort = object.extend('data', {}, this.defaultSort || {}, settings.sort || {});
this.items = [];
this.disabled = true; // default grid state is disabled
// private
this.doSilent = this.doSilent;
// exposed methods
this.fillItems = fillItems; // fillItems(items, pagination)
this.addItems = appendItems; // appendItems(items)
this.addItem = appendItems; // appendItems(items)
this.appendItems = appendItems; // appendItems(items)
this.appendItem = appendItems; // appendItems(items)
this.prependItems = prependItems; // prependItems(items)
this.prependItem = prependItems; // prependItems(items)
this.setSort = setSort; // setSort(sortObj)
this.setSortSilent = doSilent('setSort');
this.setSortBy = setSortBy; // setSortBy(sortBy, sortDir)
this.setSortBySilent = doSilent('setSortBy');
this.updateQuery = updateQuery; // updateQuery(query)
this.updateQuerySilent = doSilent('updateQuery');
this.setQuery = setQuery; // setQuery(filterQuery)
this.setQuerySilent = doSilent('setQuery');
this.setFilter = setQuery; // setQuery(filterQuery)
this.setFilterSilent = doSilent('setQuery');
this.setPage = setPage; // setPage('first','last','next','prev','refresh')
this.setPageSilent = doSilent('setPage');
this.load = load; // load(cb)
this.refresh = load; // load(cb)
this.createItem = createItem; // createItem(item)
this.updateItem = updateItem; // updateItem(item)
this.refreshItem = refreshItem; // refreshItem(item)
this.removeItem = removeItem; // removeItem(item)
this.selectItem = selectItem; // selectItem(item, forceSelected)
this.selectAll = selectAll; // selectAll(forceSelected)
this.toggleItemSelection = toggleItemSelection; // toggleItemSelection(item)
this.toggleSelection = toggleSelection; // toggleSelection()
this.focusItem = focusItem; // focusItem(item)
this.getFocusedItem = getFocusedItem; // getFocusedItem()
this.getSelectedItems = getSelectedItems; // getSelectedItems()
this.clearSelection = clearSelection; // clearSelection()
return this;
}
// global default settings
Grid.defaults = {};
function doSilent(propName){
return function(){
var grid = this;
grid.silentMode = true;
grid[propName].apply(grid, arguments);
grid.silentMode = false;
return grid;
};
}
function getResourceMethod(opType, item){
if(!this.resource) throw new Error('NeGrid: resource is undefined');
// opType = 'find','create','update','remove'
return this.resource[opType];
}
// methods definitions
function fillItems(items, pagination){
var grid = this;
pagination = pagination || {};
grid.items = items;
grid.pagination = pagination;
grid.pagesCount = Math.ceil(pagination.count / grid.limit);
if(pagination.page <= 1) grid.prevDisabled = true;
else grid.prevDisabled = !pagination.prev;
if(pagination.spage >= grid.pagesCount) grid.nextDisabled = true;
else grid.nextDisabled = !pagination.next;
if(typeof grid.onFill === 'function' && !grid.silentMode) grid.onFill(grid.items, grid.pagination, grid.query);
return this;
}
function appendItems(items){
items = Array.isArray(items) ? items : [items];
Array.prototype.push.apply(this.items, items);
return this;
}
function prependItems(items){
items = Array.isArray(items) ? items : [items];
Array.prototype.unshift.apply(this.items, items);
return this;
}
function setSort(sortObj, cb){
var grid = this;
grid.sort = sortObj;
return grid.setPage('first', cb);
}
function setSortBy(sortBy, sortDir){
if(!sortBy) return;
var sort = {};
sort[sortBy] = sortDir || this.sortDir;
return this.setSort(sort);
}
function load(cb, errCb){
var grid = this;
if(!grid.interceptLoad || (grid.interceptLoad && grid.interceptLoad(grid.query)!==false)){
grid.disabled = true;
grid.lastFindReqId = grid.getResourceMethod('find')(grid.query, function(items, pagination){
if(grid.lastFindReqId && grid.lastFindReqId !== this.requestId) return;
if(typeof grid.onLoad === 'function') grid.onLoad(items, pagination);
grid.fillItems(items, pagination);
if(cb) cb();
grid.disabled = false;
}, errCb);
}
return grid;
}
function setPage(pageNum, cb, newQuery){
if(typeof arguments[0] === 'function'){
cb = arguments[0];
pageNum = null;
}
var grid = this;
var page;
if(typeof pageNum==='number') page = pageNum;
else if(pageNum==='first') page = 1;
else if(pageNum==='next') page = grid.pagination.page + 1;
else if(pageNum==='last') page = grid.pagesCount;
else if(pageNum==='prev') page = grid.pagination.page - 1;
else if(pageNum==='refresh' || pageNum === null) page = grid.pagination.page || 1;
else page = 1;
if(grid.pagesCount && page > grid.pagesCount && typeof pageNum !== 'number') page = grid.pagesCount+0;
if(page <= 0) page = 1;
grid.page = page;
grid.updateQuery(newQuery);
if(grid.autoLoad && !grid.silentMode) return grid.load(cb);
else if(cb) cb();
return grid;
}
function setQuery(newQuery, cb){
var grid = this;
grid.query = object.extend('data', {}, grid.defaultQuery || {}, newQuery || {});
grid.setPage(grid.query.$page || 'first', cb, newQuery);
return grid;
}
function updateQuery(newQuery){
var grid = this;
newQuery = newQuery || {};
grid.page = newQuery.$page || grid.page;
grid.limit = newQuery.$limit || grid.limit;
grid.sort = newQuery.$sort || grid.sort;
if(grid.page && (typeof grid.page !== 'number' || grid.page <= 0)) grid.page = 1;
// check limit boundaries
if(!grid.limit || grid.limit < 0) grid.limit = grid.defaultLimit;
else if(grid.limit > grid.maxLimit) grid.limit = grid.maxLimit;
var query = object.extend('data', {}, newQuery, { $limit:grid.limit, $sort:{}, $page:grid.page });
// merge sort with defaultSort
if(grid.sort) query.$sort = grid.sort;
query.$sort = object.extend('data', {}, grid.defaultSort || {}, query.$sort || {});
if(Object.keys(query.$sort).length===0) delete query.$sort;
delete grid.query.$page;
delete grid.query.$sort;
delete grid.query.$limit;
grid.query = object.extend('data', query, grid.query || {});
if(grid.onQuery && !grid.silentMode) grid.onQuery(grid.query);
return grid;
}
function createItem(item, cb, errCb){
var grid = this;
grid.getResourceMethod('create', item)(item, function(data){
grid.setPage('first', cb);
if(typeof grid.onCreate === 'function') grid.onCreate(item);
if(!grid.autoLoad) grid.load(cb);
}, errCb);
return grid;
}
function updateItem(item, cb, errCb){
var grid = this;
grid.getResourceMethod('update', item)(item, function(data){
var index = grid.items.indexOf(item);
var oldItem = angular.copy(item);
grid.items[ index ] = object.extend('data', grid.items[ index ], data);
if(grid.onUpdate) grid.onUpdate(grid.items[ index ], oldItem);
if(cb) cb(grid.items[ index ]);
}, errCb);
return grid;
}
function refreshItem(item, cb, errCb){
var grid = this;
var idKey = grid.idKey;
var idQuery = {};
idQuery[ idKey ] = object.deepGet(item, idKey);
grid.getResourceMethod('find', item)(idQuery, function(items, pagination){
var index = grid.items.indexOf(item);
grid.items[ index ] = object.extend('data', grid.items[ index ], items[0]);
if(cb) cb(grid.items[ index ]);
}, errCb);
return grid;
}
function removeItem(item, cb, errCb){
var grid = this;
grid.getResourceMethod('remove',item)(item, function(data){
grid.items.splice(grid.items.indexOf(item), 1);
if(grid.onRemove) grid.onRemove(item);
if(cb) cb(item);
}, errCb);
return grid;
}
function focusItem(item){
var grid = this;
if(item.$focused === true) return grid; // row is already focused
for(var i=0;i<grid.items.length;i++) { // clear all focused items
grid.items[i].$focused = false;
}
item.$focused = true;
grid.focusedItem = item;
if(typeof grid.onFocus === 'function') grid.onFocus(item);
return grid;
}
function getFocusedItem(){
var grid = this;
for(var i=0;i<grid.items.length;i++) {
if(grid.items[i].$focused === true) return grid.items[i];
}
}
function selectItem(item, forceSelected){
var grid = this;
if(!grid.multiSelect){
for(var i=0;i<grid.items.length;i++){
delete grid.items[i].$selected;
}
}
if(typeof forceSelected === 'boolean') item.$selected = forceSelected;
else item.$selected = !item.$selected;
if(typeof grid.onSelect === 'function') grid.onSelect(item);
return grid;
}
function toggleItemSelection(item){
return this.selectItem(item);
}
function selectAll(forceSelected){
var grid = this;
if(!grid.multiSelect) return grid;
for(var i=0;i<grid.items.length;i++) grid.selectItem(grid.items[i], forceSelected);
return grid;
}
function toggleSelection(){
return this.selectAll();
}
function clearSelection(){
var grid = this;
for(var i=0;i<grid.items.length;i++){
delete grid.items[i].$selected;
}
return grid;
}
function getSelectedItems(){
var grid = this;
var selectedRows = [];
for(var i=0; i<grid.items.length; i++) {
if(grid.items[i].$selected===true) selectedRows.push(grid.items[i]);
}
return selectedRows;
}
Grid.define =
Grid.create = function(settings){
return new Grid(settings);
};
return Grid;
}]);
/**
* NE LOADING
* ***************************************************************************************************************************
*/
angular.module('neLoading', [])
.constant('neLoadingDebounce', 350) // delay of changes apply, if response will be received in lower interval than debounce, loading will not emit changes
.constant('neLoadingEndDelay', 300) // delay of loading end, loading message hide will be delayed
.factory('neLoading',['$timeout','neLoadingDebounce','neLoadingEndDelay', function($timeout, debounce, endDelay) {
var service = {
requestCount: 0,
isLoading: function() {
return service.requestCount > 0;
},
statusTimeout:null,
status:0,
prevStatus:0,
lastStart: new Date().getTime(),
statusListeners:[],
fireStatusListeners: function(status){
for(var i=0;i<service.statusListeners.length;i++){
(function(i){
$timeout(function(){
service.statusListeners[i](status!==undefined ? status : service.status);
},0,false);
})(i);
}
},
setStatus: function(percent) {
if(service.statusTimeout) $timeout.cancel(service.statusTimeout);
if(percent < 0) return;
service.prevStatus = service.status+0;
service.status = percent;
var now = new Date().getTime();
if(service.prevStatus === 0 && percent > 0) service.lastStart = now;
if((now - service.lastStart) > debounce) service.fireStatusListeners(service.status);
if(service.status > 0 && service.status < 99){
service.statusTimeout = $timeout(function(){
service.setStatus(randomIncrement(service.status));
}, debounce, false);
}
else if(service.status >= 100){
service.status = 0;
service.prevStatus = 0;
service.statusTimeout = $timeout(function(){
service.setStatus(0);
service.fireStatusListeners(0);
}, endDelay, false);
}
},
reqStarted: function(debugNotes){
// if(service.statusTimeout) $timeout.cancel(service.statusTimeout);
if(service.status===0) service.setStatus(1);
//$timeout(function(){
service.requestCount++;
if(debugNotes) console.log(debugNotes, service.requestCount, service.status);
//}, 0, false);
},
reqEnded: function(debugNotes){
//$timeout(function(){
if(service.requestCount>0) service.requestCount--;
if(debugNotes) console.log(debugNotes, service.requestCount, service.status);
if(service.requestCount === 0) service.setStatus(100);
//}, 0, false);
}
};
function randomIncrement(status){
var rnd = 0;
var stat = status / 100;
if (stat >= 0 && stat < 0.25) {
// Start out between 3 - 6% increments
rnd = (Math.random() * (5 - 3 + 1) + 3) / 100;
} else if (stat >= 0.25 && stat < 0.65) {
// increment between 0 - 3%
rnd = (Math.random() * 3) / 100;
} else if (stat >= 0.65 && stat < 0.9) {
// increment between 0 - 2%
rnd = (Math.random() * 2) / 100;
} else if (stat >= 0.9 && stat < 0.99) {
// finally, increment it .5 %
rnd = 0.005;
} else {
// after 99%, don't increment:
rnd = 0;
}
return status + Math.ceil(100*rnd);
}
return service;
}])
.factory('neLoadingInterceptor',['$q', '$cacheFactory', 'neLoading', function($q, $cacheFactory, loading){
function isCached(config) {
if(!config) return false;
var cache;
if (config.method !== 'GET' || config.cache === false) {
config.cached = false;
return false;
}
if (config.cache === true){ //&& defaults.cache === undefined) {
cache = $cacheFactory.get('$http');
}
else {
cache = config.cache;
}
var cached = cache !== undefined ?
cache.get(config.url) !== undefined : false;
if (config.cached !== undefined && cached !== config.cached) {
return config.cached;
}
config.cached = cached;
return cached;
}
return {
request: function(config) {
// Check to make sure this request hasn't already been cached and that
// the requester didn't explicitly ask us to ignore this request:
if (!config.ignoreLoading && !isCached(config)) {
loading.reqStarted();
}
return config;
},
response: function(response) {
if(!response.config.ignoreLoading && !isCached(response.config)) {
loading.reqEnded();
}
return response;
},
responseError: function(rejection) {
if (!rejection.config.ignoreLoading && !isCached(rejection.config)) {
loading.reqEnded();
}
return $q.reject(rejection);
}
};
}])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('neLoadingInterceptor');
}])
.controller('NeLoadingCtrl',['$scope', 'neLoading', function($scope, loading) {
loading.statusListeners.push(function(status){
$scope.status = status;
$scope.loading = status > 0;
$scope.$digest();
});
}]);
/**
* NE LOCAL
* ***************************************************************************************************************************
*/
/*
* very simple localization service and translate filter
*
* config example:
*
* app.config(['localProvider', function(localProvider){
localProvider.language('sk-sk');
localProvider.set('sk-sk',{
name:'Meno',
surname:'Priezvisko',
dateTime:'Datum'
});
}])
*/
angular.module('neLocal',[])
.provider('neLocal',[function(){
var currentLangId = 'default';
var langs = { default:{ common:{} } };
var currentPath = '/';
this.translate = function(original){
if(original===undefined || original===null) return '';
var orig = original+'';
var lang = langs[currentLangId] || {};
lang.common = lang.common || {};
return (lang[currentPath] ? lang[currentPath][orig] : null) || lang.common[orig] ||
(langs.default[currentPath] ? langs.default[currentPath][orig] : null) || langs.default.common[orig] || orig || '';
};
this.setPath = function(path){
currentPath = path;
};
this.language = function(langId){
if(langId) currentLangId = langId;
return currentLangId;
};
this.languages = function(langId){
return langId ? langs[langId] : langs;
};
this.getLanguageId = function(){
return currentLangId;
};
this.getLanguagePath = function(){
return currentPath;
};
this.set = this.translations = function(langId, path, original, translated){
langs[langId] = langs[langId] || {};
langs[langId].common = langs[langId].common || {};
if(arguments.length===4){
langs[langId][path] = langs[langId][path] || {};
langs[langId][path][original] = translated;
}
else if(arguments.length===3 && angular.isObject(original)){
langs[langId][path] = langs[langId][path] || {};
angular.extend(langs[langId][path], original);
}
else if(arguments.length===3){
translated = arguments[2];
original = arguments[1];
langs[langId].common[original] = translated;
}
else if(arguments.length===2){
original = arguments[1];
var hasCommon = angular.isObject(original.common);
angular.extend(hasCommon ? langs[langId] : langs[langId].common, original);
}
else throw new Error('Wrong arguments');
};
this.$get = function() {
return this;
};
return this;
}])
.run(['$rootScope', '$location', 'neLocal', function($rootScope, $location, local){
$rootScope.$on('$routeChangeStart', function(evt, absNewUrl, absOldUrl){
local.setPath($location.path());
});
}])
.filter('neTranslate', ['neLocal', function(local) {
return function(input, expression, comparator){
return local.translate(input);
};
}])
// alias for neTranslate
.filter('translate', ['neLocal', function(local) {
return function(input, expression, comparator){
return local.translate(input);
};
}]);
/**
* NE MENU
* ***************************************************************************************************************************
*/
angular.module('neMenu', [ ])
.factory('NeMenu', ['$document', '$timeout', function($document, $timeout){
var _menus = {};
function Menu(id, opts){
if(typeof id !== 'string') throw new Error('NeMenu: menu ID is required !');
if(_menus[ id ]) return _menus[ id ];
var defaultOpts = {
id: id,
// onChange: function(key, value){},
// onSelect: function(item, oldItem){}
};
var menu = angular.merge(this, defaultOpts, opts || {});
menu.items = [
//{
// id:'myid', icon:'fa fa-pencil', name:'Dashboard', href:'#/pencil',
// children:[
// { name:'sub item 1', href:'#/pencil/1' },
// { name:'sub item 1', href:'#/pencil/2' }
// ]
//}
//{ icon:'fa fa-file-text', name:'Content Management', href:'#/cms', },
//{ icon:'fa fa-users', name:'Users Management', href:'#/users', }
];
// if(menu.cookies.use) {
// menu.state = $cookies.getObject('menu:'+menu.id) || {};
// }
_menus[ id ] = menu;
return menu;
}
Menu.prototype.set = function(key, value){
var menu = this;
menu[ key ] = value;
if(menu.onChange) menu.onChange(key, value);
return menu;
};
Menu.prototype.toggle = function(key){
var menu = this;
menu[ key ] = !menu[ key ];
if(menu.onChange) menu.onChange(key, menu[ key ]);
return menu;
};
Menu.prototype.select =
Menu.prototype.selectItem = function(item, $event){
var menu = this;
var prevSelected;
if($event && (item.onSelect || item.children && item.children.length)) {
$event.preventDefault();
if(!item.selected) bindClose(item);
}
for(var i=0;i<menu.items.length;i++) {
if(menu.items[i].selected) prevSelected = menu.items[i];
if(menu.items[i] === item) menu.items[i].selected = !menu.items[i].selected;
else menu.items[i].selected = false;
}
if(menu.onSelect) menu.onSelect(item, prevSelected);
if(item.onSelect) item.onSelect(item, prevSelected);
return menu;
};
// TODO: move to directive
function bindClose(item){
$timeout(function(){ // wait untill this click event finish
$document.bind('click', close);
function close() {
$timeout(function(){ // force $rootScope.$apply via %$timeout
item.selected = false;
$document.unbind('click', close);
});
}
}, 0, false);
}
Menu.prototype.get =
Menu.prototype.getItem = function walkChildren(id, parent){
var menu = this;
var item;
var children = (parent ? parent.children : menu.items) || [];
for(var i=0;i<children.length;i++){
if(children[i].id === id) return children[i];
}
for(var i=0;i<children.length;i++){
if(children[i].children) {
item = walkChildren(id, children[i]);
if(item) return item;
}
}
};
Menu.get = function(menuId){
return _menus[ menuId ];
};
return Menu;
}]);
/**
* NE MODALS
* ***************************************************************************************************************************
*/
/*
* @example:
* modals.create({
id:'account.changePassword',
title:'Change your password',
templateUrl:'views/areas/account/changepass.html',
- modal text if include not used
text: 'modal text',
- modal html if include not used
html: '<p>My Modal Text</p>',
- generated buttons, when include not set
buttons:[{ text:'Cancel', disabled:false, css:'btn btn-default', click:function(){} },
{ text:'Ok', disabled:false, css:'btn btn-primary', click:function(){} }],
- custom method can be accessed from modal scope (modal.changePass)
changePass: function(oldPass, newPass){
changePass.post({ oldPass:oldPass, newPass:newPass }, function(data){
notify.show('Password changed.', 'success');
modals.get('account.changePassword').hide();
});
}
});
*
*
*/
angular.module('neModals', [])
.factory('neModals',['$timeout','$sce', function($timeout, $sce){
var modals = {
items:{},
defaults:{
visible:false,
backdrop:true,
backdropOpacity:0.4,
css:'',
removeOnClose:false,
destroyOnClose:false,
showAfterCreate:true,
title:'modal title',
allowResize:true,
zIndex:1040,
text:'',
html:'',
include:'', // alias bodyTemplateUrl
buttons:[{ text:'Cancel', disabled:false, css:'btn-default', click:function(){} },
{ text:'Ok', disabled:false, css:'btn-primary', click:function(){} }]
},
opened:0,
changeListeners: [],
fireChangeListeners: function(){
for(var i=0;i<this.changeListeners.length;i++){
(function(i){
$timeout(function(){
modals.changeListeners[i](modals.items);
}, 0, false);
})(i);
}
}
};
function Modal(settings){
settings = settings || modals.defaults;
for(var key in settings){
this[key] = settings[key];
}
this.id = settings.id || ('modal_' + Object.keys(modals.items).length);
this.backdrop = true;
if(settings.backdrop===false) this.backdrop = false;
this.backdropOpacity = this.backdropOpacity || modals.defaults.backdropOpacity;
this.css = this.css || modals.defaults.css;
this.zIndex = modals.defaults.zIndex;
this.showAfterCreate = (this.showAfterCreate===undefined) ? true : this.showAfterCreate;
this.removeOnClose = (this.removeOnClose===undefined) ? true : this.removeOnClose;
this.destroyOnClose = (this.destroyOnClose===undefined) ? true : this.destroyOnClose;
this.html = this.html ? $sce.trustAsHtml(this.html) : '';
this.include = this.include || this.templateUrl || this.bodyTemplateUrl;
this.allowResize = this.allowResize===undefined ? modals.defaults.allowResize : this.allowResize;
this.show = this.open = function(){
if(this.visible) return; // do not open already opened modal
this.visible = true;
// bootstrap scroll fix, TODO:move to directive
if(modals.opened === 0)
angular.element(document.getElementsByTagName('body')).addClass('modal-open');
modals.opened++;
this.zIndex = modals.defaults.zIndex + (11*modals.opened);
modals.fireChangeListeners();
};
this.hide = this.close = function(){
if(!this.visible) return; // do not close already closed modal
this.visible = false;
modals.opened--;
if(this.removeOnClose && this.destroyOnClose) modals.remove(this.id);
// bootstrap scroll fix, TODO:move to directive
if(modals.opened === 0){
angular.element(document.getElementsByTagName('body')).removeClass('modal-open');
}
modals.fireChangeListeners();
if(typeof this.onClose === 'function') this.onClose();
};
// register or overwrite modal
modals.items[this.id] = this;
if(this.showAfterCreate) this.show();
else modals.fireChangeListeners();
return this;
}
modals.create = function(settings){
return new Modal(settings);
};
modals.get = function(id){
return modals.items[id];
};
modals.remove = function(id){
delete modals.items[id];
};
return modals;
}])
.controller('NeModalsCtrl', ['$scope', 'neModals', function($scope, modals){
modals.changeListeners.push(function(modals){
$scope.modals = modals;
$scope.$digest();
});
}])
.directive('neModalsContainer',[function(){
return {
templateUrl:'neModals/container.html'
};
}])
.run(['$templateCache', function($templateCache){
$templateCache.put('neModals/container.html',
'<div ng-controller="NeModalsCtrl">'+
' <div ng-repeat="(id,modal) in modals">'+
' <div class="modal ng-hide" ng-show="modal.visible" style="z-index:{{modal.zIndex}};">'+
' <div class="modal-dialog {{modal.css}}" ng-class="{\'modal-full\':modal.wide,\'modal-lg\':modal.large||modal.lg,\'modal-xs\':modal.small||modal.xs}">'+
' <div class="modal-content">'+
' <div class="modal-header">'+
' <button class="close" ng-click="modal.hide()"><i class="fa fa-times fa-fw fa-lg"></i></button>'+
' <button class="close" ng-if="modal.allowResize" ng-click="modal.wide = !modal.wide">'+
' <i style="font-size:15px;margin-right:5px;" class="fa fa-fw" ng-class="{\'fa-expand\':!modal.wide,\'fa-compress\':modal.wide}"></i>'+
' </button>'+
' <h4 class="modal-title">{{modal.title|translate}}</h4>'+
' </div>'+
' <div class="modal-body">'+
' {{modal.text|translate}}'+
' <div ng-bind-html="modal.html"></div>'+
' <div ng-include="modal.include"></div>'+
' </div>'+
' <div class="modal-footer" ng-show="modal.buttons">'+
' <button ng-repeat="button in modal.buttons" type="button" ng-disabled="button.disabled" class="{{button.css}}" ng-click="button.click()">{{button.text|translate}}</button>'+
' </div>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="modal-backdrop in" ng-show="modal.visible && modal.backdrop" ng-style="{\'z-index\':modal.zIndex-10,\'opacity\':modal.opacity}"></div>'+
' </div>'+
'</div>');
}]);
/**
* NE NOTIFICATIONS
* ***************************************************************************************************************************
*/
/*
* @example:
* notifications.warning('Title','message', [timeout in ms]);
*/
angular.module('neNotifications',['neLoading'])
.factory('neNotifications', ['$timeout', function($timeout){
var notifications = this;
notifications.timeout = 3000; // default timeout
notifications.queue = [];
notifications.changeListeners = [];
notifications.fireListeners = function(){
for(var i=0;i<notifications.changeListeners.length;i++){
(function(i){
$timeout(function(){
notifications.changeListeners[i](notifications.queue);
}, 0 ,false);
})(i);
}
};
notifications.add =
notifications.show =
notifications.create = function(type, title, text, icon, timeout) {
var opts = {};
// create(type, title, text, timeout)
if(arguments.length === 4 && typeof arguments[3] !== 'string'){
timeout = arguments[3];
icon = '';
}
// create(type, text, timeout)
else if(arguments.length === 3 && typeof arguments[2] !== 'string'){
timeout = arguments[2];
text = arguments[1];
title = '';
}
// create(text, timeout)
else if(arguments.length === 2 && typeof arguments[2] !== 'string'){
timeout = arguments[1];
text = arguments[0];
title = '';
type = 'info';
}
// create(type, text)
else if(arguments.length === 2 && typeof arguments[2] === 'string'){
text = arguments[1];
title = '';
}
// create(opts)
else if(arguments.length === 1 && angular.isObject(arguments[0])){
opts = arguments[0];
type = opts.type;
title = opts.title;
icon = opts.icon;
text = opts.text;
timeout = opts.timeout;
}
if(type==='error' || type==='danger') {
type='danger';
}
function destroy(){
notifications.remove(this.id);
}
function update(n){
n = n || {};
delete n.id;
var existsOnIndex = notifications.getIndex(this.id);
if(existsOnIndex > -1) notifications.queue[ existsOnIndex ] = angular.merge(this, n);
notifications.fireListeners();
return this;
}
function postpone(mseconds){
var n = this;
if(n.timeoutPromise) $timeout.cancel(n.timeoutPromise);
if(!n.fixed && typeof mseconds === 'number') {
var remainTime = n.timeout - (new Date().getTime() - n.showTime);
remainTime = remainTime < 0 ? 0 : remainTime;
n.showTime = new Date().getTime();
n.timeout = remainTime + mseconds;
n.timeoutPromise = $timeout(function(){
notifications.remove(n.id);
}, n.timeout, false);
}
}
var nId = new Date().getTime() + Math.floor((Math.random() * 100) + 1);
var n = angular.merge(opts, {
id: opts.id || nId,
type: type,
title: title,
icon: icon,
text: text,
timeout: 0,
fixed: false,
close: destroy,
hide: destroy,
destroy: destroy,
update: update,
postpone: postpone
});
n.include = opts.bodyTemplateUrl || opts.include;
var existsOnIndex = notifications.getIndex(n.id);
if(existsOnIndex > -1) notifications.queue[ existsOnIndex ] = n;
else notifications.queue.push(n);
notifications.fireListeners();
if(timeout !== false && timeout !== 0) {
n.timeout = parseInt(timeout, 10);
n.showTime = new Date().getTime();
n.timeoutPromise = $timeout(function(){
notifications.remove(n.id);
}, n.timeout || notifications.timeout, false);
}
else n.fixed = true;
return n;
};
function unifyArguments(title, text, timeout, args){
if(args.length === 2 && typeof args[1] !== 'string') {
timeout = args[1];
text = args[0];
title = '';
}
}
notifications.error =
notifications.danger = notifications.danger = function(title, text, timeout){
unifyArguments(title, text, timeout, arguments);
return this.show('error', title, text, 'fa fa-exclamation-circle fa-2x', timeout!==undefined ? timeout : notifications.timeout * 2);
};
notifications.success = function(title, text, timeout){
unifyArguments(title, text, timeout, arguments);
return this.show('success', title, text, 'fa fa-check-circle fa-2x', timeout);
};
notifications.warning = function(title, text, timeout){
unifyArguments(title, text, timeout, arguments);
return this.show('warning', title, text, 'fa fa-warning fa-2x', timeout);
};
notifications.info = function(title, text, timeout){
unifyArguments(title, text, timeout, arguments);
return this.show('info', title, text, 'fa fa-info-circle fa-2x', timeout);
};
notifications.getIndex = function(nId){
for(var i=0;i<notifications.queue.length;i++){
if(notifications.queue[i].id === nId) {
return i;
}
}
};
notifications.get = function(nId){
return notifications.queue[ notifications.getIndex(nId) ];
};
notifications.remove = notifications.hide = function(nId){
var index = notifications.getIndex(nId);
if(index === -1) return;
notifications.queue.splice(index,1);
notifications.fireListeners();
};
return notifications;
}])
.controller('NeNotificationsCtrl', [ '$scope', 'neNotifications', function($scope, notify){
notify.changeListeners.push(function(queue){
$scope.notifications = queue;
$scope.$digest();
});
}])
.directive('neNotificationsContainer',[function(){
return {
templateUrl:'neNotifications/container.html'
};
}])
.run(['$templateCache', function($templateCache){
$templateCache.put('neNotifications/container.html',
'<div class="notification-container" ng-controller="NeNotificationsCtrl">'+
' <div ng-show="true" class="ng-hide">'+
' <div ng-repeat="n in notifications" class="alert alert-{{n.type}}" ng-class="{expanded:n.expanded}" ng-click="n.fixed=true;n.postpone()" ng-mouseenter="n.postpone()" ng-mouseleave="n.postpone(1000)">'+
' <i class="alert-pin fa fa-thumb-tack" ng-if="n.fixed"></i>'+
' <i class="alert-expand fa" ng-class="{\'fa-expand\':!n.expanded,\'fa-compress\':n.expanded}" ng-click="n.expanded=!n.expanded;n.fixed=true"></i>'+
' <i class="alert-close fa fa-times" ng-click="n.close()"></i>'+
' <table style="width:100%;word-wrap:break-word" class="table-fixed">'+
' <tr>'+
' <td style="width:40px">'+
' <i class="{{n.icon}}"></i>'+
' </td>'+
' <td style="padding:0px 5px">'+
' <div class="notification-content" ng-if="!n.include">'+
' <strong ng-if="n.title"><span ne-bind-html="{{n.title|translate}}"></span><br></strong>'+
' <span ne-bind-html="{{n.text|translate}}"></span>'+
' </div>'+
' <div ng-if="n.include" ng-include="n.include"></div>'+
' </td>'+
' </tr>'+
' </table>'+
' </div>'+
' <div class="alert alert-default" ng-show="loading" ng-controller="NeLoadingCtrl">'+
' <table style="width:100%">'+
' <tr>'+
' <td style="width:40px">'+
' <i class="fa fa-fw fa-spinner fa-spin fa-2x"></i>'+
' </td>'+
' <td style="padding:0px 5px">'+
' <strong>{{::\'Loading...\'|translate}}</strong>'+
' </td>'+
' </tr>'+
' </table>'+
' </div>'+
' </div>'+
'</div>');
}]);
/**
* NE OBJECT
* ***************************************************************************************************************************
*/
angular.module('neObject',[])
.factory('neObject', ['$timeout', function($timeout){
var hasOwn = Object.prototype.hasOwnProperty;
function isPlainObject(obj) {
if (!obj || Object.prototype.toString.call(obj) !== '[object Object]' || obj.nodeType || obj.setInterval)
return false;
var has_own_constructor = hasOwnProperty.call(obj, 'constructor');
var has_is_property_of_method = hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf');
// Not own constructor property must be Object
if (obj.constructor && !has_own_constructor && !has_is_property_of_method)
return false;
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
}
function extend() {
var options, name, src, copy, copyIsArray, clone,
reservedInstances = this.extendReservedInstances,
object = this,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === 'boolean' || target === 'data' ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== 'object' && typeof target !== 'function') {
target = {};
}
for ( ; i < length; i++ ) {
options = arguments[ i ];
if(isReservedInstance(options, reservedInstances)){
target = options;
return target;
}
// Only deal with non-null/undefined values
else if ( options !== null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// prevent modifying reserved instances
if ( isReservedInstance(copy, reservedInstances) ){
target[ name ] = copy;
continue;
}
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( isPlainObject(copy) || (copyIsArray = Array.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
if(deep === 'data') {
// if data mode, do not merge arrays, just copy
target[ name ] = copy.slice(0);
continue;
}
clone = src && Array.isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = object.extend( deep, clone, copy );
}
// copy all include undefined props - helpful in query builder
else { // if (copy !== undefined){ // Don't bring in undefined values
target[name] = copy;
}
}
}
}
// Return the modified object
return target;
}
function isReservedInstance(value, reservedInstances){
for(var i=0;i<reservedInstances.length;i++){
if(value instanceof reservedInstances[i]) return true;
}
return false;
}
function deepReplace(parentObj, cb, keyPath){ // cb(keyPath, key, value)
if(!angular.isObject(parentObj)) return;
keyPath = keyPath || '';
var value;
for(var key in parentObj){
if(angular.isObject(parentObj[key])) deepReplace(parentObj[key], cb, (keyPath==='' ? key : keyPath + '.' + key));
value = cb((keyPath==='' ? key : keyPath + '.' + key), key, parentObj[key]);
if(value===undefined) delete parentObj[key];
else parentObj[key] = value;
}
}
/**
* Define cascading props in objects in namespace separated by dot,
* if props are on lower level, it will create empty object
* @param {Object} parent base object where you want add props
* @param {String} namespace dot separated
* @param {Object} value value to add to object prop
* @param {String} mode if "push", it will add value to array
* @returns {Object} parent object after properties are added
*/
function deepSet(parent, namespace, value, mode) {
// if(typeof value==='string') value = value.replace(/(\r\n|\r|\n)\s*$/, ''); // replace line endings and white spaces
var parts = namespace.split('.');
var current = parent;
if(namespace==='this') {
if(mode==='push') parent.push(value);
else parent = value.toString();
}
else {
for(var i=0; i<parts.length; i++) {
if(i >= parts.length-1) {
if(mode==='push') current[parts[i]].push(value);
else current[parts[i]] = value;
}
else current[parts[i]] = current[parts[i]]===undefined || current[parts[i]]===null ? {} : current[parts[i]];
current = current[parts[i]];
}
}
return parent;
}
function deepGet(parent, namespace) {
if((!parent && parent!==false && parent!==0) || typeof parent === 'function') return undefined;
if(namespace==='this') return parent;
var parts = namespace.split('.');
var current = parent;
for(var i=0; i<parts.length; i++) {
if(!current[parts[i]] && current[parts[i]]!==false && current[parts[i]]!==0) return undefined;
else current = current[parts[i]];
}
// function as value is not allowed
if(typeof current === 'function') return undefined;
return current;
}
function deepRemove(obj, keyPath){
obj = obj || {};
keyPath = keyPath || '';
var keys = keyPath.split('.');
if(keys.length===0) return;
if(keys.length===1) { delete obj[keys[0]]; return; }
for(var i=0;i < keys.length-1;i++) {
obj = obj[keys[i]];
if(!obj) return;
}
delete obj[keys[keys.length-1]]; // delete last prop
}
function sortArray(keyName, dir, array){ // sortArray({ key1:1, key2:-1 }, dir)
var keys;
if(arguments.length===2){
if(isObject(keyName)) {
keys = keyName;
array = arguments[1];
}
else {
array = arguments[1];
dir = 1;
}
}
else {
keys = {};
keys[keyName] = dir;
}
for(var key in keys){
if(keys[key]==='asc') keys[key] = 1;
if(keys[key]==='desc') keys[key] = -1;
}
array.sort(function(a, b) {
for(var key in keys){
if( deepGet(a, key) > deepGet(b, key)) return keys[key];
if( deepGet(a, key) < deepGet(b, key)) return -keys[key];
}
return 0;
});
return array;
}
function objectToArray(obj, sortNamespace, dir){
var array = [];
for(var key in obj) {
if(key!=='$key' && key!=='$sortIndex' && obj.hasOwnProperty(key)){
obj.$key = key;
if(sortNamespace) obj.$sortIndex = deepGet(obj[key], sortNamespace);
array.push(obj[key]);
}
}
return sortNamespace ? sortArray('$sortIndex', dir || 'asc', array) : array;
}
function arrayToObject(array, idNamespace){
if(!angular.isArray(array) || !idNamespace) return {};
var obj = {}, key;
for(var i=0;i<array.length;i++){
key = deepGet(array[i], idNamespace);
obj[key] = array[i];
}
return obj;
}
function isRegExp(value) {
return Object.prototype.toString.call(value) === '[object RegExp]';
}
function isWindow(obj) {
return obj && obj.window === obj;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function defaultExcludeKeyFnc(key){
if(key[0] === '$' && key[1] === '$') return true;
}
// modified angular equals to support single dollar key prefixes
function deepEquals(o1, o2, excludeKeyFnc) {
excludeKeyFnc = excludeKeyFnc || defaultExcludeKeyFnc;
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2 && t1 == 'object') {
if (angular.isArray(o1)) {
if (!angular.isArray(o2)) return false;
if ((length = o1.length) == o2.length) {
for (key = 0; key < length; key++) {
if (!deepEquals(o1[key], o2[key], excludeKeyFnc)) return false;
}
return true;
}
} else if (angular.isDate(o1)) {
if (!angular.isDate(o2)) return false;
return deepEquals(o1.getTime(), o2.getTime(), excludeKeyFnc);
} else if (isRegExp(o1)) {
if (!isRegExp(o2)) return false;
return o1.toString() == o2.toString();
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
angular.isArray(o2) || angular.isDate(o2) || isRegExp(o2)) return false;
keySet = Object.create(null);
for (key in o1) {
if (excludeKeyFnc(key) || angular.isFunction(o1[key])) continue;
if (!deepEquals(o1[key], o2[key], excludeKeyFnc)) return false;
keySet[key] = true;
}
for (key in o2) {
if (!(key in keySet) &&
!excludeKeyFnc(key) &&
angular.isDefined(o2[key]) &&
!angular.isFunction(o2[key])) return false;
}
return true;
}
}
return false;
}
/**
* Service function that helps to avoid multiple calls of a function (typically save()) during angular digest cycle.
* $apply will be called after original function returns;
*
* @example:
* $scope.save = debounce(function(order){
* // POST your order here ...$http....
* // debounce() will make sure save() will be called only once
* });
*/
function debounce(fn, timeout, apply){ // debounce fn
timeout = angular.isUndefined(timeout) ? 0 : timeout;
apply = angular.isUndefined(apply) ? true : apply; // !!default is true! most suitable to my experience
var prevTimeout;
return function(){ // intercepting fn
if(prevTimeout) $timeout.cancel(prevTimeout);
var that = this;
var argz = arguments;
prevTimeout = $timeout(function(){
prevTimeout = null;
fn.apply(that, argz);
}, timeout, apply);
return prevTimeout;
};
}
// auto parse dates
var regexIso8601 = /^(\d{4}|\+\d{6})(?:-(\d{2})(?:-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})\.(\d{1,})(Z|([\-+])(\d{2}):(\d{2}))?)?)?)?$/;
var regexIsoStrict = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
function dateStringsToDates(input, useStrictDateParser) {
if(useStrictDateParser === undefined) useStrictDateParser = true; // only if forced to not use strict
var value, match, milliseconds;
// try to parse if input is string
if(typeof input === 'string' && (match = input.match(useStrictDateParser ? regexIsoStrict : regexIso8601))) {
milliseconds = Date.parse(match[0]);
if (!isNaN(milliseconds)) {
input = new Date(milliseconds);
}
return input;
}
// Ignore things that aren't objects
else if(typeof input !== 'object') return input;
for(var key in input){
value = input[key];
// Check for string properties which look like dates.
if(typeof value === 'string' && (match = value.match(useStrictDateParser ? regexIsoStrict : regexIso8601))) {
milliseconds = Date.parse(match[0]);
if (!isNaN(milliseconds)) {
input[key] = new Date(milliseconds);
}
}
else if (typeof value === 'object') {
// Recurse into object
dateStringsToDates(value, useStrictDateParser);
}
}
return input;
}
function fromJson(str, useStrictDateParser){
var result;
try {
result = JSON.parse(str);
}
catch(err){}
return dateStringsToDates(result, useStrictDateParser);
}
function removePrefixedProps(input, prefix) {
// Ignore things that aren't objects.
if(typeof input !== 'object' || !prefix) return input;
for(var key in input) {
if(input.hasOwnProperty(key)) {
var value = input[key];
if(key.indexOf(prefix)===0) delete input[key];
else if(typeof value === 'object') removePrefixedProps(value, prefix);
}
}
}
function isObject(obj){
return Object.prototype.toString.call(obj) === '[object Object]';
}
function isArray(obj){
return Array.isArray(obj);
}
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
function guid() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
return {
isObject: isObject,
isArray: isArray,
sortArray: sortArray,
extendReservedInstances: [File, FileList, Blob],
extend: extend,
merge: extend,
setObjValue: deepSet,
deepSet: deepSet,
getObjValue: deepGet,
deepGet: deepGet,
deepReplace: deepReplace,
deepRemove: deepRemove,
deepEquals: deepEquals,
deepEqual: deepEquals,
objectToArray: objectToArray,
arrayToObject: arrayToObject,
dateStringsToDates: dateStringsToDates,
fromJson: fromJson,
fromJSON: fromJson,
removePrefixedProps: removePrefixedProps,
debounce: debounce,
guid: guid
};
}]);
/**
* NE QUERY
* ***************************************************************************************************************************
*/
/*
* advanced mongodb query builder and parser
* it can be extended to build and parse another query language
*/
angular.module('neQuery',['neLocal','neObject'])
.config(['neLocalProvider', function(localProvider){
localProvider.set('default', {
$eq:'=',
$lt:'<',
$lte:'<=',
$gt:'>',
$gte:'>=',
$regex_exact:'exact match',
$regex_contains:'contains',
$regex_begins:'begins with',
$regex_ends:'ends with',
$in:'is in',
$ne:'not equal to',
$regex_ncontains:'not contains',
$regex_nbegins:'not begins with',
$regex_nends:'not ends with',
$nin:'is not in',
$regex:'custom regex',
$size:'items count',
$exists:'exists',
$and:'and',
$or:'or',
OR:'OR',
AND:'AND',
choose:'(choose)',
qtype_short_number:'0-9',
qtype_short_date:'Date',
qtype_short_datetime:'Time',
qtype_short_boolean:'Y/N',
qtype_short_string:'A-Z',
qtype_short_array:'[A]',
qtype_short_object:'{O}',
qtype_number:'Number',
qtype_date:'Date',
qtype_datetime:'Date & Time',
qtype_boolean:'Boolean',
qtype_string:'Text',
qtype_array:'Array',
qtype_object:'Object',
qvalue_true:'True',
qvalue_false:'False',
Search:'Search',
'Order By':'Order By',
'choose field':'choose field',
'type value':'type value',
'empty value':'empty value'
});
}])
.run(['$templateCache', function($templateCache){
$templateCache.put('neQuery/query.html',
'<div class="visible-inline-block">'+
'<div ng-repeat-start="query in query track by $index" class="visible-inline-block" style="position:relative;margin:2px" ng-style="{\'margin-top\':$first ? \'0px\' : \'2px\'}">'+
' <small ng-if="!$first && query.logical===\'OR\' && !query.length">{{query.logical | translate}}<br></small>'+
' <div ng-if="!query.length" class="visible-inline-block">'+
' <div class="dropdown visible-inline-block" uib-dropdown keyboard-nav>'+
' <button ng-if="query.onlyPredefinedFields" class="btn btn-sm btn-default" ng-disabled="disabled" uib-dropdown-toggle style="width:142px">'+
' <span class="nowrap" ng-if="query.fieldName">{{query.fieldName}}</span><span class="nowrap" ng-if="!query.fieldName">{{::\'choose field\'|translate}}</span>'+
' </button>'+
' <input ng-if="!query.onlyPredefinedFields" type="text" ng-disabled="disabled" placeholder="{{::\'choose field\'|translate}}" class="input-sm" uib-dropdown-toggle ng-change="query.setFieldByName(query.fieldName);onChange()" ng-model="query.fieldName"/>'+
' <ul ng-if="query.fields.filterByName(query.fieldName, query.field.name).length" class="dropdown-menu" style="max-height:250px;overflow:auto">'+
' <li ng-repeat="field in query.fields.filterByName(query.fieldName, query.field.name)" ng-class="{\'active\':(field.name===query.fieldName)}">'+
' <a href="" ng-click="query.setField(field);onChange()">'+
' {{field.name}}'+
' </a>'+
' </li>'+
' </ul>'+
' </div>'+
' <div class="dropdown visible-inline-block" uib-dropdown keyboard-nav>'+
' <button ng-disabled="query.field.disableOperator || disabled" class="btn btn-default btn-sm btn-intensive" uib-dropdown-toggle style="width:120px">'+
' <span class="class="nowrap"">{{query.operator | translate}} </span>'+
' </button>'+
' <ul class="dropdown-menu" style="min-width:210px;overflow:auto">'+
' <li ng-if="!query.field.disableType" class="text-center" style="padding-top:4px">'+
' <div class="btn-group btngroup-xs">'+
' <button class="btn btn-default btn-xs" ng-class="{\'btn-success\':(query.type.name===type)}" style="padding:2px;" uib-tooltip="{{\'qtype_\'+type | translate}}" tooltip-append-to-body="true" ng-repeat="type in query.types" ng-click="query.setType(type);$event.stopPropagation();">'+
' {{\'qtype_short_\'+type | translate}}'+
' </button>'+
' </div>'+
' </li>'+
' <li ng-if="!query.field.disableType" class="divider"></li>'+
' <li ng-repeat="operator in query.type.operators" ng-if="!query.field.allowedOperatorIndexes || query.field.allowedOperatorIndexes.indexOf($index)>-1" ng-class="{\'active\':(query.operator===operator)}">'+
' <a href="" ng-click="query.setOperator(operator);onChange()">'+
' <span>{{operator | translate}}</span>'+
' </a>'+
' </li>'+
' </ul>'+
' </div>'+
' <div class="visible-inline-block" ne-query-value="query"></div>'+
' <div class="btn-group btn-group-xs" ng-if="!disabled">'+
' <button class="btn btn-default" ng-click="query.next(\'AND\');onChange()">{{::\'AND\' | translate}}</button>'+
' <button class="btn btn-default" ng-click="query.next(\'OR\');onChange()">{{::\'OR\' | translate}}</button>'+
' <button class="btn btn-default" ng-click="query.levelDown();onChange()"><i class="fa fa-fw fa-level-down"></i></button>'+
' <button class="btn btn-default" ng-click="close();query.remove();onChange()"><i class="fa fa-fw fa-minus"></i></button>'+
' </div>'+
' </div>'+
' <div ng-if="query.length" class="visible-inline-block" style="position:relative;">'+
' <small>{{ ($first ? \' \' : query.logical) | translate}}<br></small>'+
' <div class="btn-group btn-group-xs" style="position:absolute;right:0px;top:1px" ng-if="!disabled">'+
' <button class="btn btn-default" style="border:1px dashed #999;border-right:none;color:#999;border-bottom: 1px solid transparent;" ng-click="query.next(\'AND\')">{{::\'AND\' | translate}}</button>'+
' <button class="btn btn-default" style="border:none;border-top:1px dashed #999;color:#999;border-bottom: 1px solid transparent;" ng-click="query.next(\'OR\')">{{::\'OR\' | translate}}</button>'+
' <button class="btn btn-default" style="border:1px dashed #999;border-left:none;color:#999;border-bottom: 1px solid transparent;" ng-click="close();query.remove()"><i class="fa fa-minus"></i></button>'+
' </div>'+
' <div class="query-subquery visible-inline-block" ng-include="\'neQuery/query.html\'" style="border:1px dashed #999;padding:8px;margin:2px 0px;"></div>'+
' </div>'+
'</div>'+
'<br ng-repeat-end>'+
'</div>');
$templateCache.put('neQuery/date.html',
'<input type="text" '+
' class="input-sm" '+
' placeholder="{{(query.field.isEmptyValue(query.value) ? (query.field.placeholder||\'type value\') : \'empty value\')|translate}}" '+
' uib-datepicker-popup '+
' is-open="query.value_opened" '+
' ng-click="query.value_opened=!query.value_opened" '+
' ng-disabled="disabled" '+
' ng-model="query.value" '+
' ng-change="onChange()">');
$templateCache.put('neQuery/datetime.html',
'<input type="text" '+
' class="input-sm" '+
' placeholder="{{(query.field.isEmptyValue(query.value) ? (query.field.placeholder||\'type value\') : \'empty value\')|translate}}"'+
' uib-datetimepicker-popup '+
' show-seconds="true" '+
' is-open="query.value_opened" '+
' ng-click="query.value_opened=!query.value_opened" '+
' ng-disabled="disabled" '+
' ng-model="query.value" '+
' ng-change="onChange()">');
$templateCache.put('neQuery/number.html',
'<input type="number" '+
' class="input-sm" '+
' placeholder="{{(query.field.isEmptyValue(query.value) ? (query.field.placeholder||\'type value\') : \'empty value\')|translate}}" '+
' ng-disabled="disabled" '+
' ng-model="query.value" '+
' ng-change="onChange()" '+
' style="width:142px;">');
$templateCache.put('neQuery/list.html',
'<select class="input-sm" '+
' ng-disabled="disabled" '+
' ng-model="query.value" '+
' ng-options="(value | translate) for value in query.field.values" '+
' ng-change="onChange()" '+
' style="width:142px;">'+
'</select>');
$templateCache.put('neQuery/boolean.html',
'<select class="input-sm" '+
' ng-disabled="disabled" '+
' ng-model="query.value" '+
' ng-options="(\'qvalue_\'+value | translate) for value in [true,false]" '+
' ng-change="onChange()" '+
' style="width:142px;">'+
'</select>');
$templateCache.put('neQuery/string.html',
'<input type="text" '+
' class="input-sm" '+
' placeholder="{{(query.field.isEmptyValue(query.value) ? (query.field.placeholder||\'type value\') : \'empty value\')|translate}}" '+
' ng-disabled="disabled" '+
' ng-model="query.value" '+
' ng-change="onChange()"/>');
$templateCache.put('neQuery/string-suggestions.html',
'<div class="dropdown visible-inline-block" uib-dropdown keyboard-nav>'+
' <input type="text" '+
' class="input-sm" '+
' placeholder="{{(query.field.isEmptyValue(query.value) ? (query.field.placeholder||\'type value\') : \'empty value\')|translate}}" '+
' uib-dropdown-toggle '+
' ng-disabled="disabled" '+
' ng-model="query.suggestion" '+
' ng-click="(query.field.suggestionMinLength===0 && !query.suggestions) ? query.field.createSuggestions(query, query.suggestion) : null" '+
' ng-change="query.page=1;query.field.onlySuggestedValues ? query.value=null : query.value=query.suggestion;query.field.createSuggestions(query, query.suggestion, true);onChange()">'+
' <ul ng-if="query.suggestions.length" class="dropdown-menu" style="max-height:250px;overflow:auto">'+
' <li ng-if="query.field.pagination" class="text-center" style="padding-top:4px">'+
' <button class="btn btn-xs btn-default" ng-disabled="!query.pagination.prev" ng-click="$event.stopPropagation();query.page=(query.page||1)-1;query.field.createSuggestions(query, query.suggestion)"><i class="fa fa-fw fa-backward"></i></button>'+
' {{query.page||1}}'+
' <button class="btn btn-xs btn-default" ng-disabled="!query.pagination.next" ng-click="$event.stopPropagation();query.page=(query.page||1)+1;query.field.createSuggestions(query, query.suggestion)"><i class="fa fa-fw fa-forward"></i></button>'+
' </li>'+
' <li ng-if="query.field.pagination" class="divider"></li>'+
' <li ng-repeat="value in query.suggestions" ng-class="{\'active\':(value===query.value)}">'+
' <a href="" ng-click="query.value=value.key;query.suggestion=value.name;onChange()">'+
' {{value.name}}'+
' </a>'+
' </li>'+
' </ul>'+
'</div>');
$templateCache.put('neQuery/disabled.html',
'<input type="text" disabled="disabled" class="input-sm" ng-model="query.value">');
$templateCache.put('neQuery/sort.html',
'<div class="visible-inline-block">'+
'<div ng-repeat-start="sort in query.sortBy track by $index" style="display:inline-block;position:relative;margin:2px" ng-style="{\'margin-top\':$first ? \'0px\' : \'2px\'}">'+
' <small>{{::\'Order By\'|translate}}</small>'+
' <div class="visible-inline-block">'+
' <div class="dropdown visible-inline-block" uib-dropdown keyboard-nav>'+
' <button ng-if="query.onlyPredefinedFields" ng-disabled="disabled" class="btn btn-sm btn-default" uib-dropdown-toggle style="width:142px">'+
' <span class="nowrap" ng-if="sort.fieldName">{{sort.fieldName}}</span><span class="nowrap" ng-if="!sort.fieldName">{{::\'choose field\'|translate}}</span>'+
' </button>'+
' <input ng-if="!query.onlyPredefinedFields" type="text" ng-disabled="disabled" placeholder="{{::\'choose field\'|translate}}" class="input-sm" uib-dropdown-toggle ng-change="query.setSortByName(sort.fieldName, $index);onChange()" ng-model="sort.fieldName" />'+
' <ul ng-if="query.fields.filterByName(sort.fieldName, sort.name).length" class="dropdown-menu" style="max-height:250px;overflow:auto">'+
' <li ng-repeat="field in query.fields.filterByName(sort.fieldName, sort.name)" ng-class="{\'active\':(field.name===sort.fieldName)}">'+
' <a href="" ng-click="query.setSortField(field,$parent.$index);onChange()">'+
' {{field.name}}'+
' </a>'+
' </li>'+
' </ul>'+
' </div>'+
' <div class="btn-group btn-group-xs">'+
' <button class="btn btn-default" ng-disabled="disabled" ng-click="query.toggleSortDirection($index);onChange()">'+
' <i class="fa fa-fw" ng-class="{\'fa-sort-amount-asc\':sort.direction===1,\'fa-sort-amount-desc\':sort.direction===-1}"></i>'+
' </button>'+
' <button class="btn btn-default" ng-disabled="disabled" ng-click="query.addSort($index);onChange()"><i class="fa fa-fw fa-plus"></i></button>'+
' <button class="btn btn-default" ng-disabled="disabled" ng-click="query.removeSort($index);onChange()"><i class="fa fa-fw fa-minus"></i></button>'+
' </div>'+
' </div>'+
'</div>'+
'<br ng-repeat-end>'+
'<button ng-if="!query.sortBy.length" class="btn btn-default btn-sm btn-intensive" ng-disabled="disabled" ng-click="query.addSort();onChange()"><i class="fa fa-fw fa-signal"></i> <span class="hidden-sm">{{::\'Order By\'|translate}}</span></button>'+
'</div>');
}])
.directive('neQueryValue',[function(){
return {
restrict:'A',
// require:'ngModel',
template:'<div ng-include="query.field.template||query.type.templates[query.operator]||query.type.template||query.templates[query.type.name]||query.templates.disabled"></div>',
//scope:{ query:'=neQueryValue' },
link: function(elm, scope, attrs, ctrl){
}
};
}])
.directive('neQuerySearch',[function(){
return {
restrict:'A',
template: '<div class="pull-left" ne-query="query" ne-query-change="onChange()" ne-query-disabled="disabled"></div>'+
'<div class="pull-left hidden-xs" style="width:20px"> </div>'+
'<div class="pull-left" ne-query-sort="query" ne-query-sort-change="onChange()" ne-query-sort-disabled="disabled"></div>'+
'<button ng-disabled="disabled" class="btn btn-primary btn-sm btn-intensive" ng-click="searchClick()" style="margin-left:2px">'+
' <i class="fa fa-fw fa-search"></i>'+
' <span class="hidden-sm">{{::\'Search\' | translate}}</span>'+
'</button>',
scope:{ query:'=neQuerySearch', searchClick:'&neQuerySearchClick', onQuerySearchChange:'&neQuerySearchChange', querySearchEmpty:'=neQuerySearchEmpty', disabled:'=neQuerySearchDisabled' },
link: function(scope, elm, attrs, ctrl){
var watchEmptyState = !!attrs.neQuerySearchEmpty;
scope.onChange = function(){
scope.query.setDirty();
if(watchEmptyState) scope.querySearchEmpty = scope.query.isEmpty();
if(scope.onQuerySearchChange) scope.onQuerySearchChange();
};
if(watchEmptyState) scope.querySearchEmpty = scope.query.isEmpty();
}
};
}])
.directive('neQuery',[function(){
return {
restrict:'A',
templateUrl: 'neQuery/query.html',
scope:{ query:'=neQuery', onQueryChange:'&neQueryChange', queryEmpty:'=neQueryEmpty', disabled:'=neQueryDisabled' },
link: function(scope, elm, attrs, ctrl){
var watchEmptyState = !!attrs.neQueryEmpty;
scope.onChange = function(){
scope.query.setDirty();
if(watchEmptyState) scope.queryEmpty = scope.query.isQueryEmpty();
if(scope.onQueryChange) scope.onQueryChange();
};
if(watchEmptyState) scope.queryEmpty = scope.query.isQueryEmpty();
}
};
}])
.directive('neQuerySort',[function(){
return {
restrict:'A',
templateUrl: 'neQuery/sort.html',
scope:{ query:'=neQuerySort', onQuerySortChange:'&neQuerySortChange', querySortEmpty:'=neQuerySortEmpty', disabled:'=neQuerySortDisabled' },
link: function(scope, elm, attrs, ctrl){
var watchEmptyState = !!attrs.neQuerySortEmpty;
scope.onChange = function(){
scope.query.setDirty();
if(watchEmptyState) scope.querySortEmpty = scope.query.isSortEmpty();
if(scope.onQuerySortChange) scope.onQuerySortChange();
};
if(watchEmptyState) scope.querySortEmpty = scope.query.isSortEmpty();
}
};
}])
.constant('neQueryConfig', {
useRegexBracketsWrap: false,
useStrictDateParser: true // matches only full date-time format like: 2018-03-13T23:00:00.000Z
})
.factory('NeQuery',['neLocal','neObject', 'neQueryConfig', function(local, object, queryConfig){
var templates = {
query: 'neQuery/query.html',
sort: 'neQuery/sort.html',
disabled: 'neQuery/disabled.html',
number: 'neQuery/number.html',
string: 'neQuery/string.html',
boolean: 'neQuery/boolean.html',
date: 'neQuery/date.html',
datetime: 'neQuery/datetime.html',
list: 'neQuery/list.html',
suggestions: 'neQuery/string-suggestions.html'
};
// used when parsing query
var querySortKey = '$sort';
var queryOptionKeys = ['$limit', '$page', '$skip', '$sort'];
var queryOptionKeyPrefix = '$';
function isRegexString(str){
if(str === undefined) return false;
var regexChars = {
'-': true,
'[': true,
']': true,
'/': true,
'{': true,
'}': true,
'(': true,
')': true,
'*': true,
'+': true,
'?': true,
'.': true,
'\\': true,
'^': true,
'$': true,
'|': true
}
var escaped = false;
for(var i=0;i<str.length;i++){
if(str[i] === '\\') escaped = !escaped;
if(str[i+1] !== '\\' && regexChars[ str[i] ] && !escaped) return true;
}
return false;
}
function escapeRegExp(str) {
return (str||'').replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
function unEscapeRegExp(str) {
return (str||'').replace(/\\(?!\\)/g,'');
}
var defaultType = 'string';
var types = {
string:{
name:'string',
operators: ['$regex_exact','$regex_contains','$regex_begins','$regex_ends','$in', // 'equal','contains','begins with','ends with','is in',
'$ne','$regex_ncontains','$regex_nbegins','$regex_nends','$nin','$regex'], // 'not equal','not contains','not begins with','not ends with','not in', 'regexp'
template: templates.string
},
number:{
name:'number',
operators:['$eq','$lt','$lte','$gt','$gte'], // '=','<','<=','>','>='
template: templates.number
},
boolean:{
name:'boolean',
operators:['$eq'], // 'is'
template: templates.boolean,
onBuild: function(value){ if([true,'true','True',1,'yes','Yes'].indexOf(value)!==-1) return true; else return false; }
},
date:{
name:'date',
operators:['$eq','$lt','$lte','$gt','$gte'], // '=','<','<=','>','>='
template: templates.date
},
datetime:{
name:'datetime',
operators:['$eq','$lt','$lte','$gt','$gte'], // '=','<','<=','>','>='
template: templates.datetime
},
object:{
name:'object',
operators:['$exists'],
template: templates.boolean
},
array:{
name:'array',
operators:['$size'], // $elemMatch
template: templates.string,
templates:{
'$size':templates.number,
//'$elemMatch':templates.string
}
}
};
function buildSort(sortBy){
if(!sortBy) return {};
var query = this, s = {};
s[querySortKey] = {};
for(var i=0;i<sortBy.length;i++){
s[querySortKey][ sortBy[i].key ] = sortBy[i].direction;
}
return s;
}
function parseSort(sortBy){
var query = this, s = [];
query.sortBy = []; // clean sort
if(Object.prototype.toString.call(sortBy)==='[object Object]'){
for(var key in sortBy){
query.addSort();
query.setSortByName(key, query.sortBy.length-1).direction = sortBy[key];
}
}
return s;
}
function isKeyConflict(dest, src){
if(['string','number','boolean'].indexOf(typeof dest) > -1) return true;
if(src === null || src === undefined || typeof src === 'function') return false;
// primitive type will cause override
if(['string','number','boolean'].indexOf(typeof src) > -1) return true;
else { // src is object
for(var key in src){
if(dest[key] !== undefined && dest[key] !== null) return true;
}
}
return false;
}
function build(query, excludeSort){
var result = {}, value;
result = object.extend(true, result, query.options); // add query options to result
// nested logical query, need to group ands
if(query.length) {
var andGroups = [], g=0;
for(var i=0;i<query.length;i++){
if(i>0 && query[i].logical==='OR') g++;
andGroups[g] = andGroups[g] || [];
andGroups[g].push(query[i]);
}
// no OR query, just ANDs
if(g===0) {
var presult,
wrappedByAnd = false,
andGroup = andGroups[g];
for(var i=0;i<andGroup.length;i++){
presult = build(andGroup[i], true);
// check if there is key conflict:
// 1. no conflict scenario: pkey:{ $lte:5 }, pkey:{ $gte:1 }
// 2. conflict scenario: pkey:{ $regex:'5' }, pkey:{ $regex:'1' } or pkey:123, pkey:123
for(var pkey in presult){
if(result[ pkey ] !== undefined && result[ pkey ] !== null){
if(andGroup[i].field.merge) result = andGroup[i].field.merge(pkey, presult, result);
else if(!isKeyConflict(result[pkey], presult[pkey])){ // check keys conflicts
result[pkey] = object.extend(true, result[pkey], presult[pkey]);
}
else {
// key conflict, and field has no merge method, need to wrap it by AND
delete result[ pkey ]; // this field will be inside $and
result = queries['AND'].build(andGroup); // object.extend(true, {}, queries['AND'].build(andGroup));
wrappedByAnd = true;
break;
}
}
else result[pkey] = presult[pkey];
}
// don't continue if andGroup was wrapped by and
if(wrappedByAnd) break;
}
}
// mixed ors and ands
else result = object.extend(true, result, queries['OR'].build(andGroups));
}
// simple query
else if(query.operator && query.field && query.field.key) {
value = angular.copy(query.value);
if(query.type.onBuild) value = query.type.onBuild(value);
if(!query.field.isEmptyValue || !query.field.isEmptyValue(value)){
value = queries[ query.operator ].build(typeof query.field.onBuild==='function' ? query.field.onBuild(value) : value);
if(value!==undefined && value!==null) {
if(query.field.build) {
var customBuild = query.field.build(query.field.key, value, query); // custom field build
result[ customBuild.key || query.field.key] = customBuild.key ? customBuild.value : customBuild;
}
else result[query.field.key] = value;
}
}
}
// build sort
if(!excludeSort) result = object.extend(true, result, buildSort.call(query, query.sortBy));
return result;
}
function parse(builtQuery, parentLogical){
var query = this, result, child;
var keys = [];
// filter reserved keys
for(var key in builtQuery){
if(['AND','OR','VALUE'].indexOf(key)!==-1) continue; // this are reserved keys for parsing
if(key===querySortKey){
parseSort.call(query, builtQuery[key]);
}
else if(!queries[key] && (key[0]===queryOptionKeyPrefix || queryOptionKeys.indexOf(key)!==-1)){
// this is reserved key name
query.options[key] = builtQuery[key];
}
else keys.push(key);
}
for(var k=0;k<keys.length;k++){
key = keys[k];
// check for custom fields parsers
var customParser=null;
for(var f=0;f<query.fields.length;f++){
if((query.fields[f].field===key || (query.fields[f].match && key.match(query.fields[f].match))) && query.fields[f].parse){
customParser = query.fields[f].parse;
break;
}
}
var modified = {};
if(customParser) {
modified = customParser(key, builtQuery[key], parentLogical);
if(modified && modified.key) {
key = modified.key;
builtQuery[key] = modified.value;
}
else if(modified) builtQuery[key] = modified;
if(Array.isArray(builtQuery[key])) {
for(var q in builtQuery[key]) {
parse.call(query, builtQuery[key][q].value, builtQuery[key][q].logical || parentLogical);
}
continue;
}
}
result = (queries[key] || queries.VALUE).parse(key, builtQuery[key]);
// not recognized, continue
if(!result) {
if(modified.key) delete builtQuery[modified.key]; // - remove modified.key after parse
continue;
}
// multiple operators in one key (e.g. range < >=), between have to be AND, but first
else if(Array.isArray(result)){
for(var i=0;i<result.length;i++) {
addQuery(query, result[i], (k===0 && i===0) ? parentLogical : 'AND');
}
}
// AND, or OR queries
else if(result.queries) {
child = null;
for(var i=0;i<result.queries.length;i++){
// if there is only one OR, or AND in query, no need to append child, just sibling
// if parent logical !== result logical, and it is first item inside logical group, its logical will be parent logical
// pseudo example 1: or[ and[1,2], or[1,2], and[1,2] ]
// pseudo example 2: and[ or[1,2], and[1,2], or[1,2] ]
// pseudo example 3: and[ or[1,2], or[1,2] ]
// pseudo example 4: or[ and[1,2], and[1,2] ]
if(keys.length===1 && !parentLogical) query.parse(result.queries[i], i===0 && parentLogical ? parentLogical : result.logical);
// if mixed ANDs or ORs with other keys, create one child and then append to it all remaining queries
else if(child) child.parse(result.queries[i], result.logical);
else {
child = query.append(parentLogical);
child.parse(result.queries[i], result.logical);
}
}
}
// direct value query, only first will have parentlogical, next has 'AND'
else if(k===0) addQuery(query, result, parentLogical);
else addQuery(query, result, 'AND');
if(modified.key) delete builtQuery[modified.key]; // - remove modified.key after parse
}
function addQuery(query, result, logical){
child = query.append(logical);
child.type = types[result.typeName];
child.value = result.value;
child.setFieldByName(result.fieldName, true); // reset if defined, because default field (first) was already set
child.resolveValueNames();
child.operator = result.operator; // force change operator to show original query operator, even if field has disabled changing operator
}
return query;
}
// date parse regex
var regexIso8601 = /^(\d{4}|\+\d{6})(?:-(\d{2})(?:-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})\.(\d{1,})(Z|([\-+])(\d{2}):(\d{2}))?)?)?)?$/;
var regexIsoStrict = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
function parseValueType(value){
var type, match, milliseconds;
if(typeof value==='boolean') type = 'boolean';
else if(typeof value==='number') type = 'number';
else if(value instanceof Date) {
if(value.getHours() === 0 && value.getMinutes() === 0 && value.getSeconds() === 0 && value.getMilliseconds() === 0) type = 'date';
else type = 'datetime';
}
else if(typeof value==='string') {
match = value.match(queryConfig.useStrictDateParser ? regexIsoStrict : regexIso8601);
if(match) milliseconds = Date.parse(match[0]);
if (!isNaN(milliseconds)) {
value = new Date(milliseconds);
if(value.getHours() === 0 && value.getMinutes() === 0 && value.getSeconds() === 0 && value.getMilliseconds() === 0) type = 'date';
else type = 'datetime';
}
else type = 'string';
}
//else if(Array.isArray(value)) type = 'array';
//else if(Object.prototype.toString.call(value)==='[object Object]') type = 'object';
return {
type:type,
value:value
};
}
var queries = {
AND:{ // called on build when AND operator
build: function(value){
var $and = [], andVal;
for(var i=0;i<(value.length||0);i++){
andVal = build(value[i], true);
if(Object.keys(andVal).length) $and.push(andVal);
}
return $and.length ? { $and: $and } : {};
}
},
OR:{ // called on build when OR operator
build: function(value){
var $or = [], orVal;
for(var i=0;i<(value.length||0);i++){
orVal = build(value[i], true);
if(Object.keys(orVal).length) $or.push(orVal);
}
return $or.length ? { $or: $or } : {};
}
},
VALUE:{ // if parsed query value is not recognized object, this will be called
parse: function(key, value){
var siblings = [], sibling;
var vt = parseValueType(value), type = vt.type;
value = vt.value;
if(Object.prototype.toString.call(value)==='[object Object]'){
for(var prop in value){
sibling = (queries[prop] || queries.VALUE).parse(key, value[prop]);
if(sibling) siblings.push(sibling);
}
return siblings;
}
if(type) return {
fieldName: key,
typeName: type,
operator: type==='string' ? '$regex_exact' : '$eq',
value: value
};
}
},
$and:{
parse: function(key, value){
// key = null (if root), or 0,1,2 (if inside other logical operator)
// value = [ {subquery}, {subquery} ]
if(!Array.isArray(value)) return null;
return {
logical: 'AND',
queries: value
};
}
},
$or:{
parse: function(key, value){
// key = null (if root), or 0,1,2 (if inside other logical operator)
// value = [ {subquery}, {subquery} ]
if(!Array.isArray(value)) return null;
return {
logical: 'OR',
queries: value
};
}
},
$eq:{
build: function(value){
return value;
},
parse: function(key, value){
var vt = parseValueType(value), type = vt.type;
value = vt.value;
if(type) return {
fieldName: key,
typeName: type,
operator: type==='string' ? '$regex_exact' : '$eq',
value: value
};
}
},
$exists:{
build: function(value){
return { $exists: value };
},
parse: function(key, value){
// value = true / false
if(typeof value==='boolean') return {
fieldName: key,
typeName: 'object',
operator: '$exists',
value: value
};
}
},
$size:{
build: function(value){
return { $size: value };
},
parse: function(key, value){
// value = true / false
if(typeof value==='number') return {
fieldName: key,
typeName: 'array',
operator: '$size',
value: value
};
}
},
$lt:{
build: function(value){ return { $lt: value }; },
parse: function(key, value){
var vt = parseValueType(value), type = vt.type;
value = vt.value;
if(type==='number' || type==='date' || type==='datetime') return {
fieldName: key,
typeName: type,
operator: '$lt',
value: value
};
}
},
$lte:{
build: function(value){ return { $lte: value }; },
parse: function(key, value){
var vt = parseValueType(value), type = vt.type;
value = vt.value;
if(type==='number' || type==='date' || type==='datetime') return {
fieldName: key,
typeName: type,
operator: '$lte',
value: value
};
}
},
$gt:{
build: function(value){ return { $gt: value }; },
parse: function(key, value){
var vt = parseValueType(value), type = vt.type;
value = vt.value;
if(type==='number' || type==='date' || type==='datetime') return {
fieldName: key,
typeName: type,
operator: '$gt',
value: value
};
}
},
$gte:{
build: function(value){ return { $gte: value }; },
parse: function(key, value){
var vt = parseValueType(value), type = vt.type;
value = vt.value;
if(type==='number' || type==='date' || type==='datetime') return {
fieldName: key,
typeName: type,
operator: '$gte',
value: value
};
}
},
$regex:{
build: function(value){
if(queryConfig.useRegexBracketsWrap) value = '(' + value + ')';
return {
$regex: value
};
},
parse: function(key, value){
var operator, op, match;
if(queryConfig.useRegexBracketsWrap && typeof value === 'string' && value[0] === '(' && value[ value.length-1 ] === ')'){
value = value.slice(1, value.length - 1);
}
else for(var i=0;i<types.string.operators.length;i++){
op = types.string.operators[i];
if(queries[op] && queries[op].check && (match = queries[op].check(value)) !== undefined) {
operator = op;
value = match;
break;
}
}
return {
fieldName: key,
typeName: 'string',
operator: operator || '$regex',
value: value
};
}
},
$regex_exact:{ // fake regex shortcut - this means simple equal
build: function(value){
return value;
}
},
$regex_contains:{ // regex shortcut
build: function(value){
value = escapeRegExp(value); //.replace(/^\//,'').replace(/\/[gimy]*$/,'');
return { $regex: '.*' +value+ '.*' };
},
check: function(value){
value = ( value.match(/^\.\*(.*)\.\*$/ ) || [] )[1];
if( isRegexString(value) ) return undefined;
return value === undefined ? undefined : unEscapeRegExp(value);
}
},
$regex_ncontains:{ // regex shortcut
build: function(value){
value = value = escapeRegExp(value);
return { $regex: '^((?!' +value+ ').)*$' };
},
check: function(value){
value = (value.match(/^\^\(\(\?\!(.*)\)\.\)\*\$$/) || [])[1];
if( isRegexString(value) ) return undefined;
return value === undefined ? undefined : unEscapeRegExp(value);
}
},
$regex_begins:{ // regex shortcut
build: function(value){
value = escapeRegExp(value);
return { $regex: '^' +value+ '.*' };
},
check: function(value){
value = (value.match(/^\^(.*)\.\*$/) || [])[1];
if( isRegexString(value) ) return undefined;
return value === undefined ? undefined : unEscapeRegExp(value);
}
},
$regex_nbegins:{ // regex shortcut
build: function(value){
value = escapeRegExp(value);
return { $regex: '^(?!' +value+ ').*$' };
},
check: function(value){
value = (value.match(/^\^\(\?\!(.*)\)\.\*\$$/) || [])[1];
if( isRegexString(value) ) return undefined;
return value === undefined ? undefined : unEscapeRegExp(value);
}
},
$regex_ends:{ // regex shortcut
build: function(value){
value = escapeRegExp(value);
return { $regex: '.*' +value+ '$' };
},
check: function(value){
value = (value.match(/^\.\*(.*)\$$/) || [])[1];
if( isRegexString(value) ) return undefined;
return value === undefined ? undefined : unEscapeRegExp(value);
}
},
$regex_nends:{ // regex shortcut
build: function(value){
value = escapeRegExp(value);
return { $regex: '^(?!.*' +value+ '$)' };
},
check: function(value){
value = (value.match(/^\^\(\?\!\.\*(.*)\$\)$/) || [])[1];
if( isRegexString(value) ) return undefined;
return value === undefined ? undefined : unEscapeRegExp(value);
}
},
$ne:{
build: function(value){ return { $ne: value }; },
parse: function(key, value){
var vt = parseValueType(value), type = vt.type;
value = vt.value;
if(type) return {
fieldName: key,
typeName: type,
operator: '$ne',
value: value
};
}
},
$in:{
build: function(value){
if(typeof value==='string'){
value = value.replace(/,\s+/g,',') // replace whitespace before commas
.replace(/\s+,/g,',') // replace whitespace after commas
.replace(/^,/,'') // replace comma in begin of string
.replace(/,$/,'') // replace comma in end of string
.split(',');
}
return { $in: value };
},
parse: function(key, value){
if(Array.isArray(value)) return {
fieldName: key,
typeName: 'string',
operator: '$in',
value: value.join(', ')
};
}
},
$nin:{
build: function(value){
if(typeof value==='string'){
value = value.replace(/,\s+/g,',') // replace whitespace before commas
.replace(/\s+,/g,',') // replace whitespace after commas
.replace(/^,/,'') // replace comma in begin of string
.replace(/,$/,'') // replace comma in end of string
.split(',');
}
return { $nin: value };
},
parse: function(key, value){
if(Array.isArray(value)) return {
fieldName: key,
typeName: 'string',
operator: '$nin',
value: value.join(', ')
};
}
}
};
//var exampleQuery = [ //.OR=true
// 'field operator value',
// [ //.AND=true
// [
// 'field operator value',
// 'field operator value',
// [ //.AND=true
// 'field operator value'
// ]
// ],
// // AND
// 'field operator value'
// ]
//]
function newQuery(logical){
var q = [];
q.options = {}; // additional query options
q.sortBy = [];
q.build = function(excludeSort){ return build.call(this, this, excludeSort); };
q.parse = function(builtQuery, logical){ return parse.call(this, builtQuery, logical); };
q.fill = function(builtQuery){
this.splice(0, this.length); // clear array
this.parse(builtQuery); // start with first child
if((!this.parent || !this.parent()) && this.length===0) this.append('AND'); // if this is root query and there is no child, add one
if(q.runValueNameResolver) q.runValueNameResolver();
if(q.onFill) q.onFill();
return q;
};
q.isEmpty = isEmpty; // is both, sort and query empty
q.isQueryEmpty = isQueryEmpty;
q.isSortEmpty = isSortEmpty;
q.isDirty = isDirty;
q.setDirty = setDirty;
q.clear = clear;
q.newQuery = newQuery;
q.templates = templates;
q.fields = this.fields; // inherit fields
q.types = this.types; // inherit types
q.onlyPredefinedFields = this.onlyPredefinedFields; // inherit onlyPredefinedFields
q.logical = logical || 'AND'; // default logical is AND
q.append = append;
q.next = next;
q.levelDown = levelDown;
q.remove = remove;
q.reset = reset;
q.setFieldByName = setFieldByName;
q.resolveValueNames = resolveValueNames;
q.setField = setField;
q.setOperator = setOperator;
q.setType = setType;
q.addSort = addSort;
q.removeSort = removeSort;
q.toggleSortDirection = toggleSortDirection;
q.setSortByName = setSortByName;
q.setSortField = setSortField;
var parent;
q.root = q.getRoot = function(){ return parent ? parent.getRoot() : q; };
q.parent = q.getParent = function(){ return parent; };
q.setParent = function(newParent){ parent = newParent; };
// sometimes, it is better to resolve all names by one BE call, so q.resolveAllValueNames is called instead of field.resolveValueNames
if(!parent) q.runValueNameResolver = function(){
var q = this;
var fieldValsToResolve = {}; // field.key:{ valueNames }
var needsToResolveSomeField = false;
var fieldsByKey = {};
q.fields.forEach(function(field){
var valsToResolve = {};
// cache fields by key, if someone wants to use other field props than key
fieldsByKey[ field.key ] = field;
if(field.valueNames) {
for(var val in field.valueNames) {
if(field.valueNames[val] === null || field.valueNames[val] === undefined) {
valsToResolve[ val ] = null;
}
}
fieldValsToResolve[field.key] = valsToResolve;
if(!Object.keys(valsToResolve).length) delete fieldValsToResolve[field.key];
else if(field.resolveValueNames) field.resolveValueNames(valsToResolve, function(resolvedValNames){
resolvedValNames = resolvedValNames || {};
for(var val in resolvedValNames) field.valueNames[val] = resolvedValNames[val];
});
}
});
if(q.resolveAllValueNames && Object.keys(fieldValsToResolve).length) {
q.resolveAllValueNames(fieldValsToResolve, fieldsByKey, function(resolvedFieldVals){
q.fields.forEach(function(field){
if(resolvedFieldVals[ field.key ]) object.merge(field.valueNames, resolvedFieldVals[ field.key ]);
});
});
}
};
// set initial query state
q.reset();
return q;
}
function append(logical){
var q = this.newQuery(logical);
// make reference to parent non enumerable to prevent stack overflow when merging (it is circular reference)
q.setParent(this);
this.push(q);
return q;
}
function levelDown(logical){
var self = this;
if(!self.parent()) return;
// if this is only child of parent disable levelDovn
if(self.parent().length<=1) return;
var index = self.parent().indexOf(self);
var wrapper = self.next(self.logical);
self.parent().splice(index, 1); // remove element from parent
self.logical = 'AND'; // default logical if first element
self.setParent(wrapper); // now, parent is wrapper
wrapper.push(self); // append element to wrapper
return wrapper;
}
function next(logical){
var self = this;
if(!self.parent()) return;
var index = self.parent().indexOf(self);
var q = this.newQuery(logical);
q.setParent(self.parent());
self.parent().splice(index+1,0,q);
return q;
}
function remove(){
var self = this;
if(!self.parent()) return;
// don't remove last root element, just reset field
if(!self.parent().parent() && self.parent().length===1) return self.reset();
// if removing last child of element, remove also element
if(self.parent().length===1) return self.parent().remove();
var index = self.parent().indexOf(self);
self.parent().splice(index,1);
self = null;
}
function reset(){
var q = this;
if(q.fields.length) { // default field is first when there are some
q.field = q.fields[0];
q.type = types[ q.field.type ];
if(!q.type) throw new Error('Field type "' +q.field.type+ '" not recognized, please choose one from "' +Object.keys(types).join(', ')+ '"');
q.fieldName = q.field.name;
q.operator = q.type.operators[ q.field.operatorIndex||0 ];
}
else {
q.field = q.field || {};
q.type = types[ q.type || q.types[0] ];
q.operator = q.type.operators[0];
}
q.value = null;
}
function clear(){
this.splice(0, this.length); // clear array
this.setDirty(false);
return this;
}
function isEmpty(builtQuery){
builtQuery = builtQuery || this.build();
return this.isQueryEmpty(builtQuery) && this.isSortEmpty(builtQuery);
}
function isQueryEmpty(builtQuery){
builtQuery = builtQuery || this.build();
var keysLength = Object.keys(builtQuery).length;
return keysLength === 0 || (keysLength === 1 && builtQuery.hasOwnProperty('$sort'));
}
function isSortEmpty(builtQuery){
builtQuery = builtQuery || this.build();
return Object.keys(builtQuery.$sort||{}).length === 0;
}
function setDirty(isDirty){
this.$dirty = isDirty = false ? false : true;
this.$touched = isDirty = false ? false : true;
return this;
}
function isDirty(){
return this.$dirty;
}
function setFieldByName(fieldName, resetPrevField){
if(resetPrevField) delete this.field;
if(fieldName){
var fieldNameLower = fieldName.toLowerCase();
for(var i=0;i<this.fields.length;i++){
if(this.fields[i].key===fieldName || this.fields[i].nameLower===fieldNameLower){
return this.setField(this.fields[i]); // match with predefined fields
}
else if(this.fields[i].match && (fieldName.match(this.fields[i].match) || fieldNameLower.match(this.fields[i].match))){
if(this.field && this.field.field === this.fields[i].field) return;
else return this.setField(this.fields[i], fieldName); // match with predefined fields
}
}
}
this.fieldName = fieldName;
this.field = { key:fieldName };
}
function resolveValueNames() {
var q = this;
var root = q.getRoot();
var rootField = root.fields.filter(function(field){
return field.key === (q.field || {}).key;
})[0];
if(!rootField) return;
rootField.valueNames = rootField.valueNames || {};
// set suggestion getter for refreshing purposes
Object.defineProperty(q, 'suggestion', {
get: function() { return rootField.valueNames[ q.value ] || q.value; },
set: function(name) { rootField.valueNames[ q.value ] = name; },
});
if(rootField.valueNames[ q.value ]) return; // already resolved
else if(q.field.resolveValueName) { // single value resolve
q.field.resolveValueName(q.value, function(valueName){
if(typeof valueName === 'string') {
q.suggestion = valueName;
rootField.valueNames[ q.value ] = valueName;
}
else {
if(!Array.isArray(valueName)) valueName = [valueName];
for(var i=0;i<valueName.length;i++){
if(valueName[i].key === q.value) {
q.suggestion = valueName[i].name;
rootField.valueNames[ q.value ] = valueName[i].name;
return;
}
}
}
});
}
else { // all value names resolve
// register another value which need to be resolved
rootField.valueNames[ q.value ] = null;
}
}
function setField(field, fieldName){
// field type changed, reset value
if(this.type.name !== field.type){
this.type = types[ field.type ];
if(!this.type) throw new Error('Field type "' +field.type+ '" not recognized, please choose one from "' +Object.keys(types).join(', ')+ '"');
// this.operator = this.type.operators[0];
this.value = null;
}
var prevField = this.field;
this.field = angular.copy(field||{});
this.fieldName = fieldName || this.field.name;
// set default operator, if field has operatorIndex
this.operator = this.type.operators[ this.field.operatorIndex||0 ];
if(field.onSet) field.onSet(this, prevField);
}
function setOperator(operator){
if(this.type.templates && this.type.templates[this.operator] !== this.type.templates[operator]) this.value = null;
this.operator = operator;
}
function setType(type){
this.type = types[ type ];
this.operator = this.type.operators[0];
this.value = null; // clear value because of operator changed
}
function addSort(index){
var s = {};
if(this.fields.length){
s.fieldName = this.fields[0].name;
s.name = this.fields[0].name;
s.key = this.fields[0].key;
s.direction = 1;
}
if(!isNaN(index)) this.sortBy.splice(index+1,0,s);
else this.sortBy.push(s);
}
function removeSort(index){
this.sortBy.splice((!isNaN(index) ? index : this.sortBy.length-1),1);
}
function toggleSortDirection(index){
index = index || 0;
this.sortBy[index].direction = this.sortBy[index].direction===1 ? -1 : 1;
}
function setSortByName(fieldName, index){
index = index || 0;
if(fieldName){
var fieldNameLower = fieldName.toLowerCase();
for(var i=0;i<this.fields.length;i++){
if(this.fields[i].key===fieldName || this.fields[i].nameLower===fieldNameLower){
// match with predefined fields
this.sortBy[index].fieldName = this.fields[i].name;
this.sortBy[index].name = this.fields[i].name;
this.sortBy[index].key = this.fields[i].key;
return this.sortBy[index];
}
}
}
this.sortBy[index].fieldName = fieldName;
this.sortBy[index].key = fieldName;
return this.sortBy[index];
}
function setSortField(field, index){
index = index || 0;
this.sortBy[index].fieldName = field.name;
this.sortBy[index].name = field.name;
this.sortBy[index].key = field.key;
}
function filterByName(fieldName, currentFieldName){
var result = [], fields = this, fieldNameLower = (fieldName || '').toLowerCase();
if(!fieldName || fieldName===currentFieldName) return fields;
for(var i=0;i<fields.length;i++){
if(fields[i].nameLower && fields[i].nameLower.match( new RegExp('.*' +fieldNameLower+ '.*')))
result.push(fields[i]);
}
return result;
}
// field behaviour usage: behaviour:'keyValueArray',
// or behaviour:{ keyValueArray:{ prefix:'variants.', idKey:'id', valueKey:'value' } }
var fieldBehaviours = {
keyValueArray: function(opts){
var field = this;
var propName = field.field;
var keyPrefix = opts.prefix || opts.keyPrefix || '';
var idKey = opts.key || opts.idKey;
var valueKey = opts.value || opts.valueKey;
if(!idKey || !valueKey) throw new Error('neQuery: Cannot set field behaviour, "idKey" or "valueKey" not defined');
return {
match: new RegExp(propName+'.*'),
build:function(key, expression, query){
var $elemMatch = {};
$elemMatch[idKey] = query.fieldName.replace(propName+'.','');
$elemMatch[valueKey] = expression;
return {
key: keyPrefix+propName,
value:{
$elemMatch:$elemMatch
}
}
},
merge: function(key, toMerge, merged){
if(toMerge[key].$elemMatch){
if(merged[key].$all) {
merged[key].$all.push(toMerge[key]);
}
else merged[key] = {
$all:[
merged[key],
toMerge[key]
]
};
}
return merged;
},
parse: function(key, value, parentLogical){
// $elemMatch:{ id:'asdasd', value:'asdasd' }
if(value.$elemMatch){
var fieldName = key + '.' + value.$elemMatch[ idKey ];
return {
key: fieldName.replace(keyPrefix,''),
value: value.$elemMatch[ valueKey ]
};
}
else if(Array.isArray(value.$all)){
var result = [];
for(var i=0;i<value.$all.length;i++){
if(value.$all[i].$elemMatch){
result[i] = {
value: {},
logical: i>0 ? 'AND' : parentLogical
};
result[i].value[ propName+'.'+value.$all[i].$elemMatch[ idKey ] ] = value.$all[i].$elemMatch[ valueKey ];
}
}
return result;
}
}
};
}
};
function Query(name, fields){ // Query(opts)
var opts = {};
if(arguments.length===1){
if(Array.isArray(arguments[0])){
fields = arguments[0];
name = null;
}
else if(angular.isObject(arguments[0])) {
opts = arguments[0];
fields = opts.fields;
name = opts.name;
}
}
fields = fields || [];
for(var i=0;i<fields.length;i++){
fields[i].key = fields[i].key || fields[i].field || fields[i].property;
fields[i].name = local.translate(fields[i].name || fields[i].key);
fields[i].nameLower = (fields[i].name || '').toLowerCase();
if(fields[i].behaviour){ // init behaviour = copy merge, parse, build methods
var behName=null, behOpts={}, behFnc=null;
if(typeof fields[i].behaviour === 'string') behName = fields[i].behaviour;
else {
behName = Object.keys(fields[i].behaviour)[0];
behOpts = fields[i].behaviour[ behName ];
}
var beh = fieldBehaviours[ behName ];
if(beh){
var bMethods = beh.call(fields[i], behOpts);
for(var bkey in bMethods){
fields[i][bkey] = bMethods[ bkey ];
}
}
}
// if type is set, disable changing type
if(fields[i].type) fields[i].disableType = true;
fields[i].type = fields[i].type || fields[i].defaultType || defaultType; // set default type if field has no type
// config can disable some operators
fields[i].allowedOperatorIndexes = fields[i].allowedOperatorIndexes;
// if operator is set, disable changing operator
if(fields[i].operatorIndex >= 0) fields[i].disableOperator = true;
fields[i].operatorIndex = fields[i].operatorIndex || fields[i].defaultOperatorIndex;
// set list template if values are set, but template not
if(fields[i].values && !fields[i].template) fields[i].template = templates.list;
// config can define emptyValues - values which can be valid but considered as empty, e.g. empty string, zero, etc...
fields[i].emptyValues = fields[i].emptyValues || fields[i].ignoreValues;
fields[i].isEmptyValue = fields[i].isEmptyValue || function(value){
if(value===null || value===undefined) return true;
return (this.emptyValues||this.type.emptyValues) ? (this.emptyValues||this.type.emptyValues).indexOf(value) > -1 : false;
};
// wrap load suggestions method
fields[i].loadSuggestions = fields[i].loadSuggestions || fields[i].getSuggestions || fields[i].suggestions;
fields[i].onlySuggestedValues = fields[i].onlySuggestedValues;
if(fields[i].loadSuggestions) {
fields[i].resetOnFieldChange = true;
fields[i].onSet = fields[i].onSet || function(query, prevField){
if(prevField){
query.value = null;
query.suggestion = '';
query.suggestions = [];
}
else query.suggestion = query.suggestion || query.value;
};
fields[i].template = fields[i].template || templates.suggestions;
fields[i].createSuggestions = (function(field){
field.suggestionMinLength = field.suggestionMinLength >= 0 ? field.suggestionMinLength : (field.suggestionMinSearchLength >= 0 ? field.suggestionMinSearchLength : 3);
var loadSuggestionsDebounced = object.debounce(loadSuggestions, field.suggestionDebounce >= 0 ? field.suggestionDebounce : 350);
function loadSuggestions(query, searchText){
searchText = searchText || '';
query.page = query.page || field.page || 1;
query.limit = query.limit || field.limit || 10;
if(searchText.length >= field.suggestionMinLength) field.loadSuggestions.call(query, searchText, function(values, pagination){
query.suggestions = values.map(function(value) {
return {
key: value.key || value,
name: value.name || value.key || value
};
});
query.pagination = pagination;
query.page = pagination.page || query.page;
query.limit = pagination.limit || query.limit;
});
}
return function(query, searchText, debounce){
if(debounce) return loadSuggestionsDebounced(query, searchText);
else return loadSuggestions(query, searchText);
};
})(fields[i]);
}
}
fields.filterByName = filterByName;
var q = newQuery.call({ fields:fields, types:Object.keys(types) },'AND'); // default logical is AND
q.name = name;
q.onlyPredefinedFields = opts.onlyPredefinedFields;
q.append('AND');
return q;
}
Query.templates = templates;
Query.fieldBehaviours = fieldBehaviours;
return Query;
}])
.factory('neQueryTests', ['NeQuery','neObject', function(Query, object){
return function(){
var q = new Query();
function testQuery(name, inputQuery, compareQuery){
var builtQuery = q.fill(inputQuery).build();
var isEqual = object.deepEqual(compareQuery || inputQuery, builtQuery, function(key){
return key==='$sort';
});
if(!isEqual) console.warn('Query test failed "' +name+ '", input query do not match built one', compareQuery || inputQuery, builtQuery);
else console.log('Query test "' +name+ '" - OK');
}
/*
* simple queries
*/
testQuery('simple range query', { field1:{ $gte:1, $lte:2 } });
testQuery('simple and[1,2]', { field1:'value1', field2:'value2' });
testQuery('simple and[1,2] with $and operator', { $and:[{field1:'value1'}, {field2:'value2'} ] }, { field1:'value1', field2:'value2' });
testQuery('simple or[1,2] with $or operator', { $or:[{field1:'value1'}, {field2:'value2'} ] });
/*
* nested queries
*/
// or[ and[1,2], or[1,2], and[1,2] ]
testQuery('or[ and[1,2], or[1,2], and[1,2] ]', {
$and:[
{
$or:[
{ field1_or1: 'value1_or1' },
{ field2_or1: 'value2_or1' }
]
},
{
$or:[
{ field1_or2: 'value1_or2' },
{ field2_or2: 'value2_or2' }
]
}
]
});
// or[ or[1,2], and[1,2], or[1,2] ]
testQuery('or[ or[1,2], and[1,2], or[1,2] ]', {
$or:[
{
$or:[
{ field1_or1: 'value1_or1' },
{ field2_or1: 'value2_or1' }
]
},
{
$and:[
{ field1_and1: 'value1_and1' },
{ field2_and1: 'value2_and1' }
]
},
{
$or:[
{ field1_or2: 'value1_or2' },
{ field2_or2: 'value2_or2' }
]
}
]
},{
$or:[
{
$or:[
{ field1_or1: 'value1_or1' },
{ field2_or1: 'value2_or1' }
]
},
{
field1_and1: 'value1_and1',
field2_and1: 'value2_and1'
},
{
$or:[
{ field1_or2: 'value1_or2' },
{ field2_or2: 'value2_or2' }
]
}
]
});
// and[ or[1,2], and[1,2], or[1,2] ]
testQuery('and[ or[1,2], and[1,2], or[1,2] ]', {
$and:[
{
$or:[
{ field1_or1: 'value1_or1' },
{ field2_or1: 'value2_or1' }
]
},
{
$and:[
{ field1_and1: 'value1_and1' },
{ field2_and1: 'value2_and1' }
]
},
{
$or:[
{ field1_or2: 'value1_or2' },
{ field2_or2: 'value2_or2' }
]
}
]
},{
$and:[
{
$or:[
{ field1_or1: 'value1_or1' },
{ field2_or1: 'value2_or1' }
]
},
{
field1_and1: 'value1_and1',
field2_and1: 'value2_and1'
},
{
$or:[
{ field1_or2: 'value1_or2' },
{ field2_or2: 'value2_or2' }
]
}
]
});
// and[ or[1,2], or[1,2] ]
testQuery('and[ or[1,2], or[1,2] ]', {
$and:[
{
$or:[
{ field1_or1: 'value1_or1' },
{ field2_or1: 'value2_or1' }
]
},
{
$or:[
{ field1_or2: 'value1_or2' },
{ field2_or2: 'value2_or2' }
]
}
]
});
// or[ and[1,2], and[1,2] ]
testQuery('or[ and[1,2], and[1,2] ]', {
$or:[
{
$and:[
{ field1_and1: 'value1_and1' },
{ field2_and1: 'value2_and1' }
]
},
{
$and:[
{ field1_and2: 'value1_and2' },
{ field2_and2: 'value2_and2' }
]
}
]
},{
$or:[
{ field1_and1: 'value1_and1', field2_and1: 'value2_and1' },
{ field1_and2: 'value1_and2', field2_and2: 'value2_and2' }
]
});
/*
* nested, nested with ragne queries
*/
// or[ or[1,range], and[range,1,2, or[1,2] ], or[range,range] ]
testQuery('or[ or[1,range], and[range,1,2], or[range,range] ]', {
$or:[
{
$or:[
{ field1_or1: 'value1_or1' },
{ field2_or1: { $gt:1, $lt:100 } }
]
},
{
$and:[
{ field1_and1: { $gt:1, $lt:100 } },
{ field1_and1: 'value1_and1' },
{ field2_and1: 'value2_and1' },
{
$or:[
{ field1_and1_or: { $gte:1, $lte:100 } },
{ field2_and1_or: 'value2_and1_or' }
]
}
]
},
{
$or:[
{ field1_or2: { $gte:1, $lte:100 } },
{ field2_or2: { $gte:1, $lte:100 } }
]
}
]
},{
$or:[
{
$or:[
{ field1_or1: 'value1_or1' },
{ field2_or1: { $gt:1, $lt:100 } }
]
},
{
$and:[
{ field1_and1: { $gt:1 } },
{ field1_and1: { $lt:100 } },
{ field1_and1: 'value1_and1' },
{ field2_and1: 'value2_and1' },
{
$or:[
{ field1_and1_or: { $gte:1, $lte:100 } },
{ field2_and1_or: 'value2_and1_or' }
]
}
]
},
{
$or:[
{ field1_or2: { $gte:1, $lte:100 } },
{ field2_or2: { $gte:1, $lte:100 } }
]
}
]
});
};
}]);
/**
* NE REST
* ***************************************************************************************************************************
*/
/*
* RestResource Constructor
*
* @example:
*
* // define resource
* var cars = new RestResource({
baseUrl:'https://yourservice/cars',
// parsing
dataKey:'data', // data key, if data is property of response object, e.g. { data:..., status:...}
resourceListKey: 'this', // list of resources - if there is no wrapper in response object, data is resource, resourceListKey:'this'
resourceKey: 'this', // single resource data - if there is no wrapper in response object, data is resource, resourceKey:'this'
idKey:'id', // key of id, sometimes id is represented by another key, like "_id", or "productId"
errorKey:'data', // if response status !== 200, parse errors
// if response contains pagination
paginationCountKey:'pagination.count',
paginationPageKey:'pagination.page',
paginationPagesCountKey:'pagination.pages',
paginationHasNextKey:'pagination.next',
paginationHasPrevKey:'pagination.prev',
// additional data to map to result - will be added only if it is defined in response
additionalDataKeys:{
// 'data.max_score':'maxScore' - example result of "one" { id:..., maxScore:24 }, or "all" [{ id:... }, { id:... }].maxScore = 24
},
defaultQuery:{},
urlBuilder: urlBuilder,
queryStringBuilder: queryStringBuilder,
// queryString builder preferences
queryKey: null, // if there is query Key, whole query will be stringified into one query string key
queryPageKey: '$page',
queryLimitKey: '$limit',
querySortKey: '$sort',
// onError: function(status, data){ ... }
// onSuccess: function(status, data){ ... }
// onProgress: function(status, data){ ... }
transformRequest:{
removePrefixedProps:'$'
},
transformResponse:{
dateStringsToDates:true
},
commands:{
one:{
method:'GET',
url:'/{id}',
// extend resource level options in current command
// idKey, dataKey, resourceKey, resourceListKey, errorKey, pagination keys, headers, transformations, etc ...
},
all:{ method:'GET', isList:true },
find:{ method:'GET', isList:true }, // alias for "all"
create:{ method:'POST', url:'/{id}' },
update:{ method:'PUT', url:'/{id}' },
remove:{ method:'DELETE', url:'/{id}' },
// upload:{ method:'POST-MULTIPART', url:'/{id}' }
// customCommandName:{ method:'POST', url:'/{id}/{command}/{deep.prop1}/{propTwo}.json', body:true }
}
});
// use resource:
// query is empty
cars.create( {body}, [successCallback,] [errorCallback]);
// query and body defined
cars.create( {query}, {body}, [successCallback,] [errorCallback]);
// id and body is defined
cars.create( {id}, {body}, [successCallback,] [errorCallback]);
// id is defined, query and body is empty
cars.one( {id}, [successCallback,] [errorCallback]);
// id, query and body is empty, usually when getting all documents
cars.find( [successCallback,] [errorCallback]);
// http method with body, but body is not set - use option "body:false" in command opts to avoid resource thinking that first argument is body
cars.find( {query}, [successCallback,] [errorCallback]);
// upload can have progressCallback
cars.create( {body}, [successCallback,] [errorCallback,] [progressCallback]);
*
*/
// TODO:
// request, response transform:
// datetime json parser - test
// removePrefixedProps - test
// escapeKeyNames - after parsing
// objectToArray - after parsing
// syncDST - after parsing
// changeZone - after parsing
angular.module('neRest',['neObject','neNotifications','neLoading'])
.config(['$httpProvider', function($httpProvider) {
// add default XHR header
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}])
.factory('NeResourceTransformators.dateStringsToDates', ['neObject', function(object){
return object.dateStringsToDates;
}])
.factory('NeResourceTransformators.removePrefixedProps', ['neObject', function(object){
return object.removePrefixedProps;
}])
.factory('NeRestResource', ['$http',
'$timeout',
'neObject',
'neNotifications',
'neLoading',
'NeResourceTransformators.dateStringsToDates',
'NeResourceTransformators.removePrefixedProps',
function($http, $timeout, object, notify, loading, dateStringsToDates, removePrefixedProps){
var defaultResourceOpts = {
baseUrl:'/yoururl',
urlEndSlash:false,
// default headers for every request
headers:{ 'Content-Type': 'application/json' },
// parsing
dataKey:'data', // data key, if data is property of response object, e.g. { data:..., status:...}
resourceListKey: 'this', // list of resources - if there is no wrapper in response object, data is resource, resourceListKey:'this'
resourceKey: 'this', // single resource data - if there is no wrapper in response object, data is resource, resourceKey:'this'
idKey:'id', // key of id, sometimes id is represented by another key, like "_id", or "productId"
errorKey:'data', // if response status !== 200, parse errors
// if response contains pagination
paginationCountKey:'pagination.count',
paginationPageKey:'pagination.page',
paginationPagesCountKey:'pagination.pages',
paginationHasNextKey:'pagination.next',
paginationHasPrevKey:'pagination.prev',
// additional data to map to result - will be added only if it is defined in response
additionalDataKeys:{
// 'data.max_score':'maxScore' - example result of "one" { id:..., maxScore:24 }, or "all" [{ id:... }, { id:... }].maxScore = 24
},
responseErrors: {
'400':function(data, status, headers){
var text = data;
if(angular.isObject(data)) {
text = '';
for(var key in data){
text += key + ': ' + data[key] + ', ';
}
}
notify.error('Validation Failed', text);
},
'403':function(data, status, headers){
notify.error('Access Denied', 'Try logout and login again, please');
},
'404':function(data, status, headers){
notify.error('Document or his version not found','Try refresh page, please');
},
'409':function(data, status, headers){
notify.error(data);
},
'default':function(data, status, headers){
notify.error('Connection Failed', 'Try later, please');
}
},
defaultQuery:{},
urlBuilder: urlBuilder,
queryStringBuilder: queryStringBuilder,
// queryString builder preferences
queryKey: null, // if there is query Key, whole query will be stringified into one query string key
queryPageKey: '$page',
queryLimitKey: '$limit',
querySortKey: '$sort',
// onError: function(status, data){ ... }
// onSuccess: function(status, data){ ... }
// onProgress: function(status, data){ ... }
transformRequest:{
removePrefixedProps:'$'
},
transformResponse:{
dateStringsToDates:true
},
commands:{
one:{
method:'GET',
url:'/{id}',
// extend resource level options in current command
// idKey, dataKey, resourceKey, resourceListKey, errorKey, pagination keys, headers, transformations, etc ...
},
all:{ method:'GET', isList:true },
find:{ method:'GET', isList:true }, // alias for "all"
create:{ method:'POST', url:'/{id}' },
update:{ method:'PUT', url:'/{id}' },
remove:{ method:'DELETE', url:'/{id}' },
// upload:{ method:'POST-MULTIPART', url:'/{id}' }
// customCommandName:{ method:'POST', url:'/{id}/{command}/{deep.prop1}/{propTwo}.json', body:true }
}
};
/*
* REQUEST BUILDERS
*/
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
function replaceStringAll(str, whatStr, withStr){
var regexp = new RegExp( escapeRegExp(whatStr), 'g' );
return str.replace(regexp, withStr);
}
function unifyUrlPath(str){
str = str.indexOf('?') > -1 ? str.replace(/([^\/])\?/,'$1/?') : str +'/'; // add last slash to ensure server will know this is resource path, not static file
return str.replace(/([^:])(\/){2,}/g,'$1/'); // remove double slashes in path
}
function getUrlParams(urlTemplate){
var urlParams = (urlTemplate || '').match(/\{([^\{\}]+)/g) || [];
for(var i=0;i<urlParams.length;i++) urlParams[i] = urlParams[i].substring(1);
return urlParams;
}
function stringifyWithoutQuotes(value){
if(value===undefined || value===null) return '';
return JSON.stringify(value).replace(/^"/,'').replace(/"$/,'');
}
function urlBuilder(baseUrl, urlTemplate, params, cmdName) {
var resource = this;
urlTemplate = unifyUrlPath(urlTemplate || '');
var url = baseUrl ? baseUrl + '/' + urlTemplate : urlTemplate;
var urlParams = resource.options.commands[cmdName].urlParams;
var value, paramValue;
for(var i=0;i<urlParams.length;i++){
paramValue = object.deepGet(params, urlParams[i]);
value = urlParams[i] === '_command' ? cmdName : (paramValue===undefined ? '' : paramValue);
if(typeof value === 'string') value = encodeURIComponent(value).replace(/\//g, '%2F').replace(/\?/g, '%3F').replace(/#/g,'%23'); // escape "/","?","#"
url = replaceStringAll(url,'{' +urlParams[i]+ '}', stringifyWithoutQuotes(value));
}
if(resource.options.commands[cmdName].isFile) return unifyUrlPath(url).replace(/\/$/,''); // remove last slash if this is static file
else return unifyUrlPath(url);
}
function queryStringBuilder(query, cmdName) {
var resource = this,
queryString = '',
cmdOpts = resource.options.commands[cmdName],
opts = resource.options,
queryKey = cmdOpts.queryKey || opts.queryKey,
urlParams = cmdOpts.urlParams;
if(queryKey) {
// don't render empty query
if(Object.keys(query).length) return '?' + queryKey + '=' + JSON.stringify(query);
return '';
}
for(var key in query){
if(query.hasOwnProperty(key) && urlParams.indexOf(key) === -1) {
if(Array.isArray(query[key])){
for(var i=0;i<query[key].length;i++) queryString += '&'+key+'='+stringifyWithoutQuotes(query[key][i]);
}
else if(query[key] !== undefined) queryString += '&'+key+'='+stringifyWithoutQuotes(query[key]);
}
}
return queryString ? ('?' + queryString.substring(1)) : '';
}
/*
* RESOURCE PARSERS
*/
function parseResource(opts, cmdName, data, resourceData){
var cmdOpts = opts.commands[cmdName],
dataKey = cmdOpts.dataKey || opts.dataKey,
resourceKey = cmdOpts.resourceKey || opts.resourceKey,
idKey = cmdOpts.idKey || opts.idKey;
if(resourceData){
resourceData = object.deepGet(resourceData, resourceKey);
}
else if(data){
var parsedData = object.deepGet(data, dataKey);
resourceData = object.deepGet(parsedData, resourceKey);
}
if(resourceData) {
var id = object.deepGet(resourceData, idKey);
if(id !== undefined) resourceData.id = id;
}
return resourceData;
}
function parseResourceList(opts, cmdName, data){
var parsedData,
cmdOpts = opts.commands[cmdName],
isList = cmdOpts.isList,
dataKey = cmdOpts.dataKey || opts.dataKey,
resourceListKey = cmdOpts.resourceListKey || opts.resourceListKey;
parsedData = object.deepGet(data, dataKey);
if(resourceListKey) parsedData = object.deepGet(parsedData, resourceListKey);
var list = [];
if(Array.isArray(parsedData)) for(var i=0;i<parsedData.length;i++){
list.push(parseResource(opts, cmdName, null, parsedData[i]));
}
return list;
}
function parsePagination(opts, cmdName, data, query){
var cmdOpts = opts.commands[cmdName];
var queryPageKey = cmdOpts.queryPageKey || opts.queryPageKey;
var pagination = {
count: object.deepGet(data, cmdOpts.paginationCountKey || opts.paginationCountKey) || 0,
page: object.deepGet(data, cmdOpts.paginationPageKey || opts.paginationPageKey) || object.deepGet(query, queryPageKey) || 0,
pages: object.deepGet(data, cmdOpts.paginationPagesCountKey || opts.paginationPagesCountKey) || 0,
next: object.deepGet(data, cmdOpts.paginationHasNextKey || opts.paginationHasNextKey),
prev: object.deepGet(data, cmdOpts.paginationHasPrevKey || opts.paginationHasPrevKey)
};
// calculate has next/prev if page and pages are defined
if(pagination.page !== undefined && pagination.pages !== undefined && (pagination.next === undefined || pagination.prev === undefined)){
pagination.next = pagination.page < pagination.pages;
pagination.prev = pagination.page > 1;
}
return pagination;
}
function parseAdditionalKeys(opts, cmdName, data, parsedData){
var cmdOpts = opts.commands[cmdName],
value,
keys = cmdOpts.additionalDataKeys || opts.additionalDataKeys;
for(var key in keys){
value = object.deepGet(data, key);
if(value !== undefined) object.deepSet(parsedData, keys[key], value);
}
return parsedData;
}
/*
* RESPONSE HANDLERS
*/
function execCbs(ctx, fncs){
var args = [], i;
for(i=2;i<arguments.length;i++) args.push(arguments[i]);
for(i=0;i<fncs.length;i++){
if(typeof fncs[i] === 'function' && fncs[i].apply(ctx, args) === true) return;
}
}
function handleSuccess(httpOpts, query, opts, cmdName, successCbs){
return function(response){
var httpOpts = response.config,
cmdOpts = opts.commands[cmdName],
data = applyTransformators(copyData(response.data), cmdOpts.transformResponse),
status = response.status,
headers = response.headers,
isList = cmdOpts.isList,
parsedData;
if(isList) {
parsedData = parseResourceList(opts, cmdName, data) || [];
parsedData.pagination = parsePagination(opts, cmdName, data, query);
}
else {
parsedData = parseResource(opts, cmdName, data);
}
parsedData = parseAdditionalKeys(opts, cmdName, data, parsedData);
execCbs(httpOpts, [ cmdOpts.onData, opts.onData ], parsedData, (parsedData||{}).pagination, data, status, headers, isList, cmdName);
execCbs(httpOpts, successCbs, parsedData, (parsedData||{}).pagination, data, status, headers);
};
}
function handleError(httpOpts, query, opts, cmdName, errorCbs){
return function(response){
var httpOpts = response.config,
cmdOpts = opts.commands[cmdName],
data = applyTransformators(copyData(response.data), cmdOpts.transformResponse),
status = response.status,
headers = response.headers,
responseErrorCbs = errorCbs.concat([
(cmdOpts.responseErrors||{})[status] || (cmdOpts.responseErrors||{})['default'],
opts.responseErrors[status] || opts.responseErrors['default']
]),
errorKey = cmdOpts.errorKey || opts.errorKey,
parsedError = object.deepGet(data, errorKey);
execCbs(httpOpts, responseErrorCbs, parsedError, status, headers, response.data);
};
}
/*
* HTTP UPLOAD HANDLER
*/
var xhr = (function () {
try { return new XMLHttpRequest(); } catch (e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (e1) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (e2) {}
try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (e3) {}
throw new Error('This browser does not support XMLHttpRequest.');
})();
function upload(cmdName, query, httpOpts, successCbs, errorCbs, progressCbs){
var opts = this.options;
var url = httpOpts.url;
var headers = httpOpts.headers;
var data = httpOpts.data;
var ignoreLoading = httpOpts.ignoreLoading;
var fd = new FormData();
for(var key in data) {
if(data[key] instanceof Blob || data[key] instanceof File) {
fd.append(key, data[key], data[key].name);
}
else fd.append(key, data[key]);
}
function handleResponse(res, type) {
res = res || {};
var contentType = res.getResponseHeader('content-type');
var data = res.responseText;
var status = res.status ? parseInt(res.status) : 0;
if(contentType && contentType.substring(0,16)==='application/json') {
try { data = JSON.parse(res.responseText); }
catch(e) { status = 0; }
}
var response = {
data: data,
status: status,
headers: res.headers,
httpOpts: {},
};
xhrListeners('removeEventListener');
if(!ignoreLoading) loading.reqEnded();
if(status >= 200 && status <= 299) handleSuccess(httpOpts, query, opts, cmdName, successCbs)(response);
else handleError(httpOpts, query, opts, cmdName, errorCbs)(response);
}
function loadListener(e){ handleResponse(e.target, 'load'); }
function errorListener(e){ handleResponse(e.target, 'error'); }
function abortListener(e){ handleResponse(e.target, 'abort'); }
function progressListener(e) {
if(!progressCbs) return;
if (e.lengthComputable) execCbs(httpOpts, progressCbs, Math.ceil(100 * e.loaded / e.total));
else execCbs(httpOpts, progressCbs, 50); // Unable to compute progress information since the total size is unknown
}
function xhrListeners(elProp){
xhr[elProp]('load', loadListener, false);
xhr[elProp]('error', errorListener, false);
xhr[elProp]('abort', abortListener, false);
xhr.upload[elProp]('progress', progressListener, false);
}
$timeout(function(){
xhrListeners('addEventListener');
if(!ignoreLoading) loading.reqStarted(); // show loading notification
// open connection
xhr.open('POST', url, true);
// set headers
for(var key in headers) {
if(key.toLowerCase() !== 'content-type' &&
key.toLowerCase() !== 'content-length') xhr.setRequestHeader( key, headers[key] );
}
xhr.send(fd);
});
}
/*
* RESOURCE CONSTRUCTOR
*/
function Resource(){
var args = [ {}, Resource.defaults ];
for(var i=0;i<arguments.length;i++) args.push(arguments[i]);
var opts = angular.merge.apply(angular, args);
opts.baseUrl = unifyUrlPath(opts.baseUrl);
var resource = this;
resource.options = opts;
for(var cmdName in opts.commands){
// extend transformations
opts.commands[ cmdName ].transformRequest = angular.merge({}, opts.transformRequest, opts.commands[ cmdName ].transformRequest || {});
opts.commands[ cmdName ].transformResponse = angular.merge({}, opts.transformResponse, opts.commands[ cmdName ].transformResponse || {});
resource[ cmdName ] = (function(cmdName){
return function(){
var args = [cmdName];
for(var i=0;i<arguments.length;i++){
args.push(arguments[i]);
}
return resource.command.apply(resource, args);
};
})(cmdName);
}
return resource;
}
Resource.defaults = defaultResourceOpts;
Resource.define = Resource.create = function(opts){ return new Resource(opts); };
Resource.dataTransformators = {
'dateStringsToDates': dateStringsToDates,
'removePrefixedProps': removePrefixedProps
};
/*
* RESOURCE PROTOTYPE METHODS
*/
Resource.prototype.command = function(cmdName, idOrQuery, data, successCb, errorCb, progressCb){
var resource = this;
if(!resource.options.commands[cmdName]) throw new Error('This resource has no command "' +cmdName+ '" defined');
// argument idOrQuery is optional
if(typeof arguments[1] === 'function'){
progressCb = arguments[3];
errorCb = arguments[2];
successCb = arguments[1];
idOrQuery = {};
data = null;
}
// argument data is optional
else if(typeof arguments[2] === 'function') {
progressCb = arguments[4];
errorCb = arguments[3];
successCb = arguments[2];
idOrQuery = arguments[1];
data = null;
}
var query,
opts = resource.options,
cmdOpts = opts.commands[cmdName],
baseUrl = (typeof cmdOpts.baseUrl === 'string' ? cmdOpts.baseUrl : opts.baseUrl) || '',
method = (cmdOpts.method || 'GET').toLowerCase(),
responseType = cmdOpts.responseType || opts.responseType,
canHaveBody = typeof cmdOpts.body === 'boolean' ? cmdOpts.body : (['options','post','post-multipart','upload','put','delete'].indexOf(method) > -1),
headers = cmdOpts.headers || opts.headers,
urlTemplate = (typeof cmdOpts.url === 'string' ? cmdOpts.url : opts.url) || '',
urlBuilder = cmdOpts.urlBuilder || opts.urlBuilder,
urlEndSlash = cmdOpts.urlEndSlash || opts.urlEndSlash,
queryStringBuilder = cmdOpts.queryStringBuilder || opts.queryStringBuilder,
defaultQuery = cmdOpts.defaultQuery || opts.defaultQuery,
ignoreLoading = cmdOpts.ignoreLoading!==undefined ? cmdOpts.ignoreLoading : opts.ignoreLoading,
transformRequest = cmdOpts.transformRequest,
idKey = cmdOpts.idKey || opts.idKey,
pageKey = cmdOpts.queryPageKey || opts.queryPageKey,
limitKey = cmdOpts.queryLimitKey || opts.queryLimitKey,
sortKey = cmdOpts.querySortKey || opts.querySortKey;
opts.commands[cmdName].urlParams = cmdOpts.urlParams || getUrlParams(urlTemplate);
// if data is missing, and idOrQuery is object, and this method can have body, therefore data = idOrQuery
if(data === null && canHaveBody && angular.isObject(idOrQuery)) {
data = arguments[1];
idOrQuery = null;
query = {};
}
else {
query = {};
if(idOrQuery && (typeof idOrQuery === 'string' || typeof idOrQuery === 'number')) {
query = object.deepSet(query, idKey, idOrQuery);
}
else query = idOrQuery;
query = angular.merge({}, defaultQuery, query || {});
}
if(query.$page === 0) throw new Error('NeRestResource: query.$page is equal to zero, must be greater');
// do not modify source objects, make a copy than modify
query = copyData(query);
if(data) data = copyData(data);
// replace default pagination props by custom if defined in query
query = replacePaginationProps(query, pageKey, limitKey, sortKey, object);
if(data) data = replacePaginationProps(data, pageKey, limitKey, sortKey, object);
var successCbs = [ successCb, cmdOpts.onSuccess, opts.onSuccess ];
var errorCbs = [ errorCb, cmdOpts.onError, opts.onError ];
var progressCbs = [ progressCb, cmdOpts.onProgress, opts.onProgress ];
var params = angular.merge({}, data||{}, query||{});
var urlPath = urlBuilder.call(resource, baseUrl, urlTemplate, params, cmdName);
if(urlEndSlash && urlPath.indexOf('?')===-1) urlPath += '/';
var queryString = queryStringBuilder.call(resource, query, cmdName);
if(urlPath.indexOf('?') > -1 && queryString.indexOf('?') === 0) queryString = '&'+queryString.substring(1);
var requestId = object.guid();
var httpOpts = {
url: urlPath + queryString,
method: method,
data: applyTransformators(data, transformRequest),
headers: typeof headers === 'function' ? headers(opts.headers, data, cmdName, method, urlPath + queryString) : headers,
ignoreLoading: ignoreLoading,
requestId: requestId,
responseType: responseType
};
if(method === 'post-multipart' || method === 'upload') upload.call(resource, cmdName, query, httpOpts, successCbs, errorCbs, progressCbs);
else $http(httpOpts).then(handleSuccess(httpOpts, query, opts, cmdName, successCbs), handleError(httpOpts, query, opts, cmdName, errorCbs));
return requestId;
};
function replacePaginationProps(queryOrData, pageKey, limitKey, sortKey, object) {
if(pageKey !== '$page'){
queryOrData = object.deepSet(queryOrData, pageKey, queryOrData.$page);
delete queryOrData.$page;
}
if(limitKey !== '$limit'){
queryOrData = object.deepSet(queryOrData, limitKey, queryOrData.$limit);
delete queryOrData.$limit;
}
if(sortKey !== '$sort'){
queryOrData = object.deepSet(queryOrData, sortKey, queryOrData.$sort);
delete queryOrData.$sort;
}
return queryOrData;
}
function copyData(data){
var copy = data;
if(Object.prototype.toString.call(data) === '[object Object]') copy = object.extend(true, {}, data);
if(Array.isArray(data)) copy = object.extend(true, [], data);
return copy;
}
/*
* REQ/RES TRANSFORMATORS
*/
function applyTransformators(data, transforms){
transforms = transforms || {};
for(var id in transforms){
if(Resource.dataTransformators[ id ]) Resource.dataTransformators[ id ]( data, transforms[id] );
}
return data;
}
return Resource;
}]);
/**
* NE STATE
* ***************************************************************************************************************************
*/
angular.module('neState', ['ngCookies'])
.factory('NeStateService',['$timeout','$location','$rootScope','$cookies','neObject', function($timeout, $location, $rootScope, $cookies, object){
function encryptString(str){
return window.btoa(str);
}
function decryptString(str){
return window.atob(str);
}
var locationStore = {
encrypt: false,
prefix: 'q',
parser: function (locationString){
var locationPrefix = this.prefix;
var encryptLocation = this.encrypt;
locationString = locationString || $location.search()[ locationPrefix ]; // decodeURIComponent not necessary, locationString is already decoded
try {
if(encryptLocation) locationString = decryptString(locationString);
return object.fromJson(locationString || '{}') || {};
}
catch(err){}
return {};
},
builder: function(stateObj){
var locationPrefix = this.prefix;
var encryptLocation = this.encrypt;
var str = JSON.stringify(stateObj, removeEmptyStates); //.replace(/=/,'%3D').replace(/\&/, '%26').replace(/\?/, '%3F');
// there don't have to be empty states in url
function removeEmptyStates(key, value){
if(!stateObj[key]) return value;
if(Object.keys(stateObj[key]).length) return value;
}
if(encryptLocation) str = encryptString(str);
return str;
},
autoUpdate: false, // auto updates on change
autoFill: false, // watch and fire state change
sync: false, // auto update and also watch
_unbinders:{}, // unbind route change listeners
init: function(state, stateId){
var locationStore = this;
if(!(locationStore.autoFill || locationStore.sync)) return;
if(stateId) locationStore._unbinders[ stateId ] = {
routeUpdate: $rootScope.$on('$routeUpdate', function (){
locationStore.fill(state, stateId);
}),
routeChangeSuccess: $rootScope.$on('$routeChangeSuccess', function (){
locationStore.fill(state, stateId);
})
};
locationStore.fill(state, stateId);
},
destroy: function(state, stateId){
return this.unbind(state, stateId);
},
unbind: function(state, stateId){
var locationStore = this;
var unbindStateIds = stateId ? [stateId] : Object.keys(locationStore._unbinders);
for(var i=0;i<unbindStateIds.length;i++){
var id = unbindStateIds[i];
if(locationStore._unbinders[id]){
locationStore._unbinders[id].routeUpdate();
locationStore._unbinders[id].routeChangeSuccess();
}
}
},
fill: function(state, stateId){
var locationStore = this;
var locationString = $location.search()[ locationStore.prefix ];
var stateObj = locationStore.parser(locationString) || {};
$timeout(function(){
if(stateId) state.change(stateId, stateObj[stateId] || {}, true);
else for(var id in state.history) state.change(id, stateObj[id] || {}, true);
});
},
update: function(state, stateId){
var locationStore = this;
if(!(locationStore.autoUpdate || locationStore.sync)) return;
var locationSearch = locationStore.builder(state.getCurrentState());
$location.search(locationStore.prefix, locationSearch);
}
};
// TODO: implement
var cookiesStore = {
//encrypt: false,
prefix: 'appState',
//domain:'',
//expires:'',
path:'/',
secure:false,
autoUpdate: false, // auto updates on change
autoFill: false, // watch and fire state change
sync: false, // auto update and also watch
init: function(state, stateId){},
destroy: function(state, stateId){},
unbind: function(state, stateId){},
fill: function(state, stateId){
var locationStore = this;
var stateObj = $cookies.getObject(locationStore.prefix) || {};
$timeout(function(){
if(stateId) state.change(stateId, stateObj[stateId] || {}, true);
else for(var id in state.history) state.change(id, stateObj[id] || {}, true);
});
},
update: function(state, stateId){
var locationStore = this;
if(!(locationStore.autoUpdate || locationStore.sync)) return;
$cookies.putObject(locationStore.prefix, state.getCurrentState(), {
domain: locationStore.domain,
expires: locationStore.expires,
path: locationStore.path,
secure: locationStore.secure,
});
}
};
var defaultOpts = {
maxHistoryStates: 5,
store: locationStore
};
function StateService(opts){
opts = opts || {};
angular.merge(this, {}, defaultOpts, opts);
this.history = {};
this.changeListeners = [];
return this;
}
StateService.locationStore = locationStore;
StateService.cookiesStore = cookiesStore;
StateService.prototype.create =
StateService.prototype.register = function(id, opts){
opts = opts || {};
var state = this;
if(state.history[id]) return state.history[id];
var stateHistory = [];
stateHistory.maxHistoryStates = opts.maxHistoryStates || state.maxHistoryStates;
if(opts.store === 'location') opts.store = locationStore;
if(opts.store === 'cookies') opts.store = cookiesStore;
stateHistory.store = angular.merge({}, state.store, opts.store || {});
stateHistory.changeListeners = [];
stateHistory.currentStateIndex = -1;
state.history[id] = stateHistory;
state.history[id].store.init(state, id);
return state.history[id];
};
StateService.prototype.changeState =
StateService.prototype.change = function(id, value, disableStoreUpdate) {
if(!angular.isObject(value)) throw new Error('StateService: cannot change state, value have to be object and is "' +value+ '"');
var state = this;
state.history[id] = state.history[id] || state.register(id);
var currIndex = state.history[id].currentStateIndex;
var howManyRemove = state.history[id].length ? state.history[id].length - 1 - currIndex : 0;
if(state.history[id].length > 0 && object.deepEquals(state.history[id][currIndex], value)) return state; // same state as previous, no change
state.history[id].splice(currIndex + 1, howManyRemove);
state.history[id].push( angular.merge({}, value) );
if(state.history[id].length > state.history[id].maxHistoryStates) state.history[id].splice(0,1);
else state.history[id].currentStateIndex++;
if(!disableStoreUpdate){
state.history[id].store.update(state, id);
}
var changedFromStore = disableStoreUpdate;
return state.fireChange(id, null, changedFromStore);
};
StateService.prototype.updateState =
StateService.prototype.update = function(id, value){
if(!angular.isObject(value)) throw new Error('StateService: cannot change state, value have to be object and is "' +value+ '"');
var state = this;
state.history[id] = state.history[id] || state.register(id);
if(!state.history[id].length) return state; // nothing to update, there is no state yet
var currIndex = state.history[id].currentStateIndex;
state.history[id][ currIndex ] = angular.merge({}, value);
return state;
};
StateService.prototype.fireChange = function(id, oldValue, changedFromStore) {
if(!this.history[id]) throw new Error('StateService: there is no registered state with id "' +id+ '"');
var historyIndex = this.history[id].currentStateIndex;
var specChangeListeners = this.history[id].changeListeners;
oldValue = oldValue || this.getPrevState(id) || {};
var newValue = this.getCurrentState(id) || {};
for(var i=0;i<specChangeListeners.length;i++) specChangeListeners[i]( newValue, oldValue, changedFromStore, historyIndex );
for(var i=0;i<this.changeListeners.length;i++) this.changeListeners[i]( id, newValue, oldValue, changedFromStore, historyIndex );
return this;
};
StateService.prototype.watch =
StateService.prototype.onChange = function(id, fnc) {
var state = this;
if(arguments.length === 1) {
fnc = arguments[0];
id = null;
}
if(id) {
state.history[id] = state.history[id] || state.register(id);
state.history[id].changeListeners.push(fnc);
}
else state.changeListeners.push(fnc);
return state;
};
StateService.prototype.unWatch =
StateService.prototype.unbindChange =
StateService.prototype.offChange = function(id, fnc) {
if(arguments.length === 1) {
fnc = arguments[0];
id = null;
}
var index;
if(id) {
if(!this.history[id]) throw new Error('StateService: there is no registered state with id "' +id+ '"');
index = this.history[id].changeListeners.indexOf(fnc);
if(index >= 0) this.history[id].changeListeners.splice(index, 1);
}
else {
index = this.changeListeners.indexOf(fnc);
if(index >= 0) this.changeListeners.splice(index, 1);
}
return this;
};
StateService.prototype.clear = function(id) {
if(id) {
this.history[id].splice(0, this.history[id].length);
this.history[id].changeListeners = [];
this.history[id].currentStateIndex = -1;
}
else {
this.history = {};
this.changeListeners = [];
}
return this;
};
StateService.prototype.destroy = function(id) {
if(id) {
this.history[id].store.unbind(this, id);
this.store.unbind(this, id);
this.clear(id);
delete this.history[id];
}
else {
this.history = {};
this.changeListeners = [];
this.store.unbind(this, id);
for(var h in this.history) this.history[h].store.unbind(this, h);
}
return this;
};
StateService.prototype.getCurrentState = function(id) {
if(arguments.length === 0){
var states = {};
for(var id in this.history) states[id] = this.history[id][ this.history[id].currentStateIndex ];
return states;
}
if(!this.history[id]) throw new Error('StateService: there is no registered state with id "' +id+ '"');
return this.history[id][ this.history[id].currentStateIndex ];
};
StateService.prototype.getPrevState = function(id) {
if(!this.history[id]) throw new Error('StateService: there is no registered state with id "' +id+ '"');
var prevIndex = this.history[id].currentStateIndex - 1;
if(prevIndex < 0) return {};
return this.history[id][ prevIndex ];
};
StateService.prototype.getNextState = function(id) {
if(!this.history[id]) throw new Error('StateService: there is no registered state with id "' +id+ '"');
var nextIndex = this.history[id].currentStateIndex + 1;
if(nextIndex >= this.history[id].length) nextIndex = this.history[id].length ? this.history[id].length - 1 : 0;
return this.history[id][ nextIndex ];
};
StateService.prototype.getFutureState = function(id, value){
var futureState = {};
if(arguments.length === 2){
futureState[id] = value;
futureState = angular.merge({}, this.getCurrentState(), futureState);
}
else futureState = this.getCurrentState();
return futureState;
};
function moveState(indexIncrement){
return function(id) {
if(!this.history[id]) throw new Error('StateService: there is no registered state with id "' +id+ '"');
var oldValue = this.getCurrentState(id);
var currStateIndex = this.history[id].currentStateIndex + indexIncrement;
if(currStateIndex < 0) currStateIndex = 0;
if(currStateIndex >= this.history[id].length) currStateIndex = this.history[id].length ? this.history[id].length - 1 : 0;
this.history[id].currentStateIndex = currStateIndex;
return oldValue === this.getCurrentState(id) ? this : this.fireChange(id, oldValue);
};
}
StateService.prototype.undo = moveState(-1);
StateService.prototype.redo = moveState(1);
StateService.prototype.undoAll = function() {
for(var id in stateObj) this.undo(id);
};
StateService.prototype.redoAll = function() {
for(var id in stateObj) this.redo(id);
};
return StateService;
}]);
/**
* NE TREE
* ***************************************************************************************************************************
*/
/*
* TREEVIEW - factory defining treeview behaviour
*
* Usage:
* var myTree = new Tree({
* id: 'products',
* resource: products,
* parentReferenceKey: 'parentId',
* // childrenKey: 'children',
* // childrenCountKey: 'childrenCount',
* // childrenReferenceKey: 'childIds',
* // ancestorsReferenceKey: 'ancestors',
* autoLoad:true,
* multiSelect:false,
* limit:20,
* itemTemplate: 'neTree/item.html'
* }).load();
*
*/
angular.module('neTree',['neObject'])
.run(['$templateCache', function($templateCache) {
$templateCache.put('neTree/item.html','<div>{{item}}</div>');
$templateCache.put('neTree/child.html',
'<div ng-include="tree.itemTemplate"></div>' +
'<ul ng-show="item.$expanded">' +
' <li ng-repeat="item in item.$children" ng-include="\'neTree/child.html\'"></li>' +
'</ul>');
$templateCache.put('neTree/tree.html',
'<div class="tree">' +
' <ul>' +
' <li ng-repeat="item in tree.items" ng-include="\'neTree/child.html\'"></li>' +
' </ul>' +
' <div class="tree-backdrop" ng-show="tree.disabled"></div>' +
'</div>');
$templateCache.put('neTree/tree-item-pagination.html',
'<div ng-if="item.$expanded" class="tree-item-pagination" ng-class="{\'tree-item-pagination-border\':item.$children.length}">'+
' <div ng-if="item.$pagination && !item.$paginationDisabled" class="btn-group btn-group-xs">'+
' <button class="btn btn-light btn-xs" ng-click="tree.setPage(item, \'prev\')" ng-disabled="item.$prevDisabled">'+
' <i class="fa fa-backward"></i>'+
' </button>'+
' <button class="btn btn-light btn-xs" ng-click="tree.addPage(item)" ng-disabled="item.$nextDisabled">'+
' {{item.$pagination.page}} <span ng-if="item.$pagination.pagesCount">{{::\'of\'|translate}} {{item.$pagination.pagesCount}}</span>'+
' </button>'+
' <button class="btn btn-light btn-xs" ng-click="tree.setPage(item, \'next\')" ng-disabled="item.$nextDisabled">'+
' <i class="fa fa-forward"></i>'+
' </button>'+
' </div>'+
'</div>');
}])
.directive('neTreeUpdateBlur', ['$timeout', function($timeout){
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
//scope:{ blurUpdate:'=' },
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
var dirty_class = attrs.dirtyClass || 'is-dirty';
if(dirty_class==='ng-dirty')
throw new Error('dirtyClass cannot be equal to "ng-dirty", it is angular reserved class name');
var names = (attrs.treeUpdateBlur || '').split(',');
var itemName = names[0] || 'item';
var treeName = names[1] || 'tree';
if(!scope[treeName]) throw new Error('Scope has not grid with name "'+treeName+'"');
if(!scope[itemName]) throw new Error('Scope has not grid item with name "'+itemName+'"');
var isDirty = false;
function setDirty(dirty){
isDirty = dirty;
if(isDirty) element.addClass(dirty_class);
else element.removeClass(dirty_class);
}
function reset(){
scope.$apply(function(){
ngModel.$setViewValue('firstValue');
setDirty(false);
});
}
function setPristine(){
setDirty(false);
firstValue = ngModel.$viewValue;
}
element.on('blur', function(){
if(isDirty) scope[treeName].updateItem(scope[itemName], setPristine);
});
element.bind("keydown keypress", function (event) {
if(event.which === 13 && isDirty && element[0].nodeName==='INPUT') {
scope[treeName].updateItem(scope[itemName], setPristine);
event.preventDefault();
}
//if(event.which === 27 && isDirty) {
// reset();
// event.preventDefault();
//}
});
// catch the init value
var firstValue = '';
scope.$watch(ngModel.$viewValue, function(){
firstValue = ngModel.$viewValue;
});
ngModel.$viewChangeListeners.push(function(){
if(firstValue !== ngModel.$viewValue) setDirty(true);
else setDirty(false);
});
}
};
}])
.directive('neTree', [function(){
return {
restrict:'EA',
templateUrl: 'neTree/tree.html',
scope:{ tree:'=neTree' },
replace:true,
link: function(scope, elm, attrs){
scope.tree.itemTemplate = scope.tree.itemTemplate || 'neTree/item.html';
//scope.$eval(attrs.treeview);
}
};
}])
.directive('neTreeItemPagination', [function(){
return {
restrict:'EA',
templateUrl: 'neTree/tree-item-pagination.html',
link: function(scope, elm, attrs){
}
};
}])
.factory('NeTree',['$timeout','neObject', function($timeout, object){
// TODO: helper for creating nested tree structure from flat array - using "item.ancestors" property
// this.treeFromArray = function(array, rootLevel, rootItemId){
// array = array || [];
// if(arguments.length===2 && typeof arguments[1]==='string'){
// rootItemId = arguments[1];
// rootLevel = 0;
// }
// rootLevel = rootLevel || 0;
//
// var parentIdObj = {}, parentId;
// var rootChildren = [];
//
// for(var i=0;i<array.length;i++){
// if(rootItemId && rootItemId === array[i].ancestors[array[i].ancestors.length-1]) {
// rootChildren.push(array[i]);
// }
// else if(!rootItemId && array[i].ancestors.length === rootLevel) {
// rootChildren.push(array[i]);
// }
// else {
// parentId = array[i].ancestors[array[i].ancestors.length-1];
// parentIdObj[parentId] = parentIdObj[parentId] || [];
// parentIdObj[parentId].push(array[i]);
// }
// }
//
// return (function createTree(children, parentIdObj){
// if(!children) return [];
//
// for(var i=0;i<children.length;i++){
// children[i].$children = createTree(parentIdObj[children[i].id], parentIdObj);
// }
// return children;
// })(rootChildren, parentIdObj);
// };
function Tree(settings){
var args = [ {}, Tree.defaults ];
for(var i=0;i<arguments.length;i++) args.push(arguments[i]);
settings = angular.merge.apply(angular, args);
// init values
this.id = settings.id;
this.idKey = settings.idKey || 'id';
this.childrenKey = settings.childrenKey;
this.childrenCountKey = settings.childrenCountKey;
this.childrenReferenceKey = settings.childrenReferenceKey;
this.parentReferenceKey = settings.parentReferenceKey;
this.ancestorsReferenceKey = settings.ancestorsReferenceKey;
this.getChildrenQuery = settings.getChildrenQuery || getChildrenQuery; // getChildrenQuery(parent)
this.maintainReferences = settings.maintainReferences || maintainReferences; // maintainReferences(parent, child, removeMode)
this.defaultLimit = settings.defaultLimit || 10;
this.$limit = settings.limit || this.defaultLimit; //default page size
this.maxLimit = settings.maxLimit || 100; //max page size
this.defaultQuery = settings.defaultQuery || {};
this.defaultSort = settings.defaultSort || {};
this.interceptLoad = settings.interceptLoad || settings.beforeLoad || settings.loadInterceptor;
this.onQuery = settings.onQueryChange || settings.onQuery || settings.onFilter;
this.onFill = settings.onFill || settings.onData || settings.onLoad;
this.onSelect = settings.onSelect;
this.onFocus = settings.onFocus;
this.onMove = settings.onMove;
this.onUpdate = settings.onUpdate;
this.onCreate = settings.onCreate;
this.resource = settings.restResource || settings.resource;
this.getResourceMethod = settings.getResourceMethod || settings.resourceMethod || (typeof this.resource === 'function' ? this.resource : null) || getResourceMethod; // getResourceMethod(opType, item)
this.onRemove = settings.onRemove;
this.autoLoad = settings.autoLoad || settings.loadOnChange;
this.multiSelect = settings.multiSelect || settings.multiselect || false;
// if(!this.resource) throw new Error('settings.resource is undefined');
// if(!this.id) throw new Error('Tree must have property "id"');
// defaults
this.silentMode = false;
this.$query = object.extend('data', {}, { $page:this.$page, $limit:this.$limit }, this.defaultQuery);
this.items = [];
this.itemTemplate = settings.itemTemplate || settings.include || 'neTree/item.html';
this.disabled = true; // default grid state is disabled
// exposed methods
this.fillItems = fillItems; // fillItems([parent,] items)
this.fill = fillItems; // fillItems([parent,] items)
this.addItems = appendItems; // appendItems([parent,] items)
this.addItem = appendItems; // appendItems([parent,] items)
this.appendItems = appendItems; // appendItems([parent,] items)
this.appendItem = appendItems; // appendItems([parent,] items)
this.prependItems = prependItems; // prependItems([parent,] items)
this.prependItem = prependItems; // prependItems([parent,] items)
this.setSort = setSort; // setSort([parent,] sortObj)
this.setSortSilent = doSilent('setSort');
this.setSortBy = setSortBy; // setSortBy([parent,] sortBy, sortDir)
this.setSortBySilent = doSilent('setSortBy');
this.updateQuery = updateQuery; // updateQuery([parent,] query)
this.updateQuerySilent = doSilent('updateQuery');
this.setQuery = setQuery; // setQuery([parent,] filterQuery)
this.setQuerySilent = doSilent('setQuery');
this.setFilter = setQuery; // setQuery([parent,] filterQuery)
this.setFilterSilent = doSilent('setQuery');
this.setPage = setPage; // setPage([parent,] 'first','last','next','prev','refresh')
this.setPageSilent = doSilent('setPage');
this.addPage = addPage; // addPage(parent, limit, cb)
this.addPageSilent = doSilent('addPage');
this.appendPage = addPage; // addPage(parent, limit, cb)
this.appendPageSilent = doSilent('addPage');
this.load = load; // load([parent,] cb)
this.loadItems = load; // load([parent,] cb)
this.refresh = load; // load([parent,] cb)
this.refreshItems = load; // load([parent,] cb)
this.refreshItem = refreshItem; // refreshItem(item, cb)
this.createItem = createItem; // createItem(parent, item, appendChild, cb)
this.copyItem = copyItem; // copyItem(item, cb)
this.updateItem = updateItem; // updateItem(item, cb)
this.removeItem = removeItem; // removeItem(item, cb)
this.moveItem = moveItem; // moveItem(item, toItem, inside/after/before, cb)
this.selectItem = selectItem; // selectItem(item)
//this.selectAll = selectAll; // selectAll(parent)
//this.expandAll = expandAll; // selectAll(parent)
//this.toggleItemSelection = toggleItemSelection; // toggleItemSelection(item)
//this.toggleSelection = toggleSelection; // toggleSelection()
//this.deselectItems = deselectItems; // deselectItems()
this.focusItem = focusItem; // focusItem(item)
this.getFocusedItem = getFocusedItem; // getFocusedItem()
this.getSelectedItems = getSelectedItems; // getSelectedItems()
this.selectedItems = [];
this.focusedItem = null; // reference to focusedItem
this.walkItems = walkItems; // walkItems([parent,] fnc) - run fnc on all of items, and descendants
this.walk = walkItems; // alias for walkItems
this.getParentOf = getParentOf; // getParentOf(item)
this.getParentsOf = getAncestorsOf; // getAncestorsOf(item)
this.getAncestorsOf = getAncestorsOf; // getAncestorsOf(item)
this.getChildrenOf = getChildrenOf; // getChildrenOf(item)
this.getChildrenCountOf = getChildrenCountOf; // getChildrenCountOf(parent)
return this;
}
// global default settings
Tree.defaults = {};
function doSilent(propName){
return function(){
var tree = this;
tree.silentMode = true;
tree[propName].apply(tree, arguments);
tree.silentMode = false;
return tree;
};
}
function getResourceMethod(opType, item){
if(!this.resource) throw new Error('NeTree: resource is undefined');
// opType = 'find','create','update','remove'
return this.resource[opType];
}
function walkItems(parent, fnc){ // run fnc on all of items, and descendants
if(arguments.length === 1){
fnc = arguments[0];
parent = null;
}
var tree = this;
if(parent && parent !== tree && fnc(parent, tree.getParentOf(parent)) === true) return;
return (function walkLevel(items, parent, fnc){
items = items || [];
for(var i=0;i<items.length;i++){
if(fnc(items[i], parent) === true) return;
}
for(var i=0;i<items.length;i++){
if(items[i].$children && items[i].$children.length > 0){
walkLevel(items[i].$children, items[i], fnc);
}
}
})(parent ? (parent.$children || (parent===tree ? tree.items : [])) : tree.items, parent, fnc);
}
function getParentOf(item){
var foundParent;
this.walkItems(function(parent){
if(parent.$children && parent.$children.indexOf(item) >= 0){
foundParent = parent;
return true;
}
else return false;
});
return foundParent;
}
function getAncestorsOf(item, ancestors){
var tree = this;
ancestors = ancestors || [];
var parent = tree.getParentOf(item);
if(parent) {
ancestors.unshift(parent);
return tree.getAncestorsOf(parent, ancestors);
}
return ancestors;
}
function getChildrenOf(parent){
var tree = this;
if(!parent) throw new Error('Wrong arguments');
return parent.$children;
}
function getChildrenCountOf(parent){
var tree = this;
if(!parent) throw new Error('Wrong arguments');
return (parent.$children || []).length;
// return (object.deepGet(parent, tree.childrenCountKey) || []).length;
}
/*
* Data Integrity methods
*/
function getChildrenQuery(parent){
var tree = this;
var idKey = tree.idKey;
var ancKey = tree.ancestorsReferenceKey;
var parentKey = tree.parentReferenceKey;
var childrenKey = tree.childrenReferenceKey;
var query = {};
if(ancKey){
if(!parent) query[ ancKey ] = { $size:0 };
else {
query.$and = [{},{}];
query.$and[0][ ancKey ] = {
$size: (object.deepGet(parent,ancKey) || []).length + 1
};
query.$and[1][ ancKey ] = object.deepGet(parent, idKey);
}
}
else if(parentKey){
query[ parentKey ] = object.deepGet(parent, idKey);
}
else if(childrenKey){
query[ childrenKey ] = object.deepGet(parent, childrenKey);
}
else throw new Error('Cannot create query, "ancestorsReferenceKey", or "parentReferenceKey", or "childrenReferenceKey" not set');
return query;
}
function maintainReferences(parent, child, remove){
if(!parent || !child) return;
var tree = this;
var idKey = tree.idKey;
var ancKey = tree.ancestorsReferenceKey;
var parentKey = tree.parentReferenceKey;
var childrenKey = tree.childrenReferenceKey;
var countKey = tree.childrenCountKey;
var childAlreadyRegistered = false;
if(ancKey && !remove) {
var ancs = [].concat(object.deepGet(parent, ancKey) || []);
ancs.push( object.deepGet(parent, idKey) );
object.deepSet(child, ancKey, ancs);
}
if(parentKey && !remove){
var parentId = object.deepGet(parent, idKey);
object.deepSet(child, parentKey, parentId);
}
if(childrenKey) {
var childIds = object.deepGet(parent, childrenKey) || [];
var childId = object.deepGet(child, idKey);
if(!remove) {
if(childIds.indexOf(childId) === -1) childIds.push( childId );
else childAlreadyRegistered = true;
}
else {
var index = childIds.indexOf( childId );
if(index > -1) childIds.splice(index, 1);
}
object.deepSet(parent, childrenKey, childIds);
}
if(countKey && !childAlreadyRegistered) {
var count = object.deepGet(parent, countKey) || 0;
object.deepSet(parent, countKey, count+( !remove ? 1 : -1 ));
}
}
/*
* tree CRUD methods
*/
function calcPagination(prefix, item, pagination){
var tree = this;
pagination = pagination || {};
item[prefix+'limit'] = item[prefix+'limit'] || tree.defaultLimit;
item[prefix+'pagination'] = pagination;
item[prefix+'pagesCount'] = Math.ceil(pagination.count / item[prefix+'limit']);
if(pagination.prev !== undefined) item[prefix+'prevDisabled'] = !pagination.prev;
else if(pagination.page <= 1) item[prefix+'prevDisabled'] = true;
if(pagination.next !== undefined) item[prefix+'nextDisabled'] = !pagination.next;
else if(pagination.page >= item[prefix+'pagesCount']) item[prefix+'nextDisabled'] = true;
item[prefix+'paginationDisabled'] = item[prefix+'prevDisabled'] && item[prefix+'nextDisabled'];
}
// methods definitions
function fillItems(parent, items, pagination, fillMode){
var tree = this;
tree.disabled = false;
if(Array.isArray(arguments[0])){
pagination = arguments[1];
items = arguments[0];
parent = null;
}
if(arguments.length === 3 && typeof arguments[2] === 'string'){
fillMode = arguments[2];
pagination = parent ? parent.$pagination : null;
}
items = Array.isArray(items) ? items : [items];
if(parent) {
if(['push','append'].indexOf(fillMode) > -1) Array.prototype.push.apply(parent.$children, items);
else if(['unshift','prepend'].indexOf(fillMode) > -1) Array.prototype.unshift.apply(parent.$children, items);
else parent.$children = items;
calcPagination('$', parent, pagination);
}
else {
if(['push','append'].indexOf(fillMode) > -1) Array.prototype.push.apply(tree.items, items);
else if(['unshift','prepend'].indexOf(fillMode) > -1) Array.prototype.unshift.apply(tree.items, items);
else tree.items = items;
calcPagination('$', tree, pagination); // ensure paging is also set with $ prefix to unify in templates
}
parseChildrenKey(tree, parent);
if(typeof tree.onFill === 'function' && !tree.silentMode) {
if(parent) tree.onFill(parent, parent.$children, parent.$pagination, parent.$query);
else tree.onFill(tree, tree.items, tree.$pagination, tree.$query);
}
return this;
}
function parseChildrenKey(tree, parent){
tree.walkItems(parent, function(item, parent){
if(tree.childrenKey){
var children = object.deepGet(item, tree.childrenKey);
if(children && !item.$children) item.$children = children;
}
item.$level = parent ? parent.$level+1 : 0;
});
}
function setSort(parent, sortObj, cb){
if(typeof arguments[1] === 'function'){
cb = arguments[1];
sortObj = arguments[0];
parent = null;
}
var tree = this;
if(parent) parent.$sort = sortObj;
else tree.$sort = sortObj;
return grid.setPage('first', parent, cb);
}
function setSortBy(parent, sortBy, sortDir){
if(typeof arguments[0] === 'string'){
sortDir = arguments[1];
sortBy = arguments[0];
parent = null;
}
if(!sortBy) return;
var sort = {};
sort[sortBy] = sortDir;
return this.setSort(parent, sort);
}
function load(parent, loadMode, cb, errCb){
var tree = this;
if(arguments.length===2 && typeof arguments[1]==='function'){
cb = arguments[1];
loadMode = false;
}
else if(arguments.length === 1 && typeof arguments[0] === 'function'){
cb = arguments[0];
loadMode = false;
parent = null;
}
var children = parent ? tree.getChildrenOf(parent) : tree.items;
var childrenCount = parent ? tree.getChildrenCountOf(parent) : tree.items.length;
if(!parent || !children || (children.length < childrenCount) || loadMode){
if(!tree.interceptLoad || (tree.interceptLoad && tree.interceptLoad((parent||tree).$query, parent)!==false)){
var query = parent ? (parent.$query || {}) : tree.$query || {};
query = object.extend('data', {}, { $page:1, $limit:(tree.$limit || tree.defaultLimit) }, tree.defaultQuery, query, tree.getChildrenQuery(parent));
if(query.$sort) query.$sort = object.extend('data', {}, tree.defaultSort ,query.$sort);
if(parent) parent.$query = query;
else delete query.$limit;
tree.disabled = true;
tree.lastFindReqId = tree.getResourceMethod('find', parent)(query, function(items, pagination){
if(tree.lastFindReqId && tree.lastFindReqId !== this.requestId) return;
tree.fillItems(parent, items, pagination, loadMode);
if(cb) cb(items);
tree.disabled = false;
}, errCb);
}
}
else if(cb) cb(tree.items);
return tree;
}
function setPage(parent, pageNum, cb, newQuery){
if(typeof arguments[0] === 'function'){
cb = arguments[0];
pageNum = null;
}
else if(typeof arguments[1] === 'function'){
cb = arguments[1];
pageNum = arguments[0];
parent = null;
}
var tree = this;
var page;
parent = parent || tree;
parent.$pagination = parent.$pagination || {};
if(typeof pageNum==='number') page = pageNum;
else if(pageNum==='first') page = 1;
else if(pageNum==='next') page = parent.$pagination.page + 1;
else if(pageNum==='last') page = parent.$pagesCount;
else if(pageNum==='prev') page = parent.$pagination.page - 1;
else if(pageNum==='refresh' || pageNum === null) page = parent.$pagination.page || 1;
else page = 1;
if(parent.$pagesCount && page > parent.$pagesCount && typeof pageNum !== 'number') page = parent.$pagesCount+0;
if(page <= 0) page = 1;
parent.$page = page;
tree.updateQuery(parent, newQuery);
if(tree.autoLoad && !tree.silentMode) return tree.load(parent, true, cb);
else if(cb) cb();
return tree;
}
function setQuery(parent, newQuery, cb){
if(arguments.length===2){
cb = arguments[1];
newQuery = arguments[0];
parent = null;
}
parent = parent || tree;
var tree = this;
parent.$query = object.extend('data', {}, tree.defaultQuery || {}, newQuery || {});
tree.setPage(parent, parent.$query.$page || 'first', cb, newQuery);
return tree;
}
function addPage(parent, pageNum, cb){
if(typeof arguments[1] === 'function'){
cb = arguments[1];
if(typeof arguments[0] === 'number'){
limit = arguments[0];
parent = null;
}
else limit = null;
}
var tree = this;
pageNum = pageNum || 'next';
tree.setPageSilent(parent, pageNum);
if(tree.autoLoad && !tree.silentMode) return tree.load(parent, 'push', cb);
else if(cb) cb();
return tree;
}
function appendItems(parent, items){
if(arguments.length === 1){
items = arguments[0];
parent = null
}
var tree = this;
if(!items) return;
tree.fillItems(parent, items, 'push');
return tree;
}
function prependItems(parent, items){
if(arguments.length === 1){
items = arguments[0];
parent = null
}
var tree = this;
if(!items) return;
tree.fillItems(parent, items, 'unshift');
return tree;
}
function updateQuery(parent, newQuery){
if(arguments.length === 1){
newQuery = arguments[0];
parent = null;
}
var tree = this;
newQuery = newQuery || {};
parent = parent || tree;
parent.$page = newQuery.$page || parent.$page;
parent.$limit = newQuery.$limit || parent.$limit || tree.$limit;
parent.$sort = newQuery.$sort || parent.$sort;
if(parent.$page && (typeof parent.$page !== 'number' || parent.$page <= 0)) parent.$page = 1;
// check limit boundaries
if(!parent.$limit || parent.$limit < 0) parent.$limit = tree.defaultLimit;
else if(parent.$limit > tree.maxLimit) parent.$limit = tree.maxLimit;
var query = object.extend('data', {}, newQuery, { $limit:parent.$limit, $sort:{}, $page:parent.$page });
// merge sort with defaultSort
if(parent.$sort) query.$sort = parent.$sort;
query.$sort = object.extend('data', {}, tree.defaultSort || {}, parent.$sort || {});
if(Object.keys(query.$sort).length===0) delete query.$sort;
if(parent.$query){
delete parent.$query.$page;
delete parent.$query.$sort;
delete parent.$query.$limit;
}
parent.$query = object.extend('data', query, parent.$query || {});
if(tree.onQuery && !tree.silentMode) tree.onQuery(parent.$query, parent);
return tree;
}
function copyItem(item, appendChild, cb){
var copy = angular.copy(item);
object.deepRemove(copy, this.idKey);
return this.createItem(this.getParentOf(item), copy, appendChild, cb);
}
function createItem(parent, item, appendChild, cb, errCb){
var tree = this;
if(typeof arguments[1] === 'boolean'){
cb = arguments[2];
appendChild = arguments[1];
item = arguments[0];
parent = null;
}
else if(arguments.length === 3 && typeof arguments[2] === 'function') {
cb = arguments[2];
appendChild = false;
}
else if(arguments.length === 2 && typeof arguments[1] === 'function') {
cb = arguments[1];
item = arguments[0];
parent = null;
}
else if(arguments.length === 1){
item = arguments[0];
parent = null;
}
// ad parentId or ancestors
tree.maintainReferences(parent, item);
tree.getResourceMethod('create', item, parent)(item, function(newItem){
item = object.extend('data', item, newItem);
if(appendChild && parent) { // add childId if childReferenceKey
tree.maintainReferences(parent, item);
}
if(!appendChild) {
if(typeof cb ==='function') cb(item);
if(typeof tree.onCreate ==='function') tree.onCreate(item);
}
else if(parent && parent.$children){
parent.$expanded = true;
tree.appendItems(parent, newItem);
if(typeof cb ==='function') cb(newItem);
if(typeof tree.onCreate ==='function') tree.onCreate(newItem);
}
else {
tree.load(parent, function(children){
if(parent) parent.$expanded = true;
for(var i=0;i<children.length;i++){
if(object.deepGet(children[i], tree.idKey) === object.deepGet(newItem, tree.idKey)){
if(typeof cb ==='function') cb(children[i]);
if(typeof tree.onCreate ==='function') tree.onCreate(children[i]);
break;
}
}
});
}
}, errCb);
return tree;
}
function updateItem(item, cb, errCb){
this.getResourceMethod('update', item)(item, function(data){
item = object.extend('data', item, data);
if(cb) cb(item);
}, errCb);
return this;
}
function refreshItem(item, cb, errCb){
var idKey = this.idKey;
var idQuery = {};
idQuery[ idKey ] = object.deepGet(item, idKey);
this.getResourceMethod('find', item)(idQuery, function(data){
var wasExpanded = item.$expanded;
item = data;
if(wasExpanded) load(item, function(){
if(cb) cb(item);
})
else if(cb) cb(item);
}, errCb);
return this;
}
function moveItem(item, toItem, mode, cb){
// var tree = this;
//
// var parent, newIndex, oldParent = tree.getParentOf(item);
// var treeIndex = ((oldParent || {}).$children || tree.items).indexOf(item);
//
// if(item===toItem) return;
// else if(mode === 'inside') {
// parent = toItem;
// newIndex = null; // this will push item to the end
// }
// else if(mode === 'before') {
// parent = tree.getParentOf(toItem);
// newIndex = toItem.orderIndex;
// }
// else if(mode === 'after') {
// parent = tree.getParentOf(toItem);
// newIndex = toItem.orderIndex+1;
// }
// else return;
//
// var itemToUpdate = angular.copy(item);
// itemToUpdate.ancestors = parent ? angular.copy(parent.ancestors) : [];
// if(parent) itemToUpdate.ancestors.push(parent.id);
// if(!newIndex) delete itemToUpdate.orderIndex;
// else itemToUpdate.orderIndex = newIndex;
//
// tree.resource.update(itemToUpdate, function(newItem){
// item.orderIndex = newIndex;
// ((oldParent || {}).$children || tree.items).splice(treeIndex ,1);
//
// tree.loadItems(parent, true, function(children){
// if(parent) parent.$expanded = true;
//
// for(var i=0;i<children.length;i++){
// if(children[i].id === newItem.id){
// if(typeof cb ==='function') cb(children[i]);
// if(tree.onMove) tree.onMove(children[i]);
// break;
// }
// }
// });
// });
}
function removeItem(item, cb, errCb){
var tree = this;
tree.getResourceMethod('remove',item)(item, function(){
tree.maintainReferences( tree.getParentOf(item), item, true );
var parent = tree.getParentOf(item);
if(parent) parent.$children.splice(parent.$children.indexOf(item) ,1);
else tree.items.splice(tree.items.indexOf(item), 1);
if(typeof cb ==='function') cb();
}, errCb);
}
function focusItem(item, toggle){
var tree = this;
var wasFocused = item.$focused ? true : false;
if(tree.focusedItem && tree.focusedItem !== item) tree.focusedItem.$focused = false;
item.$focused = toggle ? !item.$focused : true;
tree.focusedItem = toggle && wasFocused ? null : item;
if(typeof tree.onFocus === 'function') tree.onFocus(item);
return tree;
}
function getFocusedItem(){
return this.focusedItem;
}
function selectItem(item){ // toggle item selection
var tree = this;
var deselectAll = !tree.multiSelect;
var isSelected = item.$selected;
if(deselectAll) {
for(var i=0;i<tree.selectedItems.length;i++){
if(tree.selectedItems[i].$selected) tree.selectedItems[i].$selected = false;
}
if(!isSelected) {
item.$selected = true;
tree.selectedItems = [item];
}
else tree.selectedItems = [];
}
else if(item.$selected) { // deselect item
item.$selected = false;
var index = tree.selectedItems.indexOf(item);
if(index >= 0) tree.selectedItems.splice(index,1);
}
else {
item.$selected = true;
tree.selectedItems.push(item);
}
if(typeof tree.onSelect === 'function') tree.onSelect(item, item.$selected);
}
function deselectItems(){
var tree = this;
for(var i=0;i<tree.selectedItems.length;i++){
if(tree.selectedItems[i].$selected) tree.selectedItems[i].$selected = false;
}
tree.selectedItems = [];
}
function getSelectedItems(){
return this.selectedItems;
}
return Tree;
}]);/**
* oclazyload - Load modules on demand (lazy load) with angularJS
* @version v1.0.9
* @link https://github.com/ocombe/ocLazyLoad
* @license MIT
* @author Olivier Combe <olivier.combe@gmail.com>
*/
(function (angular, window) {
'use strict';
var regModules = ['ng', 'oc.lazyLoad'],
regInvokes = {},
regConfigs = [],
modulesToLoad = [],
// modules to load from angular.module or other sources
realModules = [],
// real modules called from angular.module
recordDeclarations = [],
broadcast = angular.noop,
runBlocks = {},
justLoaded = [];
var ocLazyLoad = angular.module('oc.lazyLoad', ['ng']);
ocLazyLoad.provider('$ocLazyLoad', ["$controllerProvider", "$provide", "$compileProvider", "$filterProvider", "$injector", "$animateProvider", function ($controllerProvider, $provide, $compileProvider, $filterProvider, $injector, $animateProvider) {
var modules = {},
providers = {
$controllerProvider: $controllerProvider,
$compileProvider: $compileProvider,
$filterProvider: $filterProvider,
$provide: $provide, // other things (constant, decorator, provider, factory, service)
$injector: $injector,
$animateProvider: $animateProvider
},
debug = false,
events = false,
moduleCache = [],
modulePromises = {};
moduleCache.push = function (value) {
if (this.indexOf(value) === -1) {
Array.prototype.push.apply(this, arguments);
}
};
this.config = function (config) {
// If we want to define modules configs
if (angular.isDefined(config.modules)) {
if (angular.isArray(config.modules)) {
angular.forEach(config.modules, function (moduleConfig) {
modules[moduleConfig.name] = moduleConfig;
});
} else {
modules[config.modules.name] = config.modules;
}
}
if (angular.isDefined(config.debug)) {
debug = config.debug;
}
if (angular.isDefined(config.events)) {
events = config.events;
}
};
/**
* Get the list of existing registered modules
* @param element
*/
this._init = function _init(element) {
// this is probably useless now because we override angular.bootstrap
if (modulesToLoad.length === 0) {
var elements = [element],
names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/,
append = function append(elm) {
return elm && elements.push(elm);
};
angular.forEach(names, function (name) {
names[name] = true;
append(document.getElementById(name));
name = name.replace(':', '\\:');
if (typeof element[0] !== 'undefined' && element[0].querySelectorAll) {
angular.forEach(element[0].querySelectorAll('.' + name), append);
angular.forEach(element[0].querySelectorAll('.' + name + '\\:'), append);
angular.forEach(element[0].querySelectorAll('[' + name + ']'), append);
}
});
angular.forEach(elements, function (elm) {
if (modulesToLoad.length === 0) {
var className = ' ' + element.className + ' ';
var match = NG_APP_CLASS_REGEXP.exec(className);
if (match) {
modulesToLoad.push((match[2] || '').replace(/\s+/g, ','));
} else {
angular.forEach(elm.attributes, function (attr) {
if (modulesToLoad.length === 0 && names[attr.name]) {
modulesToLoad.push(attr.value);
}
});
}
}
});
}
if (modulesToLoad.length === 0 && !((window.jasmine || window.mocha) && angular.isDefined(angular.mock))) {
console.error('No module found during bootstrap, unable to init ocLazyLoad. You should always use the ng-app directive or angular.boostrap when you use ocLazyLoad.');
}
var addReg = function addReg(moduleName) {
if (regModules.indexOf(moduleName) === -1) {
// register existing modules
regModules.push(moduleName);
var mainModule = angular.module(moduleName);
// register existing components (directives, services, ...)
_invokeQueue(null, mainModule._invokeQueue, moduleName);
_invokeQueue(null, mainModule._configBlocks, moduleName); // angular 1.3+
angular.forEach(mainModule.requires, addReg);
}
};
angular.forEach(modulesToLoad, function (moduleName) {
addReg(moduleName);
});
modulesToLoad = []; // reset for next bootstrap
recordDeclarations.pop(); // wait for the next lazy load
};
/**
* Like JSON.stringify but that doesn't throw on circular references
* @param obj
*/
var stringify = function stringify(obj) {
try {
return JSON.stringify(obj);
} catch (e) {
var cache = [];
return JSON.stringify(obj, function (key, value) {
if (angular.isObject(value) && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
}
};
var hashCode = function hashCode(str) {
var hash = 0,
i,
chr,
len;
if (str.length == 0) {
return hash;
}
for (i = 0, len = str.length; i < len; i++) {
chr = str.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
function _register(providers, registerModules, params) {
if (registerModules) {
var k,
moduleName,
moduleFn,
tempRunBlocks = [];
for (k = registerModules.length - 1; k >= 0; k--) {
moduleName = registerModules[k];
if (!angular.isString(moduleName)) {
moduleName = getModuleName(moduleName);
}
if (!moduleName || justLoaded.indexOf(moduleName) !== -1 || modules[moduleName] && realModules.indexOf(moduleName) === -1) {
continue;
}
// new if not registered
var newModule = regModules.indexOf(moduleName) === -1;
moduleFn = ngModuleFct(moduleName);
if (newModule) {
regModules.push(moduleName);
_register(providers, moduleFn.requires, params);
}
if (moduleFn._runBlocks.length > 0) {
// new run blocks detected! Replace the old ones (if existing)
runBlocks[moduleName] = [];
while (moduleFn._runBlocks.length > 0) {
runBlocks[moduleName].push(moduleFn._runBlocks.shift());
}
}
if (angular.isDefined(runBlocks[moduleName]) && (newModule || params.rerun)) {
tempRunBlocks = tempRunBlocks.concat(runBlocks[moduleName]);
}
_invokeQueue(providers, moduleFn._invokeQueue, moduleName, params.reconfig);
_invokeQueue(providers, moduleFn._configBlocks, moduleName, params.reconfig); // angular 1.3+
broadcast(newModule ? 'ocLazyLoad.moduleLoaded' : 'ocLazyLoad.moduleReloaded', moduleName);
registerModules.pop();
justLoaded.push(moduleName);
}
// execute the run blocks at the end
var instanceInjector = providers.getInstanceInjector();
angular.forEach(tempRunBlocks, function (fn) {
instanceInjector.invoke(fn);
});
}
}
function _registerInvokeList(args, moduleName) {
var invokeList = args[2][0],
type = args[1],
newInvoke = false;
if (angular.isUndefined(regInvokes[moduleName])) {
regInvokes[moduleName] = {};
}
if (angular.isUndefined(regInvokes[moduleName][type])) {
regInvokes[moduleName][type] = {};
}
var onInvoke = function onInvoke(invokeName, invoke) {
if (!regInvokes[moduleName][type].hasOwnProperty(invokeName)) {
regInvokes[moduleName][type][invokeName] = [];
}
if (checkHashes(invoke, regInvokes[moduleName][type][invokeName])) {
newInvoke = true;
regInvokes[moduleName][type][invokeName].push(invoke);
broadcast('ocLazyLoad.componentLoaded', [moduleName, type, invokeName]);
}
};
function checkHashes(potentialNew, invokes) {
var isNew = true,
newHash;
if (invokes.length) {
newHash = signature(potentialNew);
angular.forEach(invokes, function (invoke) {
isNew = isNew && signature(invoke) !== newHash;
});
}
return isNew;
}
function signature(data) {
if (angular.isArray(data)) {
// arrays are objects, we need to test for it first
return hashCode(data.toString());
} else if (angular.isObject(data)) {
// constants & values for example
return hashCode(stringify(data));
} else {
if (angular.isDefined(data) && data !== null) {
return hashCode(data.toString());
} else {
// null & undefined constants
return data;
}
}
}
if (angular.isString(invokeList)) {
onInvoke(invokeList, args[2][1]);
} else if (angular.isObject(invokeList)) {
angular.forEach(invokeList, function (invoke, key) {
if (angular.isString(invoke)) {
// decorators for example
onInvoke(invoke, invokeList[1]);
} else {
// components registered as object lists {"componentName": function() {}}
onInvoke(key, invoke);
}
});
} else {
return false;
}
return newInvoke;
}
function _invokeQueue(providers, queue, moduleName, reconfig) {
if (!queue) {
return;
}
var i, len, args, provider;
for (i = 0, len = queue.length; i < len; i++) {
args = queue[i];
if (angular.isArray(args)) {
if (providers !== null) {
if (providers.hasOwnProperty(args[0])) {
provider = providers[args[0]];
} else {
throw new Error('unsupported provider ' + args[0]);
}
}
var isNew = _registerInvokeList(args, moduleName);
if (args[1] !== 'invoke') {
if (isNew && angular.isDefined(provider)) {
provider[args[1]].apply(provider, args[2]);
}
} else {
// config block
var callInvoke = function callInvoke(fct) {
var invoked = regConfigs.indexOf(moduleName + '-' + fct);
if (invoked === -1 || reconfig) {
if (invoked === -1) {
regConfigs.push(moduleName + '-' + fct);
}
if (angular.isDefined(provider)) {
provider[args[1]].apply(provider, args[2]);
}
}
};
if (angular.isFunction(args[2][0])) {
callInvoke(args[2][0]);
} else if (angular.isArray(args[2][0])) {
for (var j = 0, jlen = args[2][0].length; j < jlen; j++) {
if (angular.isFunction(args[2][0][j])) {
callInvoke(args[2][0][j]);
}
}
}
}
}
}
}
function getModuleName(module) {
var moduleName = null;
if (angular.isString(module)) {
moduleName = module;
} else if (angular.isObject(module) && module.hasOwnProperty('name') && angular.isString(module.name)) {
moduleName = module.name;
}
return moduleName;
}
function moduleExists(moduleName) {
if (!angular.isString(moduleName)) {
return false;
}
try {
return ngModuleFct(moduleName);
} catch (e) {
if (/No module/.test(e) || e.message.indexOf('$injector:nomod') > -1) {
return false;
}
}
}
this.$get = ["$log", "$rootElement", "$rootScope", "$cacheFactory", "$q", function ($log, $rootElement, $rootScope, $cacheFactory, $q) {
var instanceInjector,
filesCache = $cacheFactory('ocLazyLoad');
if (!debug) {
$log = {};
$log['error'] = angular.noop;
$log['warn'] = angular.noop;
$log['info'] = angular.noop;
}
// Make this lazy because when $get() is called the instance injector hasn't been assigned to the rootElement yet
providers.getInstanceInjector = function () {
return instanceInjector ? instanceInjector : instanceInjector = $rootElement.data('$injector') || angular.injector();
};
broadcast = function broadcast(eventName, params) {
if (events) {
$rootScope.$broadcast(eventName, params);
}
if (debug) {
$log.info(eventName, params);
}
};
function reject(e) {
var deferred = $q.defer();
$log.error(e.message);
deferred.reject(e);
return deferred.promise;
}
return {
_broadcast: broadcast,
_$log: $log,
/**
* Returns the files cache used by the loaders to store the files currently loading
* @returns {*}
*/
_getFilesCache: function getFilesCache() {
return filesCache;
},
/**
* Let the service know that it should monitor angular.module because files are loading
* @param watch boolean
*/
toggleWatch: function toggleWatch(watch) {
if (watch) {
recordDeclarations.push(true);
} else {
recordDeclarations.pop();
}
},
/**
* Let you get a module config object
* @param moduleName String the name of the module
* @returns {*}
*/
getModuleConfig: function getModuleConfig(moduleName) {
if (!angular.isString(moduleName)) {
throw new Error('You need to give the name of the module to get');
}
if (!modules[moduleName]) {
return null;
}
return angular.copy(modules[moduleName]);
},
/**
* Let you define a module config object
* @param moduleConfig Object the module config object
* @returns {*}
*/
setModuleConfig: function setModuleConfig(moduleConfig) {
if (!angular.isObject(moduleConfig)) {
throw new Error('You need to give the module config object to set');
}
modules[moduleConfig.name] = moduleConfig;
return moduleConfig;
},
/**
* Returns the list of loaded modules
* @returns {string[]}
*/
getModules: function getModules() {
return regModules;
},
/**
* Let you check if a module has been loaded into Angular or not
* @param modulesNames String/Object a module name, or a list of module names
* @returns {boolean}
*/
isLoaded: function isLoaded(modulesNames) {
var moduleLoaded = function moduleLoaded(module) {
var isLoaded = regModules.indexOf(module) > -1;
if (!isLoaded) {
isLoaded = !!moduleExists(module);
}
return isLoaded;
};
if (angular.isString(modulesNames)) {
modulesNames = [modulesNames];
}
if (angular.isArray(modulesNames)) {
var i, len;
for (i = 0, len = modulesNames.length; i < len; i++) {
if (!moduleLoaded(modulesNames[i])) {
return false;
}
}
return true;
} else {
throw new Error('You need to define the module(s) name(s)');
}
},
/**
* Given a module, return its name
* @param module
* @returns {String}
*/
_getModuleName: getModuleName,
/**
* Returns a module if it exists
* @param moduleName
* @returns {module}
*/
_getModule: function getModule(moduleName) {
try {
return ngModuleFct(moduleName);
} catch (e) {
// this error message really suxx
if (/No module/.test(e) || e.message.indexOf('$injector:nomod') > -1) {
e.message = 'The module "' + stringify(moduleName) + '" that you are trying to load does not exist. ' + e.message;
}
throw e;
}
},
/**
* Check if a module exists and returns it if it does
* @param moduleName
* @returns {boolean}
*/
moduleExists: moduleExists,
/**
* Load the dependencies, and might try to load new files depending on the config
* @param moduleName (String or Array of Strings)
* @param localParams
* @returns {*}
* @private
*/
_loadDependencies: function _loadDependencies(moduleName, localParams) {
var loadedModule,
requires,
diff,
promisesList = [],
self = this;
moduleName = self._getModuleName(moduleName);
if (moduleName === null) {
return $q.when();
} else {
try {
loadedModule = self._getModule(moduleName);
} catch (e) {
return reject(e);
}
// get unloaded requires
requires = self.getRequires(loadedModule);
}
angular.forEach(requires, function (requireEntry) {
// If no configuration is provided, try and find one from a previous load.
// If there isn't one, bail and let the normal flow run
if (angular.isString(requireEntry)) {
var config = self.getModuleConfig(requireEntry);
if (config === null) {
moduleCache.push(requireEntry); // We don't know about this module, but something else might, so push it anyway.
return;
}
requireEntry = config;
// ignore the name because it's probably not a real module name
config.name = undefined;
}
// Check if this dependency has been loaded previously
if (self.moduleExists(requireEntry.name)) {
// compare against the already loaded module to see if the new definition adds any new files
diff = requireEntry.files.filter(function (n) {
return self.getModuleConfig(requireEntry.name).files.indexOf(n) < 0;
});
// If the module was redefined, advise via the console
if (diff.length !== 0) {
self._$log.warn('Module "', moduleName, '" attempted to redefine configuration for dependency. "', requireEntry.name, '"\n Additional Files Loaded:', diff);
}
// Push everything to the file loader, it will weed out the duplicates.
if (angular.isDefined(self.filesLoader)) {
// if a files loader is defined
promisesList.push(self.filesLoader(requireEntry, localParams).then(function () {
return self._loadDependencies(requireEntry);
}));
} else {
return reject(new Error('Error: New dependencies need to be loaded from external files (' + requireEntry.files + '), but no loader has been defined.'));
}
return;
} else if (angular.isArray(requireEntry)) {
var files = [];
angular.forEach(requireEntry, function (entry) {
// let's check if the entry is a file name or a config name
var config = self.getModuleConfig(entry);
if (config === null) {
files.push(entry);
} else if (config.files) {
files = files.concat(config.files);
}
});
if (files.length > 0) {
requireEntry = {
files: files
};
}
} else if (angular.isObject(requireEntry)) {
if (requireEntry.hasOwnProperty('name') && requireEntry['name']) {
// The dependency doesn't exist in the module cache and is a new configuration, so store and push it.
self.setModuleConfig(requireEntry);
moduleCache.push(requireEntry['name']);
}
}
// Check if the dependency has any files that need to be loaded. If there are, push a new promise to the promise list.
if (angular.isDefined(requireEntry.files) && requireEntry.files.length !== 0) {
if (angular.isDefined(self.filesLoader)) {
// if a files loader is defined
promisesList.push(self.filesLoader(requireEntry, localParams).then(function () {
return self._loadDependencies(requireEntry);
}));
} else {
return reject(new Error('Error: the module "' + requireEntry.name + '" is defined in external files (' + requireEntry.files + '), but no loader has been defined.'));
}
}
});
// Create a wrapper promise to watch the promise list and resolve it once everything is done.
return $q.all(promisesList);
},
/**
* Inject new modules into Angular
* @param moduleName
* @param localParams
* @param real
*/
inject: function inject(moduleName) {
var localParams = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var real = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
var self = this,
deferred = $q.defer();
if (angular.isDefined(moduleName) && moduleName !== null) {
if (angular.isArray(moduleName)) {
var promisesList = [];
angular.forEach(moduleName, function (module) {
promisesList.push(self.inject(module, localParams, real));
});
return $q.all(promisesList);
} else {
self._addToLoadList(self._getModuleName(moduleName), true, real);
}
}
if (modulesToLoad.length > 0) {
var res = modulesToLoad.slice(); // clean copy
var loadNext = function loadNext(moduleName) {
moduleCache.push(moduleName);
modulePromises[moduleName] = deferred.promise;
self._loadDependencies(moduleName, localParams).then(function success() {
try {
justLoaded = [];
_register(providers, moduleCache, localParams);
} catch (e) {
self._$log.error(e.message);
deferred.reject(e);
return;
}
if (modulesToLoad.length > 0) {
loadNext(modulesToLoad.shift()); // load the next in list
} else {
deferred.resolve(res); // everything has been loaded, resolve
}
}, function error(err) {
deferred.reject(err);
});
};
// load the first in list
loadNext(modulesToLoad.shift());
} else if (localParams && localParams.name && modulePromises[localParams.name]) {
return modulePromises[localParams.name];
} else {
deferred.resolve();
}
return deferred.promise;
},
/**
* Get the list of required modules/services/... for this module
* @param module
* @returns {Array}
*/
getRequires: function getRequires(module) {
var requires = [];
angular.forEach(module.requires, function (requireModule) {
if (regModules.indexOf(requireModule) === -1) {
requires.push(requireModule);
}
});
return requires;
},
/**
* Invoke the new modules & component by their providers
* @param providers
* @param queue
* @param moduleName
* @param reconfig
* @private
*/
_invokeQueue: _invokeQueue,
/**
* Check if a module has been invoked and registers it if not
* @param args
* @param moduleName
* @returns {boolean} is new
*/
_registerInvokeList: _registerInvokeList,
/**
* Register a new module and loads it, executing the run/config blocks if needed
* @param providers
* @param registerModules
* @param params
* @private
*/
_register: _register,
/**
* Add a module name to the list of modules that will be loaded in the next inject
* @param name
* @param force
* @private
*/
_addToLoadList: _addToLoadList,
/**
* Unregister modules (you shouldn't have to use this)
* @param modules
*/
_unregister: function _unregister(modules) {
if (angular.isDefined(modules)) {
if (angular.isArray(modules)) {
angular.forEach(modules, function (module) {
regInvokes[module] = undefined;
});
}
}
}
};
}];
// Let's get the list of loaded modules & components
this._init(angular.element(window.document));
}]);
var bootstrapFct = angular.bootstrap;
angular.bootstrap = function (element, modules, config) {
// we use slice to make a clean copy
angular.forEach(modules.slice(), function (module) {
_addToLoadList(module, true, true);
});
return bootstrapFct(element, modules, config);
};
var _addToLoadList = function _addToLoadList(name, force, real) {
if ((recordDeclarations.length > 0 || force) && angular.isString(name) && modulesToLoad.indexOf(name) === -1) {
modulesToLoad.push(name);
if (real) {
realModules.push(name);
}
}
};
var ngModuleFct = angular.module;
angular.module = function (name, requires, configFn) {
_addToLoadList(name, false, true);
return ngModuleFct(name, requires, configFn);
};
// CommonJS package manager support:
if (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.exports === exports) {
module.exports = 'oc.lazyLoad';
}
})(angular, window);
(function (angular) {
'use strict';
angular.module('oc.lazyLoad').directive('ocLazyLoad', ["$ocLazyLoad", "$compile", "$animate", "$parse", "$timeout", function ($ocLazyLoad, $compile, $animate, $parse, $timeout) {
return {
restrict: 'A',
terminal: true,
priority: 1000,
compile: function compile(element, attrs) {
// we store the content and remove it before compilation
var content = element[0].innerHTML;
element.html('');
return function ($scope, $element, $attr) {
var model = $parse($attr.ocLazyLoad);
$scope.$watch(function () {
return model($scope) || $attr.ocLazyLoad; // it can be a module name (string), an object, an array, or a scope reference to any of this
}, function (moduleName) {
if (angular.isDefined(moduleName)) {
$ocLazyLoad.load(moduleName).then(function () {
// Attach element contents to DOM and then compile them.
// This prevents an issue where IE invalidates saved element objects (HTMLCollections)
// of the compiled contents when attaching to the parent DOM.
$animate.enter(content, $element);
// get the new content & compile it
$compile($element.contents())($scope);
});
}
}, true);
};
}
};
}]);
})(angular);
(function (angular) {
'use strict';
angular.module('oc.lazyLoad').config(["$provide", function ($provide) {
$provide.decorator('$ocLazyLoad', ["$delegate", "$q", "$window", "$interval", function ($delegate, $q, $window, $interval) {
var uaCssChecked = false,
useCssLoadPatch = false,
anchor = $window.document.getElementsByTagName('head')[0] || $window.document.getElementsByTagName('body')[0];
/**
* Load a js/css file
* @param type
* @param path
* @param params
* @returns promise
*/
$delegate.buildElement = function buildElement(type, path, params) {
var deferred = $q.defer(),
el,
loaded,
filesCache = $delegate._getFilesCache(),
cacheBuster = function cacheBuster(url) {
var dc = new Date().getTime();
if (url.indexOf('?') >= 0) {
if (url.substring(0, url.length - 1) === '&') {
return url + '_dc=' + dc;
}
return url + '&_dc=' + dc;
} else {
return url + '?_dc=' + dc;
}
};
// Store the promise early so the file load can be detected by other parallel lazy loads
// (ie: multiple routes on one page) a 'true' value isn't sufficient
// as it causes false positive load results.
if (angular.isUndefined(filesCache.get(path))) {
filesCache.put(path, deferred.promise);
}
// Switch in case more content types are added later
switch (type) {
case 'css':
el = $window.document.createElement('link');
el.type = 'text/css';
el.rel = 'stylesheet';
el.href = params.cache === false ? cacheBuster(path) : path;
break;
case 'js':
el = $window.document.createElement('script');
el.src = params.cache === false ? cacheBuster(path) : path;
break;
default:
filesCache.remove(path);
deferred.reject(new Error('Requested type "' + type + '" is not known. Could not inject "' + path + '"'));
break;
}
el.onload = el['onreadystatechange'] = function (e) {
if (el['readyState'] && !/^c|loade/.test(el['readyState']) || loaded) return;
el.onload = el['onreadystatechange'] = null;
loaded = 1;
$delegate._broadcast('ocLazyLoad.fileLoaded', path);
deferred.resolve();
};
el.onerror = function () {
filesCache.remove(path);
deferred.reject(new Error('Unable to load ' + path));
};
el.async = params.serie ? 0 : 1;
var insertBeforeElem = anchor.lastChild;
if (params.insertBefore) {
var element = angular.element(angular.isDefined(window.jQuery) ? params.insertBefore : document.querySelector(params.insertBefore));
if (element && element.length > 0) {
insertBeforeElem = element[0];
}
}
insertBeforeElem.parentNode.insertBefore(el, insertBeforeElem);
/*
The event load or readystatechange doesn't fire in:
- iOS < 6 (default mobile browser)
- Android < 4.4 (default mobile browser)
- Safari < 6 (desktop browser)
*/
if (type == 'css') {
if (!uaCssChecked) {
var ua = $window.navigator.userAgent.toLowerCase();
// iOS < 6
if (/iP(hone|od|ad)/.test($window.navigator.platform)) {
var v = $window.navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
var iOSVersion = parseFloat([parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)].join('.'));
useCssLoadPatch = iOSVersion < 6;
} else if (ua.indexOf("android") > -1) {
// Android < 4.4
var androidVersion = parseFloat(ua.slice(ua.indexOf("android") + 8));
useCssLoadPatch = androidVersion < 4.4;
} else if (ua.indexOf('safari') > -1) {
var versionMatch = ua.match(/version\/([\.\d]+)/i);
useCssLoadPatch = versionMatch && versionMatch[1] && parseFloat(versionMatch[1]) < 6;
}
}
if (useCssLoadPatch) {
var tries = 1000; // * 20 = 20000 miliseconds
var interval = $interval(function () {
try {
el.sheet.cssRules;
$interval.cancel(interval);
el.onload();
} catch (e) {
if (--tries <= 0) {
el.onerror();
}
}
}, 20);
}
}
return deferred.promise;
};
return $delegate;
}]);
}]);
})(angular);
(function (angular) {
'use strict';
angular.module('oc.lazyLoad').config(["$provide", function ($provide) {
$provide.decorator('$ocLazyLoad', ["$delegate", "$q", function ($delegate, $q) {
/**
* The function that loads new files
* @param config
* @param params
* @returns {*}
*/
$delegate.filesLoader = function filesLoader(config) {
var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var cssFiles = [],
templatesFiles = [],
jsFiles = [],
promises = [],
cachePromise = null,
filesCache = $delegate._getFilesCache();
$delegate.toggleWatch(true); // start watching angular.module calls
angular.extend(params, config);
var pushFile = function pushFile(path) {
var file_type = null,
m;
if (angular.isObject(path)) {
file_type = path.type;
path = path.path;
}
cachePromise = filesCache.get(path);
if (angular.isUndefined(cachePromise) || params.cache === false) {
// always check for requirejs syntax just in case
if ((m = /^(css|less|html|htm|js)?(?=!)/.exec(path)) !== null) {
// Detect file type using preceding type declaration (ala requireJS)
file_type = m[1];
path = path.substr(m[1].length + 1, path.length); // Strip the type from the path
}
if (!file_type) {
if ((m = /[.](css|less|html|htm|js)?((\?|#).*)?$/.exec(path)) !== null) {
// Detect file type via file extension
file_type = m[1];
} else if (!$delegate.jsLoader.hasOwnProperty('ocLazyLoadLoader') && $delegate.jsLoader.hasOwnProperty('requirejs')) {
// requirejs
file_type = 'js';
} else {
$delegate._$log.error('File type could not be determined. ' + path);
return;
}
}
if ((file_type === 'css' || file_type === 'less') && cssFiles.indexOf(path) === -1) {
cssFiles.push(path);
} else if ((file_type === 'html' || file_type === 'htm') && templatesFiles.indexOf(path) === -1) {
templatesFiles.push(path);
} else if (file_type === 'js' || jsFiles.indexOf(path) === -1) {
jsFiles.push(path);
} else {
$delegate._$log.error('File type is not valid. ' + path);
}
} else if (cachePromise) {
promises.push(cachePromise);
}
};
if (params.serie) {
pushFile(params.files.shift());
} else {
angular.forEach(params.files, function (path) {
pushFile(path);
});
}
if (cssFiles.length > 0) {
var cssDeferred = $q.defer();
$delegate.cssLoader(cssFiles, function (err) {
if (angular.isDefined(err) && $delegate.cssLoader.hasOwnProperty('ocLazyLoadLoader')) {
$delegate._$log.error(err);
cssDeferred.reject(err);
} else {
cssDeferred.resolve();
}
}, params);
promises.push(cssDeferred.promise);
}
if (templatesFiles.length > 0) {
var templatesDeferred = $q.defer();
$delegate.templatesLoader(templatesFiles, function (err) {
if (angular.isDefined(err) && $delegate.templatesLoader.hasOwnProperty('ocLazyLoadLoader')) {
$delegate._$log.error(err);
templatesDeferred.reject(err);
} else {
templatesDeferred.resolve();
}
}, params);
promises.push(templatesDeferred.promise);
}
if (jsFiles.length > 0) {
var jsDeferred = $q.defer();
$delegate.jsLoader(jsFiles, function (err) {
if (angular.isDefined(err) && ($delegate.jsLoader.hasOwnProperty("ocLazyLoadLoader") || $delegate.jsLoader.hasOwnProperty("requirejs"))) {
$delegate._$log.error(err);
jsDeferred.reject(err);
} else {
jsDeferred.resolve();
}
}, params);
promises.push(jsDeferred.promise);
}
if (promises.length === 0) {
var deferred = $q.defer(),
err = "Error: no file to load has been found, if you're trying to load an existing module you should use the 'inject' method instead of 'load'.";
$delegate._$log.error(err);
deferred.reject(err);
return deferred.promise;
} else if (params.serie && params.files.length > 0) {
return $q.all(promises).then(function () {
return $delegate.filesLoader(config, params);
});
} else {
return $q.all(promises)['finally'](function (res) {
$delegate.toggleWatch(false); // stop watching angular.module calls
return res;
});
}
};
/**
* Load a module or a list of modules into Angular
* @param module Mixed the name of a predefined module config object, or a module config object, or an array of either
* @param params Object optional parameters
* @returns promise
*/
$delegate.load = function (originalModule) {
var originalParams = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var self = this,
config = null,
deferredList = [],
deferred = $q.defer(),
errText;
// clean copy
var module = angular.copy(originalModule);
var params = angular.copy(originalParams);
// If module is an array, break it down
if (angular.isArray(module)) {
// Resubmit each entry as a single module
angular.forEach(module, function (m) {
deferredList.push(self.load(m, params));
});
// Resolve the promise once everything has loaded
$q.all(deferredList).then(function (res) {
deferred.resolve(res);
}, function (err) {
deferred.reject(err);
});
return deferred.promise;
}
// Get or Set a configuration depending on what was passed in
if (angular.isString(module)) {
config = self.getModuleConfig(module);
if (!config) {
config = {
files: [module]
};
}
} else if (angular.isObject(module)) {
// case {type: 'js', path: lazyLoadUrl + 'testModule.fakejs'}
if (angular.isDefined(module.path) && angular.isDefined(module.type)) {
config = {
files: [module]
};
} else {
config = self.setModuleConfig(module);
}
}
if (config === null) {
var moduleName = self._getModuleName(module);
errText = 'Module "' + (moduleName || 'unknown') + '" is not configured, cannot load.';
$delegate._$log.error(errText);
deferred.reject(new Error(errText));
return deferred.promise;
} else {
// deprecated
if (angular.isDefined(config.template)) {
if (angular.isUndefined(config.files)) {
config.files = [];
}
if (angular.isString(config.template)) {
config.files.push(config.template);
} else if (angular.isArray(config.template)) {
config.files.concat(config.template);
}
}
}
var localParams = angular.extend({}, params, config);
// if someone used an external loader and called the load function with just the module name
if (angular.isUndefined(config.files) && angular.isDefined(config.name) && $delegate.moduleExists(config.name)) {
return $delegate.inject(config.name, localParams, true);
}
$delegate.filesLoader(config, localParams).then(function () {
$delegate.inject(null, localParams).then(function (res) {
deferred.resolve(res);
}, function (err) {
deferred.reject(err);
});
}, function (err) {
deferred.reject(err);
});
return deferred.promise;
};
// return the patched service
return $delegate;
}]);
}]);
})(angular);
(function (angular) {
'use strict';
angular.module('oc.lazyLoad').config(["$provide", function ($provide) {
$provide.decorator('$ocLazyLoad', ["$delegate", "$q", function ($delegate, $q) {
/**
* cssLoader function
* @type Function
* @param paths array list of css files to load
* @param callback to call when everything is loaded. We use a callback and not a promise
* @param params object config parameters
* because the user can overwrite cssLoader and it will probably not use promises :(
*/
$delegate.cssLoader = function (paths, callback, params) {
var promises = [];
angular.forEach(paths, function (path) {
promises.push($delegate.buildElement('css', path, params));
});
$q.all(promises).then(function () {
callback();
}, function (err) {
callback(err);
});
};
$delegate.cssLoader.ocLazyLoadLoader = true;
return $delegate;
}]);
}]);
})(angular);
(function (angular) {
'use strict';
angular.module('oc.lazyLoad').config(["$provide", function ($provide) {
$provide.decorator('$ocLazyLoad', ["$delegate", "$q", function ($delegate, $q) {
/**
* jsLoader function
* @type Function
* @param paths array list of js files to load
* @param callback to call when everything is loaded. We use a callback and not a promise
* @param params object config parameters
* because the user can overwrite jsLoader and it will probably not use promises :(
*/
$delegate.jsLoader = function (paths, callback, params) {
var promises = [];
angular.forEach(paths, function (path) {
promises.push($delegate.buildElement('js', path, params));
});
$q.all(promises).then(function () {
callback();
}, function (err) {
callback(err);
});
};
$delegate.jsLoader.ocLazyLoadLoader = true;
return $delegate;
}]);
}]);
})(angular);
(function (angular) {
'use strict';
angular.module('oc.lazyLoad').config(["$provide", function ($provide) {
$provide.decorator('$ocLazyLoad', ["$delegate", "$templateCache", "$q", "$http", function ($delegate, $templateCache, $q, $http) {
/**
* templatesLoader function
* @type Function
* @param paths array list of css files to load
* @param callback to call when everything is loaded. We use a callback and not a promise
* @param params object config parameters for $http
* because the user can overwrite templatesLoader and it will probably not use promises :(
*/
$delegate.templatesLoader = function (paths, callback, params) {
var promises = [],
filesCache = $delegate._getFilesCache();
angular.forEach(paths, function (url) {
var deferred = $q.defer();
promises.push(deferred.promise);
$http.get(url, params).success(function (data) {
if (angular.isString(data) && data.length > 0) {
angular.forEach(angular.element(data), function (node) {
if (node.nodeName === 'SCRIPT' && node.type === 'text/ng-template') {
$templateCache.put(node.id, node.innerHTML);
}
});
}
if (angular.isUndefined(filesCache.get(url))) {
filesCache.put(url, true);
}
deferred.resolve();
}).error(function (err) {
deferred.reject(new Error('Unable to load template file "' + url + '": ' + err));
});
});
return $q.all(promises).then(function () {
callback();
}, function (err) {
callback(err);
});
};
$delegate.templatesLoader.ocLazyLoadLoader = true;
return $delegate;
}]);
}]);
})(angular);
// Array.indexOf polyfill for IE8
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
// TODO: Text Color, Text BG Color
angular.module('textAngular.ext', ['textAngularSetup', 'neModals'])
.value('taOptions', {
forceTextAngularSanitize: true,
keyMappings : [],
toolbar: [
['undo', 'redo'],
['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'pre', 'quote', 'table'],
['bold', 'italics', 'underline', 'strikeThrough', 'ul', 'ol'],
['color', 'bgColor', 'clear'],
['justifyLeft','justifyCenter','justifyRight','justifyFull','indent','outdent'],
['html', 'insertImage', 'insertLink', 'insertVideo'] // 'wordcount', 'charcount'
],
classes: {
focussed: "focussed",
toolbar: "btn-toolbar",
toolbarGroup: "btn-group btn-group-xs",
toolbarButton: "btn btn-default",
toolbarButtonActive: "active",
disabled: "disabled",
textEditor: 'form-control',
htmlEditor: 'form-control'
},
defaultTagAttributes : {
a: {target:""}
},
setup: {
// wysiwyg mode
textEditorSetup: function($element){ /* Do some processing here */ },
// raw html
htmlEditorSetup: function($element){ /* Do some processing here */ }
},
defaultFileDropHandler: function(file, insertAction){
// var reader = new FileReader();
// if(file.type.substring(0, 5) === 'image'){
// reader.onload = function() {
// if(reader.result !== '') insertAction('insertImage', reader.result, true);
// };
//
// reader.readAsDataURL(file);
// // NOTE: For async procedures return a promise and resolve it when the editor should update the model.
// return true;
// }
return false;
}
})
.run(['$templateCache', function($templateCache) {
$templateCache.put('textAngular/insert-link-modal.html',
'<div>'+
' <div>'+
' <input type="text" class="form-control" ng-model="modal.link" placeholder="http://" />'+
' </div>'+
' <div class="text-right margin-top-lg">'+
' <button class="btn btn-default" ng-click="modal.close()">{{::\'Cancel\'|translate}}</button>'+
' <button class="btn btn-mini btn-primary" ng-disabled="!modal.link" ng-click="modal.insertLink(modal.link);modal.close()">{{::\'Insert\'|translate}}</button>'+
' </div>'+
'</div>');
$templateCache.put('textAngular/insert-table-modal.html',
'<div>'+
' <div>'+
' <label>{{::\'Columns\'|translate}}</label><br>'+
' <input type="number" class="form-control" ng-model="modal.cols"><br>'+
' '+
' <label>{{::\'Rows\'|translate}}</label><br>'+
' <input type="number" class="form-control" ng-model="modal.rows">'+
' </div>'+
' <div class="text-right margin-top-lg">'+
' <button class="btn btn-default btn-mini" ng-click="modal.close()">{{::\'Cancel\'|translate}}</button>'+
' <button class="btn btn-mini btn-primary" ng-click="modal.insertTable(modal.cols || 2, modal.rows || 2);modal.close()">{{::\'Insert\'|translate}}</button>'+
' </div>'+
'</div>');
$templateCache.put('textAngular/change-color-dropdown.html',
'<div class="btn-group" style="float:left;" uib-dropdown>'+
' <button class="btn btn-default btn-xs" uib-dropdown-toggle ng-click="storeSelection()" ng-disabled="isDisabled()">'+
' <i class="fa {{icon}}"></i><i class="fa fa-caret-down"></i>'+
' </button>'+
' <ul class="dropdown-menu">'+
' <li ng-repeat="c in colors" style="float:left;float:left;margin:2px;">'+
' <a href="" style="border:1px solid black;display:block;width:15px;height:15px;padding:0px;background-color:{{c}}"'+
' ng-click="setColor(c)"> </a>'+
' </li>'+
' </ul>'+
'</div>');
}])
.run(['$templateCache', '$window', 'taRegisterTool', 'taTranslations', 'taSelection', 'taToolFunctions', '$sanitize', 'taOptions','taTools','neModals', function($templateCache, $window, taRegisterTool, taTranslations, taSelection, taToolFunctions, $sanitize, taOptions, taTools, neModals){
taTools.clear.iconclass = 'fa fa-eraser';
taTools.clear.action = function(){
this.$editor().wrapSelection('removeFormat', null);
};
taTools.insertLink.action = function(deferred, restoreSelection){
var ta = this;
neModals.create({
id: 'textAngular.insertLink',
title: 'Insert Link',
templateUrl: 'textAngular/insert-link-modal.html',
removeOnClose: true,
link:'http://',
onClose: function(){
if(!this.inserted){
restoreSelection();
deferred.resolve();
}
},
insertLink: function(link){
this.inserted = true;
restoreSelection();
if(link && link !== '' && link !== 'http://') {
ta.$editor().wrapSelection('createLink', link, true);
}
deferred.resolve();
}
});
return false;
};
taTools.insertImage.action = function(deferred, restoreSelection){
var ta = this;
neModals.create({
id: 'textAngular.insertImage',
title: 'Insert Image',
templateUrl: 'textAngular/insert-link-modal.html',
removeOnClose: true,
link:'http://',
onClose: function(){
if(!this.inserted){
restoreSelection();
deferred.resolve();
}
},
insertLink: function(link){
this.inserted = true;
restoreSelection();
if(link && link !== '' && link !== 'http://') {
ta.$editor().wrapSelection('insertImage', link, true);
}
deferred.resolve();
}
});
return false;
};
taTools.insertVideo.action = function(deferred, restoreSelection){
neModals.create({
id: 'textAngular.insertVideo',
title: 'Insert Youtube Video',
templateUrl: 'textAngular/insert-link-modal.html',
removeOnClose: true,
link:'https://',
onClose: function(){
if(!this.inserted){
restoreSelection();
deferred.resolve();
}
},
insertLink: function(link){
this.inserted = true;
var videoId;
restoreSelection();
if(link && link !== '' && link !== 'https://') {
videoId = taToolFunctions.extractYoutubeVideoId(link);
if(videoId){
var urlLink = "https://www.youtube.com/embed/" + videoId;
var embed = '<img class="ta-insert-video" src="https://img.youtube.com/vi/' + videoId + '/hqdefault.jpg" ta-insert-video="' + urlLink + '" contenteditable="false" allowfullscreen="true" frameborder="0" />';
ta.$editor().wrapSelection('insertHTML', embed, true);
}
}
deferred.resolve();
}
});
return false;
},
taTools.insertLink.onElementSelect.action = function(event, $element, editorScope){
// setup the editor toolbar
// Credit to the work at http://hackerwins.github.io/summernote/ for this editbar logic
event.preventDefault();
editorScope.displayElements.popover.css('width', '436px');
var container = editorScope.displayElements.popoverContainer;
container.empty();
container.css('line-height', '28px');
var link = angular.element('<a href="' + $element.attr('href') + '" target="_blank">' + $element.attr('href') + ' <i class="fa fa-mail-forward"></i></a>');
link.css({
'display': 'inline-block',
'max-width': '200px',
'overflow': 'hidden',
'text-overflow': 'ellipsis',
'white-space': 'nowrap',
'vertical-align': 'middle'
});
container.append(link);
var buttonGroup = angular.element('<div class="btn-group pull-right">');
var reLinkButton = angular.element('<button type="button" class="btn btn-default btn-sm btn-small" tabindex="-1" unselectable="on" title="' + taTranslations.editLink.reLinkButton.tooltip + '"><i class="fa fa-edit icon-edit"></i></button>');
reLinkButton.on('click', function(event){
event.preventDefault();
neModals.create({
id: 'textAngular.insertLink',
title: 'Insert Link',
templateUrl: 'textAngular/insert-link-modal.html',
removeOnClose: true,
link: $element.attr('href'),
insertLink: function(link){
if(link && link !== '' && link !== 'http://') {
$element.attr('href', link);
editorScope.updateTaBindtaTextElement();
}
editorScope.hidePopover();
}
});
});
buttonGroup.append(reLinkButton);
var targetToggle = angular.element('<button type="button" class="btn btn-default btn-sm btn-small" tabindex="-1" unselectable="on"><i class="fa fa-external-link"></i></button>');
if($element.attr('target') === '_blank'){
targetToggle.addClass('active');
}
targetToggle.on('click', function(event){
event.preventDefault();
$element.attr('target', ($element.attr('target') === '_blank') ? '' : '_blank');
targetToggle.toggleClass('active');
editorScope.updateTaBindtaTextElement();
});
buttonGroup.append(targetToggle);
var unLinkButton = angular.element('<button type="button" class="btn btn-default btn-sm btn-small" tabindex="-1" unselectable="on" title="' + taTranslations.editLink.unLinkButton.tooltip + '"><i class="fa fa-unlink icon-unlink"></i></button>');
// directly before this click event is fired a digest is fired off whereby the reference to $element is orphaned off
unLinkButton.on('click', function(event){
event.preventDefault();
$element.replaceWith($element.contents());
editorScope.updateTaBindtaTextElement();
editorScope.hidePopover();
});
buttonGroup.append(unLinkButton);
container.append(buttonGroup);
editorScope.showPopover($element);
};
taRegisterTool('table', {
iconclass: 'fa fa-table',
tooltiptext: 'Table',
action: function(deferred, restoreSelection){
var ta = this;
neModals.create({
id: 'textAngular.insertTable',
title: 'Insert Table',
templateUrl: 'textAngular/insert-table-modal.html',
removeOnClose: true,
cols:2,
rows:2,
onClose: function(){
console.warn('inserted', this.inserted);
if(!this.inserted){
restoreSelection();
deferred.resolve();
}
},
insertTable: function(cols, rows){
this.inserted = true;
restoreSelection();
if(cols > 0 && rows > 0) {
var tableHTML = createTableHTML(cols, rows);
ta.$editor().wrapSelection('insertHTML', tableHTML, true);
}
deferred.resolve();
}
});
return false;
}
});
function createTableHTML(cols, rows){
if ((rows > 0) && (cols > 0)) {
var tableHTML = '<table><thead><tr>';
for (var j=0; j < cols; j++) {
tableHTML += '<th>col'+ (j+1) +'</th>';
}
tableHTML += '</tr></thead><tbody>';
for (var i=0; i < rows; i++) {
tableHTML += '<tr>';
for (var j=0; j < cols; j++) {
tableHTML += '<td>row'+ (i+1) +'</td>';
}
tableHTML += '</tr>';
}
tableHTML += '</tbody></table>';
return tableHTML;
}
}
var colors = ['#ffffff','#ffccc9','#ffce93','#fffc9e','#ffffc7','#9aff99','#96fffb','#cdffff','#cbcefb','#cfcfcf','#fd6864','#fe996b','#fffe65','#fcff2f','#67fd9a','#38fff8','#68fdff','#9698ed','#c0c0c0','#fe0000','#f8a102','#ffcc67','#f8ff00','#34ff34','#68cbd0','#34cdf9','#6665cd','#9b9b9b','#cb0000','#f56b00','#ffcb2f','#ffc702','#32cb00','#00d2cb','#3166ff','#6434fc','#656565','#9a0000','#ce6301','#cd9934','#999903','#009901','#329a9d','#3531ff','#6200c9','#343434','#680100','#963400','#986536','#646809','#036400','#34696d','#00009b','#303498','#000000','#330001','#643403','#663234','#343300','#013300','#003532','#010066','#340096'];
taRegisterTool('color', {
display: $templateCache.get('textAngular/change-color-dropdown.html'),
class:' ',
icon:'fa-font',
colors: colors,
storeSelection: function(){
this.selection = $window.rangy.saveSelection();
},
setColor: function(color){
$window.rangy.restoreSelection(this.selection);
this.$editor().wrapSelection('foreColor', color);
},
action: function(){
return true;
}
});
taRegisterTool('bgColor', {
display: $templateCache.get('textAngular/change-color-dropdown.html'),
class:' ',
icon:'fa-magic',
colors: colors,
storeSelection: function(){
this.selection = $window.rangy.saveSelection();
},
setColor: function(color){
$window.rangy.restoreSelection(this.selection);
this.$editor().wrapSelection('backColor', color);
},
action: function(){
return true;
}
});
}]);!function(a,b){b["true"]=a,function(b,c){"function"==typeof define&&define.amd?define(b):"undefined"!=typeof module&&"object"==typeof a?module.exports=b():c.rangy=b()}(function(){function a(a,b){var c=typeof a[b];return c==u||!(c!=t||!a[b])||"unknown"==c}function b(a,b){return!(typeof a[b]!=t||!a[b])}function c(a,b){return typeof a[b]!=v}function d(a){return function(b,c){for(var d=c.length;d--;)if(!a(b,c[d]))return!1;return!0}}function e(a){return a&&A(a,z)&&C(a,y)}function f(a){return b(a,"body")?a.body:a.getElementsByTagName("body")[0]}function g(b){typeof console!=v&&a(console,"log")&&console.log(b)}function h(a,b){F&&b?alert(a):g(a)}function i(a){H.initialized=!0,H.supported=!1,h("Rangy is not supported in this environment. Reason: "+a,H.config.alertOnFail)}function j(a){h("Rangy warning: "+a,H.config.alertOnWarn)}function k(a){return a.message||a.description||String(a)}function l(){if(F&&!H.initialized){var b,c=!1,d=!1;a(document,"createRange")&&(b=document.createRange(),A(b,x)&&C(b,w)&&(c=!0));var h=f(document);if(!h||"body"!=h.nodeName.toLowerCase())return void i("No body element found");if(h&&a(h,"createTextRange")&&(b=h.createTextRange(),e(b)&&(d=!0)),!c&&!d)return void i("Neither Range nor TextRange are available");H.initialized=!0,H.features={implementsDomRange:c,implementsTextRange:d};var j,l;for(var m in E)(j=E[m])instanceof p&&j.init(j,H);for(var n=0,o=K.length;o>n;++n)try{K[n](H)}catch(q){l="Rangy init listener threw an exception. Continuing. Detail: "+k(q),g(l)}}}function m(a,b,c){c&&(a+=" in module "+c.name),H.warn("DEPRECATED: "+a+" is deprecated. Please use "+b+" instead.")}function n(a,b,c,d){a[b]=function(){return m(b,c,d),a[c].apply(a,G.toArray(arguments))}}function o(a){a=a||window,l();for(var b=0,c=L.length;c>b;++b)L[b](a)}function p(a,b,c){this.name=a,this.dependencies=b,this.initialized=!1,this.supported=!1,this.initializer=c}function q(a,b,c){var d=new p(a,b,function(b){if(!b.initialized){b.initialized=!0;try{c(H,b),b.supported=!0}catch(d){var e="Module '"+a+"' failed to load: "+k(d);g(e),d.stack&&g(d.stack)}}});return E[a]=d,d}function r(){}function s(){}var t="object",u="function",v="undefined",w=["startContainer","startOffset","endContainer","endOffset","collapsed","commonAncestorContainer"],x=["setStart","setStartBefore","setStartAfter","setEnd","setEndBefore","setEndAfter","collapse","selectNode","selectNodeContents","compareBoundaryPoints","deleteContents","extractContents","cloneContents","insertNode","surroundContents","cloneRange","toString","detach"],y=["boundingHeight","boundingLeft","boundingTop","boundingWidth","htmlText","text"],z=["collapse","compareEndPoints","duplicate","moveToElementText","parentElement","select","setEndPoint","getBoundingClientRect"],A=d(a),B=d(b),C=d(c),D=[].forEach?function(a,b){a.forEach(b)}:function(a,b){for(var c=0,d=a.length;d>c;++c)b(a[c],c)},E={},F=typeof window!=v&&typeof document!=v,G={isHostMethod:a,isHostObject:b,isHostProperty:c,areHostMethods:A,areHostObjects:B,areHostProperties:C,isTextRange:e,getBody:f,forEach:D},H={version:"1.3.0",initialized:!1,isBrowser:F,supported:!0,util:G,features:{},modules:E,config:{alertOnFail:!1,alertOnWarn:!1,preferTextRange:!1,autoInitialize:typeof rangyAutoInitialize==v?!0:rangyAutoInitialize}};H.fail=i,H.warn=j;var I;({}).hasOwnProperty?(G.extend=I=function(a,b,c){var d,e;for(var f in b)b.hasOwnProperty(f)&&(d=a[f],e=b[f],c&&null!==d&&"object"==typeof d&&null!==e&&"object"==typeof e&&I(d,e,!0),a[f]=e);return b.hasOwnProperty("toString")&&(a.toString=b.toString),a},G.createOptions=function(a,b){var c={};return I(c,b),a&&I(c,a),c}):i("hasOwnProperty not supported"),F||i("Rangy can only run in a browser"),function(){var a;if(F){var b=document.createElement("div");b.appendChild(document.createElement("span"));var c=[].slice;try{1==c.call(b.childNodes,0)[0].nodeType&&(a=function(a){return c.call(a,0)})}catch(d){}}a||(a=function(a){for(var b=[],c=0,d=a.length;d>c;++c)b[c]=a[c];return b}),G.toArray=a}();var J;F&&(a(document,"addEventListener")?J=function(a,b,c){a.addEventListener(b,c,!1)}:a(document,"attachEvent")?J=function(a,b,c){a.attachEvent("on"+b,c)}:i("Document does not have required addEventListener or attachEvent method"),G.addListener=J);var K=[];G.deprecationNotice=m,G.createAliasForDeprecatedMethod=n,H.init=l,H.addInitListener=function(a){H.initialized?a(H):K.push(a)};var L=[];H.addShimListener=function(a){L.push(a)},F&&(H.shim=H.createMissingNativeApi=o,n(H,"createMissingNativeApi","shim")),p.prototype={init:function(){for(var a,b,c=this.dependencies||[],d=0,e=c.length;e>d;++d){if(b=c[d],a=E[b],!(a&&a instanceof p))throw new Error("required module '"+b+"' not found");if(a.init(),!a.supported)throw new Error("required module '"+b+"' not supported")}this.initializer(this)},fail:function(a){throw this.initialized=!0,this.supported=!1,new Error(a)},warn:function(a){H.warn("Module "+this.name+": "+a)},deprecationNotice:function(a,b){H.warn("DEPRECATED: "+a+" in module "+this.name+" is deprecated. Please use "+b+" instead")},createError:function(a){return new Error("Error in Rangy "+this.name+" module: "+a)}},H.createModule=function(a){var b,c;2==arguments.length?(b=arguments[1],c=[]):(b=arguments[2],c=arguments[1]);var d=q(a,c,b);H.initialized&&H.supported&&d.init()},H.createCoreModule=function(a,b,c){q(a,b,c)},H.RangePrototype=r,H.rangePrototype=new r,H.selectionPrototype=new s,H.createCoreModule("DomUtil",[],function(a,b){function c(a){var b;return typeof a.namespaceURI==F||null===(b=a.namespaceURI)||"http://www.w3.org/1999/xhtml"==b}function d(a){var b=a.parentNode;return 1==b.nodeType?b:null}function e(a){for(var b=0;a=a.previousSibling;)++b;return b}function f(a){switch(a.nodeType){case 7:case 10:return 0;case 3:case 8:return a.length;default:return a.childNodes.length}}function g(a,b){var c,d=[];for(c=a;c;c=c.parentNode)d.push(c);for(c=b;c;c=c.parentNode)if(K(d,c))return c;return null}function h(a,b,c){for(var d=c?b:b.parentNode;d;){if(d===a)return!0;d=d.parentNode}return!1}function i(a,b){return h(a,b,!0)}function j(a,b,c){for(var d,e=c?a:a.parentNode;e;){if(d=e.parentNode,d===b)return e;e=d}return null}function k(a){var b=a.nodeType;return 3==b||4==b||8==b}function l(a){if(!a)return!1;var b=a.nodeType;return 3==b||8==b}function m(a,b){var c=b.nextSibling,d=b.parentNode;return c?d.insertBefore(a,c):d.appendChild(a),a}function n(a,b,c){var d=a.cloneNode(!1);if(d.deleteData(0,b),a.deleteData(b,a.length-b),m(d,a),c)for(var f,g=0;f=c[g++];)f.node==a&&f.offset>b?(f.node=d,f.offset-=b):f.node==a.parentNode&&f.offset>e(a)&&++f.offset;return d}function o(a){if(9==a.nodeType)return a;if(typeof a.ownerDocument!=F)return a.ownerDocument;if(typeof a.document!=F)return a.document;if(a.parentNode)return o(a.parentNode);throw b.createError("getDocument: no document found for node")}function p(a){var c=o(a);if(typeof c.defaultView!=F)return c.defaultView;if(typeof c.parentWindow!=F)return c.parentWindow;throw b.createError("Cannot get a window object for node")}function q(a){if(typeof a.contentDocument!=F)return a.contentDocument;if(typeof a.contentWindow!=F)return a.contentWindow.document;throw b.createError("getIframeDocument: No Document object found for iframe element")}function r(a){if(typeof a.contentWindow!=F)return a.contentWindow;if(typeof a.contentDocument!=F)return a.contentDocument.defaultView;throw b.createError("getIframeWindow: No Window object found for iframe element")}function s(a){return a&&G.isHostMethod(a,"setTimeout")&&G.isHostObject(a,"document")}function t(a,b,c){var d;if(a?G.isHostProperty(a,"nodeType")?d=1==a.nodeType&&"iframe"==a.tagName.toLowerCase()?q(a):o(a):s(a)&&(d=a.document):d=document,!d)throw b.createError(c+"(): Parameter must be a Window object or DOM node");return d}function u(a){for(var b;b=a.parentNode;)a=b;return a}function v(a,c,d,f){var h,i,k,l,m;if(a==d)return c===f?0:f>c?-1:1;if(h=j(d,a,!0))return c<=e(h)?-1:1;if(h=j(a,d,!0))return e(h)<f?-1:1;if(i=g(a,d),!i)throw new Error("comparePoints error: nodes have no common ancestor");if(k=a===i?i:j(a,i,!0),l=d===i?i:j(d,i,!0),k===l)throw b.createError("comparePoints got to case 4 and childA and childB are the same!");for(m=i.firstChild;m;){if(m===k)return-1;if(m===l)return 1;m=m.nextSibling}}function w(a){var b;try{return b=a.parentNode,!1}catch(c){return!0}}function x(a){if(!a)return"[No node]";if(L&&w(a))return"[Broken node]";if(k(a))return'"'+a.data+'"';if(1==a.nodeType){var b=a.id?' id="'+a.id+'"':"";return"<"+a.nodeName+b+">[index:"+e(a)+",length:"+a.childNodes.length+"]["+(a.innerHTML||"[innerHTML not supported]").slice(0,25)+"]"}return a.nodeName}function y(a){for(var b,c=o(a).createDocumentFragment();b=a.firstChild;)c.appendChild(b);return c}function z(a,b,c){var d=H(a),e=a.createElement("div");e.contentEditable=""+!!c,b&&(e.innerHTML=b);var f=d.firstChild;return f?d.insertBefore(e,f):d.appendChild(e),e}function A(a){return a.parentNode.removeChild(a)}function B(a){this.root=a,this._next=a}function C(a){return new B(a)}function D(a,b){this.node=a,this.offset=b}function E(a){this.code=this[a],this.codeName=a,this.message="DOMException: "+this.codeName}var F="undefined",G=a.util,H=G.getBody;G.areHostMethods(document,["createDocumentFragment","createElement","createTextNode"])||b.fail("document missing a Node creation method"),G.isHostMethod(document,"getElementsByTagName")||b.fail("document missing getElementsByTagName method");var I=document.createElement("div");G.areHostMethods(I,["insertBefore","appendChild","cloneNode"]||!G.areHostObjects(I,["previousSibling","nextSibling","childNodes","parentNode"]))||b.fail("Incomplete Element implementation"),G.isHostProperty(I,"innerHTML")||b.fail("Element is missing innerHTML property");var J=document.createTextNode("test");G.areHostMethods(J,["splitText","deleteData","insertData","appendData","cloneNode"]||!G.areHostObjects(I,["previousSibling","nextSibling","childNodes","parentNode"])||!G.areHostProperties(J,["data"]))||b.fail("Incomplete Text Node implementation");var K=function(a,b){for(var c=a.length;c--;)if(a[c]===b)return!0;return!1},L=!1;!function(){var b=document.createElement("b");b.innerHTML="1";var c=b.firstChild;b.innerHTML="<br />",L=w(c),a.features.crashyTextNodes=L}();var M;typeof window.getComputedStyle!=F?M=function(a,b){return p(a).getComputedStyle(a,null)[b]}:typeof document.documentElement.currentStyle!=F?M=function(a,b){return a.currentStyle?a.currentStyle[b]:""}:b.fail("No means of obtaining computed style properties found"),B.prototype={_current:null,hasNext:function(){return!!this._next},next:function(){var a,b,c=this._current=this._next;if(this._current)if(a=c.firstChild)this._next=a;else{for(b=null;c!==this.root&&!(b=c.nextSibling);)c=c.parentNode;this._next=b}return this._current},detach:function(){this._current=this._next=this.root=null}},D.prototype={equals:function(a){return!!a&&this.node===a.node&&this.offset==a.offset},inspect:function(){return"[DomPosition("+x(this.node)+":"+this.offset+")]"},toString:function(){return this.inspect()}},E.prototype={INDEX_SIZE_ERR:1,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INVALID_STATE_ERR:11,INVALID_NODE_TYPE_ERR:24},E.prototype.toString=function(){return this.message},a.dom={arrayContains:K,isHtmlNamespace:c,parentElement:d,getNodeIndex:e,getNodeLength:f,getCommonAncestor:g,isAncestorOf:h,isOrIsAncestorOf:i,getClosestAncestorIn:j,isCharacterDataNode:k,isTextOrCommentNode:l,insertAfter:m,splitDataNode:n,getDocument:o,getWindow:p,getIframeWindow:r,getIframeDocument:q,getBody:H,isWindow:s,getContentDocument:t,getRootContainer:u,comparePoints:v,isBrokenNode:w,inspectNode:x,getComputedStyleProperty:M,createTestElement:z,removeNode:A,fragmentFromNodeChildren:y,createIterator:C,DomPosition:D},a.DOMException=E}),H.createCoreModule("DomRange",["DomUtil"],function(a,b){function c(a,b){return 3!=a.nodeType&&(P(a,b.startContainer)||P(a,b.endContainer))}function d(a){return a.document||Q(a.startContainer)}function e(a){return W(a.startContainer)}function f(a){return new L(a.parentNode,O(a))}function g(a){return new L(a.parentNode,O(a)+1)}function h(a,b,c){var d=11==a.nodeType?a.firstChild:a;return N(b)?c==b.length?J.insertAfter(a,b):b.parentNode.insertBefore(a,0==c?b:S(b,c)):c>=b.childNodes.length?b.appendChild(a):b.insertBefore(a,b.childNodes[c]),d}function i(a,b,c){if(z(a),z(b),d(b)!=d(a))throw new M("WRONG_DOCUMENT_ERR");var e=R(a.startContainer,a.startOffset,b.endContainer,b.endOffset),f=R(a.endContainer,a.endOffset,b.startContainer,b.startOffset);return c?0>=e&&f>=0:0>e&&f>0}function j(a){for(var b,c,e,f=d(a.range).createDocumentFragment();c=a.next();){if(b=a.isPartiallySelectedSubtree(),c=c.cloneNode(!b),b&&(e=a.getSubtreeIterator(),c.appendChild(j(e)),e.detach()),10==c.nodeType)throw new M("HIERARCHY_REQUEST_ERR");f.appendChild(c)}return f}function k(a,b,c){var d,e;c=c||{stop:!1};for(var f,g;f=a.next();)if(a.isPartiallySelectedSubtree()){if(b(f)===!1)return void(c.stop=!0);if(g=a.getSubtreeIterator(),k(g,b,c),g.detach(),c.stop)return}else for(d=J.createIterator(f);e=d.next();)if(b(e)===!1)return void(c.stop=!0)}function l(a){for(var b;a.next();)a.isPartiallySelectedSubtree()?(b=a.getSubtreeIterator(),l(b),b.detach()):a.remove()}function m(a){for(var b,c,e=d(a.range).createDocumentFragment();b=a.next();){if(a.isPartiallySelectedSubtree()?(b=b.cloneNode(!1),c=a.getSubtreeIterator(),b.appendChild(m(c)),c.detach()):a.remove(),10==b.nodeType)throw new M("HIERARCHY_REQUEST_ERR");e.appendChild(b)}return e}function n(a,b,c){var d,e=!(!b||!b.length),f=!!c;e&&(d=new RegExp("^("+b.join("|")+")$"));var g=[];return k(new p(a,!1),function(b){if((!e||d.test(b.nodeType))&&(!f||c(b))){var h=a.startContainer;if(b!=h||!N(h)||a.startOffset!=h.length){var i=a.endContainer;b==i&&N(i)&&0==a.endOffset||g.push(b)}}}),g}function o(a){var b="undefined"==typeof a.getName?"Range":a.getName();return"["+b+"("+J.inspectNode(a.startContainer)+":"+a.startOffset+", "+J.inspectNode(a.endContainer)+":"+a.endOffset+")]"}function p(a,b){if(this.range=a,this.clonePartiallySelectedTextNodes=b,!a.collapsed){this.sc=a.startContainer,this.so=a.startOffset,this.ec=a.endContainer,this.eo=a.endOffset;var c=a.commonAncestorContainer;this.sc===this.ec&&N(this.sc)?(this.isSingleCharacterDataNode=!0,this._first=this._last=this._next=this.sc):(this._first=this._next=this.sc!==c||N(this.sc)?T(this.sc,c,!0):this.sc.childNodes[this.so],this._last=this.ec!==c||N(this.ec)?T(this.ec,c,!0):this.ec.childNodes[this.eo-1])}}function q(a){return function(b,c){for(var d,e=c?b:b.parentNode;e;){if(d=e.nodeType,V(a,d))return e;e=e.parentNode}return null}}function r(a,b){if(ea(a,b))throw new M("INVALID_NODE_TYPE_ERR")}function s(a,b){if(!V(b,a.nodeType))throw new M("INVALID_NODE_TYPE_ERR")}function t(a,b){if(0>b||b>(N(a)?a.length:a.childNodes.length))throw new M("INDEX_SIZE_ERR")}function u(a,b){if(ca(a,!0)!==ca(b,!0))throw new M("WRONG_DOCUMENT_ERR")}function v(a){if(da(a,!0))throw new M("NO_MODIFICATION_ALLOWED_ERR")}function w(a,b){if(!a)throw new M(b)}function x(a,b){return b<=(N(a)?a.length:a.childNodes.length)}function y(a){return!!a.startContainer&&!!a.endContainer&&!(X&&(J.isBrokenNode(a.startContainer)||J.isBrokenNode(a.endContainer)))&&W(a.startContainer)==W(a.endContainer)&&x(a.startContainer,a.startOffset)&&x(a.endContainer,a.endOffset)}function z(a){if(!y(a))throw new Error("Range error: Range is not valid. This usually happens after DOM mutation. Range: ("+a.inspect()+")")}function A(a,b){z(a);var c=a.startContainer,d=a.startOffset,e=a.endContainer,f=a.endOffset,g=c===e;N(e)&&f>0&&f<e.length&&S(e,f,b),N(c)&&d>0&&d<c.length&&(c=S(c,d,b),g?(f-=d,e=c):e==c.parentNode&&f>=O(c)&&f++,d=0),a.setStartAndEnd(c,d,e,f)}function B(a){z(a);var b=a.commonAncestorContainer.parentNode.cloneNode(!1);return b.appendChild(a.cloneContents()),b.innerHTML}function C(a){a.START_TO_START=ka,a.START_TO_END=la,a.END_TO_END=ma,a.END_TO_START=na,a.NODE_BEFORE=oa,a.NODE_AFTER=pa,a.NODE_BEFORE_AND_AFTER=qa,a.NODE_INSIDE=ra}function D(a){C(a),C(a.prototype)}function E(a,b){return function(){z(this);var c,d,e=this.startContainer,f=this.startOffset,h=this.commonAncestorContainer,i=new p(this,!0);e!==h&&(c=T(e,h,!0),d=g(c),e=d.node,f=d.offset),k(i,v),i.reset();var j=a(i);return i.detach(),b(this,e,f,e,f),j}}function F(b,d){function e(a,b){return function(c){s(c,Z),s(W(c),$);var d=(a?f:g)(c);(b?h:i)(this,d.node,d.offset)}}function h(a,b,c){var e=a.endContainer,f=a.endOffset;(b!==a.startContainer||c!==a.startOffset)&&((W(b)!=W(e)||1==R(b,c,e,f))&&(e=b,f=c),d(a,b,c,e,f))}function i(a,b,c){var e=a.startContainer,f=a.startOffset;(b!==a.endContainer||c!==a.endOffset)&&((W(b)!=W(e)||-1==R(b,c,e,f))&&(e=b,f=c),d(a,e,f,b,c))}var j=function(){};j.prototype=a.rangePrototype,b.prototype=new j,K.extend(b.prototype,{setStart:function(a,b){r(a,!0),t(a,b),h(this,a,b)},setEnd:function(a,b){r(a,!0),t(a,b),i(this,a,b)},setStartAndEnd:function(){var a=arguments,b=a[0],c=a[1],e=b,f=c;switch(a.length){case 3:f=a[2];break;case 4:e=a[2],f=a[3]}d(this,b,c,e,f)},setBoundary:function(a,b,c){this["set"+(c?"Start":"End")](a,b)},setStartBefore:e(!0,!0),setStartAfter:e(!1,!0),setEndBefore:e(!0,!1),setEndAfter:e(!1,!1),collapse:function(a){z(this),a?d(this,this.startContainer,this.startOffset,this.startContainer,this.startOffset):d(this,this.endContainer,this.endOffset,this.endContainer,this.endOffset)},selectNodeContents:function(a){r(a,!0),d(this,a,0,a,U(a))},selectNode:function(a){r(a,!1),s(a,Z);var b=f(a),c=g(a);d(this,b.node,b.offset,c.node,c.offset)},extractContents:E(m,d),deleteContents:E(l,d),canSurroundContents:function(){z(this),v(this.startContainer),v(this.endContainer);var a=new p(this,!0),b=a._first&&c(a._first,this)||a._last&&c(a._last,this);return a.detach(),!b},splitBoundaries:function(){A(this)},splitBoundariesPreservingPositions:function(a){A(this,a)},normalizeBoundaries:function(){z(this);var a,b=this.startContainer,c=this.startOffset,e=this.endContainer,f=this.endOffset,g=function(a){var b=a.nextSibling;b&&b.nodeType==a.nodeType&&(e=a,f=a.length,a.appendData(b.data),Y(b))},h=function(a){var d=a.previousSibling;if(d&&d.nodeType==a.nodeType){b=a;var g=a.length;if(c=d.length,a.insertData(0,d.data),Y(d),b==e)f+=c,e=b;else if(e==a.parentNode){var h=O(a);f==h?(e=a,f=g):f>h&&f--}}},i=!0;if(N(e))f==e.length?g(e):0==f&&(a=e.previousSibling,a&&a.nodeType==e.nodeType&&(f=a.length,b==e&&(i=!1),a.appendData(e.data),Y(e),e=a));else{if(f>0){var j=e.childNodes[f-1];j&&N(j)&&g(j)}i=!this.collapsed}if(i){if(N(b))0==c?h(b):c==b.length&&(a=b.nextSibling,a&&a.nodeType==b.nodeType&&(e==a&&(e=b,f+=b.length),b.appendData(a.data),Y(a)));else if(c<b.childNodes.length){var k=b.childNodes[c];k&&N(k)&&h(k)}}else b=e,c=f;d(this,b,c,e,f)},collapseToPoint:function(a,b){r(a,!0),t(a,b),this.setStartAndEnd(a,b)}}),D(b)}function G(a){a.collapsed=a.startContainer===a.endContainer&&a.startOffset===a.endOffset,a.commonAncestorContainer=a.collapsed?a.startContainer:J.getCommonAncestor(a.startContainer,a.endContainer)}function H(a,b,c,d,e){a.startContainer=b,a.startOffset=c,a.endContainer=d,a.endOffset=e,a.document=J.getDocument(b),G(a)}function I(a){this.startContainer=a,this.startOffset=0,this.endContainer=a,this.endOffset=0,this.document=a,G(this)}var J=a.dom,K=a.util,L=J.DomPosition,M=a.DOMException,N=J.isCharacterDataNode,O=J.getNodeIndex,P=J.isOrIsAncestorOf,Q=J.getDocument,R=J.comparePoints,S=J.splitDataNode,T=J.getClosestAncestorIn,U=J.getNodeLength,V=J.arrayContains,W=J.getRootContainer,X=a.features.crashyTextNodes,Y=J.removeNode;p.prototype={_current:null,_next:null,_first:null,_last:null,isSingleCharacterDataNode:!1,reset:function(){this._current=null,this._next=this._first},hasNext:function(){return!!this._next},next:function(){var a=this._current=this._next;return a&&(this._next=a!==this._last?a.nextSibling:null,N(a)&&this.clonePartiallySelectedTextNodes&&(a===this.ec&&(a=a.cloneNode(!0)).deleteData(this.eo,a.length-this.eo),this._current===this.sc&&(a=a.cloneNode(!0)).deleteData(0,this.so))),a},remove:function(){var a,b,c=this._current;!N(c)||c!==this.sc&&c!==this.ec?c.parentNode&&Y(c):(a=c===this.sc?this.so:0,b=c===this.ec?this.eo:c.length,a!=b&&c.deleteData(a,b-a))},isPartiallySelectedSubtree:function(){var a=this._current;return c(a,this.range)},getSubtreeIterator:function(){var a;if(this.isSingleCharacterDataNode)a=this.range.cloneRange(),a.collapse(!1);else{a=new I(d(this.range));var b=this._current,c=b,e=0,f=b,g=U(b);P(b,this.sc)&&(c=this.sc,e=this.so),P(b,this.ec)&&(f=this.ec,g=this.eo),H(a,c,e,f,g)}return new p(a,this.clonePartiallySelectedTextNodes)},detach:function(){this.range=this._current=this._next=this._first=this._last=this.sc=this.so=this.ec=this.eo=null}};var Z=[1,3,4,5,7,8,10],$=[2,9,11],_=[5,6,10,12],aa=[1,3,4,5,7,8,10,11],ba=[1,3,4,5,7,8],ca=q([9,11]),da=q(_),ea=q([6,10,12]),fa=document.createElement("style"),ga=!1;try{fa.innerHTML="<b>x</b>",ga=3==fa.firstChild.nodeType}catch(ha){}a.features.htmlParsingConforms=ga;var ia=ga?function(a){var b=this.startContainer,c=Q(b);if(!b)throw new M("INVALID_STATE_ERR");var d=null;return 1==b.nodeType?d=b:N(b)&&(d=J.parentElement(b)),d=null===d||"HTML"==d.nodeName&&J.isHtmlNamespace(Q(d).documentElement)&&J.isHtmlNamespace(d)?c.createElement("body"):d.cloneNode(!1),d.innerHTML=a,J.fragmentFromNodeChildren(d)}:function(a){var b=d(this),c=b.createElement("body");return c.innerHTML=a,J.fragmentFromNodeChildren(c)},ja=["startContainer","startOffset","endContainer","endOffset","collapsed","commonAncestorContainer"],ka=0,la=1,ma=2,na=3,oa=0,pa=1,qa=2,ra=3;K.extend(a.rangePrototype,{compareBoundaryPoints:function(a,b){z(this),u(this.startContainer,b.startContainer);var c,d,e,f,g=a==na||a==ka?"start":"end",h=a==la||a==ka?"start":"end";return c=this[g+"Container"],d=this[g+"Offset"],e=b[h+"Container"],f=b[h+"Offset"],R(c,d,e,f)},insertNode:function(a){if(z(this),s(a,aa),v(this.startContainer),P(a,this.startContainer))throw new M("HIERARCHY_REQUEST_ERR");var b=h(a,this.startContainer,this.startOffset);this.setStartBefore(b)},cloneContents:function(){z(this);var a,b;if(this.collapsed)return d(this).createDocumentFragment();if(this.startContainer===this.endContainer&&N(this.startContainer))return a=this.startContainer.cloneNode(!0),a.data=a.data.slice(this.startOffset,this.endOffset),b=d(this).createDocumentFragment(),b.appendChild(a),b;var c=new p(this,!0);return a=j(c),c.detach(),a},canSurroundContents:function(){z(this),v(this.startContainer),v(this.endContainer);var a=new p(this,!0),b=a._first&&c(a._first,this)||a._last&&c(a._last,this);return a.detach(),!b},surroundContents:function(a){if(s(a,ba),!this.canSurroundContents())throw new M("INVALID_STATE_ERR");var b=this.extractContents();if(a.hasChildNodes())for(;a.lastChild;)a.removeChild(a.lastChild);h(a,this.startContainer,this.startOffset),a.appendChild(b),this.selectNode(a)},cloneRange:function(){z(this);for(var a,b=new I(d(this)),c=ja.length;c--;)a=ja[c],b[a]=this[a];return b},toString:function(){z(this);var a=this.startContainer;if(a===this.endContainer&&N(a))return 3==a.nodeType||4==a.nodeType?a.data.slice(this.startOffset,this.endOffset):"";var b=[],c=new p(this,!0);return k(c,function(a){(3==a.nodeType||4==a.nodeType)&&b.push(a.data)}),c.detach(),b.join("")},compareNode:function(a){z(this);var b=a.parentNode,c=O(a);if(!b)throw new M("NOT_FOUND_ERR");var d=this.comparePoint(b,c),e=this.comparePoint(b,c+1);return 0>d?e>0?qa:oa:e>0?pa:ra},comparePoint:function(a,b){return z(this),w(a,"HIERARCHY_REQUEST_ERR"),u(a,this.startContainer),R(a,b,this.startContainer,this.startOffset)<0?-1:R(a,b,this.endContainer,this.endOffset)>0?1:0},createContextualFragment:ia,toHtml:function(){return B(this)},intersectsNode:function(a,b){if(z(this),W(a)!=e(this))return!1;var c=a.parentNode,d=O(a);if(!c)return!0;var f=R(c,d,this.endContainer,this.endOffset),g=R(c,d+1,this.startContainer,this.startOffset);return b?0>=f&&g>=0:0>f&&g>0},isPointInRange:function(a,b){return z(this),w(a,"HIERARCHY_REQUEST_ERR"),u(a,this.startContainer),R(a,b,this.startContainer,this.startOffset)>=0&&R(a,b,this.endContainer,this.endOffset)<=0},intersectsRange:function(a){return i(this,a,!1)},intersectsOrTouchesRange:function(a){return i(this,a,!0)},intersection:function(a){if(this.intersectsRange(a)){var b=R(this.startContainer,this.startOffset,a.startContainer,a.startOffset),c=R(this.endContainer,this.endOffset,a.endContainer,a.endOffset),d=this.cloneRange();return-1==b&&d.setStart(a.startContainer,a.startOffset),1==c&&d.setEnd(a.endContainer,a.endOffset),d}return null},union:function(a){if(this.intersectsOrTouchesRange(a)){var b=this.cloneRange();return-1==R(a.startContainer,a.startOffset,this.startContainer,this.startOffset)&&b.setStart(a.startContainer,a.startOffset),1==R(a.endContainer,a.endOffset,this.endContainer,this.endOffset)&&b.setEnd(a.endContainer,a.endOffset),b}throw new M("Ranges do not intersect")},containsNode:function(a,b){return b?this.intersectsNode(a,!1):this.compareNode(a)==ra},containsNodeContents:function(a){return this.comparePoint(a,0)>=0&&this.comparePoint(a,U(a))<=0},containsRange:function(a){var b=this.intersection(a);return null!==b&&a.equals(b)},containsNodeText:function(a){var b=this.cloneRange();b.selectNode(a);var c=b.getNodes([3]);if(c.length>0){b.setStart(c[0],0);var d=c.pop();return b.setEnd(d,d.length),this.containsRange(b)}return this.containsNodeContents(a)},getNodes:function(a,b){return z(this),n(this,a,b)},getDocument:function(){return d(this)},collapseBefore:function(a){this.setEndBefore(a),this.collapse(!1)},collapseAfter:function(a){this.setStartAfter(a),this.collapse(!0)},getBookmark:function(b){var c=d(this),e=a.createRange(c);b=b||J.getBody(c),e.selectNodeContents(b);var f=this.intersection(e),g=0,h=0;return f&&(e.setEnd(f.startContainer,f.startOffset),g=e.toString().length,h=g+f.toString().length),{start:g,end:h,containerNode:b}},moveToBookmark:function(a){var b=a.containerNode,c=0;this.setStart(b,0),this.collapse(!0);for(var d,e,f,g,h=[b],i=!1,j=!1;!j&&(d=h.pop());)if(3==d.nodeType)e=c+d.length,!i&&a.start>=c&&a.start<=e&&(this.setStart(d,a.start-c),i=!0),i&&a.end>=c&&a.end<=e&&(this.setEnd(d,a.end-c),j=!0),c=e;else for(g=d.childNodes,f=g.length;f--;)h.push(g[f])},getName:function(){return"DomRange"},equals:function(a){return I.rangesEqual(this,a)},isValid:function(){return y(this)},inspect:function(){return o(this)},detach:function(){}}),F(I,H),K.extend(I,{rangeProperties:ja,RangeIterator:p,copyComparisonConstants:D,createPrototypeRange:F,inspect:o,toHtml:B,getRangeDocument:d,rangesEqual:function(a,b){return a.startContainer===b.startContainer&&a.startOffset===b.startOffset&&a.endContainer===b.endContainer&&a.endOffset===b.endOffset}}),a.DomRange=I}),H.createCoreModule("WrappedRange",["DomRange"],function(a,b){var c,d,e=a.dom,f=a.util,g=e.DomPosition,h=a.DomRange,i=e.getBody,j=e.getContentDocument,k=e.isCharacterDataNode;if(a.features.implementsDomRange&&!function(){function d(a){for(var b,c=m.length;c--;)b=m[c],a[b]=a.nativeRange[b];a.collapsed=a.startContainer===a.endContainer&&a.startOffset===a.endOffset}function g(a,b,c,d,e){var f=a.startContainer!==b||a.startOffset!=c,g=a.endContainer!==d||a.endOffset!=e,h=!a.equals(a.nativeRange);(f||g||h)&&(a.setEnd(d,e),a.setStart(b,c))}var k,l,m=h.rangeProperties;c=function(a){if(!a)throw b.createError("WrappedRange: Range must be specified");this.nativeRange=a,d(this)},h.createPrototypeRange(c,g),k=c.prototype,k.selectNode=function(a){this.nativeRange.selectNode(a),d(this)},k.cloneContents=function(){return this.nativeRange.cloneContents()},k.surroundContents=function(a){this.nativeRange.surroundContents(a),d(this)},k.collapse=function(a){this.nativeRange.collapse(a),d(this)},k.cloneRange=function(){return new c(this.nativeRange.cloneRange())},k.refresh=function(){d(this)},k.toString=function(){return this.nativeRange.toString()};var n=document.createTextNode("test");i(document).appendChild(n);var o=document.createRange();o.setStart(n,0),o.setEnd(n,0);try{o.setStart(n,1),k.setStart=function(a,b){this.nativeRange.setStart(a,b),d(this)},k.setEnd=function(a,b){this.nativeRange.setEnd(a,b),d(this)},l=function(a){return function(b){this.nativeRange[a](b),d(this)}}}catch(p){k.setStart=function(a,b){try{this.nativeRange.setStart(a,b)}catch(c){this.nativeRange.setEnd(a,b),this.nativeRange.setStart(a,b)}d(this)},k.setEnd=function(a,b){try{this.nativeRange.setEnd(a,b)}catch(c){this.nativeRange.setStart(a,b),this.nativeRange.setEnd(a,b)}d(this)},l=function(a,b){return function(c){try{this.nativeRange[a](c)}catch(e){this.nativeRange[b](c),this.nativeRange[a](c)}d(this)}}}k.setStartBefore=l("setStartBefore","setEndBefore"),k.setStartAfter=l("setStartAfter","setEndAfter"),k.setEndBefore=l("setEndBefore","setStartBefore"),k.setEndAfter=l("setEndAfter","setStartAfter"),k.selectNodeContents=function(a){this.setStartAndEnd(a,0,e.getNodeLength(a))},o.selectNodeContents(n),o.setEnd(n,3);var q=document.createRange();q.selectNodeContents(n),q.setEnd(n,4),q.setStart(n,2),-1==o.compareBoundaryPoints(o.START_TO_END,q)&&1==o.compareBoundaryPoints(o.END_TO_START,q)?k.compareBoundaryPoints=function(a,b){return b=b.nativeRange||b,a==b.START_TO_END?a=b.END_TO_START:a==b.END_TO_START&&(a=b.START_TO_END),this.nativeRange.compareBoundaryPoints(a,b)}:k.compareBoundaryPoints=function(a,b){return this.nativeRange.compareBoundaryPoints(a,b.nativeRange||b)};var r=document.createElement("div");r.innerHTML="123";var s=r.firstChild,t=i(document);t.appendChild(r),o.setStart(s,1),o.setEnd(s,2),o.deleteContents(),"13"==s.data&&(k.deleteContents=function(){this.nativeRange.deleteContents(),d(this)},k.extractContents=function(){var a=this.nativeRange.extractContents();return d(this),a}),t.removeChild(r),t=null,f.isHostMethod(o,"createContextualFragment")&&(k.createContextualFragment=function(a){return this.nativeRange.createContextualFragment(a)}),i(document).removeChild(n),k.getName=function(){return"WrappedRange"},a.WrappedRange=c,a.createNativeRange=function(a){return a=j(a,b,"createNativeRange"),a.createRange()}}(),a.features.implementsTextRange){var l=function(a){var b=a.parentElement(),c=a.duplicate();c.collapse(!0);var d=c.parentElement();c=a.duplicate(),c.collapse(!1);var f=c.parentElement(),g=d==f?d:e.getCommonAncestor(d,f);return g==b?g:e.getCommonAncestor(b,g)},m=function(a){return 0==a.compareEndPoints("StartToEnd",a)},n=function(a,b,c,d,f){var h=a.duplicate();h.collapse(c);var i=h.parentElement();if(e.isOrIsAncestorOf(b,i)||(i=b),!i.canHaveHTML){var j=new g(i.parentNode,e.getNodeIndex(i));return{boundaryPosition:j,nodeInfo:{nodeIndex:j.offset,containerElement:j.node}}}var l=e.getDocument(i).createElement("span");l.parentNode&&e.removeNode(l);for(var m,n,o,p,q,r=c?"StartToStart":"StartToEnd",s=f&&f.containerElement==i?f.nodeIndex:0,t=i.childNodes.length,u=t,v=u;;){if(v==t?i.appendChild(l):i.insertBefore(l,i.childNodes[v]),h.moveToElementText(l),m=h.compareEndPoints(r,a),0==m||s==u)break;if(-1==m){if(u==s+1)break;s=v}else u=u==s+1?s:v;v=Math.floor((s+u)/2),i.removeChild(l)}if(q=l.nextSibling,-1==m&&q&&k(q)){h.setEndPoint(c?"EndToStart":"EndToEnd",a);var w;if(/[\r\n]/.test(q.data)){var x=h.duplicate(),y=x.text.replace(/\r\n/g,"\r").length;for(w=x.moveStart("character",y);-1==(m=x.compareEndPoints("StartToEnd",x));)w++,x.moveStart("character",1)}else w=h.text.length;p=new g(q,w)}else n=(d||!c)&&l.previousSibling,o=(d||c)&&l.nextSibling,p=o&&k(o)?new g(o,0):n&&k(n)?new g(n,n.data.length):new g(i,e.getNodeIndex(l));return e.removeNode(l),{boundaryPosition:p,nodeInfo:{nodeIndex:v,containerElement:i}}},o=function(a,b){var c,d,f,g,h=a.offset,j=e.getDocument(a.node),l=i(j).createTextRange(),m=k(a.node);return m?(c=a.node,d=c.parentNode):(g=a.node.childNodes,c=h<g.length?g[h]:null,d=a.node),f=j.createElement("span"),f.innerHTML="&#feff;",c?d.insertBefore(f,c):d.appendChild(f),l.moveToElementText(f),l.collapse(!b),d.removeChild(f),m&&l[b?"moveStart":"moveEnd"]("character",h),l};d=function(a){this.textRange=a,this.refresh()},d.prototype=new h(document),
d.prototype.refresh=function(){var a,b,c,d=l(this.textRange);m(this.textRange)?b=a=n(this.textRange,d,!0,!0).boundaryPosition:(c=n(this.textRange,d,!0,!1),a=c.boundaryPosition,b=n(this.textRange,d,!1,!1,c.nodeInfo).boundaryPosition),this.setStart(a.node,a.offset),this.setEnd(b.node,b.offset)},d.prototype.getName=function(){return"WrappedTextRange"},h.copyComparisonConstants(d);var p=function(a){if(a.collapsed)return o(new g(a.startContainer,a.startOffset),!0);var b=o(new g(a.startContainer,a.startOffset),!0),c=o(new g(a.endContainer,a.endOffset),!1),d=i(h.getRangeDocument(a)).createTextRange();return d.setEndPoint("StartToStart",b),d.setEndPoint("EndToEnd",c),d};if(d.rangeToTextRange=p,d.prototype.toTextRange=function(){return p(this)},a.WrappedTextRange=d,!a.features.implementsDomRange||a.config.preferTextRange){var q=function(a){return a("return this;")()}(Function);"undefined"==typeof q.Range&&(q.Range=d),a.createNativeRange=function(a){return a=j(a,b,"createNativeRange"),i(a).createTextRange()},a.WrappedRange=d}}a.createRange=function(c){return c=j(c,b,"createRange"),new a.WrappedRange(a.createNativeRange(c))},a.createRangyRange=function(a){return a=j(a,b,"createRangyRange"),new h(a)},f.createAliasForDeprecatedMethod(a,"createIframeRange","createRange"),f.createAliasForDeprecatedMethod(a,"createIframeRangyRange","createRangyRange"),a.addShimListener(function(b){var c=b.document;"undefined"==typeof c.createRange&&(c.createRange=function(){return a.createRange(c)}),c=b=null})}),H.createCoreModule("WrappedSelection",["DomRange","WrappedRange"],function(a,b){function c(a){return"string"==typeof a?/^backward(s)?$/i.test(a):!!a}function d(a,c){if(a){if(C.isWindow(a))return a;if(a instanceof r)return a.win;var d=C.getContentDocument(a,b,c);return C.getWindow(d)}return window}function e(a){return d(a,"getWinSelection").getSelection()}function f(a){return d(a,"getDocSelection").document.selection}function g(a){var b=!1;return a.anchorNode&&(b=1==C.comparePoints(a.anchorNode,a.anchorOffset,a.focusNode,a.focusOffset)),b}function h(a,b,c){var d=c?"end":"start",e=c?"start":"end";a.anchorNode=b[d+"Container"],a.anchorOffset=b[d+"Offset"],a.focusNode=b[e+"Container"],a.focusOffset=b[e+"Offset"]}function i(a){var b=a.nativeSelection;a.anchorNode=b.anchorNode,a.anchorOffset=b.anchorOffset,a.focusNode=b.focusNode,a.focusOffset=b.focusOffset}function j(a){a.anchorNode=a.focusNode=null,a.anchorOffset=a.focusOffset=0,a.rangeCount=0,a.isCollapsed=!0,a._ranges.length=0}function k(b){var c;return b instanceof F?(c=a.createNativeRange(b.getDocument()),c.setEnd(b.endContainer,b.endOffset),c.setStart(b.startContainer,b.startOffset)):b instanceof G?c=b.nativeRange:J.implementsDomRange&&b instanceof C.getWindow(b.startContainer).Range&&(c=b),c}function l(a){if(!a.length||1!=a[0].nodeType)return!1;for(var b=1,c=a.length;c>b;++b)if(!C.isAncestorOf(a[0],a[b]))return!1;return!0}function m(a){var c=a.getNodes();if(!l(c))throw b.createError("getSingleElementFromRange: range "+a.inspect()+" did not consist of a single element");return c[0]}function n(a){return!!a&&"undefined"!=typeof a.text}function o(a,b){var c=new G(b);a._ranges=[c],h(a,c,!1),a.rangeCount=1,a.isCollapsed=c.collapsed}function p(b){if(b._ranges.length=0,"None"==b.docSelection.type)j(b);else{var c=b.docSelection.createRange();if(n(c))o(b,c);else{b.rangeCount=c.length;for(var d,e=L(c.item(0)),f=0;f<b.rangeCount;++f)d=a.createRange(e),d.selectNode(c.item(f)),b._ranges.push(d);b.isCollapsed=1==b.rangeCount&&b._ranges[0].collapsed,h(b,b._ranges[b.rangeCount-1],!1)}}}function q(a,c){for(var d=a.docSelection.createRange(),e=m(c),f=L(d.item(0)),g=M(f).createControlRange(),h=0,i=d.length;i>h;++h)g.add(d.item(h));try{g.add(e)}catch(j){throw b.createError("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)")}g.select(),p(a)}function r(a,b,c){this.nativeSelection=a,this.docSelection=b,this._ranges=[],this.win=c,this.refresh()}function s(a){a.win=a.anchorNode=a.focusNode=a._ranges=null,a.rangeCount=a.anchorOffset=a.focusOffset=0,a.detached=!0}function t(a,b){for(var c,d,e=ba.length;e--;)if(c=ba[e],d=c.selection,"deleteAll"==b)s(d);else if(c.win==a)return"delete"==b?(ba.splice(e,1),!0):d;return"deleteAll"==b&&(ba.length=0),null}function u(a,c){for(var d,e=L(c[0].startContainer),f=M(e).createControlRange(),g=0,h=c.length;h>g;++g){d=m(c[g]);try{f.add(d)}catch(i){throw b.createError("setRanges(): Element within one of the specified Ranges could not be added to control selection (does it have layout?)")}}f.select(),p(a)}function v(a,b){if(a.win.document!=L(b))throw new H("WRONG_DOCUMENT_ERR")}function w(b){return function(c,d){var e;this.rangeCount?(e=this.getRangeAt(0),e["set"+(b?"Start":"End")](c,d)):(e=a.createRange(this.win.document),e.setStartAndEnd(c,d)),this.setSingleRange(e,this.isBackward())}}function x(a){var b=[],c=new I(a.anchorNode,a.anchorOffset),d=new I(a.focusNode,a.focusOffset),e="function"==typeof a.getName?a.getName():"Selection";if("undefined"!=typeof a.rangeCount)for(var f=0,g=a.rangeCount;g>f;++f)b[f]=F.inspect(a.getRangeAt(f));return"["+e+"(Ranges: "+b.join(", ")+")(anchor: "+c.inspect()+", focus: "+d.inspect()+"]"}a.config.checkSelectionRanges=!0;var y,z,A="boolean",B="number",C=a.dom,D=a.util,E=D.isHostMethod,F=a.DomRange,G=a.WrappedRange,H=a.DOMException,I=C.DomPosition,J=a.features,K="Control",L=C.getDocument,M=C.getBody,N=F.rangesEqual,O=E(window,"getSelection"),P=D.isHostObject(document,"selection");J.implementsWinGetSelection=O,J.implementsDocSelection=P;var Q=P&&(!O||a.config.preferTextRange);if(Q)y=f,a.isSelectionValid=function(a){var b=d(a,"isSelectionValid").document,c=b.selection;return"None"!=c.type||L(c.createRange().parentElement())==b};else{if(!O)return b.fail("Neither document.selection or window.getSelection() detected."),!1;y=e,a.isSelectionValid=function(){return!0}}a.getNativeSelection=y;var R=y();if(!R)return b.fail("Native selection was null (possibly issue 138?)"),!1;var S=a.createNativeRange(document),T=M(document),U=D.areHostProperties(R,["anchorNode","focusNode","anchorOffset","focusOffset"]);J.selectionHasAnchorAndFocus=U;var V=E(R,"extend");J.selectionHasExtend=V;var W=typeof R.rangeCount==B;J.selectionHasRangeCount=W;var X=!1,Y=!0,Z=V?function(b,c){var d=F.getRangeDocument(c),e=a.createRange(d);e.collapseToPoint(c.endContainer,c.endOffset),b.addRange(k(e)),b.extend(c.startContainer,c.startOffset)}:null;D.areHostMethods(R,["addRange","getRangeAt","removeAllRanges"])&&typeof R.rangeCount==B&&J.implementsDomRange&&!function(){var b=window.getSelection();if(b){for(var c=b.rangeCount,d=c>1,e=[],f=g(b),h=0;c>h;++h)e[h]=b.getRangeAt(h);var i=C.createTestElement(document,"",!1),j=i.appendChild(document.createTextNode(" ")),k=document.createRange();if(k.setStart(j,1),k.collapse(!0),b.removeAllRanges(),b.addRange(k),Y=1==b.rangeCount,b.removeAllRanges(),!d){var l=window.navigator.appVersion.match(/Chrome\/(.*?) /);if(l&&parseInt(l[1])>=36)X=!1;else{var m=k.cloneRange();k.setStart(j,0),m.setEnd(j,3),m.setStart(j,2),b.addRange(k),b.addRange(m),X=2==b.rangeCount}}for(C.removeNode(i),b.removeAllRanges(),h=0;c>h;++h)0==h&&f?Z?Z(b,e[h]):(a.warn("Rangy initialization: original selection was backwards but selection has been restored forwards because the browser does not support Selection.extend"),b.addRange(e[h])):b.addRange(e[h])}}(),J.selectionSupportsMultipleRanges=X,J.collapsedNonEditableSelectionsSupported=Y;var $,_=!1;T&&E(T,"createControlRange")&&($=T.createControlRange(),D.areHostProperties($,["item","add"])&&(_=!0)),J.implementsControlRange=_,z=U?function(a){return a.anchorNode===a.focusNode&&a.anchorOffset===a.focusOffset}:function(a){return a.rangeCount?a.getRangeAt(a.rangeCount-1).collapsed:!1};var aa;E(R,"getRangeAt")?aa=function(a,b){try{return a.getRangeAt(b)}catch(c){return null}}:U&&(aa=function(b){var c=L(b.anchorNode),d=a.createRange(c);return d.setStartAndEnd(b.anchorNode,b.anchorOffset,b.focusNode,b.focusOffset),d.collapsed!==this.isCollapsed&&d.setStartAndEnd(b.focusNode,b.focusOffset,b.anchorNode,b.anchorOffset),d}),r.prototype=a.selectionPrototype;var ba=[],ca=function(a){if(a&&a instanceof r)return a.refresh(),a;a=d(a,"getNativeSelection");var b=t(a),c=y(a),e=P?f(a):null;return b?(b.nativeSelection=c,b.docSelection=e,b.refresh()):(b=new r(c,e,a),ba.push({win:a,selection:b})),b};a.getSelection=ca,D.createAliasForDeprecatedMethod(a,"getIframeSelection","getSelection");var da=r.prototype;if(!Q&&U&&D.areHostMethods(R,["removeAllRanges","addRange"])){da.removeAllRanges=function(){this.nativeSelection.removeAllRanges(),j(this)};var ea=function(a,b){Z(a.nativeSelection,b),a.refresh()};W?da.addRange=function(b,d){if(_&&P&&this.docSelection.type==K)q(this,b);else if(c(d)&&V)ea(this,b);else{var e;X?e=this.rangeCount:(this.removeAllRanges(),e=0);var f=k(b).cloneRange();try{this.nativeSelection.addRange(f)}catch(g){}if(this.rangeCount=this.nativeSelection.rangeCount,this.rangeCount==e+1){if(a.config.checkSelectionRanges){var i=aa(this.nativeSelection,this.rangeCount-1);i&&!N(i,b)&&(b=new G(i))}this._ranges[this.rangeCount-1]=b,h(this,b,ha(this.nativeSelection)),this.isCollapsed=z(this)}else this.refresh()}}:da.addRange=function(a,b){c(b)&&V?ea(this,a):(this.nativeSelection.addRange(k(a)),this.refresh())},da.setRanges=function(a){if(_&&P&&a.length>1)u(this,a);else{this.removeAllRanges();for(var b=0,c=a.length;c>b;++b)this.addRange(a[b])}}}else{if(!(E(R,"empty")&&E(S,"select")&&_&&Q))return b.fail("No means of selecting a Range or TextRange was found"),!1;da.removeAllRanges=function(){try{if(this.docSelection.empty(),"None"!=this.docSelection.type){var a;if(this.anchorNode)a=L(this.anchorNode);else if(this.docSelection.type==K){var b=this.docSelection.createRange();b.length&&(a=L(b.item(0)))}if(a){var c=M(a).createTextRange();c.select(),this.docSelection.empty()}}}catch(d){}j(this)},da.addRange=function(b){this.docSelection.type==K?q(this,b):(a.WrappedTextRange.rangeToTextRange(b).select(),this._ranges[0]=b,this.rangeCount=1,this.isCollapsed=this._ranges[0].collapsed,h(this,b,!1))},da.setRanges=function(a){this.removeAllRanges();var b=a.length;b>1?u(this,a):b&&this.addRange(a[0])}}da.getRangeAt=function(a){if(0>a||a>=this.rangeCount)throw new H("INDEX_SIZE_ERR");return this._ranges[a].cloneRange()};var fa;if(Q)fa=function(b){var c;a.isSelectionValid(b.win)?c=b.docSelection.createRange():(c=M(b.win.document).createTextRange(),c.collapse(!0)),b.docSelection.type==K?p(b):n(c)?o(b,c):j(b)};else if(E(R,"getRangeAt")&&typeof R.rangeCount==B)fa=function(b){if(_&&P&&b.docSelection.type==K)p(b);else if(b._ranges.length=b.rangeCount=b.nativeSelection.rangeCount,b.rangeCount){for(var c=0,d=b.rangeCount;d>c;++c)b._ranges[c]=new a.WrappedRange(b.nativeSelection.getRangeAt(c));h(b,b._ranges[b.rangeCount-1],ha(b.nativeSelection)),b.isCollapsed=z(b)}else j(b)};else{if(!U||typeof R.isCollapsed!=A||typeof S.collapsed!=A||!J.implementsDomRange)return b.fail("No means of obtaining a Range or TextRange from the user's selection was found"),!1;fa=function(a){var b,c=a.nativeSelection;c.anchorNode?(b=aa(c,0),a._ranges=[b],a.rangeCount=1,i(a),a.isCollapsed=z(a)):j(a)}}da.refresh=function(a){var b=a?this._ranges.slice(0):null,c=this.anchorNode,d=this.anchorOffset;if(fa(this),a){var e=b.length;if(e!=this._ranges.length)return!0;if(this.anchorNode!=c||this.anchorOffset!=d)return!0;for(;e--;)if(!N(b[e],this._ranges[e]))return!0;return!1}};var ga=function(a,b){var c=a.getAllRanges();a.removeAllRanges();for(var d=0,e=c.length;e>d;++d)N(b,c[d])||a.addRange(c[d]);a.rangeCount||j(a)};_&&P?da.removeRange=function(a){if(this.docSelection.type==K){for(var b,c=this.docSelection.createRange(),d=m(a),e=L(c.item(0)),f=M(e).createControlRange(),g=!1,h=0,i=c.length;i>h;++h)b=c.item(h),b!==d||g?f.add(c.item(h)):g=!0;f.select(),p(this)}else ga(this,a)}:da.removeRange=function(a){ga(this,a)};var ha;!Q&&U&&J.implementsDomRange?(ha=g,da.isBackward=function(){return ha(this)}):ha=da.isBackward=function(){return!1},da.isBackwards=da.isBackward,da.toString=function(){for(var a=[],b=0,c=this.rangeCount;c>b;++b)a[b]=""+this._ranges[b];return a.join("")},da.collapse=function(b,c){v(this,b);var d=a.createRange(b);d.collapseToPoint(b,c),this.setSingleRange(d),this.isCollapsed=!0},da.collapseToStart=function(){if(!this.rangeCount)throw new H("INVALID_STATE_ERR");var a=this._ranges[0];this.collapse(a.startContainer,a.startOffset)},da.collapseToEnd=function(){if(!this.rangeCount)throw new H("INVALID_STATE_ERR");var a=this._ranges[this.rangeCount-1];this.collapse(a.endContainer,a.endOffset)},da.selectAllChildren=function(b){v(this,b);var c=a.createRange(b);c.selectNodeContents(b),this.setSingleRange(c)},da.deleteFromDocument=function(){if(_&&P&&this.docSelection.type==K){for(var a,b=this.docSelection.createRange();b.length;)a=b.item(0),b.remove(a),C.removeNode(a);this.refresh()}else if(this.rangeCount){var c=this.getAllRanges();if(c.length){this.removeAllRanges();for(var d=0,e=c.length;e>d;++d)c[d].deleteContents();this.addRange(c[e-1])}}},da.eachRange=function(a,b){for(var c=0,d=this._ranges.length;d>c;++c)if(a(this.getRangeAt(c)))return b},da.getAllRanges=function(){var a=[];return this.eachRange(function(b){a.push(b)}),a},da.setSingleRange=function(a,b){this.removeAllRanges(),this.addRange(a,b)},da.callMethodOnEachRange=function(a,b){var c=[];return this.eachRange(function(d){c.push(d[a].apply(d,b||[]))}),c},da.setStart=w(!0),da.setEnd=w(!1),a.rangePrototype.select=function(a){ca(this.getDocument()).setSingleRange(this,a)},da.changeEachRange=function(a){var b=[],c=this.isBackward();this.eachRange(function(c){a(c),b.push(c)}),this.removeAllRanges(),c&&1==b.length?this.addRange(b[0],"backward"):this.setRanges(b)},da.containsNode=function(a,b){return this.eachRange(function(c){return c.containsNode(a,b)},!0)||!1},da.getBookmark=function(a){return{backward:this.isBackward(),rangeBookmarks:this.callMethodOnEachRange("getBookmark",[a])}},da.moveToBookmark=function(b){for(var c,d,e=[],f=0;c=b.rangeBookmarks[f++];)d=a.createRange(this.win),d.moveToBookmark(c),e.push(d);b.backward?this.setSingleRange(e[0],"backward"):this.setRanges(e)},da.saveRanges=function(){return{backward:this.isBackward(),ranges:this.callMethodOnEachRange("cloneRange")}},da.restoreRanges=function(a){this.removeAllRanges();for(var b,c=0;b=a.ranges[c];++c)this.addRange(b,a.backward&&0==c)},da.toHtml=function(){var a=[];return this.eachRange(function(b){a.push(F.toHtml(b))}),a.join("")},J.implementsTextRange&&(da.getNativeTextRange=function(){var c;if(c=this.docSelection){var d=c.createRange();if(n(d))return d;throw b.createError("getNativeTextRange: selection is a control selection")}if(this.rangeCount>0)return a.WrappedTextRange.rangeToTextRange(this.getRangeAt(0));throw b.createError("getNativeTextRange: selection contains no range")}),da.getName=function(){return"WrappedSelection"},da.inspect=function(){return x(this)},da.detach=function(){t(this.win,"delete"),s(this)},r.detachAll=function(){t(null,"deleteAll")},r.inspect=x,r.isDirectionBackward=c,a.Selection=r,a.selectionPrototype=da,a.addShimListener(function(a){"undefined"==typeof a.getSelection&&(a.getSelection=function(){return ca(a)}),a=null})});var M=!1,N=function(a){M||(M=!0,!H.initialized&&H.config.autoInitialize&&l())};return F&&("complete"==document.readyState?N():(a(document,"addEventListener")&&document.addEventListener("DOMContentLoaded",N,!1),J(window,"load",N))),H},this),function(b,c){"function"==typeof define&&define.amd?define(["./rangy-core"],b):"undefined"!=typeof module&&"object"==typeof a?module.exports=b(require("rangy")):b(c.rangy)}(function(a){return a.createModule("SaveRestore",["WrappedRange"],function(a,b){function c(a,b){return(b||document).getElementById(a)}function d(a,b){var c,d="selectionBoundary_"+ +new Date+"_"+(""+Math.random()).slice(2),e=o.getDocument(a.startContainer),f=a.cloneRange();return f.collapse(b),c=e.createElement("span"),c.id=d,c.style.lineHeight="0",c.style.display="none",c.className="rangySelectionBoundary",c.appendChild(e.createTextNode(r)),f.insertNode(c),c}function e(a,d,e,f){var g=c(e,a);g?(d[f?"setStartBefore":"setEndBefore"](g),p(g)):b.warn("Marker element has been removed. Cannot restore selection.")}function f(a,b){return b.compareBoundaryPoints(a.START_TO_START,a)}function g(b,c){var e,f,g=a.DomRange.getRangeDocument(b),h=b.toString(),i=q(c);return b.collapsed?(f=d(b,!1),{document:g,markerId:f.id,collapsed:!0}):(f=d(b,!1),e=d(b,!0),{document:g,startMarkerId:e.id,endMarkerId:f.id,collapsed:!1,backward:i,toString:function(){return"original text: '"+h+"', new text: '"+b.toString()+"'"}})}function h(d,f){var g=d.document;"undefined"==typeof f&&(f=!0);var h=a.createRange(g);if(d.collapsed){var i=c(d.markerId,g);if(i){i.style.display="inline";var j=i.previousSibling;j&&3==j.nodeType?(p(i),h.collapseToPoint(j,j.length)):(h.collapseBefore(i),p(i))}else b.warn("Marker element has been removed. Cannot restore selection.")}else e(g,h,d.startMarkerId,!0),e(g,h,d.endMarkerId,!1);return f&&h.normalizeBoundaries(),h}function i(b,d){var e,h,i=[],j=q(d);b=b.slice(0),b.sort(f);for(var k=0,l=b.length;l>k;++k)i[k]=g(b[k],j);for(k=l-1;k>=0;--k)e=b[k],h=a.DomRange.getRangeDocument(e),e.collapsed?e.collapseAfter(c(i[k].markerId,h)):(e.setEndBefore(c(i[k].endMarkerId,h)),e.setStartAfter(c(i[k].startMarkerId,h)));return i}function j(c){if(!a.isSelectionValid(c))return b.warn("Cannot save selection. This usually happens when the selection is collapsed and the selection document has lost focus."),null;var d=a.getSelection(c),e=d.getAllRanges(),f=1==e.length&&d.isBackward(),g=i(e,f);return f?d.setSingleRange(e[0],f):d.setRanges(e),{win:c,rangeInfos:g,restored:!1}}function k(a){for(var b=[],c=a.length,d=c-1;d>=0;d--)b[d]=h(a[d],!0);return b}function l(b,c){if(!b.restored){var d=b.rangeInfos,e=a.getSelection(b.win),f=k(d),g=d.length;1==g&&c&&a.features.selectionHasExtend&&d[0].backward?(e.removeAllRanges(),e.addRange(f[0],!0)):e.setRanges(f),b.restored=!0}}function m(a,b){var d=c(b,a);d&&p(d)}function n(a){for(var b,c=a.rangeInfos,d=0,e=c.length;e>d;++d)b=c[d],b.collapsed?m(a.doc,b.markerId):(m(a.doc,b.startMarkerId),m(a.doc,b.endMarkerId))}var o=a.dom,p=o.removeNode,q=a.Selection.isDirectionBackward,r="\ufeff";a.util.extend(a,{saveRange:g,restoreRange:h,saveRanges:i,restoreRanges:k,saveSelection:j,restoreSelection:l,removeMarkerElement:m,removeMarkers:n})}),a},this)}({},function(){return this}());/**
* @license AngularJS v1.3.10
* (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {'use strict';
var $sanitizeMinErr = angular.$$minErr('$sanitize');
/**
* @ngdoc module
* @name ngSanitize
* @description
*
* # ngSanitize
*
* The `ngSanitize` module provides functionality to sanitize HTML.
*
*
* <div doc-module-components="ngSanitize"></div>
*
* See {@link ngSanitize.$sanitize `$sanitize`} for usage.
*/
/*
* HTML Parser By Misko Hevery (misko@hevery.com)
* based on: HTML Parser By John Resig (ejohn.org)
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*
* // Use like so:
* htmlParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
*/
/**
* @ngdoc service
* @name $sanitize
* @kind function
*
* @description
* The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are
* then serialized back to properly escaped html string. This means that no unsafe input can make
* it into the returned string, however, since our parser is more strict than a typical browser
* parser, it's possible that some obscure input, which would be recognized as valid HTML by a
* browser, won't make it through the sanitizer. The input may also contain SVG markup.
* The whitelist is configured using the functions `aHrefSanitizationWhitelist` and
* `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}.
*
* @param {string} html HTML input.
* @returns {string} Sanitized HTML.
*
* @example
<example module="sanitizeExample" deps="angular-sanitize.js">
<file name="index.html">
<script>
angular.module('sanitizeExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
$scope.snippet =
'<p style="color:blue">an html\n' +
'<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
'snippet</p>';
$scope.deliberatelyTrustDangerousSnippet = function() {
return $sce.trustAsHtml($scope.snippet);
};
}]);
</script>
<div ng-controller="ExampleController">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<td>Directive</td>
<td>How</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="bind-html-with-sanitize">
<td>ng-bind-html</td>
<td>Automatically uses $sanitize</td>
<td><pre><div ng-bind-html="snippet"><br/></div></pre></td>
<td><div ng-bind-html="snippet"></div></td>
</tr>
<tr id="bind-html-with-trust">
<td>ng-bind-html</td>
<td>Bypass $sanitize by explicitly trusting the dangerous value</td>
<td>
<pre><div ng-bind-html="deliberatelyTrustDangerousSnippet()">
</div></pre>
</td>
<td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
</tr>
<tr id="bind-default">
<td>ng-bind</td>
<td>Automatically escapes</td>
<td><pre><div ng-bind="snippet"><br/></div></pre></td>
<td><div ng-bind="snippet"></div></td>
</tr>
</table>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should sanitize the html snippet by default', function() {
expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
});
it('should inline raw snippet if bound to a trusted value', function() {
expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should escape snippet without any filter', function() {
expect(element(by.css('#bind-default div')).getInnerHtml()).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should update', function() {
element(by.model('snippet')).clear();
element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
toBe('new <b>text</b>');
expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(
'new <b onclick="alert(1)">text</b>');
expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(
"new <b onclick=\"alert(1)\">text</b>");
});
</file>
</example>
*/
function $SanitizeProvider() {
this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
return function(html) {
if (typeof arguments[1] != 'undefined') {
arguments[1].version = 'taSanitize';
}
var buf = [];
htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
return !/^unsafe/.test($$sanitizeUri(uri, isImage));
}));
return buf.join('');
};
}];
}
function sanitizeText(chars) {
var buf = [];
var writer = htmlSanitizeWriter(buf, angular.noop);
writer.chars(chars);
return buf.join('');
}
// Regular Expressions for parsing tags and attributes
var START_TAG_REGEXP =
/^<((?:[a-zA-Z])[\w:-]*)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*(>?)/,
END_TAG_REGEXP = /^<\/\s*([\w:-]+)[^>]*>/,
ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,
BEGIN_TAG_REGEXP = /^</,
BEGING_END_TAGE_REGEXP = /^<\//,
COMMENT_REGEXP = /<!--(.*?)-->/g,
SINGLE_COMMENT_REGEXP = /(^<!--.*?-->)/,
DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i,
CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g,
SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
// Match everything outside of normal chars and " (quote character)
NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g,
WHITE_SPACE_REGEXP = /^(\s+)/;
// Good source of info about elements and attributes
// http://dev.w3.org/html5/spec/Overview.html#semantics
// http://simon.html5.org/html-elements
// Safe Void Elements - HTML5
// http://dev.w3.org/html5/spec/Overview.html#void-elements
var voidElements = makeMap("area,br,col,hr,img,wbr,input");
// Elements that you can, intentionally, leave open (and which close themselves)
// http://dev.w3.org/html5/spec/Overview.html#optional-tags
var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),
optionalEndTagInlineElements = makeMap("rp,rt"),
optionalEndTagElements = angular.extend({},
optionalEndTagInlineElements,
optionalEndTagBlockElements);
// Safe Block Elements - HTML5
var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," +
"aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," +
"h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul"));
// Inline Elements - HTML5
var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," +
"bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," +
"samp,small,span,strike,strong,sub,sup,time,tt,u,var"));
// SVG Elements
// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements
var svgElements = makeMap("animate,animateColor,animateMotion,animateTransform,circle,defs," +
"desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient," +
"line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,set," +
"stop,svg,switch,text,title,tspan,use");
// Special Elements (can contain anything)
var specialElements = makeMap("script,style");
var validElements = angular.extend({},
voidElements,
blockElements,
inlineElements,
optionalEndTagElements,
svgElements);
//Attributes that have href and hence need to be sanitized
var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap,xlink:href");
var htmlAttrs = makeMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+
'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+
'id,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+
'scope,scrolling,shape,size,span,start,summary,target,title,type,'+
'valign,value,vspace,width');
// SVG attributes (without "id" and "name" attributes)
// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
var svgAttrs = makeMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
'attributeName,attributeType,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,' +
'color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,' +
'font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,' +
'gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,' +
'keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,' +
'markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,' +
'overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,' +
'repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,' +
'stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,' +
'stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,' +
'stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,' +
'underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,' +
'viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,' +
'xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,' +
'zoomAndPan');
var validAttrs = angular.extend({},
uriAttrs,
svgAttrs,
htmlAttrs);
function makeMap(str) {
var obj = {}, items = str.split(','), i;
for (i = 0; i < items.length; i++) obj[items[i]] = true;
return obj;
}
/**
* @example
* htmlParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
* @param {string} html string
* @param {object} handler
*/
function htmlParser(html, handler) {
if (typeof html !== 'string') {
if (html === null || typeof html === 'undefined') {
html = '';
} else {
html = '' + html;
}
}
var index, chars, match, stack = [], last = html, text;
stack.last = function() { return stack[ stack.length - 1 ]; };
while (html) {
text = '';
chars = true;
// Make sure we're not in a script or style element
if (!stack.last() || !specialElements[ stack.last() ]) {
// White space
if (WHITE_SPACE_REGEXP.test(html)) {
match = html.match(WHITE_SPACE_REGEXP);
if (match) {
var mat = match[0];
if (handler.whitespace) handler.whitespace(match[0]);
html = html.replace(match[0], '');
chars = false;
}
//Comment
} else if (SINGLE_COMMENT_REGEXP.test(html)) {
match = html.match(SINGLE_COMMENT_REGEXP);
if (match) {
if (handler.comment) handler.comment(match[1]);
html = html.replace(match[0], '');
chars = false;
}
// DOCTYPE
} else if (DOCTYPE_REGEXP.test(html)) {
match = html.match(DOCTYPE_REGEXP);
if (match) {
html = html.replace(match[0], '');
chars = false;
}
// end tag
} else if (BEGING_END_TAGE_REGEXP.test(html)) {
match = html.match(END_TAG_REGEXP);
if (match) {
html = html.substring(match[0].length);
match[0].replace(END_TAG_REGEXP, parseEndTag);
chars = false;
}
// start tag
} else if (BEGIN_TAG_REGEXP.test(html)) {
match = html.match(START_TAG_REGEXP);
if (match) {
// We only have a valid start-tag if there is a '>'.
if (match[4]) {
html = html.substring(match[0].length);
match[0].replace(START_TAG_REGEXP, parseStartTag);
}
chars = false;
} else {
// no ending tag found --- this piece should be encoded as an entity.
text += '<';
html = html.substring(1);
}
}
if (chars) {
index = html.indexOf("<");
text += index < 0 ? html : html.substring(0, index);
html = index < 0 ? "" : html.substring(index);
if (handler.chars) handler.chars(decodeEntities(text));
}
} else {
html = html.replace(new RegExp("([^]*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'),
function(all, text) {
text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1");
if (handler.chars) handler.chars(decodeEntities(text));
return "";
});
parseEndTag("", stack.last());
}
if (html == last) {
throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " +
"of html: {0}", html);
}
last = html;
}
// Clean up any remaining tags
parseEndTag();
function parseStartTag(tag, tagName, rest, unary) {
tagName = angular.lowercase(tagName);
if (blockElements[ tagName ]) {
while (stack.last() && inlineElements[ stack.last() ]) {
parseEndTag("", stack.last());
}
}
if (optionalEndTagElements[ tagName ] && stack.last() == tagName) {
parseEndTag("", tagName);
}
unary = voidElements[ tagName ] || !!unary;
if (!unary)
stack.push(tagName);
var attrs = {};
rest.replace(ATTR_REGEXP,
function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {
var value = doubleQuotedValue
|| singleQuotedValue
|| unquotedValue
|| '';
attrs[name] = decodeEntities(value);
});
if (handler.start) handler.start(tagName, attrs, unary);
}
function parseEndTag(tag, tagName) {
var pos = 0, i;
tagName = angular.lowercase(tagName);
if (tagName)
// Find the closest opened tag of the same type
for (pos = stack.length - 1; pos >= 0; pos--)
if (stack[ pos ] == tagName)
break;
if (pos >= 0) {
// Close all the open elements, up the stack
for (i = stack.length - 1; i >= pos; i--)
if (handler.end) handler.end(stack[ i ]);
// Remove the open elements from the stack
stack.length = pos;
}
}
}
var hiddenPre=document.createElement("pre");
var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/;
/**
* decodes all entities into regular string
* @param value
* @returns {string} A string with decoded entities.
*/
function decodeEntities(value) {
if (!value) { return ''; }
// Note: IE8 does not preserve spaces at the start/end of innerHTML
// so we must capture them and reattach them afterward
var parts = spaceRe.exec(value);
var spaceBefore = parts[1];
var spaceAfter = parts[3];
var content = parts[2];
if (content) {
hiddenPre.innerHTML=content.replace(/</g,"<");
// innerText depends on styling as it doesn't display hidden elements.
// Therefore, it's better to use textContent not to cause unnecessary
// reflows. However, IE<9 don't support textContent so the innerText
// fallback is necessary.
content = 'textContent' in hiddenPre ?
hiddenPre.textContent : hiddenPre.innerText;
}
return spaceBefore + content + spaceAfter;
}
/**
* Escapes all potentially dangerous characters, so that the
* resulting string can be safely inserted into attribute or
* element text.
* @param value
* @returns {string} escaped text
*/
function encodeEntities(value) {
return value.
replace(/&/g, '&').
replace(SURROGATE_PAIR_REGEXP, function(value) {
var hi = value.charCodeAt(0);
var low = value.charCodeAt(1);
return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
}).
replace(NON_ALPHANUMERIC_REGEXP, function(value) {
// unsafe chars are: \u0000-\u001f \u007f-\u009f \u00ad \u0600-\u0604 \u070f \u17b4 \u17b5 \u200c-\u200f \u2028-\u202f \u2060-\u206f \ufeff \ufff0-\uffff from jslint.com/lint.html
// decimal values are: 0-31, 127-159, 173, 1536-1540, 1807, 6068, 6069, 8204-8207, 8232-8239, 8288-8303, 65279, 65520-65535
var c = value.charCodeAt(0);
// if unsafe character encode
if(c <= 159 ||
c == 173 ||
(c >= 1536 && c <= 1540) ||
c == 1807 ||
c == 6068 ||
c == 6069 ||
(c >= 8204 && c <= 8207) ||
(c >= 8232 && c <= 8239) ||
(c >= 8288 && c <= 8303) ||
c == 65279 ||
(c >= 65520 && c <= 65535)) return '&#' + c + ';';
return value; // avoids multilingual issues
}).
replace(/</g, '<').
replace(/>/g, '>');
}
var trim = (function() {
// native trim is way faster: http://jsperf.com/angular-trim-test
// but IE doesn't have it... :-(
// TODO: we should move this into IE/ES5 polyfill
if (!String.prototype.trim) {
return function(value) {
return angular.isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value;
};
}
return function(value) {
return angular.isString(value) ? value.trim() : value;
};
})();
// Custom logic for accepting certain style options only - textAngular
// Currently allows only the color, background-color, text-align, float, width and height attributes
// all other attributes should be easily done through classes.
function validStyles(styleAttr){
var result = '';
var styleArray = styleAttr.split(';');
angular.forEach(styleArray, function(value){
var v = value.split(':');
if(v.length == 2){
var key = trim(angular.lowercase(v[0]));
var value = trim(angular.lowercase(v[1]));
if(
(key === 'color' || key === 'background-color') && (
value.match(/^rgb\([0-9%,\. ]*\)$/i)
|| value.match(/^rgba\([0-9%,\. ]*\)$/i)
|| value.match(/^hsl\([0-9%,\. ]*\)$/i)
|| value.match(/^hsla\([0-9%,\. ]*\)$/i)
|| value.match(/^#[0-9a-f]{3,6}$/i)
|| value.match(/^[a-z]*$/i)
)
||
key === 'text-align' && (
value === 'left'
|| value === 'right'
|| value === 'center'
|| value === 'justify'
)
||
key === 'text-decoration' && (
value === 'underline'
|| value === 'line-through'
)
|| key === 'font-weight' && (
value === 'bold'
)
||
key === 'float' && (
value === 'left'
|| value === 'right'
|| value === 'none'
)
||
(key === 'width' || key === 'height') && (
value.match(/[0-9\.]*(px|em|rem|%)/)
)
|| // Reference #520
(key === 'direction' && value.match(/^ltr|rtl|initial|inherit$/))
) result += key + ': ' + value + ';';
}
});
return result;
}
// this function is used to manually allow specific attributes on specific tags with certain prerequisites
function validCustomTag(tag, attrs, lkey, value){
// catch the div placeholder for the iframe replacement
if (tag === 'img' && attrs['ta-insert-video']){
if(lkey === 'ta-insert-video' || lkey === 'allowfullscreen' || lkey === 'frameborder' || (lkey === 'contenteditable' && value === 'false')) return true;
}
return false;
}
/**
* create an HTML/XML writer which writes to buffer
* @param {Array} buf use buf.jain('') to get out sanitized html string
* @returns {object} in the form of {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* }
*/
function htmlSanitizeWriter(buf, uriValidator) {
var ignore = false;
var out = angular.bind(buf, buf.push);
return {
start: function(tag, attrs, unary) {
tag = angular.lowercase(tag);
if (!ignore && specialElements[tag]) {
ignore = tag;
}
if (!ignore && validElements[tag] === true) {
out('<');
out(tag);
angular.forEach(attrs, function(value, key) {
var lkey=angular.lowercase(key);
var isImage=(tag === 'img' && lkey === 'src') || (lkey === 'background');
if ((lkey === 'style' && (value = validStyles(value)) !== '') || validCustomTag(tag, attrs, lkey, value) || validAttrs[lkey] === true &&
(uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
out(' ');
out(key);
out('="');
out(encodeEntities(value));
out('"');
}
});
out(unary ? '/>' : '>');
}
},
comment: function (com) {
out(com);
},
whitespace: function (ws) {
out(encodeEntities(ws));
},
end: function(tag) {
tag = angular.lowercase(tag);
if (!ignore && validElements[tag] === true) {
out('</');
out(tag);
out('>');
}
if (tag == ignore) {
ignore = false;
}
},
chars: function(chars) {
if (!ignore) {
out(encodeEntities(chars));
}
}
};
}
// define ngSanitize module and register $sanitize service
angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
/* global sanitizeText: false */
/**
* @ngdoc filter
* @name linky
* @kind function
*
* @description
* Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and
* plain email address links.
*
* Requires the {@link ngSanitize `ngSanitize`} module to be installed.
*
* @param {string} text Input text.
* @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in.
* @returns {string} Html-linkified text.
*
* @usage
<span ng-bind-html="linky_expression | linky"></span>
*
* @example
<example module="linkyExample" deps="angular-sanitize.js">
<file name="index.html">
<script>
angular.module('linkyExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.snippet =
'Pretty text with some links:\n'+
'http://angularjs.org/,\n'+
'mailto:us@somewhere.org,\n'+
'another@somewhere.org,\n'+
'and one more: ftp://127.0.0.1/.';
$scope.snippetWithTarget = 'http://angularjs.org/';
}]);
</script>
<div ng-controller="ExampleController">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<td>Filter</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="linky-filter">
<td>linky filter</td>
<td>
<pre><div ng-bind-html="snippet | linky"><br></div></pre>
</td>
<td>
<div ng-bind-html="snippet | linky"></div>
</td>
</tr>
<tr id="linky-target">
<td>linky target</td>
<td>
<pre><div ng-bind-html="snippetWithTarget | linky:'_blank'"><br></div></pre>
</td>
<td>
<div ng-bind-html="snippetWithTarget | linky:'_blank'"></div>
</td>
</tr>
<tr id="escaped-html">
<td>no filter</td>
<td><pre><div ng-bind="snippet"><br></div></pre></td>
<td><div ng-bind="snippet"></div></td>
</tr>
</table>
</file>
<file name="protractor.js" type="protractor">
it('should linkify the snippet with urls', function() {
expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
'another@somewhere.org, and one more: ftp://127.0.0.1/.');
expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
});
it('should not linkify snippet without the linky filter', function() {
expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
'another@somewhere.org, and one more: ftp://127.0.0.1/.');
expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
});
it('should update', function() {
element(by.model('snippet')).clear();
element(by.model('snippet')).sendKeys('new http://link.');
expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
toBe('new http://link.');
expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
.toBe('new http://link.');
});
it('should work with the target property', function() {
expect(element(by.id('linky-target')).
element(by.binding("snippetWithTarget | linky:'_blank'")).getText()).
toBe('http://angularjs.org/');
expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
});
</file>
</example>
*/
angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
var LINKY_URL_REGEXP =
/((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"”’]/,
MAILTO_REGEXP = /^mailto:/;
return function(text, target) {
if (!text) return text;
var match;
var raw = text;
var html = [];
var url;
var i;
while ((match = raw.match(LINKY_URL_REGEXP))) {
// We can not end in these as they are sometimes found at the end of the sentence
url = match[0];
// if we did not match ftp/http/www/mailto then assume mailto
if (!match[2] && !match[4]) {
url = (match[3] ? 'http://' : 'mailto:') + url;
}
i = match.index;
addText(raw.substr(0, i));
addLink(url, match[0].replace(MAILTO_REGEXP, ''));
raw = raw.substring(i + match[0].length);
}
addText(raw);
return $sanitize(html.join(''));
function addText(text) {
if (!text) {
return;
}
html.push(sanitizeText(text));
}
function addLink(url, text) {
html.push('<a ');
if (angular.isDefined(target)) {
html.push('target="',
target,
'" ');
}
html.push('href="',
url.replace(/"/g, '"'),
'">');
addText(text);
html.push('</a>');
}
};
}]);
})(window, window.angular);
/*
@license textAngular
Author : Austin Anderson
License : 2013 MIT
Version 1.5.0
See README.md or https://github.com/fraywing/textAngular/wiki for requirements and use.
*/
/*
Commonjs package manager support (eg componentjs).
*/
/* istanbul ignore next: */
'undefined'!=typeof module&&'undefined'!=typeof exports&&module.exports===exports&&(module.exports='textAngular');
(function(){ // encapsulate all variables so they don't become global vars
"use strict";
// IE version detection - http://stackoverflow.com/questions/4169160/javascript-ie-detection-why-not-use-simple-conditional-comments
// We need this as IE sometimes plays funny tricks with the contenteditable.
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
// ie === undefined
// If you're in IE (>=5) then you can determine which version:
// ie === 7; // IE7
// Thus, to detect IE:
// if (ie) {}
// And to detect the version:
// ie === 6 // IE6
// ie > 7 // IE8, IE9, IE10 ...
// ie < 9 // Anything less than IE9
// ----------------------------------------------------------
/* istanbul ignore next: untestable browser check */
var _browserDetect = {
ie: (function(){
var undef,
v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
}()),
webkit: /AppleWebKit\/([\d.]+)/i.test(navigator.userAgent)
};
// fix a webkit bug, see: https://gist.github.com/shimondoodkin/1081133
// this is set true when a blur occurs as the blur of the ta-bind triggers before the click
var globalContentEditableBlur = false;
/* istanbul ignore next: Browser Un-Focus fix for webkit */
if(_browserDetect.webkit) {
document.addEventListener("mousedown", function(_event){
var e = _event || window.event;
var curelement = e.target;
if(globalContentEditableBlur && curelement !== null){
var isEditable = false;
var tempEl = curelement;
while(tempEl !== null && tempEl.tagName.toLowerCase() !== 'html' && !isEditable){
isEditable = tempEl.contentEditable === 'true';
tempEl = tempEl.parentNode;
}
if(!isEditable){
document.getElementById('textAngular-editableFix-010203040506070809').setSelectionRange(0, 0); // set caret focus to an element that handles caret focus correctly.
curelement.focus(); // focus the wanted element.
if (curelement.select) {
curelement.select(); // use select to place cursor for input elements.
}
}
}
globalContentEditableBlur = false;
}, false); // add global click handler
angular.element(document).ready(function () {
angular.element(document.body).append(angular.element('<input id="textAngular-editableFix-010203040506070809" class="ta-hidden-input" aria-hidden="true" unselectable="on" tabIndex="-1">'));
});
}
// Gloabl to textAngular REGEXP vars for block and list elements.
var BLOCKELEMENTS = /^(address|article|aside|audio|blockquote|canvas|dd|div|dl|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|noscript|ol|output|p|pre|section|table|tfoot|ul|video)$/i;
var LISTELEMENTS = /^(ul|li|ol)$/i;
var VALIDELEMENTS = /^(address|article|aside|audio|blockquote|canvas|dd|div|dl|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|noscript|ol|output|p|pre|section|table|tfoot|ul|video|li)$/i;
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Compatibility
/* istanbul ignore next: trim shim for older browsers */
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
/*
Custom stylesheet for the placeholders rules.
Credit to: http://davidwalsh.name/add-rules-stylesheets
*/
var sheet, addCSSRule, removeCSSRule, _addCSSRule, _removeCSSRule, _getRuleIndex;
/* istanbul ignore else: IE <8 test*/
if(_browserDetect.ie > 8 || _browserDetect.ie === undefined){
var _sheets = document.styleSheets;
/* istanbul ignore next: preference for stylesheet loaded externally */
for(var i = 0; i < _sheets.length; i++){
if(_sheets[i].media.length === 0 || _sheets[i].media.mediaText.match(/(all|screen)/ig)){
if(_sheets[i].href){
if(_sheets[i].href.match(/textangular\.(min\.|)css/ig)){
sheet = _sheets[i];
break;
}
}
}
}
/* istanbul ignore next: preference for stylesheet loaded externally */
if(!sheet){
// this sheet is used for the placeholders later on.
sheet = (function() {
// Create the <style> tag
var style = document.createElement("style");
/* istanbul ignore else : WebKit hack :( */
if(_browserDetect.webkit) style.appendChild(document.createTextNode(""));
// Add the <style> element to the page, add as first so the styles can be overridden by custom stylesheets
document.getElementsByTagName('head')[0].appendChild(style);
return style.sheet;
})();
}
// use as: addCSSRule("header", "float: left");
addCSSRule = function(selector, rules) {
return _addCSSRule(sheet, selector, rules);
};
_addCSSRule = function(_sheet, selector, rules){
var insertIndex;
var insertedRule;
// This order is important as IE 11 has both cssRules and rules but they have different lengths - cssRules is correct, rules gives an error in IE 11
/* istanbul ignore next: browser catches */
if(_sheet.cssRules) insertIndex = Math.max(_sheet.cssRules.length - 1, 0);
else if(_sheet.rules) insertIndex = Math.max(_sheet.rules.length - 1, 0);
/* istanbul ignore else: untestable IE option */
if(_sheet.insertRule) {
_sheet.insertRule(selector + "{" + rules + "}", insertIndex);
}
else {
_sheet.addRule(selector, rules, insertIndex);
}
/* istanbul ignore next: browser catches */
if(sheet.rules) insertedRule = sheet.rules[insertIndex];
else if(sheet.cssRules) insertedRule = sheet.cssRules[insertIndex];
// return the inserted stylesheet rule
return insertedRule;
};
_getRuleIndex = function(rule, rules) {
var i, ruleIndex;
for (i=0; i < rules.length; i++) {
/* istanbul ignore else: check for correct rule */
if (rules[i].cssText === rule.cssText) {
ruleIndex = i;
break;
}
}
return ruleIndex;
};
removeCSSRule = function(rule){
_removeCSSRule(sheet, rule);
};
/* istanbul ignore next: tests are browser specific */
_removeCSSRule = function(sheet, rule){
var rules = sheet.cssRules || sheet.rules;
if(!rules || rules.length === 0) return;
var ruleIndex = _getRuleIndex(rule, rules);
if(sheet.removeRule){
sheet.removeRule(ruleIndex);
}else{
sheet.deleteRule(ruleIndex);
}
};
}
angular.module('textAngular.factories', [])
.factory('taBrowserTag', [function(){
return function(tag){
/* istanbul ignore next: ie specific test */
if(!tag) return (_browserDetect.ie <= 8)? 'P' : 'p';
else if(tag === '') return (_browserDetect.ie === undefined)? 'div' : (_browserDetect.ie <= 8)? 'P' : 'p';
else return (_browserDetect.ie <= 8)? tag.toUpperCase() : tag;
};
}]).factory('taApplyCustomRenderers', ['taCustomRenderers', 'taDOM', function(taCustomRenderers, taDOM){
return function(val){
var element = angular.element('<div></div>');
element[0].innerHTML = val;
angular.forEach(taCustomRenderers, function(renderer){
var elements = [];
// get elements based on what is defined. If both defined do secondary filter in the forEach after using selector string
if(renderer.selector && renderer.selector !== '')
elements = element.find(renderer.selector);
/* istanbul ignore else: shouldn't fire, if it does we're ignoring everything */
else if(renderer.customAttribute && renderer.customAttribute !== '')
elements = taDOM.getByAttribute(element, renderer.customAttribute);
// process elements if any found
angular.forEach(elements, function(_element){
_element = angular.element(_element);
if(renderer.selector && renderer.selector !== '' && renderer.customAttribute && renderer.customAttribute !== ''){
if(_element.attr(renderer.customAttribute) !== undefined) renderer.renderLogic(_element);
} else renderer.renderLogic(_element);
});
});
return element[0].innerHTML;
};
}]).factory('taFixChrome', function(){
// get whaterever rubbish is inserted in chrome
// should be passed an html string, returns an html string
var taFixChrome = function(html){
if(!html || !angular.isString(html) || html.length <= 0) return html;
// grab all elements with a style attibute
var spanMatch = /<([^>\/]+?)style=("([^"]+)"|'([^']+)')([^>]*)>/ig;
var match, styleVal, newTag, finalHtml = '', lastIndex = 0;
while(match = spanMatch.exec(html)){
// one of the quoted values ' or "
/* istanbul ignore next: quotations match */
styleVal = match[3] || match[4];
// test for chrome inserted junk
if(styleVal && styleVal.match(/line-height: 1.[0-9]{3,12};|color: inherit; line-height: 1.1;/i)){
// replace original tag with new tag
styleVal = styleVal.replace(/( |)font-family: inherit;|( |)line-height: 1.[0-9]{3,12};|( |)color: inherit;/ig, '');
newTag = '<' + match[1].trim();
if(styleVal.trim().length > 0) newTag += ' style=' + match[2].substring(0,1) + styleVal + match[2].substring(0,1);
newTag += match[5].trim() + ">";
finalHtml += html.substring(lastIndex, match.index) + newTag;
lastIndex = match.index + match[0].length;
}
}
finalHtml += html.substring(lastIndex);
// only replace when something has changed, else we get focus problems on inserting lists
if(lastIndex > 0){
// replace all empty strings
return finalHtml.replace(/<span\s?>(.*?)<\/span>(<br(\/|)>|)/ig, '$1');
} else return html;
};
return taFixChrome;
}).factory('taSanitize', ['$sanitize', function taSanitizeFactory($sanitize){
var convert_infos = [
{
property: 'font-weight',
values: [ 'bold' ],
tag: 'b'
},
{
property: 'font-style',
values: [ 'italic' ],
tag: 'i'
}
];
var styleMatch = [];
for(var i = 0; i < convert_infos.length; i++){
var _partialStyle = '(' + convert_infos[i].property + ':\\s*(';
for(var j = 0; j < convert_infos[i].values.length; j++){
/* istanbul ignore next: not needed to be tested yet */
if(j > 0) _partialStyle += '|';
_partialStyle += convert_infos[i].values[j];
}
_partialStyle += ');)';
styleMatch.push(_partialStyle);
}
var styleRegexString = '(' + styleMatch.join('|') + ')';
function wrapNested(html, wrapTag) {
var depth = 0;
var lastIndex = 0;
var match;
var tagRegex = /<[^>]*>/ig;
while(match = tagRegex.exec(html)){
lastIndex = match.index;
if(match[0].substr(1, 1) === '/'){
if(depth === 0) break;
else depth--;
}else depth++;
}
return wrapTag +
html.substring(0, lastIndex) +
// get the start tags reversed - this is safe as we construct the strings with no content except the tags
angular.element(wrapTag)[0].outerHTML.substring(wrapTag.length) +
html.substring(lastIndex);
}
function transformLegacyStyles(html){
if(!html || !angular.isString(html) || html.length <= 0) return html;
var i;
var styleElementMatch = /<([^>\/]+?)style=("([^"]+)"|'([^']+)')([^>]*)>/ig;
var match, subMatch, styleVal, newTag, lastNewTag = '', newHtml, finalHtml = '', lastIndex = 0;
while(match = styleElementMatch.exec(html)){
// one of the quoted values ' or "
/* istanbul ignore next: quotations match */
styleVal = match[3] || match[4];
var styleRegex = new RegExp(styleRegexString, 'i');
// test for style values to change
if(angular.isString(styleVal) && styleRegex.test(styleVal)){
// remove build tag list
newTag = '';
// init regex here for exec
var styleRegexExec = new RegExp(styleRegexString, 'ig');
// find relevand tags and build a string of them
while(subMatch = styleRegexExec.exec(styleVal)){
for(i = 0; i < convert_infos.length; i++){
if(!!subMatch[(i*2) + 2]){
newTag += '<' + convert_infos[i].tag + '>';
}
}
}
// recursively find more legacy styles in html before this tag and after the previous match (if any)
newHtml = transformLegacyStyles(html.substring(lastIndex, match.index));
// build up html
if(lastNewTag.length > 0){
finalHtml += wrapNested(newHtml, lastNewTag);
}else finalHtml += newHtml;
// grab the style val without the transformed values
styleVal = styleVal.replace(new RegExp(styleRegexString, 'ig'), '');
// build the html tag
finalHtml += '<' + match[1].trim();
if(styleVal.length > 0) finalHtml += ' style="' + styleVal + '"';
finalHtml += match[5] + '>';
// update the start index to after this tag
lastIndex = match.index + match[0].length;
lastNewTag = newTag;
}
}
if(lastNewTag.length > 0){
finalHtml += wrapNested(html.substring(lastIndex), lastNewTag);
}
else finalHtml += html.substring(lastIndex);
return finalHtml;
}
function transformLegacyAttributes(html){
if(!html || !angular.isString(html) || html.length <= 0) return html;
// replace all align='...' tags with text-align attributes
var attrElementMatch = /<([^>\/]+?)align=("([^"]+)"|'([^']+)')([^>]*)>/ig;
var match, finalHtml = '', lastIndex = 0;
// match all attr tags
while(match = attrElementMatch.exec(html)){
// add all html before this tag
finalHtml += html.substring(lastIndex, match.index);
// record last index after this tag
lastIndex = match.index + match[0].length;
// construct tag without the align attribute
var newTag = '<' + match[1] + match[5];
// add the style attribute
if(/style=("([^"]+)"|'([^']+)')/ig.test(newTag)){
/* istanbul ignore next: quotations match */
newTag = newTag.replace(/style=("([^"]+)"|'([^']+)')/i, 'style="$2$3 text-align:' + (match[3] || match[4]) + ';"');
}else{
/* istanbul ignore next: quotations match */
newTag += ' style="text-align:' + (match[3] || match[4]) + ';"';
}
newTag += '>';
// add to html
finalHtml += newTag;
}
// return with remaining html
return finalHtml + html.substring(lastIndex);
}
return function taSanitize(unsafe, oldsafe, ignore){
// unsafe html should NEVER built into a DOM object via angular.element. This allows XSS to be inserted and run.
if ( !ignore ) {
try {
unsafe = transformLegacyStyles(unsafe);
} catch (e) {
}
}
// unsafe and oldsafe should be valid HTML strings
// any exceptions (lets say, color for example) should be made here but with great care
// setup unsafe element for modification
unsafe = transformLegacyAttributes(unsafe);
var safe;
try {
safe = $sanitize(unsafe);
// do this afterwards, then the $sanitizer should still throw for bad markup
if(ignore) safe = unsafe;
} catch (e){
safe = oldsafe || '';
}
// Do processing for <pre> tags, removing tabs and return carriages outside of them
var _preTags = safe.match(/(<pre[^>]*>.*?<\/pre[^>]*>)/ig);
var processedSafe = safe.replace(/(&#(9|10);)*/ig, '');
var re = /<pre[^>]*>.*?<\/pre[^>]*>/ig;
var index = 0;
var lastIndex = 0;
var origTag;
safe = '';
while((origTag = re.exec(processedSafe)) !== null && index < _preTags.length){
safe += processedSafe.substring(lastIndex, origTag.index) + _preTags[index];
lastIndex = origTag.index + origTag[0].length;
index++;
}
return safe + processedSafe.substring(lastIndex);
};
}]).factory('taToolExecuteAction', ['$q', '$log', function($q, $log){
// this must be called on a toolScope or instance
return function(editor){
if(editor !== undefined) this.$editor = function(){ return editor; };
var deferred = $q.defer(),
promise = deferred.promise,
_editor = this.$editor();
// pass into the action the deferred function and also the function to reload the current selection if rangy available
var result;
try{
result = this.action(deferred, _editor.startAction());
// We set the .finally callback here to make sure it doesn't get executed before any other .then callback.
promise['finally'](function(){
_editor.endAction.call(_editor);
});
}catch(exc){
$log.error(exc);
}
if(result || result === undefined){
// if true or undefined is returned then the action has finished. Otherwise the deferred action will be resolved manually.
deferred.resolve();
}
};
}]);
angular.module('textAngular.DOM', ['textAngular.factories'])
.factory('taExecCommand', ['taSelection', 'taBrowserTag', '$document', function(taSelection, taBrowserTag, $document){
var listToDefault = function(listElement, defaultWrap){
var $target, i;
// if all selected then we should remove the list
// grab all li elements and convert to taDefaultWrap tags
var children = listElement.find('li');
for(i = children.length - 1; i >= 0; i--){
$target = angular.element('<' + defaultWrap + '>' + children[i].innerHTML + '</' + defaultWrap + '>');
listElement.after($target);
}
listElement.remove();
taSelection.setSelectionToElementEnd($target[0]);
};
var selectLi = function(liElement){
if(/(<br(|\/)>)$/i.test(liElement.innerHTML.trim())) taSelection.setSelectionBeforeElement(angular.element(liElement).find("br")[0]);
else taSelection.setSelectionToElementEnd(liElement);
};
var listToList = function(listElement, newListTag){
var $target = angular.element('<' + newListTag + '>' + listElement[0].innerHTML + '</' + newListTag + '>');
listElement.after($target);
listElement.remove();
selectLi($target.find('li')[0]);
};
var childElementsToList = function(elements, listElement, newListTag){
var html = '';
for(var i = 0; i < elements.length; i++){
html += '<' + taBrowserTag('li') + '>' + elements[i].innerHTML + '</' + taBrowserTag('li') + '>';
}
var $target = angular.element('<' + newListTag + '>' + html + '</' + newListTag + '>');
listElement.after($target);
listElement.remove();
selectLi($target.find('li')[0]);
};
return function(taDefaultWrap, topNode){
taDefaultWrap = taBrowserTag(taDefaultWrap);
return function(command, showUI, options, defaultTagAttributes){
var i, $target, html, _nodes, next, optionsTagName, selectedElement;
var defaultWrapper = angular.element('<' + taDefaultWrap + '>');
try{
selectedElement = taSelection.getSelectionElement();
}catch(e){}
var $selected = angular.element(selectedElement);
if(selectedElement !== undefined){
var tagName = selectedElement.tagName.toLowerCase();
if(command.toLowerCase() === 'insertorderedlist' || command.toLowerCase() === 'insertunorderedlist'){
var selfTag = taBrowserTag((command.toLowerCase() === 'insertorderedlist')? 'ol' : 'ul');
if(tagName === selfTag){
// if all selected then we should remove the list
// grab all li elements and convert to taDefaultWrap tags
return listToDefault($selected, taDefaultWrap);
}else if(tagName === 'li' && $selected.parent()[0].tagName.toLowerCase() === selfTag && $selected.parent().children().length === 1){
// catch for the previous statement if only one li exists
return listToDefault($selected.parent(), taDefaultWrap);
}else if(tagName === 'li' && $selected.parent()[0].tagName.toLowerCase() !== selfTag && $selected.parent().children().length === 1){
// catch for the previous statement if only one li exists
return listToList($selected.parent(), selfTag);
}else if(tagName.match(BLOCKELEMENTS) && !$selected.hasClass('ta-bind')){
// if it's one of those block elements we have to change the contents
// if it's a ol/ul we are changing from one to the other
if(tagName === 'ol' || tagName === 'ul'){
return listToList($selected, selfTag);
}else{
var childBlockElements = false;
angular.forEach($selected.children(), function(elem){
if(elem.tagName.match(BLOCKELEMENTS)) {
childBlockElements = true;
}
});
if(childBlockElements){
return childElementsToList($selected.children(), $selected, selfTag);
}else{
return childElementsToList([angular.element('<div>' + selectedElement.innerHTML + '</div>')[0]], $selected, selfTag);
}
}
}else if(tagName.match(BLOCKELEMENTS)){
// if we get here then all the contents of the ta-bind are selected
_nodes = taSelection.getOnlySelectedElements();
if(_nodes.length === 0){
// here is if there is only text in ta-bind ie <div ta-bind>test content</div>
$target = angular.element('<' + selfTag + '><li>' + selectedElement.innerHTML + '</li></' + selfTag + '>');
$selected.html('');
$selected.append($target);
}else if(_nodes.length === 1 && (_nodes[0].tagName.toLowerCase() === 'ol' || _nodes[0].tagName.toLowerCase() === 'ul')){
if(_nodes[0].tagName.toLowerCase() === selfTag){
// remove
return listToDefault(angular.element(_nodes[0]), taDefaultWrap);
}else{
return listToList(angular.element(_nodes[0]), selfTag);
}
}else{
html = '';
var $nodes = [];
for(i = 0; i < _nodes.length; i++){
/* istanbul ignore else: catch for real-world can't make it occur in testing */
if(_nodes[i].nodeType !== 3){
var $n = angular.element(_nodes[i]);
/* istanbul ignore if: browser check only, phantomjs doesn't return children nodes but chrome at least does */
if(_nodes[i].tagName.toLowerCase() === 'li') continue;
else if(_nodes[i].tagName.toLowerCase() === 'ol' || _nodes[i].tagName.toLowerCase() === 'ul'){
html += $n[0].innerHTML; // if it's a list, add all it's children
}else if(_nodes[i].tagName.toLowerCase() === 'span' && (_nodes[i].childNodes[0].tagName.toLowerCase() === 'ol' || _nodes[i].childNodes[0].tagName.toLowerCase() === 'ul')){
html += $n[0].childNodes[0].innerHTML; // if it's a list, add all it's children
}else{
html += '<' + taBrowserTag('li') + '>' + $n[0].innerHTML + '</' + taBrowserTag('li') + '>';
}
$nodes.unshift($n);
}
}
$target = angular.element('<' + selfTag + '>' + html + '</' + selfTag + '>');
$nodes.pop().replaceWith($target);
angular.forEach($nodes, function($node){ $node.remove(); });
}
taSelection.setSelectionToElementEnd($target[0]);
return;
}
}else if(command.toLowerCase() === 'formatblock'){
optionsTagName = options.toLowerCase().replace(/[<>]/ig, '');
if(optionsTagName.trim() === 'default') {
optionsTagName = taDefaultWrap;
options = '<' + taDefaultWrap + '>';
}
if(tagName === 'li') $target = $selected.parent();
else $target = $selected;
// find the first blockElement
while(!$target[0].tagName || !$target[0].tagName.match(BLOCKELEMENTS) && !$target.parent().attr('contenteditable')){
$target = $target.parent();
/* istanbul ignore next */
tagName = ($target[0].tagName || '').toLowerCase();
}
if(tagName === optionsTagName){
// $target is wrap element
_nodes = $target.children();
var hasBlock = false;
for(i = 0; i < _nodes.length; i++){
hasBlock = hasBlock || _nodes[i].tagName.match(BLOCKELEMENTS);
}
if(hasBlock){
$target.after(_nodes);
next = $target.next();
$target.remove();
$target = next;
}else{
defaultWrapper.append($target[0].childNodes);
$target.after(defaultWrapper);
$target.remove();
$target = defaultWrapper;
}
}else if($target.parent()[0].tagName.toLowerCase() === optionsTagName && !$target.parent().hasClass('ta-bind')){
//unwrap logic for parent
var blockElement = $target.parent();
var contents = blockElement.contents();
for(i = 0; i < contents.length; i ++){
/* istanbul ignore next: can't test - some wierd thing with how phantomjs works */
if(blockElement.parent().hasClass('ta-bind') && contents[i].nodeType === 3){
defaultWrapper = angular.element('<' + taDefaultWrap + '>');
defaultWrapper[0].innerHTML = contents[i].outerHTML;
contents[i] = defaultWrapper[0];
}
blockElement.parent()[0].insertBefore(contents[i], blockElement[0]);
}
blockElement.remove();
}else if(tagName.match(LISTELEMENTS)){
// wrapping a list element
$target.wrap(options);
}else{
// default wrap behaviour
_nodes = taSelection.getOnlySelectedElements();
if(_nodes.length === 0) _nodes = [$target[0]];
// find the parent block element if any of the nodes are inline or text
for(i = 0; i < _nodes.length; i++){
if(_nodes[i].nodeType === 3 || !_nodes[i].tagName.match(BLOCKELEMENTS)){
while(_nodes[i].nodeType === 3 || !_nodes[i].tagName || !_nodes[i].tagName.match(BLOCKELEMENTS)){
_nodes[i] = _nodes[i].parentNode;
}
}
}
if(angular.element(_nodes[0]).hasClass('ta-bind')){
$target = angular.element(options);
$target[0].innerHTML = _nodes[0].innerHTML;
_nodes[0].innerHTML = $target[0].outerHTML;
}else if(optionsTagName === 'blockquote'){
// blockquotes wrap other block elements
html = '';
for(i = 0; i < _nodes.length; i++){
html += _nodes[i].outerHTML;
}
$target = angular.element(options);
$target[0].innerHTML = html;
_nodes[0].parentNode.insertBefore($target[0],_nodes[0]);
for(i = _nodes.length - 1; i >= 0; i--){
/* istanbul ignore else: */
if(_nodes[i].parentNode) _nodes[i].parentNode.removeChild(_nodes[i]);
}
}
else {
// regular block elements replace other block elements
for(i = 0; i < _nodes.length; i++){
$target = angular.element(options);
$target[0].innerHTML = _nodes[i].innerHTML;
_nodes[i].parentNode.insertBefore($target[0],_nodes[i]);
_nodes[i].parentNode.removeChild(_nodes[i]);
}
}
}
taSelection.setSelectionToElementEnd($target[0]);
return;
}else if(command.toLowerCase() === 'createlink'){
var tagBegin = '<a href="' + options + '" target="' +
(defaultTagAttributes.a.target ? defaultTagAttributes.a.target : '') +
'">',
tagEnd = '</a>',
_selection = taSelection.getSelection();
if(_selection.collapsed){
// insert text at selection, then select then just let normal exec-command run
taSelection.insertHtml(tagBegin + options + tagEnd, topNode);
}else if(rangy.getSelection().getRangeAt(0).canSurroundContents()){
var node = angular.element(tagBegin + tagEnd)[0];
rangy.getSelection().getRangeAt(0).surroundContents(node);
}
return;
}else if(command.toLowerCase() === 'inserthtml'){
taSelection.insertHtml(options, topNode);
return;
}
}
try{
$document[0].execCommand(command, showUI, options);
}catch(e){}
};
};
}]).service('taSelection', ['$window', '$document', 'taDOM',
/* istanbul ignore next: all browser specifics and PhantomJS dosen't seem to support half of it */
function($window, $document, taDOM){
// need to dereference the document else the calls don't work correctly
var _document = $document[0];
var rangy = $window.rangy;
var brException = function (element, offset) {
/* check if selection is a BR element at the beginning of a container. If so, get
* the parentNode instead.
* offset should be zero in this case. Otherwise, return the original
* element.
*/
if (element.tagName && element.tagName.match(/^br$/i) && offset === 0 && !element.previousSibling) {
return {
element: element.parentNode,
offset: 0
};
} else {
return {
element: element,
offset: offset
};
}
};
var api = {
getSelection: function(){
var range = rangy.getSelection().getRangeAt(0);
var container = range.commonAncestorContainer;
var selection = {
start: brException(range.startContainer, range.startOffset),
end: brException(range.endContainer, range.endOffset),
collapsed: range.collapsed
};
// Check if the container is a text node and return its parent if so
container = container.nodeType === 3 ? container.parentNode : container;
if (container.parentNode === selection.start.element ||
container.parentNode === selection.end.element) {
selection.container = container.parentNode;
} else {
selection.container = container;
}
return selection;
},
getOnlySelectedElements: function(){
var range = rangy.getSelection().getRangeAt(0);
var container = range.commonAncestorContainer;
// Check if the container is a text node and return its parent if so
container = container.nodeType === 3 ? container.parentNode : container;
return range.getNodes([1], function(node){
return node.parentNode === container;
});
},
// Some basic selection functions
getSelectionElement: function () {
return api.getSelection().container;
},
setSelection: function(el, start, end){
var range = rangy.createRange();
range.setStart(el, start);
range.setEnd(el, end);
rangy.getSelection().setSingleRange(range);
},
setSelectionBeforeElement: function (el){
var range = rangy.createRange();
range.selectNode(el);
range.collapse(true);
rangy.getSelection().setSingleRange(range);
},
setSelectionAfterElement: function (el){
var range = rangy.createRange();
range.selectNode(el);
range.collapse(false);
rangy.getSelection().setSingleRange(range);
},
setSelectionToElementStart: function (el){
var range = rangy.createRange();
range.selectNodeContents(el);
range.collapse(true);
rangy.getSelection().setSingleRange(range);
},
setSelectionToElementEnd: function (el){
var range = rangy.createRange();
range.selectNodeContents(el);
range.collapse(false);
if(el.childNodes && el.childNodes[el.childNodes.length - 1] && el.childNodes[el.childNodes.length - 1].nodeName === 'br'){
range.startOffset = range.endOffset = range.startOffset - 1;
}
rangy.getSelection().setSingleRange(range);
},
// from http://stackoverflow.com/questions/6690752/insert-html-at-caret-in-a-contenteditable-div
// topNode is the contenteditable normally, all manipulation MUST be inside this.
insertHtml: function(html, topNode){
var parent, secondParent, _childI, nodes, i, lastNode, _tempFrag;
var element = angular.element("<div>" + html + "</div>");
var range = rangy.getSelection().getRangeAt(0);
var frag = _document.createDocumentFragment();
var children = element[0].childNodes;
var isInline = true;
if(children.length > 0){
// NOTE!! We need to do the following:
// check for blockelements - if they exist then we have to split the current element in half (and all others up to the closest block element) and insert all children in-between.
// If there are no block elements, or there is a mixture we need to create textNodes for the non wrapped text (we don't want them spans messing up the picture).
nodes = [];
for(_childI = 0; _childI < children.length; _childI++){
if(!(
(children[_childI].nodeName.toLowerCase() === 'p' && children[_childI].innerHTML.trim() === '') || // empty p element
(children[_childI].nodeType === 3 && children[_childI].nodeValue.trim() === '') // empty text node
)){
isInline = isInline && !BLOCKELEMENTS.test(children[_childI].nodeName);
nodes.push(children[_childI]);
}
}
for(var _n = 0; _n < nodes.length; _n++) lastNode = frag.appendChild(nodes[_n]);
if(!isInline && range.collapsed && /^(|<br(|\/)>)$/i.test(range.startContainer.innerHTML)) range.selectNode(range.startContainer);
}else{
isInline = true;
// paste text of some sort
lastNode = frag = _document.createTextNode(html);
}
// Other Edge case - selected data spans multiple blocks.
if(isInline){
range.deleteContents();
}else{ // not inline insert
if(range.collapsed && range.startContainer !== topNode){
if(range.startContainer.innerHTML && range.startContainer.innerHTML.match(/^<[^>]*>$/i)){
// this log is to catch when innerHTML is something like `<img ...>`
parent = range.startContainer;
if(range.startOffset === 1){
// before single tag
range.setStartAfter(parent);
range.setEndAfter(parent);
}else{
// after single tag
range.setStartBefore(parent);
range.setEndBefore(parent);
}
}else{
// split element into 2 and insert block element in middle
if(range.startContainer.nodeType === 3 && range.startContainer.parentNode !== topNode){ // if text node
parent = range.startContainer.parentNode;
secondParent = parent.cloneNode();
// split the nodes into two lists - before and after, splitting the node with the selection into 2 text nodes.
taDOM.splitNodes(parent.childNodes, parent, secondParent, range.startContainer, range.startOffset);
// Escape out of the inline tags like b
while(!VALIDELEMENTS.test(parent.nodeName)){
angular.element(parent).after(secondParent);
parent = parent.parentNode;
var _lastSecondParent = secondParent;
secondParent = parent.cloneNode();
// split the nodes into two lists - before and after, splitting the node with the selection into 2 text nodes.
taDOM.splitNodes(parent.childNodes, parent, secondParent, _lastSecondParent);
}
}else{
parent = range.startContainer;
secondParent = parent.cloneNode();
taDOM.splitNodes(parent.childNodes, parent, secondParent, undefined, undefined, range.startOffset);
}
angular.element(parent).after(secondParent);
// put cursor to end of inserted content
range.setStartAfter(parent);
range.setEndAfter(parent);
if(/^(|<br(|\/)>)$/i.test(parent.innerHTML.trim())){
range.setStartBefore(parent);
range.setEndBefore(parent);
angular.element(parent).remove();
}
if(/^(|<br(|\/)>)$/i.test(secondParent.innerHTML.trim())) angular.element(secondParent).remove();
if(parent.nodeName.toLowerCase() === 'li'){
_tempFrag = _document.createDocumentFragment();
for(i = 0; i < frag.childNodes.length; i++){
element = angular.element('<li>');
taDOM.transferChildNodes(frag.childNodes[i], element[0]);
taDOM.transferNodeAttributes(frag.childNodes[i], element[0]);
_tempFrag.appendChild(element[0]);
}
frag = _tempFrag;
if(lastNode){
lastNode = frag.childNodes[frag.childNodes.length - 1];
lastNode = lastNode.childNodes[lastNode.childNodes.length - 1];
}
}
}
}else{
range.deleteContents();
}
}
range.insertNode(frag);
if(lastNode){
api.setSelectionToElementEnd(lastNode);
}
}
};
return api;
}]).service('taDOM', function(){
var taDOM = {
// recursive function that returns an array of angular.elements that have the passed attribute set on them
getByAttribute: function(element, attribute){
var resultingElements = [];
var childNodes = element.children();
if(childNodes.length){
angular.forEach(childNodes, function(child){
resultingElements = resultingElements.concat(taDOM.getByAttribute(angular.element(child), attribute));
});
}
if(element.attr(attribute) !== undefined) resultingElements.push(element);
return resultingElements;
},
transferChildNodes: function(source, target){
// clear out target
target.innerHTML = '';
while(source.childNodes.length > 0) target.appendChild(source.childNodes[0]);
return target;
},
splitNodes: function(nodes, target1, target2, splitNode, subSplitIndex, splitIndex){
if(!splitNode && isNaN(splitIndex)) throw new Error('taDOM.splitNodes requires a splitNode or splitIndex');
var startNodes = document.createDocumentFragment();
var endNodes = document.createDocumentFragment();
var index = 0;
while(nodes.length > 0 && (isNaN(splitIndex) || splitIndex !== index) && nodes[0] !== splitNode){
startNodes.appendChild(nodes[0]); // this removes from the nodes array (if proper childNodes object.
index++;
}
if(!isNaN(subSplitIndex) && subSplitIndex >= 0 && nodes[0]){
startNodes.appendChild(document.createTextNode(nodes[0].nodeValue.substring(0, subSplitIndex)));
nodes[0].nodeValue = nodes[0].nodeValue.substring(subSplitIndex);
}
while(nodes.length > 0) endNodes.appendChild(nodes[0]);
taDOM.transferChildNodes(startNodes, target1);
taDOM.transferChildNodes(endNodes, target2);
},
transferNodeAttributes: function(source, target){
for(var i = 0; i < source.attributes.length; i++) target.setAttribute(source.attributes[i].name, source.attributes[i].value);
return target;
}
};
return taDOM;
});
angular.module('textAngular.validators', [])
.directive('taMaxText', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ctrl){
var max = parseInt(scope.$eval(attrs.taMaxText));
if (isNaN(max)){
throw('Max text must be an integer');
}
attrs.$observe('taMaxText', function(value){
max = parseInt(value);
if (isNaN(max)){
throw('Max text must be an integer');
}
if (ctrl.$dirty){
ctrl.$validate();
}
});
ctrl.$validators.taMaxText = function(viewValue){
var source = angular.element('<div/>');
source.html(viewValue);
return source.text().length <= max;
};
}
};
}).directive('taMinText', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ctrl){
var min = parseInt(scope.$eval(attrs.taMinText));
if (isNaN(min)){
throw('Min text must be an integer');
}
attrs.$observe('taMinText', function(value){
min = parseInt(value);
if (isNaN(min)){
throw('Min text must be an integer');
}
if (ctrl.$dirty){
ctrl.$validate();
}
});
ctrl.$validators.taMinText = function(viewValue){
var source = angular.element('<div/>');
source.html(viewValue);
return !source.text().length || source.text().length >= min;
};
}
};
});
angular.module('textAngular.taBind', ['textAngular.factories', 'textAngular.DOM'])
.service('_taBlankTest', [function(){
var INLINETAGS_NONBLANK = /<(a|abbr|acronym|bdi|bdo|big|cite|code|del|dfn|img|ins|kbd|label|map|mark|q|ruby|rp|rt|s|samp|time|tt|var)[^>]*(>|$)/i;
return function(_defaultTest){
return function(_blankVal){
if(!_blankVal) return true;
// find first non-tag match - ie start of string or after tag that is not whitespace
var _firstMatch = /(^[^<]|>)[^<]/i.exec(_blankVal);
var _firstTagIndex;
if(!_firstMatch){
// find the end of the first tag removing all the
// Don't do a global replace as that would be waaayy too long, just replace the first 4 occurences should be enough
_blankVal = _blankVal.toString().replace(/="[^"]*"/i, '').replace(/="[^"]*"/i, '').replace(/="[^"]*"/i, '').replace(/="[^"]*"/i, '');
_firstTagIndex = _blankVal.indexOf('>');
}else{
_firstTagIndex = _firstMatch.index;
}
_blankVal = _blankVal.trim().substring(_firstTagIndex, _firstTagIndex + 100);
// check for no tags entry
if(/^[^<>]+$/i.test(_blankVal)) return false;
// this regex is to match any number of whitespace only between two tags
if (_blankVal.length === 0 || _blankVal === _defaultTest || /^>(\s| )*<\/[^>]+>$/ig.test(_blankVal)) return true;
// this regex tests if there is a tag followed by some optional whitespace and some text after that
else if (/>\s*[^\s<]/i.test(_blankVal) || INLINETAGS_NONBLANK.test(_blankVal)) return false;
else return true;
};
};
}])
.directive('taButton', [function(){
return {
link: function(scope, element, attrs){
element.attr('unselectable', 'on');
element.on('mousedown', function(e, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(e, eventData);
// this prevents focusout from firing on the editor when clicking toolbar buttons
e.preventDefault();
return false;
});
}
};
}])
.directive('taBind', [
'taSanitize', '$timeout', '$window', '$document', 'taFixChrome', 'taBrowserTag',
'taSelection', 'taSelectableElements', 'taApplyCustomRenderers', 'taOptions',
'_taBlankTest', '$parse', 'taDOM', 'textAngularManager',
function(
taSanitize, $timeout, $window, $document, taFixChrome, taBrowserTag,
taSelection, taSelectableElements, taApplyCustomRenderers, taOptions,
_taBlankTest, $parse, taDOM, textAngularManager){
// Uses for this are textarea or input with ng-model and ta-bind='text'
// OR any non-form element with contenteditable="contenteditable" ta-bind="html|text" ng-model
return {
priority: 2, // So we override validators correctly
require: ['ngModel','?ngModelOptions'],
link: function(scope, element, attrs, controller){
var ngModel = controller[0];
var ngModelOptions = controller[1] || {};
// the option to use taBind on an input or textarea is required as it will sanitize all input into it correctly.
var _isContentEditable = element.attr('contenteditable') !== undefined && element.attr('contenteditable');
var _isInputFriendly = _isContentEditable || element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input';
var _isReadonly = false;
var _focussed = false;
var _skipRender = false;
var _disableSanitizer = attrs.taUnsafeSanitizer || taOptions.disableSanitizer;
var _lastKey;
// see http://www.javascripter.net/faq/keycodes.htm for good information
// NOTE Mute On|Off 173 (Opera MSIE Safari Chrome) 181 (Firefox)
// BLOCKED_KEYS are special keys...
// Tab, pause/break, CapsLock, Esc, Page Up, End, Home,
// Left arrow, Up arrow, Right arrow, Down arrow, Insert, Delete,
// f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12
// NumLock, ScrollLock
var BLOCKED_KEYS = /^(9|19|20|27|33|34|35|36|37|38|39|40|45|112|113|114|115|116|117|118|119|120|121|122|123|144|145)$/i;
// UNDO_TRIGGER_KEYS - spaces, enter, delete, backspace, all punctuation
// Backspace, Enter, Space, Delete, (; :) (Firefox), (= +) (Firefox),
// Numpad +, Numpad -, (; :), (= +),
// (, <), (- _), (. >), (/ ?), (` ~), ([ {), (\ |), (] }), (' ")
// NOTE - Firefox: 173 = (- _) -- adding this to UNDO_TRIGGER_KEYS
var UNDO_TRIGGER_KEYS = /^(8|13|32|46|59|61|107|109|173|186|187|188|189|190|191|192|219|220|221|222)$/i;
var _pasteHandler;
// defaults to the paragraph element, but we need the line-break or it doesn't allow you to type into the empty element
// non IE is '<p><br/></p>', ie is '<p></p>' as for once IE gets it correct...
var _defaultVal, _defaultTest;
var _CTRL_KEY = 0x0001;
var _META_KEY = 0x0002;
var _ALT_KEY = 0x0004;
var _SHIFT_KEY = 0x0008;
// map events to special keys...
// mappings is an array of maps from events to specialKeys as declared in textAngularSetup
var _keyMappings = [
// ctrl/command + z
{
specialKey: 'UndoKey',
forbiddenModifiers: _ALT_KEY + _SHIFT_KEY,
mustHaveModifiers: [_META_KEY + _CTRL_KEY],
keyCode: 90
},
// ctrl/command + shift + z
{
specialKey: 'RedoKey',
forbiddenModifiers: _ALT_KEY,
mustHaveModifiers: [_META_KEY + _CTRL_KEY, _SHIFT_KEY],
keyCode: 90
},
// ctrl/command + y
{
specialKey: 'RedoKey',
forbiddenModifiers: _ALT_KEY + _SHIFT_KEY,
mustHaveModifiers: [_META_KEY + _CTRL_KEY],
keyCode: 89
},
// TabKey
{
specialKey: 'TabKey',
forbiddenModifiers: _META_KEY + _SHIFT_KEY + _ALT_KEY + _CTRL_KEY,
mustHaveModifiers: [],
keyCode: 9
},
// shift + TabKey
{
specialKey: 'ShiftTabKey',
forbiddenModifiers: _META_KEY + _ALT_KEY + _CTRL_KEY,
mustHaveModifiers: [_SHIFT_KEY],
keyCode: 9
}
];
function _mapKeys(event) {
var specialKey;
_keyMappings.forEach(function (map){
if (map.keyCode === event.keyCode) {
var netModifiers = (event.metaKey ? _META_KEY: 0) +
(event.ctrlKey ? _CTRL_KEY: 0) +
(event.shiftKey ? _SHIFT_KEY: 0) +
(event.altKey ? _ALT_KEY: 0);
if (map.forbiddenModifiers & netModifiers) return;
if (map.mustHaveModifiers.every(function (modifier) { return netModifiers & modifier; })){
specialKey = map.specialKey;
}
}
});
return specialKey;
}
// set the default to be a paragraph value
if(attrs.taDefaultWrap === undefined) attrs.taDefaultWrap = 'p';
/* istanbul ignore next: ie specific test */
if(attrs.taDefaultWrap === ''){
_defaultVal = '';
_defaultTest = (_browserDetect.ie === undefined)? '<div><br></div>' : (_browserDetect.ie >= 11)? '<p><br></p>' : (_browserDetect.ie <= 8)? '<P> </P>' : '<p> </p>';
}else{
_defaultVal = (_browserDetect.ie === undefined || _browserDetect.ie >= 11)?
'<' + attrs.taDefaultWrap + '><br></' + attrs.taDefaultWrap + '>' :
(_browserDetect.ie <= 8)?
'<' + attrs.taDefaultWrap.toUpperCase() + '></' + attrs.taDefaultWrap.toUpperCase() + '>' :
'<' + attrs.taDefaultWrap + '></' + attrs.taDefaultWrap + '>';
_defaultTest = (_browserDetect.ie === undefined || _browserDetect.ie >= 11)?
'<' + attrs.taDefaultWrap + '><br></' + attrs.taDefaultWrap + '>' :
(_browserDetect.ie <= 8)?
'<' + attrs.taDefaultWrap.toUpperCase() + '> </' + attrs.taDefaultWrap.toUpperCase() + '>' :
'<' + attrs.taDefaultWrap + '> </' + attrs.taDefaultWrap + '>';
}
/* istanbul ignore else */
if(!ngModelOptions.$options) ngModelOptions.$options = {}; // ng-model-options support
var _blankTest = _taBlankTest(_defaultTest);
var _ensureContentWrapped = function(value) {
if (_blankTest(value)) return value;
var domTest = angular.element("<div>" + value + "</div>");
//console.log('domTest.children().length():', domTest.children().length);
if (domTest.children().length === 0) {
value = "<" + attrs.taDefaultWrap + ">" + value + "</" + attrs.taDefaultWrap + ">";
} else {
var _children = domTest[0].childNodes;
var i;
var _foundBlockElement = false;
for (i = 0; i < _children.length; i++) {
if (_foundBlockElement = _children[i].nodeName.toLowerCase().match(BLOCKELEMENTS)) break;
}
if (!_foundBlockElement) {
value = "<" + attrs.taDefaultWrap + ">" + value + "</" + attrs.taDefaultWrap + ">";
}
else{
value = "";
for(i = 0; i < _children.length; i++){
var node = _children[i];
var nodeName = node.nodeName.toLowerCase();
//console.log(nodeName);
if(nodeName === '#comment') {
value += '<!--' + node.nodeValue + '-->';
} else if(nodeName === '#text') {
// determine if this is all whitespace, if so, we will leave it as it is.
// otherwise, we will wrap it as it is
var text = node.textContent;
if (!text.trim()) {
// just whitespace
value += text;
} else {
// not pure white space so wrap in <p>...</p> or whatever attrs.taDefaultWrap is set to.
value += "<" + attrs.taDefaultWrap + ">" + text + "</" + attrs.taDefaultWrap + ">";
}
} else if(!nodeName.match(BLOCKELEMENTS)){
/* istanbul ignore next: Doesn't seem to trigger on tests */
var _subVal = (node.outerHTML || node.nodeValue);
/* istanbul ignore else: Doesn't seem to trigger on tests, is tested though */
if(_subVal.trim() !== '')
value += "<" + attrs.taDefaultWrap + ">" + _subVal + "</" + attrs.taDefaultWrap + ">";
else value += _subVal;
} else {
value += node.outerHTML;
}
}
}
}
//console.log(value);
return value;
};
if(attrs.taPaste) _pasteHandler = $parse(attrs.taPaste);
element.addClass('ta-bind');
var _undoKeyupTimeout;
scope['$undoManager' + (attrs.id || '')] = ngModel.$undoManager = {
_stack: [],
_index: 0,
_max: 1000,
push: function(value){
if((typeof value === "undefined" || value === null) ||
((typeof this.current() !== "undefined" && this.current() !== null) && value === this.current())) return value;
if(this._index < this._stack.length - 1){
this._stack = this._stack.slice(0,this._index+1);
}
this._stack.push(value);
if(_undoKeyupTimeout) $timeout.cancel(_undoKeyupTimeout);
if(this._stack.length > this._max) this._stack.shift();
this._index = this._stack.length - 1;
return value;
},
undo: function(){
return this.setToIndex(this._index-1);
},
redo: function(){
return this.setToIndex(this._index+1);
},
setToIndex: function(index){
if(index < 0 || index > this._stack.length - 1){
return undefined;
}
this._index = index;
return this.current();
},
current: function(){
return this._stack[this._index];
}
};
var _redoUndoTimeout;
var _undo = scope['$undoTaBind' + (attrs.id || '')] = function(){
/* istanbul ignore else: can't really test it due to all changes being ignored as well in readonly */
if(!_isReadonly && _isContentEditable){
var content = ngModel.$undoManager.undo();
if(typeof content !== "undefined" && content !== null){
_setInnerHTML(content);
_setViewValue(content, false);
if(_redoUndoTimeout) $timeout.cancel(_redoUndoTimeout);
_redoUndoTimeout = $timeout(function(){
element[0].focus();
taSelection.setSelectionToElementEnd(element[0]);
}, 1);
}
}
};
var _redo = scope['$redoTaBind' + (attrs.id || '')] = function(){
/* istanbul ignore else: can't really test it due to all changes being ignored as well in readonly */
if(!_isReadonly && _isContentEditable){
var content = ngModel.$undoManager.redo();
if(typeof content !== "undefined" && content !== null){
_setInnerHTML(content);
_setViewValue(content, false);
/* istanbul ignore next */
if(_redoUndoTimeout) $timeout.cancel(_redoUndoTimeout);
_redoUndoTimeout = $timeout(function(){
element[0].focus();
taSelection.setSelectionToElementEnd(element[0]);
}, 1);
}
}
};
// in here we are undoing the converts used elsewhere to prevent the < > and & being displayed when they shouldn't in the code.
var _compileHtml = function(){
if(_isContentEditable) return element[0].innerHTML;
if(_isInputFriendly) return element.val();
throw ('textAngular Error: attempting to update non-editable taBind');
};
var _setViewValue = function(_val, triggerUndo, skipRender){
_skipRender = skipRender || false;
if(typeof triggerUndo === "undefined" || triggerUndo === null) triggerUndo = true && _isContentEditable; // if not contentEditable then the native undo/redo is fine
if(typeof _val === "undefined" || _val === null) _val = _compileHtml();
if(_blankTest(_val)){
// this avoids us from tripping the ng-pristine flag if we click in and out with out typing
if(ngModel.$viewValue !== '') ngModel.$setViewValue('');
if(triggerUndo && ngModel.$undoManager.current() !== '') ngModel.$undoManager.push('');
}else{
_reApplyOnSelectorHandlers();
if(ngModel.$viewValue !== _val){
ngModel.$setViewValue(_val);
if(triggerUndo) ngModel.$undoManager.push(_val);
}
}
ngModel.$render();
};
//used for updating when inserting wrapped elements
scope['updateTaBind' + (attrs.id || '')] = function(){
if(!_isReadonly) _setViewValue(undefined, undefined, true);
};
// catch DOM XSS via taSanitize
// Sanitizing both ways is identical
var _sanitize = function(unsafe){
return (ngModel.$oldViewValue = taSanitize(taFixChrome(unsafe), ngModel.$oldViewValue, _disableSanitizer));
};
// trigger the validation calls
if(element.attr('required')) ngModel.$validators.required = function(modelValue, viewValue) {
return !_blankTest(modelValue || viewValue);
};
// parsers trigger from the above keyup function or any other time that the viewValue is updated and parses it for storage in the ngModel
ngModel.$parsers.push(_sanitize);
ngModel.$parsers.unshift(_ensureContentWrapped);
// because textAngular is bi-directional (which is awesome) we need to also sanitize values going in from the server
ngModel.$formatters.push(_sanitize);
ngModel.$formatters.unshift(_ensureContentWrapped);
ngModel.$formatters.unshift(function(value){
return ngModel.$undoManager.push(value || '');
});
//this code is used to update the models when data is entered/deleted
if(_isInputFriendly){
scope.events = {};
if(!_isContentEditable){
// if a textarea or input just add in change and blur handlers, everything else is done by angulars input directive
element.on('change blur', scope.events.change = scope.events.blur = function(){
if(!_isReadonly) ngModel.$setViewValue(_compileHtml());
});
element.on('keydown', scope.events.keydown = function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
// Reference to http://stackoverflow.com/questions/6140632/how-to-handle-tab-in-textarea
/* istanbul ignore else: otherwise normal functionality */
if(event.keyCode === 9){ // tab was pressed
// get caret position/selection
var start = this.selectionStart;
var end = this.selectionEnd;
var value = element.val();
if(event.shiftKey){
// find \t
var _linebreak = value.lastIndexOf('\n', start), _tab = value.lastIndexOf('\t', start);
if(_tab !== -1 && _tab >= _linebreak){
// set textarea value to: text before caret + tab + text after caret
element.val(value.substring(0, _tab) + value.substring(_tab + 1));
// put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start - 1;
}
}else{
// set textarea value to: text before caret + tab + text after caret
element.val(value.substring(0, start) + "\t" + value.substring(end));
// put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start + 1;
}
// prevent the focus lose
event.preventDefault();
}
});
var _repeat = function(string, n){
var result = '';
for(var _n = 0; _n < n; _n++) result += string;
return result;
};
// add a forEach function that will work on a NodeList, etc..
var forEach = function (array, callback, scope) {
for (var i= 0; i<array.length; i++) {
callback.call(scope, i, array[i]);
}
};
// handle <ul> or <ol> nodes
var recursiveListFormat = function(listNode, tablevel){
var _html = '';
var _subnodes = listNode.childNodes;
tablevel++;
// tab out and add the <ul> or <ol> html piece
_html += _repeat('\t', tablevel-1) + listNode.outerHTML.substring(0, 4);
forEach(_subnodes, function (index, node) {
/* istanbul ignore next: browser catch */
var nodeName = node.nodeName.toLowerCase();
if (nodeName === '#comment') {
_html += '<!--' + node.nodeValue + '-->';
return;
}
if (nodeName === '#text') {
_html += node.textContent;
return;
}
/* istanbul ignore next: not tested, and this was original code -- so not wanting to possibly cause an issue, leaving it... */
if(!node.outerHTML) {
// no html to add
return;
}
if(nodeName === 'ul' || nodeName === 'ol') {
_html += '\n' + recursiveListFormat(node, tablevel);
}
else {
// no reformatting within this subnode, so just do the tabing...
_html += '\n' + _repeat('\t', tablevel) + node.outerHTML;
}
});
// now add on the </ol> or </ul> piece
_html += '\n' + _repeat('\t', tablevel-1) + listNode.outerHTML.substring(listNode.outerHTML.lastIndexOf('<'));
return _html;
};
// handle formating of something like:
// <ol><!--First comment-->
// <li>Test Line 1<!--comment test list 1--></li>
// <ul><!--comment ul-->
// <li>Nested Line 1</li>
// <!--comment between nested lines--><li>Nested Line 2</li>
// </ul>
// <li>Test Line 3</li>
// </ol>
ngModel.$formatters.unshift(function(htmlValue){
// tabulate the HTML so it looks nicer
//
// first get a list of the nodes...
// we do this by using the element parser...
//
// doing this -- which is simpiler -- breaks our tests...
//var _nodes=angular.element(htmlValue);
var _nodes = angular.element('<div>' + htmlValue + '</div>')[0].childNodes;
if(_nodes.length > 0){
// do the reformatting of the layout...
htmlValue = '';
forEach(_nodes, function (index, node) {
var nodeName = node.nodeName.toLowerCase();
if (nodeName === '#comment') {
htmlValue += '<!--' + node.nodeValue + '-->';
return;
}
if (nodeName === '#text') {
htmlValue += node.textContent;
return;
}
/* istanbul ignore next: not tested, and this was original code -- so not wanting to possibly cause an issue, leaving it... */
if(!node.outerHTML)
{
// nothing to format!
return;
}
if(htmlValue.length > 0) {
// we aready have some content, so drop to a new line
htmlValue += '\n';
}
if(nodeName === 'ul' || nodeName === 'ol') {
// okay a set of list stuff we want to reformat in a nested way
htmlValue += '' + recursiveListFormat(node, 0);
}
else {
// just use the original without any additional formating
htmlValue += '' + node.outerHTML;
}
});
}
return htmlValue;
});
}else{
// all the code specific to contenteditable divs
var _processingPaste = false;
/* istanbul ignore next: phantom js cannot test this for some reason */
var processpaste = function(text) {
/* istanbul ignore else: don't care if nothing pasted */
if(text && text.trim().length){
// test paste from word/microsoft product
if(text.match(/class=["']*Mso(Normal|List)/i) || text.match(/content=["']*Word.Document/i)){
var textFragment = text.match(/<!--StartFragment-->([\s\S]*?)<!--EndFragment-->/i);
if(!textFragment) textFragment = text;
else textFragment = textFragment[1];
textFragment = textFragment.replace(/<o:p>[\s\S]*?<\/o:p>/ig, '').replace(/class=(["']|)MsoNormal(["']|)/ig, '');
var dom = angular.element("<div>" + textFragment + "</div>");
var targetDom = angular.element("<div></div>");
var _list = {
element: null,
lastIndent: [],
lastLi: null,
isUl: false
};
_list.lastIndent.peek = function(){
var n = this.length;
if (n>0) return this[n-1];
};
var _resetList = function(isUl){
_list.isUl = isUl;
_list.element = angular.element(isUl ? "<ul>" : "<ol>");
_list.lastIndent = [];
_list.lastIndent.peek = function(){
var n = this.length;
if (n>0) return this[n-1];
};
_list.lastLevelMatch = null;
};
for(var i = 0; i <= dom[0].childNodes.length; i++){
if(!dom[0].childNodes[i] || dom[0].childNodes[i].nodeName === "#text"){
continue;
} else {
var tagName = dom[0].childNodes[i].tagName.toLowerCase();
if(tagName !== "p" && tagName !== "h1" && tagName !== "h2" && tagName !== "h3" && tagName !== "h4" && tagName !== "h5" && tagName !== "h6"){
continue;
}
}
var el = angular.element(dom[0].childNodes[i]);
var _listMatch = (el.attr('class') || '').match(/MsoList(Bullet|Number|Paragraph)(CxSp(First|Middle|Last)|)/i);
if(_listMatch){
if(el[0].childNodes.length < 2 || el[0].childNodes[1].childNodes.length < 1){
continue;
}
var isUl = _listMatch[1].toLowerCase() === "bullet" || (_listMatch[1].toLowerCase() !== "number" && !(/^[^0-9a-z<]*[0-9a-z]+[^0-9a-z<>]</i.test(el[0].childNodes[1].innerHTML) || /^[^0-9a-z<]*[0-9a-z]+[^0-9a-z<>]</i.test(el[0].childNodes[1].childNodes[0].innerHTML)));
var _indentMatch = (el.attr('style') || '').match(/margin-left:([\-\.0-9]*)/i);
var indent = parseFloat((_indentMatch)?_indentMatch[1]:0);
var _levelMatch = (el.attr('style') || '').match(/mso-list:l([0-9]+) level([0-9]+) lfo[0-9+]($|;)/i);
// prefers the mso-list syntax
if(_levelMatch && _levelMatch[2]) indent = parseInt(_levelMatch[2]);
if ((_levelMatch && (!_list.lastLevelMatch || _levelMatch[1] !== _list.lastLevelMatch[1])) || !_listMatch[3] || _listMatch[3].toLowerCase() === "first" || (_list.lastIndent.peek() === null) || (_list.isUl !== isUl && _list.lastIndent.peek() === indent)) {
_resetList(isUl);
targetDom.append(_list.element);
} else if (_list.lastIndent.peek() != null && _list.lastIndent.peek() < indent){
_list.element = angular.element(isUl ? "<ul>" : "<ol>");
_list.lastLi.append(_list.element);
} else if (_list.lastIndent.peek() != null && _list.lastIndent.peek() > indent){
while(_list.lastIndent.peek() != null && _list.lastIndent.peek() > indent){
if(_list.element.parent()[0].tagName.toLowerCase() === 'li'){
_list.element = _list.element.parent();
continue;
}else if(/[uo]l/i.test(_list.element.parent()[0].tagName.toLowerCase())){
_list.element = _list.element.parent();
}else{ // else it's it should be a sibling
break;
}
_list.lastIndent.pop();
}
_list.isUl = _list.element[0].tagName.toLowerCase() === "ul";
if (isUl !== _list.isUl) {
_resetList(isUl);
targetDom.append(_list.element);
}
}
_list.lastLevelMatch = _levelMatch;
if(indent !== _list.lastIndent.peek()) _list.lastIndent.push(indent);
_list.lastLi = angular.element("<li>");
_list.element.append(_list.lastLi);
_list.lastLi.html(el.html().replace(/<!(--|)\[if !supportLists\](--|)>[\s\S]*?<!(--|)\[endif\](--|)>/ig, ''));
el.remove();
}else{
_resetList(false);
targetDom.append(el);
}
}
var _unwrapElement = function(node){
node = angular.element(node);
for(var _n = node[0].childNodes.length - 1; _n >= 0; _n--) node.after(node[0].childNodes[_n]);
node.remove();
};
angular.forEach(targetDom.find('span'), function(node){
node.removeAttribute('lang');
if(node.attributes.length <= 0) _unwrapElement(node);
});
angular.forEach(targetDom.find('font'), _unwrapElement);
text = targetDom.html();
}else{
// remove unnecessary chrome insert
text = text.replace(/<(|\/)meta[^>]*?>/ig, '');
if(text.match(/<[^>]*?(ta-bind)[^>]*?>/)){
// entire text-angular or ta-bind has been pasted, REMOVE AT ONCE!!
if(text.match(/<[^>]*?(text-angular)[^>]*?>/)){
var _el = angular.element("<div>" + text + "</div>");
_el.find('textarea').remove();
var binds = taDOM.getByAttribute(_el, 'ta-bind');
for(var _b = 0; _b < binds.length; _b++){
var _target = binds[_b][0].parentNode.parentNode;
for(var _c = 0; _c < binds[_b][0].childNodes.length; _c++){
_target.parentNode.insertBefore(binds[_b][0].childNodes[_c], _target);
}
_target.parentNode.removeChild(_target);
}
text = _el.html().replace('<br class="Apple-interchange-newline">', '');
}
}else if(text.match(/^<span/)){
// in case of pasting only a span - chrome paste, remove them. THis is just some wierd formatting
// if we remove the '<span class="Apple-converted-space"> </span>' here we destroy the spacing
// on paste from even ourselves!
if (!text.match(/<span class=(\"Apple-converted-space\"|\'Apple-converted-space\')>.<\/span>/ig)) {
text = text.replace(/<(|\/)span[^>]*?>/ig, '');
}
}
// Webkit on Apple tags
text = text.replace(/<br class="Apple-interchange-newline"[^>]*?>/ig, '').replace(/<span class="Apple-converted-space">( | )<\/span>/ig, ' ');
}
if (/<li(\s.*)?>/i.test(text) && /(<ul(\s.*)?>|<ol(\s.*)?>).*<li(\s.*)?>/i.test(text) === false) {
// insert missing parent of li element
text = text.replace(/<li(\s.*)?>.*<\/li(\s.*)?>/i, '<ul>$&</ul>');
}
// parse whitespace from plaintext input, starting with preceding spaces that get stripped on paste
text = text.replace(/^[ |\u00A0]+/gm, function (match) {
var result = '';
for (var i = 0; i < match.length; i++) {
result += ' ';
}
return result;
}).replace(/\n|\r\n|\r/g, '<br />').replace(/\t/g, ' ');
if(_pasteHandler) text = _pasteHandler(scope, {$html: text}) || text;
text = taSanitize(text, '', _disableSanitizer);
taSelection.insertHtml(text, element[0]);
$timeout(function(){
ngModel.$setViewValue(_compileHtml());
_processingPaste = false;
element.removeClass('processing-paste');
}, 0);
}else{
_processingPaste = false;
element.removeClass('processing-paste');
}
};
element.on('paste', scope.events.paste = function(e, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(e, eventData);
if(_isReadonly || _processingPaste){
e.stopPropagation();
e.preventDefault();
return false;
}
// Code adapted from http://stackoverflow.com/questions/2176861/javascript-get-clipboard-data-on-paste-event-cross-browser/6804718#6804718
_processingPaste = true;
element.addClass('processing-paste');
var pastedContent;
var clipboardData = (e.originalEvent || e).clipboardData;
if (clipboardData && clipboardData.getData && clipboardData.types.length > 0) {// Webkit - get data from clipboard, put into editdiv, cleanup, then cancel event
var _types = "";
for(var _t = 0; _t < clipboardData.types.length; _t++){
_types += " " + clipboardData.types[_t];
}
/* istanbul ignore next: browser tests */
if (/text\/html/i.test(_types)) {
pastedContent = clipboardData.getData('text/html');
} else if (/text\/plain/i.test(_types)) {
pastedContent = clipboardData.getData('text/plain');
}
processpaste(pastedContent);
e.stopPropagation();
e.preventDefault();
return false;
} else {// Everything else - empty editdiv and allow browser to paste content into it, then cleanup
var _savedSelection = $window.rangy.saveSelection(),
_tempDiv = angular.element('<div class="ta-hidden-input" contenteditable="true"></div>');
$document.find('body').append(_tempDiv);
_tempDiv[0].focus();
$timeout(function(){
// restore selection
$window.rangy.restoreSelection(_savedSelection);
processpaste(_tempDiv[0].innerHTML);
element[0].focus();
_tempDiv.remove();
}, 0);
}
});
element.on('cut', scope.events.cut = function(e){
// timeout to next is needed as otherwise the paste/cut event has not finished actually changing the display
if(!_isReadonly) $timeout(function(){
ngModel.$setViewValue(_compileHtml());
}, 0);
else e.preventDefault();
});
element.on('keydown', scope.events.keydown = function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
event.specialKey = _mapKeys(event);
var userSpecialKey;
/* istanbul ignore next: difficult to test */
taOptions.keyMappings.forEach(function (mapping) {
if (event.specialKey === mapping.commandKeyCode) {
// taOptions has remapped this binding... so
// we disable our own
event.specialKey = undefined;
}
if (mapping.testForKey(event)) {
userSpecialKey = mapping.commandKeyCode;
}
if ((mapping.commandKeyCode === 'UndoKey') || (mapping.commandKeyCode === 'RedoKey')) {
// this is necessary to fully stop the propagation.
if (!mapping.enablePropagation) {
event.preventDefault();
}
}
});
/* istanbul ignore next: difficult to test */
if (typeof userSpecialKey !== 'undefined') {
event.specialKey = userSpecialKey;
}
/* istanbul ignore next: difficult to test as can't seem to select */
if ((typeof event.specialKey !== 'undefined') && (
event.specialKey !== 'UndoKey' || event.specialKey !== 'RedoKey'
)) {
event.preventDefault();
textAngularManager.sendKeyCommand(scope, event);
}
/* istanbul ignore else: readonly check */
if(!_isReadonly){
if (event.specialKey==='UndoKey') {
_undo();
event.preventDefault();
}
if (event.specialKey==='RedoKey') {
_redo();
event.preventDefault();
}
/* istanbul ignore next: difficult to test as can't seem to select */
if(event.keyCode === 13 && !event.shiftKey){
var contains = function(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
};
var $selection;
var selection = taSelection.getSelectionElement();
if(!selection.tagName.match(VALIDELEMENTS)) return;
var _new = angular.element(_defaultVal);
// if we are in the last element of a blockquote, or ul or ol and the element is blank
// we need to pull the element outside of the said type
var moveOutsideElements = ['blockquote', 'ul', 'ol'];
if (contains(moveOutsideElements, selection.parentNode.tagName.toLowerCase())) {
if (/^<br(|\/)>$/i.test(selection.innerHTML.trim()) && !selection.nextSibling) {
// if last element is blank, pull element outside.
$selection = angular.element(selection);
var _parent = $selection.parent();
_parent.after(_new);
$selection.remove();
if (_parent.children().length === 0) _parent.remove();
taSelection.setSelectionToElementStart(_new[0]);
event.preventDefault();
}
if (/^<[^>]+><br(|\/)><\/[^>]+>$/i.test(selection.innerHTML.trim())) {
$selection = angular.element(selection);
$selection.after(_new);
$selection.remove();
taSelection.setSelectionToElementStart(_new[0]);
event.preventDefault();
}
}
}
}
});
var _keyupTimeout;
element.on('keyup', scope.events.keyup = function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
/* istanbul ignore next: FF specific bug fix */
if (event.keyCode === 9) {
var _selection = taSelection.getSelection();
if(_selection.start.element === element[0] && element.children().length) taSelection.setSelectionToElementStart(element.children()[0]);
return;
}
if(_undoKeyupTimeout) $timeout.cancel(_undoKeyupTimeout);
if(!_isReadonly && !BLOCKED_KEYS.test(event.keyCode)){
// if enter - insert new taDefaultWrap, if shift+enter insert <br/>
if(_defaultVal !== '' && event.keyCode === 13){
if(!event.shiftKey){
// new paragraph, br should be caught correctly
var selection = taSelection.getSelectionElement();
while(!selection.tagName.match(VALIDELEMENTS) && selection !== element[0]){
selection = selection.parentNode;
}
if(selection.tagName.toLowerCase() !== attrs.taDefaultWrap && selection.tagName.toLowerCase() !== 'li' && (selection.innerHTML.trim() === '' || selection.innerHTML.trim() === '<br>')){
var _new = angular.element(_defaultVal);
angular.element(selection).replaceWith(_new);
taSelection.setSelectionToElementStart(_new[0]);
}
}
}
var val = _compileHtml();
if(_defaultVal !== '' && val.trim() === ''){
_setInnerHTML(_defaultVal);
taSelection.setSelectionToElementStart(element.children()[0]);
}else if(val.substring(0, 1) !== '<' && attrs.taDefaultWrap !== ''){
/* we no longer do this, since there can be comments here and white space
var _savedSelection = $window.rangy.saveSelection();
val = _compileHtml();
val = "<" + attrs.taDefaultWrap + ">" + val + "</" + attrs.taDefaultWrap + ">";
_setInnerHTML(val);
$window.rangy.restoreSelection(_savedSelection);
*/
}
var triggerUndo = _lastKey !== event.keyCode && UNDO_TRIGGER_KEYS.test(event.keyCode);
if(_keyupTimeout) $timeout.cancel(_keyupTimeout);
_keyupTimeout = $timeout(function() {
_setViewValue(val, triggerUndo, true);
}, ngModelOptions.$options.debounce || 400);
if(!triggerUndo) _undoKeyupTimeout = $timeout(function(){ ngModel.$undoManager.push(val); }, 250);
_lastKey = event.keyCode;
}
});
element.on('blur', scope.events.blur = function(){
_focussed = false;
/* istanbul ignore else: if readonly don't update model */
if(!_isReadonly){
_setViewValue(undefined, undefined, true);
}else{
_skipRender = true; // don't redo the whole thing, just check the placeholder logic
ngModel.$render();
}
});
// Placeholders not supported on ie 8 and below
if(attrs.placeholder && (_browserDetect.ie > 8 || _browserDetect.ie === undefined)){
var rule;
if(attrs.id) rule = addCSSRule('#' + attrs.id + '.placeholder-text:before', 'content: "' + attrs.placeholder + '"');
else throw('textAngular Error: An unique ID is required for placeholders to work');
scope.$on('$destroy', function(){
removeCSSRule(rule);
});
}
element.on('focus', scope.events.focus = function(){
_focussed = true;
element.removeClass('placeholder-text');
_reApplyOnSelectorHandlers();
});
element.on('mouseup', scope.events.mouseup = function(){
var _selection = taSelection.getSelection();
if(_selection.start.element === element[0] && element.children().length) taSelection.setSelectionToElementStart(element.children()[0]);
});
// prevent propagation on mousedown in editor, see #206
element.on('mousedown', scope.events.mousedown = function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
event.stopPropagation();
});
}
}
var selectorClickHandler = function(event){
// emit the element-select event, pass the element
scope.$emit('ta-element-select', this);
event.preventDefault();
return false;
};
var fileDropHandler = function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
// emit the drop event, pass the element, preventing should be done elsewhere
if(!dropFired && !_isReadonly){
dropFired = true;
var dataTransfer;
if(event.originalEvent) dataTransfer = event.originalEvent.dataTransfer;
else dataTransfer = event.dataTransfer;
scope.$emit('ta-drop-event', this, event, dataTransfer);
$timeout(function(){
dropFired = false;
_setViewValue(undefined, undefined, true);
}, 100);
}
};
//used for updating when inserting wrapped elements
var _reApplyOnSelectorHandlers = scope['reApplyOnSelectorHandlers' + (attrs.id || '')] = function(){
/* istanbul ignore else */
if(!_isReadonly) angular.forEach(taSelectableElements, function(selector){
// check we don't apply the handler twice
element.find(selector)
.off('click', selectorClickHandler)
.on('click', selectorClickHandler);
});
};
var _setInnerHTML = function(newval){
element[0].innerHTML = newval;
};
var _renderTimeout;
var _renderInProgress = false;
// changes to the model variable from outside the html/text inputs
ngModel.$render = function(){
/* istanbul ignore if: Catches rogue renders, hard to replicate in tests */
if(_renderInProgress) return;
else _renderInProgress = true;
// catch model being null or undefined
var val = ngModel.$viewValue || '';
// if the editor isn't focused it needs to be updated, otherwise it's receiving user input
if(!_skipRender){
/* istanbul ignore else: in other cases we don't care */
if(_isContentEditable && _focussed){
// update while focussed
element.removeClass('placeholder-text');
if(_renderTimeout) $timeout.cancel(_renderTimeout);
_renderTimeout = $timeout(function(){
/* istanbul ignore if: Can't be bothered testing this... */
if(!_focussed){
element[0].focus();
taSelection.setSelectionToElementEnd(element.children()[element.children().length - 1]);
}
_renderTimeout = undefined;
}, 1);
}
if(_isContentEditable){
// WYSIWYG Mode
if(attrs.placeholder){
if(val === ''){
// blank
_setInnerHTML(_defaultVal);
}else{
// not-blank
_setInnerHTML(val);
}
}else{
_setInnerHTML((val === '') ? _defaultVal : val);
}
// if in WYSIWYG and readOnly we kill the use of links by clicking
if(!_isReadonly){
_reApplyOnSelectorHandlers();
element.on('drop', fileDropHandler);
}else{
element.off('drop', fileDropHandler);
}
}else if(element[0].tagName.toLowerCase() !== 'textarea' && element[0].tagName.toLowerCase() !== 'input'){
// make sure the end user can SEE the html code as a display. This is a read-only display element
_setInnerHTML(taApplyCustomRenderers(val));
}else{
// only for input and textarea inputs
element.val(val);
}
}
if(_isContentEditable && attrs.placeholder){
if(val === ''){
if(_focussed) element.removeClass('placeholder-text');
else element.addClass('placeholder-text');
}else{
element.removeClass('placeholder-text');
}
}
_renderInProgress = _skipRender = false;
};
if(attrs.taReadonly){
//set initial value
_isReadonly = scope.$eval(attrs.taReadonly);
if(_isReadonly){
element.addClass('ta-readonly');
// we changed to readOnly mode (taReadonly='true')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.attr('disabled', 'disabled');
}
if(element.attr('contenteditable') !== undefined && element.attr('contenteditable')){
element.removeAttr('contenteditable');
}
}else{
element.removeClass('ta-readonly');
// we changed to NOT readOnly mode (taReadonly='false')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.removeAttr('disabled');
}else if(_isContentEditable){
element.attr('contenteditable', 'true');
}
}
// taReadonly only has an effect if the taBind element is an input or textarea or has contenteditable='true' on it.
// Otherwise it is readonly by default
scope.$watch(attrs.taReadonly, function(newVal, oldVal){
if(oldVal === newVal) return;
if(newVal){
element.addClass('ta-readonly');
// we changed to readOnly mode (taReadonly='true')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.attr('disabled', 'disabled');
}
if(element.attr('contenteditable') !== undefined && element.attr('contenteditable')){
element.removeAttr('contenteditable');
}
// turn ON selector click handlers
angular.forEach(taSelectableElements, function(selector){
element.find(selector).on('click', selectorClickHandler);
});
element.off('drop', fileDropHandler);
}else{
element.removeClass('ta-readonly');
// we changed to NOT readOnly mode (taReadonly='false')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.removeAttr('disabled');
}else if(_isContentEditable){
element.attr('contenteditable', 'true');
}
// remove the selector click handlers
angular.forEach(taSelectableElements, function(selector){
element.find(selector).off('click', selectorClickHandler);
});
element.on('drop', fileDropHandler);
}
_isReadonly = newVal;
});
}
// Initialise the selectableElements
// if in WYSIWYG and readOnly we kill the use of links by clicking
if(_isContentEditable && !_isReadonly){
angular.forEach(taSelectableElements, function(selector){
element.find(selector).on('click', selectorClickHandler);
});
element.on('drop', fileDropHandler);
element.on('blur', function(){
/* istanbul ignore next: webkit fix */
if(_browserDetect.webkit) { // detect webkit
globalContentEditableBlur = true;
}
});
}
}
};
}]);
// this global var is used to prevent multiple fires of the drop event. Needs to be global to the textAngular file.
var dropFired = false;
var textAngular = angular.module("textAngular", ['ngSanitize', 'textAngularSetup', 'textAngular.factories', 'textAngular.DOM', 'textAngular.validators', 'textAngular.taBind']); //This makes ngSanitize required
textAngular.config([function(){
// clear taTools variable. Just catches testing and any other time that this config may run multiple times...
angular.forEach(taTools, function(value, key){ delete taTools[key]; });
}]);
textAngular.run([function(){
/* istanbul ignore next: not sure how to test this */
// Require Rangy and rangy savedSelection module.
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(function(require) {
window.rangy = require('rangy');
window.rangy.saveSelection = require('rangy/lib/rangy-selectionsaverestore');
});
} else if (typeof require ==='function' && typeof module !== 'undefined' && typeof exports === 'object') {
// Node/CommonJS style
window.rangy = require('rangy');
window.rangy.saveSelection = require('rangy/lib/rangy-selectionsaverestore');
} else {
// Ensure that rangy and rangy.saveSelection exists on the window (global scope).
// TODO: Refactor so that the global scope is no longer used.
if(!window.rangy){
throw("rangy-core.js and rangy-selectionsaverestore.js are required for textAngular to work correctly, rangy-core is not yet loaded.");
}else{
window.rangy.init();
if(!window.rangy.saveSelection){
throw("rangy-selectionsaverestore.js is required for textAngular to work correctly.");
}
}
}
}]);
textAngular.directive("textAngular", [
'$compile', '$timeout', 'taOptions', 'taSelection', 'taExecCommand',
'textAngularManager', '$window', '$document', '$animate', '$log', '$q', '$parse',
function($compile, $timeout, taOptions, taSelection, taExecCommand,
textAngularManager, $window, $document, $animate, $log, $q, $parse){
return {
require: '?ngModel',
scope: {},
restrict: "EA",
priority: 2, // So we override validators correctly
link: function(scope, element, attrs, ngModel){
// all these vars should not be accessable outside this directive
var _keydown, _keyup, _keypress, _mouseup, _focusin, _focusout,
_originalContents, _toolbars,
_serial = (attrs.serial) ? attrs.serial : Math.floor(Math.random() * 10000000000000000),
_taExecCommand, _resizeMouseDown, _updateSelectedStylesTimeout;
scope._name = (attrs.name) ? attrs.name : 'textAngularEditor' + _serial;
var oneEvent = function(_element, event, action){
$timeout(function(){
// shim the .one till fixed
var _func = function(){
_element.off(event, _func);
action.apply(this, arguments);
};
_element.on(event, _func);
}, 100);
};
_taExecCommand = taExecCommand(attrs.taDefaultWrap);
// get the settings from the defaults and add our specific functions that need to be on the scope
angular.extend(scope, angular.copy(taOptions), {
// wraps the selection in the provided tag / execCommand function. Should only be called in WYSIWYG mode.
wrapSelection: function(command, opt, isSelectableElementTool){
if(command.toLowerCase() === "undo"){
scope['$undoTaBindtaTextElement' + _serial]();
}else if(command.toLowerCase() === "redo"){
scope['$redoTaBindtaTextElement' + _serial]();
}else{
// catch errors like FF erroring when you try to force an undo with nothing done
_taExecCommand(command, false, opt, scope.defaultTagAttributes);
if(isSelectableElementTool){
// re-apply the selectable tool events
scope['reApplyOnSelectorHandlerstaTextElement' + _serial]();
}
// refocus on the shown display element, this fixes a display bug when using :focus styles to outline the box.
// You still have focus on the text/html input it just doesn't show up
scope.displayElements.text[0].focus();
}
},
showHtml: scope.$eval(attrs.taShowHtml) || false
});
// setup the options from the optional attributes
if(attrs.taFocussedClass) scope.classes.focussed = attrs.taFocussedClass;
if(attrs.taTextEditorClass) scope.classes.textEditor = attrs.taTextEditorClass;
if(attrs.taHtmlEditorClass) scope.classes.htmlEditor = attrs.taHtmlEditorClass;
if(attrs.taDefaultTagAttributes){
try {
// TODO: This should use angular.merge to enhance functionality once angular 1.4 is required
angular.extend(scope.defaultTagAttributes, angular.fromJson(attrs.taDefaultTagAttributes));
} catch (error) {
$log.error(error);
}
}
// optional setup functions
if(attrs.taTextEditorSetup) scope.setup.textEditorSetup = scope.$parent.$eval(attrs.taTextEditorSetup);
if(attrs.taHtmlEditorSetup) scope.setup.htmlEditorSetup = scope.$parent.$eval(attrs.taHtmlEditorSetup);
// optional fileDropHandler function
if(attrs.taFileDrop) scope.fileDropHandler = scope.$parent.$eval(attrs.taFileDrop);
else scope.fileDropHandler = scope.defaultFileDropHandler;
_originalContents = element[0].innerHTML;
// clear the original content
element[0].innerHTML = '';
// Setup the HTML elements as variable references for use later
scope.displayElements = {
// we still need the hidden input even with a textarea as the textarea may have invalid/old input in it,
// wheras the input will ALLWAYS have the correct value.
forminput: angular.element("<input type='hidden' tabindex='-1' style='display: none;'>"),
html: angular.element("<textarea></textarea>"),
text: angular.element("<div></div>"),
// other toolbased elements
scrollWindow: angular.element("<div class='ta-scroll-window'></div>"),
popover: angular.element('<div class="popover fade bottom" style="max-width: none; width: 305px;"></div>'),
popoverArrow: angular.element('<div class="arrow"></div>'),
popoverContainer: angular.element('<div class="popover-content"></div>'),
resize: {
overlay: angular.element('<div class="ta-resizer-handle-overlay"></div>'),
background: angular.element('<div class="ta-resizer-handle-background"></div>'),
anchors: [
angular.element('<div class="ta-resizer-handle-corner ta-resizer-handle-corner-tl"></div>'),
angular.element('<div class="ta-resizer-handle-corner ta-resizer-handle-corner-tr"></div>'),
angular.element('<div class="ta-resizer-handle-corner ta-resizer-handle-corner-bl"></div>'),
angular.element('<div class="ta-resizer-handle-corner ta-resizer-handle-corner-br"></div>')
],
info: angular.element('<div class="ta-resizer-handle-info"></div>')
}
};
// Setup the popover
scope.displayElements.popover.append(scope.displayElements.popoverArrow);
scope.displayElements.popover.append(scope.displayElements.popoverContainer);
scope.displayElements.scrollWindow.append(scope.displayElements.popover);
scope.displayElements.popover.on('mousedown', function(e, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(e, eventData);
// this prevents focusout from firing on the editor when clicking anything in the popover
e.preventDefault();
return false;
});
// define the popover show and hide functions
scope.showPopover = function(_el){
scope.displayElements.popover.css('display', 'block');
scope.reflowPopover(_el);
$animate.addClass(scope.displayElements.popover, 'in');
oneEvent($document.find('body'), 'click keyup', function(){scope.hidePopover();});
};
scope.reflowPopover = function(_el){
/* istanbul ignore if: catches only if near bottom of editor */
if(scope.displayElements.text[0].offsetHeight - 51 > _el[0].offsetTop){
scope.displayElements.popover.css('top', _el[0].offsetTop + _el[0].offsetHeight + scope.displayElements.scrollWindow[0].scrollTop + 'px');
scope.displayElements.popover.removeClass('top').addClass('bottom');
}else{
scope.displayElements.popover.css('top', _el[0].offsetTop - 54 + scope.displayElements.scrollWindow[0].scrollTop + 'px');
scope.displayElements.popover.removeClass('bottom').addClass('top');
}
var _maxLeft = scope.displayElements.text[0].offsetWidth - scope.displayElements.popover[0].offsetWidth;
var _targetLeft = _el[0].offsetLeft + (_el[0].offsetWidth / 2.0) - (scope.displayElements.popover[0].offsetWidth / 2.0);
scope.displayElements.popover.css('left', Math.max(0, Math.min(_maxLeft, _targetLeft)) + 'px');
scope.displayElements.popoverArrow.css('margin-left', (Math.min(_targetLeft, (Math.max(0, _targetLeft - _maxLeft))) - 11) + 'px');
};
scope.hidePopover = function(){
scope.displayElements.popover.css('display', '');
scope.displayElements.popoverContainer.attr('style', '');
scope.displayElements.popoverContainer.attr('class', 'popover-content');
scope.displayElements.popover.removeClass('in');
};
// setup the resize overlay
scope.displayElements.resize.overlay.append(scope.displayElements.resize.background);
angular.forEach(scope.displayElements.resize.anchors, function(anchor){ scope.displayElements.resize.overlay.append(anchor);});
scope.displayElements.resize.overlay.append(scope.displayElements.resize.info);
scope.displayElements.scrollWindow.append(scope.displayElements.resize.overlay);
// define the show and hide events
scope.reflowResizeOverlay = function(_el){
_el = angular.element(_el)[0];
scope.displayElements.resize.overlay.css({
'display': 'block',
'left': _el.offsetLeft - 5 + 'px',
'top': _el.offsetTop - 5 + 'px',
'width': _el.offsetWidth + 10 + 'px',
'height': _el.offsetHeight + 10 + 'px'
});
scope.displayElements.resize.info.text(_el.offsetWidth + ' x ' + _el.offsetHeight);
};
/* istanbul ignore next: pretty sure phantomjs won't test this */
scope.showResizeOverlay = function(_el){
var _body = $document.find('body');
_resizeMouseDown = function(event){
var startPosition = {
width: parseInt(_el.attr('width')),
height: parseInt(_el.attr('height')),
x: event.clientX,
y: event.clientY
};
if(startPosition.width === undefined || isNaN(startPosition.width)) startPosition.width = _el[0].offsetWidth;
if(startPosition.height === undefined || isNaN(startPosition.height)) startPosition.height = _el[0].offsetHeight;
scope.hidePopover();
var ratio = startPosition.height / startPosition.width;
var mousemove = function(event){
// calculate new size
var pos = {
x: Math.max(0, startPosition.width + (event.clientX - startPosition.x)),
y: Math.max(0, startPosition.height + (event.clientY - startPosition.y))
};
// DEFAULT: the aspect ratio is not locked unless the Shift key is pressed.
//
// attribute: ta-resize-force-aspect-ratio -- locks resize into maintaing the aspect ratio
var bForceAspectRatio = (attrs.taResizeForceAspectRatio !== undefined);
// attribute: ta-resize-maintain-aspect-ratio=true causes the space ratio to remain locked
// unless the Shift key is pressed
var bFlipKeyBinding = attrs.taResizeMaintainAspectRatio;
var bKeepRatio = bForceAspectRatio || (bFlipKeyBinding && !event.shiftKey);
if(bKeepRatio) {
var newRatio = pos.y / pos.x;
pos.x = ratio > newRatio ? pos.x : pos.y / ratio;
pos.y = ratio > newRatio ? pos.x * ratio : pos.y;
}
var el = angular.element(_el);
function roundedMaxVal(val) {
return Math.round(Math.max(0, val));
}
el.css('height', roundedMaxVal(pos.y) + 'px');
el.css('width', roundedMaxVal(pos.x) + 'px');
// reflow the popover tooltip
scope.reflowResizeOverlay(_el);
};
_body.on('mousemove', mousemove);
oneEvent(_body, 'mouseup', function(event){
event.preventDefault();
event.stopPropagation();
_body.off('mousemove', mousemove);
// at this point, we need to force the model to update! since the css has changed!
// this fixes bug: #862 - we now hide the popover -- as this seems more consitent.
// there are still issues under firefox, the window does not repaint. -- not sure
// how best to resolve this, but clicking anywhere works.
scope.$apply(function (){
scope.hidePopover();
scope.updateTaBindtaTextElement();
}, 100);
});
event.stopPropagation();
event.preventDefault();
};
scope.displayElements.resize.anchors[3].off('mousedown');
scope.displayElements.resize.anchors[3].on('mousedown', _resizeMouseDown);
scope.reflowResizeOverlay(_el);
oneEvent(_body, 'click', function(){scope.hideResizeOverlay();});
};
/* istanbul ignore next: pretty sure phantomjs won't test this */
scope.hideResizeOverlay = function(){
scope.displayElements.resize.anchors[3].off('mousedown', _resizeMouseDown);
scope.displayElements.resize.overlay.css('display', '');
};
// allow for insertion of custom directives on the textarea and div
scope.setup.htmlEditorSetup(scope.displayElements.html);
scope.setup.textEditorSetup(scope.displayElements.text);
scope.displayElements.html.attr({
'id': 'taHtmlElement' + _serial,
'ng-show': 'showHtml',
'ta-bind': 'ta-bind',
'ng-model': 'html',
'ng-model-options': element.attr('ng-model-options')
});
scope.displayElements.text.attr({
'id': 'taTextElement' + _serial,
'contentEditable': 'true',
'ta-bind': 'ta-bind',
'ng-model': 'html',
'ng-model-options': element.attr('ng-model-options')
});
scope.displayElements.scrollWindow.attr({'ng-hide': 'showHtml'});
if(attrs.taDefaultWrap) scope.displayElements.text.attr('ta-default-wrap', attrs.taDefaultWrap);
if(attrs.taUnsafeSanitizer){
scope.displayElements.text.attr('ta-unsafe-sanitizer', attrs.taUnsafeSanitizer);
scope.displayElements.html.attr('ta-unsafe-sanitizer', attrs.taUnsafeSanitizer);
}
// add the main elements to the origional element
scope.displayElements.scrollWindow.append(scope.displayElements.text);
element.append(scope.displayElements.scrollWindow);
element.append(scope.displayElements.html);
scope.displayElements.forminput.attr('name', scope._name);
element.append(scope.displayElements.forminput);
if(attrs.tabindex){
element.removeAttr('tabindex');
scope.displayElements.text.attr('tabindex', attrs.tabindex);
scope.displayElements.html.attr('tabindex', attrs.tabindex);
}
if (attrs.placeholder) {
scope.displayElements.text.attr('placeholder', attrs.placeholder);
scope.displayElements.html.attr('placeholder', attrs.placeholder);
}
if(attrs.taDisabled){
scope.displayElements.text.attr('ta-readonly', 'disabled');
scope.displayElements.html.attr('ta-readonly', 'disabled');
scope.disabled = scope.$parent.$eval(attrs.taDisabled);
scope.$parent.$watch(attrs.taDisabled, function(newVal){
scope.disabled = newVal;
if(scope.disabled){
element.addClass(scope.classes.disabled);
}else{
element.removeClass(scope.classes.disabled);
}
});
}
if(attrs.taPaste){
scope._pasteHandler = function(_html){
return $parse(attrs.taPaste)(scope.$parent, {$html: _html});
};
scope.displayElements.text.attr('ta-paste', '_pasteHandler($html)');
}
// compile the scope with the text and html elements only - if we do this with the main element it causes a compile loop
$compile(scope.displayElements.scrollWindow)(scope);
$compile(scope.displayElements.html)(scope);
scope.updateTaBindtaTextElement = scope['updateTaBindtaTextElement' + _serial];
scope.updateTaBindtaHtmlElement = scope['updateTaBindtaHtmlElement' + _serial];
// add the classes manually last
element.addClass("ta-root");
scope.displayElements.scrollWindow.addClass("ta-text ta-editor " + scope.classes.textEditor);
scope.displayElements.html.addClass("ta-html ta-editor " + scope.classes.htmlEditor);
// used in the toolbar actions
scope._actionRunning = false;
var _savedSelection = false;
scope.startAction = function(){
scope._actionRunning = true;
// if rangy library is loaded return a function to reload the current selection
_savedSelection = $window.rangy.saveSelection();
return function(){
if(_savedSelection) $window.rangy.restoreSelection(_savedSelection);
};
};
scope.endAction = function(){
scope._actionRunning = false;
if(_savedSelection){
if(scope.showHtml){
scope.displayElements.html[0].focus();
}else{
scope.displayElements.text[0].focus();
}
// $window.rangy.restoreSelection(_savedSelection);
$window.rangy.removeMarkers(_savedSelection);
}
_savedSelection = false;
scope.updateSelectedStyles();
// only update if in text or WYSIWYG mode
if(!scope.showHtml) scope['updateTaBindtaTextElement' + _serial]();
};
// note that focusout > focusin is called everytime we click a button - except bad support: http://www.quirksmode.org/dom/events/blurfocus.html
// cascades to displayElements.text and displayElements.html automatically.
_focusin = function(){
scope.focussed = true;
element.addClass(scope.classes.focussed);
_toolbars.focus();
element.triggerHandler('focus');
};
scope.displayElements.html.on('focus', _focusin);
scope.displayElements.text.on('focus', _focusin);
_focusout = function(e){
// if we are NOT runnig an action and have NOT focussed again on the text etc then fire the blur events
if(!scope._actionRunning && $document[0].activeElement !== scope.displayElements.html[0] && $document[0].activeElement !== scope.displayElements.text[0]){
element.removeClass(scope.classes.focussed);
_toolbars.unfocus();
// to prevent multiple apply error defer to next seems to work.
$timeout(function(){
scope._bUpdateSelectedStyles = false;
element.triggerHandler('blur');
scope.focussed = false;
}, 0);
}
e.preventDefault();
return false;
};
scope.displayElements.html.on('blur', _focusout);
scope.displayElements.text.on('blur', _focusout);
scope.displayElements.text.on('paste', function(event){
element.triggerHandler('paste', event);
});
// Setup the default toolbar tools, this way allows the user to add new tools like plugins.
// This is on the editor for future proofing if we find a better way to do this.
scope.queryFormatBlockState = function(command){
// $document[0].queryCommandValue('formatBlock') errors in Firefox if we call this when focussed on the textarea
return !scope.showHtml && command.toLowerCase() === $document[0].queryCommandValue('formatBlock').toLowerCase();
};
scope.queryCommandState = function(command){
// $document[0].queryCommandValue('formatBlock') errors in Firefox if we call this when focussed on the textarea
return (!scope.showHtml) ? $document[0].queryCommandState(command) : '';
};
scope.switchView = function(){
scope.showHtml = !scope.showHtml;
$animate.enabled(false, scope.displayElements.html);
$animate.enabled(false, scope.displayElements.text);
//Show the HTML view
if(scope.showHtml){
//defer until the element is visible
$timeout(function(){
$animate.enabled(true, scope.displayElements.html);
$animate.enabled(true, scope.displayElements.text);
// [0] dereferences the DOM object from the angular.element
return scope.displayElements.html[0].focus();
}, 100);
}else{
//Show the WYSIWYG view
//defer until the element is visible
$timeout(function(){
$animate.enabled(true, scope.displayElements.html);
$animate.enabled(true, scope.displayElements.text);
// [0] dereferences the DOM object from the angular.element
return scope.displayElements.text[0].focus();
}, 100);
}
};
// changes to the model variable from outside the html/text inputs
// if no ngModel, then the only input is from inside text-angular
if(attrs.ngModel){
var _firstRun = true;
ngModel.$render = function(){
if(_firstRun){
// we need this firstRun to set the originalContents otherwise it gets overrided by the setting of ngModel to undefined from NaN
_firstRun = false;
// if view value is null or undefined initially and there was original content, set to the original content
var _initialValue = scope.$parent.$eval(attrs.ngModel);
if((_initialValue === undefined || _initialValue === null) && (_originalContents && _originalContents !== '')){
// on passing through to taBind it will be sanitised
ngModel.$setViewValue(_originalContents);
}
}
scope.displayElements.forminput.val(ngModel.$viewValue);
// if the editors aren't focused they need to be updated, otherwise they are doing the updating
scope.html = ngModel.$viewValue || '';
};
// trigger the validation calls
if(element.attr('required')) ngModel.$validators.required = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return !(!value || value.trim() === '');
};
}else{
// if no ngModel then update from the contents of the origional html.
scope.displayElements.forminput.val(_originalContents);
scope.html = _originalContents;
}
// changes from taBind back up to here
scope.$watch('html', function(newValue, oldValue){
if(newValue !== oldValue){
if(attrs.ngModel && ngModel.$viewValue !== newValue) ngModel.$setViewValue(newValue);
scope.displayElements.forminput.val(newValue);
}
});
if(attrs.taTargetToolbars) _toolbars = textAngularManager.registerEditor(scope._name, scope, attrs.taTargetToolbars.split(','));
else{
var _toolbar = angular.element('<div text-angular-toolbar name="textAngularToolbar' + _serial + '">');
// passthrough init of toolbar options
if(attrs.taToolbar) _toolbar.attr('ta-toolbar', attrs.taToolbar);
if(attrs.taToolbarClass) _toolbar.attr('ta-toolbar-class', attrs.taToolbarClass);
if(attrs.taToolbarGroupClass) _toolbar.attr('ta-toolbar-group-class', attrs.taToolbarGroupClass);
if(attrs.taToolbarButtonClass) _toolbar.attr('ta-toolbar-button-class', attrs.taToolbarButtonClass);
if(attrs.taToolbarActiveButtonClass) _toolbar.attr('ta-toolbar-active-button-class', attrs.taToolbarActiveButtonClass);
if(attrs.taFocussedClass) _toolbar.attr('ta-focussed-class', attrs.taFocussedClass);
element.prepend(_toolbar);
$compile(_toolbar)(scope.$parent);
_toolbars = textAngularManager.registerEditor(scope._name, scope, ['textAngularToolbar' + _serial]);
}
scope.$on('$destroy', function(){
textAngularManager.unregisterEditor(scope._name);
angular.element(window).off('blur');
});
// catch element select event and pass to toolbar tools
scope.$on('ta-element-select', function(event, element){
if(_toolbars.triggerElementSelect(event, element)){
scope['reApplyOnSelectorHandlerstaTextElement' + _serial]();
}
});
scope.$on('ta-drop-event', function(event, element, dropEvent, dataTransfer){
scope.displayElements.text[0].focus();
if(dataTransfer && dataTransfer.files && dataTransfer.files.length > 0){
angular.forEach(dataTransfer.files, function(file){
// taking advantage of boolean execution, if the fileDropHandler returns true, nothing else after it is executed
// If it is false then execute the defaultFileDropHandler if the fileDropHandler is NOT the default one
// Once one of these has been executed wrap the result as a promise, if undefined or variable update the taBind, else we should wait for the promise
try{
$q.when(scope.fileDropHandler(file, scope.wrapSelection) ||
(scope.fileDropHandler !== scope.defaultFileDropHandler &&
$q.when(scope.defaultFileDropHandler(file, scope.wrapSelection)))).then(function(){
scope['updateTaBindtaTextElement' + _serial]();
});
}catch(error){
$log.error(error);
}
});
dropEvent.preventDefault();
dropEvent.stopPropagation();
/* istanbul ignore else, the updates if moved text */
}else{
$timeout(function(){
scope['updateTaBindtaTextElement' + _serial]();
}, 0);
}
});
// the following is for applying the active states to the tools that support it
scope._bUpdateSelectedStyles = false;
/* istanbul ignore next: browser window/tab leave check */
angular.element(window).on('blur', function(){
scope._bUpdateSelectedStyles = false;
scope.focussed = false;
});
// loop through all the tools polling their activeState function if it exists
scope.updateSelectedStyles = function(){
var _selection;
/* istanbul ignore next: This check is to ensure multiple timeouts don't exist */
if(_updateSelectedStylesTimeout) $timeout.cancel(_updateSelectedStylesTimeout);
// test if the common element ISN'T the root ta-text node
if((_selection = taSelection.getSelectionElement()) !== undefined && _selection.parentNode !== scope.displayElements.text[0]){
_toolbars.updateSelectedStyles(angular.element(_selection));
}else _toolbars.updateSelectedStyles();
// used to update the active state when a key is held down, ie the left arrow
/* istanbul ignore else: browser only check */
if(scope._bUpdateSelectedStyles) _updateSelectedStylesTimeout = $timeout(scope.updateSelectedStyles, 200);
};
// start updating on keydown
_keydown = function(){
/* istanbul ignore next: ie catch */
if(!scope.focussed){
scope._bUpdateSelectedStyles = false;
return;
}
/* istanbul ignore else: don't run if already running */
if(!scope._bUpdateSelectedStyles){
scope._bUpdateSelectedStyles = true;
scope.$apply(function(){
scope.updateSelectedStyles();
});
}
};
scope.displayElements.html.on('keydown', _keydown);
scope.displayElements.text.on('keydown', _keydown);
// stop updating on key up and update the display/model
_keyup = function(){
scope._bUpdateSelectedStyles = false;
};
scope.displayElements.html.on('keyup', _keyup);
scope.displayElements.text.on('keyup', _keyup);
// stop updating on key up and update the display/model
_keypress = function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
scope.$apply(function(){
if(_toolbars.sendKeyCommand(event)){
/* istanbul ignore else: don't run if already running */
if(!scope._bUpdateSelectedStyles){
scope.updateSelectedStyles();
}
event.preventDefault();
return false;
}
});
};
scope.displayElements.html.on('keypress', _keypress);
scope.displayElements.text.on('keypress', _keypress);
// update the toolbar active states when we click somewhere in the text/html boxed
_mouseup = function(){
// ensure only one execution of updateSelectedStyles()
scope._bUpdateSelectedStyles = false;
scope.$apply(function(){
scope.updateSelectedStyles();
});
};
scope.displayElements.html.on('mouseup', _mouseup);
scope.displayElements.text.on('mouseup', _mouseup);
}
};
}
]);
textAngular.service('textAngularManager', ['taToolExecuteAction', 'taTools', 'taRegisterTool', function(taToolExecuteAction, taTools, taRegisterTool){
// this service is used to manage all textAngular editors and toolbars.
// All publicly published functions that modify/need to access the toolbar or editor scopes should be in here
// these contain references to all the editors and toolbars that have been initialised in this app
var toolbars = {}, editors = {};
// when we focus into a toolbar, we need to set the TOOLBAR's $parent to be the toolbars it's linked to.
// We also need to set the tools to be updated to be the toolbars...
return {
// register an editor and the toolbars that it is affected by
registerEditor: function(name, scope, targetToolbars){
// targetToolbars are optional, we don't require a toolbar to function
if(!name || name === '') throw('textAngular Error: An editor requires a name');
if(!scope) throw('textAngular Error: An editor requires a scope');
if(editors[name]) throw('textAngular Error: An Editor with name "' + name + '" already exists');
// _toolbars is an ARRAY of toolbar scopes
var _toolbars = [];
angular.forEach(targetToolbars, function(_name){
if(toolbars[_name]) _toolbars.push(toolbars[_name]);
// if it doesn't exist it may not have been compiled yet and it will be added later
});
editors[name] = {
scope: scope,
toolbars: targetToolbars,
_registerToolbar: function(toolbarScope){
// add to the list late
if(this.toolbars.indexOf(toolbarScope.name) >= 0) _toolbars.push(toolbarScope);
},
// this is a suite of functions the editor should use to update all it's linked toolbars
editorFunctions: {
disable: function(){
// disable all linked toolbars
angular.forEach(_toolbars, function(toolbarScope){ toolbarScope.disabled = true; });
},
enable: function(){
// enable all linked toolbars
angular.forEach(_toolbars, function(toolbarScope){ toolbarScope.disabled = false; });
},
focus: function(){
// this should be called when the editor is focussed
angular.forEach(_toolbars, function(toolbarScope){
toolbarScope._parent = scope;
toolbarScope.disabled = false;
toolbarScope.focussed = true;
scope.focussed = true;
});
},
unfocus: function(){
// this should be called when the editor becomes unfocussed
angular.forEach(_toolbars, function(toolbarScope){
toolbarScope.disabled = true;
toolbarScope.focussed = false;
});
scope.focussed = false;
},
updateSelectedStyles: function(selectedElement){
// update the active state of all buttons on liked toolbars
angular.forEach(_toolbars, function(toolbarScope){
angular.forEach(toolbarScope.tools, function(toolScope){
if(toolScope.activeState){
toolbarScope._parent = scope;
toolScope.active = toolScope.activeState(selectedElement);
}
});
});
},
sendKeyCommand: function(event){
// we return true if we applied an action, false otherwise
var result = false;
if(event.ctrlKey || event.metaKey || event.specialKey) angular.forEach(taTools, function(tool, name){
if(tool.commandKeyCode && (tool.commandKeyCode === event.which || tool.commandKeyCode === event.specialKey)){
for(var _t = 0; _t < _toolbars.length; _t++){
if(_toolbars[_t].tools[name] !== undefined){
taToolExecuteAction.call(_toolbars[_t].tools[name], scope);
result = true;
break;
}
}
}
});
return result;
},
triggerElementSelect: function(event, element){
// search through the taTools to see if a match for the tag is made.
// if there is, see if the tool is on a registered toolbar and not disabled.
// NOTE: This can trigger on MULTIPLE tools simultaneously.
var elementHasAttrs = function(_element, attrs){
var result = true;
for(var i = 0; i < attrs.length; i++) result = result && _element.attr(attrs[i]);
return result;
};
var workerTools = [];
var unfilteredTools = {};
var result = false;
element = angular.element(element);
// get all valid tools by element name, keep track if one matches the
var onlyWithAttrsFilter = false;
angular.forEach(taTools, function(tool, name){
if(
tool.onElementSelect &&
tool.onElementSelect.element &&
tool.onElementSelect.element.toLowerCase() === element[0].tagName.toLowerCase() &&
(!tool.onElementSelect.filter || tool.onElementSelect.filter(element))
){
// this should only end up true if the element matches the only attributes
onlyWithAttrsFilter = onlyWithAttrsFilter ||
(angular.isArray(tool.onElementSelect.onlyWithAttrs) && elementHasAttrs(element, tool.onElementSelect.onlyWithAttrs));
if(!tool.onElementSelect.onlyWithAttrs || elementHasAttrs(element, tool.onElementSelect.onlyWithAttrs)) unfilteredTools[name] = tool;
}
});
// if we matched attributes to filter on, then filter, else continue
if(onlyWithAttrsFilter){
angular.forEach(unfilteredTools, function(tool, name){
if(tool.onElementSelect.onlyWithAttrs && elementHasAttrs(element, tool.onElementSelect.onlyWithAttrs)) workerTools.push({'name': name, 'tool': tool});
});
// sort most specific (most attrs to find) first
workerTools.sort(function(a,b){
return b.tool.onElementSelect.onlyWithAttrs.length - a.tool.onElementSelect.onlyWithAttrs.length;
});
}else{
angular.forEach(unfilteredTools, function(tool, name){
workerTools.push({'name': name, 'tool': tool});
});
}
// Run the actions on the first visible filtered tool only
if(workerTools.length > 0){
for(var _i = 0; _i < workerTools.length; _i++){
var tool = workerTools[_i].tool;
var name = workerTools[_i].name;
for(var _t = 0; _t < _toolbars.length; _t++){
if(_toolbars[_t].tools[name] !== undefined){
tool.onElementSelect.action.call(_toolbars[_t].tools[name], event, element, scope);
result = true;
break;
}
}
if(result) break;
}
}
return result;
}
}
};
return editors[name].editorFunctions;
},
// retrieve editor by name, largely used by testing suites only
retrieveEditor: function(name){
return editors[name];
},
unregisterEditor: function(name){
delete editors[name];
},
// registers a toolbar such that it can be linked to editors
registerToolbar: function(scope){
if(!scope) throw('textAngular Error: A toolbar requires a scope');
if(!scope.name || scope.name === '') throw('textAngular Error: A toolbar requires a name');
if(toolbars[scope.name]) throw('textAngular Error: A toolbar with name "' + scope.name + '" already exists');
toolbars[scope.name] = scope;
angular.forEach(editors, function(_editor){
_editor._registerToolbar(scope);
});
},
// retrieve toolbar by name, largely used by testing suites only
retrieveToolbar: function(name){
return toolbars[name];
},
// retrieve toolbars by editor name, largely used by testing suites only
retrieveToolbarsViaEditor: function(name){
var result = [], _this = this;
angular.forEach(this.retrieveEditor(name).toolbars, function(name){
result.push(_this.retrieveToolbar(name));
});
return result;
},
unregisterToolbar: function(name){
delete toolbars[name];
},
// functions for updating the toolbar buttons display
updateToolsDisplay: function(newTaTools){
// pass a partial struct of the taTools, this allows us to update the tools on the fly, will not change the defaults.
var _this = this;
angular.forEach(newTaTools, function(_newTool, key){
_this.updateToolDisplay(key, _newTool);
});
},
// this function resets all toolbars to their default tool definitions
resetToolsDisplay: function(){
var _this = this;
angular.forEach(taTools, function(_newTool, key){
_this.resetToolDisplay(key);
});
},
// update a tool on all toolbars
updateToolDisplay: function(toolKey, _newTool){
var _this = this;
angular.forEach(toolbars, function(toolbarScope, toolbarKey){
_this.updateToolbarToolDisplay(toolbarKey, toolKey, _newTool);
});
},
// resets a tool to the default/starting state on all toolbars
resetToolDisplay: function(toolKey){
var _this = this;
angular.forEach(toolbars, function(toolbarScope, toolbarKey){
_this.resetToolbarToolDisplay(toolbarKey, toolKey);
});
},
// update a tool on a specific toolbar
updateToolbarToolDisplay: function(toolbarKey, toolKey, _newTool){
if(toolbars[toolbarKey]) toolbars[toolbarKey].updateToolDisplay(toolKey, _newTool);
else throw('textAngular Error: No Toolbar with name "' + toolbarKey + '" exists');
},
// reset a tool on a specific toolbar to it's default starting value
resetToolbarToolDisplay: function(toolbarKey, toolKey){
if(toolbars[toolbarKey]) toolbars[toolbarKey].updateToolDisplay(toolKey, taTools[toolKey], true);
else throw('textAngular Error: No Toolbar with name "' + toolbarKey + '" exists');
},
// removes a tool from all toolbars and it's definition
removeTool: function(toolKey){
delete taTools[toolKey];
angular.forEach(toolbars, function(toolbarScope){
delete toolbarScope.tools[toolKey];
for(var i = 0; i < toolbarScope.toolbar.length; i++){
var toolbarIndex;
for(var j = 0; j < toolbarScope.toolbar[i].length; j++){
if(toolbarScope.toolbar[i][j] === toolKey){
toolbarIndex = {
group: i,
index: j
};
break;
}
if(toolbarIndex !== undefined) break;
}
if(toolbarIndex !== undefined){
toolbarScope.toolbar[toolbarIndex.group].slice(toolbarIndex.index, 1);
toolbarScope._$element.children().eq(toolbarIndex.group).children().eq(toolbarIndex.index).remove();
}
}
});
},
// toolkey, toolDefinition are required. If group is not specified will pick the last group, if index isnt defined will append to group
addTool: function(toolKey, toolDefinition, group, index){
taRegisterTool(toolKey, toolDefinition);
angular.forEach(toolbars, function(toolbarScope){
toolbarScope.addTool(toolKey, toolDefinition, group, index);
});
},
// adds a Tool but only to one toolbar not all
addToolToToolbar: function(toolKey, toolDefinition, toolbarKey, group, index){
taRegisterTool(toolKey, toolDefinition);
toolbars[toolbarKey].addTool(toolKey, toolDefinition, group, index);
},
// this is used when externally the html of an editor has been changed and textAngular needs to be notified to update the model.
// this will call a $digest if not already happening
refreshEditor: function(name){
if(editors[name]){
editors[name].scope.updateTaBindtaTextElement();
/* istanbul ignore else: phase catch */
if(!editors[name].scope.$$phase) editors[name].scope.$digest();
}else throw('textAngular Error: No Editor with name "' + name + '" exists');
},
// this is used by taBind to send a key command in response to a special key event
sendKeyCommand: function(scope, event){
var _editor = editors[scope._name];
/* istanbul ignore else: if nothing to do, do nothing */
if (_editor && _editor.editorFunctions.sendKeyCommand(event)) {
/* istanbul ignore else: don't run if already running */
if(!scope._bUpdateSelectedStyles){
scope.updateSelectedStyles();
}
event.preventDefault();
return false;
}
}
};
}]);
textAngular.directive('textAngularToolbar', [
'$compile', 'textAngularManager', 'taOptions', 'taTools', 'taToolExecuteAction', '$window',
function($compile, textAngularManager, taOptions, taTools, taToolExecuteAction, $window){
return {
scope: {
name: '@' // a name IS required
},
restrict: "EA",
link: function(scope, element, attrs){
if(!scope.name || scope.name === '') throw('textAngular Error: A toolbar requires a name');
angular.extend(scope, angular.copy(taOptions));
if(attrs.taToolbar) scope.toolbar = scope.$parent.$eval(attrs.taToolbar);
if(attrs.taToolbarClass) scope.classes.toolbar = attrs.taToolbarClass;
if(attrs.taToolbarGroupClass) scope.classes.toolbarGroup = attrs.taToolbarGroupClass;
if(attrs.taToolbarButtonClass) scope.classes.toolbarButton = attrs.taToolbarButtonClass;
if(attrs.taToolbarActiveButtonClass) scope.classes.toolbarButtonActive = attrs.taToolbarActiveButtonClass;
if(attrs.taFocussedClass) scope.classes.focussed = attrs.taFocussedClass;
scope.disabled = true;
scope.focussed = false;
scope._$element = element;
element[0].innerHTML = '';
element.addClass("ta-toolbar " + scope.classes.toolbar);
scope.$watch('focussed', function(){
if(scope.focussed) element.addClass(scope.classes.focussed);
else element.removeClass(scope.classes.focussed);
});
var setupToolElement = function(toolDefinition, toolScope){
var toolElement;
if(toolDefinition && toolDefinition.display){
toolElement = angular.element(toolDefinition.display);
}
else toolElement = angular.element("<button type='button'>");
if(toolDefinition && toolDefinition["class"]) toolElement.addClass(toolDefinition["class"]);
else toolElement.addClass(scope.classes.toolbarButton);
toolElement.attr('name', toolScope.name);
// important to not take focus from the main text/html entry
toolElement.attr('ta-button', 'ta-button');
toolElement.attr('ng-disabled', 'isDisabled()');
toolElement.attr('tabindex', '-1');
toolElement.attr('ng-click', 'executeAction()');
toolElement.attr('ng-class', 'displayActiveToolClass(active)');
if (toolDefinition && toolDefinition.tooltiptext) {
toolElement.attr('title', toolDefinition.tooltiptext);
}
if(toolDefinition && !toolDefinition.display && !toolScope._display){
// first clear out the current contents if any
toolElement[0].innerHTML = '';
// add the buttonText
if(toolDefinition.buttontext) toolElement[0].innerHTML = toolDefinition.buttontext;
// add the icon to the front of the button if there is content
if(toolDefinition.iconclass){
var icon = angular.element('<i>'), content = toolElement[0].innerHTML;
icon.addClass(toolDefinition.iconclass);
toolElement[0].innerHTML = '';
toolElement.append(icon);
if(content && content !== '') toolElement.append(' ' + content);
}
}
toolScope._lastToolDefinition = angular.copy(toolDefinition);
return $compile(toolElement)(toolScope);
};
// Keep a reference for updating the active states later
scope.tools = {};
// create the tools in the toolbar
// default functions and values to prevent errors in testing and on init
scope._parent = {
disabled: true,
showHtml: false,
queryFormatBlockState: function(){ return false; },
queryCommandState: function(){ return false; }
};
var defaultChildScope = {
$window: $window,
$editor: function(){
// dynamically gets the editor as it is set
return scope._parent;
},
isDisabled: function(){
// to set your own disabled logic set a function or boolean on the tool called 'disabled'
return ( // this bracket is important as without it it just returns the first bracket and ignores the rest
// when the button's disabled function/value evaluates to true
(typeof this.$eval('disabled') !== 'function' && this.$eval('disabled')) || this.$eval('disabled()') ||
// all buttons except the HTML Switch button should be disabled in the showHtml (RAW html) mode
(this.name !== 'html' && this.$editor().showHtml) ||
// if the toolbar is disabled
this.$parent.disabled ||
// if the current editor is disabled
this.$editor().disabled
);
},
displayActiveToolClass: function(active){
return (active)? scope.classes.toolbarButtonActive : '';
},
executeAction: taToolExecuteAction
};
angular.forEach(scope.toolbar, function(group){
// setup the toolbar group
var groupElement = angular.element("<div>");
groupElement.addClass(scope.classes.toolbarGroup);
angular.forEach(group, function(tool){
// init and add the tools to the group
// a tool name (key name from taTools struct)
//creates a child scope of the main angularText scope and then extends the childScope with the functions of this particular tool
// reference to the scope and element kept
scope.tools[tool] = angular.extend(scope.$new(true), taTools[tool], defaultChildScope, {name: tool});
scope.tools[tool].$element = setupToolElement(taTools[tool], scope.tools[tool]);
// append the tool compiled with the childScope to the group element
groupElement.append(scope.tools[tool].$element);
});
// append the group to the toolbar
element.append(groupElement);
});
// update a tool
// if a value is set to null, remove from the display
// when forceNew is set to true it will ignore all previous settings, used to reset to taTools definition
// to reset to defaults pass in taTools[key] as _newTool and forceNew as true, ie `updateToolDisplay(key, taTools[key], true);`
scope.updateToolDisplay = function(key, _newTool, forceNew){
var toolInstance = scope.tools[key];
if(toolInstance){
// get the last toolDefinition, then override with the new definition
if(toolInstance._lastToolDefinition && !forceNew) _newTool = angular.extend({}, toolInstance._lastToolDefinition, _newTool);
if(_newTool.buttontext === null && _newTool.iconclass === null && _newTool.display === null)
throw('textAngular Error: Tool Definition for updating "' + key + '" does not have a valid display/iconclass/buttontext value');
// if tool is defined on this toolbar, update/redo the tool
if(_newTool.buttontext === null){
delete _newTool.buttontext;
}
if(_newTool.iconclass === null){
delete _newTool.iconclass;
}
if(_newTool.display === null){
delete _newTool.display;
}
var toolElement = setupToolElement(_newTool, toolInstance);
toolInstance.$element.replaceWith(toolElement);
toolInstance.$element = toolElement;
}
};
// we assume here that all values passed are valid and correct
scope.addTool = function(key, _newTool, groupIndex, index){
scope.tools[key] = angular.extend(scope.$new(true), taTools[key], defaultChildScope, {name: key});
scope.tools[key].$element = setupToolElement(taTools[key], scope.tools[key]);
var group;
if(groupIndex === undefined) groupIndex = scope.toolbar.length - 1;
group = angular.element(element.children()[groupIndex]);
if(index === undefined){
group.append(scope.tools[key].$element);
scope.toolbar[groupIndex][scope.toolbar[groupIndex].length - 1] = key;
}else{
group.children().eq(index).after(scope.tools[key].$element);
scope.toolbar[groupIndex][index] = key;
}
};
textAngularManager.registerToolbar(scope);
scope.$on('$destroy', function(){
textAngularManager.unregisterToolbar(scope.name);
});
}
};
}
]);
})();
// tests against the current jqLite/jquery implementation if this can be an element
function validElementString(string){
try{
return angular.element(string).length !== 0;
}catch(any){
return false;
}
}
// setup the global contstant functions for setting up the toolbar
// all tool definitions
var taTools = {};
/*
A tool definition is an object with the following key/value parameters:
action: [function(deferred, restoreSelection)]
a function that is executed on clicking on the button - this will allways be executed using ng-click and will
overwrite any ng-click value in the display attribute.
The function is passed a deferred object ($q.defer()), if this is wanted to be used `return false;` from the action and
manually call `deferred.resolve();` elsewhere to notify the editor that the action has finished.
restoreSelection is only defined if the rangy library is included and it can be called as `restoreSelection()` to restore the users
selection in the WYSIWYG editor.
display: [string]?
Optional, an HTML element to be displayed as the button. The `scope` of the button is the tool definition object with some additional functions
If set this will cause buttontext and iconclass to be ignored
class: [string]?
Optional, if set will override the taOptions.classes.toolbarButton class.
buttontext: [string]?
if this is defined it will replace the contents of the element contained in the `display` element
iconclass: [string]?
if this is defined an icon (<i>) will be appended to the `display` element with this string as it's class
tooltiptext: [string]?
Optional, a plain text description of the action, used for the title attribute of the action button in the toolbar by default.
activestate: [function(commonElement)]?
this function is called on every caret movement, if it returns true then the class taOptions.classes.toolbarButtonActive
will be applied to the `display` element, else the class will be removed
disabled: [function()]?
if this function returns true then the tool will have the class taOptions.classes.disabled applied to it, else it will be removed
Other functions available on the scope are:
name: [string]
the name of the tool, this is the first parameter passed into taRegisterTool
isDisabled: [function()]
returns true if the tool is disabled, false if it isn't
displayActiveToolClass: [function(boolean)]
returns true if the tool is 'active' in the currently focussed toolbar
onElementSelect: [Object]
This object contains the following key/value pairs and is used to trigger the ta-element-select event
element: [String]
an element name, will only trigger the onElementSelect action if the tagName of the element matches this string
filter: [function(element)]?
an optional filter that returns a boolean, if true it will trigger the onElementSelect.
action: [function(event, element, editorScope)]
the action that should be executed if the onElementSelect function runs
*/
// name and toolDefinition to add into the tools available to be added on the toolbar
function registerTextAngularTool(name, toolDefinition){
if(!name || name === '' || taTools.hasOwnProperty(name)) throw('textAngular Error: A unique name is required for a Tool Definition');
if(
(toolDefinition.display && (toolDefinition.display === '' || !validElementString(toolDefinition.display))) ||
(!toolDefinition.display && !toolDefinition.buttontext && !toolDefinition.iconclass)
)
throw('textAngular Error: Tool Definition for "' + name + '" does not have a valid display/iconclass/buttontext value');
taTools[name] = toolDefinition;
}
angular.module('textAngularSetup', [])
.constant('taRegisterTool', registerTextAngularTool)
.value('taTools', taTools)
// Here we set up the global display defaults, to set your own use a angular $provider#decorator.
.value('taOptions', {
//////////////////////////////////////////////////////////////////////////////////////
// forceTextAngularSanitize
// set false to allow the textAngular-sanitize provider to be replaced
// with angular-sanitize or a custom provider.
forceTextAngularSanitize: true,
///////////////////////////////////////////////////////////////////////////////////////
// keyMappings
// allow customizable keyMappings for specialized key boards or languages
//
// keyMappings provides key mappings that are attached to a given commandKeyCode.
// To modify a specific keyboard binding, simply provide function which returns true
// for the event you wish to map to.
// Or to disable a specific keyboard binding, provide a function which returns false.
// Note: 'RedoKey' and 'UndoKey' are internally bound to the redo and undo functionality.
// At present, the following commandKeyCodes are in use:
// 98, 'TabKey', 'ShiftTabKey', 105, 117, 'UndoKey', 'RedoKey'
//
// To map to an new commandKeyCode, add a new key mapping such as:
// {commandKeyCode: 'CustomKey', testForKey: function (event) {
// if (event.keyCode=57 && event.ctrlKey && !event.shiftKey && !event.altKey) return true;
// } }
// to the keyMappings. This example maps ctrl+9 to 'CustomKey'
// Then where taRegisterTool(...) is called, add a commandKeyCode: 'CustomKey' and your
// tool will be bound to ctrl+9.
//
// To disble one of the already bound commandKeyCodes such as 'RedoKey' or 'UndoKey' add:
// {commandKeyCode: 'RedoKey', testForKey: function (event) { return false; } },
// {commandKeyCode: 'UndoKey', testForKey: function (event) { return false; } },
// to disable them.
//
keyMappings : [],
toolbar: [
['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'pre', 'quote'],
['bold', 'italics', 'underline', 'strikeThrough', 'ul', 'ol', 'redo', 'undo', 'clear'],
['justifyLeft','justifyCenter','justifyRight','justifyFull','indent','outdent'],
['html', 'insertImage', 'insertLink', 'insertVideo','wordcount', 'charcount']
],
classes: {
focussed: "focussed",
toolbar: "btn-toolbar",
toolbarGroup: "btn-group",
toolbarButton: "btn btn-default",
toolbarButtonActive: "active",
disabled: "disabled",
textEditor: 'form-control',
htmlEditor: 'form-control'
},
defaultTagAttributes : {
a: {target:""}
},
setup: {
// wysiwyg mode
textEditorSetup: function($element){ /* Do some processing here */ },
// raw html
htmlEditorSetup: function($element){ /* Do some processing here */ }
},
defaultFileDropHandler:
/* istanbul ignore next: untestable image processing */
function(file, insertAction){
var reader = new FileReader();
if(file.type.substring(0, 5) === 'image'){
reader.onload = function() {
if(reader.result !== '') insertAction('insertImage', reader.result, true);
};
reader.readAsDataURL(file);
// NOTE: For async procedures return a promise and resolve it when the editor should update the model.
return true;
}
return false;
}
})
// This is the element selector string that is used to catch click events within a taBind, prevents the default and $emits a 'ta-element-select' event
// these are individually used in an angular.element().find() call. What can go here depends on whether you have full jQuery loaded or just jQLite with angularjs.
// div is only used as div.ta-insert-video caught in filter.
.value('taSelectableElements', ['a','img'])
// This is an array of objects with the following options:
// selector: <string> a jqLite or jQuery selector string
// customAttribute: <string> an attribute to search for
// renderLogic: <function(element)>
// Both or one of selector and customAttribute must be defined.
.value('taCustomRenderers', [
{
// Parse back out: '<div class="ta-insert-video" ta-insert-video src="' + urlLink + '" allowfullscreen="true" width="300" frameborder="0" height="250"></div>'
// To correct video element. For now only support youtube
selector: 'img',
customAttribute: 'ta-insert-video',
renderLogic: function(element){
var iframe = angular.element('<iframe></iframe>');
var attributes = element.prop("attributes");
// loop through element attributes and apply them on iframe
angular.forEach(attributes, function(attr) {
iframe.attr(attr.name, attr.value);
});
iframe.attr('src', iframe.attr('ta-insert-video'));
element.replaceWith(iframe);
}
}
])
.value('taTranslations', {
// moved to sub-elements
//toggleHTML: "Toggle HTML",
//insertImage: "Please enter a image URL to insert",
//insertLink: "Please enter a URL to insert",
//insertVideo: "Please enter a youtube URL to embed",
html: {
tooltip: 'Toggle html / Rich Text'
},
// tooltip for heading - might be worth splitting
heading: {
tooltip: 'Heading '
},
p: {
tooltip: 'Paragraph'
},
pre: {
tooltip: 'Preformatted text'
},
ul: {
tooltip: 'Unordered List'
},
ol: {
tooltip: 'Ordered List'
},
quote: {
tooltip: 'Quote/unquote selection or paragraph'
},
undo: {
tooltip: 'Undo'
},
redo: {
tooltip: 'Redo'
},
bold: {
tooltip: 'Bold'
},
italic: {
tooltip: 'Italic'
},
underline: {
tooltip: 'Underline'
},
strikeThrough:{
tooltip: 'Strikethrough'
},
justifyLeft: {
tooltip: 'Align text left'
},
justifyRight: {
tooltip: 'Align text right'
},
justifyFull: {
tooltip: 'Justify text'
},
justifyCenter: {
tooltip: 'Center'
},
indent: {
tooltip: 'Increase indent'
},
outdent: {
tooltip: 'Decrease indent'
},
clear: {
tooltip: 'Clear formatting'
},
insertImage: {
dialogPrompt: 'Please enter an image URL to insert',
tooltip: 'Insert image',
hotkey: 'the - possibly language dependent hotkey ... for some future implementation'
},
insertVideo: {
tooltip: 'Insert video',
dialogPrompt: 'Please enter a youtube URL to embed'
},
insertLink: {
tooltip: 'Insert / edit link',
dialogPrompt: "Please enter a URL to insert"
},
editLink: {
reLinkButton: {
tooltip: "Relink"
},
unLinkButton: {
tooltip: "Unlink"
},
targetToggle: {
buttontext: "Open in New Window"
}
},
wordcount: {
tooltip: 'Display words Count'
},
charcount: {
tooltip: 'Display characters Count'
}
})
.factory('taToolFunctions', ['$window','taTranslations', function($window, taTranslations) {
return {
imgOnSelectAction: function(event, $element, editorScope){
// setup the editor toolbar
// Credit to the work at http://hackerwins.github.io/summernote/ for this editbar logic/display
var finishEdit = function(){
editorScope.updateTaBindtaTextElement();
editorScope.hidePopover();
};
event.preventDefault();
editorScope.displayElements.popover.css('width', '375px');
var container = editorScope.displayElements.popoverContainer;
container.empty();
var buttonGroup = angular.element('<div class="btn-group" style="padding-right: 6px;">');
var fullButton = angular.element('<button type="button" class="btn btn-default btn-sm btn-small" unselectable="on" tabindex="-1">100% </button>');
fullButton.on('click', function(event){
event.preventDefault();
$element.css({
'width': '100%',
'height': ''
});
finishEdit();
});
var halfButton = angular.element('<button type="button" class="btn btn-default btn-sm btn-small" unselectable="on" tabindex="-1">50% </button>');
halfButton.on('click', function(event){
event.preventDefault();
$element.css({
'width': '50%',
'height': ''
});
finishEdit();
});
var quartButton = angular.element('<button type="button" class="btn btn-default btn-sm btn-small" unselectable="on" tabindex="-1">25% </button>');
quartButton.on('click', function(event){
event.preventDefault();
$element.css({
'width': '25%',
'height': ''
});
finishEdit();
});
var resetButton = angular.element('<button type="button" class="btn btn-default btn-sm btn-small" unselectable="on" tabindex="-1">Reset</button>');
resetButton.on('click', function(event){
event.preventDefault();
$element.css({
width: '',
height: ''
});
finishEdit();
});
buttonGroup.append(fullButton);
buttonGroup.append(halfButton);
buttonGroup.append(quartButton);
buttonGroup.append(resetButton);
container.append(buttonGroup);
buttonGroup = angular.element('<div class="btn-group" style="padding-right: 6px;">');
var floatLeft = angular.element('<button type="button" class="btn btn-default btn-sm btn-small" unselectable="on" tabindex="-1"><i class="fa fa-align-left"></i></button>');
floatLeft.on('click', function(event){
event.preventDefault();
// webkit
$element.css('float', 'left');
// firefox
$element.css('cssFloat', 'left');
// IE < 8
$element.css('styleFloat', 'left');
finishEdit();
});
var floatRight = angular.element('<button type="button" class="btn btn-default btn-sm btn-small" unselectable="on" tabindex="-1"><i class="fa fa-align-right"></i></button>');
floatRight.on('click', function(event){
event.preventDefault();
// webkit
$element.css('float', 'right');
// firefox
$element.css('cssFloat', 'right');
// IE < 8
$element.css('styleFloat', 'right');
finishEdit();
});
var floatNone = angular.element('<button type="button" class="btn btn-default btn-sm btn-small" unselectable="on" tabindex="-1"><i class="fa fa-align-justify"></i></button>');
floatNone.on('click', function(event){
event.preventDefault();
// webkit
$element.css('float', '');
// firefox
$element.css('cssFloat', '');
// IE < 8
$element.css('styleFloat', '');
finishEdit();
});
buttonGroup.append(floatLeft);
buttonGroup.append(floatNone);
buttonGroup.append(floatRight);
container.append(buttonGroup);
buttonGroup = angular.element('<div class="btn-group">');
var remove = angular.element('<button type="button" class="btn btn-default btn-sm btn-small" unselectable="on" tabindex="-1"><i class="fa fa-trash-o"></i></button>');
remove.on('click', function(event){
event.preventDefault();
$element.remove();
finishEdit();
});
buttonGroup.append(remove);
container.append(buttonGroup);
editorScope.showPopover($element);
editorScope.showResizeOverlay($element);
},
aOnSelectAction: function(event, $element, editorScope){
// setup the editor toolbar
// Credit to the work at http://hackerwins.github.io/summernote/ for this editbar logic
event.preventDefault();
editorScope.displayElements.popover.css('width', '436px');
var container = editorScope.displayElements.popoverContainer;
container.empty();
container.css('line-height', '28px');
var link = angular.element('<a href="' + $element.attr('href') + '" target="_blank">' + $element.attr('href') + '</a>');
link.css({
'display': 'inline-block',
'max-width': '200px',
'overflow': 'hidden',
'text-overflow': 'ellipsis',
'white-space': 'nowrap',
'vertical-align': 'middle'
});
container.append(link);
var buttonGroup = angular.element('<div class="btn-group pull-right">');
var reLinkButton = angular.element('<button type="button" class="btn btn-default btn-sm btn-small" tabindex="-1" unselectable="on" title="' + taTranslations.editLink.reLinkButton.tooltip + '"><i class="fa fa-edit icon-edit"></i></button>');
reLinkButton.on('click', function(event){
event.preventDefault();
var urlLink = $window.prompt(taTranslations.insertLink.dialogPrompt, $element.attr('href'));
if(urlLink && urlLink !== '' && urlLink !== 'http://'){
$element.attr('href', urlLink);
editorScope.updateTaBindtaTextElement();
}
editorScope.hidePopover();
});
buttonGroup.append(reLinkButton);
var unLinkButton = angular.element('<button type="button" class="btn btn-default btn-sm btn-small" tabindex="-1" unselectable="on" title="' + taTranslations.editLink.unLinkButton.tooltip + '"><i class="fa fa-unlink icon-unlink"></i></button>');
// directly before this click event is fired a digest is fired off whereby the reference to $element is orphaned off
unLinkButton.on('click', function(event){
event.preventDefault();
$element.replaceWith($element.contents());
editorScope.updateTaBindtaTextElement();
editorScope.hidePopover();
});
buttonGroup.append(unLinkButton);
var targetToggle = angular.element('<button type="button" class="btn btn-default btn-sm btn-small" tabindex="-1" unselectable="on">' + taTranslations.editLink.targetToggle.buttontext + '</button>');
if($element.attr('target') === '_blank'){
targetToggle.addClass('active');
}
targetToggle.on('click', function(event){
event.preventDefault();
$element.attr('target', ($element.attr('target') === '_blank') ? '' : '_blank');
targetToggle.toggleClass('active');
editorScope.updateTaBindtaTextElement();
});
buttonGroup.append(targetToggle);
container.append(buttonGroup);
editorScope.showPopover($element);
},
extractYoutubeVideoId: function(url) {
var re = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/i;
var match = url.match(re);
return (match && match[1]) || null;
}
};
}])
.run(['taRegisterTool', '$window', 'taTranslations', 'taSelection', 'taToolFunctions', '$sanitize', 'taOptions', function(taRegisterTool, $window, taTranslations, taSelection, taToolFunctions, $sanitize, taOptions){
// test for the version of $sanitize that is in use
// You can disable this check by setting taOptions.textAngularSanitize == false
var gv = {}; $sanitize('', gv);
/* istanbul ignore next, throws error */
if ((taOptions.forceTextAngularSanitize===true) && (gv.version !== 'taSanitize')) {
throw angular.$$minErr('textAngular')("textAngularSetup", "The textAngular-sanitize provider has been replaced by another -- have you included angular-sanitize by mistake?");
}
taRegisterTool("html", {
iconclass: 'fa fa-code',
tooltiptext: taTranslations.html.tooltip,
action: function(){
this.$editor().switchView();
},
activeState: function(){
return this.$editor().showHtml;
}
});
// add the Header tools
// convenience functions so that the loop works correctly
var _retActiveStateFunction = function(q){
return function(){ return this.$editor().queryFormatBlockState(q); };
};
var headerAction = function(){
return this.$editor().wrapSelection("formatBlock", "<" + this.name.toUpperCase() +">");
};
angular.forEach(['h1','h2','h3','h4','h5','h6'], function(h){
taRegisterTool(h.toLowerCase(), {
buttontext: h.toUpperCase(),
tooltiptext: taTranslations.heading.tooltip + h.charAt(1),
action: headerAction,
activeState: _retActiveStateFunction(h.toLowerCase())
});
});
taRegisterTool('p', {
buttontext: 'P',
tooltiptext: taTranslations.p.tooltip,
action: function(){
return this.$editor().wrapSelection("formatBlock", "<P>");
},
activeState: function(){ return this.$editor().queryFormatBlockState('p'); }
});
// key: pre -> taTranslations[key].tooltip, taTranslations[key].buttontext
taRegisterTool('pre', {
buttontext: 'pre',
tooltiptext: taTranslations.pre.tooltip,
action: function(){
return this.$editor().wrapSelection("formatBlock", "<PRE>");
},
activeState: function(){ return this.$editor().queryFormatBlockState('pre'); }
});
taRegisterTool('ul', {
iconclass: 'fa fa-list-ul',
tooltiptext: taTranslations.ul.tooltip,
action: function(){
return this.$editor().wrapSelection("insertUnorderedList", null);
},
activeState: function(){ return this.$editor().queryCommandState('insertUnorderedList'); }
});
taRegisterTool('ol', {
iconclass: 'fa fa-list-ol',
tooltiptext: taTranslations.ol.tooltip,
action: function(){
return this.$editor().wrapSelection("insertOrderedList", null);
},
activeState: function(){ return this.$editor().queryCommandState('insertOrderedList'); }
});
taRegisterTool('quote', {
iconclass: 'fa fa-quote-right',
tooltiptext: taTranslations.quote.tooltip,
action: function(){
return this.$editor().wrapSelection("formatBlock", "<BLOCKQUOTE>");
},
activeState: function(){ return this.$editor().queryFormatBlockState('blockquote'); }
});
taRegisterTool('undo', {
iconclass: 'fa fa-undo',
tooltiptext: taTranslations.undo.tooltip,
action: function(){
return this.$editor().wrapSelection("undo", null);
}
});
taRegisterTool('redo', {
iconclass: 'fa fa-repeat',
tooltiptext: taTranslations.redo.tooltip,
action: function(){
return this.$editor().wrapSelection("redo", null);
}
});
taRegisterTool('bold', {
iconclass: 'fa fa-bold',
tooltiptext: taTranslations.bold.tooltip,
action: function(){
return this.$editor().wrapSelection("bold", null);
},
activeState: function(){
return this.$editor().queryCommandState('bold');
},
commandKeyCode: 98
});
taRegisterTool('justifyLeft', {
iconclass: 'fa fa-align-left',
tooltiptext: taTranslations.justifyLeft.tooltip,
action: function(){
return this.$editor().wrapSelection("justifyLeft", null);
},
activeState: function(commonElement){
/* istanbul ignore next: */
if (commonElement && commonElement.nodeName === '#document') return false;
var result = false;
if (commonElement)
result =
commonElement.css('text-align') === 'left' ||
commonElement.attr('align') === 'left' ||
(
commonElement.css('text-align') !== 'right' &&
commonElement.css('text-align') !== 'center' &&
commonElement.css('text-align') !== 'justify' && !this.$editor().queryCommandState('justifyRight') && !this.$editor().queryCommandState('justifyCenter')
) && !this.$editor().queryCommandState('justifyFull');
result = result || this.$editor().queryCommandState('justifyLeft');
return result;
}
});
taRegisterTool('justifyRight', {
iconclass: 'fa fa-align-right',
tooltiptext: taTranslations.justifyRight.tooltip,
action: function(){
return this.$editor().wrapSelection("justifyRight", null);
},
activeState: function(commonElement){
/* istanbul ignore next: */
if (commonElement && commonElement.nodeName === '#document') return false;
var result = false;
if(commonElement) result = commonElement.css('text-align') === 'right';
result = result || this.$editor().queryCommandState('justifyRight');
return result;
}
});
taRegisterTool('justifyFull', {
iconclass: 'fa fa-align-justify',
tooltiptext: taTranslations.justifyFull.tooltip,
action: function(){
return this.$editor().wrapSelection("justifyFull", null);
},
activeState: function(commonElement){
var result = false;
if(commonElement) result = commonElement.css('text-align') === 'justify';
result = result || this.$editor().queryCommandState('justifyFull');
return result;
}
});
taRegisterTool('justifyCenter', {
iconclass: 'fa fa-align-center',
tooltiptext: taTranslations.justifyCenter.tooltip,
action: function(){
return this.$editor().wrapSelection("justifyCenter", null);
},
activeState: function(commonElement){
/* istanbul ignore next: */
if (commonElement && commonElement.nodeName === '#document') return false;
var result = false;
if(commonElement) result = commonElement.css('text-align') === 'center';
result = result || this.$editor().queryCommandState('justifyCenter');
return result;
}
});
taRegisterTool('indent', {
iconclass: 'fa fa-indent',
tooltiptext: taTranslations.indent.tooltip,
action: function(){
return this.$editor().wrapSelection("indent", null);
},
activeState: function(){
return this.$editor().queryFormatBlockState('blockquote');
},
commandKeyCode: 'TabKey'
});
taRegisterTool('outdent', {
iconclass: 'fa fa-outdent',
tooltiptext: taTranslations.outdent.tooltip,
action: function(){
return this.$editor().wrapSelection("outdent", null);
},
activeState: function(){
return false;
},
commandKeyCode: 'ShiftTabKey'
});
taRegisterTool('italics', {
iconclass: 'fa fa-italic',
tooltiptext: taTranslations.italic.tooltip,
action: function(){
return this.$editor().wrapSelection("italic", null);
},
activeState: function(){
return this.$editor().queryCommandState('italic');
},
commandKeyCode: 105
});
taRegisterTool('underline', {
iconclass: 'fa fa-underline',
tooltiptext: taTranslations.underline.tooltip,
action: function(){
return this.$editor().wrapSelection("underline", null);
},
activeState: function(){
return this.$editor().queryCommandState('underline');
},
commandKeyCode: 117
});
taRegisterTool('strikeThrough', {
iconclass: 'fa fa-strikethrough',
tooltiptext: taTranslations.strikeThrough.tooltip,
action: function(){
return this.$editor().wrapSelection("strikeThrough", null);
},
activeState: function(){
return document.queryCommandState('strikeThrough');
}
});
taRegisterTool('clear', {
iconclass: 'fa fa-ban',
tooltiptext: taTranslations.clear.tooltip,
action: function(deferred, restoreSelection){
var i;
this.$editor().wrapSelection("removeFormat", null);
var possibleNodes = angular.element(taSelection.getSelectionElement());
// remove lists
var removeListElements = function(list){
list = angular.element(list);
var prevElement = list;
angular.forEach(list.children(), function(liElem){
var newElem = angular.element('<p></p>');
newElem.html(angular.element(liElem).html());
prevElement.after(newElem);
prevElement = newElem;
});
list.remove();
};
angular.forEach(possibleNodes.find("ul"), removeListElements);
angular.forEach(possibleNodes.find("ol"), removeListElements);
if(possibleNodes[0].tagName.toLowerCase() === 'li'){
var _list = possibleNodes[0].parentNode.childNodes;
var _preLis = [], _postLis = [], _found = false;
for(i = 0; i < _list.length; i++){
if(_list[i] === possibleNodes[0]){
_found = true;
}else if(!_found) _preLis.push(_list[i]);
else _postLis.push(_list[i]);
}
var _parent = angular.element(possibleNodes[0].parentNode);
var newElem = angular.element('<p></p>');
newElem.html(angular.element(possibleNodes[0]).html());
if(_preLis.length === 0 || _postLis.length === 0){
if(_postLis.length === 0) _parent.after(newElem);
else _parent[0].parentNode.insertBefore(newElem[0], _parent[0]);
if(_preLis.length === 0 && _postLis.length === 0) _parent.remove();
else angular.element(possibleNodes[0]).remove();
}else{
var _firstList = angular.element('<'+_parent[0].tagName+'></'+_parent[0].tagName+'>');
var _secondList = angular.element('<'+_parent[0].tagName+'></'+_parent[0].tagName+'>');
for(i = 0; i < _preLis.length; i++) _firstList.append(angular.element(_preLis[i]));
for(i = 0; i < _postLis.length; i++) _secondList.append(angular.element(_postLis[i]));
_parent.after(_secondList);
_parent.after(newElem);
_parent.after(_firstList);
_parent.remove();
}
taSelection.setSelectionToElementEnd(newElem[0]);
}
// clear out all class attributes. These do not seem to be cleared via removeFormat
var $editor = this.$editor();
var recursiveRemoveClass = function(node){
node = angular.element(node);
if(node[0] !== $editor.displayElements.text[0]) node.removeAttr('class');
angular.forEach(node.children(), recursiveRemoveClass);
};
angular.forEach(possibleNodes, recursiveRemoveClass);
// check if in list. If not in list then use formatBlock option
if(possibleNodes[0].tagName.toLowerCase() !== 'li' &&
possibleNodes[0].tagName.toLowerCase() !== 'ol' &&
possibleNodes[0].tagName.toLowerCase() !== 'ul') this.$editor().wrapSelection("formatBlock", "default");
restoreSelection();
}
});
taRegisterTool('insertImage', {
iconclass: 'fa fa-picture-o',
tooltiptext: taTranslations.insertImage.tooltip,
action: function(){
var imageLink;
imageLink = $window.prompt(taTranslations.insertImage.dialogPrompt, 'http://');
if(imageLink && imageLink !== '' && imageLink !== 'http://'){
return this.$editor().wrapSelection('insertImage', imageLink, true);
}
},
onElementSelect: {
element: 'img',
action: taToolFunctions.imgOnSelectAction
}
});
taRegisterTool('insertVideo', {
iconclass: 'fa fa-youtube-play',
tooltiptext: taTranslations.insertVideo.tooltip,
action: function(){
var urlPrompt;
urlPrompt = $window.prompt(taTranslations.insertVideo.dialogPrompt, 'https://');
if (urlPrompt && urlPrompt !== '' && urlPrompt !== 'https://') {
videoId = taToolFunctions.extractYoutubeVideoId(urlPrompt);
/* istanbul ignore else: if it's invalid don't worry - though probably should show some kind of error message */
if(videoId){
// create the embed link
var urlLink = "https://www.youtube.com/embed/" + videoId;
// create the HTML
// for all options see: http://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
// maxresdefault.jpg seems to be undefined on some.
var embed = '<img class="ta-insert-video" src="https://img.youtube.com/vi/' + videoId + '/hqdefault.jpg" ta-insert-video="' + urlLink + '" contenteditable="false" allowfullscreen="true" frameborder="0" />';
// insert
return this.$editor().wrapSelection('insertHTML', embed, true);
}
}
},
onElementSelect: {
element: 'img',
onlyWithAttrs: ['ta-insert-video'],
action: taToolFunctions.imgOnSelectAction
}
});
taRegisterTool('insertLink', {
tooltiptext: taTranslations.insertLink.tooltip,
iconclass: 'fa fa-link',
action: function(){
var urlLink;
urlLink = $window.prompt(taTranslations.insertLink.dialogPrompt, 'http://');
if(urlLink && urlLink !== '' && urlLink !== 'http://'){
return this.$editor().wrapSelection('createLink', urlLink, true);
}
},
activeState: function(commonElement){
if(commonElement) return commonElement[0].tagName === 'A';
return false;
},
onElementSelect: {
element: 'a',
action: taToolFunctions.aOnSelectAction
}
});
taRegisterTool('wordcount', {
display: '<div id="toolbarWC" style="display:block; min-width:100px;">Words: <span ng-bind="wordcount"></span></div>',
disabled: true,
wordcount: 0,
activeState: function(){ // this fires on keyup
var textElement = this.$editor().displayElements.text;
/* istanbul ignore next: will default to '' when undefined */
var workingHTML = textElement[0].innerHTML || '';
var noOfWords = 0;
/* istanbul ignore if: will default to '' when undefined */
if (workingHTML.replace(/\s*<[^>]*?>\s*/g, '') !== '') {
noOfWords = workingHTML.replace(/<\/?(b|i|em|strong|span|u|strikethrough|a|img|small|sub|sup|label)( [^>*?])?>/gi, '') // remove inline tags without adding spaces
.replace(/(<[^>]*?>\s*<[^>]*?>)/ig, ' ') // replace adjacent tags with possible space between with a space
.replace(/(<[^>]*?>)/ig, '') // remove any singular tags
.replace(/\s+/ig, ' ') // condense spacing
.match(/\S+/g).length; // count remaining non-space strings
}
//Set current scope
this.wordcount = noOfWords;
//Set editor scope
this.$editor().wordcount = noOfWords;
return false;
}
});
taRegisterTool('charcount', {
display: '<div id="toolbarCC" style="display:block; min-width:120px;">Characters: <span ng-bind="charcount"></span></div>',
disabled: true,
charcount: 0,
activeState: function(){ // this fires on keyup
var textElement = this.$editor().displayElements.text;
var sourceText = textElement[0].innerText || textElement[0].textContent; // to cover the non-jquery use case.
// Caculate number of chars
var noOfChars = sourceText.replace(/(\r\n|\n|\r)/gm,"").replace(/^\s+/g,' ').replace(/\s+$/g, ' ').length;
//Set current scope
this.charcount = noOfChars;
//Set editor scope
this.$editor().charcount = noOfChars;
return false;
}
});
}]);
/*
* angular-ui-bootstrap
* http://angular-ui.github.io/bootstrap/
* Version: 1.3.2 - 2016-04-14
* License: MIT
*/angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.collapse","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.dateparser","ui.bootstrap.isClass","ui.bootstrap.datepicker","ui.bootstrap.position","ui.bootstrap.datepickerPopup","ui.bootstrap.debounce","ui.bootstrap.dropdown","ui.bootstrap.stackedMap","ui.bootstrap.modal","ui.bootstrap.paging","ui.bootstrap.pager","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.typeahead"]);
angular.module("ui.bootstrap.tpls", ["uib/template/accordion/accordion-group.html","uib/template/accordion/accordion.html","uib/template/alert/alert.html","uib/template/carousel/carousel.html","uib/template/carousel/slide.html","uib/template/datepicker/datepicker.html","uib/template/datepicker/day.html","uib/template/datepicker/month.html","uib/template/datepicker/year.html","uib/template/datepickerPopup/popup.html","uib/template/modal/backdrop.html","uib/template/modal/window.html","uib/template/pager/pager.html","uib/template/pagination/pagination.html","uib/template/tooltip/tooltip-html-popup.html","uib/template/tooltip/tooltip-popup.html","uib/template/tooltip/tooltip-template-popup.html","uib/template/popover/popover-html.html","uib/template/popover/popover-template.html","uib/template/popover/popover.html","uib/template/progressbar/bar.html","uib/template/progressbar/progress.html","uib/template/progressbar/progressbar.html","uib/template/rating/rating.html","uib/template/tabs/tab.html","uib/template/tabs/tabset.html","uib/template/timepicker/timepicker.html","uib/template/typeahead/typeahead-match.html","uib/template/typeahead/typeahead-popup.html"]);
angular.module('ui.bootstrap.collapse', [])
.directive('uibCollapse', ['$animate', '$q', '$parse', '$injector', function($animate, $q, $parse, $injector) {
var $animateCss = $injector.has('$animateCss') ? $injector.get('$animateCss') : null;
return {
link: function(scope, element, attrs) {
var expandingExpr = $parse(attrs.expanding),
expandedExpr = $parse(attrs.expanded),
collapsingExpr = $parse(attrs.collapsing),
collapsedExpr = $parse(attrs.collapsed);
if (!scope.$eval(attrs.uibCollapse)) {
element.addClass('in')
.addClass('collapse')
.attr('aria-expanded', true)
.attr('aria-hidden', false)
.css({height: 'auto'});
}
function expand() {
if (element.hasClass('collapse') && element.hasClass('in')) {
return;
}
$q.resolve(expandingExpr(scope))
.then(function() {
element.removeClass('collapse')
.addClass('collapsing')
.attr('aria-expanded', true)
.attr('aria-hidden', false);
if ($animateCss) {
$animateCss(element, {
addClass: 'in',
easing: 'ease',
to: { height: element[0].scrollHeight + 'px' }
}).start()['finally'](expandDone);
} else {
$animate.addClass(element, 'in', {
to: { height: element[0].scrollHeight + 'px' }
}).then(expandDone);
}
});
}
function expandDone() {
element.removeClass('collapsing')
.addClass('collapse')
.css({height: 'auto'});
expandedExpr(scope);
}
function collapse() {
if (!element.hasClass('collapse') && !element.hasClass('in')) {
return collapseDone();
}
$q.resolve(collapsingExpr(scope))
.then(function() {
element
// IMPORTANT: The height must be set before adding "collapsing" class.
// Otherwise, the browser attempts to animate from height 0 (in
// collapsing class) to the given height here.
.css({height: element[0].scrollHeight + 'px'})
// initially all panel collapse have the collapse class, this removal
// prevents the animation from jumping to collapsed state
.removeClass('collapse')
.addClass('collapsing')
.attr('aria-expanded', false)
.attr('aria-hidden', true);
if ($animateCss) {
$animateCss(element, {
removeClass: 'in',
to: {height: '0'}
}).start()['finally'](collapseDone);
} else {
$animate.removeClass(element, 'in', {
to: {height: '0'}
}).then(collapseDone);
}
});
}
function collapseDone() {
element.css({height: '0'}); // Required so that collapse works when animation is disabled
element.removeClass('collapsing')
.addClass('collapse');
collapsedExpr(scope);
}
scope.$watch(attrs.uibCollapse, function(shouldCollapse) {
if (shouldCollapse) {
collapse();
} else {
expand();
}
});
}
};
}]);
angular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse'])
.constant('uibAccordionConfig', {
closeOthers: true
})
.controller('UibAccordionController', ['$scope', '$attrs', 'uibAccordionConfig', function($scope, $attrs, accordionConfig) {
// This array keeps track of the accordion groups
this.groups = [];
// Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to
this.closeOthers = function(openGroup) {
var closeOthers = angular.isDefined($attrs.closeOthers) ?
$scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers;
if (closeOthers) {
angular.forEach(this.groups, function(group) {
if (group !== openGroup) {
group.isOpen = false;
}
});
}
};
// This is called from the accordion-group directive to add itself to the accordion
this.addGroup = function(groupScope) {
var that = this;
this.groups.push(groupScope);
groupScope.$on('$destroy', function(event) {
that.removeGroup(groupScope);
});
};
// This is called from the accordion-group directive when to remove itself
this.removeGroup = function(group) {
var index = this.groups.indexOf(group);
if (index !== -1) {
this.groups.splice(index, 1);
}
};
}])
// The accordion directive simply sets up the directive controller
// and adds an accordion CSS class to itself element.
.directive('uibAccordion', function() {
return {
controller: 'UibAccordionController',
controllerAs: 'accordion',
transclude: true,
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/accordion/accordion.html';
}
};
})
// The accordion-group directive indicates a block of html that will expand and collapse in an accordion
.directive('uibAccordionGroup', function() {
return {
require: '^uibAccordion', // We need this directive to be inside an accordion
transclude: true, // It transcludes the contents of the directive into the template
replace: true, // The element containing the directive will be replaced with the template
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/accordion/accordion-group.html';
},
scope: {
heading: '@', // Interpolate the heading attribute onto this scope
panelClass: '@?', // Ditto with panelClass
isOpen: '=?',
isDisabled: '=?'
},
controller: function() {
this.setHeading = function(element) {
this.heading = element;
};
},
link: function(scope, element, attrs, accordionCtrl) {
accordionCtrl.addGroup(scope);
scope.openClass = attrs.openClass || 'panel-open';
scope.panelClass = attrs.panelClass || 'panel-default';
scope.$watch('isOpen', function(value) {
element.toggleClass(scope.openClass, !!value);
if (value) {
accordionCtrl.closeOthers(scope);
}
});
scope.toggleOpen = function($event) {
if (!scope.isDisabled) {
if (!$event || $event.which === 32) {
scope.isOpen = !scope.isOpen;
}
}
};
var id = 'accordiongroup-' + scope.$id + '-' + Math.floor(Math.random() * 10000);
scope.headingId = id + '-tab';
scope.panelId = id + '-panel';
}
};
})
// Use accordion-heading below an accordion-group to provide a heading containing HTML
.directive('uibAccordionHeading', function() {
return {
transclude: true, // Grab the contents to be used as the heading
template: '', // In effect remove this element!
replace: true,
require: '^uibAccordionGroup',
link: function(scope, element, attrs, accordionGroupCtrl, transclude) {
// Pass the heading to the accordion-group controller
// so that it can be transcluded into the right place in the template
// [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat]
accordionGroupCtrl.setHeading(transclude(scope, angular.noop));
}
};
})
// Use in the accordion-group template to indicate where you want the heading to be transcluded
// You must provide the property on the accordion-group controller that will hold the transcluded element
.directive('uibAccordionTransclude', function() {
return {
require: '^uibAccordionGroup',
link: function(scope, element, attrs, controller) {
scope.$watch(function() { return controller[attrs.uibAccordionTransclude]; }, function(heading) {
if (heading) {
var elem = angular.element(element[0].querySelector('[uib-accordion-header]'));
elem.html('');
elem.append(heading);
}
});
}
};
});
angular.module('ui.bootstrap.alert', [])
.controller('UibAlertController', ['$scope', '$attrs', '$interpolate', '$timeout', function($scope, $attrs, $interpolate, $timeout) {
$scope.closeable = !!$attrs.close;
var dismissOnTimeout = angular.isDefined($attrs.dismissOnTimeout) ?
$interpolate($attrs.dismissOnTimeout)($scope.$parent) : null;
if (dismissOnTimeout) {
$timeout(function() {
$scope.close();
}, parseInt(dismissOnTimeout, 10));
}
}])
.directive('uibAlert', function() {
return {
controller: 'UibAlertController',
controllerAs: 'alert',
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/alert/alert.html';
},
transclude: true,
replace: true,
scope: {
type: '@',
close: '&'
}
};
});
angular.module('ui.bootstrap.buttons', [])
.constant('uibButtonConfig', {
activeClass: 'active',
toggleEvent: 'click'
})
.controller('UibButtonsController', ['uibButtonConfig', function(buttonConfig) {
this.activeClass = buttonConfig.activeClass || 'active';
this.toggleEvent = buttonConfig.toggleEvent || 'click';
}])
.directive('uibBtnRadio', ['$parse', function($parse) {
return {
require: ['uibBtnRadio', 'ngModel'],
controller: 'UibButtonsController',
controllerAs: 'buttons',
link: function(scope, element, attrs, ctrls) {
var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
var uncheckableExpr = $parse(attrs.uibUncheckable);
element.find('input').css({display: 'none'});
//model -> UI
ngModelCtrl.$render = function() {
element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.uibBtnRadio)));
};
//ui->model
element.on(buttonsCtrl.toggleEvent, function() {
if (attrs.disabled) {
return;
}
var isActive = element.hasClass(buttonsCtrl.activeClass);
if (!isActive || angular.isDefined(attrs.uncheckable)) {
scope.$apply(function() {
ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.uibBtnRadio));
ngModelCtrl.$render();
});
}
});
if (attrs.uibUncheckable) {
scope.$watch(uncheckableExpr, function(uncheckable) {
attrs.$set('uncheckable', uncheckable ? '' : undefined);
});
}
}
};
}])
.directive('uibBtnCheckbox', function() {
return {
require: ['uibBtnCheckbox', 'ngModel'],
controller: 'UibButtonsController',
controllerAs: 'button',
link: function(scope, element, attrs, ctrls) {
var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
element.find('input').css({display: 'none'});
function getTrueValue() {
return getCheckboxValue(attrs.btnCheckboxTrue, true);
}
function getFalseValue() {
return getCheckboxValue(attrs.btnCheckboxFalse, false);
}
function getCheckboxValue(attribute, defaultValue) {
return angular.isDefined(attribute) ? scope.$eval(attribute) : defaultValue;
}
//model -> UI
ngModelCtrl.$render = function() {
element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue()));
};
//ui->model
element.on(buttonsCtrl.toggleEvent, function() {
if (attrs.disabled) {
return;
}
scope.$apply(function() {
ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());
ngModelCtrl.$render();
});
});
}
};
});
angular.module('ui.bootstrap.carousel', [])
.controller('UibCarouselController', ['$scope', '$element', '$interval', '$timeout', '$animate', function($scope, $element, $interval, $timeout, $animate) {
var self = this,
slides = self.slides = $scope.slides = [],
SLIDE_DIRECTION = 'uib-slideDirection',
currentIndex = $scope.active,
currentInterval, isPlaying, bufferedTransitions = [];
var destroyed = false;
self.addSlide = function(slide, element) {
slides.push({
slide: slide,
element: element
});
slides.sort(function(a, b) {
return +a.slide.index - +b.slide.index;
});
//if this is the first slide or the slide is set to active, select it
if (slide.index === $scope.active || slides.length === 1 && !angular.isNumber($scope.active)) {
if ($scope.$currentTransition) {
$scope.$currentTransition = null;
}
currentIndex = slide.index;
$scope.active = slide.index;
setActive(currentIndex);
self.select(slides[findSlideIndex(slide)]);
if (slides.length === 1) {
$scope.play();
}
}
};
self.getCurrentIndex = function() {
for (var i = 0; i < slides.length; i++) {
if (slides[i].slide.index === currentIndex) {
return i;
}
}
};
self.next = $scope.next = function() {
var newIndex = (self.getCurrentIndex() + 1) % slides.length;
if (newIndex === 0 && $scope.noWrap()) {
$scope.pause();
return;
}
return self.select(slides[newIndex], 'next');
};
self.prev = $scope.prev = function() {
var newIndex = self.getCurrentIndex() - 1 < 0 ? slides.length - 1 : self.getCurrentIndex() - 1;
if ($scope.noWrap() && newIndex === slides.length - 1) {
$scope.pause();
return;
}
return self.select(slides[newIndex], 'prev');
};
self.removeSlide = function(slide) {
var index = findSlideIndex(slide);
var bufferedIndex = bufferedTransitions.indexOf(slides[index]);
if (bufferedIndex !== -1) {
bufferedTransitions.splice(bufferedIndex, 1);
}
//get the index of the slide inside the carousel
slides.splice(index, 1);
if (slides.length > 0 && currentIndex === index) {
if (index >= slides.length) {
currentIndex = slides.length - 1;
$scope.active = currentIndex;
setActive(currentIndex);
self.select(slides[slides.length - 1]);
} else {
currentIndex = index;
$scope.active = currentIndex;
setActive(currentIndex);
self.select(slides[index]);
}
} else if (currentIndex > index) {
currentIndex--;
$scope.active = currentIndex;
}
//clean the active value when no more slide
if (slides.length === 0) {
currentIndex = null;
$scope.active = null;
clearBufferedTransitions();
}
};
/* direction: "prev" or "next" */
self.select = $scope.select = function(nextSlide, direction) {
var nextIndex = findSlideIndex(nextSlide.slide);
//Decide direction if it's not given
if (direction === undefined) {
direction = nextIndex > self.getCurrentIndex() ? 'next' : 'prev';
}
//Prevent this user-triggered transition from occurring if there is already one in progress
if (nextSlide.slide.index !== currentIndex &&
!$scope.$currentTransition) {
goNext(nextSlide.slide, nextIndex, direction);
} else if (nextSlide && nextSlide.slide.index !== currentIndex && $scope.$currentTransition) {
bufferedTransitions.push(slides[nextIndex]);
}
};
/* Allow outside people to call indexOf on slides array */
$scope.indexOfSlide = function(slide) {
return +slide.slide.index;
};
$scope.isActive = function(slide) {
return $scope.active === slide.slide.index;
};
$scope.isPrevDisabled = function() {
return $scope.active === 0 && $scope.noWrap();
};
$scope.isNextDisabled = function() {
return $scope.active === slides.length - 1 && $scope.noWrap();
};
$scope.pause = function() {
if (!$scope.noPause) {
isPlaying = false;
resetTimer();
}
};
$scope.play = function() {
if (!isPlaying) {
isPlaying = true;
restartTimer();
}
};
$scope.$on('$destroy', function() {
destroyed = true;
resetTimer();
});
$scope.$watch('noTransition', function(noTransition) {
$animate.enabled($element, !noTransition);
});
$scope.$watch('interval', restartTimer);
$scope.$watchCollection('slides', resetTransition);
$scope.$watch('active', function(index) {
if (angular.isNumber(index) && currentIndex !== index) {
for (var i = 0; i < slides.length; i++) {
if (slides[i].slide.index === index) {
index = i;
break;
}
}
var slide = slides[index];
if (slide) {
setActive(index);
self.select(slides[index]);
currentIndex = index;
}
}
});
function clearBufferedTransitions() {
while (bufferedTransitions.length) {
bufferedTransitions.shift();
}
}
function getSlideByIndex(index) {
for (var i = 0, l = slides.length; i < l; ++i) {
if (slides[i].index === index) {
return slides[i];
}
}
}
function setActive(index) {
for (var i = 0; i < slides.length; i++) {
slides[i].slide.active = i === index;
}
}
function goNext(slide, index, direction) {
if (destroyed) {
return;
}
angular.extend(slide, {direction: direction});
angular.extend(slides[currentIndex].slide || {}, {direction: direction});
if ($animate.enabled($element) && !$scope.$currentTransition &&
slides[index].element && self.slides.length > 1) {
slides[index].element.data(SLIDE_DIRECTION, slide.direction);
var currentIdx = self.getCurrentIndex();
if (angular.isNumber(currentIdx) && slides[currentIdx].element) {
slides[currentIdx].element.data(SLIDE_DIRECTION, slide.direction);
}
$scope.$currentTransition = true;
$animate.on('addClass', slides[index].element, function(element, phase) {
if (phase === 'close') {
$scope.$currentTransition = null;
$animate.off('addClass', element);
if (bufferedTransitions.length) {
var nextSlide = bufferedTransitions.pop().slide;
var nextIndex = nextSlide.index;
var nextDirection = nextIndex > self.getCurrentIndex() ? 'next' : 'prev';
clearBufferedTransitions();
goNext(nextSlide, nextIndex, nextDirection);
}
}
});
}
$scope.active = slide.index;
currentIndex = slide.index;
setActive(index);
//every time you change slides, reset the timer
restartTimer();
}
function findSlideIndex(slide) {
for (var i = 0; i < slides.length; i++) {
if (slides[i].slide === slide) {
return i;
}
}
}
function resetTimer() {
if (currentInterval) {
$interval.cancel(currentInterval);
currentInterval = null;
}
}
function resetTransition(slides) {
if (!slides.length) {
$scope.$currentTransition = null;
clearBufferedTransitions();
}
}
function restartTimer() {
resetTimer();
var interval = +$scope.interval;
if (!isNaN(interval) && interval > 0) {
currentInterval = $interval(timerFn, interval);
}
}
function timerFn() {
var interval = +$scope.interval;
if (isPlaying && !isNaN(interval) && interval > 0 && slides.length) {
$scope.next();
} else {
$scope.pause();
}
}
}])
.directive('uibCarousel', function() {
return {
transclude: true,
replace: true,
controller: 'UibCarouselController',
controllerAs: 'carousel',
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/carousel/carousel.html';
},
scope: {
active: '=',
interval: '=',
noTransition: '=',
noPause: '=',
noWrap: '&'
}
};
})
.directive('uibSlide', function() {
return {
require: '^uibCarousel',
transclude: true,
replace: true,
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/carousel/slide.html';
},
scope: {
actual: '=?',
index: '=?'
},
link: function (scope, element, attrs, carouselCtrl) {
carouselCtrl.addSlide(scope, element);
//when the scope is destroyed then remove the slide from the current slides array
scope.$on('$destroy', function() {
carouselCtrl.removeSlide(scope);
});
}
};
})
.animation('.item', ['$animateCss',
function($animateCss) {
var SLIDE_DIRECTION = 'uib-slideDirection';
function removeClass(element, className, callback) {
element.removeClass(className);
if (callback) {
callback();
}
}
return {
beforeAddClass: function(element, className, done) {
if (className === 'active') {
var stopped = false;
var direction = element.data(SLIDE_DIRECTION);
var directionClass = direction === 'next' ? 'left' : 'right';
var removeClassFn = removeClass.bind(this, element,
directionClass + ' ' + direction, done);
element.addClass(direction);
$animateCss(element, {addClass: directionClass})
.start()
.done(removeClassFn);
return function() {
stopped = true;
};
}
done();
},
beforeRemoveClass: function (element, className, done) {
if (className === 'active') {
var stopped = false;
var direction = element.data(SLIDE_DIRECTION);
var directionClass = direction === 'next' ? 'left' : 'right';
var removeClassFn = removeClass.bind(this, element, directionClass, done);
$animateCss(element, {addClass: directionClass})
.start()
.done(removeClassFn);
return function() {
stopped = true;
};
}
done();
}
};
}]);
angular.module('ui.bootstrap.dateparser', [])
.service('uibDateParser', ['$log', '$locale', 'dateFilter', 'orderByFilter', function($log, $locale, dateFilter, orderByFilter) {
// Pulled from https://github.com/mbostock/d3/blob/master/src/format/requote.js
var SPECIAL_CHARACTERS_REGEXP = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
var localeId;
var formatCodeToRegex;
this.init = function() {
localeId = $locale.id;
this.parsers = {};
this.formatters = {};
formatCodeToRegex = [
{
key: 'yyyy',
regex: '\\d{4}',
apply: function(value) { this.year = +value; },
formatter: function(date) {
var _date = new Date();
_date.setFullYear(Math.abs(date.getFullYear()));
return dateFilter(_date, 'yyyy');
}
},
{
key: 'yy',
regex: '\\d{2}',
apply: function(value) { value = +value; this.year = value < 69 ? value + 2000 : value + 1900; },
formatter: function(date) {
var _date = new Date();
_date.setFullYear(Math.abs(date.getFullYear()));
return dateFilter(_date, 'yy');
}
},
{
key: 'y',
regex: '\\d{1,4}',
apply: function(value) { this.year = +value; },
formatter: function(date) {
var _date = new Date();
_date.setFullYear(Math.abs(date.getFullYear()));
return dateFilter(_date, 'y');
}
},
{
key: 'M!',
regex: '0?[1-9]|1[0-2]',
apply: function(value) { this.month = value - 1; },
formatter: function(date) {
var value = date.getMonth();
if (/^[0-9]$/.test(value)) {
return dateFilter(date, 'MM');
}
return dateFilter(date, 'M');
}
},
{
key: 'MMMM',
regex: $locale.DATETIME_FORMATS.MONTH.join('|'),
apply: function(value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); },
formatter: function(date) { return dateFilter(date, 'MMMM'); }
},
{
key: 'MMM',
regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),
apply: function(value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); },
formatter: function(date) { return dateFilter(date, 'MMM'); }
},
{
key: 'MM',
regex: '0[1-9]|1[0-2]',
apply: function(value) { this.month = value - 1; },
formatter: function(date) { return dateFilter(date, 'MM'); }
},
{
key: 'M',
regex: '[1-9]|1[0-2]',
apply: function(value) { this.month = value - 1; },
formatter: function(date) { return dateFilter(date, 'M'); }
},
{
key: 'd!',
regex: '[0-2]?[0-9]{1}|3[0-1]{1}',
apply: function(value) { this.date = +value; },
formatter: function(date) {
var value = date.getDate();
if (/^[1-9]$/.test(value)) {
return dateFilter(date, 'dd');
}
return dateFilter(date, 'd');
}
},
{
key: 'dd',
regex: '[0-2][0-9]{1}|3[0-1]{1}',
apply: function(value) { this.date = +value; },
formatter: function(date) { return dateFilter(date, 'dd'); }
},
{
key: 'd',
regex: '[1-2]?[0-9]{1}|3[0-1]{1}',
apply: function(value) { this.date = +value; },
formatter: function(date) { return dateFilter(date, 'd'); }
},
{
key: 'EEEE',
regex: $locale.DATETIME_FORMATS.DAY.join('|'),
formatter: function(date) { return dateFilter(date, 'EEEE'); }
},
{
key: 'EEE',
regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|'),
formatter: function(date) { return dateFilter(date, 'EEE'); }
},
{
key: 'HH',
regex: '(?:0|1)[0-9]|2[0-3]',
apply: function(value) { this.hours = +value; },
formatter: function(date) { return dateFilter(date, 'HH'); }
},
{
key: 'hh',
regex: '0[0-9]|1[0-2]',
apply: function(value) { this.hours = +value; },
formatter: function(date) { return dateFilter(date, 'hh'); }
},
{
key: 'H',
regex: '1?[0-9]|2[0-3]',
apply: function(value) { this.hours = +value; },
formatter: function(date) { return dateFilter(date, 'H'); }
},
{
key: 'h',
regex: '[0-9]|1[0-2]',
apply: function(value) { this.hours = +value; },
formatter: function(date) { return dateFilter(date, 'h'); }
},
{
key: 'mm',
regex: '[0-5][0-9]',
apply: function(value) { this.minutes = +value; },
formatter: function(date) { return dateFilter(date, 'mm'); }
},
{
key: 'm',
regex: '[0-9]|[1-5][0-9]',
apply: function(value) { this.minutes = +value; },
formatter: function(date) { return dateFilter(date, 'm'); }
},
{
key: 'sss',
regex: '[0-9][0-9][0-9]',
apply: function(value) { this.milliseconds = +value; },
formatter: function(date) { return dateFilter(date, 'sss'); }
},
{
key: 'ss',
regex: '[0-5][0-9]',
apply: function(value) { this.seconds = +value; },
formatter: function(date) { return dateFilter(date, 'ss'); }
},
{
key: 's',
regex: '[0-9]|[1-5][0-9]',
apply: function(value) { this.seconds = +value; },
formatter: function(date) { return dateFilter(date, 's'); }
},
{
key: 'a',
regex: $locale.DATETIME_FORMATS.AMPMS.join('|'),
apply: function(value) {
if (this.hours === 12) {
this.hours = 0;
}
if (value === 'PM') {
this.hours += 12;
}
},
formatter: function(date) { return dateFilter(date, 'a'); }
},
{
key: 'Z',
regex: '[+-]\\d{4}',
apply: function(value) {
var matches = value.match(/([+-])(\d{2})(\d{2})/),
sign = matches[1],
hours = matches[2],
minutes = matches[3];
this.hours += toInt(sign + hours);
this.minutes += toInt(sign + minutes);
},
formatter: function(date) {
return dateFilter(date, 'Z');
}
},
{
key: 'ww',
regex: '[0-4][0-9]|5[0-3]',
formatter: function(date) { return dateFilter(date, 'ww'); }
},
{
key: 'w',
regex: '[0-9]|[1-4][0-9]|5[0-3]',
formatter: function(date) { return dateFilter(date, 'w'); }
},
{
key: 'GGGG',
regex: $locale.DATETIME_FORMATS.ERANAMES.join('|').replace(/\s/g, '\\s'),
formatter: function(date) { return dateFilter(date, 'GGGG'); }
},
{
key: 'GGG',
regex: $locale.DATETIME_FORMATS.ERAS.join('|'),
formatter: function(date) { return dateFilter(date, 'GGG'); }
},
{
key: 'GG',
regex: $locale.DATETIME_FORMATS.ERAS.join('|'),
formatter: function(date) { return dateFilter(date, 'GG'); }
},
{
key: 'G',
regex: $locale.DATETIME_FORMATS.ERAS.join('|'),
formatter: function(date) { return dateFilter(date, 'G'); }
}
];
};
this.init();
function createParser(format, func) {
var map = [], regex = format.split('');
// check for literal values
var quoteIndex = format.indexOf('\'');
if (quoteIndex > -1) {
var inLiteral = false;
format = format.split('');
for (var i = quoteIndex; i < format.length; i++) {
if (inLiteral) {
if (format[i] === '\'') {
if (i + 1 < format.length && format[i+1] === '\'') { // escaped single quote
format[i+1] = '$';
regex[i+1] = '';
} else { // end of literal
regex[i] = '';
inLiteral = false;
}
}
format[i] = '$';
} else {
if (format[i] === '\'') { // start of literal
format[i] = '$';
regex[i] = '';
inLiteral = true;
}
}
}
format = format.join('');
}
angular.forEach(formatCodeToRegex, function(data) {
var index = format.indexOf(data.key);
if (index > -1) {
format = format.split('');
regex[index] = '(' + data.regex + ')';
format[index] = '$'; // Custom symbol to define consumed part of format
for (var i = index + 1, n = index + data.key.length; i < n; i++) {
regex[i] = '';
format[i] = '$';
}
format = format.join('');
map.push({
index: index,
key: data.key,
apply: data[func],
matcher: data.regex
});
}
});
return {
regex: new RegExp('^' + regex.join('') + '$'),
map: orderByFilter(map, 'index')
};
}
this.filter = function(date, format) {
if (!angular.isDate(date) || isNaN(date) || !format) {
return '';
}
format = $locale.DATETIME_FORMATS[format] || format;
if ($locale.id !== localeId) {
this.init();
}
if (!this.formatters[format]) {
this.formatters[format] = createParser(format, 'formatter');
}
var parser = this.formatters[format],
map = parser.map;
var _format = format;
return map.reduce(function(str, mapper, i) {
var match = _format.match(new RegExp('(.*)' + mapper.key));
if (match && angular.isString(match[1])) {
str += match[1];
_format = _format.replace(match[1] + mapper.key, '');
}
var endStr = i === map.length - 1 ? _format : '';
if (mapper.apply) {
return str + mapper.apply.call(null, date) + endStr;
}
return str + endStr;
}, '');
};
this.parse = function(input, format, baseDate) {
if (!angular.isString(input) || !format) {
return input;
}
format = $locale.DATETIME_FORMATS[format] || format;
format = format.replace(SPECIAL_CHARACTERS_REGEXP, '\\$&');
if ($locale.id !== localeId) {
this.init();
}
if (!this.parsers[format]) {
this.parsers[format] = createParser(format, 'apply');
}
var parser = this.parsers[format],
regex = parser.regex,
map = parser.map,
results = input.match(regex),
tzOffset = false;
if (results && results.length) {
var fields, dt;
if (angular.isDate(baseDate) && !isNaN(baseDate.getTime())) {
fields = {
year: baseDate.getFullYear(),
month: baseDate.getMonth(),
date: baseDate.getDate(),
hours: baseDate.getHours(),
minutes: baseDate.getMinutes(),
seconds: baseDate.getSeconds(),
milliseconds: baseDate.getMilliseconds()
};
} else {
if (baseDate) {
$log.warn('dateparser:', 'baseDate is not a valid date');
}
fields = { year: 1900, month: 0, date: 1, hours: 0, minutes: 0, seconds: 0, milliseconds: 0 };
}
for (var i = 1, n = results.length; i < n; i++) {
var mapper = map[i - 1];
if (mapper.matcher === 'Z') {
tzOffset = true;
}
if (mapper.apply) {
mapper.apply.call(fields, results[i]);
}
}
var datesetter = tzOffset ? Date.prototype.setUTCFullYear :
Date.prototype.setFullYear;
var timesetter = tzOffset ? Date.prototype.setUTCHours :
Date.prototype.setHours;
if (isValid(fields.year, fields.month, fields.date)) {
if (angular.isDate(baseDate) && !isNaN(baseDate.getTime()) && !tzOffset) {
dt = new Date(baseDate);
datesetter.call(dt, fields.year, fields.month, fields.date);
timesetter.call(dt, fields.hours, fields.minutes,
fields.seconds, fields.milliseconds);
} else {
dt = new Date(0);
datesetter.call(dt, fields.year, fields.month, fields.date);
timesetter.call(dt, fields.hours || 0, fields.minutes || 0,
fields.seconds || 0, fields.milliseconds || 0);
}
}
return dt;
}
};
// Check if date is valid for specific month (and year for February).
// Month: 0 = Jan, 1 = Feb, etc
function isValid(year, month, date) {
if (date < 1) {
return false;
}
if (month === 1 && date > 28) {
return date === 29 && (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0);
}
if (month === 3 || month === 5 || month === 8 || month === 10) {
return date < 31;
}
return true;
}
function toInt(str) {
return parseInt(str, 10);
}
this.toTimezone = toTimezone;
this.fromTimezone = fromTimezone;
this.timezoneToOffset = timezoneToOffset;
this.addDateMinutes = addDateMinutes;
this.convertTimezoneToLocal = convertTimezoneToLocal;
function toTimezone(date, timezone) {
return date && timezone ? convertTimezoneToLocal(date, timezone) : date;
}
function fromTimezone(date, timezone) {
return date && timezone ? convertTimezoneToLocal(date, timezone, true) : date;
}
//https://github.com/angular/angular.js/blob/4daafd3dbe6a80d578f5a31df1bb99c77559543e/src/Angular.js#L1207
function timezoneToOffset(timezone, fallback) {
var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
}
function addDateMinutes(date, minutes) {
date = new Date(date.getTime());
date.setMinutes(date.getMinutes() + minutes);
return date;
}
function convertTimezoneToLocal(date, timezone, reverse) {
reverse = reverse ? -1 : 1;
var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
}
}]);
// Avoiding use of ng-class as it creates a lot of watchers when a class is to be applied to
// at most one element.
angular.module('ui.bootstrap.isClass', [])
.directive('uibIsClass', [
'$animate',
function ($animate) {
// 11111111 22222222
var ON_REGEXP = /^\s*([\s\S]+?)\s+on\s+([\s\S]+?)\s*$/;
// 11111111 22222222
var IS_REGEXP = /^\s*([\s\S]+?)\s+for\s+([\s\S]+?)\s*$/;
var dataPerTracked = {};
return {
restrict: 'A',
compile: function(tElement, tAttrs) {
var linkedScopes = [];
var instances = [];
var expToData = {};
var lastActivated = null;
var onExpMatches = tAttrs.uibIsClass.match(ON_REGEXP);
var onExp = onExpMatches[2];
var expsStr = onExpMatches[1];
var exps = expsStr.split(',');
return linkFn;
function linkFn(scope, element, attrs) {
linkedScopes.push(scope);
instances.push({
scope: scope,
element: element
});
exps.forEach(function(exp, k) {
addForExp(exp, scope);
});
scope.$on('$destroy', removeScope);
}
function addForExp(exp, scope) {
var matches = exp.match(IS_REGEXP);
var clazz = scope.$eval(matches[1]);
var compareWithExp = matches[2];
var data = expToData[exp];
if (!data) {
var watchFn = function(compareWithVal) {
var newActivated = null;
instances.some(function(instance) {
var thisVal = instance.scope.$eval(onExp);
if (thisVal === compareWithVal) {
newActivated = instance;
return true;
}
});
if (data.lastActivated !== newActivated) {
if (data.lastActivated) {
$animate.removeClass(data.lastActivated.element, clazz);
}
if (newActivated) {
$animate.addClass(newActivated.element, clazz);
}
data.lastActivated = newActivated;
}
};
expToData[exp] = data = {
lastActivated: null,
scope: scope,
watchFn: watchFn,
compareWithExp: compareWithExp,
watcher: scope.$watch(compareWithExp, watchFn)
};
}
data.watchFn(scope.$eval(compareWithExp));
}
function removeScope(e) {
var removedScope = e.targetScope;
var index = linkedScopes.indexOf(removedScope);
linkedScopes.splice(index, 1);
instances.splice(index, 1);
if (linkedScopes.length) {
var newWatchScope = linkedScopes[0];
angular.forEach(expToData, function(data) {
if (data.scope === removedScope) {
data.watcher = newWatchScope.$watch(data.compareWithExp, data.watchFn);
data.scope = newWatchScope;
}
});
} else {
expToData = {};
}
}
}
};
}]);
angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.isClass'])
.value('$datepickerSuppressError', false)
.value('$datepickerLiteralWarning', true)
.constant('uibDatepickerConfig', {
datepickerMode: 'day',
formatDay: 'dd',
formatMonth: 'MMMM',
formatYear: 'yyyy',
formatDayHeader: 'EEE',
formatDayTitle: 'MMMM yyyy',
formatMonthTitle: 'yyyy',
maxDate: null,
maxMode: 'year',
minDate: null,
minMode: 'day',
ngModelOptions: {},
shortcutPropagation: false,
showWeeks: true,
yearColumns: 5,
yearRows: 4
})
.controller('UibDatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$locale', '$log', 'dateFilter', 'uibDatepickerConfig', '$datepickerLiteralWarning', '$datepickerSuppressError', 'uibDateParser',
function($scope, $attrs, $parse, $interpolate, $locale, $log, dateFilter, datepickerConfig, $datepickerLiteralWarning, $datepickerSuppressError, dateParser) {
var self = this,
ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl;
ngModelOptions = {},
watchListeners = [],
optionsUsed = !!$attrs.datepickerOptions;
if (!$scope.datepickerOptions) {
$scope.datepickerOptions = {};
}
// Modes chain
this.modes = ['day', 'month', 'year'];
[
'customClass',
'dateDisabled',
'datepickerMode',
'formatDay',
'formatDayHeader',
'formatDayTitle',
'formatMonth',
'formatMonthTitle',
'formatYear',
'maxDate',
'maxMode',
'minDate',
'minMode',
'showWeeks',
'shortcutPropagation',
'startingDay',
'yearColumns',
'yearRows'
].forEach(function(key) {
switch (key) {
case 'customClass':
case 'dateDisabled':
$scope[key] = $scope.datepickerOptions[key] || angular.noop;
break;
case 'datepickerMode':
$scope.datepickerMode = angular.isDefined($scope.datepickerOptions.datepickerMode) ?
$scope.datepickerOptions.datepickerMode : datepickerConfig.datepickerMode;
break;
case 'formatDay':
case 'formatDayHeader':
case 'formatDayTitle':
case 'formatMonth':
case 'formatMonthTitle':
case 'formatYear':
self[key] = angular.isDefined($scope.datepickerOptions[key]) ?
$interpolate($scope.datepickerOptions[key])($scope.$parent) :
datepickerConfig[key];
break;
case 'showWeeks':
case 'shortcutPropagation':
case 'yearColumns':
case 'yearRows':
self[key] = angular.isDefined($scope.datepickerOptions[key]) ?
$scope.datepickerOptions[key] : datepickerConfig[key];
break;
case 'startingDay':
if (angular.isDefined($scope.datepickerOptions.startingDay)) {
self.startingDay = $scope.datepickerOptions.startingDay;
} else if (angular.isNumber(datepickerConfig.startingDay)) {
self.startingDay = datepickerConfig.startingDay;
} else {
self.startingDay = ($locale.DATETIME_FORMATS.FIRSTDAYOFWEEK + 8) % 7;
}
break;
case 'maxDate':
case 'minDate':
$scope.$watch('datepickerOptions.' + key, function(value) {
if (value) {
if (angular.isDate(value)) {
self[key] = dateParser.fromTimezone(new Date(value), ngModelOptions.timezone);
} else {
if ($datepickerLiteralWarning) {
$log.warn('Literal date support has been deprecated, please switch to date object usage');
}
self[key] = new Date(dateFilter(value, 'medium'));
}
} else {
self[key] = datepickerConfig[key] ?
dateParser.fromTimezone(new Date(datepickerConfig[key]), ngModelOptions.timezone) :
null;
}
self.refreshView();
});
break;
case 'maxMode':
case 'minMode':
if ($scope.datepickerOptions[key]) {
$scope.$watch(function() { return $scope.datepickerOptions[key]; }, function(value) {
self[key] = $scope[key] = angular.isDefined(value) ? value : datepickerOptions[key];
if (key === 'minMode' && self.modes.indexOf($scope.datepickerOptions.datepickerMode) < self.modes.indexOf(self[key]) ||
key === 'maxMode' && self.modes.indexOf($scope.datepickerOptions.datepickerMode) > self.modes.indexOf(self[key])) {
$scope.datepickerMode = self[key];
$scope.datepickerOptions.datepickerMode = self[key];
}
});
} else {
self[key] = $scope[key] = datepickerConfig[key] || null;
}
break;
}
});
$scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000);
$scope.disabled = angular.isDefined($attrs.disabled) || false;
if (angular.isDefined($attrs.ngDisabled)) {
watchListeners.push($scope.$parent.$watch($attrs.ngDisabled, function(disabled) {
$scope.disabled = disabled;
self.refreshView();
}));
}
$scope.isActive = function(dateObject) {
if (self.compare(dateObject.date, self.activeDate) === 0) {
$scope.activeDateId = dateObject.uid;
return true;
}
return false;
};
this.init = function(ngModelCtrl_) {
ngModelCtrl = ngModelCtrl_;
ngModelOptions = ngModelCtrl_.$options || datepickerConfig.ngModelOptions;
if ($scope.datepickerOptions.initDate) {
self.activeDate = dateParser.fromTimezone($scope.datepickerOptions.initDate, ngModelOptions.timezone) || new Date();
$scope.$watch('datepickerOptions.initDate', function(initDate) {
if (initDate && (ngModelCtrl.$isEmpty(ngModelCtrl.$modelValue) || ngModelCtrl.$invalid)) {
self.activeDate = dateParser.fromTimezone(initDate, ngModelOptions.timezone);
self.refreshView();
}
});
} else {
self.activeDate = new Date();
}
this.activeDate = ngModelCtrl.$modelValue ?
dateParser.fromTimezone(new Date(ngModelCtrl.$modelValue), ngModelOptions.timezone) :
dateParser.fromTimezone(new Date(), ngModelOptions.timezone);
ngModelCtrl.$render = function() {
self.render();
};
};
this.render = function() {
if (ngModelCtrl.$viewValue) {
var date = new Date(ngModelCtrl.$viewValue),
isValid = !isNaN(date);
if (isValid) {
this.activeDate = dateParser.fromTimezone(date, ngModelOptions.timezone);
} else if (!$datepickerSuppressError) {
$log.error('Datepicker directive: "ng-model" value must be a Date object');
}
}
this.refreshView();
};
this.refreshView = function() {
if (this.element) {
$scope.selectedDt = null;
this._refreshView();
if ($scope.activeDt) {
$scope.activeDateId = $scope.activeDt.uid;
}
var date = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null;
date = dateParser.fromTimezone(date, ngModelOptions.timezone);
ngModelCtrl.$setValidity('dateDisabled', !date ||
this.element && !this.isDisabled(date));
}
};
this.createDateObject = function(date, format) {
var model = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null;
model = dateParser.fromTimezone(model, ngModelOptions.timezone);
var today = new Date();
today = dateParser.fromTimezone(today, ngModelOptions.timezone);
var time = this.compare(date, today);
var dt = {
date: date,
label: dateParser.filter(date, format),
selected: model && this.compare(date, model) === 0,
disabled: this.isDisabled(date),
past: time < 0,
current: time === 0,
future: time > 0,
customClass: this.customClass(date) || null
};
if (model && this.compare(date, model) === 0) {
$scope.selectedDt = dt;
}
if (self.activeDate && this.compare(dt.date, self.activeDate) === 0) {
$scope.activeDt = dt;
}
return dt;
};
this.isDisabled = function(date) {
return $scope.disabled ||
this.minDate && this.compare(date, this.minDate) < 0 ||
this.maxDate && this.compare(date, this.maxDate) > 0 ||
$scope.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode});
};
this.customClass = function(date) {
return $scope.customClass({date: date, mode: $scope.datepickerMode});
};
// Split array into smaller arrays
this.split = function(arr, size) {
var arrays = [];
while (arr.length > 0) {
arrays.push(arr.splice(0, size));
}
return arrays;
};
$scope.select = function(date) {
if ($scope.datepickerMode === self.minMode) {
var dt = ngModelCtrl.$viewValue ? dateParser.fromTimezone(new Date(ngModelCtrl.$viewValue), ngModelOptions.timezone) : new Date(0, 0, 0, 0, 0, 0, 0);
dt.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
dt = dateParser.toTimezone(dt, ngModelOptions.timezone);
ngModelCtrl.$setViewValue(dt);
ngModelCtrl.$render();
} else {
self.activeDate = date;
setMode(self.modes[self.modes.indexOf($scope.datepickerMode) - 1]);
$scope.$emit('uib:datepicker.mode');
}
$scope.$broadcast('uib:datepicker.focus');
};
$scope.move = function(direction) {
var year = self.activeDate.getFullYear() + direction * (self.step.years || 0),
month = self.activeDate.getMonth() + direction * (self.step.months || 0);
self.activeDate.setFullYear(year, month, 1);
self.refreshView();
};
$scope.toggleMode = function(direction) {
direction = direction || 1;
if ($scope.datepickerMode === self.maxMode && direction === 1 ||
$scope.datepickerMode === self.minMode && direction === -1) {
return;
}
setMode(self.modes[self.modes.indexOf($scope.datepickerMode) + direction]);
$scope.$emit('uib:datepicker.mode');
};
// Key event mapper
$scope.keys = { 13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down' };
var focusElement = function() {
self.element[0].focus();
};
// Listen for focus requests from popup directive
$scope.$on('uib:datepicker.focus', focusElement);
$scope.keydown = function(evt) {
var key = $scope.keys[evt.which];
if (!key || evt.shiftKey || evt.altKey || $scope.disabled) {
return;
}
evt.preventDefault();
if (!self.shortcutPropagation) {
evt.stopPropagation();
}
if (key === 'enter' || key === 'space') {
if (self.isDisabled(self.activeDate)) {
return; // do nothing
}
$scope.select(self.activeDate);
} else if (evt.ctrlKey && (key === 'up' || key === 'down')) {
$scope.toggleMode(key === 'up' ? 1 : -1);
} else {
self.handleKeyDown(key, evt);
self.refreshView();
}
};
$scope.$on('$destroy', function() {
//Clear all watch listeners on destroy
while (watchListeners.length) {
watchListeners.shift()();
}
});
function setMode(mode) {
$scope.datepickerMode = mode;
$scope.datepickerOptions.datepickerMode = mode;
}
}])
.controller('UibDaypickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) {
var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
this.step = { months: 1 };
this.element = $element;
function getDaysInMonth(year, month) {
return month === 1 && year % 4 === 0 &&
(year % 100 !== 0 || year % 400 === 0) ? 29 : DAYS_IN_MONTH[month];
}
this.init = function(ctrl) {
angular.extend(ctrl, this);
scope.showWeeks = ctrl.showWeeks;
ctrl.refreshView();
};
this.getDates = function(startDate, n) {
var dates = new Array(n), current = new Date(startDate), i = 0, date;
while (i < n) {
date = new Date(current);
dates[i++] = date;
current.setDate(current.getDate() + 1);
}
return dates;
};
this._refreshView = function() {
var year = this.activeDate.getFullYear(),
month = this.activeDate.getMonth(),
firstDayOfMonth = new Date(this.activeDate);
firstDayOfMonth.setFullYear(year, month, 1);
var difference = this.startingDay - firstDayOfMonth.getDay(),
numDisplayedFromPreviousMonth = difference > 0 ?
7 - difference : - difference,
firstDate = new Date(firstDayOfMonth);
if (numDisplayedFromPreviousMonth > 0) {
firstDate.setDate(-numDisplayedFromPreviousMonth + 1);
}
// 42 is the number of days on a six-week calendar
var days = this.getDates(firstDate, 42);
for (var i = 0; i < 42; i ++) {
days[i] = angular.extend(this.createDateObject(days[i], this.formatDay), {
secondary: days[i].getMonth() !== month,
uid: scope.uniqueId + '-' + i
});
}
scope.labels = new Array(7);
for (var j = 0; j < 7; j++) {
scope.labels[j] = {
abbr: dateFilter(days[j].date, this.formatDayHeader),
full: dateFilter(days[j].date, 'EEEE')
};
}
scope.title = dateFilter(this.activeDate, this.formatDayTitle);
scope.rows = this.split(days, 7);
if (scope.showWeeks) {
scope.weekNumbers = [];
var thursdayIndex = (4 + 7 - this.startingDay) % 7,
numWeeks = scope.rows.length;
for (var curWeek = 0; curWeek < numWeeks; curWeek++) {
scope.weekNumbers.push(
getISO8601WeekNumber(scope.rows[curWeek][thursdayIndex].date));
}
}
};
this.compare = function(date1, date2) {
var _date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
var _date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
_date1.setFullYear(date1.getFullYear());
_date2.setFullYear(date2.getFullYear());
return _date1 - _date2;
};
function getISO8601WeekNumber(date) {
var checkDate = new Date(date);
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday
var time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
}
this.handleKeyDown = function(key, evt) {
var date = this.activeDate.getDate();
if (key === 'left') {
date = date - 1;
} else if (key === 'up') {
date = date - 7;
} else if (key === 'right') {
date = date + 1;
} else if (key === 'down') {
date = date + 7;
} else if (key === 'pageup' || key === 'pagedown') {
var month = this.activeDate.getMonth() + (key === 'pageup' ? - 1 : 1);
this.activeDate.setMonth(month, 1);
date = Math.min(getDaysInMonth(this.activeDate.getFullYear(), this.activeDate.getMonth()), date);
} else if (key === 'home') {
date = 1;
} else if (key === 'end') {
date = getDaysInMonth(this.activeDate.getFullYear(), this.activeDate.getMonth());
}
this.activeDate.setDate(date);
};
}])
.controller('UibMonthpickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) {
this.step = { years: 1 };
this.element = $element;
this.init = function(ctrl) {
angular.extend(ctrl, this);
ctrl.refreshView();
};
this._refreshView = function() {
var months = new Array(12),
year = this.activeDate.getFullYear(),
date;
for (var i = 0; i < 12; i++) {
date = new Date(this.activeDate);
date.setFullYear(year, i, 1);
months[i] = angular.extend(this.createDateObject(date, this.formatMonth), {
uid: scope.uniqueId + '-' + i
});
}
scope.title = dateFilter(this.activeDate, this.formatMonthTitle);
scope.rows = this.split(months, 3);
};
this.compare = function(date1, date2) {
var _date1 = new Date(date1.getFullYear(), date1.getMonth());
var _date2 = new Date(date2.getFullYear(), date2.getMonth());
_date1.setFullYear(date1.getFullYear());
_date2.setFullYear(date2.getFullYear());
return _date1 - _date2;
};
this.handleKeyDown = function(key, evt) {
var date = this.activeDate.getMonth();
if (key === 'left') {
date = date - 1;
} else if (key === 'up') {
date = date - 3;
} else if (key === 'right') {
date = date + 1;
} else if (key === 'down') {
date = date + 3;
} else if (key === 'pageup' || key === 'pagedown') {
var year = this.activeDate.getFullYear() + (key === 'pageup' ? - 1 : 1);
this.activeDate.setFullYear(year);
} else if (key === 'home') {
date = 0;
} else if (key === 'end') {
date = 11;
}
this.activeDate.setMonth(date);
};
}])
.controller('UibYearpickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) {
var columns, range;
this.element = $element;
function getStartingYear(year) {
return parseInt((year - 1) / range, 10) * range + 1;
}
this.yearpickerInit = function() {
columns = this.yearColumns;
range = this.yearRows * columns;
this.step = { years: range };
};
this._refreshView = function() {
var years = new Array(range), date;
for (var i = 0, start = getStartingYear(this.activeDate.getFullYear()); i < range; i++) {
date = new Date(this.activeDate);
date.setFullYear(start + i, 0, 1);
years[i] = angular.extend(this.createDateObject(date, this.formatYear), {
uid: scope.uniqueId + '-' + i
});
}
scope.title = [years[0].label, years[range - 1].label].join(' - ');
scope.rows = this.split(years, columns);
scope.columns = columns;
};
this.compare = function(date1, date2) {
return date1.getFullYear() - date2.getFullYear();
};
this.handleKeyDown = function(key, evt) {
var date = this.activeDate.getFullYear();
if (key === 'left') {
date = date - 1;
} else if (key === 'up') {
date = date - columns;
} else if (key === 'right') {
date = date + 1;
} else if (key === 'down') {
date = date + columns;
} else if (key === 'pageup' || key === 'pagedown') {
date += (key === 'pageup' ? - 1 : 1) * range;
} else if (key === 'home') {
date = getStartingYear(this.activeDate.getFullYear());
} else if (key === 'end') {
date = getStartingYear(this.activeDate.getFullYear()) + range - 1;
}
this.activeDate.setFullYear(date);
};
}])
.directive('uibDatepicker', function() {
return {
replace: true,
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/datepicker/datepicker.html';
},
scope: {
datepickerOptions: '=?'
},
require: ['uibDatepicker', '^ngModel'],
controller: 'UibDatepickerController',
controllerAs: 'datepicker',
link: function(scope, element, attrs, ctrls) {
var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];
datepickerCtrl.init(ngModelCtrl);
}
};
})
.directive('uibDaypicker', function() {
return {
replace: true,
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/datepicker/day.html';
},
require: ['^uibDatepicker', 'uibDaypicker'],
controller: 'UibDaypickerController',
link: function(scope, element, attrs, ctrls) {
var datepickerCtrl = ctrls[0],
daypickerCtrl = ctrls[1];
daypickerCtrl.init(datepickerCtrl);
}
};
})
.directive('uibMonthpicker', function() {
return {
replace: true,
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/datepicker/month.html';
},
require: ['^uibDatepicker', 'uibMonthpicker'],
controller: 'UibMonthpickerController',
link: function(scope, element, attrs, ctrls) {
var datepickerCtrl = ctrls[0],
monthpickerCtrl = ctrls[1];
monthpickerCtrl.init(datepickerCtrl);
}
};
})
.directive('uibYearpicker', function() {
return {
replace: true,
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/datepicker/year.html';
},
require: ['^uibDatepicker', 'uibYearpicker'],
controller: 'UibYearpickerController',
link: function(scope, element, attrs, ctrls) {
var ctrl = ctrls[0];
angular.extend(ctrl, ctrls[1]);
ctrl.yearpickerInit();
ctrl.refreshView();
}
};
});
angular.module('ui.bootstrap.position', [])
/**
* A set of utility methods for working with the DOM.
* It is meant to be used where we need to absolute-position elements in
* relation to another element (this is the case for tooltips, popovers,
* typeahead suggestions etc.).
*/
.factory('$uibPosition', ['$document', '$window', function($document, $window) {
/**
* Used by scrollbarWidth() function to cache scrollbar's width.
* Do not access this variable directly, use scrollbarWidth() instead.
*/
var SCROLLBAR_WIDTH;
/**
* scrollbar on body and html element in IE and Edge overlay
* content and should be considered 0 width.
*/
var BODY_SCROLLBAR_WIDTH;
var OVERFLOW_REGEX = {
normal: /(auto|scroll)/,
hidden: /(auto|scroll|hidden)/
};
var PLACEMENT_REGEX = {
auto: /\s?auto?\s?/i,
primary: /^(top|bottom|left|right)$/,
secondary: /^(top|bottom|left|right|center)$/,
vertical: /^(top|bottom)$/
};
var BODY_REGEX = /(HTML|BODY)/;
return {
/**
* Provides a raw DOM element from a jQuery/jQLite element.
*
* @param {element} elem - The element to convert.
*
* @returns {element} A HTML element.
*/
getRawNode: function(elem) {
return elem.nodeName ? elem : elem[0] || elem;
},
/**
* Provides a parsed number for a style property. Strips
* units and casts invalid numbers to 0.
*
* @param {string} value - The style value to parse.
*
* @returns {number} A valid number.
*/
parseStyle: function(value) {
value = parseFloat(value);
return isFinite(value) ? value : 0;
},
/**
* Provides the closest positioned ancestor.
*
* @param {element} element - The element to get the offest parent for.
*
* @returns {element} The closest positioned ancestor.
*/
offsetParent: function(elem) {
elem = this.getRawNode(elem);
var offsetParent = elem.offsetParent || $document[0].documentElement;
function isStaticPositioned(el) {
return ($window.getComputedStyle(el).position || 'static') === 'static';
}
while (offsetParent && offsetParent !== $document[0].documentElement && isStaticPositioned(offsetParent)) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || $document[0].documentElement;
},
/**
* Provides the scrollbar width, concept from TWBS measureScrollbar()
* function in https://github.com/twbs/bootstrap/blob/master/js/modal.js
* In IE and Edge, scollbar on body and html element overlay and should
* return a width of 0.
*
* @returns {number} The width of the browser scollbar.
*/
scrollbarWidth: function(isBody) {
if (isBody) {
if (angular.isUndefined(BODY_SCROLLBAR_WIDTH)) {
var bodyElem = $document.find('body');
bodyElem.addClass('uib-position-body-scrollbar-measure');
BODY_SCROLLBAR_WIDTH = $window.innerWidth - bodyElem[0].clientWidth;
BODY_SCROLLBAR_WIDTH = isFinite(BODY_SCROLLBAR_WIDTH) ? BODY_SCROLLBAR_WIDTH : 0;
bodyElem.removeClass('uib-position-body-scrollbar-measure');
}
return BODY_SCROLLBAR_WIDTH;
}
if (angular.isUndefined(SCROLLBAR_WIDTH)) {
var scrollElem = angular.element('<div class="uib-position-scrollbar-measure"></div>');
$document.find('body').append(scrollElem);
SCROLLBAR_WIDTH = scrollElem[0].offsetWidth - scrollElem[0].clientWidth;
SCROLLBAR_WIDTH = isFinite(SCROLLBAR_WIDTH) ? SCROLLBAR_WIDTH : 0;
scrollElem.remove();
}
return SCROLLBAR_WIDTH;
},
/**
* Provides the padding required on an element to replace the scrollbar.
*
* @returns {object} An object with the following properties:
* <ul>
* <li>**scrollbarWidth**: the width of the scrollbar</li>
* <li>**widthOverflow**: whether the the width is overflowing</li>
* <li>**right**: the amount of right padding on the element needed to replace the scrollbar</li>
* <li>**rightOriginal**: the amount of right padding currently on the element</li>
* <li>**heightOverflow**: whether the the height is overflowing</li>
* <li>**bottom**: the amount of bottom padding on the element needed to replace the scrollbar</li>
* <li>**bottomOriginal**: the amount of bottom padding currently on the element</li>
* </ul>
*/
scrollbarPadding: function(elem) {
elem = this.getRawNode(elem);
var elemStyle = $window.getComputedStyle(elem);
var paddingRight = this.parseStyle(elemStyle.paddingRight);
var paddingBottom = this.parseStyle(elemStyle.paddingBottom);
var scrollParent = this.scrollParent(elem, false, true);
var scrollbarWidth = this.scrollbarWidth(scrollParent, BODY_REGEX.test(scrollParent.tagName));
return {
scrollbarWidth: scrollbarWidth,
widthOverflow: scrollParent.scrollWidth > scrollParent.clientWidth,
right: paddingRight + scrollbarWidth,
originalRight: paddingRight,
heightOverflow: scrollParent.scrollHeight > scrollParent.clientHeight,
bottom: paddingBottom + scrollbarWidth,
originalBottom: paddingBottom
};
},
/**
* Checks to see if the element is scrollable.
*
* @param {element} elem - The element to check.
* @param {boolean=} [includeHidden=false] - Should scroll style of 'hidden' be considered,
* default is false.
*
* @returns {boolean} Whether the element is scrollable.
*/
isScrollable: function(elem, includeHidden) {
elem = this.getRawNode(elem);
var overflowRegex = includeHidden ? OVERFLOW_REGEX.hidden : OVERFLOW_REGEX.normal;
var elemStyle = $window.getComputedStyle(elem);
return overflowRegex.test(elemStyle.overflow + elemStyle.overflowY + elemStyle.overflowX);
},
/**
* Provides the closest scrollable ancestor.
* A port of the jQuery UI scrollParent method:
* https://github.com/jquery/jquery-ui/blob/master/ui/scroll-parent.js
*
* @param {element} elem - The element to find the scroll parent of.
* @param {boolean=} [includeHidden=false] - Should scroll style of 'hidden' be considered,
* default is false.
* @param {boolean=} [includeSelf=false] - Should the element being passed be
* included in the scrollable llokup.
*
* @returns {element} A HTML element.
*/
scrollParent: function(elem, includeHidden, includeSelf) {
elem = this.getRawNode(elem);
var overflowRegex = includeHidden ? OVERFLOW_REGEX.hidden : OVERFLOW_REGEX.normal;
var documentEl = $document[0].documentElement;
var elemStyle = $window.getComputedStyle(elem);
if (includeSelf && overflowRegex.test(elemStyle.overflow + elemStyle.overflowY + elemStyle.overflowX)) {
return elem;
}
var excludeStatic = elemStyle.position === 'absolute';
var scrollParent = elem.parentElement || documentEl;
if (scrollParent === documentEl || elemStyle.position === 'fixed') {
return documentEl;
}
while (scrollParent.parentElement && scrollParent !== documentEl) {
var spStyle = $window.getComputedStyle(scrollParent);
if (excludeStatic && spStyle.position !== 'static') {
excludeStatic = false;
}
if (!excludeStatic && overflowRegex.test(spStyle.overflow + spStyle.overflowY + spStyle.overflowX)) {
break;
}
scrollParent = scrollParent.parentElement;
}
return scrollParent;
},
/**
* Provides read-only equivalent of jQuery's position function:
* http://api.jquery.com/position/ - distance to closest positioned
* ancestor. Does not account for margins by default like jQuery position.
*
* @param {element} elem - The element to caclulate the position on.
* @param {boolean=} [includeMargins=false] - Should margins be accounted
* for, default is false.
*
* @returns {object} An object with the following properties:
* <ul>
* <li>**width**: the width of the element</li>
* <li>**height**: the height of the element</li>
* <li>**top**: distance to top edge of offset parent</li>
* <li>**left**: distance to left edge of offset parent</li>
* </ul>
*/
position: function(elem, includeMagins) {
elem = this.getRawNode(elem);
var elemOffset = this.offset(elem);
if (includeMagins) {
var elemStyle = $window.getComputedStyle(elem);
elemOffset.top -= this.parseStyle(elemStyle.marginTop);
elemOffset.left -= this.parseStyle(elemStyle.marginLeft);
}
var parent = this.offsetParent(elem);
var parentOffset = {top: 0, left: 0};
if (parent !== $document[0].documentElement) {
parentOffset = this.offset(parent);
parentOffset.top += parent.clientTop - parent.scrollTop;
parentOffset.left += parent.clientLeft - parent.scrollLeft;
}
return {
width: Math.round(angular.isNumber(elemOffset.width) ? elemOffset.width : elem.offsetWidth),
height: Math.round(angular.isNumber(elemOffset.height) ? elemOffset.height : elem.offsetHeight),
top: Math.round(elemOffset.top - parentOffset.top),
left: Math.round(elemOffset.left - parentOffset.left)
};
},
/**
* Provides read-only equivalent of jQuery's offset function:
* http://api.jquery.com/offset/ - distance to viewport. Does
* not account for borders, margins, or padding on the body
* element.
*
* @param {element} elem - The element to calculate the offset on.
*
* @returns {object} An object with the following properties:
* <ul>
* <li>**width**: the width of the element</li>
* <li>**height**: the height of the element</li>
* <li>**top**: distance to top edge of viewport</li>
* <li>**right**: distance to bottom edge of viewport</li>
* </ul>
*/
offset: function(elem) {
elem = this.getRawNode(elem);
var elemBCR = elem.getBoundingClientRect();
return {
width: Math.round(angular.isNumber(elemBCR.width) ? elemBCR.width : elem.offsetWidth),
height: Math.round(angular.isNumber(elemBCR.height) ? elemBCR.height : elem.offsetHeight),
top: Math.round(elemBCR.top + ($window.pageYOffset || $document[0].documentElement.scrollTop)),
left: Math.round(elemBCR.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft))
};
},
/**
* Provides offset distance to the closest scrollable ancestor
* or viewport. Accounts for border and scrollbar width.
*
* Right and bottom dimensions represent the distance to the
* respective edge of the viewport element. If the element
* edge extends beyond the viewport, a negative value will be
* reported.
*
* @param {element} elem - The element to get the viewport offset for.
* @param {boolean=} [useDocument=false] - Should the viewport be the document element instead
* of the first scrollable element, default is false.
* @param {boolean=} [includePadding=true] - Should the padding on the offset parent element
* be accounted for, default is true.
*
* @returns {object} An object with the following properties:
* <ul>
* <li>**top**: distance to the top content edge of viewport element</li>
* <li>**bottom**: distance to the bottom content edge of viewport element</li>
* <li>**left**: distance to the left content edge of viewport element</li>
* <li>**right**: distance to the right content edge of viewport element</li>
* </ul>
*/
viewportOffset: function(elem, useDocument, includePadding) {
elem = this.getRawNode(elem);
includePadding = includePadding !== false ? true : false;
var elemBCR = elem.getBoundingClientRect();
var offsetBCR = {top: 0, left: 0, bottom: 0, right: 0};
var offsetParent = useDocument ? $document[0].documentElement : this.scrollParent(elem);
var offsetParentBCR = offsetParent.getBoundingClientRect();
offsetBCR.top = offsetParentBCR.top + offsetParent.clientTop;
offsetBCR.left = offsetParentBCR.left + offsetParent.clientLeft;
if (offsetParent === $document[0].documentElement) {
offsetBCR.top += $window.pageYOffset;
offsetBCR.left += $window.pageXOffset;
}
offsetBCR.bottom = offsetBCR.top + offsetParent.clientHeight;
offsetBCR.right = offsetBCR.left + offsetParent.clientWidth;
if (includePadding) {
var offsetParentStyle = $window.getComputedStyle(offsetParent);
offsetBCR.top += this.parseStyle(offsetParentStyle.paddingTop);
offsetBCR.bottom -= this.parseStyle(offsetParentStyle.paddingBottom);
offsetBCR.left += this.parseStyle(offsetParentStyle.paddingLeft);
offsetBCR.right -= this.parseStyle(offsetParentStyle.paddingRight);
}
return {
top: Math.round(elemBCR.top - offsetBCR.top),
bottom: Math.round(offsetBCR.bottom - elemBCR.bottom),
left: Math.round(elemBCR.left - offsetBCR.left),
right: Math.round(offsetBCR.right - elemBCR.right)
};
},
/**
* Provides an array of placement values parsed from a placement string.
* Along with the 'auto' indicator, supported placement strings are:
* <ul>
* <li>top: element on top, horizontally centered on host element.</li>
* <li>top-left: element on top, left edge aligned with host element left edge.</li>
* <li>top-right: element on top, lerightft edge aligned with host element right edge.</li>
* <li>bottom: element on bottom, horizontally centered on host element.</li>
* <li>bottom-left: element on bottom, left edge aligned with host element left edge.</li>
* <li>bottom-right: element on bottom, right edge aligned with host element right edge.</li>
* <li>left: element on left, vertically centered on host element.</li>
* <li>left-top: element on left, top edge aligned with host element top edge.</li>
* <li>left-bottom: element on left, bottom edge aligned with host element bottom edge.</li>
* <li>right: element on right, vertically centered on host element.</li>
* <li>right-top: element on right, top edge aligned with host element top edge.</li>
* <li>right-bottom: element on right, bottom edge aligned with host element bottom edge.</li>
* </ul>
* A placement string with an 'auto' indicator is expected to be
* space separated from the placement, i.e: 'auto bottom-left' If
* the primary and secondary placement values do not match 'top,
* bottom, left, right' then 'top' will be the primary placement and
* 'center' will be the secondary placement. If 'auto' is passed, true
* will be returned as the 3rd value of the array.
*
* @param {string} placement - The placement string to parse.
*
* @returns {array} An array with the following values
* <ul>
* <li>**[0]**: The primary placement.</li>
* <li>**[1]**: The secondary placement.</li>
* <li>**[2]**: If auto is passed: true, else undefined.</li>
* </ul>
*/
parsePlacement: function(placement) {
var autoPlace = PLACEMENT_REGEX.auto.test(placement);
if (autoPlace) {
placement = placement.replace(PLACEMENT_REGEX.auto, '');
}
placement = placement.split('-');
placement[0] = placement[0] || 'top';
if (!PLACEMENT_REGEX.primary.test(placement[0])) {
placement[0] = 'top';
}
placement[1] = placement[1] || 'center';
if (!PLACEMENT_REGEX.secondary.test(placement[1])) {
placement[1] = 'center';
}
if (autoPlace) {
placement[2] = true;
} else {
placement[2] = false;
}
return placement;
},
/**
* Provides coordinates for an element to be positioned relative to
* another element. Passing 'auto' as part of the placement parameter
* will enable smart placement - where the element fits. i.e:
* 'auto left-top' will check to see if there is enough space to the left
* of the hostElem to fit the targetElem, if not place right (same for secondary
* top placement). Available space is calculated using the viewportOffset
* function.
*
* @param {element} hostElem - The element to position against.
* @param {element} targetElem - The element to position.
* @param {string=} [placement=top] - The placement for the targetElem,
* default is 'top'. 'center' is assumed as secondary placement for
* 'top', 'left', 'right', and 'bottom' placements. Available placements are:
* <ul>
* <li>top</li>
* <li>top-right</li>
* <li>top-left</li>
* <li>bottom</li>
* <li>bottom-left</li>
* <li>bottom-right</li>
* <li>left</li>
* <li>left-top</li>
* <li>left-bottom</li>
* <li>right</li>
* <li>right-top</li>
* <li>right-bottom</li>
* </ul>
* @param {boolean=} [appendToBody=false] - Should the top and left values returned
* be calculated from the body element, default is false.
*
* @returns {object} An object with the following properties:
* <ul>
* <li>**top**: Value for targetElem top.</li>
* <li>**left**: Value for targetElem left.</li>
* <li>**placement**: The resolved placement.</li>
* </ul>
*/
positionElements: function(hostElem, targetElem, placement, appendToBody) {
hostElem = this.getRawNode(hostElem);
targetElem = this.getRawNode(targetElem);
// need to read from prop to support tests.
var targetWidth = angular.isDefined(targetElem.offsetWidth) ? targetElem.offsetWidth : targetElem.prop('offsetWidth');
var targetHeight = angular.isDefined(targetElem.offsetHeight) ? targetElem.offsetHeight : targetElem.prop('offsetHeight');
placement = this.parsePlacement(placement);
var hostElemPos = appendToBody ? this.offset(hostElem) : this.position(hostElem);
var targetElemPos = {top: 0, left: 0, placement: ''};
if (placement[2]) {
var viewportOffset = this.viewportOffset(hostElem, appendToBody);
var targetElemStyle = $window.getComputedStyle(targetElem);
var adjustedSize = {
width: targetWidth + Math.round(Math.abs(this.parseStyle(targetElemStyle.marginLeft) + this.parseStyle(targetElemStyle.marginRight))),
height: targetHeight + Math.round(Math.abs(this.parseStyle(targetElemStyle.marginTop) + this.parseStyle(targetElemStyle.marginBottom)))
};
placement[0] = placement[0] === 'top' && adjustedSize.height > viewportOffset.top && adjustedSize.height <= viewportOffset.bottom ? 'bottom' :
placement[0] === 'bottom' && adjustedSize.height > viewportOffset.bottom && adjustedSize.height <= viewportOffset.top ? 'top' :
placement[0] === 'left' && adjustedSize.width > viewportOffset.left && adjustedSize.width <= viewportOffset.right ? 'right' :
placement[0] === 'right' && adjustedSize.width > viewportOffset.right && adjustedSize.width <= viewportOffset.left ? 'left' :
placement[0];
placement[1] = placement[1] === 'top' && adjustedSize.height - hostElemPos.height > viewportOffset.bottom && adjustedSize.height - hostElemPos.height <= viewportOffset.top ? 'bottom' :
placement[1] === 'bottom' && adjustedSize.height - hostElemPos.height > viewportOffset.top && adjustedSize.height - hostElemPos.height <= viewportOffset.bottom ? 'top' :
placement[1] === 'left' && adjustedSize.width - hostElemPos.width > viewportOffset.right && adjustedSize.width - hostElemPos.width <= viewportOffset.left ? 'right' :
placement[1] === 'right' && adjustedSize.width - hostElemPos.width > viewportOffset.left && adjustedSize.width - hostElemPos.width <= viewportOffset.right ? 'left' :
placement[1];
if (placement[1] === 'center') {
if (PLACEMENT_REGEX.vertical.test(placement[0])) {
var xOverflow = hostElemPos.width / 2 - targetWidth / 2;
if (viewportOffset.left + xOverflow < 0 && adjustedSize.width - hostElemPos.width <= viewportOffset.right) {
placement[1] = 'left';
} else if (viewportOffset.right + xOverflow < 0 && adjustedSize.width - hostElemPos.width <= viewportOffset.left) {
placement[1] = 'right';
}
} else {
var yOverflow = hostElemPos.height / 2 - adjustedSize.height / 2;
if (viewportOffset.top + yOverflow < 0 && adjustedSize.height - hostElemPos.height <= viewportOffset.bottom) {
placement[1] = 'top';
} else if (viewportOffset.bottom + yOverflow < 0 && adjustedSize.height - hostElemPos.height <= viewportOffset.top) {
placement[1] = 'bottom';
}
}
}
}
switch (placement[0]) {
case 'top':
targetElemPos.top = hostElemPos.top - targetHeight;
break;
case 'bottom':
targetElemPos.top = hostElemPos.top + hostElemPos.height;
break;
case 'left':
targetElemPos.left = hostElemPos.left - targetWidth;
break;
case 'right':
targetElemPos.left = hostElemPos.left + hostElemPos.width;
break;
}
switch (placement[1]) {
case 'top':
targetElemPos.top = hostElemPos.top;
break;
case 'bottom':
targetElemPos.top = hostElemPos.top + hostElemPos.height - targetHeight;
break;
case 'left':
targetElemPos.left = hostElemPos.left;
break;
case 'right':
targetElemPos.left = hostElemPos.left + hostElemPos.width - targetWidth;
break;
case 'center':
if (PLACEMENT_REGEX.vertical.test(placement[0])) {
targetElemPos.left = hostElemPos.left + hostElemPos.width / 2 - targetWidth / 2;
} else {
targetElemPos.top = hostElemPos.top + hostElemPos.height / 2 - targetHeight / 2;
}
break;
}
targetElemPos.top = Math.round(targetElemPos.top);
targetElemPos.left = Math.round(targetElemPos.left);
targetElemPos.placement = placement[1] === 'center' ? placement[0] : placement[0] + '-' + placement[1];
return targetElemPos;
},
/**
* Provides a way for positioning tooltip & dropdown
* arrows when using placement options beyond the standard
* left, right, top, or bottom.
*
* @param {element} elem - The tooltip/dropdown element.
* @param {string} placement - The placement for the elem.
*/
positionArrow: function(elem, placement) {
elem = this.getRawNode(elem);
var innerElem = elem.querySelector('.tooltip-inner, .popover-inner');
if (!innerElem) {
return;
}
var isTooltip = angular.element(innerElem).hasClass('tooltip-inner');
var arrowElem = isTooltip ? elem.querySelector('.tooltip-arrow') : elem.querySelector('.arrow');
if (!arrowElem) {
return;
}
var arrowCss = {
top: '',
bottom: '',
left: '',
right: ''
};
placement = this.parsePlacement(placement);
if (placement[1] === 'center') {
// no adjustment necessary - just reset styles
angular.element(arrowElem).css(arrowCss);
return;
}
var borderProp = 'border-' + placement[0] + '-width';
var borderWidth = $window.getComputedStyle(arrowElem)[borderProp];
var borderRadiusProp = 'border-';
if (PLACEMENT_REGEX.vertical.test(placement[0])) {
borderRadiusProp += placement[0] + '-' + placement[1];
} else {
borderRadiusProp += placement[1] + '-' + placement[0];
}
borderRadiusProp += '-radius';
var borderRadius = $window.getComputedStyle(isTooltip ? innerElem : elem)[borderRadiusProp];
switch (placement[0]) {
case 'top':
arrowCss.bottom = isTooltip ? '0' : '-' + borderWidth;
break;
case 'bottom':
arrowCss.top = isTooltip ? '0' : '-' + borderWidth;
break;
case 'left':
arrowCss.right = isTooltip ? '0' : '-' + borderWidth;
break;
case 'right':
arrowCss.left = isTooltip ? '0' : '-' + borderWidth;
break;
}
arrowCss[placement[1]] = borderRadius;
angular.element(arrowElem).css(arrowCss);
}
};
}]);
angular.module('ui.bootstrap.datepickerPopup', ['ui.bootstrap.datepicker', 'ui.bootstrap.position'])
.value('$datepickerPopupLiteralWarning', true)
.constant('uibDatepickerPopupConfig', {
altInputFormats: [],
appendToBody: false,
clearText: 'Clear',
closeOnDateSelection: true,
closeText: 'Done',
currentText: 'Today',
datepickerPopup: 'yyyy-MM-dd',
datepickerPopupTemplateUrl: 'uib/template/datepickerPopup/popup.html',
datepickerTemplateUrl: 'uib/template/datepicker/datepicker.html',
html5Types: {
date: 'yyyy-MM-dd',
'datetime-local': 'yyyy-MM-ddTHH:mm:ss.sss',
'month': 'yyyy-MM'
},
onOpenFocus: true,
showButtonBar: true,
placement: 'auto bottom-left'
})
.controller('UibDatepickerPopupController', ['$scope', '$element', '$attrs', '$compile', '$log', '$parse', '$window', '$document', '$rootScope', '$uibPosition', 'dateFilter', 'uibDateParser', 'uibDatepickerPopupConfig', '$timeout', 'uibDatepickerConfig', '$datepickerPopupLiteralWarning',
function($scope, $element, $attrs, $compile, $log, $parse, $window, $document, $rootScope, $position, dateFilter, dateParser, datepickerPopupConfig, $timeout, datepickerConfig, $datepickerPopupLiteralWarning) {
var cache = {},
isHtml5DateInput = false;
var dateFormat, closeOnDateSelection, appendToBody, onOpenFocus,
datepickerPopupTemplateUrl, datepickerTemplateUrl, popupEl, datepickerEl, scrollParentEl,
ngModel, ngModelOptions, $popup, altInputFormats, watchListeners = [],
timezone;
this.init = function(_ngModel_) {
ngModel = _ngModel_;
ngModelOptions = _ngModel_.$options;
closeOnDateSelection = angular.isDefined($attrs.closeOnDateSelection) ?
$scope.$parent.$eval($attrs.closeOnDateSelection) :
datepickerPopupConfig.closeOnDateSelection;
appendToBody = angular.isDefined($attrs.datepickerAppendToBody) ?
$scope.$parent.$eval($attrs.datepickerAppendToBody) :
datepickerPopupConfig.appendToBody;
onOpenFocus = angular.isDefined($attrs.onOpenFocus) ?
$scope.$parent.$eval($attrs.onOpenFocus) : datepickerPopupConfig.onOpenFocus;
datepickerPopupTemplateUrl = angular.isDefined($attrs.datepickerPopupTemplateUrl) ?
$attrs.datepickerPopupTemplateUrl :
datepickerPopupConfig.datepickerPopupTemplateUrl;
datepickerTemplateUrl = angular.isDefined($attrs.datepickerTemplateUrl) ?
$attrs.datepickerTemplateUrl : datepickerPopupConfig.datepickerTemplateUrl;
altInputFormats = angular.isDefined($attrs.altInputFormats) ?
$scope.$parent.$eval($attrs.altInputFormats) :
datepickerPopupConfig.altInputFormats;
$scope.showButtonBar = angular.isDefined($attrs.showButtonBar) ?
$scope.$parent.$eval($attrs.showButtonBar) :
datepickerPopupConfig.showButtonBar;
if (datepickerPopupConfig.html5Types[$attrs.type]) {
dateFormat = datepickerPopupConfig.html5Types[$attrs.type];
isHtml5DateInput = true;
} else {
dateFormat = $attrs.uibDatepickerPopup || datepickerPopupConfig.datepickerPopup;
$attrs.$observe('uibDatepickerPopup', function(value, oldValue) {
var newDateFormat = value || datepickerPopupConfig.datepickerPopup;
// Invalidate the $modelValue to ensure that formatters re-run
// FIXME: Refactor when PR is merged: https://github.com/angular/angular.js/pull/10764
if (newDateFormat !== dateFormat) {
dateFormat = newDateFormat;
ngModel.$modelValue = null;
if (!dateFormat) {
throw new Error('uibDatepickerPopup must have a date format specified.');
}
}
});
}
if (!dateFormat) {
throw new Error('uibDatepickerPopup must have a date format specified.');
}
if (isHtml5DateInput && $attrs.uibDatepickerPopup) {
throw new Error('HTML5 date input types do not support custom formats.');
}
// popup element used to display calendar
popupEl = angular.element('<div uib-datepicker-popup-wrap><div uib-datepicker></div></div>');
if (ngModelOptions) {
timezone = ngModelOptions.timezone;
$scope.ngModelOptions = angular.copy(ngModelOptions);
$scope.ngModelOptions.timezone = null;
if ($scope.ngModelOptions.updateOnDefault === true) {
$scope.ngModelOptions.updateOn = $scope.ngModelOptions.updateOn ?
$scope.ngModelOptions.updateOn + ' default' : 'default';
}
popupEl.attr('ng-model-options', 'ngModelOptions');
} else {
timezone = null;
}
popupEl.attr({
'ng-model': 'date',
'ng-change': 'dateSelection(date)',
'template-url': datepickerPopupTemplateUrl
});
// datepicker element
datepickerEl = angular.element(popupEl.children()[0]);
datepickerEl.attr('template-url', datepickerTemplateUrl);
if (!$scope.datepickerOptions) {
$scope.datepickerOptions = {};
}
if (isHtml5DateInput) {
if ($attrs.type === 'month') {
$scope.datepickerOptions.datepickerMode = 'month';
$scope.datepickerOptions.minMode = 'month';
}
}
datepickerEl.attr('datepicker-options', 'datepickerOptions');
if (!isHtml5DateInput) {
// Internal API to maintain the correct ng-invalid-[key] class
ngModel.$$parserName = 'date';
ngModel.$validators.date = validator;
ngModel.$parsers.unshift(parseDate);
ngModel.$formatters.push(function(value) {
if (ngModel.$isEmpty(value)) {
$scope.date = value;
return value;
}
$scope.date = dateParser.fromTimezone(value, timezone);
if (angular.isNumber($scope.date)) {
$scope.date = new Date($scope.date);
}
return dateParser.filter($scope.date, dateFormat);
});
} else {
ngModel.$formatters.push(function(value) {
$scope.date = dateParser.fromTimezone(value, timezone);
return value;
});
}
// Detect changes in the view from the text box
ngModel.$viewChangeListeners.push(function() {
$scope.date = parseDateString(ngModel.$viewValue);
});
$element.on('keydown', inputKeydownBind);
$popup = $compile(popupEl)($scope);
// Prevent jQuery cache memory leak (template is now redundant after linking)
popupEl.remove();
if (appendToBody) {
$document.find('body').append($popup);
} else {
$element.after($popup);
}
$scope.$on('$destroy', function() {
if ($scope.isOpen === true) {
if (!$rootScope.$$phase) {
$scope.$apply(function() {
$scope.isOpen = false;
});
}
}
$popup.remove();
$element.off('keydown', inputKeydownBind);
$document.off('click', documentClickBind);
if (scrollParentEl) {
scrollParentEl.off('scroll', positionPopup);
}
angular.element($window).off('resize', positionPopup);
//Clear all watch listeners on destroy
while (watchListeners.length) {
watchListeners.shift()();
}
});
};
$scope.getText = function(key) {
return $scope[key + 'Text'] || datepickerPopupConfig[key + 'Text'];
};
$scope.isDisabled = function(date) {
if (date === 'today') {
date = dateParser.fromTimezone(new Date(), timezone);
}
var dates = {};
angular.forEach(['minDate', 'maxDate'], function(key) {
if (!$scope.datepickerOptions[key]) {
dates[key] = null;
} else if (angular.isDate($scope.datepickerOptions[key])) {
dates[key] = dateParser.fromTimezone(new Date($scope.datepickerOptions[key]), timezone);
} else {
if ($datepickerPopupLiteralWarning) {
$log.warn('Literal date support has been deprecated, please switch to date object usage');
}
dates[key] = new Date(dateFilter($scope.datepickerOptions[key], 'medium'));
}
});
return $scope.datepickerOptions &&
dates.minDate && $scope.compare(date, dates.minDate) < 0 ||
dates.maxDate && $scope.compare(date, dates.maxDate) > 0;
};
$scope.compare = function(date1, date2) {
return new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
};
// Inner change
$scope.dateSelection = function(dt) {
if (angular.isDefined(dt)) {
$scope.date = dt;
}
var date = $scope.date ? dateParser.filter($scope.date, dateFormat) : null; // Setting to NULL is necessary for form validators to function
$element.val(date);
ngModel.$setViewValue(date);
if (closeOnDateSelection) {
$scope.isOpen = false;
$element[0].focus();
}
};
$scope.keydown = function(evt) {
if (evt.which === 27) {
evt.stopPropagation();
$scope.isOpen = false;
$element[0].focus();
}
};
$scope.select = function(date, evt) {
evt.stopPropagation();
if (date === 'today') {
var today = new Date();
if (angular.isDate($scope.date)) {
date = new Date($scope.date);
date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate());
} else {
date = new Date(today.setHours(0, 0, 0, 0));
}
}
$scope.dateSelection(date);
};
$scope.close = function(evt) {
evt.stopPropagation();
$scope.isOpen = false;
$element[0].focus();
};
$scope.disabled = angular.isDefined($attrs.disabled) || false;
if ($attrs.ngDisabled) {
watchListeners.push($scope.$parent.$watch($parse($attrs.ngDisabled), function(disabled) {
$scope.disabled = disabled;
}));
}
$scope.$watch('isOpen', function(value) {
if (value) {
if (!$scope.disabled) {
$timeout(function() {
positionPopup();
if (onOpenFocus) {
$scope.$broadcast('uib:datepicker.focus');
}
$document.on('click', documentClickBind);
var placement = $attrs.popupPlacement ? $attrs.popupPlacement : datepickerPopupConfig.placement;
if (appendToBody || $position.parsePlacement(placement)[2]) {
scrollParentEl = scrollParentEl || angular.element($position.scrollParent($element));
if (scrollParentEl) {
scrollParentEl.on('scroll', positionPopup);
}
} else {
scrollParentEl = null;
}
angular.element($window).on('resize', positionPopup);
}, 0, false);
} else {
$scope.isOpen = false;
}
} else {
$document.off('click', documentClickBind);
if (scrollParentEl) {
scrollParentEl.off('scroll', positionPopup);
}
angular.element($window).off('resize', positionPopup);
}
});
function cameltoDash(string) {
return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); });
}
function parseDateString(viewValue) {
var date = dateParser.parse(viewValue, dateFormat, $scope.date);
if (isNaN(date)) {
for (var i = 0; i < altInputFormats.length; i++) {
date = dateParser.parse(viewValue, altInputFormats[i], $scope.date);
if (!isNaN(date)) {
return date;
}
}
}
return date;
}
function parseDate(viewValue) {
if (angular.isNumber(viewValue)) {
// presumably timestamp to date object
viewValue = new Date(viewValue);
}
if (!viewValue) {
return null;
}
if (angular.isDate(viewValue) && !isNaN(viewValue)) {
return viewValue;
}
if (angular.isString(viewValue)) {
var date = parseDateString(viewValue);
if (!isNaN(date)) {
return dateParser.toTimezone(date, timezone);
}
}
return ngModel.$options && ngModel.$options.allowInvalid ? viewValue : undefined;
}
function validator(modelValue, viewValue) {
var value = modelValue || viewValue;
if (!$attrs.ngRequired && !value) {
return true;
}
if (angular.isNumber(value)) {
value = new Date(value);
}
if (!value) {
return true;
}
if (angular.isDate(value) && !isNaN(value)) {
return true;
}
if (angular.isString(value)) {
return !isNaN(parseDateString(viewValue));
}
return false;
}
function documentClickBind(event) {
if (!$scope.isOpen && $scope.disabled) {
return;
}
var popup = $popup[0];
var dpContainsTarget = $element[0].contains(event.target);
// The popup node may not be an element node
// In some browsers (IE) only element nodes have the 'contains' function
var popupContainsTarget = popup.contains !== undefined && popup.contains(event.target);
if ($scope.isOpen && !(dpContainsTarget || popupContainsTarget)) {
$scope.$apply(function() {
$scope.isOpen = false;
});
}
}
function inputKeydownBind(evt) {
if (evt.which === 27 && $scope.isOpen) {
evt.preventDefault();
evt.stopPropagation();
$scope.$apply(function() {
$scope.isOpen = false;
});
$element[0].focus();
} else if (evt.which === 40 && !$scope.isOpen) {
evt.preventDefault();
evt.stopPropagation();
$scope.$apply(function() {
$scope.isOpen = true;
});
}
}
function positionPopup() {
if ($scope.isOpen) {
var dpElement = angular.element($popup[0].querySelector('.uib-datepicker-popup'));
var placement = $attrs.popupPlacement ? $attrs.popupPlacement : datepickerPopupConfig.placement;
var position = $position.positionElements($element, dpElement, placement, appendToBody);
dpElement.css({top: position.top + 'px', left: position.left + 'px'});
if (dpElement.hasClass('uib-position-measure')) {
dpElement.removeClass('uib-position-measure');
}
}
}
$scope.$on('uib:datepicker.mode', function() {
$timeout(positionPopup, 0, false);
});
}])
.directive('uibDatepickerPopup', function() {
return {
require: ['ngModel', 'uibDatepickerPopup'],
controller: 'UibDatepickerPopupController',
scope: {
datepickerOptions: '=?',
isOpen: '=?',
currentText: '@',
clearText: '@',
closeText: '@'
},
link: function(scope, element, attrs, ctrls) {
var ngModel = ctrls[0],
ctrl = ctrls[1];
ctrl.init(ngModel);
}
};
})
.directive('uibDatepickerPopupWrap', function() {
return {
replace: true,
transclude: true,
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/datepickerPopup/popup.html';
}
};
});
angular.module('ui.bootstrap.debounce', [])
/**
* A helper, internal service that debounces a function
*/
.factory('$$debounce', ['$timeout', function($timeout) {
return function(callback, debounceTime) {
var timeoutPromise;
return function() {
var self = this;
var args = Array.prototype.slice.call(arguments);
if (timeoutPromise) {
$timeout.cancel(timeoutPromise);
}
timeoutPromise = $timeout(function() {
callback.apply(self, args);
}, debounceTime);
};
};
}]);
angular.module('ui.bootstrap.dropdown', ['ui.bootstrap.position'])
.constant('uibDropdownConfig', {
appendToOpenClass: 'uib-dropdown-open',
openClass: 'open'
})
.service('uibDropdownService', ['$document', '$rootScope', function($document, $rootScope) {
var openScope = null;
this.open = function(dropdownScope, element) {
if (!openScope) {
$document.on('click', closeDropdown);
element.on('keydown', keybindFilter);
}
if (openScope && openScope !== dropdownScope) {
openScope.isOpen = false;
}
openScope = dropdownScope;
};
this.close = function(dropdownScope, element) {
if (openScope === dropdownScope) {
openScope = null;
$document.off('click', closeDropdown);
element.off('keydown', keybindFilter);
}
};
var closeDropdown = function(evt) {
// This method may still be called during the same mouse event that
// unbound this event handler. So check openScope before proceeding.
if (!openScope) { return; }
if (evt && openScope.getAutoClose() === 'disabled') { return; }
if (evt && evt.which === 3) { return; }
var toggleElement = openScope.getToggleElement();
if (evt && toggleElement && toggleElement[0].contains(evt.target)) {
return;
}
var dropdownElement = openScope.getDropdownElement();
if (evt && openScope.getAutoClose() === 'outsideClick' &&
dropdownElement && dropdownElement[0].contains(evt.target)) {
return;
}
openScope.isOpen = false;
if (!$rootScope.$$phase) {
openScope.$apply();
}
};
var keybindFilter = function(evt) {
if (evt.which === 27) {
evt.stopPropagation();
openScope.focusToggleElement();
closeDropdown();
} else if (openScope.isKeynavEnabled() && [38, 40].indexOf(evt.which) !== -1 && openScope.isOpen) {
evt.preventDefault();
evt.stopPropagation();
openScope.focusDropdownEntry(evt.which);
}
};
}])
.controller('UibDropdownController', ['$scope', '$element', '$attrs', '$parse', 'uibDropdownConfig', 'uibDropdownService', '$animate', '$uibPosition', '$document', '$compile', '$templateRequest', function($scope, $element, $attrs, $parse, dropdownConfig, uibDropdownService, $animate, $position, $document, $compile, $templateRequest) {
var self = this,
scope = $scope.$new(), // create a child scope so we are not polluting original one
templateScope,
appendToOpenClass = dropdownConfig.appendToOpenClass,
openClass = dropdownConfig.openClass,
getIsOpen,
setIsOpen = angular.noop,
toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop,
appendToBody = false,
appendTo = null,
keynavEnabled = false,
selectedOption = null,
body = $document.find('body');
$element.addClass('dropdown');
this.init = function() {
if ($attrs.isOpen) {
getIsOpen = $parse($attrs.isOpen);
setIsOpen = getIsOpen.assign;
$scope.$watch(getIsOpen, function(value) {
scope.isOpen = !!value;
});
}
if (angular.isDefined($attrs.dropdownAppendTo)) {
var appendToEl = $parse($attrs.dropdownAppendTo)(scope);
if (appendToEl) {
appendTo = angular.element(appendToEl);
}
}
appendToBody = angular.isDefined($attrs.dropdownAppendToBody);
keynavEnabled = angular.isDefined($attrs.keyboardNav);
if (appendToBody && !appendTo) {
appendTo = body;
}
if (appendTo && self.dropdownMenu) {
appendTo.append(self.dropdownMenu);
$element.on('$destroy', function handleDestroyEvent() {
self.dropdownMenu.remove();
});
}
};
this.toggle = function(open) {
scope.isOpen = arguments.length ? !!open : !scope.isOpen;
if (angular.isFunction(setIsOpen)) {
setIsOpen(scope, scope.isOpen);
}
return scope.isOpen;
};
// Allow other directives to watch status
this.isOpen = function() {
return scope.isOpen;
};
scope.getToggleElement = function() {
return self.toggleElement;
};
scope.getAutoClose = function() {
return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled'
};
scope.getElement = function() {
return $element;
};
scope.isKeynavEnabled = function() {
return keynavEnabled;
};
scope.focusDropdownEntry = function(keyCode) {
var elems = self.dropdownMenu ? //If append to body is used.
angular.element(self.dropdownMenu).find('a') :
$element.find('ul').eq(0).find('a');
switch (keyCode) {
case 40: {
if (!angular.isNumber(self.selectedOption)) {
self.selectedOption = 0;
} else {
self.selectedOption = self.selectedOption === elems.length - 1 ?
self.selectedOption :
self.selectedOption + 1;
}
break;
}
case 38: {
if (!angular.isNumber(self.selectedOption)) {
self.selectedOption = elems.length - 1;
} else {
self.selectedOption = self.selectedOption === 0 ?
0 : self.selectedOption - 1;
}
break;
}
}
elems[self.selectedOption].focus();
};
scope.getDropdownElement = function() {
return self.dropdownMenu;
};
scope.focusToggleElement = function() {
if (self.toggleElement) {
self.toggleElement[0].focus();
}
};
scope.$watch('isOpen', function(isOpen, wasOpen) {
if (appendTo && self.dropdownMenu) {
var pos = $position.positionElements($element, self.dropdownMenu, 'bottom-left', true),
css,
rightalign;
css = {
top: pos.top + 'px',
display: isOpen ? 'block' : 'none'
};
rightalign = self.dropdownMenu.hasClass('dropdown-menu-right');
if (!rightalign) {
css.left = pos.left + 'px';
css.right = 'auto';
} else {
css.left = 'auto';
css.right = window.innerWidth -
(pos.left + $element.prop('offsetWidth')) + 'px';
}
// Need to adjust our positioning to be relative to the appendTo container
// if it's not the body element
if (!appendToBody) {
var appendOffset = $position.offset(appendTo);
css.top = pos.top - appendOffset.top + 'px';
if (!rightalign) {
css.left = pos.left - appendOffset.left + 'px';
} else {
css.right = window.innerWidth -
(pos.left - appendOffset.left + $element.prop('offsetWidth')) + 'px';
}
}
self.dropdownMenu.css(css);
}
var openContainer = appendTo ? appendTo : $element;
var hasOpenClass = openContainer.hasClass(appendTo ? appendToOpenClass : openClass);
if (hasOpenClass === !isOpen) {
$animate[isOpen ? 'addClass' : 'removeClass'](openContainer, appendTo ? appendToOpenClass : openClass).then(function() {
if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
toggleInvoker($scope, { open: !!isOpen });
}
});
}
if (isOpen) {
if (self.dropdownMenuTemplateUrl) {
$templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) {
templateScope = scope.$new();
$compile(tplContent.trim())(templateScope, function(dropdownElement) {
var newEl = dropdownElement;
self.dropdownMenu.replaceWith(newEl);
self.dropdownMenu = newEl;
});
});
}
scope.focusToggleElement();
uibDropdownService.open(scope, $element);
} else {
if (self.dropdownMenuTemplateUrl) {
if (templateScope) {
templateScope.$destroy();
}
var newEl = angular.element('<ul class="dropdown-menu"></ul>');
self.dropdownMenu.replaceWith(newEl);
self.dropdownMenu = newEl;
}
uibDropdownService.close(scope, $element);
self.selectedOption = null;
}
if (angular.isFunction(setIsOpen)) {
setIsOpen($scope, isOpen);
}
});
}])
.directive('uibDropdown', function() {
return {
controller: 'UibDropdownController',
link: function(scope, element, attrs, dropdownCtrl) {
dropdownCtrl.init();
}
};
})
.directive('uibDropdownMenu', function() {
return {
restrict: 'A',
require: '?^uibDropdown',
link: function(scope, element, attrs, dropdownCtrl) {
if (!dropdownCtrl || angular.isDefined(attrs.dropdownNested)) {
return;
}
element.addClass('dropdown-menu');
var tplUrl = attrs.templateUrl;
if (tplUrl) {
dropdownCtrl.dropdownMenuTemplateUrl = tplUrl;
}
if (!dropdownCtrl.dropdownMenu) {
dropdownCtrl.dropdownMenu = element;
}
}
};
})
.directive('uibDropdownToggle', function() {
return {
require: '?^uibDropdown',
link: function(scope, element, attrs, dropdownCtrl) {
if (!dropdownCtrl) {
return;
}
element.addClass('dropdown-toggle');
dropdownCtrl.toggleElement = element;
var toggleDropdown = function(event) {
event.preventDefault();
if (!element.hasClass('disabled') && !attrs.disabled) {
scope.$apply(function() {
dropdownCtrl.toggle();
});
}
};
element.bind('click', toggleDropdown);
// WAI-ARIA
element.attr({ 'aria-haspopup': true, 'aria-expanded': false });
scope.$watch(dropdownCtrl.isOpen, function(isOpen) {
element.attr('aria-expanded', !!isOpen);
});
scope.$on('$destroy', function() {
element.unbind('click', toggleDropdown);
});
}
};
});
angular.module('ui.bootstrap.stackedMap', [])
/**
* A helper, internal data structure that acts as a map but also allows getting / removing
* elements in the LIFO order
*/
.factory('$$stackedMap', function() {
return {
createNew: function() {
var stack = [];
return {
add: function(key, value) {
stack.push({
key: key,
value: value
});
},
get: function(key) {
for (var i = 0; i < stack.length; i++) {
if (key === stack[i].key) {
return stack[i];
}
}
},
keys: function() {
var keys = [];
for (var i = 0; i < stack.length; i++) {
keys.push(stack[i].key);
}
return keys;
},
top: function() {
return stack[stack.length - 1];
},
remove: function(key) {
var idx = -1;
for (var i = 0; i < stack.length; i++) {
if (key === stack[i].key) {
idx = i;
break;
}
}
return stack.splice(idx, 1)[0];
},
removeTop: function() {
return stack.splice(stack.length - 1, 1)[0];
},
length: function() {
return stack.length;
}
};
}
};
});
angular.module('ui.bootstrap.modal', ['ui.bootstrap.stackedMap', 'ui.bootstrap.position'])
/**
* A helper, internal data structure that stores all references attached to key
*/
.factory('$$multiMap', function() {
return {
createNew: function() {
var map = {};
return {
entries: function() {
return Object.keys(map).map(function(key) {
return {
key: key,
value: map[key]
};
});
},
get: function(key) {
return map[key];
},
hasKey: function(key) {
return !!map[key];
},
keys: function() {
return Object.keys(map);
},
put: function(key, value) {
if (!map[key]) {
map[key] = [];
}
map[key].push(value);
},
remove: function(key, value) {
var values = map[key];
if (!values) {
return;
}
var idx = values.indexOf(value);
if (idx !== -1) {
values.splice(idx, 1);
}
if (!values.length) {
delete map[key];
}
}
};
}
};
})
/**
* Pluggable resolve mechanism for the modal resolve resolution
* Supports UI Router's $resolve service
*/
.provider('$uibResolve', function() {
var resolve = this;
this.resolver = null;
this.setResolver = function(resolver) {
this.resolver = resolver;
};
this.$get = ['$injector', '$q', function($injector, $q) {
var resolver = resolve.resolver ? $injector.get(resolve.resolver) : null;
return {
resolve: function(invocables, locals, parent, self) {
if (resolver) {
return resolver.resolve(invocables, locals, parent, self);
}
var promises = [];
angular.forEach(invocables, function(value) {
if (angular.isFunction(value) || angular.isArray(value)) {
promises.push($q.resolve($injector.invoke(value)));
} else if (angular.isString(value)) {
promises.push($q.resolve($injector.get(value)));
} else {
promises.push($q.resolve(value));
}
});
return $q.all(promises).then(function(resolves) {
var resolveObj = {};
var resolveIter = 0;
angular.forEach(invocables, function(value, key) {
resolveObj[key] = resolves[resolveIter++];
});
return resolveObj;
});
}
};
}];
})
/**
* A helper directive for the $modal service. It creates a backdrop element.
*/
.directive('uibModalBackdrop', ['$animate', '$injector', '$uibModalStack',
function($animate, $injector, $modalStack) {
return {
replace: true,
templateUrl: 'uib/template/modal/backdrop.html',
compile: function(tElement, tAttrs) {
tElement.addClass(tAttrs.backdropClass);
return linkFn;
}
};
function linkFn(scope, element, attrs) {
if (attrs.modalInClass) {
$animate.addClass(element, attrs.modalInClass);
scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) {
var done = setIsAsync();
if (scope.modalOptions.animation) {
$animate.removeClass(element, attrs.modalInClass).then(done);
} else {
done();
}
});
}
}
}])
.directive('uibModalWindow', ['$uibModalStack', '$q', '$animateCss', '$document',
function($modalStack, $q, $animateCss, $document) {
return {
scope: {
index: '@'
},
replace: true,
transclude: true,
templateUrl: function(tElement, tAttrs) {
return tAttrs.templateUrl || 'uib/template/modal/window.html';
},
link: function(scope, element, attrs) {
element.addClass(attrs.windowClass || '');
element.addClass(attrs.windowTopClass || '');
scope.size = attrs.size;
scope.close = function(evt) {
var modal = $modalStack.getTop();
if (modal && modal.value.backdrop &&
modal.value.backdrop !== 'static' &&
evt.target === evt.currentTarget) {
evt.preventDefault();
evt.stopPropagation();
$modalStack.dismiss(modal.key, 'backdrop click');
}
};
// moved from template to fix issue #2280
element.on('click', scope.close);
// This property is only added to the scope for the purpose of detecting when this directive is rendered.
// We can detect that by using this property in the template associated with this directive and then use
// {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}.
scope.$isRendered = true;
// Deferred object that will be resolved when this modal is render.
var modalRenderDeferObj = $q.defer();
// Observe function will be called on next digest cycle after compilation, ensuring that the DOM is ready.
// In order to use this way of finding whether DOM is ready, we need to observe a scope property used in modal's template.
attrs.$observe('modalRender', function(value) {
if (value === 'true') {
modalRenderDeferObj.resolve();
}
});
modalRenderDeferObj.promise.then(function() {
var animationPromise = null;
if (attrs.modalInClass) {
animationPromise = $animateCss(element, {
addClass: attrs.modalInClass
}).start();
scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) {
var done = setIsAsync();
$animateCss(element, {
removeClass: attrs.modalInClass
}).start().then(done);
});
}
$q.when(animationPromise).then(function() {
// Notify {@link $modalStack} that modal is rendered.
var modal = $modalStack.getTop();
if (modal) {
$modalStack.modalRendered(modal.key);
}
/**
* If something within the freshly-opened modal already has focus (perhaps via a
* directive that causes focus). then no need to try and focus anything.
*/
if (!($document[0].activeElement && element[0].contains($document[0].activeElement))) {
var inputWithAutofocus = element[0].querySelector('[autofocus]');
/**
* Auto-focusing of a freshly-opened modal element causes any child elements
* with the autofocus attribute to lose focus. This is an issue on touch
* based devices which will show and then hide the onscreen keyboard.
* Attempts to refocus the autofocus element via JavaScript will not reopen
* the onscreen keyboard. Fixed by updated the focusing logic to only autofocus
* the modal element if the modal does not contain an autofocus element.
*/
if (inputWithAutofocus) {
inputWithAutofocus.focus();
} else {
element[0].focus();
}
}
});
});
}
};
}])
.directive('uibModalAnimationClass', function() {
return {
compile: function(tElement, tAttrs) {
if (tAttrs.modalAnimation) {
tElement.addClass(tAttrs.uibModalAnimationClass);
}
}
};
})
.directive('uibModalTransclude', function() {
return {
link: function(scope, element, attrs, controller, transclude) {
transclude(scope.$parent, function(clone) {
element.empty();
element.append(clone);
});
}
};
})
.factory('$uibModalStack', ['$animate', '$animateCss', '$document',
'$compile', '$rootScope', '$q', '$$multiMap', '$$stackedMap', '$uibPosition',
function($animate, $animateCss, $document, $compile, $rootScope, $q, $$multiMap, $$stackedMap, $uibPosition) {
var OPENED_MODAL_CLASS = 'modal-open';
var backdropDomEl, backdropScope;
var openedWindows = $$stackedMap.createNew();
var openedClasses = $$multiMap.createNew();
var $modalStack = {
NOW_CLOSING_EVENT: 'modal.stack.now-closing'
};
var topModalIndex = 0;
var previousTopOpenedModal = null;
//Modal focus behavior
var tabableSelector = 'a[href], area[href], input:not([disabled]), ' +
'button:not([disabled]),select:not([disabled]), textarea:not([disabled]), ' +
'iframe, object, embed, *[tabindex], *[contenteditable=true]';
var scrollbarPadding;
function isVisible(element) {
return !!(element.offsetWidth ||
element.offsetHeight ||
element.getClientRects().length);
}
function backdropIndex() {
var topBackdropIndex = -1;
var opened = openedWindows.keys();
for (var i = 0; i < opened.length; i++) {
if (openedWindows.get(opened[i]).value.backdrop) {
topBackdropIndex = i;
}
}
// If any backdrop exist, ensure that it's index is always
// right below the top modal
if (topBackdropIndex > -1 && topBackdropIndex < topModalIndex) {
topBackdropIndex = topModalIndex;
}
return topBackdropIndex;
}
$rootScope.$watch(backdropIndex, function(newBackdropIndex) {
if (backdropScope) {
backdropScope.index = newBackdropIndex;
}
});
function removeModalWindow(modalInstance, elementToReceiveFocus) {
var modalWindow = openedWindows.get(modalInstance).value;
var appendToElement = modalWindow.appendTo;
//clean up the stack
openedWindows.remove(modalInstance);
previousTopOpenedModal = openedWindows.top();
if (previousTopOpenedModal) {
topModalIndex = parseInt(previousTopOpenedModal.value.modalDomEl.attr('index'), 10);
}
removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, function() {
var modalBodyClass = modalWindow.openedClass || OPENED_MODAL_CLASS;
openedClasses.remove(modalBodyClass, modalInstance);
var areAnyOpen = openedClasses.hasKey(modalBodyClass);
appendToElement.toggleClass(modalBodyClass, areAnyOpen);
if (!areAnyOpen && scrollbarPadding && scrollbarPadding.heightOverflow && scrollbarPadding.scrollbarWidth) {
if (scrollbarPadding.originalRight) {
appendToElement.css({paddingRight: scrollbarPadding.originalRight + 'px'});
} else {
appendToElement.css({paddingRight: ''});
}
scrollbarPadding = null;
}
toggleTopWindowClass(true);
}, modalWindow.closedDeferred);
checkRemoveBackdrop();
//move focus to specified element if available, or else to body
if (elementToReceiveFocus && elementToReceiveFocus.focus) {
elementToReceiveFocus.focus();
} else if (appendToElement.focus) {
appendToElement.focus();
}
}
// Add or remove "windowTopClass" from the top window in the stack
function toggleTopWindowClass(toggleSwitch) {
var modalWindow;
if (openedWindows.length() > 0) {
modalWindow = openedWindows.top().value;
modalWindow.modalDomEl.toggleClass(modalWindow.windowTopClass || '', toggleSwitch);
}
}
function checkRemoveBackdrop() {
//remove backdrop if no longer needed
if (backdropDomEl && backdropIndex() === -1) {
var backdropScopeRef = backdropScope;
removeAfterAnimate(backdropDomEl, backdropScope, function() {
backdropScopeRef = null;
});
backdropDomEl = undefined;
backdropScope = undefined;
}
}
function removeAfterAnimate(domEl, scope, done, closedDeferred) {
var asyncDeferred;
var asyncPromise = null;
var setIsAsync = function() {
if (!asyncDeferred) {
asyncDeferred = $q.defer();
asyncPromise = asyncDeferred.promise;
}
return function asyncDone() {
asyncDeferred.resolve();
};
};
scope.$broadcast($modalStack.NOW_CLOSING_EVENT, setIsAsync);
// Note that it's intentional that asyncPromise might be null.
// That's when setIsAsync has not been called during the
// NOW_CLOSING_EVENT broadcast.
return $q.when(asyncPromise).then(afterAnimating);
function afterAnimating() {
if (afterAnimating.done) {
return;
}
afterAnimating.done = true;
$animate.leave(domEl).then(function() {
domEl.remove();
if (closedDeferred) {
closedDeferred.resolve();
}
});
scope.$destroy();
if (done) {
done();
}
}
}
$document.on('keydown', keydownListener);
$rootScope.$on('$destroy', function() {
$document.off('keydown', keydownListener);
});
function keydownListener(evt) {
if (evt.isDefaultPrevented()) {
return evt;
}
var modal = openedWindows.top();
if (modal) {
switch (evt.which) {
case 27: {
if (modal.value.keyboard) {
evt.preventDefault();
$rootScope.$apply(function() {
$modalStack.dismiss(modal.key, 'escape key press');
});
}
break;
}
case 9: {
var list = $modalStack.loadFocusElementList(modal);
var focusChanged = false;
if (evt.shiftKey) {
if ($modalStack.isFocusInFirstItem(evt, list) || $modalStack.isModalFocused(evt, modal)) {
focusChanged = $modalStack.focusLastFocusableElement(list);
}
} else {
if ($modalStack.isFocusInLastItem(evt, list)) {
focusChanged = $modalStack.focusFirstFocusableElement(list);
}
}
if (focusChanged) {
evt.preventDefault();
evt.stopPropagation();
}
break;
}
}
}
}
$modalStack.open = function(modalInstance, modal) {
var modalOpener = $document[0].activeElement,
modalBodyClass = modal.openedClass || OPENED_MODAL_CLASS;
toggleTopWindowClass(false);
// Store the current top first, to determine what index we ought to use
// for the current top modal
previousTopOpenedModal = openedWindows.top();
openedWindows.add(modalInstance, {
deferred: modal.deferred,
renderDeferred: modal.renderDeferred,
closedDeferred: modal.closedDeferred,
modalScope: modal.scope,
backdrop: modal.backdrop,
keyboard: modal.keyboard,
openedClass: modal.openedClass,
windowTopClass: modal.windowTopClass,
animation: modal.animation,
appendTo: modal.appendTo
});
openedClasses.put(modalBodyClass, modalInstance);
var appendToElement = modal.appendTo,
currBackdropIndex = backdropIndex();
if (!appendToElement.length) {
throw new Error('appendTo element not found. Make sure that the element passed is in DOM.');
}
if (currBackdropIndex >= 0 && !backdropDomEl) {
backdropScope = $rootScope.$new(true);
backdropScope.modalOptions = modal;
backdropScope.index = currBackdropIndex;
backdropDomEl = angular.element('<div uib-modal-backdrop="modal-backdrop"></div>');
backdropDomEl.attr('backdrop-class', modal.backdropClass);
if (modal.animation) {
backdropDomEl.attr('modal-animation', 'true');
}
$compile(backdropDomEl)(backdropScope);
$animate.enter(backdropDomEl, appendToElement);
scrollbarPadding = $uibPosition.scrollbarPadding(appendToElement);
if (scrollbarPadding.heightOverflow && scrollbarPadding.scrollbarWidth) {
appendToElement.css({paddingRight: scrollbarPadding.right + 'px'});
}
}
// Set the top modal index based on the index of the previous top modal
topModalIndex = previousTopOpenedModal ? parseInt(previousTopOpenedModal.value.modalDomEl.attr('index'), 10) + 1 : 0;
var angularDomEl = angular.element('<div uib-modal-window="modal-window"></div>');
angularDomEl.attr({
'template-url': modal.windowTemplateUrl,
'window-class': modal.windowClass,
'window-top-class': modal.windowTopClass,
'size': modal.size,
'index': topModalIndex,
'animate': 'animate'
}).html(modal.content);
if (modal.animation) {
angularDomEl.attr('modal-animation', 'true');
}
appendToElement.addClass(modalBodyClass);
$animate.enter($compile(angularDomEl)(modal.scope), appendToElement);
openedWindows.top().value.modalDomEl = angularDomEl;
openedWindows.top().value.modalOpener = modalOpener;
};
function broadcastClosing(modalWindow, resultOrReason, closing) {
return !modalWindow.value.modalScope.$broadcast('modal.closing', resultOrReason, closing).defaultPrevented;
}
$modalStack.close = function(modalInstance, result) {
var modalWindow = openedWindows.get(modalInstance);
if (modalWindow && broadcastClosing(modalWindow, result, true)) {
modalWindow.value.modalScope.$$uibDestructionScheduled = true;
modalWindow.value.deferred.resolve(result);
removeModalWindow(modalInstance, modalWindow.value.modalOpener);
return true;
}
return !modalWindow;
};
$modalStack.dismiss = function(modalInstance, reason) {
var modalWindow = openedWindows.get(modalInstance);
if (modalWindow && broadcastClosing(modalWindow, reason, false)) {
modalWindow.value.modalScope.$$uibDestructionScheduled = true;
modalWindow.value.deferred.reject(reason);
removeModalWindow(modalInstance, modalWindow.value.modalOpener);
return true;
}
return !modalWindow;
};
$modalStack.dismissAll = function(reason) {
var topModal = this.getTop();
while (topModal && this.dismiss(topModal.key, reason)) {
topModal = this.getTop();
}
};
$modalStack.getTop = function() {
return openedWindows.top();
};
$modalStack.modalRendered = function(modalInstance) {
var modalWindow = openedWindows.get(modalInstance);
if (modalWindow) {
modalWindow.value.renderDeferred.resolve();
}
};
$modalStack.focusFirstFocusableElement = function(list) {
if (list.length > 0) {
list[0].focus();
return true;
}
return false;
};
$modalStack.focusLastFocusableElement = function(list) {
if (list.length > 0) {
list[list.length - 1].focus();
return true;
}
return false;
};
$modalStack.isModalFocused = function(evt, modalWindow) {
if (evt && modalWindow) {
var modalDomEl = modalWindow.value.modalDomEl;
if (modalDomEl && modalDomEl.length) {
return (evt.target || evt.srcElement) === modalDomEl[0];
}
}
return false;
};
$modalStack.isFocusInFirstItem = function(evt, list) {
if (list.length > 0) {
return (evt.target || evt.srcElement) === list[0];
}
return false;
};
$modalStack.isFocusInLastItem = function(evt, list) {
if (list.length > 0) {
return (evt.target || evt.srcElement) === list[list.length - 1];
}
return false;
};
$modalStack.loadFocusElementList = function(modalWindow) {
if (modalWindow) {
var modalDomE1 = modalWindow.value.modalDomEl;
if (modalDomE1 && modalDomE1.length) {
var elements = modalDomE1[0].querySelectorAll(tabableSelector);
return elements ?
Array.prototype.filter.call(elements, function(element) {
return isVisible(element);
}) : elements;
}
}
};
return $modalStack;
}])
.provider('$uibModal', function() {
var $modalProvider = {
options: {
animation: true,
backdrop: true, //can also be false or 'static'
keyboard: true
},
$get: ['$rootScope', '$q', '$document', '$templateRequest', '$controller', '$uibResolve', '$uibModalStack',
function ($rootScope, $q, $document, $templateRequest, $controller, $uibResolve, $modalStack) {
var $modal = {};
function getTemplatePromise(options) {
return options.template ? $q.when(options.template) :
$templateRequest(angular.isFunction(options.templateUrl) ?
options.templateUrl() : options.templateUrl);
}
var promiseChain = null;
$modal.getPromiseChain = function() {
return promiseChain;
};
$modal.open = function(modalOptions) {
var modalResultDeferred = $q.defer();
var modalOpenedDeferred = $q.defer();
var modalClosedDeferred = $q.defer();
var modalRenderDeferred = $q.defer();
//prepare an instance of a modal to be injected into controllers and returned to a caller
var modalInstance = {
result: modalResultDeferred.promise,
opened: modalOpenedDeferred.promise,
closed: modalClosedDeferred.promise,
rendered: modalRenderDeferred.promise,
close: function (result) {
return $modalStack.close(modalInstance, result);
},
dismiss: function (reason) {
return $modalStack.dismiss(modalInstance, reason);
}
};
//merge and clean up options
modalOptions = angular.extend({}, $modalProvider.options, modalOptions);
modalOptions.resolve = modalOptions.resolve || {};
modalOptions.appendTo = modalOptions.appendTo || $document.find('body').eq(0);
//verify options
if (!modalOptions.template && !modalOptions.templateUrl) {
throw new Error('One of template or templateUrl options is required.');
}
var templateAndResolvePromise =
$q.all([getTemplatePromise(modalOptions), $uibResolve.resolve(modalOptions.resolve, {}, null, null)]);
function resolveWithTemplate() {
return templateAndResolvePromise;
}
// Wait for the resolution of the existing promise chain.
// Then switch to our own combined promise dependency (regardless of how the previous modal fared).
// Then add to $modalStack and resolve opened.
// Finally clean up the chain variable if no subsequent modal has overwritten it.
var samePromise;
samePromise = promiseChain = $q.all([promiseChain])
.then(resolveWithTemplate, resolveWithTemplate)
.then(function resolveSuccess(tplAndVars) {
var providedScope = modalOptions.scope || $rootScope;
var modalScope = providedScope.$new();
modalScope.$close = modalInstance.close;
modalScope.$dismiss = modalInstance.dismiss;
modalScope.$on('$destroy', function() {
if (!modalScope.$$uibDestructionScheduled) {
modalScope.$dismiss('$uibUnscheduledDestruction');
}
});
var ctrlInstance, ctrlInstantiate, ctrlLocals = {};
//controllers
if (modalOptions.controller) {
ctrlLocals.$scope = modalScope;
ctrlLocals.$uibModalInstance = modalInstance;
angular.forEach(tplAndVars[1], function(value, key) {
ctrlLocals[key] = value;
});
// the third param will make the controller instantiate later,private api
// @see https://github.com/angular/angular.js/blob/master/src/ng/controller.js#L126
ctrlInstantiate = $controller(modalOptions.controller, ctrlLocals, true);
if (modalOptions.controllerAs) {
ctrlInstance = ctrlInstantiate.instance;
if (modalOptions.bindToController) {
ctrlInstance.$close = modalScope.$close;
ctrlInstance.$dismiss = modalScope.$dismiss;
angular.extend(ctrlInstance, providedScope);
}
ctrlInstance = ctrlInstantiate();
modalScope[modalOptions.controllerAs] = ctrlInstance;
} else {
ctrlInstance = ctrlInstantiate();
}
if (angular.isFunction(ctrlInstance.$onInit)) {
ctrlInstance.$onInit();
}
}
$modalStack.open(modalInstance, {
scope: modalScope,
deferred: modalResultDeferred,
renderDeferred: modalRenderDeferred,
closedDeferred: modalClosedDeferred,
content: tplAndVars[0],
animation: modalOptions.animation,
backdrop: modalOptions.backdrop,
keyboard: modalOptions.keyboard,
backdropClass: modalOptions.backdropClass,
windowTopClass: modalOptions.windowTopClass,
windowClass: modalOptions.windowClass,
windowTemplateUrl: modalOptions.windowTemplateUrl,
size: modalOptions.size,
openedClass: modalOptions.openedClass,
appendTo: modalOptions.appendTo
});
modalOpenedDeferred.resolve(true);
}, function resolveError(reason) {
modalOpenedDeferred.reject(reason);
modalResultDeferred.reject(reason);
})['finally'](function() {
if (promiseChain === samePromise) {
promiseChain = null;
}
});
return modalInstance;
};
return $modal;
}
]
};
return $modalProvider;
});
angular.module('ui.bootstrap.paging', [])
/**
* Helper internal service for generating common controller code between the
* pager and pagination components
*/
.factory('uibPaging', ['$parse', function($parse) {
return {
create: function(ctrl, $scope, $attrs) {
ctrl.setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop;
ctrl.ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl
ctrl._watchers = [];
ctrl.init = function(ngModelCtrl, config) {
ctrl.ngModelCtrl = ngModelCtrl;
ctrl.config = config;
ngModelCtrl.$render = function() {
ctrl.render();
};
if ($attrs.itemsPerPage) {
ctrl._watchers.push($scope.$parent.$watch($attrs.itemsPerPage, function(value) {
ctrl.itemsPerPage = parseInt(value, 10);
$scope.totalPages = ctrl.calculateTotalPages();
ctrl.updatePage();
}));
} else {
ctrl.itemsPerPage = config.itemsPerPage;
}
$scope.$watch('totalItems', function(newTotal, oldTotal) {
if (angular.isDefined(newTotal) || newTotal !== oldTotal) {
$scope.totalPages = ctrl.calculateTotalPages();
ctrl.updatePage();
}
});
};
ctrl.calculateTotalPages = function() {
var totalPages = ctrl.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / ctrl.itemsPerPage);
return Math.max(totalPages || 0, 1);
};
ctrl.render = function() {
$scope.page = parseInt(ctrl.ngModelCtrl.$viewValue, 10) || 1;
};
$scope.selectPage = function(page, evt) {
if (evt) {
evt.preventDefault();
}
var clickAllowed = !$scope.ngDisabled || !evt;
if (clickAllowed && $scope.page !== page && page > 0 && page <= $scope.totalPages) {
if (evt && evt.target) {
evt.target.blur();
}
ctrl.ngModelCtrl.$setViewValue(page);
ctrl.ngModelCtrl.$render();
}
};
$scope.getText = function(key) {
return $scope[key + 'Text'] || ctrl.config[key + 'Text'];
};
$scope.noPrevious = function() {
return $scope.page === 1;
};
$scope.noNext = function() {
return $scope.page === $scope.totalPages;
};
ctrl.updatePage = function() {
ctrl.setNumPages($scope.$parent, $scope.totalPages); // Readonly variable
if ($scope.page > $scope.totalPages) {
$scope.selectPage($scope.totalPages);
} else {
ctrl.ngModelCtrl.$render();
}
};
$scope.$on('$destroy', function() {
while (ctrl._watchers.length) {
ctrl._watchers.shift()();
}
});
}
};
}]);
angular.module('ui.bootstrap.pager', ['ui.bootstrap.paging'])
.controller('UibPagerController', ['$scope', '$attrs', 'uibPaging', 'uibPagerConfig', function($scope, $attrs, uibPaging, uibPagerConfig) {
$scope.align = angular.isDefined($attrs.align) ? $scope.$parent.$eval($attrs.align) : uibPagerConfig.align;
uibPaging.create(this, $scope, $attrs);
}])
.constant('uibPagerConfig', {
itemsPerPage: 10,
previousText: '« Previous',
nextText: 'Next »',
align: true
})
.directive('uibPager', ['uibPagerConfig', function(uibPagerConfig) {
return {
scope: {
totalItems: '=',
previousText: '@',
nextText: '@',
ngDisabled: '='
},
require: ['uibPager', '?ngModel'],
controller: 'UibPagerController',
controllerAs: 'pager',
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/pager/pager.html';
},
replace: true,
link: function(scope, element, attrs, ctrls) {
var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];
if (!ngModelCtrl) {
return; // do nothing if no ng-model
}
paginationCtrl.init(ngModelCtrl, uibPagerConfig);
}
};
}]);
angular.module('ui.bootstrap.pagination', ['ui.bootstrap.paging'])
.controller('UibPaginationController', ['$scope', '$attrs', '$parse', 'uibPaging', 'uibPaginationConfig', function($scope, $attrs, $parse, uibPaging, uibPaginationConfig) {
var ctrl = this;
// Setup configuration parameters
var maxSize = angular.isDefined($attrs.maxSize) ? $scope.$parent.$eval($attrs.maxSize) : uibPaginationConfig.maxSize,
rotate = angular.isDefined($attrs.rotate) ? $scope.$parent.$eval($attrs.rotate) : uibPaginationConfig.rotate,
forceEllipses = angular.isDefined($attrs.forceEllipses) ? $scope.$parent.$eval($attrs.forceEllipses) : uibPaginationConfig.forceEllipses,
boundaryLinkNumbers = angular.isDefined($attrs.boundaryLinkNumbers) ? $scope.$parent.$eval($attrs.boundaryLinkNumbers) : uibPaginationConfig.boundaryLinkNumbers,
pageLabel = angular.isDefined($attrs.pageLabel) ? function(idx) { return $scope.$parent.$eval($attrs.pageLabel, {$page: idx}); } : angular.identity;
$scope.boundaryLinks = angular.isDefined($attrs.boundaryLinks) ? $scope.$parent.$eval($attrs.boundaryLinks) : uibPaginationConfig.boundaryLinks;
$scope.directionLinks = angular.isDefined($attrs.directionLinks) ? $scope.$parent.$eval($attrs.directionLinks) : uibPaginationConfig.directionLinks;
uibPaging.create(this, $scope, $attrs);
if ($attrs.maxSize) {
ctrl._watchers.push($scope.$parent.$watch($parse($attrs.maxSize), function(value) {
maxSize = parseInt(value, 10);
ctrl.render();
}));
}
// Create page object used in template
function makePage(number, text, isActive) {
return {
number: number,
text: text,
active: isActive
};
}
function getPages(currentPage, totalPages) {
var pages = [];
// Default page limits
var startPage = 1, endPage = totalPages;
var isMaxSized = angular.isDefined(maxSize) && maxSize < totalPages;
// recompute if maxSize
if (isMaxSized) {
if (rotate) {
// Current page is displayed in the middle of the visible ones
startPage = Math.max(currentPage - Math.floor(maxSize / 2), 1);
endPage = startPage + maxSize - 1;
// Adjust if limit is exceeded
if (endPage > totalPages) {
endPage = totalPages;
startPage = endPage - maxSize + 1;
}
} else {
// Visible pages are paginated with maxSize
startPage = (Math.ceil(currentPage / maxSize) - 1) * maxSize + 1;
// Adjust last page if limit is exceeded
endPage = Math.min(startPage + maxSize - 1, totalPages);
}
}
// Add page number links
for (var number = startPage; number <= endPage; number++) {
var page = makePage(number, pageLabel(number), number === currentPage);
pages.push(page);
}
// Add links to move between page sets
if (isMaxSized && maxSize > 0 && (!rotate || forceEllipses || boundaryLinkNumbers)) {
if (startPage > 1) {
if (!boundaryLinkNumbers || startPage > 3) { //need ellipsis for all options unless range is too close to beginning
var previousPageSet = makePage(startPage - 1, '...', false);
pages.unshift(previousPageSet);
}
if (boundaryLinkNumbers) {
if (startPage === 3) { //need to replace ellipsis when the buttons would be sequential
var secondPageLink = makePage(2, '2', false);
pages.unshift(secondPageLink);
}
//add the first page
var firstPageLink = makePage(1, '1', false);
pages.unshift(firstPageLink);
}
}
if (endPage < totalPages) {
if (!boundaryLinkNumbers || endPage < totalPages - 2) { //need ellipsis for all options unless range is too close to end
var nextPageSet = makePage(endPage + 1, '...', false);
pages.push(nextPageSet);
}
if (boundaryLinkNumbers) {
if (endPage === totalPages - 2) { //need to replace ellipsis when the buttons would be sequential
var secondToLastPageLink = makePage(totalPages - 1, totalPages - 1, false);
pages.push(secondToLastPageLink);
}
//add the last page
var lastPageLink = makePage(totalPages, totalPages, false);
pages.push(lastPageLink);
}
}
}
return pages;
}
var originalRender = this.render;
this.render = function() {
originalRender();
if ($scope.page > 0 && $scope.page <= $scope.totalPages) {
$scope.pages = getPages($scope.page, $scope.totalPages);
}
};
}])
.constant('uibPaginationConfig', {
itemsPerPage: 10,
boundaryLinks: false,
boundaryLinkNumbers: false,
directionLinks: true,
firstText: 'First',
previousText: 'Previous',
nextText: 'Next',
lastText: 'Last',
rotate: true,
forceEllipses: false
})
.directive('uibPagination', ['$parse', 'uibPaginationConfig', function($parse, uibPaginationConfig) {
return {
scope: {
totalItems: '=',
firstText: '@',
previousText: '@',
nextText: '@',
lastText: '@',
ngDisabled:'='
},
require: ['uibPagination', '?ngModel'],
controller: 'UibPaginationController',
controllerAs: 'pagination',
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/pagination/pagination.html';
},
replace: true,
link: function(scope, element, attrs, ctrls) {
var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];
if (!ngModelCtrl) {
return; // do nothing if no ng-model
}
paginationCtrl.init(ngModelCtrl, uibPaginationConfig);
}
};
}]);
/**
* The following features are still outstanding: animation as a
* function, placement as a function, inside, support for more triggers than
* just mouse enter/leave, html tooltips, and selector delegation.
*/
angular.module('ui.bootstrap.tooltip', ['ui.bootstrap.position', 'ui.bootstrap.stackedMap'])
/**
* The $tooltip service creates tooltip- and popover-like directives as well as
* houses global options for them.
*/
.provider('$uibTooltip', function() {
// The default options tooltip and popover.
var defaultOptions = {
placement: 'top',
placementClassPrefix: '',
animation: true,
popupDelay: 0,
popupCloseDelay: 0,
useContentExp: false
};
// Default hide triggers for each show trigger
var triggerMap = {
'mouseenter': 'mouseleave',
'click': 'click',
'outsideClick': 'outsideClick',
'focus': 'blur',
'none': ''
};
// The options specified to the provider globally.
var globalOptions = {};
/**
* `options({})` allows global configuration of all tooltips in the
* application.
*
* var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) {
* // place tooltips left instead of top by default
* $tooltipProvider.options( { placement: 'left' } );
* });
*/
this.options = function(value) {
angular.extend(globalOptions, value);
};
/**
* This allows you to extend the set of trigger mappings available. E.g.:
*
* $tooltipProvider.setTriggers( { 'openTrigger': 'closeTrigger' } );
*/
this.setTriggers = function setTriggers(triggers) {
angular.extend(triggerMap, triggers);
};
/**
* This is a helper function for translating camel-case to snake_case.
*/
function snake_case(name) {
var regexp = /[A-Z]/g;
var separator = '-';
return name.replace(regexp, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
/**
* Returns the actual instance of the $tooltip service.
* TODO support multiple triggers
*/
this.$get = ['$window', '$compile', '$timeout', '$document', '$uibPosition', '$interpolate', '$rootScope', '$parse', '$$stackedMap', function($window, $compile, $timeout, $document, $position, $interpolate, $rootScope, $parse, $$stackedMap) {
var openedTooltips = $$stackedMap.createNew();
$document.on('keypress', keypressListener);
$rootScope.$on('$destroy', function() {
$document.off('keypress', keypressListener);
});
function keypressListener(e) {
if (e.which === 27) {
var last = openedTooltips.top();
if (last) {
last.value.close();
openedTooltips.removeTop();
last = null;
}
}
}
return function $tooltip(ttType, prefix, defaultTriggerShow, options) {
options = angular.extend({}, defaultOptions, globalOptions, options);
/**
* Returns an object of show and hide triggers.
*
* If a trigger is supplied,
* it is used to show the tooltip; otherwise, it will use the `trigger`
* option passed to the `$tooltipProvider.options` method; else it will
* default to the trigger supplied to this directive factory.
*
* The hide trigger is based on the show trigger. If the `trigger` option
* was passed to the `$tooltipProvider.options` method, it will use the
* mapped trigger from `triggerMap` or the passed trigger if the map is
* undefined; otherwise, it uses the `triggerMap` value of the show
* trigger; else it will just use the show trigger.
*/
function getTriggers(trigger) {
var show = (trigger || options.trigger || defaultTriggerShow).split(' ');
var hide = show.map(function(trigger) {
return triggerMap[trigger] || trigger;
});
return {
show: show,
hide: hide
};
}
var directiveName = snake_case(ttType);
var startSym = $interpolate.startSymbol();
var endSym = $interpolate.endSymbol();
var template =
'<div '+ directiveName + '-popup ' +
'uib-title="' + startSym + 'title' + endSym + '" ' +
(options.useContentExp ?
'content-exp="contentExp()" ' :
'content="' + startSym + 'content' + endSym + '" ') +
'placement="' + startSym + 'placement' + endSym + '" ' +
'popup-class="' + startSym + 'popupClass' + endSym + '" ' +
'animation="animation" ' +
'is-open="isOpen" ' +
'origin-scope="origScope" ' +
'class="uib-position-measure"' +
'>' +
'</div>';
return {
compile: function(tElem, tAttrs) {
var tooltipLinker = $compile(template);
return function link(scope, element, attrs, tooltipCtrl) {
var tooltip;
var tooltipLinkedScope;
var transitionTimeout;
var showTimeout;
var hideTimeout;
var positionTimeout;
var appendToBody = angular.isDefined(options.appendToBody) ? options.appendToBody : false;
var triggers = getTriggers(undefined);
var hasEnableExp = angular.isDefined(attrs[prefix + 'Enable']);
var ttScope = scope.$new(true);
var repositionScheduled = false;
var isOpenParse = angular.isDefined(attrs[prefix + 'IsOpen']) ? $parse(attrs[prefix + 'IsOpen']) : false;
var contentParse = options.useContentExp ? $parse(attrs[ttType]) : false;
var observers = [];
var lastPlacement;
var positionTooltip = function() {
// check if tooltip exists and is not empty
if (!tooltip || !tooltip.html()) { return; }
if (!positionTimeout) {
positionTimeout = $timeout(function() {
var ttPosition = $position.positionElements(element, tooltip, ttScope.placement, appendToBody);
tooltip.css({ top: ttPosition.top + 'px', left: ttPosition.left + 'px' });
if (!tooltip.hasClass(ttPosition.placement.split('-')[0])) {
tooltip.removeClass(lastPlacement.split('-')[0]);
tooltip.addClass(ttPosition.placement.split('-')[0]);
}
if (!tooltip.hasClass(options.placementClassPrefix + ttPosition.placement)) {
tooltip.removeClass(options.placementClassPrefix + lastPlacement);
tooltip.addClass(options.placementClassPrefix + ttPosition.placement);
}
// first time through tt element will have the
// uib-position-measure class or if the placement
// has changed we need to position the arrow.
if (tooltip.hasClass('uib-position-measure')) {
$position.positionArrow(tooltip, ttPosition.placement);
tooltip.removeClass('uib-position-measure');
} else if (lastPlacement !== ttPosition.placement) {
$position.positionArrow(tooltip, ttPosition.placement);
}
lastPlacement = ttPosition.placement;
positionTimeout = null;
}, 0, false);
}
};
// Set up the correct scope to allow transclusion later
ttScope.origScope = scope;
// By default, the tooltip is not open.
// TODO add ability to start tooltip opened
ttScope.isOpen = false;
openedTooltips.add(ttScope, {
close: hide
});
function toggleTooltipBind() {
if (!ttScope.isOpen) {
showTooltipBind();
} else {
hideTooltipBind();
}
}
// Show the tooltip with delay if specified, otherwise show it immediately
function showTooltipBind() {
if (hasEnableExp && !scope.$eval(attrs[prefix + 'Enable'])) {
return;
}
cancelHide();
prepareTooltip();
if (ttScope.popupDelay) {
// Do nothing if the tooltip was already scheduled to pop-up.
// This happens if show is triggered multiple times before any hide is triggered.
if (!showTimeout) {
showTimeout = $timeout(show, ttScope.popupDelay, false);
}
} else {
show();
}
}
function hideTooltipBind() {
cancelShow();
if (ttScope.popupCloseDelay) {
if (!hideTimeout) {
hideTimeout = $timeout(hide, ttScope.popupCloseDelay, false);
}
} else {
hide();
}
}
// Show the tooltip popup element.
function show() {
cancelShow();
cancelHide();
// Don't show empty tooltips.
if (!ttScope.content) {
return angular.noop;
}
createTooltip();
// And show the tooltip.
ttScope.$evalAsync(function() {
ttScope.isOpen = true;
assignIsOpen(true);
positionTooltip();
});
}
function cancelShow() {
if (showTimeout) {
$timeout.cancel(showTimeout);
showTimeout = null;
}
if (positionTimeout) {
$timeout.cancel(positionTimeout);
positionTimeout = null;
}
}
// Hide the tooltip popup element.
function hide() {
if (!ttScope) {
return;
}
// First things first: we don't show it anymore.
ttScope.$evalAsync(function() {
if (ttScope) {
ttScope.isOpen = false;
assignIsOpen(false);
// And now we remove it from the DOM. However, if we have animation, we
// need to wait for it to expire beforehand.
// FIXME: this is a placeholder for a port of the transitions library.
// The fade transition in TWBS is 150ms.
if (ttScope.animation) {
if (!transitionTimeout) {
transitionTimeout = $timeout(removeTooltip, 150, false);
}
} else {
removeTooltip();
}
}
});
}
function cancelHide() {
if (hideTimeout) {
$timeout.cancel(hideTimeout);
hideTimeout = null;
}
if (transitionTimeout) {
$timeout.cancel(transitionTimeout);
transitionTimeout = null;
}
}
function createTooltip() {
// There can only be one tooltip element per directive shown at once.
if (tooltip) {
return;
}
tooltipLinkedScope = ttScope.$new();
tooltip = tooltipLinker(tooltipLinkedScope, function(tooltip) {
if (appendToBody) {
$document.find('body').append(tooltip);
} else {
element.after(tooltip);
}
});
prepObservers();
}
function removeTooltip() {
cancelShow();
cancelHide();
unregisterObservers();
if (tooltip) {
tooltip.remove();
tooltip = null;
}
if (tooltipLinkedScope) {
tooltipLinkedScope.$destroy();
tooltipLinkedScope = null;
}
}
/**
* Set the initial scope values. Once
* the tooltip is created, the observers
* will be added to keep things in sync.
*/
function prepareTooltip() {
ttScope.title = attrs[prefix + 'Title'];
if (contentParse) {
ttScope.content = contentParse(scope);
} else {
ttScope.content = attrs[ttType];
}
ttScope.popupClass = attrs[prefix + 'Class'];
ttScope.placement = angular.isDefined(attrs[prefix + 'Placement']) ? attrs[prefix + 'Placement'] : options.placement;
var placement = $position.parsePlacement(ttScope.placement);
lastPlacement = placement[1] ? placement[0] + '-' + placement[1] : placement[0];
var delay = parseInt(attrs[prefix + 'PopupDelay'], 10);
var closeDelay = parseInt(attrs[prefix + 'PopupCloseDelay'], 10);
ttScope.popupDelay = !isNaN(delay) ? delay : options.popupDelay;
ttScope.popupCloseDelay = !isNaN(closeDelay) ? closeDelay : options.popupCloseDelay;
}
function assignIsOpen(isOpen) {
if (isOpenParse && angular.isFunction(isOpenParse.assign)) {
isOpenParse.assign(scope, isOpen);
}
}
ttScope.contentExp = function() {
return ttScope.content;
};
/**
* Observe the relevant attributes.
*/
attrs.$observe('disabled', function(val) {
if (val) {
cancelShow();
}
if (val && ttScope.isOpen) {
hide();
}
});
if (isOpenParse) {
scope.$watch(isOpenParse, function(val) {
if (ttScope && !val === ttScope.isOpen) {
toggleTooltipBind();
}
});
}
function prepObservers() {
observers.length = 0;
if (contentParse) {
observers.push(
scope.$watch(contentParse, function(val) {
ttScope.content = val;
if (!val && ttScope.isOpen) {
hide();
}
})
);
observers.push(
tooltipLinkedScope.$watch(function() {
if (!repositionScheduled) {
repositionScheduled = true;
tooltipLinkedScope.$$postDigest(function() {
repositionScheduled = false;
if (ttScope && ttScope.isOpen) {
positionTooltip();
}
});
}
})
);
} else {
observers.push(
attrs.$observe(ttType, function(val) {
ttScope.content = val;
if (!val && ttScope.isOpen) {
hide();
} else {
positionTooltip();
}
})
);
}
observers.push(
attrs.$observe(prefix + 'Title', function(val) {
ttScope.title = val;
if (ttScope.isOpen) {
positionTooltip();
}
})
);
observers.push(
attrs.$observe(prefix + 'Placement', function(val) {
ttScope.placement = val ? val : options.placement;
if (ttScope.isOpen) {
positionTooltip();
}
})
);
}
function unregisterObservers() {
if (observers.length) {
angular.forEach(observers, function(observer) {
observer();
});
observers.length = 0;
}
}
// hide tooltips/popovers for outsideClick trigger
function bodyHideTooltipBind(e) {
if (!ttScope || !ttScope.isOpen || !tooltip) {
return;
}
// make sure the tooltip/popover link or tool tooltip/popover itself were not clicked
if (!element[0].contains(e.target) && !tooltip[0].contains(e.target)) {
hideTooltipBind();
}
}
var unregisterTriggers = function() {
triggers.show.forEach(function(trigger) {
if (trigger === 'outsideClick') {
element.off('click', toggleTooltipBind);
} else {
element.off(trigger, showTooltipBind);
element.off(trigger, toggleTooltipBind);
}
});
triggers.hide.forEach(function(trigger) {
if (trigger === 'outsideClick') {
$document.off('click', bodyHideTooltipBind);
} else {
element.off(trigger, hideTooltipBind);
}
});
};
function prepTriggers() {
var val = attrs[prefix + 'Trigger'];
unregisterTriggers();
triggers = getTriggers(val);
if (triggers.show !== 'none') {
triggers.show.forEach(function(trigger, idx) {
if (trigger === 'outsideClick') {
element.on('click', toggleTooltipBind);
$document.on('click', bodyHideTooltipBind);
} else if (trigger === triggers.hide[idx]) {
element.on(trigger, toggleTooltipBind);
} else if (trigger) {
element.on(trigger, showTooltipBind);
element.on(triggers.hide[idx], hideTooltipBind);
}
element.on('keypress', function(e) {
if (e.which === 27) {
hideTooltipBind();
}
});
});
}
}
prepTriggers();
var animation = scope.$eval(attrs[prefix + 'Animation']);
ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation;
var appendToBodyVal;
var appendKey = prefix + 'AppendToBody';
if (appendKey in attrs && attrs[appendKey] === undefined) {
appendToBodyVal = true;
} else {
appendToBodyVal = scope.$eval(attrs[appendKey]);
}
appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody;
// Make sure tooltip is destroyed and removed.
scope.$on('$destroy', function onDestroyTooltip() {
unregisterTriggers();
removeTooltip();
openedTooltips.remove(ttScope);
ttScope = null;
});
};
}
};
};
}];
})
// This is mostly ngInclude code but with a custom scope
.directive('uibTooltipTemplateTransclude', [
'$animate', '$sce', '$compile', '$templateRequest',
function ($animate, $sce, $compile, $templateRequest) {
return {
link: function(scope, elem, attrs) {
var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope);
var changeCounter = 0,
currentScope,
previousElement,
currentElement;
var cleanupLastIncludeContent = function() {
if (previousElement) {
previousElement.remove();
previousElement = null;
}
if (currentScope) {
currentScope.$destroy();
currentScope = null;
}
if (currentElement) {
$animate.leave(currentElement).then(function() {
previousElement = null;
});
previousElement = currentElement;
currentElement = null;
}
};
scope.$watch($sce.parseAsResourceUrl(attrs.uibTooltipTemplateTransclude), function(src) {
var thisChangeId = ++changeCounter;
if (src) {
//set the 2nd param to true to ignore the template request error so that the inner
//contents and scope can be cleaned up.
$templateRequest(src, true).then(function(response) {
if (thisChangeId !== changeCounter) { return; }
var newScope = origScope.$new();
var template = response;
var clone = $compile(template)(newScope, function(clone) {
cleanupLastIncludeContent();
$animate.enter(clone, elem);
});
currentScope = newScope;
currentElement = clone;
currentScope.$emit('$includeContentLoaded', src);
}, function() {
if (thisChangeId === changeCounter) {
cleanupLastIncludeContent();
scope.$emit('$includeContentError', src);
}
});
scope.$emit('$includeContentRequested', src);
} else {
cleanupLastIncludeContent();
}
});
scope.$on('$destroy', cleanupLastIncludeContent);
}
};
}])
/**
* Note that it's intentional that these classes are *not* applied through $animate.
* They must not be animated as they're expected to be present on the tooltip on
* initialization.
*/
.directive('uibTooltipClasses', ['$uibPosition', function($uibPosition) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
// need to set the primary position so the
// arrow has space during position measure.
// tooltip.positionTooltip()
if (scope.placement) {
// // There are no top-left etc... classes
// // in TWBS, so we need the primary position.
var position = $uibPosition.parsePlacement(scope.placement);
element.addClass(position[0]);
}
if (scope.popupClass) {
element.addClass(scope.popupClass);
}
if (scope.animation()) {
element.addClass(attrs.tooltipAnimationClass);
}
}
};
}])
.directive('uibTooltipPopup', function() {
return {
replace: true,
scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
templateUrl: 'uib/template/tooltip/tooltip-popup.html'
};
})
.directive('uibTooltip', [ '$uibTooltip', function($uibTooltip) {
return $uibTooltip('uibTooltip', 'tooltip', 'mouseenter');
}])
.directive('uibTooltipTemplatePopup', function() {
return {
replace: true,
scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&',
originScope: '&' },
templateUrl: 'uib/template/tooltip/tooltip-template-popup.html'
};
})
.directive('uibTooltipTemplate', ['$uibTooltip', function($uibTooltip) {
return $uibTooltip('uibTooltipTemplate', 'tooltip', 'mouseenter', {
useContentExp: true
});
}])
.directive('uibTooltipHtmlPopup', function() {
return {
replace: true,
scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
templateUrl: 'uib/template/tooltip/tooltip-html-popup.html'
};
})
.directive('uibTooltipHtml', ['$uibTooltip', function($uibTooltip) {
return $uibTooltip('uibTooltipHtml', 'tooltip', 'mouseenter', {
useContentExp: true
});
}]);
/**
* The following features are still outstanding: popup delay, animation as a
* function, placement as a function, inside, support for more triggers than
* just mouse enter/leave, and selector delegatation.
*/
angular.module('ui.bootstrap.popover', ['ui.bootstrap.tooltip'])
.directive('uibPopoverTemplatePopup', function() {
return {
replace: true,
scope: { uibTitle: '@', contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&',
originScope: '&' },
templateUrl: 'uib/template/popover/popover-template.html'
};
})
.directive('uibPopoverTemplate', ['$uibTooltip', function($uibTooltip) {
return $uibTooltip('uibPopoverTemplate', 'popover', 'click', {
useContentExp: true
});
}])
.directive('uibPopoverHtmlPopup', function() {
return {
replace: true,
scope: { contentExp: '&', uibTitle: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
templateUrl: 'uib/template/popover/popover-html.html'
};
})
.directive('uibPopoverHtml', ['$uibTooltip', function($uibTooltip) {
return $uibTooltip('uibPopoverHtml', 'popover', 'click', {
useContentExp: true
});
}])
.directive('uibPopoverPopup', function() {
return {
replace: true,
scope: { uibTitle: '@', content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
templateUrl: 'uib/template/popover/popover.html'
};
})
.directive('uibPopover', ['$uibTooltip', function($uibTooltip) {
return $uibTooltip('uibPopover', 'popover', 'click');
}]);
angular.module('ui.bootstrap.progressbar', [])
.constant('uibProgressConfig', {
animate: true,
max: 100
})
.controller('UibProgressController', ['$scope', '$attrs', 'uibProgressConfig', function($scope, $attrs, progressConfig) {
var self = this,
animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate;
this.bars = [];
$scope.max = getMaxOrDefault();
this.addBar = function(bar, element, attrs) {
if (!animate) {
element.css({'transition': 'none'});
}
this.bars.push(bar);
bar.max = getMaxOrDefault();
bar.title = attrs && angular.isDefined(attrs.title) ? attrs.title : 'progressbar';
bar.$watch('value', function(value) {
bar.recalculatePercentage();
});
bar.recalculatePercentage = function() {
var totalPercentage = self.bars.reduce(function(total, bar) {
bar.percent = +(100 * bar.value / bar.max).toFixed(2);
return total + bar.percent;
}, 0);
if (totalPercentage > 100) {
bar.percent -= totalPercentage - 100;
}
};
bar.$on('$destroy', function() {
element = null;
self.removeBar(bar);
});
};
this.removeBar = function(bar) {
this.bars.splice(this.bars.indexOf(bar), 1);
this.bars.forEach(function (bar) {
bar.recalculatePercentage();
});
};
//$attrs.$observe('maxParam', function(maxParam) {
$scope.$watch('maxParam', function(maxParam) {
self.bars.forEach(function(bar) {
bar.max = getMaxOrDefault();
bar.recalculatePercentage();
});
});
function getMaxOrDefault () {
return angular.isDefined($scope.maxParam) ? $scope.maxParam : progressConfig.max;
}
}])
.directive('uibProgress', function() {
return {
replace: true,
transclude: true,
controller: 'UibProgressController',
require: 'uibProgress',
scope: {
maxParam: '=?max'
},
templateUrl: 'uib/template/progressbar/progress.html'
};
})
.directive('uibBar', function() {
return {
replace: true,
transclude: true,
require: '^uibProgress',
scope: {
value: '=',
type: '@'
},
templateUrl: 'uib/template/progressbar/bar.html',
link: function(scope, element, attrs, progressCtrl) {
progressCtrl.addBar(scope, element, attrs);
}
};
})
.directive('uibProgressbar', function() {
return {
replace: true,
transclude: true,
controller: 'UibProgressController',
scope: {
value: '=',
maxParam: '=?max',
type: '@'
},
templateUrl: 'uib/template/progressbar/progressbar.html',
link: function(scope, element, attrs, progressCtrl) {
progressCtrl.addBar(scope, angular.element(element.children()[0]), {title: attrs.title});
}
};
});
angular.module('ui.bootstrap.rating', [])
.constant('uibRatingConfig', {
max: 5,
stateOn: null,
stateOff: null,
enableReset: true,
titles : ['one', 'two', 'three', 'four', 'five']
})
.controller('UibRatingController', ['$scope', '$attrs', 'uibRatingConfig', function($scope, $attrs, ratingConfig) {
var ngModelCtrl = { $setViewValue: angular.noop },
self = this;
this.init = function(ngModelCtrl_) {
ngModelCtrl = ngModelCtrl_;
ngModelCtrl.$render = this.render;
ngModelCtrl.$formatters.push(function(value) {
if (angular.isNumber(value) && value << 0 !== value) {
value = Math.round(value);
}
return value;
});
this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn;
this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff;
this.enableReset = angular.isDefined($attrs.enableReset) ?
$scope.$parent.$eval($attrs.enableReset) : ratingConfig.enableReset;
var tmpTitles = angular.isDefined($attrs.titles) ? $scope.$parent.$eval($attrs.titles) : ratingConfig.titles;
this.titles = angular.isArray(tmpTitles) && tmpTitles.length > 0 ?
tmpTitles : ratingConfig.titles;
var ratingStates = angular.isDefined($attrs.ratingStates) ?
$scope.$parent.$eval($attrs.ratingStates) :
new Array(angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max);
$scope.range = this.buildTemplateObjects(ratingStates);
};
this.buildTemplateObjects = function(states) {
for (var i = 0, n = states.length; i < n; i++) {
states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff, title: this.getTitle(i) }, states[i]);
}
return states;
};
this.getTitle = function(index) {
if (index >= this.titles.length) {
return index + 1;
}
return this.titles[index];
};
$scope.rate = function(value) {
if (!$scope.readonly && value >= 0 && value <= $scope.range.length) {
var newViewValue = self.enableReset && ngModelCtrl.$viewValue === value ? 0 : value;
ngModelCtrl.$setViewValue(newViewValue);
ngModelCtrl.$render();
}
};
$scope.enter = function(value) {
if (!$scope.readonly) {
$scope.value = value;
}
$scope.onHover({value: value});
};
$scope.reset = function() {
$scope.value = ngModelCtrl.$viewValue;
$scope.onLeave();
};
$scope.onKeydown = function(evt) {
if (/(37|38|39|40)/.test(evt.which)) {
evt.preventDefault();
evt.stopPropagation();
$scope.rate($scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1));
}
};
this.render = function() {
$scope.value = ngModelCtrl.$viewValue;
$scope.title = self.getTitle($scope.value - 1);
};
}])
.directive('uibRating', function() {
return {
require: ['uibRating', 'ngModel'],
scope: {
readonly: '=?readOnly',
onHover: '&',
onLeave: '&'
},
controller: 'UibRatingController',
templateUrl: 'uib/template/rating/rating.html',
replace: true,
link: function(scope, element, attrs, ctrls) {
var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1];
ratingCtrl.init(ngModelCtrl);
}
};
});
angular.module('ui.bootstrap.tabs', [])
.controller('UibTabsetController', ['$scope', function ($scope) {
var ctrl = this,
oldIndex;
ctrl.tabs = [];
ctrl.select = function(index, evt) {
if (!destroyed) {
var previousIndex = findTabIndex(oldIndex);
var previousSelected = ctrl.tabs[previousIndex];
if (previousSelected) {
previousSelected.tab.onDeselect({
$event: evt
});
if (evt && evt.isDefaultPrevented()) {
return;
}
previousSelected.tab.active = false;
}
var selected = ctrl.tabs[index];
if (selected) {
selected.tab.onSelect({
$event: evt
});
selected.tab.active = true;
ctrl.active = selected.index;
oldIndex = selected.index;
} else if (!selected && angular.isNumber(oldIndex)) {
ctrl.active = null;
oldIndex = null;
}
}
};
ctrl.addTab = function addTab(tab) {
ctrl.tabs.push({
tab: tab,
index: tab.index
});
ctrl.tabs.sort(function(t1, t2) {
if (t1.index > t2.index) {
return 1;
}
if (t1.index < t2.index) {
return -1;
}
return 0;
});
if (tab.index === ctrl.active || !angular.isNumber(ctrl.active) && ctrl.tabs.length === 1) {
var newActiveIndex = findTabIndex(tab.index);
ctrl.select(newActiveIndex);
}
};
ctrl.removeTab = function removeTab(tab) {
var index;
for (var i = 0; i < ctrl.tabs.length; i++) {
if (ctrl.tabs[i].tab === tab) {
index = i;
break;
}
}
if (ctrl.tabs[index].index === ctrl.active) {
var newActiveTabIndex = index === ctrl.tabs.length - 1 ?
index - 1 : index + 1 % ctrl.tabs.length;
ctrl.select(newActiveTabIndex);
}
ctrl.tabs.splice(index, 1);
};
$scope.$watch('tabset.active', function(val) {
if (angular.isNumber(val) && val !== oldIndex) {
ctrl.select(findTabIndex(val));
}
});
var destroyed;
$scope.$on('$destroy', function() {
destroyed = true;
});
function findTabIndex(index) {
for (var i = 0; i < ctrl.tabs.length; i++) {
if (ctrl.tabs[i].index === index) {
return i;
}
}
}
}])
.directive('uibTabset', function() {
return {
transclude: true,
replace: true,
scope: {},
bindToController: {
active: '=?',
type: '@'
},
controller: 'UibTabsetController',
controllerAs: 'tabset',
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/tabs/tabset.html';
},
link: function(scope, element, attrs) {
scope.vertical = angular.isDefined(attrs.vertical) ?
scope.$parent.$eval(attrs.vertical) : false;
scope.justified = angular.isDefined(attrs.justified) ?
scope.$parent.$eval(attrs.justified) : false;
if (angular.isUndefined(attrs.active)) {
scope.active = 0;
}
}
};
})
.directive('uibTab', ['$parse', function($parse) {
return {
require: '^uibTabset',
replace: true,
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'uib/template/tabs/tab.html';
},
transclude: true,
scope: {
heading: '@',
index: '=?',
classes: '@?',
onSelect: '&select', //This callback is called in contentHeadingTransclude
//once it inserts the tab's content into the dom
onDeselect: '&deselect'
},
controller: function() {
//Empty controller so other directives can require being 'under' a tab
},
controllerAs: 'tab',
link: function(scope, elm, attrs, tabsetCtrl, transclude) {
scope.disabled = false;
if (attrs.disable) {
scope.$parent.$watch($parse(attrs.disable), function(value) {
scope.disabled = !! value;
});
}
if (angular.isUndefined(attrs.index)) {
if (tabsetCtrl.tabs && tabsetCtrl.tabs.length) {
scope.index = Math.max.apply(null, tabsetCtrl.tabs.map(function(t) { return t.index; })) + 1;
} else {
scope.index = 0;
}
}
if (angular.isUndefined(attrs.classes)) {
scope.classes = '';
}
scope.select = function(evt) {
if (!scope.disabled) {
var index;
for (var i = 0; i < tabsetCtrl.tabs.length; i++) {
if (tabsetCtrl.tabs[i].tab === scope) {
index = i;
break;
}
}
tabsetCtrl.select(index, evt);
}
};
tabsetCtrl.addTab(scope);
scope.$on('$destroy', function() {
tabsetCtrl.removeTab(scope);
});
//We need to transclude later, once the content container is ready.
//when this link happens, we're inside a tab heading.
scope.$transcludeFn = transclude;
}
};
}])
.directive('uibTabHeadingTransclude', function() {
return {
restrict: 'A',
require: '^uibTab',
link: function(scope, elm) {
scope.$watch('headingElement', function updateHeadingElement(heading) {
if (heading) {
elm.html('');
elm.append(heading);
}
});
}
};
})
.directive('uibTabContentTransclude', function() {
return {
restrict: 'A',
require: '^uibTabset',
link: function(scope, elm, attrs) {
var tab = scope.$eval(attrs.uibTabContentTransclude).tab;
//Now our tab is ready to be transcluded: both the tab heading area
//and the tab content area are loaded. Transclude 'em both.
tab.$transcludeFn(tab.$parent, function(contents) {
angular.forEach(contents, function(node) {
if (isTabHeading(node)) {
//Let tabHeadingTransclude know.
tab.headingElement = node;
} else {
elm.append(node);
}
});
});
}
};
function isTabHeading(node) {
return node.tagName && (
node.hasAttribute('uib-tab-heading') ||
node.hasAttribute('data-uib-tab-heading') ||
node.hasAttribute('x-uib-tab-heading') ||
node.tagName.toLowerCase() === 'uib-tab-heading' ||
node.tagName.toLowerCase() === 'data-uib-tab-heading' ||
node.tagName.toLowerCase() === 'x-uib-tab-heading' ||
node.tagName.toLowerCase() === 'uib:tab-heading'
);
}
});
angular.module('ui.bootstrap.timepicker', [])
.constant('uibTimepickerConfig', {
hourStep: 1,
minuteStep: 1,
secondStep: 1,
showMeridian: true,
showSeconds: false,
meridians: null,
readonlyInput: false,
mousewheel: true,
arrowkeys: true,
showSpinners: true,
templateUrl: 'uib/template/timepicker/timepicker.html'
})
.controller('UibTimepickerController', ['$scope', '$element', '$attrs', '$parse', '$log', '$locale', 'uibTimepickerConfig', function($scope, $element, $attrs, $parse, $log, $locale, timepickerConfig) {
var selected = new Date(),
watchers = [],
ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS,
padHours = angular.isDefined($attrs.padHours) ? $scope.$parent.$eval($attrs.padHours) : true;
$scope.tabindex = angular.isDefined($attrs.tabindex) ? $attrs.tabindex : 0;
$element.removeAttr('tabindex');
this.init = function(ngModelCtrl_, inputs) {
ngModelCtrl = ngModelCtrl_;
ngModelCtrl.$render = this.render;
ngModelCtrl.$formatters.unshift(function(modelValue) {
return modelValue ? new Date(modelValue) : null;
});
var hoursInputEl = inputs.eq(0),
minutesInputEl = inputs.eq(1),
secondsInputEl = inputs.eq(2);
var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel;
if (mousewheel) {
this.setupMousewheelEvents(hoursInputEl, minutesInputEl, secondsInputEl);
}
var arrowkeys = angular.isDefined($attrs.arrowkeys) ? $scope.$parent.$eval($attrs.arrowkeys) : timepickerConfig.arrowkeys;
if (arrowkeys) {
this.setupArrowkeyEvents(hoursInputEl, minutesInputEl, secondsInputEl);
}
$scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput;
this.setupInputEvents(hoursInputEl, minutesInputEl, secondsInputEl);
};
var hourStep = timepickerConfig.hourStep;
if ($attrs.hourStep) {
watchers.push($scope.$parent.$watch($parse($attrs.hourStep), function(value) {
hourStep = +value;
}));
}
var minuteStep = timepickerConfig.minuteStep;
if ($attrs.minuteStep) {
watchers.push($scope.$parent.$watch($parse($attrs.minuteStep), function(value) {
minuteStep = +value;
}));
}
var min;
watchers.push($scope.$parent.$watch($parse($attrs.min), function(value) {
var dt = new Date(value);
min = isNaN(dt) ? undefined : dt;
}));
var max;
watchers.push($scope.$parent.$watch($parse($attrs.max), function(value) {
var dt = new Date(value);
max = isNaN(dt) ? undefined : dt;
}));
var disabled = false;
if ($attrs.ngDisabled) {
watchers.push($scope.$parent.$watch($parse($attrs.ngDisabled), function(value) {
disabled = value;
}));
}
$scope.noIncrementHours = function() {
var incrementedSelected = addMinutes(selected, hourStep * 60);
return disabled || incrementedSelected > max ||
incrementedSelected < selected && incrementedSelected < min;
};
$scope.noDecrementHours = function() {
var decrementedSelected = addMinutes(selected, -hourStep * 60);
return disabled || decrementedSelected < min ||
decrementedSelected > selected && decrementedSelected > max;
};
$scope.noIncrementMinutes = function() {
var incrementedSelected = addMinutes(selected, minuteStep);
return disabled || incrementedSelected > max ||
incrementedSelected < selected && incrementedSelected < min;
};
$scope.noDecrementMinutes = function() {
var decrementedSelected = addMinutes(selected, -minuteStep);
return disabled || decrementedSelected < min ||
decrementedSelected > selected && decrementedSelected > max;
};
$scope.noIncrementSeconds = function() {
var incrementedSelected = addSeconds(selected, secondStep);
return disabled || incrementedSelected > max ||
incrementedSelected < selected && incrementedSelected < min;
};
$scope.noDecrementSeconds = function() {
var decrementedSelected = addSeconds(selected, -secondStep);
return disabled || decrementedSelected < min ||
decrementedSelected > selected && decrementedSelected > max;
};
$scope.noToggleMeridian = function() {
if (selected.getHours() < 12) {
return disabled || addMinutes(selected, 12 * 60) > max;
}
return disabled || addMinutes(selected, -12 * 60) < min;
};
var secondStep = timepickerConfig.secondStep;
if ($attrs.secondStep) {
watchers.push($scope.$parent.$watch($parse($attrs.secondStep), function(value) {
secondStep = +value;
}));
}
$scope.showSeconds = timepickerConfig.showSeconds;
if ($attrs.showSeconds) {
watchers.push($scope.$parent.$watch($parse($attrs.showSeconds), function(value) {
$scope.showSeconds = !!value;
}));
}
// 12H / 24H mode
$scope.showMeridian = timepickerConfig.showMeridian;
if ($attrs.showMeridian) {
watchers.push($scope.$parent.$watch($parse($attrs.showMeridian), function(value) {
$scope.showMeridian = !!value;
if (ngModelCtrl.$error.time) {
// Evaluate from template
var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate();
if (angular.isDefined(hours) && angular.isDefined(minutes)) {
selected.setHours(hours);
refresh();
}
} else {
updateTemplate();
}
}));
}
// Get $scope.hours in 24H mode if valid
function getHoursFromTemplate() {
var hours = +$scope.hours;
var valid = $scope.showMeridian ? hours > 0 && hours < 13 :
hours >= 0 && hours < 24;
if (!valid || $scope.hours === '') {
return undefined;
}
if ($scope.showMeridian) {
if (hours === 12) {
hours = 0;
}
if ($scope.meridian === meridians[1]) {
hours = hours + 12;
}
}
return hours;
}
function getMinutesFromTemplate() {
var minutes = +$scope.minutes;
var valid = minutes >= 0 && minutes < 60;
if (!valid || $scope.minutes === '') {
return undefined;
}
return minutes;
}
function getSecondsFromTemplate() {
var seconds = +$scope.seconds;
return seconds >= 0 && seconds < 60 ? seconds : undefined;
}
function pad(value, noPad) {
if (value === null) {
return '';
}
return angular.isDefined(value) && value.toString().length < 2 && !noPad ?
'0' + value : value.toString();
}
// Respond on mousewheel spin
this.setupMousewheelEvents = function(hoursInputEl, minutesInputEl, secondsInputEl) {
var isScrollingUp = function(e) {
if (e.originalEvent) {
e = e.originalEvent;
}
//pick correct delta variable depending on event
var delta = e.wheelDelta ? e.wheelDelta : -e.deltaY;
return e.detail || delta > 0;
};
hoursInputEl.bind('mousewheel wheel', function(e) {
if (!disabled) {
$scope.$apply(isScrollingUp(e) ? $scope.incrementHours() : $scope.decrementHours());
}
e.preventDefault();
});
minutesInputEl.bind('mousewheel wheel', function(e) {
if (!disabled) {
$scope.$apply(isScrollingUp(e) ? $scope.incrementMinutes() : $scope.decrementMinutes());
}
e.preventDefault();
});
secondsInputEl.bind('mousewheel wheel', function(e) {
if (!disabled) {
$scope.$apply(isScrollingUp(e) ? $scope.incrementSeconds() : $scope.decrementSeconds());
}
e.preventDefault();
});
};
// Respond on up/down arrowkeys
this.setupArrowkeyEvents = function(hoursInputEl, minutesInputEl, secondsInputEl) {
hoursInputEl.bind('keydown', function(e) {
if (!disabled) {
if (e.which === 38) { // up
e.preventDefault();
$scope.incrementHours();
$scope.$apply();
} else if (e.which === 40) { // down
e.preventDefault();
$scope.decrementHours();
$scope.$apply();
}
}
});
minutesInputEl.bind('keydown', function(e) {
if (!disabled) {
if (e.which === 38) { // up
e.preventDefault();
$scope.incrementMinutes();
$scope.$apply();
} else if (e.which === 40) { // down
e.preventDefault();
$scope.decrementMinutes();
$scope.$apply();
}
}
});
secondsInputEl.bind('keydown', function(e) {
if (!disabled) {
if (e.which === 38) { // up
e.preventDefault();
$scope.incrementSeconds();
$scope.$apply();
} else if (e.which === 40) { // down
e.preventDefault();
$scope.decrementSeconds();
$scope.$apply();
}
}
});
};
this.setupInputEvents = function(hoursInputEl, minutesInputEl, secondsInputEl) {
if ($scope.readonlyInput) {
$scope.updateHours = angular.noop;
$scope.updateMinutes = angular.noop;
$scope.updateSeconds = angular.noop;
return;
}
var invalidate = function(invalidHours, invalidMinutes, invalidSeconds) {
ngModelCtrl.$setViewValue(null);
ngModelCtrl.$setValidity('time', false);
if (angular.isDefined(invalidHours)) {
$scope.invalidHours = invalidHours;
}
if (angular.isDefined(invalidMinutes)) {
$scope.invalidMinutes = invalidMinutes;
}
if (angular.isDefined(invalidSeconds)) {
$scope.invalidSeconds = invalidSeconds;
}
};
$scope.updateHours = function() {
var hours = getHoursFromTemplate(),
minutes = getMinutesFromTemplate();
ngModelCtrl.$setDirty();
if (angular.isDefined(hours) && angular.isDefined(minutes)) {
selected.setHours(hours);
selected.setMinutes(minutes);
if (selected < min || selected > max) {
invalidate(true);
} else {
refresh('h');
}
} else {
invalidate(true);
}
};
hoursInputEl.bind('blur', function(e) {
ngModelCtrl.$setTouched();
if (modelIsEmpty()) {
makeValid();
} else if ($scope.hours === null || $scope.hours === '') {
invalidate(true);
} else if (!$scope.invalidHours && $scope.hours < 10) {
$scope.$apply(function() {
$scope.hours = pad($scope.hours, !padHours);
});
}
});
$scope.updateMinutes = function() {
var minutes = getMinutesFromTemplate(),
hours = getHoursFromTemplate();
ngModelCtrl.$setDirty();
if (angular.isDefined(minutes) && angular.isDefined(hours)) {
selected.setHours(hours);
selected.setMinutes(minutes);
if (selected < min || selected > max) {
invalidate(undefined, true);
} else {
refresh('m');
}
} else {
invalidate(undefined, true);
}
};
minutesInputEl.bind('blur', function(e) {
ngModelCtrl.$setTouched();
if (modelIsEmpty()) {
makeValid();
} else if ($scope.minutes === null) {
invalidate(undefined, true);
} else if (!$scope.invalidMinutes && $scope.minutes < 10) {
$scope.$apply(function() {
$scope.minutes = pad($scope.minutes);
});
}
});
$scope.updateSeconds = function() {
var seconds = getSecondsFromTemplate();
ngModelCtrl.$setDirty();
if (angular.isDefined(seconds)) {
selected.setSeconds(seconds);
refresh('s');
} else {
invalidate(undefined, undefined, true);
}
};
secondsInputEl.bind('blur', function(e) {
if (modelIsEmpty()) {
makeValid();
} else if (!$scope.invalidSeconds && $scope.seconds < 10) {
$scope.$apply( function() {
$scope.seconds = pad($scope.seconds);
});
}
});
};
this.render = function() {
var date = ngModelCtrl.$viewValue;
if (isNaN(date)) {
ngModelCtrl.$setValidity('time', false);
$log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
} else {
if (date) {
selected = date;
}
if (selected < min || selected > max) {
ngModelCtrl.$setValidity('time', false);
$scope.invalidHours = true;
$scope.invalidMinutes = true;
} else {
makeValid();
}
updateTemplate();
}
};
// Call internally when we know that model is valid.
function refresh(keyboardChange) {
makeValid();
ngModelCtrl.$setViewValue(new Date(selected));
updateTemplate(keyboardChange);
}
function makeValid() {
ngModelCtrl.$setValidity('time', true);
$scope.invalidHours = false;
$scope.invalidMinutes = false;
$scope.invalidSeconds = false;
}
function updateTemplate(keyboardChange) {
if (!ngModelCtrl.$modelValue) {
$scope.hours = null;
$scope.minutes = null;
$scope.seconds = null;
$scope.meridian = meridians[0];
} else {
var hours = selected.getHours(),
minutes = selected.getMinutes(),
seconds = selected.getSeconds();
if ($scope.showMeridian) {
hours = hours === 0 || hours === 12 ? 12 : hours % 12; // Convert 24 to 12 hour system
}
$scope.hours = keyboardChange === 'h' ? hours : pad(hours, !padHours);
if (keyboardChange !== 'm') {
$scope.minutes = pad(minutes);
}
$scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];
if (keyboardChange !== 's') {
$scope.seconds = pad(seconds);
}
$scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];
}
}
function addSecondsToSelected(seconds) {
selected = addSeconds(selected, seconds);
refresh();
}
function addMinutes(selected, minutes) {
return addSeconds(selected, minutes*60);
}
function addSeconds(date, seconds) {
var dt = new Date(date.getTime() + seconds * 1000);
var newDate = new Date(date);
newDate.setHours(dt.getHours(), dt.getMinutes(), dt.getSeconds());
return newDate;
}
function modelIsEmpty() {
return ($scope.hours === null || $scope.hours === '') &&
($scope.minutes === null || $scope.minutes === '') &&
(!$scope.showSeconds || $scope.showSeconds && ($scope.seconds === null || $scope.seconds === ''));
}
$scope.showSpinners = angular.isDefined($attrs.showSpinners) ?
$scope.$parent.$eval($attrs.showSpinners) : timepickerConfig.showSpinners;
$scope.incrementHours = function() {
if (!$scope.noIncrementHours()) {
addSecondsToSelected(hourStep * 60 * 60);
}
};
$scope.decrementHours = function() {
if (!$scope.noDecrementHours()) {
addSecondsToSelected(-hourStep * 60 * 60);
}
};
$scope.incrementMinutes = function() {
if (!$scope.noIncrementMinutes()) {
addSecondsToSelected(minuteStep * 60);
}
};
$scope.decrementMinutes = function() {
if (!$scope.noDecrementMinutes()) {
addSecondsToSelected(-minuteStep * 60);
}
};
$scope.incrementSeconds = function() {
if (!$scope.noIncrementSeconds()) {
addSecondsToSelected(secondStep);
}
};
$scope.decrementSeconds = function() {
if (!$scope.noDecrementSeconds()) {
addSecondsToSelected(-secondStep);
}
};
$scope.toggleMeridian = function() {
var minutes = getMinutesFromTemplate(),
hours = getHoursFromTemplate();
if (!$scope.noToggleMeridian()) {
if (angular.isDefined(minutes) && angular.isDefined(hours)) {
addSecondsToSelected(12 * 60 * (selected.getHours() < 12 ? 60 : -60));
} else {
$scope.meridian = $scope.meridian === meridians[0] ? meridians[1] : meridians[0];
}
}
};
$scope.blur = function() {
ngModelCtrl.$setTouched();
};
$scope.$on('$destroy', function() {
while (watchers.length) {
watchers.shift()();
}
});
}])
.directive('uibTimepicker', ['uibTimepickerConfig', function(uibTimepickerConfig) {
return {
require: ['uibTimepicker', '?^ngModel'],
controller: 'UibTimepickerController',
controllerAs: 'timepicker',
replace: true,
scope: {},
templateUrl: function(element, attrs) {
return attrs.templateUrl || uibTimepickerConfig.templateUrl;
},
link: function(scope, element, attrs, ctrls) {
var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];
if (ngModelCtrl) {
timepickerCtrl.init(ngModelCtrl, element.find('input'));
}
}
};
}]);
angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.debounce', 'ui.bootstrap.position'])
/**
* A helper service that can parse typeahead's syntax (string provided by users)
* Extracted to a separate service for ease of unit testing
*/
.factory('uibTypeaheadParser', ['$parse', function($parse) {
// 00000111000000000000022200000000000000003333333333333330000000000044000
var TYPEAHEAD_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/;
return {
parse: function(input) {
var match = input.match(TYPEAHEAD_REGEXP);
if (!match) {
throw new Error(
'Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_"' +
' but got "' + input + '".');
}
return {
itemName: match[3],
source: $parse(match[4]),
viewMapper: $parse(match[2] || match[1]),
modelMapper: $parse(match[1])
};
}
};
}])
.controller('UibTypeaheadController', ['$scope', '$element', '$attrs', '$compile', '$parse', '$q', '$timeout', '$document', '$window', '$rootScope', '$$debounce', '$uibPosition', 'uibTypeaheadParser',
function(originalScope, element, attrs, $compile, $parse, $q, $timeout, $document, $window, $rootScope, $$debounce, $position, typeaheadParser) {
var HOT_KEYS = [9, 13, 27, 38, 40];
var eventDebounceTime = 200;
var modelCtrl, ngModelOptions;
//SUPPORTED ATTRIBUTES (OPTIONS)
//minimal no of characters that needs to be entered before typeahead kicks-in
var minLength = originalScope.$eval(attrs.typeaheadMinLength);
if (!minLength && minLength !== 0) {
minLength = 1;
}
originalScope.$watch(attrs.typeaheadMinLength, function (newVal) {
minLength = !newVal && newVal !== 0 ? 1 : newVal;
});
//minimal wait time after last character typed before typeahead kicks-in
var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0;
//should it restrict model values to the ones selected from the popup only?
var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false;
originalScope.$watch(attrs.typeaheadEditable, function (newVal) {
isEditable = newVal !== false;
});
//binding to a variable that indicates if matches are being retrieved asynchronously
var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop;
//a callback executed when a match is selected
var onSelectCallback = $parse(attrs.typeaheadOnSelect);
//should it select highlighted popup value when losing focus?
var isSelectOnBlur = angular.isDefined(attrs.typeaheadSelectOnBlur) ? originalScope.$eval(attrs.typeaheadSelectOnBlur) : false;
//binding to a variable that indicates if there were no results after the query is completed
var isNoResultsSetter = $parse(attrs.typeaheadNoResults).assign || angular.noop;
var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined;
var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false;
var appendTo = attrs.typeaheadAppendTo ?
originalScope.$eval(attrs.typeaheadAppendTo) : null;
var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false;
//If input matches an item of the list exactly, select it automatically
var selectOnExact = attrs.typeaheadSelectOnExact ? originalScope.$eval(attrs.typeaheadSelectOnExact) : false;
//binding to a variable that indicates if dropdown is open
var isOpenSetter = $parse(attrs.typeaheadIsOpen).assign || angular.noop;
var showHint = originalScope.$eval(attrs.typeaheadShowHint) || false;
//INTERNAL VARIABLES
//model setter executed upon match selection
var parsedModel = $parse(attrs.ngModel);
var invokeModelSetter = $parse(attrs.ngModel + '($$$p)');
var $setModelValue = function(scope, newValue) {
if (angular.isFunction(parsedModel(originalScope)) &&
ngModelOptions && ngModelOptions.$options && ngModelOptions.$options.getterSetter) {
return invokeModelSetter(scope, {$$$p: newValue});
}
return parsedModel.assign(scope, newValue);
};
//expressions used by typeahead
var parserResult = typeaheadParser.parse(attrs.uibTypeahead);
var hasFocus;
//Used to avoid bug in iOS webview where iOS keyboard does not fire
//mousedown & mouseup events
//Issue #3699
var selected;
//create a child scope for the typeahead directive so we are not polluting original scope
//with typeahead-specific data (matches, query etc.)
var scope = originalScope.$new();
var offDestroy = originalScope.$on('$destroy', function() {
scope.$destroy();
});
scope.$on('$destroy', offDestroy);
// WAI-ARIA
var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000);
element.attr({
'aria-autocomplete': 'list',
'aria-expanded': false,
'aria-owns': popupId
});
var inputsContainer, hintInputElem;
//add read-only input to show hint
if (showHint) {
inputsContainer = angular.element('<div></div>');
inputsContainer.css('position', 'relative');
element.after(inputsContainer);
hintInputElem = element.clone();
hintInputElem.attr('placeholder', '');
hintInputElem.attr('tabindex', '-1');
hintInputElem.val('');
hintInputElem.css({
'position': 'absolute',
'top': '0px',
'left': '0px',
'border-color': 'transparent',
'box-shadow': 'none',
'opacity': 1,
'background': 'none 0% 0% / auto repeat scroll padding-box border-box rgb(255, 255, 255)',
'color': '#999'
});
element.css({
'position': 'relative',
'vertical-align': 'top',
'background-color': 'transparent'
});
inputsContainer.append(hintInputElem);
hintInputElem.after(element);
}
//pop-up element used to display matches
var popUpEl = angular.element('<div uib-typeahead-popup></div>');
popUpEl.attr({
id: popupId,
matches: 'matches',
active: 'activeIdx',
select: 'select(activeIdx, evt)',
'move-in-progress': 'moveInProgress',
query: 'query',
position: 'position',
'assign-is-open': 'assignIsOpen(isOpen)',
debounce: 'debounceUpdate'
});
//custom item template
if (angular.isDefined(attrs.typeaheadTemplateUrl)) {
popUpEl.attr('template-url', attrs.typeaheadTemplateUrl);
}
if (angular.isDefined(attrs.typeaheadPopupTemplateUrl)) {
popUpEl.attr('popup-template-url', attrs.typeaheadPopupTemplateUrl);
}
var resetHint = function() {
if (showHint) {
hintInputElem.val('');
}
};
var resetMatches = function() {
scope.matches = [];
scope.activeIdx = -1;
element.attr('aria-expanded', false);
resetHint();
};
var getMatchId = function(index) {
return popupId + '-option-' + index;
};
// Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead.
// This attribute is added or removed automatically when the `activeIdx` changes.
scope.$watch('activeIdx', function(index) {
if (index < 0) {
element.removeAttr('aria-activedescendant');
} else {
element.attr('aria-activedescendant', getMatchId(index));
}
});
var inputIsExactMatch = function(inputValue, index) {
if (scope.matches.length > index && inputValue) {
return inputValue.toUpperCase() === scope.matches[index].label.toUpperCase();
}
return false;
};
var getMatchesAsync = function(inputValue, evt) {
var locals = {$viewValue: inputValue};
isLoadingSetter(originalScope, true);
isNoResultsSetter(originalScope, false);
$q.when(parserResult.source(originalScope, locals)).then(function(matches) {
//it might happen that several async queries were in progress if a user were typing fast
//but we are interested only in responses that correspond to the current view value
var onCurrentRequest = inputValue === modelCtrl.$viewValue;
if (onCurrentRequest && hasFocus) {
if (matches && matches.length > 0) {
scope.activeIdx = focusFirst ? 0 : -1;
isNoResultsSetter(originalScope, false);
scope.matches.length = 0;
//transform labels
for (var i = 0; i < matches.length; i++) {
locals[parserResult.itemName] = matches[i];
scope.matches.push({
id: getMatchId(i),
label: parserResult.viewMapper(scope, locals),
model: matches[i]
});
}
scope.query = inputValue;
//position pop-up with matches - we need to re-calculate its position each time we are opening a window
//with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
//due to other elements being rendered
recalculatePosition();
element.attr('aria-expanded', true);
//Select the single remaining option if user input matches
if (selectOnExact && scope.matches.length === 1 && inputIsExactMatch(inputValue, 0)) {
if (angular.isNumber(scope.debounceUpdate) || angular.isObject(scope.debounceUpdate)) {
$$debounce(function() {
scope.select(0, evt);
}, angular.isNumber(scope.debounceUpdate) ? scope.debounceUpdate : scope.debounceUpdate['default']);
} else {
scope.select(0, evt);
}
}
if (showHint) {
var firstLabel = scope.matches[0].label;
if (angular.isString(inputValue) &&
inputValue.length > 0 &&
firstLabel.slice(0, inputValue.length).toUpperCase() === inputValue.toUpperCase()) {
hintInputElem.val(inputValue + firstLabel.slice(inputValue.length));
} else {
hintInputElem.val('');
}
}
} else {
resetMatches();
isNoResultsSetter(originalScope, true);
}
}
if (onCurrentRequest) {
isLoadingSetter(originalScope, false);
}
}, function() {
resetMatches();
isLoadingSetter(originalScope, false);
isNoResultsSetter(originalScope, true);
});
};
// bind events only if appendToBody params exist - performance feature
if (appendToBody) {
angular.element($window).on('resize', fireRecalculating);
$document.find('body').on('scroll', fireRecalculating);
}
// Declare the debounced function outside recalculating for
// proper debouncing
var debouncedRecalculate = $$debounce(function() {
// if popup is visible
if (scope.matches.length) {
recalculatePosition();
}
scope.moveInProgress = false;
}, eventDebounceTime);
// Default progress type
scope.moveInProgress = false;
function fireRecalculating() {
if (!scope.moveInProgress) {
scope.moveInProgress = true;
scope.$digest();
}
debouncedRecalculate();
}
// recalculate actual position and set new values to scope
// after digest loop is popup in right position
function recalculatePosition() {
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top += element.prop('offsetHeight');
}
//we need to propagate user's query so we can higlight matches
scope.query = undefined;
//Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
var timeoutPromise;
var scheduleSearchWithTimeout = function(inputValue) {
timeoutPromise = $timeout(function() {
getMatchesAsync(inputValue);
}, waitTime);
};
var cancelPreviousTimeout = function() {
if (timeoutPromise) {
$timeout.cancel(timeoutPromise);
}
};
resetMatches();
scope.assignIsOpen = function (isOpen) {
isOpenSetter(originalScope, isOpen);
};
scope.select = function(activeIdx, evt) {
//called from within the $digest() cycle
var locals = {};
var model, item;
selected = true;
locals[parserResult.itemName] = item = scope.matches[activeIdx].model;
model = parserResult.modelMapper(originalScope, locals);
$setModelValue(originalScope, model);
modelCtrl.$setValidity('editable', true);
modelCtrl.$setValidity('parse', true);
onSelectCallback(originalScope, {
$item: item,
$model: model,
$label: parserResult.viewMapper(originalScope, locals),
$event: evt
});
resetMatches();
//return focus to the input element if a match was selected via a mouse click event
// use timeout to avoid $rootScope:inprog error
if (scope.$eval(attrs.typeaheadFocusOnSelect) !== false) {
$timeout(function() { element[0].focus(); }, 0, false);
}
};
//bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)
element.on('keydown', function(evt) {
//typeahead is open and an "interesting" key was pressed
if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {
return;
}
/**
* if there's nothing selected (i.e. focusFirst) and enter or tab is hit
* or
* shift + tab is pressed to bring focus to the previous element
* then clear the results
*/
if (scope.activeIdx === -1 && (evt.which === 9 || evt.which === 13) || evt.which === 9 && !!evt.shiftKey) {
resetMatches();
scope.$digest();
return;
}
evt.preventDefault();
var target;
switch (evt.which) {
case 9:
case 13:
scope.$apply(function () {
if (angular.isNumber(scope.debounceUpdate) || angular.isObject(scope.debounceUpdate)) {
$$debounce(function() {
scope.select(scope.activeIdx, evt);
}, angular.isNumber(scope.debounceUpdate) ? scope.debounceUpdate : scope.debounceUpdate['default']);
} else {
scope.select(scope.activeIdx, evt);
}
});
break;
case 27:
evt.stopPropagation();
resetMatches();
originalScope.$digest();
break;
case 38:
scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1;
scope.$digest();
target = popUpEl.find('li')[scope.activeIdx];
target.parentNode.scrollTop = target.offsetTop;
break;
case 40:
scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;
scope.$digest();
target = popUpEl.find('li')[scope.activeIdx];
target.parentNode.scrollTop = target.offsetTop;
break;
}
});
element.bind('focus', function (evt) {
hasFocus = true;
if (minLength === 0 && !modelCtrl.$viewValue) {
$timeout(function() {
getMatchesAsync(modelCtrl.$viewValue, evt);
}, 0);
}
});
element.bind('blur', function(evt) {
if (isSelectOnBlur && scope.matches.length && scope.activeIdx !== -1 && !selected) {
selected = true;
scope.$apply(function() {
if (angular.isObject(scope.debounceUpdate) && angular.isNumber(scope.debounceUpdate.blur)) {
$$debounce(function() {
scope.select(scope.activeIdx, evt);
}, scope.debounceUpdate.blur);
} else {
scope.select(scope.activeIdx, evt);
}
});
}
if (!isEditable && modelCtrl.$error.editable) {
modelCtrl.$setViewValue();
// Reset validity as we are clearing
modelCtrl.$setValidity('editable', true);
modelCtrl.$setValidity('parse', true);
element.val('');
}
hasFocus = false;
selected = false;
});
// Keep reference to click handler to unbind it.
var dismissClickHandler = function(evt) {
// Issue #3973
// Firefox treats right click as a click on document
if (element[0] !== evt.target && evt.which !== 3 && scope.matches.length !== 0) {
resetMatches();
if (!$rootScope.$$phase) {
originalScope.$digest();
}
}
};
$document.on('click', dismissClickHandler);
originalScope.$on('$destroy', function() {
$document.off('click', dismissClickHandler);
if (appendToBody || appendTo) {
$popup.remove();
}
if (appendToBody) {
angular.element($window).off('resize', fireRecalculating);
$document.find('body').off('scroll', fireRecalculating);
}
// Prevent jQuery cache memory leak
popUpEl.remove();
if (showHint) {
inputsContainer.remove();
}
});
var $popup = $compile(popUpEl)(scope);
if (appendToBody) {
$document.find('body').append($popup);
} else if (appendTo) {
angular.element(appendTo).eq(0).append($popup);
} else {
element.after($popup);
}
this.init = function(_modelCtrl, _ngModelOptions) {
modelCtrl = _modelCtrl;
ngModelOptions = _ngModelOptions;
scope.debounceUpdate = modelCtrl.$options && $parse(modelCtrl.$options.debounce)(originalScope);
//plug into $parsers pipeline to open a typeahead on view changes initiated from DOM
//$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue
modelCtrl.$parsers.unshift(function(inputValue) {
hasFocus = true;
if (minLength === 0 || inputValue && inputValue.length >= minLength) {
if (waitTime > 0) {
cancelPreviousTimeout();
scheduleSearchWithTimeout(inputValue);
} else {
getMatchesAsync(inputValue);
}
} else {
isLoadingSetter(originalScope, false);
cancelPreviousTimeout();
resetMatches();
}
if (isEditable) {
return inputValue;
}
if (!inputValue) {
// Reset in case user had typed something previously.
modelCtrl.$setValidity('editable', true);
return null;
}
modelCtrl.$setValidity('editable', false);
return undefined;
});
modelCtrl.$formatters.push(function(modelValue) {
var candidateViewValue, emptyViewValue;
var locals = {};
// The validity may be set to false via $parsers (see above) if
// the model is restricted to selected values. If the model
// is set manually it is considered to be valid.
if (!isEditable) {
modelCtrl.$setValidity('editable', true);
}
if (inputFormatter) {
locals.$model = modelValue;
return inputFormatter(originalScope, locals);
}
//it might happen that we don't have enough info to properly render input value
//we need to check for this situation and simply return model value if we can't apply custom formatting
locals[parserResult.itemName] = modelValue;
candidateViewValue = parserResult.viewMapper(originalScope, locals);
locals[parserResult.itemName] = undefined;
emptyViewValue = parserResult.viewMapper(originalScope, locals);
return candidateViewValue !== emptyViewValue ? candidateViewValue : modelValue;
});
};
}])
.directive('uibTypeahead', function() {
return {
controller: 'UibTypeaheadController',
require: ['ngModel', '^?ngModelOptions', 'uibTypeahead'],
link: function(originalScope, element, attrs, ctrls) {
ctrls[2].init(ctrls[0], ctrls[1]);
}
};
})
.directive('uibTypeaheadPopup', ['$$debounce', function($$debounce) {
return {
scope: {
matches: '=',
query: '=',
active: '=',
position: '&',
moveInProgress: '=',
select: '&',
assignIsOpen: '&',
debounce: '&'
},
replace: true,
templateUrl: function(element, attrs) {
return attrs.popupTemplateUrl || 'uib/template/typeahead/typeahead-popup.html';
},
link: function(scope, element, attrs) {
scope.templateUrl = attrs.templateUrl;
scope.isOpen = function() {
var isDropdownOpen = scope.matches.length > 0;
scope.assignIsOpen({ isOpen: isDropdownOpen });
return isDropdownOpen;
};
scope.isActive = function(matchIdx) {
return scope.active === matchIdx;
};
scope.selectActive = function(matchIdx) {
scope.active = matchIdx;
};
scope.selectMatch = function(activeIdx, evt) {
var debounce = scope.debounce();
if (angular.isNumber(debounce) || angular.isObject(debounce)) {
$$debounce(function() {
scope.select({activeIdx: activeIdx, evt: evt});
}, angular.isNumber(debounce) ? debounce : debounce['default']);
} else {
scope.select({activeIdx: activeIdx, evt: evt});
}
};
}
};
}])
.directive('uibTypeaheadMatch', ['$templateRequest', '$compile', '$parse', function($templateRequest, $compile, $parse) {
return {
scope: {
index: '=',
match: '=',
query: '='
},
link: function(scope, element, attrs) {
var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'uib/template/typeahead/typeahead-match.html';
$templateRequest(tplUrl).then(function(tplContent) {
var tplEl = angular.element(tplContent.trim());
element.replaceWith(tplEl);
$compile(tplEl)(scope);
});
}
};
}])
.filter('uibTypeaheadHighlight', ['$sce', '$injector', '$log', function($sce, $injector, $log) {
var isSanitizePresent;
isSanitizePresent = $injector.has('$sanitize');
function escapeRegexp(queryToEscape) {
// Regex: capture the whole query string and replace it with the string that will be used to match
// the results, for example if the capture is "a" the result will be \a
return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
function containsHtml(matchItem) {
return /<.*>/g.test(matchItem);
}
return function(matchItem, query) {
if (!isSanitizePresent && containsHtml(matchItem)) {
$log.warn('Unsafe use of typeahead please use ngSanitize'); // Warn the user about the danger
}
matchItem = query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem; // Replaces the capture string with a the same string inside of a "strong" tag
if (!isSanitizePresent) {
matchItem = $sce.trustAsHtml(matchItem); // If $sanitize is not present we pack the string in a $sce object for the ng-bind-html directive
}
return matchItem;
};
}]);
angular.module("uib/template/accordion/accordion-group.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/accordion/accordion-group.html",
"<div class=\"panel\" ng-class=\"panelClass || 'panel-default'\">\n" +
" <div role=\"tab\" id=\"{{::headingId}}\" aria-selected=\"{{isOpen}}\" class=\"panel-heading\" ng-keypress=\"toggleOpen($event)\">\n" +
" <h4 class=\"panel-title\">\n" +
" <a role=\"button\" data-toggle=\"collapse\" href aria-expanded=\"{{isOpen}}\" aria-controls=\"{{::panelId}}\" tabindex=\"0\" class=\"accordion-toggle\" ng-click=\"toggleOpen()\" uib-accordion-transclude=\"heading\"><span uib-accordion-header ng-class=\"{'text-muted': isDisabled}\">{{heading}}</span></a>\n" +
" </h4>\n" +
" </div>\n" +
" <div id=\"{{::panelId}}\" aria-labelledby=\"{{::headingId}}\" aria-hidden=\"{{!isOpen}}\" role=\"tabpanel\" class=\"panel-collapse collapse\" uib-collapse=\"!isOpen\">\n" +
" <div class=\"panel-body\" ng-transclude></div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module("uib/template/accordion/accordion.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/accordion/accordion.html",
"<div role=\"tablist\" class=\"panel-group\" ng-transclude></div>");
}]);
angular.module("uib/template/alert/alert.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/alert/alert.html",
"<div class=\"alert\" ng-class=\"['alert-' + (type || 'warning'), closeable ? 'alert-dismissible' : null]\" role=\"alert\">\n" +
" <button ng-show=\"closeable\" type=\"button\" class=\"close\" ng-click=\"close({$event: $event})\">\n" +
" <span aria-hidden=\"true\">×</span>\n" +
" <span class=\"sr-only\">Close</span>\n" +
" </button>\n" +
" <div ng-transclude></div>\n" +
"</div>\n" +
"");
}]);
angular.module("uib/template/carousel/carousel.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/carousel/carousel.html",
"<div ng-mouseenter=\"pause()\" ng-mouseleave=\"play()\" class=\"carousel\" ng-swipe-right=\"prev()\" ng-swipe-left=\"next()\">\n" +
" <div class=\"carousel-inner\" ng-transclude></div>\n" +
" <a role=\"button\" href class=\"left carousel-control\" ng-click=\"prev()\" ng-class=\"{ disabled: isPrevDisabled() }\" ng-show=\"slides.length > 1\">\n" +
" <span aria-hidden=\"true\" class=\"glyphicon glyphicon-chevron-left\"></span>\n" +
" <span class=\"sr-only\">previous</span>\n" +
" </a>\n" +
" <a role=\"button\" href class=\"right carousel-control\" ng-click=\"next()\" ng-class=\"{ disabled: isNextDisabled() }\" ng-show=\"slides.length > 1\">\n" +
" <span aria-hidden=\"true\" class=\"glyphicon glyphicon-chevron-right\"></span>\n" +
" <span class=\"sr-only\">next</span>\n" +
" </a>\n" +
" <ol class=\"carousel-indicators\" ng-show=\"slides.length > 1\">\n" +
" <li ng-repeat=\"slide in slides | orderBy:indexOfSlide track by $index\" ng-class=\"{ active: isActive(slide) }\" ng-click=\"select(slide)\">\n" +
" <span class=\"sr-only\">slide {{ $index + 1 }} of {{ slides.length }}<span ng-if=\"isActive(slide)\">, currently active</span></span>\n" +
" </li>\n" +
" </ol>\n" +
"</div>\n" +
"");
}]);
angular.module("uib/template/carousel/slide.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/carousel/slide.html",
"<div ng-class=\"{\n" +
" 'active': active\n" +
" }\" class=\"item text-center\" ng-transclude></div>\n" +
"");
}]);
angular.module("uib/template/datepicker/datepicker.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/datepicker/datepicker.html",
"<div class=\"uib-datepicker\" ng-switch=\"datepickerMode\" role=\"application\" ng-keydown=\"keydown($event)\">\n" +
" <uib-daypicker ng-switch-when=\"day\" tabindex=\"0\"></uib-daypicker>\n" +
" <uib-monthpicker ng-switch-when=\"month\" tabindex=\"0\"></uib-monthpicker>\n" +
" <uib-yearpicker ng-switch-when=\"year\" tabindex=\"0\"></uib-yearpicker>\n" +
"</div>\n" +
"");
}]);
angular.module("uib/template/datepicker/day.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/datepicker/day.html",
"<table class=\"uib-daypicker\" role=\"grid\" aria-labelledby=\"{{::uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" +
" <thead>\n" +
" <tr>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left uib-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" +
" <th colspan=\"{{::5 + showWeeks}}\"><button id=\"{{::uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm uib-title\" ng-click=\"toggleMode()\" ng-disabled=\"datepickerMode === maxMode\" tabindex=\"-1\"><strong>{{title}}</strong></button></th>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right uib-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" +
" </tr>\n" +
" <tr>\n" +
" <th ng-if=\"showWeeks\" class=\"text-center\"></th>\n" +
" <th ng-repeat=\"label in ::labels track by $index\" class=\"text-center\"><small aria-label=\"{{::label.full}}\">{{::label.abbr}}</small></th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr class=\"uib-weeks\" ng-repeat=\"row in rows track by $index\">\n" +
" <td ng-if=\"showWeeks\" class=\"text-center h6\"><em>{{ weekNumbers[$index] }}</em></td>\n" +
" <td ng-repeat=\"dt in row\" class=\"uib-day text-center\" role=\"gridcell\"\n" +
" id=\"{{::dt.uid}}\"\n" +
" ng-class=\"::dt.customClass\">\n" +
" <button type=\"button\" class=\"btn btn-default btn-sm\"\n" +
" uib-is-class=\"\n" +
" 'btn-info' for selectedDt,\n" +
" 'active' for activeDt\n" +
" on dt\"\n" +
" ng-click=\"select(dt.date)\"\n" +
" ng-disabled=\"::dt.disabled\"\n" +
" tabindex=\"-1\"><span ng-class=\"::{'text-muted': dt.secondary, 'text-info': dt.current}\">{{::dt.label}}</span></button>\n" +
" </td>\n" +
" </tr>\n" +
" </tbody>\n" +
"</table>\n" +
"");
}]);
angular.module("uib/template/datepicker/month.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/datepicker/month.html",
"<table class=\"uib-monthpicker\" role=\"grid\" aria-labelledby=\"{{::uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" +
" <thead>\n" +
" <tr>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left uib-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" +
" <th><button id=\"{{::uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm uib-title\" ng-click=\"toggleMode()\" ng-disabled=\"datepickerMode === maxMode\" tabindex=\"-1\"><strong>{{title}}</strong></button></th>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right uib-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr class=\"uib-months\" ng-repeat=\"row in rows track by $index\">\n" +
" <td ng-repeat=\"dt in row\" class=\"uib-month text-center\" role=\"gridcell\"\n" +
" id=\"{{::dt.uid}}\"\n" +
" ng-class=\"::dt.customClass\">\n" +
" <button type=\"button\" class=\"btn btn-default\"\n" +
" uib-is-class=\"\n" +
" 'btn-info' for selectedDt,\n" +
" 'active' for activeDt\n" +
" on dt\"\n" +
" ng-click=\"select(dt.date)\"\n" +
" ng-disabled=\"::dt.disabled\"\n" +
" tabindex=\"-1\"><span ng-class=\"::{'text-info': dt.current}\">{{::dt.label}}</span></button>\n" +
" </td>\n" +
" </tr>\n" +
" </tbody>\n" +
"</table>\n" +
"");
}]);
angular.module("uib/template/datepicker/year.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/datepicker/year.html",
"<table class=\"uib-yearpicker\" role=\"grid\" aria-labelledby=\"{{::uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" +
" <thead>\n" +
" <tr>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left uib-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" +
" <th colspan=\"{{::columns - 2}}\"><button id=\"{{::uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm uib-title\" ng-click=\"toggleMode()\" ng-disabled=\"datepickerMode === maxMode\" tabindex=\"-1\"><strong>{{title}}</strong></button></th>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right uib-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr class=\"uib-years\" ng-repeat=\"row in rows track by $index\">\n" +
" <td ng-repeat=\"dt in row\" class=\"uib-year text-center\" role=\"gridcell\"\n" +
" id=\"{{::dt.uid}}\"\n" +
" ng-class=\"::dt.customClass\">\n" +
" <button type=\"button\" class=\"btn btn-default\"\n" +
" uib-is-class=\"\n" +
" 'btn-info' for selectedDt,\n" +
" 'active' for activeDt\n" +
" on dt\"\n" +
" ng-click=\"select(dt.date)\"\n" +
" ng-disabled=\"::dt.disabled\"\n" +
" tabindex=\"-1\"><span ng-class=\"::{'text-info': dt.current}\">{{::dt.label}}</span></button>\n" +
" </td>\n" +
" </tr>\n" +
" </tbody>\n" +
"</table>\n" +
"");
}]);
angular.module("uib/template/datepickerPopup/popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/datepickerPopup/popup.html",
"<div>\n" +
" <ul class=\"uib-datepicker-popup dropdown-menu uib-position-measure\" dropdown-nested ng-if=\"isOpen\" ng-keydown=\"keydown($event)\" ng-click=\"$event.stopPropagation()\">\n" +
" <li ng-transclude></li>\n" +
" <li ng-if=\"showButtonBar\" class=\"uib-button-bar\">\n" +
" <span class=\"btn-group pull-left\">\n" +
" <button type=\"button\" class=\"btn btn-sm btn-info uib-datepicker-current\" ng-click=\"select('today', $event)\" ng-disabled=\"isDisabled('today')\">{{ getText('current') }}</button>\n" +
" <button type=\"button\" class=\"btn btn-sm btn-danger uib-clear\" ng-click=\"select(null, $event)\">{{ getText('clear') }}</button>\n" +
" </span>\n" +
" <button type=\"button\" class=\"btn btn-sm btn-success pull-right uib-close\" ng-click=\"close($event)\">{{ getText('close') }}</button>\n" +
" </li>\n" +
" </ul>\n" +
"</div>\n" +
"");
}]);
angular.module("uib/template/modal/backdrop.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/modal/backdrop.html",
"<div class=\"modal-backdrop\"\n" +
" uib-modal-animation-class=\"fade\"\n" +
" modal-in-class=\"in\"\n" +
" ng-style=\"{'z-index': 1040 + (index && 1 || 0) + index*10}\"\n" +
"></div>\n" +
"");
}]);
angular.module("uib/template/modal/window.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/modal/window.html",
"<div modal-render=\"{{$isRendered}}\" tabindex=\"-1\" role=\"dialog\" class=\"modal\"\n" +
" uib-modal-animation-class=\"fade\"\n" +
" modal-in-class=\"in\"\n" +
" ng-style=\"{'z-index': 1050 + index*10, display: 'block'}\">\n" +
" <div class=\"modal-dialog {{size ? 'modal-' + size : ''}}\"><div class=\"modal-content\" uib-modal-transclude></div></div>\n" +
"</div>\n" +
"");
}]);
angular.module("uib/template/pager/pager.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/pager/pager.html",
"<ul class=\"pager\">\n" +
" <li ng-class=\"{disabled: noPrevious()||ngDisabled, previous: align}\"><a href ng-click=\"selectPage(page - 1, $event)\">{{::getText('previous')}}</a></li>\n" +
" <li ng-class=\"{disabled: noNext()||ngDisabled, next: align}\"><a href ng-click=\"selectPage(page + 1, $event)\">{{::getText('next')}}</a></li>\n" +
"</ul>\n" +
"");
}]);
angular.module("uib/template/pagination/pagination.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/pagination/pagination.html",
"<ul class=\"pagination\">\n" +
" <li ng-if=\"::boundaryLinks\" ng-class=\"{disabled: noPrevious()||ngDisabled}\" class=\"pagination-first\"><a href ng-click=\"selectPage(1, $event)\">{{::getText('first')}}</a></li>\n" +
" <li ng-if=\"::directionLinks\" ng-class=\"{disabled: noPrevious()||ngDisabled}\" class=\"pagination-prev\"><a href ng-click=\"selectPage(page - 1, $event)\">{{::getText('previous')}}</a></li>\n" +
" <li ng-repeat=\"page in pages track by $index\" ng-class=\"{active: page.active,disabled: ngDisabled&&!page.active}\" class=\"pagination-page\"><a href ng-click=\"selectPage(page.number, $event)\">{{page.text}}</a></li>\n" +
" <li ng-if=\"::directionLinks\" ng-class=\"{disabled: noNext()||ngDisabled}\" class=\"pagination-next\"><a href ng-click=\"selectPage(page + 1, $event)\">{{::getText('next')}}</a></li>\n" +
" <li ng-if=\"::boundaryLinks\" ng-class=\"{disabled: noNext()||ngDisabled}\" class=\"pagination-last\"><a href ng-click=\"selectPage(totalPages, $event)\">{{::getText('last')}}</a></li>\n" +
"</ul>\n" +
"");
}]);
angular.module("uib/template/tooltip/tooltip-html-popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/tooltip/tooltip-html-popup.html",
"<div class=\"tooltip\"\n" +
" tooltip-animation-class=\"fade\"\n" +
" uib-tooltip-classes\n" +
" ng-class=\"{ in: isOpen() }\">\n" +
" <div class=\"tooltip-arrow\"></div>\n" +
" <div class=\"tooltip-inner\" ng-bind-html=\"contentExp()\"></div>\n" +
"</div>\n" +
"");
}]);
angular.module("uib/template/tooltip/tooltip-popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/tooltip/tooltip-popup.html",
"<div class=\"tooltip\"\n" +
" tooltip-animation-class=\"fade\"\n" +
" uib-tooltip-classes\n" +
" ng-class=\"{ in: isOpen() }\">\n" +
" <div class=\"tooltip-arrow\"></div>\n" +
" <div class=\"tooltip-inner\" ng-bind=\"content\"></div>\n" +
"</div>\n" +
"");
}]);
angular.module("uib/template/tooltip/tooltip-template-popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/tooltip/tooltip-template-popup.html",
"<div class=\"tooltip\"\n" +
" tooltip-animation-class=\"fade\"\n" +
" uib-tooltip-classes\n" +
" ng-class=\"{ in: isOpen() }\">\n" +
" <div class=\"tooltip-arrow\"></div>\n" +
" <div class=\"tooltip-inner\"\n" +
" uib-tooltip-template-transclude=\"contentExp()\"\n" +
" tooltip-template-transclude-scope=\"originScope()\"></div>\n" +
"</div>\n" +
"");
}]);
angular.module("uib/template/popover/popover-html.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/popover/popover-html.html",
"<div class=\"popover\"\n" +
" tooltip-animation-class=\"fade\"\n" +
" uib-tooltip-classes\n" +
" ng-class=\"{ in: isOpen() }\">\n" +
" <div class=\"arrow\"></div>\n" +
"\n" +
" <div class=\"popover-inner\">\n" +
" <h3 class=\"popover-title\" ng-bind=\"uibTitle\" ng-if=\"uibTitle\"></h3>\n" +
" <div class=\"popover-content\" ng-bind-html=\"contentExp()\"></div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module("uib/template/popover/popover-template.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/popover/popover-template.html",
"<div class=\"popover\"\n" +
" tooltip-animation-class=\"fade\"\n" +
" uib-tooltip-classes\n" +
" ng-class=\"{ in: isOpen() }\">\n" +
" <div class=\"arrow\"></div>\n" +
"\n" +
" <div class=\"popover-inner\">\n" +
" <h3 class=\"popover-title\" ng-bind=\"uibTitle\" ng-if=\"uibTitle\"></h3>\n" +
" <div class=\"popover-content\"\n" +
" uib-tooltip-template-transclude=\"contentExp()\"\n" +
" tooltip-template-transclude-scope=\"originScope()\"></div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module("uib/template/popover/popover.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/popover/popover.html",
"<div class=\"popover\"\n" +
" tooltip-animation-class=\"fade\"\n" +
" uib-tooltip-classes\n" +
" ng-class=\"{ in: isOpen() }\">\n" +
" <div class=\"arrow\"></div>\n" +
"\n" +
" <div class=\"popover-inner\">\n" +
" <h3 class=\"popover-title\" ng-bind=\"uibTitle\" ng-if=\"uibTitle\"></h3>\n" +
" <div class=\"popover-content\" ng-bind=\"content\"></div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module("uib/template/progressbar/bar.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/progressbar/bar.html",
"<div class=\"progress-bar\" ng-class=\"type && 'progress-bar-' + type\" role=\"progressbar\" aria-valuenow=\"{{value}}\" aria-valuemin=\"0\" aria-valuemax=\"{{max}}\" ng-style=\"{width: (percent < 100 ? percent : 100) + '%'}\" aria-valuetext=\"{{percent | number:0}}%\" aria-labelledby=\"{{::title}}\" ng-transclude></div>\n" +
"");
}]);
angular.module("uib/template/progressbar/progress.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/progressbar/progress.html",
"<div class=\"progress\" ng-transclude aria-labelledby=\"{{::title}}\"></div>");
}]);
angular.module("uib/template/progressbar/progressbar.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/progressbar/progressbar.html",
"<div class=\"progress\">\n" +
" <div class=\"progress-bar\" ng-class=\"type && 'progress-bar-' + type\" role=\"progressbar\" aria-valuenow=\"{{value}}\" aria-valuemin=\"0\" aria-valuemax=\"{{max}}\" ng-style=\"{width: (percent < 100 ? percent : 100) + '%'}\" aria-valuetext=\"{{percent | number:0}}%\" aria-labelledby=\"{{::title}}\" ng-transclude></div>\n" +
"</div>\n" +
"");
}]);
angular.module("uib/template/rating/rating.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/rating/rating.html",
"<span ng-mouseleave=\"reset()\" ng-keydown=\"onKeydown($event)\" tabindex=\"0\" role=\"slider\" aria-valuemin=\"0\" aria-valuemax=\"{{range.length}}\" aria-valuenow=\"{{value}}\" aria-valuetext=\"{{title}}\">\n" +
" <span ng-repeat-start=\"r in range track by $index\" class=\"sr-only\">({{ $index < value ? '*' : ' ' }})</span>\n" +
" <i ng-repeat-end ng-mouseenter=\"enter($index + 1)\" ng-click=\"rate($index + 1)\" class=\"glyphicon\" ng-class=\"$index < value && (r.stateOn || 'glyphicon-star') || (r.stateOff || 'glyphicon-star-empty')\" ng-attr-title=\"{{r.title}}\"></i>\n" +
"</span>\n" +
"");
}]);
angular.module("uib/template/tabs/tab.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/tabs/tab.html",
"<li ng-class=\"[{active: active, disabled: disabled}, classes]\" class=\"uib-tab nav-item\">\n" +
" <a href ng-click=\"select($event)\" class=\"nav-link\" uib-tab-heading-transclude>{{heading}}</a>\n" +
"</li>\n" +
"");
}]);
angular.module("uib/template/tabs/tabset.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/tabs/tabset.html",
"<div>\n" +
" <ul class=\"nav nav-{{tabset.type || 'tabs'}}\" ng-class=\"{'nav-stacked': vertical, 'nav-justified': justified}\" ng-transclude></ul>\n" +
" <div class=\"tab-content\">\n" +
" <div class=\"tab-pane\"\n" +
" ng-repeat=\"tab in tabset.tabs\"\n" +
" ng-class=\"{active: tabset.active === tab.index}\"\n" +
" uib-tab-content-transclude=\"tab\">\n" +
" </div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module("uib/template/timepicker/timepicker.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/timepicker/timepicker.html",
"<table class=\"uib-timepicker\">\n" +
" <tbody>\n" +
" <tr class=\"text-center\" ng-show=\"::showSpinners\">\n" +
" <td class=\"uib-increment hours\"><a ng-click=\"incrementHours()\" ng-class=\"{disabled: noIncrementHours()}\" class=\"btn btn-link\" ng-disabled=\"noIncrementHours()\" tabindex=\"{{::tabindex}}\"><span class=\"glyphicon glyphicon-chevron-up\"></span></a></td>\n" +
" <td> </td>\n" +
" <td class=\"uib-increment minutes\"><a ng-click=\"incrementMinutes()\" ng-class=\"{disabled: noIncrementMinutes()}\" class=\"btn btn-link\" ng-disabled=\"noIncrementMinutes()\" tabindex=\"{{::tabindex}}\"><span class=\"glyphicon glyphicon-chevron-up\"></span></a></td>\n" +
" <td ng-show=\"showSeconds\"> </td>\n" +
" <td ng-show=\"showSeconds\" class=\"uib-increment seconds\"><a ng-click=\"incrementSeconds()\" ng-class=\"{disabled: noIncrementSeconds()}\" class=\"btn btn-link\" ng-disabled=\"noIncrementSeconds()\" tabindex=\"{{::tabindex}}\"><span class=\"glyphicon glyphicon-chevron-up\"></span></a></td>\n" +
" <td ng-show=\"showMeridian\"></td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td class=\"form-group uib-time hours\" ng-class=\"{'has-error': invalidHours}\">\n" +
" <input type=\"text\" placeholder=\"HH\" ng-model=\"hours\" ng-change=\"updateHours()\" class=\"form-control text-center\" ng-readonly=\"::readonlyInput\" maxlength=\"2\" tabindex=\"{{::tabindex}}\" ng-disabled=\"noIncrementHours()\" ng-blur=\"blur()\">\n" +
" </td>\n" +
" <td class=\"uib-separator\">:</td>\n" +
" <td class=\"form-group uib-time minutes\" ng-class=\"{'has-error': invalidMinutes}\">\n" +
" <input type=\"text\" placeholder=\"MM\" ng-model=\"minutes\" ng-change=\"updateMinutes()\" class=\"form-control text-center\" ng-readonly=\"::readonlyInput\" maxlength=\"2\" tabindex=\"{{::tabindex}}\" ng-disabled=\"noIncrementMinutes()\" ng-blur=\"blur()\">\n" +
" </td>\n" +
" <td ng-show=\"showSeconds\" class=\"uib-separator\">:</td>\n" +
" <td class=\"form-group uib-time seconds\" ng-class=\"{'has-error': invalidSeconds}\" ng-show=\"showSeconds\">\n" +
" <input type=\"text\" placeholder=\"SS\" ng-model=\"seconds\" ng-change=\"updateSeconds()\" class=\"form-control text-center\" ng-readonly=\"readonlyInput\" maxlength=\"2\" tabindex=\"{{::tabindex}}\" ng-disabled=\"noIncrementSeconds()\" ng-blur=\"blur()\">\n" +
" </td>\n" +
" <td ng-show=\"showMeridian\" class=\"uib-time am-pm\"><button type=\"button\" ng-class=\"{disabled: noToggleMeridian()}\" class=\"btn btn-default text-center\" ng-click=\"toggleMeridian()\" ng-disabled=\"noToggleMeridian()\" tabindex=\"{{::tabindex}}\">{{meridian}}</button></td>\n" +
" </tr>\n" +
" <tr class=\"text-center\" ng-show=\"::showSpinners\">\n" +
" <td class=\"uib-decrement hours\"><a ng-click=\"decrementHours()\" ng-class=\"{disabled: noDecrementHours()}\" class=\"btn btn-link\" ng-disabled=\"noDecrementHours()\" tabindex=\"{{::tabindex}}\"><span class=\"glyphicon glyphicon-chevron-down\"></span></a></td>\n" +
" <td> </td>\n" +
" <td class=\"uib-decrement minutes\"><a ng-click=\"decrementMinutes()\" ng-class=\"{disabled: noDecrementMinutes()}\" class=\"btn btn-link\" ng-disabled=\"noDecrementMinutes()\" tabindex=\"{{::tabindex}}\"><span class=\"glyphicon glyphicon-chevron-down\"></span></a></td>\n" +
" <td ng-show=\"showSeconds\"> </td>\n" +
" <td ng-show=\"showSeconds\" class=\"uib-decrement seconds\"><a ng-click=\"decrementSeconds()\" ng-class=\"{disabled: noDecrementSeconds()}\" class=\"btn btn-link\" ng-disabled=\"noDecrementSeconds()\" tabindex=\"{{::tabindex}}\"><span class=\"glyphicon glyphicon-chevron-down\"></span></a></td>\n" +
" <td ng-show=\"showMeridian\"></td>\n" +
" </tr>\n" +
" </tbody>\n" +
"</table>\n" +
"");
}]);
angular.module("uib/template/typeahead/typeahead-match.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/typeahead/typeahead-match.html",
"<a href\n" +
" tabindex=\"-1\"\n" +
" ng-bind-html=\"match.label | uibTypeaheadHighlight:query\"\n" +
" ng-attr-title=\"{{match.label}}\"></a>\n" +
"");
}]);
angular.module("uib/template/typeahead/typeahead-popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/typeahead/typeahead-popup.html",
"<ul class=\"dropdown-menu\" ng-show=\"isOpen() && !moveInProgress\" ng-style=\"{top: position().top+'px', left: position().left+'px'}\" role=\"listbox\" aria-hidden=\"{{!isOpen()}}\">\n" +
" <li ng-repeat=\"match in matches track by $index\" ng-class=\"{active: isActive($index) }\" ng-mouseenter=\"selectActive($index)\" ng-click=\"selectMatch($index, $event)\" role=\"option\" id=\"{{::match.id}}\">\n" +
" <div uib-typeahead-match index=\"$index\" match=\"match\" query=\"query\" template-url=\"templateUrl\"></div>\n" +
" </li>\n" +
"</ul>\n" +
"");
}]);
angular.module('ui.bootstrap.carousel').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibCarouselCss && angular.element(document).find('head').prepend('<style type="text/css">.ng-animate.item:not(.left):not(.right){-webkit-transition:0s ease-in-out left;transition:0s ease-in-out left}</style>'); angular.$$uibCarouselCss = true; });
angular.module('ui.bootstrap.datepicker').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibDatepickerCss && angular.element(document).find('head').prepend('<style type="text/css">.uib-datepicker .uib-title{width:100%;}.uib-day button,.uib-month button,.uib-year button{min-width:100%;}.uib-left,.uib-right{width:100%}</style>'); angular.$$uibDatepickerCss = true; });
angular.module('ui.bootstrap.position').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibPositionCss && angular.element(document).find('head').prepend('<style type="text/css">.uib-position-measure{display:block !important;visibility:hidden !important;position:absolute !important;top:-9999px !important;left:-9999px !important;}.uib-position-scrollbar-measure{position:absolute !important;top:-9999px !important;width:50px !important;height:50px !important;overflow:scroll !important;}.uib-position-body-scrollbar-measure{overflow:scroll !important;}</style>'); angular.$$uibPositionCss = true; });
angular.module('ui.bootstrap.datepickerPopup').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibDatepickerpopupCss && angular.element(document).find('head').prepend('<style type="text/css">.uib-datepicker-popup.dropdown-menu{display:block;float:none;margin:0;}.uib-button-bar{padding:10px 9px 2px;}</style>'); angular.$$uibDatepickerpopupCss = true; });
angular.module('ui.bootstrap.tooltip').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibTooltipCss && angular.element(document).find('head').prepend('<style type="text/css">[uib-tooltip-popup].tooltip.top-left > .tooltip-arrow,[uib-tooltip-popup].tooltip.top-right > .tooltip-arrow,[uib-tooltip-popup].tooltip.bottom-left > .tooltip-arrow,[uib-tooltip-popup].tooltip.bottom-right > .tooltip-arrow,[uib-tooltip-popup].tooltip.left-top > .tooltip-arrow,[uib-tooltip-popup].tooltip.left-bottom > .tooltip-arrow,[uib-tooltip-popup].tooltip.right-top > .tooltip-arrow,[uib-tooltip-popup].tooltip.right-bottom > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.top-left > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.top-right > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.bottom-left > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.bottom-right > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.left-top > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.left-bottom > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.right-top > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.right-bottom > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.top-left > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.top-right > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.bottom-left > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.bottom-right > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.left-top > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.left-bottom > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.right-top > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.right-bottom > .tooltip-arrow,[uib-popover-popup].popover.top-left > .arrow,[uib-popover-popup].popover.top-right > .arrow,[uib-popover-popup].popover.bottom-left > .arrow,[uib-popover-popup].popover.bottom-right > .arrow,[uib-popover-popup].popover.left-top > .arrow,[uib-popover-popup].popover.left-bottom > .arrow,[uib-popover-popup].popover.right-top > .arrow,[uib-popover-popup].popover.right-bottom > .arrow,[uib-popover-html-popup].popover.top-left > .arrow,[uib-popover-html-popup].popover.top-right > .arrow,[uib-popover-html-popup].popover.bottom-left > .arrow,[uib-popover-html-popup].popover.bottom-right > .arrow,[uib-popover-html-popup].popover.left-top > .arrow,[uib-popover-html-popup].popover.left-bottom > .arrow,[uib-popover-html-popup].popover.right-top > .arrow,[uib-popover-html-popup].popover.right-bottom > .arrow,[uib-popover-template-popup].popover.top-left > .arrow,[uib-popover-template-popup].popover.top-right > .arrow,[uib-popover-template-popup].popover.bottom-left > .arrow,[uib-popover-template-popup].popover.bottom-right > .arrow,[uib-popover-template-popup].popover.left-top > .arrow,[uib-popover-template-popup].popover.left-bottom > .arrow,[uib-popover-template-popup].popover.right-top > .arrow,[uib-popover-template-popup].popover.right-bottom > .arrow{top:auto;bottom:auto;left:auto;right:auto;margin:0;}[uib-popover-popup].popover,[uib-popover-html-popup].popover,[uib-popover-template-popup].popover{display:block !important;}</style>'); angular.$$uibTooltipCss = true; });
angular.module('ui.bootstrap.timepicker').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibTimepickerCss && angular.element(document).find('head').prepend('<style type="text/css">.uib-time input{width:50px;}</style>'); angular.$$uibTimepickerCss = true; });
angular.module('ui.bootstrap.typeahead').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibTypeaheadCss && angular.element(document).find('head').prepend('<style type="text/css">[uib-typeahead-popup].dropdown-menu{display:block;}</style>'); angular.$$uibTypeaheadCss = true; });/**
* ANGULAR UI BOOTSTRAP - EXTENDED TEMPLATES
* ***************************************************************************************************************************
*/
angular.module('ui.bootstrap.ext', ['ui.bootstrap'])
.config(['uibDatepickerPopupConfig', function(datepickerPopupConfig){
datepickerPopupConfig.datetimepickerPopup = 'dd.MM.yyyy HH:mm';
datepickerPopupConfig.showMeridian = false;
}])
.run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/datetimepicker/popup.html",
"<ul class=\"uib-datepicker-popup dropdown-menu\" dropdown-nested ng-if=\"isOpen\" style=\"max-height:450px;display: block\" ng-style=\"{top: position.top+'px', left: position.left+'px'}\" ng-keydown=\"keydown($event)\" ng-click=\"$event.stopPropagation()\">\n" +
" <li ng-transclude></li>\n" +
" <li style=\"text-align:center\"><div style=\"display:inline-block;\" uib-timepicker ng-model=\"date\" ng-change=\"dateSelection(date)\" readonly-input=\"$parent.$parent.readonlyInput\" show-seconds=\"$parent.$parent.showSeconds\" hour-step=\"$parent.$parent.hourStep\" minute-step=\"$parent.$parent.minuteStep\" show-meridian=\"$parent.$parent.showMeridian\" min=\"$parent.$parent.min\" max=\"$parent.$parent.max\"></div></li>\n" +
" <li ng-if=\"showButtonBar\" style=\"padding:10px 9px 2px\" class=\"uib-button-bar\">\n" +
//" <span class=\"btn-group pull-left\">\n" +
//" <button type=\"button\" class=\"btn btn-sm btn-info uib-datepicker-current\" ng-click=\"$parent.$parent.$parent.setNow()\" ng-disabled=\"isDisabled('today')\">{{ getText('current') }}</button>\n" +
//" <button type=\"button\" class=\"btn btn-sm btn-danger uib-clear\" ng-click=\"$parent.$parent.$parent.setNull()\">{{ getText('clear') }}</button>\n" +
//" </span>\n" +
" <button type=\"button\" class=\"btn btn-sm btn-success pull-right uib-close\" ng-click=\"close()\">{{ getText('close') }}</button>\n" +
" </li>\n" +
"</ul>\n" +
"");
}])
.directive('uibDatetimepickerPopup',['uibDatepickerPopupConfig', function(datepickerPopupConfig){
return {
restrict: 'A',
require: 'ngModel',
replace: true,
template: '<input uib-datepicker-popup="{{dateFormat}}" close-on-date-selection="false" datepicker-popup-template-url="uib/template/datetimepicker/popup.html">',
link: function(scope, element, attrs, ngModel){
var defaultFormat = 'yyyy-MM-dd HH:mm:ss';
// timepicker options, that can be attributes
scope.readonlyInput = attrs.readonlyInput; // (Defaults: false) : Whether user can type inside the hours & minutes input.
scope.hourStep = attrs.hourStep || 1; // (Defaults: 1) : Number of hours to increase or decrease when using a button.
scope.minuteStep = attrs.minuteStep || 1; // (Defaults: 1) : Number of minutes to increase or decrease when using a button.
scope.showMeridian = attrs.showMeridian || datepickerPopupConfig.showMeridian; // (Defaults: false) : Whether to display 12H or 24H mode.
scope.min = attrs.min; // (Defaults: undefined) : Minimum time a user can select
scope.max = attrs.max; // (Defaults: undefined) : Maximum time a user can select
scope.showSeconds = attrs.showSeconds;
scope.dateFormat = attrs.uibDatetimepickerPopup || datepickerPopupConfig.datetimepickerPopup || defaultFormat;
// hidden timepicker options
// template-url (Defaults: template/timepicker/timepicker.html) : Add the ability to override the template used on the component.
// meridians (Defaults: null) : Meridian labels based on locale. To override you must supply an array like ['AM', 'PM'].
// mousewheel (Defaults: true) : Whether user can scroll inside the hours & minutes input to increase or decrease it's values.
// arrowkeys (Defaults: true) : Whether user can use up/down arrowkeys inside the hours & minutes input to increase or decrease it's values.
// show-spinners (Defaults: true) : Shows spinner arrows above and below the inputs
}
};
}])
// FIX: openScope is undefined when dropdown is in modal
.service('uibDropdownService', ['$document', '$rootScope', function($document, $rootScope) {
var openScope = null;
this.open = function(dropdownScope, element) {
if (!openScope) {
$document.on('click', closeDropdown);
element.on('keydown', keybindFilter);
}
if (openScope && openScope !== dropdownScope) {
openScope.isOpen = false;
}
openScope = dropdownScope;
};
this.close = function(dropdownScope, element) {
if (openScope === dropdownScope) {
openScope = null;
$document.off('click', closeDropdown);
element.off('keydown', keybindFilter);
}
};
var closeDropdown = function(evt) {
// This method may still be called during the same mouse event that
// unbound this event handler. So check openScope before proceeding.
if (!openScope) { return; }
if (evt && openScope.getAutoClose() === 'disabled') { return; }
if (evt && evt.which === 3) { return; }
var toggleElement = openScope.getToggleElement();
if (evt && toggleElement && toggleElement[0].contains(evt.target)) {
return;
}
var dropdownElement = openScope.getDropdownElement();
if (evt && openScope.getAutoClose() === 'outsideClick' &&
dropdownElement && dropdownElement[0].contains(evt.target)) {
return;
}
openScope.isOpen = false;
if (!$rootScope.$$phase) {
openScope.$apply();
}
};
var keybindFilter = function(evt) {
if (evt.which === 27) {
evt.stopPropagation();
if(openScope) openScope.focusToggleElement();
closeDropdown();
} else if (openScope && openScope.isKeynavEnabled() && [38, 40].indexOf(evt.which) !== -1 && openScope.isOpen) {
evt.preventDefault();
evt.stopPropagation();
openScope.focusDropdownEntry(evt.which);
}
};
}])
// FIX: keyboard nav when dropdown menu is not in DOM, if(elems[self.selectedOption]) elems[self.selectedOption].focus();
.controller('UibDropdownController', ['$scope', '$element', '$attrs', '$parse', 'uibDropdownConfig', 'uibDropdownService', '$animate', '$uibPosition', '$document', '$compile', '$templateRequest', function($scope, $element, $attrs, $parse, dropdownConfig, uibDropdownService, $animate, $position, $document, $compile, $templateRequest) {
var self = this,
scope = $scope.$new(), // create a child scope so we are not polluting original one
templateScope,
appendToOpenClass = dropdownConfig.appendToOpenClass,
openClass = dropdownConfig.openClass,
getIsOpen,
setIsOpen = angular.noop,
toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop,
appendToBody = false,
appendTo = null,
keynavEnabled = false,
selectedOption = null,
body = $document.find('body');
$element.addClass('dropdown');
this.init = function() {
if ($attrs.isOpen) {
getIsOpen = $parse($attrs.isOpen);
setIsOpen = getIsOpen.assign;
$scope.$watch(getIsOpen, function(value) {
scope.isOpen = !!value;
});
}
if (angular.isDefined($attrs.dropdownAppendTo)) {
var appendToEl = $parse($attrs.dropdownAppendTo)(scope);
if (appendToEl) {
appendTo = angular.element(appendToEl);
}
}
appendToBody = angular.isDefined($attrs.dropdownAppendToBody);
keynavEnabled = angular.isDefined($attrs.keyboardNav);
if (appendToBody && !appendTo) {
appendTo = body;
}
if (appendTo && self.dropdownMenu) {
appendTo.append(self.dropdownMenu);
$element.on('$destroy', function handleDestroyEvent() {
self.dropdownMenu.remove();
});
}
};
this.toggle = function(open) {
scope.isOpen = arguments.length ? !!open : !scope.isOpen;
if (angular.isFunction(setIsOpen)) {
setIsOpen(scope, scope.isOpen);
}
return scope.isOpen;
};
// Allow other directives to watch status
this.isOpen = function() {
return scope.isOpen;
};
scope.getToggleElement = function() {
return self.toggleElement;
};
scope.getAutoClose = function() {
return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled'
};
scope.getElement = function() {
return $element;
};
scope.isKeynavEnabled = function() {
return keynavEnabled;
};
scope.focusDropdownEntry = function(keyCode) {
var elems = self.dropdownMenu ? //If append to body is used.
angular.element(self.dropdownMenu).find('a') :
$element.find('ul').eq(0).find('a');
switch (keyCode) {
case 40: {
if (!angular.isNumber(self.selectedOption)) {
self.selectedOption = 0;
} else {
self.selectedOption = self.selectedOption === elems.length - 1 ?
self.selectedOption :
self.selectedOption + 1;
}
break;
}
case 38: {
if (!angular.isNumber(self.selectedOption)) {
self.selectedOption = elems.length - 1;
} else {
self.selectedOption = self.selectedOption === 0 ?
0 : self.selectedOption - 1;
}
break;
}
}
if(elems[self.selectedOption]) elems[self.selectedOption].focus();
};
scope.getDropdownElement = function() {
return self.dropdownMenu;
};
scope.focusToggleElement = function() {
if (self.toggleElement) {
self.toggleElement[0].focus();
}
};
scope.$watch('isOpen', function(isOpen, wasOpen) {
if (appendTo && self.dropdownMenu) {
var pos = $position.positionElements($element, self.dropdownMenu, 'bottom-left', true),
css,
rightalign;
css = {
top: pos.top + 'px',
display: isOpen ? 'block' : 'none'
};
rightalign = self.dropdownMenu.hasClass('dropdown-menu-right');
if (!rightalign) {
css.left = pos.left + 'px';
css.right = 'auto';
} else {
css.left = 'auto';
css.right = window.innerWidth -
(pos.left + $element.prop('offsetWidth')) + 'px';
}
// Need to adjust our positioning to be relative to the appendTo container
// if it's not the body element
if (!appendToBody) {
var appendOffset = $position.offset(appendTo);
css.top = pos.top - appendOffset.top + 'px';
if (!rightalign) {
css.left = pos.left - appendOffset.left + 'px';
} else {
css.right = window.innerWidth -
(pos.left - appendOffset.left + $element.prop('offsetWidth')) + 'px';
}
}
self.dropdownMenu.css(css);
}
var openContainer = appendTo ? appendTo : $element;
var hasOpenClass = openContainer.hasClass(appendTo ? appendToOpenClass : openClass);
if (hasOpenClass === !isOpen) {
$animate[isOpen ? 'addClass' : 'removeClass'](openContainer, appendTo ? appendToOpenClass : openClass).then(function() {
if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
toggleInvoker($scope, { open: !!isOpen });
}
});
}
if (isOpen) {
if (self.dropdownMenuTemplateUrl) {
$templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) {
templateScope = scope.$new();
$compile(tplContent.trim())(templateScope, function(dropdownElement) {
var newEl = dropdownElement;
self.dropdownMenu.replaceWith(newEl);
self.dropdownMenu = newEl;
});
});
}
scope.focusToggleElement();
uibDropdownService.open(scope, $element);
} else {
if (self.dropdownMenuTemplateUrl) {
if (templateScope) {
templateScope.$destroy();
}
var newEl = angular.element('<ul class="dropdown-menu"></ul>');
self.dropdownMenu.replaceWith(newEl);
self.dropdownMenu = newEl;
}
uibDropdownService.close(scope, $element);
self.selectedOption = null;
}
if (angular.isFunction(setIsOpen)) {
setIsOpen($scope, isOpen);
}
});
}]); | 40.52943 | 32,032 | 0.556952 |
1316e838a97ed7bfda85a5129fdc0885d2ce9f27 | 11,894 | js | JavaScript | Demo/src/main/webapp/resources/js/jquery/js/plugin/jquery.fixedheadertable.min.js | rickychaos/RTSP-Client | 05705bf499369dbe2db69d468a8506a2f509fec5 | [
"Apache-2.0"
] | 12 | 2019-02-24T04:45:45.000Z | 2022-03-02T03:21:15.000Z | Demo/src/main/webapp/resources/js/jquery/js/plugin/jquery.fixedheadertable.min.js | rickychaos/RTSP-Client | 05705bf499369dbe2db69d468a8506a2f509fec5 | [
"Apache-2.0"
] | null | null | null | Demo/src/main/webapp/resources/js/jquery/js/plugin/jquery.fixedheadertable.min.js | rickychaos/RTSP-Client | 05705bf499369dbe2db69d468a8506a2f509fec5 | [
"Apache-2.0"
] | 5 | 2020-09-18T15:02:08.000Z | 2022-01-06T06:49:43.000Z | /*!
* jquery.fixedHeaderTable. The jQuery fixedHeaderTable plugin
*
* Copyright (c) 2013 Mark Malek
* http://fixedheadertable.com
*
* Licensed under MIT
* http://www.opensource.org/licenses/mit-license.php
*
* http://docs.jquery.com/Plugins/Authoring
* jQuery authoring guidelines
*
* Launch : October 2009
* Version : 1.3
* Released: May 9th, 2011
*
*
* all CSS sizing (width,height) is done in pixels (px)
*/(function (c) { c.fn.fixedHeaderTable = function (m) { var u = { width: "100%", height: "100%", themeClass: "fht-default", borderCollapse: !0, fixedColumns: 0, fixedColumn: !1, sortable: !1, autoShow: !0, footer: !1, cloneHeadToFoot: !1, autoResize: !1, create: null }, b = {}, n = { init: function (a) { b = c.extend({}, u, a); return this.each(function () { var a = c(this); h._isTable(a) ? (n.setup.apply(this, Array.prototype.slice.call(arguments, 1)), c.isFunction(b.create) && b.create.call(this)) : c.error("Invalid table mark-up") }) }, setup: function () { var a = c(this), d = a.find("thead"), e = a.find("tfoot"), g = 0, f, k, p; b.originalTable = c(this).clone(); b.includePadding = h._isPaddingIncludedWithWidth(); b.scrollbarOffset = h._getScrollbarWidth(); b.themeClassName = b.themeClass; f = -1 < b.width.search("%") ? a.parent().width() - b.scrollbarOffset : b.width - b.scrollbarOffset; a.css({ width: f }); a.closest(".fht-table-wrapper").length || (a.addClass("fht-table"), a.wrap('<div class="fht-table-wrapper"></div>')); f = a.closest(".fht-table-wrapper"); !0 == b.fixedColumn && 0 >= b.fixedColumns && (b.fixedColumns = 1); 0 < b.fixedColumns && 0 == f.find(".fht-fixed-column").length && (a.wrap('<div class="fht-fixed-body"></div>'), c('<div class="fht-fixed-column"></div>').prependTo(f), k = f.find(".fht-fixed-body")); f.css({ width: b.width, height: b.height }).addClass(b.themeClassName); a.hasClass("fht-table-init") || a.wrap('<div class="fht-tbody"></div>'); p = a.closest(".fht-tbody"); var l = h._getTableProps(a); h._setupClone(p, l.tbody); a.hasClass("fht-table-init") ? k = f.find("div.fht-thead") : (k = 0 < b.fixedColumns ? c('<div class="fht-thead"><table class="fht-table"></table></div>').prependTo(k) : c('<div class="fht-thead"><table class="fht-table"></table></div>').prependTo(f), k.find("table.fht-table").addClass(b.originalTable.attr("class")).attr("style", b.originalTable.attr("style")), d.clone().appendTo(k.find("table"))); h._setupClone(k, l.thead); a.css({ "margin-top": -k.outerHeight(!0) }); !0 == b.footer && (h._setupTableFooter(a, this, l), e.length || (e = f.find("div.fht-tfoot table")), g = e.outerHeight(!0)); d = f.height() - d.outerHeight(!0) - g - l.border; p.css({ height: d }); a.addClass("fht-table-init"); "undefined" !== typeof b.altClass && n.altRows.apply(this); 0 < b.fixedColumns && h._setupFixedColumn(a, this, l); b.autoShow || f.hide(); h._bindScroll(p, l); return this }, resize: function () { return this }, altRows: function (a) { var d = c(this); a = "undefined" !== typeof a ? a : b.altClass; d.closest(".fht-table-wrapper").find("tbody tr:odd:not(:hidden)").addClass(a) }, show: function (a, d, b) { var g = c(this), f = g.closest(".fht-table-wrapper"); if ("undefined" !== typeof a && "number" === typeof a) return f.show(a, function () { c.isFunction(d) && d.call(this) }), this; if ("undefined" !== typeof a && "string" === typeof a && "undefined" !== typeof d && "number" === typeof d) return f.show(a, d, function () { c.isFunction(b) && b.call(this) }), this; g.closest(".fht-table-wrapper").show(); c.isFunction(a) && a.call(this); return this }, hide: function (a, d, b) { var g = c(this), f = g.closest(".fht-table-wrapper"); if ("undefined" !== typeof a && "number" === typeof a) return f.hide(a, function () { c.isFunction(b) && b.call(this) }), this; if ("undefined" !== typeof a && "string" === typeof a && "undefined" !== typeof d && "number" === typeof d) return f.hide(a, d, function () { c.isFunction(b) && b.call(this) }), this; g.closest(".fht-table-wrapper").hide(); c.isFunction(b) && b.call(this); return this }, destroy: function () { var a = c(this), d = a.closest(".fht-table-wrapper"); a.insertBefore(d).removeAttr("style").append(d.find("tfoot")).removeClass("fht-table fht-table-init").find(".fht-cell").remove(); d.remove(); return this } }, h = { _isTable: function (a) { var d = a.is("table"), b = 0 < a.find("thead").length; a = 0 < a.find("tbody").length; return d && b && a ? !0 : !1 }, _bindScroll: function (a) { var d = a.closest(".fht-table-wrapper"), c = a.siblings(".fht-thead"), g = a.siblings(".fht-tfoot"); a.bind("scroll", function () { 0 < b.fixedColumns && d.find(".fht-fixed-column").find(".fht-tbody table").css({ "margin-top": -a.scrollTop() }); c.find("table").css({ "margin-left": -this.scrollLeft }); (b.footer || b.cloneHeadToFoot) && g.find("table").css({ "margin-left": -this.scrollLeft }) }) }, _fixHeightWithCss: function (a, d) { b.includePadding ? a.css({ height: a.height() + d.border }) : a.css({ height: a.parent().height() + d.border }) }, _fixWidthWithCss: function (a, d, e) { b.includePadding ? a.each(function () { c(this).css({ width: void 0 == e ? c(this).width() : e }) }) : a.each(function () { c(this).css({ width: void 0 == e ? c(this).parent().width() : e }) }) }, _setupFixedColumn: function (a, d, e) { var g = a.closest(".fht-table-wrapper"), f = g.find(".fht-fixed-body"); d = g.find(".fht-fixed-column"); var k = c('<div class="fht-thead"><table class="fht-table"><thead><tr></tr></thead></table></div>'), p = c('<div class="fht-tbody"><table class="fht-table"><tbody></tbody></table></div>'); a = c('<div class="fht-tfoot"><table class="fht-table"><tfoot><tr></tr></tfoot></table></div>'); var g = g.width(), l = f.find(".fht-tbody").height() - b.scrollbarOffset, q, t, r, s; k.find("table.fht-table").addClass(b.originalTable.attr("class")); p.find("table.fht-table").addClass(b.originalTable.attr("class")); a.find("table.fht-table").addClass(b.originalTable.attr("class")); q = f.find(".fht-thead thead tr > *:lt(" + b.fixedColumns + ")"); r = b.fixedColumns * e.border; q.each(function () { r += c(this).outerWidth(!0) }); h._fixHeightWithCss(q, e); h._fixWidthWithCss(q, e); var m = []; q.each(function () { m.push(c(this).width()) }); t = f.find("tbody tr > *:not(:nth-child(n+" + (b.fixedColumns + 1) + "))").each(function (a) { h._fixHeightWithCss(c(this), e); h._fixWidthWithCss(c(this), e, m[a % b.fixedColumns]) }); k.appendTo(d).find("tr").append(q.clone()); p.appendTo(d).css({ "margin-top": -1, height: l + e.border }); t.each(function (a) { 0 == a % b.fixedColumns && (s = c("<tr></tr>").appendTo(p.find("tbody")), b.altClass && c(this).parent().hasClass(b.altClass) && s.addClass(b.altClass)); c(this).clone().appendTo(s) }); d.css({ height: 0, width: r }); var n = d.find(".fht-tbody .fht-table").height() - d.find(".fht-tbody").height(); d.find(".fht-tbody .fht-table").bind("mousewheel", function (a, d, b, e) { if (0 != e) return a = parseInt(c(this).css("marginTop"), 10) + (0 < e ? 120 : -120), 0 < a && (a = 0), a < -n && (a = -n), c(this).css("marginTop", a), f.find(".fht-tbody").scrollTop(-a).scroll(), !1 }); f.css({ width: g }); if (!0 == b.footer || !0 == b.cloneHeadToFoot) k = f.find(".fht-tfoot tr > *:lt(" + b.fixedColumns + ")"), h._fixHeightWithCss(k, e), a.appendTo(d).find("tr").append(k.clone()), d = a.find("table").innerWidth(), a.css({ top: b.scrollbarOffset, width: d }) }, _setupTableFooter: function (a, d, e) { d = a.closest(".fht-table-wrapper"); var g = a.find("tfoot"); a = d.find("div.fht-tfoot"); a.length || (a = 0 < b.fixedColumns ? c('<div class="fht-tfoot"><table class="fht-table"></table></div>').appendTo(d.find(".fht-fixed-body")) : c('<div class="fht-tfoot"><table class="fht-table"></table></div>').appendTo(d)); a.find("table.fht-table").addClass(b.originalTable.attr("class")); switch (!0) { case !g.length && !0 == b.cloneHeadToFoot && !0 == b.footer: e = d.find("div.fht-thead"); a.empty(); e.find("table").clone().appendTo(a); break; case g.length && !1 == b.cloneHeadToFoot && !0 == b.footer: a.find("table").append(g).css({ "margin-top": -e.border }), h._setupClone(a, e.tfoot) } }, _getTableProps: function (a) { var d = { thead: {}, tbody: {}, tfoot: {}, border: 0 }, c = 1; !0 == b.borderCollapse && (c = 2); d.border = (a.find("th:first-child").outerWidth() - a.find("th:first-child").innerWidth()) / c; d.thead = h._getColumnsWidth(a.find("thead tr")); d.tfoot = h._getColumnsWidth(a.find("tfoot tr")); d.tbody = h._getColumnsWidth(a.find("tbody tr")); return d }, _getColumnsWidth: function (a) { var d = {}, b = {}, g = 0, f, k; f = h._getColumnsCount(a); for (k = 0; k < f; k++) b[k] = { rowspan: 1, colspan: 1 }; a.each(function (a) { var l = 0, k = 0; c(this).children().each(function (a) { for (var f = parseInt(c(this).attr("colspan")) || 1, h = parseInt(c(this).attr("rowspan")) || 1; 1 < b[a + k].rowspan;) b[a + k].rowspan--, k += b[a].colspan; a += l + k; l += f - 1; 1 < h && (b[a] = { rowspan: h, colspan: f }); if ("undefined" === typeof d[a] || 1 != d[a].colspan) d[a] = { width: c(this).width() + parseInt(c(this).css("border-left-width")) + parseInt(c(this).css("border-right-width")), colspan: f }, 1 == f && g++ }); if (g == f) return !1 }); return d }, _getColumnsCount: function (a) { var b = 0; a.each(function (a) { var g; c(this).children().each(function (a) { a = parseInt(c(this).attr("colspan")) || 1; g = parseInt(c(this).attr("rowspan")) || 1; b += a }); if (1 < b || 1 == g) return !1 }); return b }, _setupClone: function (a, d) { var e = a.find("thead").length ? "thead tr" : a.find("tfoot").length ? "tfoot tr" : "tbody tr", g = {}, e = a.find(e); columnsCount = h._getColumnsCount(e); for (i = 0; i < columnsCount; i++) g[i] = { rowspan: 1, colspan: 1 }; e.each(function (a) { var e = 0, h = 0; c(this).children().each(function (a) { for (var f = parseInt(c(this).attr("colspan")) || 1, m = parseInt(c(this).attr("rowspan")) || 1; 1 < g[a + h].rowspan;) g[a + h].rowspan--, h += g[a].colspan; a += e + h; e += f - 1; 1 < m && (g[a] = { rowspan: m, colspan: f }); "undefined" !== typeof d[a] && d[a].colspan == f && ((c(this).find("div.fht-cell").length ? c(this).find("div.fht-cell") : c('<div class="fht-cell"></div>').appendTo(c(this))).css({ width: parseInt(d[a].width, 10) }), c(this).closest(".fht-tbody").length || !c(this).is(":last-child") || c(this).closest(".fht-fixed-column").length || (a = Math.max((c(this).innerWidth() - c(this).width()) / 2, b.scrollbarOffset), c(this).css({ "padding-right": parseInt(c(this).css("padding-right")) + a + "px" }))) }) }) }, _isPaddingIncludedWithWidth: function () { var a = c('<table class="fht-table"><tr><td style="padding: 10px; font-size: 10px;">test</td></tr></table>'), d, e; a.addClass(b.originalTable.attr("class")); a.appendTo("body"); d = a.find("td").height(); a.find("td").css("height", a.find("tr").height()); e = a.find("td").height(); a.remove(); return d != e ? !0 : !1 }, _getScrollbarWidth: function () { var a = 0; if (!a) if (/msie/.test(navigator.userAgent.toLowerCase())) { var b = c('<textarea cols="10" rows="2"></textarea>').css({ position: "absolute", top: -1E3, left: -1E3 }).appendTo("body"), e = c('<textarea cols="10" rows="2" style="overflow: hidden;"></textarea>').css({ position: "absolute", top: -1E3, left: -1E3 }).appendTo("body"), a = b.width() - e.width() + 2; b.add(e).remove() } else b = c("<div />").css({ width: 100, height: 100, overflow: "auto", position: "absolute", top: -1E3, left: -1E3 }).prependTo("body").append("<div />").find("div").css({ width: "100%", height: 200 }), a = 100 - b.width(), b.parent().remove(); return a } }; if (n[m]) return n[m].apply(this, Array.prototype.slice.call(arguments, 1)); if ("object" !== typeof m && m) c.error('Method "' + m + '" does not exist in fixedHeaderTable plugin!'); else return n.init.apply(this, arguments) } })(jQuery);
| 566.380952 | 11,446 | 0.611569 |
131a385c78a1cdf94b9f7c8b8e879c263f22c111 | 17,887 | js | JavaScript | src/components/app/community-create/CreateCommunity.js | ZBlock-Foundation/zblock-web | d0be4aa9ed431b9ec0b75722d11f9e51c2c63dab | [
"MIT"
] | null | null | null | src/components/app/community-create/CreateCommunity.js | ZBlock-Foundation/zblock-web | d0be4aa9ed431b9ec0b75722d11f9e51c2c63dab | [
"MIT"
] | null | null | null | src/components/app/community-create/CreateCommunity.js | ZBlock-Foundation/zblock-web | d0be4aa9ed431b9ec0b75722d11f9e51c2c63dab | [
"MIT"
] | 1 | 2021-02-01T01:08:54.000Z | 2021-02-01T01:08:54.000Z | import React, { useEffect, useState } from "react";
import { withRouter } from "react-router-dom";
import {
Form,
Input,
Select,
Tag,
Button,
Steps,
Divider,
Row,
Col,
Slider,
InputNumber,
Radio,
} from "antd";
import { getAllCountries, getStatesOfCountry } from "../../../api/countriesAPI";
import uuid from "uuid-random";
import Web3 from "web3";
import { ZBlock, address } from "../../../abi/zblock";
// Defining ZBlock Smart Contract
const web3 = new Web3(Web3.givenProvider);
const zBlockContract = new web3.eth.Contract(ZBlock, address);
const communityPurposeOptions = [
{ color: "gold", value: "permaculture" },
{ color: "lime", value: "vegan" },
{ color: "green", value: "eco-friendly" },
{ color: "cyan", value: "religious" },
{ color: "orange", value: "self-sufficient" },
{ color: "purple", value: "antispecist" },
{ color: "brown", value: "political" },
];
const communityPurposeColorMap = {
permaculture: "gold",
vegan: "lime",
"eco-friendly": "green",
religious: "cyan",
"self-sufficient": "orange",
antispecist: "purple",
political: "brown",
};
const communityPurposeValueMap = {
permaculture: 0,
vegan: 1,
"eco-friendly": 2,
religious: 3,
"self-sufficient": 4,
antispecist: 5,
political: 6,
};
const layout = {
labelCol: {
span: 4,
},
wrapperCol: {
span: 16,
},
};
const CreateCommunity = (props) => {
// Community Details
const [name, setName] = useState(null);
const [description, setDescription] = useState(null);
const [website, setWebsite] = useState(null);
const [founderName, setFounderName] = useState(null);
const [founderEmail, setFounderEmail] = useState(null);
const [founderPhone, setFounderPhone] = useState(null);
// Community Type&Purpose
const [type, setType] = useState(0);
const [purposes, setPurposes] = useState([]);
// Community Location
const [countries, setCountries] = useState([]);
const [selectedCountry, setSelectedCountry] = useState(null);
const [cities, setCities] = useState([]);
const [selectedCity, setSelectedCity] = useState(null);
const [addressDetail, setAddressDetail] = useState(null);
// Community Fund Locking&Releasing
const [minLockingPeriod, setMinLockingPeriod] = useState(3);
const [maxLockingPeriod, setMaxLockingPeriod] = useState(3);
const [targetAmount, setTargetAmount] = useState(0);
const [releaseFund, setReleaseFund] = useState(0);
const [securityManager, setSecurityManager] = useState(null);
const [securityManagers, setSecurityManagers] = useState([
"0xdD5625F35B98D94Aa1A38dc170A2d06283A81830",
"0xD92F1DE3a33db86Df6b3834A742116BACE66830F",
"0xf9FA39ea483AC14cC4A83127B067EFF719c8898F",
]);
// handle form submit
const handleFormSubmit = async (values) => {
// Community Detail
const communityDetail = {
id: uuid(),
name: name,
description: description,
website: website,
founderName: founderName,
founderEmail: founderEmail,
founderPhone: founderPhone,
};
// Community Type&Purpose
const communityType = type;
const communityPurposes = purposes.map((v) => communityPurposeValueMap[v]);
// Community Address
const communityAddress = {
country: selectedCountry,
city: selectedCity,
addressDetail: addressDetail,
};
// Commuinity Fund Locking&Releasing
const communityFundLocking = {
minLockingDate: minLockingPeriod,
maxLockingDate: maxLockingPeriod,
};
const communityFundReleasing = {
targetAmount: targetAmount,
releaseFund: releaseFund,
securityManager: securityManager,
};
const accounts = await window.ethereum.enable();
const account = accounts[0];
const communityInfo = {
founder: account,
detail: communityDetail,
typeInfo: communityType,
purposes: communityPurposes,
addressInfo: communityAddress,
fundLocking: communityFundLocking,
fundReleasing: communityFundReleasing,
};
try {
const gas = await zBlockContract.methods
.newCommunity(communityInfo)
.estimateGas();
const response = await zBlockContract.methods
.newCommunity(communityInfo)
.send({ from: account, gas });
props.history.push("/app/communities");
} catch (e) {
console.log(e);
}
};
// Steps
const [stepIndex, setStepIndex] = useState(0);
useEffect(() => {
try {
setCountries(getAllCountries());
} catch (e) {
console.log(e);
}
}, []);
useEffect(() => {
if (selectedCountry === null) {
return;
}
const setCityList = async () => {
try {
const cityList = await getStatesOfCountry(selectedCountry);
setCities(cityList);
setSelectedCity(null);
} catch (e) {
console.log(e);
}
};
setCityList();
}, [selectedCountry]);
const communityPurposeTagsRender = (props) => {
const { label, value, closable, onClose } = props;
return (
<Tag
color={communityPurposeColorMap[value]}
closable={closable}
onClose={onClose}
style={{ marginRight: 3 }}
>
{label}
</Tag>
);
};
const countrySelectOptions = () => {
return countries.map((country, index) => {
return (
<Select.Option key={index} value={country.isoCode}>
{country.flag} {country.name}
</Select.Option>
);
});
};
const citySelectOptions = () => {
return cities.map((city, index) => {
return (
<Select.Option key={index} value={city.isoCode}>
{city.name}
</Select.Option>
);
});
};
return (
<React.Fragment>
<h4 style={{ marginLeft: 10 }}>Create New Community</h4>
<Divider />
<Row gutter={16}>
<Col span={2}></Col>
<Col span={20}>
<Steps current={stepIndex}>
<Steps.Step key={0} title={"Details"} />
<Steps.Step key={1} title={"Type & Purpose"} />
<Steps.Step key={2} title={"Location"} />
<Steps.Step key={3} title={"Fund Locking & Releasing"} />
<Steps.Step key={4} title={"Overview"} />
</Steps>
</Col>
<Col span={2}></Col>
</Row>
<Row gutter={16}>
<Col span={24} style={{ marginTop: 20 }}>
<Form {...layout} layout="horizontal" onFinish={handleFormSubmit}>
{stepIndex === 0 && (
<div style={{ marginTop: 20 }}>
<Row>
<Col span={12}>
<Form.Item label="Name" required={true}>
<Input
placeholder="Community Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</Form.Item>
<Form.Item label="Description" required={true}>
<Input.TextArea
placeholder="Community Description"
rows={10}
minLength={10}
maxLength={500}
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</Form.Item>
<Form.Item label="Website">
<Input
placeholder="Community Website(if available)"
value={website}
onChange={(e) => setWebsite(e.target.value)}
/>
</Form.Item>
</Col>
<Col span={12}>
<Form.Item label="Founder Name" required={true}>
<Input
placeholder="Community's Founder Name"
value={founderName}
onChange={(e) => setFounderName(e.target.value)}
/>
</Form.Item>
<Form.Item
label="Founder Email"
required={true}
rules={[{ type: "email" }]}
>
<Input
placeholder="Community's Founder Email"
value={founderEmail}
onChange={(e) => setFounderEmail(e.target.value)}
/>
</Form.Item>
<Form.Item label="Founder Phone" required={true}>
<Input
placeholder="Community's Founder Phone Number"
value={founderPhone}
onChange={(e) => setFounderPhone(e.target.value)}
/>
</Form.Item>
</Col>
</Row>
</div>
)}
{stepIndex === 1 && (
<div style={{ marginLeft: "20%" }}>
<Col span={18}>
<Form.Item label="Community Type" required={true}>
<Select
showSearch
placeholder="Select Community Type"
optionFilterProp="children"
filterOption={(input, option) =>
option.children
.toLowerCase()
.indexOf(input.toLowerCase()) >= 0
}
onChange={(value) => setType(value)}
>
<Select.Option value="0">Eco-Village</Select.Option>
<Select.Option value="1">Co-Housing</Select.Option>
<Select.Option value="2">Income Sharing</Select.Option>
<Select.Option value="3">Shared House</Select.Option>
<Select.Option value="4">Shared Flat</Select.Option>
<Select.Option value="5">Homestead</Select.Option>
</Select>
</Form.Item>
</Col>
<Col span={18}>
<Form.Item label="Community Purpose" required={true}>
<Select
mode="multiple"
showArrow={true}
placeholder={"Select Community Purpose Tags"}
tagRender={communityPurposeTagsRender}
options={communityPurposeOptions}
onChange={(value) => {
setPurposes(value);
}}
/>
</Form.Item>
</Col>
</div>
)}
{stepIndex === 2 && (
<div style={{ marginLeft: "20%" }}>
<Col span={18}>
<Form.Item label="Country" required={true}>
<Select
showSearch
placeholder="Select Country"
optionFilterProp="children"
onSelect={(country) =>
country !== selectedCountry
? setSelectedCountry(country)
: ""
}
filterOption={(input, option) =>
option.children[2]
.toLowerCase()
.indexOf(input.toLowerCase()) >= 0
}
>
{countrySelectOptions()}
</Select>
</Form.Item>
<Form.Item label="City" required={true}>
<Select
showSearch
placeholder="Select City"
optionFilterProp="children"
value={selectedCity}
onSelect={(city) => setSelectedCity(city)}
filterOption={(input, option) =>
option.children
.toLowerCase()
.indexOf(input.toLowerCase()) >= 0
}
>
{citySelectOptions()}
</Select>
</Form.Item>
<Form.Item label="Address" required={true}>
<Input.TextArea
placeholder="Address Detail"
value={addressDetail}
onChange={(e) => setAddressDetail(e.target.value)}
/>
</Form.Item>
</Col>
</div>
)}
{stepIndex === 3 && (
<div style={{ marginLeft: "30%", marginTop: 50 }}>
<Col span={22}>
<Form.Item
label="Min. Locking Period(Months)"
required={true}
>
<Slider
min={3}
max={120}
value={minLockingPeriod}
onChange={(value) => setMinLockingPeriod(value)}
/>
<InputNumber
min={3}
max={120}
style={{ margin: "0 16px" }}
value={minLockingPeriod}
onChange={(value) => setMinLockingPeriod(value)}
/>
</Form.Item>
<Form.Item
label="Max. Locking Period(Months)"
required={true}
>
<Slider
min={minLockingPeriod}
max={120}
value={maxLockingPeriod}
onChange={(value) => setMaxLockingPeriod(value)}
/>
<InputNumber
min={minLockingPeriod}
max={120}
style={{ margin: "0 16px" }}
value={maxLockingPeriod}
onChange={(value) => setMaxLockingPeriod(value)}
/>
</Form.Item>
</Col>
<Col span={22}>
<Form.Item label={"Target Amount"} required={true}>
<Input
placeholder="Amount"
type="number"
style={{ width: 350 }}
value={targetAmount}
onChange={(e) => setTargetAmount(e.target.value)}
/>
</Form.Item>
<Form.Item label="Release Fund" required={true}>
<Radio.Group
defaultValue={0}
onChange={(e) => setReleaseFund(e.target.value)}
>
<Radio.Button value={0}>100% of Target</Radio.Button>
<Radio.Button value={1}>75% of Target</Radio.Button>
<Radio.Button value={2}>50% of Target</Radio.Button>
</Radio.Group>
</Form.Item>
<Form.Item label="Security Manager" required={true}>
<Select
style={{ width: 350 }}
showSearch
placeholder="Select Security Manager"
optionFilterProp="children"
onChange={(value) => setSecurityManager(value)}
filterOption={(input, option) =>
option.children
.toLowerCase()
.indexOf(input.toLowerCase()) >= 0
}
>
{securityManagers.map((securityManager, index) => {
return (
<Select.Option key={index} value={securityManager}>
{securityManager}
</Select.Option>
);
})}
</Select>
</Form.Item>
</Col>
</div>
)}
{stepIndex === 4 && (
<div
style={{
marginLeft: "30%",
marginTop: 50,
}}
>
<h3>Congratulations!</h3>
<p>
Please, click the save button in below to create your
community in blockchain.
</p>
</div>
)}
<div
style={{
marginTop: 24,
marginRight: "16.5%",
marginBottom: 10,
float: "right",
}}
>
{stepIndex > 0 && (
<Button
style={{ margin: "0 8px" }}
onClick={() => setStepIndex(stepIndex - 1)}
>
Previous
</Button>
)}
{stepIndex < 4 && (
<Button
type="primary"
onClick={() => setStepIndex(stepIndex + 1)}
>
Next
</Button>
)}
{stepIndex === 4 && (
<Button
type={"primary"}
htmlType={"submit"}
style={{
backgroundColor: "#e67e22",
borderColor: "orange",
}}
>
Save
</Button>
)}
</div>
</Form>
</Col>
</Row>
</React.Fragment>
);
};
export default withRouter(CreateCommunity);
| 32.640511 | 80 | 0.450662 |
131a78b974b9339ec40ef07dc0e0446e7b14ca58 | 1,383 | js | JavaScript | src/utils/error.js | Nennyfills/starWars | e69d78c9365c2b21a2fadc3c7640783c3f778cd2 | [
"MIT"
] | null | null | null | src/utils/error.js | Nennyfills/starWars | e69d78c9365c2b21a2fadc3c7640783c3f778cd2 | [
"MIT"
] | null | null | null | src/utils/error.js | Nennyfills/starWars | e69d78c9365c2b21a2fadc3c7640783c3f778cd2 | [
"MIT"
] | null | null | null | export default {
email: {
required: 'Email is required!',
email: 'The input is not valid Email'
},
password: {
required: 'Password is required!'
},
fullName: {
required: 'Full Name is required!'
},
firstName: {
required: 'First Name is required!'
},
lastName: {
required: 'Last Name is required!'
},
service: {
required: 'Service is required!'
},
phoneNumber: {
required: 'Phone Number is required!'
},
feecategory: {
required: 'Fee Category is required!'
},
categoryname: {
required: 'Category Name is required!'
},
categorytype: {
required: 'Category Type is required!'
},
field: {
required: 'Field is required!'
},
servicename: {
required: 'Service Name is required!'
},
servicedefault: {
required: 'Default Fees is required!'
},
merchantCode: {
required: 'Merchant Code is required!'
},
platform: {
required: 'Platform is required!'
},
userCode: {
required: 'User Code is required!'
},
percentage: {
required: 'Percentage is required!'
},
absolute: {
required: 'Absolute is required!'
},
description: {
required: 'Description is required!'
},
productName: {
required: 'product Name is required!'
},
agent: {
required: 'Agent is required!'
},
serviceName: {
required: 'Service name is required'
}
};
| 19.757143 | 42 | 0.610268 |
131d0b2a2061b0b76ceb890417dd72f20c3d51c1 | 62,080 | js | JavaScript | games/byte_me_game.js | raphaelrk/KhanAcademy-sketches | 669dab66c9d73c552bc63efd1fa98d6d382f7491 | [
"MIT"
] | null | null | null | games/byte_me_game.js | raphaelrk/KhanAcademy-sketches | 669dab66c9d73c552bc63efd1fa98d6d382f7491 | [
"MIT"
] | null | null | null | games/byte_me_game.js | raphaelrk/KhanAcademy-sketches | 669dab66c9d73c552bc63efd1fa98d6d382f7491 | [
"MIT"
] | null | null | null | // https://www.khanacademy.org/computer-programming/byte-me-submissions/6114950898778112
/**
* Submit your program by writing it here and saving it as a spin-off
* If you already wrote your program elsewhere, comment a link to it under 'tips and thanks'
*
* © © © © © © © © © © © © © © © © © © © © © © © © © © © © © © © © © © © © © © © © © © ©
* MHS BYTE CLUB
*
* impossible quiz: http://www.theimpossiblequiz.net/impossiblequiz.html
* tinyurl to here: http://tinyurl.com/bytemegame is this
*
* example program: https://www.khanacademy.org/cs/byte/5147960346411008
*
* image to program maker: http://petercollingridge.appspot.com/pixelator
* ^ blocked on school network
* */
var currentLevel = 0;
var lastFrameLevel = 0;
var games = [];
var Opener = function() {
this.draw = function() {
background(0, 0, 0);
fill(255, 255, 255);
textFont(createFont("Tahoma"), 38);
text("Save your scene\nas a spinoff", 47, 100);
text("© MHS BYTE CLUB", 37, 377);
ellipse(mouseX, mouseY, 32, 32);
if(dist(mouseX, mouseY, 55, 364) < 4) {
fill(51, 255, 0);
ellipse(55, 364, 36, 36);
if(mouseIsPressed) {
currentLevel++;
}
}
};
};
/**
* https://www.khanacademy.org/cs/spin-off-of-byte-me-submissions/5728671417761792
* By Chris Shannon
* */
var ShannonDontTouchWhite = function() {
var pageNumber = 1;
var GREEN = color(13, 255, 0);
var WHITE = color(255, 255, 255);
this.draw = function() {
if(pageNumber === 1) {
background(255, 255, 255);
fill(30, 0, 255);
textAlign(CENTER, CENTER);
textSize(35);
noStroke();
text("To Start place mouse here", 200, 200);
rect(200, 230, 10, 110);
triangle(190, 330, 220, 330, 205, 350);
fill(255, 0, 0);
rect(100, 350, 200, 50);
}
if(mouseY > 350 && mouseX > 100 && mouseX < 300 && mouseY < 400) {
pageNumber = 2;
}
if(pageNumber === 2) {
background(255, 255, 255);
fill(255, 0, 0);
rect(100, 350, 200, 50);
fill(30, 0, 255);
textAlign(CENTER, CENTER);
textSize(35);
noStroke();
text("Don't touch the white!", 200, 300);
text("Drag mouse Here!", 200, 200);
rect(195, 112, 10, 68);
triangle(200, 102, 215, 118, 185, 118);
fill(13, 255, 0);
rect(100, 50, 200, 50);
}
if(pageNumber === 2 && get(mouseX, mouseY) === GREEN) {
pageNumber = 3;
}
if(pageNumber === 3) {
background(247, 255, 0);
fill(255, 0, 0);
textSize(35);
text("You Win!", 200, 200);
currentLevel++;
}
if(pageNumber === 2 && get(mouseX, mouseY) === WHITE) {
background(247, 255, 0);
fill(255, 0, 0);
textSize(35);
text("You Lose!", 200, 200);
currentLevel = games.length - 1;
}
};
};
/**
* https://www.khanacademy.org/cs/spin-off-of-byte-me-submissions/5032665856344064
* By Daniel Balogh
* */
var Balogh = function() {
var x = 80;
var y = 0;
var i = 1;
var r = 1;
var Green = color(0, 255, 0);
frameRate(0);
this.draw = function() {
pushMatrix();
r =floor(random(1, 16)); //random square
background(247, 231, 5);
textSize(35);
fill(0, 0, 0);
text("Solve Puzzle to Continue", 10, 365);
strokeWeight(1);
stroke(247, 231, 5);
translate(200, 125);
rotate(i); //roation
fill(random(0, 255), random(0, 55), random(0, 55)); //square 1
if(r===1){
fill(0, 255, 0);
}
rect(x,0, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 2
if(r===2){
fill(0, 255, 0);
}
rect(0, 0, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 3
if(r===3){
fill(0, 255, 0);
}
rect(x, 80, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 4
if(r===4){
fill(0, 255, 0);
}
rect(0, 80, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 5
if(r===5){
fill(0, 255, 0);
}
rect(-x, 0, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 6
if(r===6){
fill(0, 255, 0);
}
rect(-x, 160, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 7
if(r===7){
fill(0, 255, 0);
}
rect(-x-80, 0, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 8
if(r===8){
fill(0, 255, 0);
}
rect(-x, -x, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 9
if(r===9){
fill(0, 255, 0);
}
rect(x, -x, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 10
if(r===10){
fill(0, 255, 0);
}
rect(0, -x, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 11
if(r===11){
fill(0, 255, 0);
}
rect(-160, -x, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 12
if(r===12){
fill(0, 255, 0);
}
rect(-x, x, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 13
if(r===13){
fill(0, 255, 0);
}
rect(x, 160, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 14
if(r===14){
fill(0, 255, 0);
}
rect(-160, 160, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 15
if(r===15){
fill(0, 255, 0);
}
rect(-160, x, 80, 80);
fill(random(0, 255), random(0, 55), random(0, 55)); //square 16
if(r===16){
fill(0, 255, 0);
}
rect(0, 160, 80, 80);
i +=1; //more rotation
var mouseColor = get(mouseX, mouseY);
if(mouseIsPressed && get(mouseX, mouseY) === Green) {
popMatrix();
pushMatrix();
background(0, 0, 0);
translate(0, 0);
fill(255, 0, 0);
rotate(0);
textAlign(CENTER);
textSize(44);
text("Congragulations!", 200, 200);
currentLevel++;
}
popMatrix();
};
};
/**
* https://www.khanacademy.org/cs/spin-off-of-byte-me-submissions/5198126795456512
* https://www.khanacademy.org/cs/dont-touch-anything-white/4858147959472128
* By Kenny Stepney
* */
var Kenny = function() {
///Don't Touch ANYTHING White Version: v1.4
//304900 is my best!
//can you beat me?
//v0.1
//-added a menu screen
//-added one level
//-lose screen changes color
//-win screen changes color
//-touching anything white sends player to lose screen
//-made the "Don't go to fast" flashy
//v0.2
//- made it harder
//v0.3
//-added a difficult select option(current doesn't work)
//v0.4
//-cleaned up messy code
//-got the easy button working
//-cleaner transitions
//-made easymode harder
//v0.4.5
//-fixed a bug that broke the game(thanks to Nick S.)
//-got hardmode and medium mode working
//v0.5
//-*****MEDIUM MODE FINISHED!!!!!!!!
//-setup for hardmode started
//-updated message
//v0.6
//-added scoreboard feature(broken)
//-cleaned up code
//-user friendly win/lose screen
//v0.7
//-***HARDMODE FINISHED!
//v0.8
//-Multiple bug fixes
//-huge game breaking bug fixed
//v0.8.5
//-Fixed a huge cheat for hardmode
//v0.9
//- white board around win box
//v1.0 THe Offical game is out!!!!!!!!
//-fixed score system
//v1.1.1
//-score system fixed
//v1.2
//-added random words on the start screen and game select
//v1.3
//-Cleaned the entire game up
//-began easy mode 2
//-more random text
//v1.3.5
//-fixed Magor bugs cause by the score system.
//v1.3.8
//-fixed more problems caused by the score system
//v1.4
//-A huge game break bug.
/** Official Game is OUT!!!! **/
//By Kenny Stepney
//Please leave comments, suggestions, and anything else below
//NEVER CHANGE TEXT SIZE!
//Is a bit spazzy it times.
//share high scores!
//Future Updates
//-new better levels
//gets rid of the outlines of the rectangles
noStroke();
var currentScene = 1;
var s = 20;
var i = 1;
var o = 0;
var d = 0;
//declares colors, game won't work without these
var WHITE = color(255, 255, 255);
var BLACK1 = color(10, 8, 8);
var BLACK2 = color(8, 8, 8);
var BLACK3 = color(8, 4, 4);
var BLACK4 = color(15, 9, 8);
var BLACK5 = color(10, 8, 9);
var YELLOW = color(225, 255, 0);
var RED = color(255, 0, 0);
var GREEN = color(13, 255, 0);
var GREEN1 = color(13, 255, 1);
var GREEN2 = color(13, 255, 2);
var GREEN3 = color(13, 255, 3);
var BLUE = color(0, 21, 255);
var BLUE1 = color(0, 21, 254);
var BLUE2 = color(0, 21, 253);
var BLUE3 = color(0, 21, 252);
var BLUE4 = color(0, 21, 251);
var BLUE5 = color(0, 21, 249);
var GOLD = color(255, 204, 0);
var GOLD1 = color(255, 204, 1);
var GOLD2 = color(255, 204, 2);
var DARKBLUE = color(0, 166, 255);
var DARKBLUE1 = color(1, 166, 255);
//makes life much easy by declaring the size of the rectangles
var easyRectWidth = 93;
var easyRectHeight = 54;
var easyRecty = 246;
var easyRectx = 26;
var mediumRectWidth = 123;
var mediumRectHeight = 54;
var mediumRecty = 100;
var mediumRectx = 146;
var hardRectWidth = 93;
var hardRectHeight = 54;
var hardRecty = 246;
var hardRectx = 298;
//declares the base variable for your score
var score = 0;
var hiScore = 1000;
//This doesn't work yet.
var funText = ["Hello!!!", "The sunrise troop coasts!", "Thanks for playing!", "The spokesman invites the educational need!", "When can the piece frustrate a peanut forum?", "Each economy floats the fuss!", "The voice peers opposite the impressed sauce!", "Next to the caring skin grows a terminal challenge!" , "The vocabulary jams in the degenerate!", "The ice emphasizes the war!","The nostalgic profit records the sound...", "The front gathers the stone", "The periodic argument authorizes the mountain", "The night drafts the draconian fold"];
//the function for the random text displayer
var randomText = function() {
s++;
fill(random(0, 255), random(0, 255), random(0, 255));
if(s > 40) {
s -= 1;
}
if(s < 0) {
s++;
}
textSize(s);
text(funText[floor(random(0, 10))], 299, 35, 100, 100);
fill(random(0, 255), random(0, 255), random(0, 255));
if(s > 40) {
s -= 1;
}
};
//displays the screen when the user wins
var winScene = function() {
if(score > hiScore){
hiScore = score;
hiScore = hiScore.toFixed(d);
}
score = score.toFixed(d);
background(random(0, 255), random(0,255), random(0,255));
fill(255, 255, 255);
textSize(30);
text("YOU WON!!!!", 125, 109, 156, 100);
text("Score: " + score , 130, 183, 400, 100);
text("High Score: " + hiScore , 130, 243, 400, 100);
fill(0, 166, 255);
text("Play Again", 16, 305, 171, 100);
fill(255, 204, 0);
text("Return to title screen", 250, 305, 144, 100);
fill(random(0, 255), random(0, 255), random(0, 255));
textSize(10);
text("Click to go back to difficult selection(resets score when you hit title screen)", 124, 41, 250, 100);
if(currentScene === 3){
textSize(30);
fill(255, 204, 2);
text("Continue", 250, 75, 300, 100);
}
textSize(20);
fill(255, 204, 1);
text("Reset High Score", 1, 75, 171, 100);
currentLevel++;
};
//Gives the user a little instruction on how to play
var startScene1 = function() {
score = 0;
background(5, 5, 5);
fill(255, 255, 255);
textSize(30);
text("Don't Touch ANYTHING White!", 43, 200, 404, 100);
text("Click to Start!", 120, 121, 200, 150);
fill(random(0, 255), random(0, 255), random(0, 255));
textSize(10);
textSize(s);
text(funText[floor(random(0, funText.length + 1))], 255, 35, 150, 100);
text(funText[floor(random(0, funText.length + 1))], 20, 35, 150, 100);
fill(random(0, 255), random(0, 255), random(0, 255));
text("The Game thats touch sensitive!", 152, 320, 200, 100);
textSize(5);
fill(255, 255, 255);
text("v8.5 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 100);
textSize(20);
// text("If it freezes or the your score doesn't show up restart, until I get this fixed", 133, 277, 199, 100);
};
//variable for the difficulty selection
var gamemodeSelect = function() {
background(5, 4, 4);
fill(255, 0, 0);
textSize(30);
rect(easyRectx, easyRecty, easyRectWidth, easyRectHeight);
fill(254, 255, 255);
text("Easy", easyRectx + 13, easyRecty + 13, 100, 100);
fill(13, 255, 0);
rect(mediumRectx, mediumRecty, mediumRectWidth, mediumRectHeight);
fill(254, 255, 255);
text("Medium", mediumRectx + 8, mediumRecty + 15, 100, 100);
fill(0, 21, 255);
rect(hardRectx, hardRecty, hardRectWidth, hardRectHeight);
fill(254, 255, 255);
text("Hard", hardRectx + 15, hardRecty + 15, 100, 100);
fill(227, 0, 38);
textSize(20);
text("Touch, don't Click, VERY SENSITIVE!", 50, 320, 347, 100);
textSize(s);
text(funText[floor(random(0, 10))], 255, 35, 150, 100);
text(funText[floor(random(0, 10))], 20, 35, 150, 100);
};
//displays the "losing scene"
var loseScene = function() {
score *= 0.50;
score = score;
if(score > hiScore){
hiScore = score;
hiScore = hiScore;
}
background(random(0, 255), random(0,255), random(0,255));
fill(8, 4, 4);
textSize(30);
text("YOU LOSE!!!!", 125, 139, 196, 100);
text("Score: " + score , 130, 183, 400, 100);
text("High Score: " + hiScore , 130, 233, 400, 100);
fill(0, 166, 255);
text("Play Again", 16, 305, 171, 100);
fill(255, 204, 0);
text("Return to title screen", 250, 305, 144, 100);
fill(random(0, 255), random(0, 255), random(0, 255));
textSize(10);
text("Click to go back to difficult selection(resets score when you hit title screen)", 124, 41, 250, 100);
textSize(20);
fill(255, 204, 1);
text("Reset High Score", 1, 75, 171, 100);
hiScore = 1000;
};
//setup for the easy mode difficulty
var easyModeScene = function() {
background(237, 5, 51);
fill(255, 255, 255);
rect(0, 40, 400, 45);
fill(10, 8, 8);
rect(200, 250, 50, 150);
fill(8, 8, 8);
rect(200, 200, 125, 50);
fill(15, 9, 9);
rect(275, 0, 50, 250);
fill(225, 255, 0);
rect(0, 0, 400, 45);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
fill(0, 85, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
text("Start here --->", 103, 353, 100, 100);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 100);
};
//Displays the first "Scene" of the easy level
var easyScene = function() {
background(255, 255, 255);
fill(255, 255, 255);
rect(0, 40, 400, 45);
fill(10, 8, 8);
rect(200, 250, 50, 150);
fill(8, 8, 8);
rect(200, 200, 125, 50);
fill(15, 9, 9);
rect(275, 0, 50, 250);
fill(225, 255, 0);
rect(0, 0, 400, 45);
fill(0, 85, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
text("Start here --->", 103, 353, 100, 100);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 100);
};
//changes the easy scene
var easyScene2 = function() {
background(255, 255, 255);
fill(10, 8, 8);
rect(200, 250, 50, 150);
fill(8, 8, 8);
rect(125, 200, 125, 50);
fill(8, 4, 4);
rect(125, 0, 50, 250);
fill(225, 255, 0);
rect(0, 0, 400, 45);
fill(255, 255, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
fill(random(0, 255), random(0, 255), random(0, 255));
textSize(30);
text("Don't Go To Fast!!!", 300, 200, 100, 100);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 100);
};
//The final easy "scene"
var easyScene3 = function() {
background(255, 255, 255);
fill(10, 8, 8);
rect(200, 250, 50, 150);
fill(8, 8, 8);
rect(125, 200, 125, 50);
fill(8, 4, 4);
rect(125, 0, 50, 100);
rect(125, 75, 100, 50);
rect(175, 125, 50, 125);
fill(225, 255, 0);
rect(0, 0, 400, 45);
fill(255, 255, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
fill(random(0, 255), random(0, 255), random(0, 255));
textSize(30);
text("Don't Go To Fast!!!", 300, 200, 100, 100);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
textSize(5);
text("v0.1 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 100);
};
var easy2Scene = function() {
background(237, 5, 51);
fill(255, 255, 255);
rect(0, 40, 400, 45);
fill(10, 8, 9);
rect(200, 1, 50, 224);
rect(1, 348, 255, 50);
fill(15, 9, 8);
rect(196, 200, 100, 50);
fill(15, 9, 9);
rect(151, 200, 50, 250);
fill(225, 255, 0);
rect(0, 0, 400, 45);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
fill(0, 85, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
text("Start here <---", 291, 353, 100, 100);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 100);
};
var easy2Scene1 = function() {
background(255, 255, 255);
fill(255, 255, 255);
rect(0, 40, 400, 45);
fill(10, 8, 9);
rect(200, 250, 50, 150);
fill(15, 9, 8);
rect(75, 200, 289, 50);
fill(15, 9, 9);
rect(124, 200, 100, 50);
rect(43, 150, 50, 250);
fill(225, 255, 0);
rect(0, 0, 400, 45);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
fill(0, 85, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 100);
};
var easy2Scene2 = function() {
pushMatrix();
translate(425, -1);
rotate(90);
background(255, 255, 255);
fill(255, 255, 255);
rect(0, 40, 400, 45);
fill(10, 8, 9);
rect(200, 205, 50, 166);
rect(75, 156, 255, 50);
fill(15, 9, 9);
rect(283, 156, 100, 50);
fill(15, 9, 8);
rect(43, 114, 50, 262);
fill(225, 255, 0);
rect(0, 0, 400, 45);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
fill(0, 85, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 306, 100);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 415, 200, 100);
popMatrix();
};
var easy2Scene3 = function() {
};
//basically what i said for easy except for medium and hard
var mediumModeScene = function() {
background(237, 5, 51);
fill(255, 255, 255);
rect(0, 40, 430, 45);
fill(13, 255, 0);
rect(200, 250, 35, 150);
fill(13, 255, 1);
rect(200, 229, 125, 32);
fill(13, 255, 2);
rect(290, 0, 35, 261);
fill(13, 255, 3);
rect(200, 320, -153, 35);
fill(225, 255, 0);
rect(0, 0, 439, 45);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
fill(20, 15, 15);
text("Start here --->", 103, 360, 100, 100);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 100);
};
var mediumScene2 = function() {
background(255, 255, 255);
fill(255, 255, 255);
rect(0, 43, 430, 45);
fill(13, 255, 0);
rect(200, 262, 35, 150);
fill(13, 255, 1);
rect(200, 230, 125, 32);
fill(13, 255, 2);
rect(290, 1, 35, 250);
fill(13, 255, 3);
rect(200, 320, -153, 35);
fill(225, 255, 0);
rect(0, 0, 439, 45);
fill(255, 255, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
text("Start here --->", 103, 360, 100, 100);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 100);
};
var mediumScene3 = function() {
background(255, 255, 255);
fill(255, 255, 255);
rect(0, 43, 430, 45);
fill(13, 255, 0);
rect(200, 262, 35, 150);
fill(13, 255, 1);
rect(200, 230, 125, 32);
fill(13, 255, 2);
rect(92, 1, 42, 350);
fill(13, 255, 3);
rect(200, 230, -153, 35);
fill(225, 255, 0);
rect(0, 0, 497, 45);
fill(255, 255, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
text("Start here --->", 103, 360, 100, 100);
fill(random(0, 255), random(0, 255), random(0, 255));
text("TIP: Go down!", 10, 286, 100, 100);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 100);
};
var mediumScene4 = function() {
background(255, 255, 255);
fill(255, 255, 255);
rect(0, 43, 430, 45);
fill(13, 255, 0);
rect(200, 262, 35, 150);
fill(13, 255, 1);
rect(200, 230, 125, 32);
fill(0, 255, 17);
rect(86, 199, 102, 42);
rect(146, 150, 42, 90);
rect(86, 109, 102, 42);
rect(86, 45, 42, 90);
rect(86, 233, 42, 90);
fill(13, 255, 3);
rect(200, 323, -153, 35);
fill(225, 255, 0);
rect(0, 0, 497, 45);
fill(255, 255, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
text("Start here --->", 103, 360, 100, 100);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 100);
};
var hardModeScene = function() {
background(237, 5, 51);
fill(255, 255, 255);
rect(0, 44, 430, 225);
fill(0, 21, 254);
rect(200, 251, 20, 150);
fill(0, 21, 252);
rect(188, 213, 120, 20);
fill(0, 21, 253);
rect(86, 213, 102, 20);
rect(240, 123, 20, 90);
rect(179, 115, 81, 20);
rect(179, 45,20, 90);
rect(86, 233, 20, 102);
fill(0, 21, 254);
rect(200, 323, -153, 20);
fill(0, 21, 249);
rect(260, 115, -40, 20);
fill(225, 255, 0);
rect(0, 0, 497, 45);
fill(255, 255, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
fill(22, 102, 222);
text("Start here --->", 103, 360, 100, 100);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 100);
};
var hardMode1 = function() {
background(255, 255, 255);
fill(255, 255, 255);
rect(0, 44, 430, 45);
fill(0, 21, 254);
rect(200, 251, 20, 150);
fill(0, 21, 252);
rect(188, 213, 120, 20);
fill(0, 21, 250);
rect(86, 213, 102, 20);
rect(240, 123, 20, 90);
rect(179, 115, 81, 20);
rect(179, 45,20, 90);
rect(200, 335, -153, 20);
fill(0, 21, 253);
rect(86, 233, 20, 122);
fill(0, 21, 249);
rect(260, 115, -40, 20);
fill(225, 255, 0);
rect(0, 0, 497, 45);
fill(255, 255, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
fill(22, 102, 222);
text("Start here --->", 103, 360, 100, 100);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 100);
};
var hardMode2 = function() {
background(255, 255, 255);
fill(255, 255, 255);
rect(0, 44, 430, 45);
fill(0, 21, 250);
rect(200, 352, 20, 150);
fill(0, 21, 252);
rect(188, 213, 120, 20);
rect(288, 213, 20, 20);
fill(0, 21, 250);
rect(86, 213, 102, 20);
rect(240, 123, 20, 90);
rect(179, 115, 81, 20);
rect(179, 45,20, 90);
rect(200, 335, -154, 20);
rect(200, 335, 103, 20);
fill(0, 21, 253);
rect(288, 233, 20, 122);
fill(0, 21, 249);
rect(260, 115, -40, 20);
fill(0, 21, 251);
rect(200, 258, 20, 78);
fill(225, 255, 0);
rect(0, 0, 497, 45);
fill(255, 255, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
fill(22, 102, 222);
text("Start here --->", 103, 360, 100, 100);
fill(random(0, 255), random(0, 255), random(0, 255));
text("Things just got MUCH harder!", 53, 118, 100, 311);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 210);
};
var hardMode3 = function() {
background(255, 255, 255);
fill(255, 255, 255);
rect(0, 44, 430, 45);
fill(0, 21, 254);
rect(200, 251, 20, 150);
fill(0, 21, 252);
rect(188, 213, 73, 20);
rect(288, 213, 20, 20);
fill(0, 21, 250);
rect(86, 213, 102, 20);
rect(240, 123, 20, 90);
rect(179, 115, 81, 20);
rect(179, 45,20, 90);
rect(200, 335, -154, 20);
rect(200, 335, 103, 20);
fill(0, 21, 253);
rect(288, 233, 20, 122);
fill(0, 21, 249);
rect(260, 115, -40, 20);
fill(0, 21, 251);
rect(200, 255, 20, 100);
fill(225, 255, 0);
rect(0, 0, 497, 45);
fill(255, 255, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
fill(22, 102, 222);
text("Start here --->", 103, 360, 100, 100);
fill(random(0, 255), random(0, 255), random(0, 255));
text("NOPE!", 53, 118, 100, 311);
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 210);
};
var hardMode4 = function() {
background(255, 255, 255);
fill(255, 255, 255);
rect(0, 44, 430, 45);
fill(0, 21, 254);
rect(200, 342, 20, 218);
fill(0, 21, 252);
rect(188, 213, 73, 20);
rect(288, 213, 20, 20);
fill(0, 21, 250);
rect(86, 213, 102, 20);
rect(240, 123, 20, 90);
rect(179, 115, 81, 20);
rect(179, 45,20, 90);
rect(200, 335, -154, 20);
rect(200, 335, 103, 20);
fill(0, 21, 253);
rect(288, 233, 20, 122);
fill(0, 21, 249);
rect(260, 115, -40, 20);
fill(0, 21, 251);
rect(200, 223, 20, 133);
fill(225, 255, 0);
rect(0, 0, 497, 45);
fill(255, 255, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
fill(22, 102, 222);
text("Start here --->", 103, 360, 100, 100);
fill(random(0, 255), random(0, 255), random(0, 255));
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 210);
};
var hardMode5 = function() {
background(255, 255, 255);
fill(255, 255, 255);
rect(0, 44, 430, 45);
fill(0, 21, 254);
rect(200, 342, 20, 218);
fill(0, 21, 252);
rect(188, 213, 73, 20);
rect(288, 213, 20, 20);
fill(0, 21, 249);
rect(240, 117, 20, 20);
fill(0, 21, 250);
rect(86, 213, 102, 20);
rect(114, 123, 20, 90);
rect(240, 123, 20, 90);
rect(114, 115, 81, 20);
rect(179, 45,20, 90);
rect(200, 335, -154, 20);
rect(200, 335, 103, 20);
fill(0, 21, 253);
rect(288, 233, 20, 122);
fill(0, 21, 249);
rect(260, 115, -40, 20);
fill(0, 21, 251);
rect(200, 223, 20, 133);
fill(225, 255, 0);
rect(0, 0, 497, 45);
fill(255, 255, 255);
textSize(20);
text("Drag Your Mouse Here to Win", 80, 20, 300, 100);
fill(22, 102, 222);
text("Start here --->", 103, 360, 100, 100);
fill(random(0, 255), random(0, 255), random(0, 255));
fill(255, 255, 255);
rect(-57, -45, 100, 100);
rect(366, -46, 100, 100);
rect(0, -34, 400, 45);
textSize(5);
text("v0.4 Don't Touch Anything White Copyright Kenny Stepney", 152, 390, 200, 210);
};
//displays first scene
if(currentScene === 1) {
startScene1();
}
//Changes Scenes
this.mouseClicked = function() {
currentScene = 2;
if(currentScene === 2) {
gamemodeSelect();
}
};
//gets the game working like it should
this.draw = function() {
if(get(mouseX, mouseY) === RED) {
easyModeScene();
currentScene = 3;
fill(255, 255, 254);
text("Easy", 50, 45, 100, 100);
}
if(get(mouseX, mouseY) === GREEN) {
mediumModeScene();
currentScene = 4;
fill(255, 255, 254);
}
if(get(mouseX, mouseY) === BLUE) {
hardModeScene();
currentScene = 5;
fill(255, 255, 254);
}
if(get(mouseX, mouseY) === WHITE) {
score /= 2;
loseScene();
}
if(get(mouseX, mouseY) === YELLOW) {
winScene();
score *= 2;
}
if(get(mouseX, mouseY) === BLACK1) {
easyScene();
score += 20;
}
if(get(mouseX, mouseY) === BLACK2){
easyScene2();
score += 35;
}
if(get(mouseX, mouseY) === BLACK3) {
easyScene3();
score += 50;
}
if(get(mouseX, mouseY) === BLACK4) {
easy2Scene2();
score += 50;
}
if(get(mouseX, mouseY) === BLACK5) {
easy2Scene1();
score += 75;
}
if(get(mouseX, mouseY) === GREEN) {
mediumScene2();
score += 50;
}
if(get(mouseX, mouseY) === GREEN1) {
mediumScene3();
score += 75;
}
if(get(mouseX, mouseY) === GREEN2) {
mediumScene4();
score += 100;
}
if(get(mouseX, mouseY) === GOLD) {
startScene1();
score = 0;
}
if(get(mouseX, mouseY) === BLUE) {
hardModeScene();
score += 80;
}
if(get(mouseX, mouseY) === BLUE1) {
hardMode1();
score += 100;
}
if(get(mouseX, mouseY) === BLUE2) {
hardMode2();
score += 150;
}
if(get(mouseX, mouseY) === BLUE3) {
hardMode3();
score += 200;
}
if(get(mouseX, mouseY) === BLUE4) {
hardMode4();
score += 300;
}
if(get(mouseX, mouseY) === BLUE5) {
hardMode5();
score += 600;
}
if(get(mouseX, mouseY) === GOLD1) {
startScene1();
hiScore = 1000;
}
if(get(mouseX, mouseY) === GOLD2) {
easy2Scene();
currentScene = 6;
}
if(get(mouseX, mouseY) === DARKBLUE) {
if(currentScene === 3) {
easyModeScene();
}
if(currentScene === 4) {
mediumModeScene();
}
if(currentScene === 5) {
hardModeScene();
}
if(currentScene === 6) {
easy2Scene();
}
}
frameRate(60);
};
currentScene = 1;
};
/**
* https://www.khanacademy.org/cs/spin-off-of-byte-me-submissions/6630628462428160
* By Chris Shannon
* */
var ShannonMovingButton = function() {
var GREEN = color(50, 255, 0);
var greenButtonRow = floor(random(1, 8));
var greenButtonCol = floor(random(1, 8));
var greenButtonY = 50 * greenButtonRow;
var greenButtonX = 50 * greenButtonCol;
this.draw = function() {
background(255, 0, 0);
fill(0, 0, 0);
textSize(20);
text("Click the green button!", 89, 25);
for(var x = 50; x < 400; x += 50) {
fill(38, 0, 255);
noStroke();
for(var y = 50; y < 400; y += 50){
noStroke();
ellipse(x, y, 25, 25);
}
}
if(frameCount % 32 === 0) {
greenButtonRow = floor(random(1, 8));
greenButtonCol = floor(random(1, 8));
greenButtonY = 50 * greenButtonRow;
greenButtonX = 50 * greenButtonCol;
}
fill(50, 255, 0);
ellipse(greenButtonX, greenButtonY, 25, 25);
if(mouseIsPressed && get(mouseX, mouseY) === GREEN) {
currentLevel++;
}
};
};
/**
* https://www.khanacademy.org/cs/click-the-circle/4691148637732864
* By Douglas Alberts
* */
var Alberts = function() {
var a = 113;
this.draw = function() {
background(255, 255, 255);
ellipse(mouseX, mouseY, 20, 20);
textSize(37);
fill(0, 0, 0);
text("Click the Circle", 74,200);
ellipse(a,174,3,3);
};
this.mouseClicked = function() {
if(dist(mouseX, mouseY, 113, 174) < 5) {
// go on
// println("woo");
background(255, 255, 255);
text("WOO", 150, 200);
currentLevel++;
}
};
};
/**
* https://www.khanacademy.org/cs/trial-panel/5984925857873920
* By Mr. Matt Farmer
* */
var Farmer = function() {
var clock = 1000;
this.draw = function() {
background(255, 255, 255);
clock--;
if(clock < 1) {
background(3, 255, 11);
textAlign(CENTER,CENTER);
textSize(16);
fill(255,255,255);
text("Congratulations all puppies have been given hugs in your honor", 97, 300,200,100);
currentLevel++;
}
//periodic messages
if(clock < 800 && 600 < clock){
textSize(16);
text("Seriously, like, don't even joke, man.", 200, 350);
}
if(clock < 500 && 250 < clock){
textSize(16);
text("Whew, that was close!", 200, 350);
text("Really thought you were gonna push it...",200,375);
}
if(clock === 182){
textSize(16);
text("PUSH IT!", 200, 350);
}
if(clock === 102){
textSize(16);
text("WAIT, DON'T!", 200, 350);
}
textSize(24);
fill(0, 0, 0);
text(clock,200,300);
//red button
fill(222, 0, 0);
ellipse(200,200,80,80);
fill(255, 255, 255);
textSize(12);
text("PUSH ME",200,200);
//blue botton
fill(0, 255, 255);
ellipse(120,200,30,30);
//yellowbutton
fill(255, 255, 0);
ellipse(280,200,30,30);
fill(0,0,0);
textSize(16);
textAlign(CENTER,CENTER);
text("Whatever you do, don't touch",200,20);
textSize(55);
fill(222, 0, 0);
text("the red button!",200, 70);
var mouseColor = get(mouseX,mouseY);
var dude = getImage("avatars/old-spice-man");
//pushing the blue button
if(mouseColor === color(0,255,255)&& mouseIsPressed) {
image(dude,100,400*cos(clock));
fill(6, 179, 6);
textAlign(CENTER,CENTER);
text("Whoa!",200,400*cos(clock)+50);
}
//pushing the yellow button
var i = 0;
var noiseScale = 0.02;
if(mouseColor === color(255, 255, 0)&& mouseIsPressed){
translate(mouseX,mouseY);
rotate(8*clock);
fill(random(0,255),random(0,255),random(255));
text("Party!",50,50);
text("Party!",-50,-50);
resetMatrix();
if(noise(frameCount)>0.09){
text("dance!!",random(0,350),random(0,350));
text("daNCE!",random(0,350),random(0,350));
text("DANCE!",random(0,350),random(0,350));
text("dAnCe!",random(0,350),random(0,350));
i++;
}
}
//pusing the red button!
if (mouseColor === color(222,0,0)){
background(201, 4, 4);
textSize(20);
fill(252, 252, 252);
text("OH NO!!! You've touched the button!", 200,325);
fill(0, 0, 0);
textSize(12);
text("A puppy has been kicked in your honor.",200,350);
currentLevel = games.length - 1;
}
};
};
/**
* https://www.khanacademy.org/cs/spin-off-of-byte-me-submissions/6371603346882560
* By Chris Shannon
* */
var ShannonRedButton = function() {
var GREEN = color(50, 255, 0);
var RED = color(255, 0, 0);
noStroke();
fill(RED);
ellipse(200, 200, 75, 75);//middle button
fill(GREEN);
ellipse(90, 200, 75, 75);//left button
fill(GREEN);
ellipse(310, 200, 75, 75);//right button
this.draw = function() {
var buttonX1 = 112;
var buttonY1 = 2;
//background(255, 255, 255);
fill(255, 0, 0);
noStroke();
textAlign(CENTER, CENTER);
textSize(25);
text("Click the Red Button", 200, 10);
text("BUT NOT THE GREEN ONE", 200, 30);
ellipse(buttonX1, buttonY1, 2.5, 2.5);
if(mouseY > 100 && mouseX > 100 && mouseX < 300 && get(mouseX, mouseY) === RED) {
fill(GREEN);
ellipse(200, 200, 75, 75);//middle button
fill(RED);
ellipse(90, 200, 75, 75);//left button
fill(RED);
ellipse(310, 200, 75, 75);//right button
}
if(mouseY > 100 && get(mouseX, mouseY) === RED) {
fill(RED);
ellipse(200, 200, 75, 75);//middle button
fill(GREEN);
ellipse(90, 200, 75, 75);//left button
fill(GREEN);
ellipse(310, 200, 75, 75);//right button
}
if(mouseIsPressed && get(mouseX, mouseY) === GREEN) {
background(107, 6, 122);
textAlign(CENTER, CENTER);
textSize(50);
text("You Lose!", 200, 200);
currentLevel = games.length - 1;
}
if(mouseIsPressed && mouseX > buttonX1-3 && mouseX < buttonX1+3.5 && mouseY > buttonY1-3 && mouseY < buttonY1+3.5) {
background(107, 6, 122);
textAlign(CENTER, CENTER);
textSize(50);
text("You Win!", 200, 200);
currentLevel++;
}
};
};
/**
* https://www.khanacademy.org/cs/byte/5147960346411008
* By Raphael Rouvinov-Kats
* */
var Rouvinov = function() {
/**
* MHS impossible quiz level
*
* By Raphael Rouvinv-Kats
* */
var signum = function(num) {
return abs(num)/num;
};
var Button = function(x, y, w, h, text,
buttonColor, textColor) {
this.x = x;
this.y = y;
this.w = w; // width
this.h = h; // height
this.text = text;
this.buttonColor = buttonColor;
this.textColor = textColor;
};
Button.prototype.draw = function() {
// set rect settings
stroke(0, 0, 0, 50);
strokeWeight(4);
var r = red(this.buttonColor);
var g = green(this.buttonColor);
var b = blue(this.buttonColor);
var dC = 0; // change in color
if(this.hoveredOver()) {
dC = 10;
if(mouseIsPressed) { dC = 20; }
}
// draw rect
fill(r-dC - 30, g-dC - 30, b-dC - 30);
rect(this.x, this.y, this.w, this.h, 8); // shadowy rect
noStroke();
fill(r-dC, g-dC, b-dC);
var pad = 2;
rect(this.x + pad, this.y + pad, this.w - pad*2, this.h - pad*2, 8); // foreground rect
// set text settings
fill(this.textColor);
var text_size = this.w / this.text.length;
textFont(createFont("sans-serif"), 24);
textSize(text_size);
// draw text
text(this.text,
this.x + this.w/2 - this.text.length*text_size/3,
this.y + this.h/2 + text_size / 3);
};
Button.prototype.hoveredOver = function() {
if(mouseX > this.x && mouseX < this.x + this.w &&
mouseY > this.y && mouseY < this.y + this.h) {
return true;
}
return false;
};
Button.prototype.moveAwayFromMouse = function() {
var dx= 0, dy = 0;
var x = this.x + this.w / 2;
var y = this.y + this.h / 2;
var xDiff = x - mouseX;
var yDiff = y - mouseY;
if(xDiff === 0) {
xDiff = 0.1;
}
var ang = atan2(xDiff, yDiff);
dx = 30*cos(ang);
dy = 30*sin(ang);
dx = abs(dx) * signum(xDiff);
dy = abs(dy) * signum(yDiff);
// if in clicking distance, move fast towards mouse
if(dist(x, y, mouseX, mouseY) < dist(0, 0, this.w/2, this.h/2)) {
dx = -signum(dx)*this.w;
dy = -signum(dy)*this.h;
}
this.x += dx;
this.y += dy;
this.x = constrain(this.x, 5, width - this.w -5);
this.y = constrain(this.y, 5, height - this.h - 5);
};
var unfollowButton = new Button(266, 353, 134, 47, "UNFOLLOW",
color(179, 93, 179), color(255, 255, 255));
mouseX = 0;
mouseY = 0;
this.draw = function() {
fill(250, 250, 250, 100);
noStroke();
rect(0, 0, width, height);
stroke(0, 0, 0);
fill(0, 0, 0);
for(var i = 0; i < 5; i++) {
fill(255, 0, 0, 100);
var txt = "#mundypride";
if(random(0, 1) < 0.1) {
txt = "1:1";
}
text(txt, random(-400, 400), random(0, 500));
}
// move and draw unfollow button
unfollowButton.moveAwayFromMouse();
unfollowButton.draw();
// principal bg
fill(0, 48, 191, 50);
rect(0, 0, width, 63);
// @MHS_Principal
fill(204, 0, 0);
textFont(createFont("Tahoma"), 54);
text("@MHS_Principal", 8, 50);
};
this.keyPressed = function() {
if('#' === key.toString() || '1' === key.toString()) {
background(0, 0, 0);
fill(255, 255, 255);
textFont(createFont("Tahoma"), 36);
text("<Insert next level here>", 10, 100);
currentLevel++;
}
};
};
/**
* https://www.khanacademy.org/computer-programming/marching-game/4658341294112768
* By Angel Montero
*/
var Montero = function() {
var mainMenuScene = 1;
var rulesScene = 2;
var commentsScene = 3;
var playScene = 4;
var winScene = 5;
var loseScene = 6;
var currentScene = mainMenuScene;
var currentplaysec;
var currentplaymin;
var playminutes;
var playseconds;
var drawbtnReturnToMenu = function() {
noStroke();
fill(255, 255, 255);
rect(200, 200, 115, 45);
textSize(20);
fill(60, 0, 255);
text("Main Menu", 207, 223);
};
var drawRulesScene = function() {
background(255, 0, 0);
textSize(24);
fill(0, 43, 255);
text("There will be content saying", 57, 20);
text("Ready, Set, Go! After this content", 30, 45);
text("is presented, you have to move", 30, 70);
text("the mouse to the light green", 30, 95);
text("spot and click on the spot to win.", 30, 120);
text("you will be faced with gray spots", 30, 145);
text("that are marchers. If you touch", 30, 170);
text("any marcher, you lose.", 30, 195);
text("There is an easy way to win. See", 30, 300);
text("if you can find it. Good Luck!", 30, 325);
noStroke();
fill(255, 255, 255);
rect(200, 200, 115, 45);
textSize(20);
fill(255, 0, 0);
};
var drawwinScene = function(){
background(34, 255, 0);
textSize(40);
fill(0, 0, 0);
text("You won. 1000 points", 10, 50);
currentLevel++;
};
var drawPlayScene = function() {
background(8, 46, 5);
//Place on the field
fill(43, 255, 0);
ellipse(300, 100, 15, 15);
//M on the field
textSize(134);
fill(255, 0, 0);
text("M", 147, 247);
//Yard markers
textSize(40);
fill(255, 255, 255);
text("<30", 0, 380);
textSize(40);
fill(255, 255, 255);
text("<40", 80, 380);
textSize(40);
fill(255, 255, 255);
text("50", 180, 380);
textSize(40);
fill(255, 255, 255);
text("40>", 260, 380);
textSize(40);
fill(255, 255, 255);
text("30>", 340, 380);
// lines on the field
fill(255, 255, 255);
rect(0, 0, 5, 400);
fill(255, 255, 255);
rect(40, 0, 5, 400);
fill(255, 255, 255);
rect(80, 0, 5, 400);
fill(255, 255, 255);
rect(120, 0, 5, 400);
fill(255, 255, 255);
rect(160, 0, 5, 400);
fill(255, 255, 255);
rect(197, 0, 10, 400);
fill(255, 255, 255);
rect(240, 0, 5, 400);
fill(255, 255, 255);
rect(280, 0, 5, 400);
fill(255, 255, 255);
rect(320, 0, 5, 400);
fill(255, 255, 255);
rect(360, 0, 5, 400);
fill(255, 255, 255);
rect(395, 0, 5, 400);
// text(currentScene + " Current Scene Value", 100, 150);
// text(currentplaysec + " seconds initial", 100, 250);
if (currentScene === playScene) {
playminutes = minute() - currentplaymin;
playseconds = playminutes * 60 + second() - currentplaysec;
// text(playseconds + " seconds elapsed", 100, 350);
if (playseconds < 2) {
textSize(40);
fill(255, 0, 0);
text("Ready", 10, 30);
}
if (playseconds >= 2 && playseconds < 4) {
textSize(40);
fill(255, 0, 0);
text("Set", 10, 30);
}
if (playseconds >= 4 && playseconds < 6) {
textSize(40);
fill(255, 0, 0);
text("Go!", 10, 30);
}
//Your dot
if (playseconds >= 6){
var dot;
if (true) {
fill(255, 0, 0);
ellipse(mouseX, mouseY, 15, 15);
var players;
fill(168, 168, 168);
var m = millis()/4;
ellipse(m % width, 200, 15, 15);
ellipse(m % width, 100, 15, 15);
ellipse(m % width, 325, 15, 15);
ellipse(123, m % width, 15, 15);
ellipse(m % width, m % width, 15, 15);
ellipse(265, m % width, 15, 15);
ellipse(m % width, 150, 15, 15);
ellipse(m % width, 250, 15, 15);
ellipse(m % width, 50, 15, 15);
ellipse(200, m% width, 15, 15);
ellipse(50, m % width, 15, 15);
ellipse(324, m % width, 15, 15);
ellipse(m % width, 10, 15, 15);
ellipse(390, m % width, 15, 15);
ellipse(10, m % width, 15, 15);
ellipse(20, m % width, 15, 15);
ellipse(360, m % width, 15, 15);
ellipse(m % width, 80, 15, 15);
ellipse(m % width, 125, 15, 15);
ellipse(m % width, 173, 15, 15);
ellipse(m % width, 221, 15, 15);
ellipse(m % width, 278, 15, 15);
ellipse(m % width, 301, 15, 15);
ellipse(m % width, 357, 15, 15);
ellipse(m % width, 371, 15, 15);
ellipse(73, m % width, 15, 15);
ellipse(107, m % width, 15, 15);
ellipse(223, m % width, 15, 15);
ellipse(285, m % width, 15, 15);
ellipse(345, m % width, 15, 15);
}
}
}
};
var drawloseScene = function() {
background(255, 0, 0);
textSize(40);
fill(31, 5, 5);
text("You lost. No points", 25, 47);
};
var drawbtnRules = function() {
noStroke();
fill(255, 255, 255);
rect(53, 223, 115, 45);
textSize(23);
fill(255, 0, 0);
text("Rules", 73, 252);
};
var drawbtnComments = function() {
noStroke();
fill(255, 255, 255);
rect(269, 223, 115, 45);
textSize(23);
fill(255, 0, 0);
text("Comments", 271, 252);
};
var drawbtnPlayGame = function() {
noStroke();
fill(255, 255, 255);
rect(167, 316, 115, 45);
textSize(23);
fill(255, 0, 0);
text("Play Game", 168, 346);
};
this.draw = function() {
if(currentScene === mainMenuScene) {
// draw main menu
background(255, 170, 0);
//GameTitle
textSize(24);
fill(255, 0, 0);
text("Marching Game", 52,187);
drawbtnRules();
drawbtnComments();
drawbtnPlayGame();
}
else if(currentScene === rulesScene) {
// draw rules
background(255, 0, 0);
drawRulesScene();
drawbtnReturnToMenu();
}
else if(currentScene === commentsScene) {
// draw comments
background(55, 196, 104);
textSize(25);
fill(240, 240, 12);
text("Sorry, there are no comments.", 30, 20);
drawbtnReturnToMenu();
}
else if(currentScene === playScene) {
// plays game
drawPlayScene();
if(mouseIsPressed === false) {
var mouseCol = get(mouseX, mouseY);
if(mouseCol === color(168, 168, 168)) {
currentScene = loseScene;
}
}
} else if(currentScene === loseScene) {
drawloseScene();
}
};
this.mousePressed = function() {
if(currentScene === mainMenuScene) {
if(mouseX >= 53 && mouseX < 168 && mouseY >= 223 && mouseY < 268) {
currentScene = rulesScene;
}
if(mouseX >= 269 && mouseX < 384 && mouseY >= 223 && mouseY < 268){
currentScene = commentsScene;
}
if(mouseX >= 167 && mouseX < 282 && mouseY >= 316 && mouseY < 361){
currentplaysec = second();
currentplaymin = minute();
currentScene = playScene;
}
}
else if(currentScene === rulesScene) {
if(mouseX >= 200 && mouseX < 315 && mouseY >= 200 && mouseY < 245) {
currentScene = mainMenuScene;
}
}
else if(currentScene === commentsScene) {
if(mouseX >= 200 && mouseX < 315 && mouseY >= 200 && mouseY < 245) {
currentScene = mainMenuScene;
}
}
else if(currentScene === playScene) {
if(mouseX >= 295 && mouseX < 305 && mouseY >= 95 && mouseY < 105) {
currentScene = drawwinScene();
}
}
};
};
/**
* https://www.khanacademy.org/computer-programming/spin-off-of-byte-me-submissions/4562186463870976
* By Alex Nickl
* */
var Nickl = function() {
var GREEN = color(0, 250, 0);
var RED = color(255, 0, 0);
var buttonRound = 1;
var drawButtons = function() {
if(buttonRound === 1 || buttonRound === 3 ){
noStroke();
fill(255, 0, 0);
ellipse(100, 200, 130,130);
fill(0, 250, 0);
ellipse(250,200,130,130);
}
if(buttonRound === 2 || buttonRound === 4 ){
noStroke();
fill(255, 0, 0);
ellipse(250,200,130,130);
fill(0, 250, 0);
ellipse(100,200,130,130);
}
};
this.draw = function() {
background(0, 0, 0);
fill(255, 255, 255);
textFont(createFont("Tahoma"), 18);
text("click the buttons in this order\ngreen red red green", 47, 100);
text("© MHS BYTE CLUB", 37, 377);
drawButtons();
if(buttonRound === 5) {
currentLevel++;
}
};
this.mousePressed = function() {
var mouseColor = get(mouseX,mouseY);
if(buttonRound === 1 || buttonRound === 4) {
if(mouseColor === RED){
background(255, 0, 0);
text("fail",100,100);
noLoop();
}
if(mouseColor === GREEN){
buttonRound++;
}
} else if(buttonRound === 2 || buttonRound === 3) {
if(mouseColor === RED){
buttonRound++;
}
if(mouseColor === GREEN){
background(255, 0, 0);
text("fail",100,100);
noLoop();
}
}
};
};
var Congragulations = function() {
this.draw = function() {
background(0, 0, 0);
fill(255, 255, 255);
textFont(createFont("Tahoma"), 38);
text("Congragulations!\nYou won!!!!!!!!!!!!!!!!!!!!!!!!", 47, 100);
text("© Play Again?", 37, 377);
ellipse(mouseX, mouseY, 32, 32);
if(dist(mouseX, mouseY, 55, 363) < 4) {
fill(51, 255, 0);
ellipse(55, 363, 36, 36);
if(mouseIsPressed) {
currentLevel = 1;
}
}
};
};
var Lost = function() {
this.draw = function() {
background(0, 0, 0);
fill(255, 255, 255);
textFont(createFont("Tahoma"), 38);
text("Oh noes!\nYou lost!!!!!!!!!!!!!!!!!!!!!!!!", 47, 100);
text("© Play Again?", 37, 377);
ellipse(mouseX, mouseY, 32, 32);
if(dist(mouseX, mouseY, 55, 358) < 4) {
fill(51, 255, 0);
ellipse(55, 358, 36, 36);
if(mouseIsPressed) {
currentLevel = 1;
}
}
};
};
games = [Opener, ShannonDontTouchWhite, Balogh, Kenny, ShannonMovingButton, Alberts, Farmer, ShannonRedButton, Rouvinov, Montero, Nickl, Congragulations, Lost];
var game = new games[currentLevel]();
var draw = function() {
game.draw();
if(currentLevel !== lastFrameLevel) {
colorMode(RGB, 255);
background(255, 255, 255);
fill(255, 255, 255);
stroke(0, 0, 0);
strokeWeight(1);
textFont(createFont("sans-serif"), 12);
textAlign(LEFT, BOTTOM);
angleMode = "degrees";
frameRate(30);
resetMatrix();
loop();
game = new games[currentLevel]();
/*
mouseClicked = game.mouseClicked;
mousePressed = game.mousePressed;
mouseReleased = game.mouseReleased;
mouseMoved = game.mouseMoved;
mouseDragged = game.mouseDragged;
mouseOver = game.mouseOver;
mouseOut = game.mouseOut;
keyPressed = game.keyPressed;
keyReleased = game.keyReleased;
keyTyped = game.keyTyped;
keyPressed = game.keyPressed;
*/
}
lastFrameLevel = currentLevel;
};
var mouseClicked = function(){ game.mouseClicked(); };
var mousePressed = function(){ game.mousePressed(); };
var mouseReleased = function(){ game.mouseReleased(); };
var mouseMoved = function(){ game.mouseMoved(); };
var mouseDragged = function(){ game.mouseDragged(); };
var mouseOver = function(){ game.mouseOver(); };
var mouseOut = function(){ game.mouseOut(); };
var keyPressed = function(){ game.keyPressed(); };
var keyReleased = function(){ game.keyReleased(); };
var keyTyped = function(){ game.keyTyped(); };
var keyPressed = function(){ game.keyPressed(); };
| 30.135922 | 552 | 0.467832 |
131f14ec8af75cb0ee4db23dd223d2591a56f507 | 7,324 | js | JavaScript | photowall/src/redux/actions.js | MuhammadHafidzMisrudin/learning-js-dev | 1f74d581424335662eb182daea326de97e071c0b | [
"MIT"
] | null | null | null | photowall/src/redux/actions.js | MuhammadHafidzMisrudin/learning-js-dev | 1f74d581424335662eb182daea326de97e071c0b | [
"MIT"
] | null | null | null | photowall/src/redux/actions.js | MuhammadHafidzMisrudin/learning-js-dev | 1f74d581424335662eb182daea326de97e071c0b | [
"MIT"
] | null | null | null | /// Action creators.
import {database} from '../database/config';
// Add action method to update the database first, then dispatch an action creator.
// Whenever submit a post, it updates the database first.
// Once it's done updating, it will dispatch an action creator with dispatch method.
export function startAddingPost(post) {
return (dispatch) => {
// Update the database with promise.
// After update the database, it will dispatch an action that updates the Redux store.
return database.ref('posts').update({[post.id]: post}).then(() => {
// Dispatch add post action.
dispatch(addPost(post));
}).catch((error) => {
// Check if update doesnt work and error occurs.
console.log(error);
});
};
}
// Add action method for fetching data posts from the database.
// Method to observe database, grab the data, then invoke the dispatch method to load the data posts onto the Redux store.
// Return a function takes in a dispatch method.
export function startLoadingPost() {
return (dispatch) => {
/*
Access the reference the node posts.
Observe database once and return the value.
Promise returns the data in the form of snapshot.
Snapshot contains all children the node posts.
*/
return database.ref('posts').once('value').then((snapshot) => {
// Initialize an array to store each snapshot.
let posts = [];
// Iterate through each child snapshot.
// Append to an array of posts and get the value.
snapshot.forEach((childSnapshot) => {
posts.push(childSnapshot.val());
});
// Dispatch load post action.
dispatch(loadPosts(posts));
}).catch((error) => {
// Check if update doesnt work and error occurs.
console.log(error);
});
};
}
// Add action method for removing data posts and comments.
export function startRemovingPost(index, id) {
/*
This specifies the paths to update data to null (basically delete the data).
It navigates to the post with specific id for deletion when the remove button clicked.
As well as the comments belonging to that post, with that same id for deletion.
*/
const updatesByDelete = {
[`posts/${id}`]: null,
[`comments/${id}`]: null
};
return (dispatch) => {
/*
Travel to the node posts.
From the node post, access to specific id belonging to the post and the comments.
Node with specific id will be removed with the post and its comments.
Modify and update the data to null.
Update the database from its root node, such that it navigates to the posts path.
As well as the comments path, and sets them to null.
(In other words, deletes both of them).
After deleting the post and its comments from the database,
It updates the UI by dispatching an action to the Redux reducer.
*/
return database.ref().update(updatesByDelete).then(() => {
// If the removal successful, dispatch remove action.
dispatch(removePost(index));
}).catch((error) => {
// Check if update doesnt work and error occurs.
console.log(error);
});
};
// return (dispatch) => {
// // Travel to the node posts.
// // From the node post, access to specific id belonging to the post.
// // Node with specific id will be removed.
// return database.ref(`posts/${id}`).remove().then(() => {
// // If the removal successful, dispatch remove action.
// dispatch(removePost(index));
// }).catch((error) => {
// // Check if update doesnt work and error occurs.
// console.log(error);
// });
// };
}
// Add action method for saving comments.
// Params of comment and post id.
// Use the post id to direct to the proper node that displays comment, the comment is saved in the database.
export function startAddingComment(comment, postId) {
return (dispatch) => {
// Push comment into the database with specific post id.
return database.ref('comments/' + postId).push(comment).then(() => {
// Dispatch the add comment action that updates Redux store with submitted comment.
dispatch(addComment(comment, postId));
}).catch((error) => {
// Check if update doesnt work and error occurs.
console.log(error);
});
};
}
// Add action method for fetching data comments from the database.
// Method to observe database, grab the data, then invoke the dispatch method to load the data comments onto the Redux store.
export function startLoadingComments() {
return (dispatch) => {
/*
Access the reference the node comments.
Observe database once and return the value.
Promise returns the data in the form of snapshot.
Snapshot contains all children the node comments.
*/
return database.ref('comments').once('value').then((snapshot) => {
// Initialize an object to store each snapshot.
let comments = {};
// Iterate through each child snapshot.
// Append to an object of comments and get the value.
snapshot.forEach((childSnapshot) => {
// Comment object has a specific key of the post id.
// Post id with comments is set equal to value.
// Object contains a bunch a key-value pairs.
comments[childSnapshot.key] = Object.values(childSnapshot.val());
});
// Dispatch load comments action.
dispatch(loadComments(comments));
}).catch((error) => {
// Check if update doesnt work and error occurs.
console.log(error);
});
};
}
// Add action creator of remove function.
// Return a js object that describes the event that should update the application state.
export function removePost(index) {
return {
type: 'REMOVE_POST',
index // index: index
}
}
// Add action creator of adding post function.
// Return a js object that describes the event that should update the application state.
export function addPost(post) {
return {
type: 'ADD_POST',
post // post: post
}
}
// Add action creator of adding comments function.
// Pass arguments of comment and its post id.
export function addComment(comment, postId) {
return {
type: 'ADD_COMMENT',
comment,
postId
}
}
// Add action creator of load posts function.
// Load the posts onto the Redux store.
// Pass the parameter of the posts that is loaded from the database.
// Return js object.
export function loadPosts(posts) {
return {
type: 'LOAD_POSTS',
posts
}
}
// Add action creator of load comments function.
// Load the comments onto the Redux store.
export function loadComments(comments) {
return {
type: 'LOAD_COMMENTS',
comments
}
} | 33.290909 | 125 | 0.607045 |
131ff6f8ad3a831bd5132afa6f41f184d8291da7 | 8,490 | js | JavaScript | Docs/search/all_66.js | DemoXinMC/Otter | e1447885302276313c1e4ffc9632ceec0d7a6d37 | [
"MIT"
] | 63 | 2019-01-20T21:31:14.000Z | 2022-02-08T02:10:38.000Z | Otter/Docs/search/all_66.js | cartman300/Habitat | 29aa049f6bdc3f37ab5d032b7840206d695267a1 | [
"MIT"
] | 35 | 2020-04-05T16:27:27.000Z | 2020-04-21T12:49:37.000Z | Otter/Docs/search/all_66.js | cartman300/Habitat | 29aa049f6bdc3f37ab5d032b7840206d695267a1 | [
"MIT"
] | 18 | 2019-01-26T04:13:51.000Z | 2022-02-04T13:21:51.000Z | var searchData=
[
['fileexists',['FileExists',['../class_otter_1_1_files.html#ad2bdce8b4f8fa1ecb7a477c5ed5ce90c',1,'Otter.Files.FileExists()'],['../class_otter_1_1_data_saver.html#a6fed90808d1015e2f0790a076a1c3a98',1,'Otter.DataSaver.FileExists()']]],
['filepath',['Filepath',['../class_otter_1_1_game.html#a72ef64d3ff24cce30aeaaf6595528d52',1,'Otter::Game']]],
['files',['Files',['../class_otter_1_1_files.html',1,'Otter']]],
['fill',['Fill',['../class_otter_1_1_square_clock.html#a6b53d1f8ebec408c28f6eb827a11ae73',1,'Otter.SquareClock.Fill()'],['../class_otter_1_1_surface.html#ad1515db29e971c00f77e76c5f2498ff0',1,'Otter.Surface.Fill()']]],
['fillangle',['FillAngle',['../class_otter_1_1_square_clock.html#aaed149685640e5c76d931f1f000e2c26',1,'Otter::SquareClock']]],
['fillcolor',['FillColor',['../class_otter_1_1_surface.html#ae03197ab03409475a0e3fd13966a90c5',1,'Otter::Surface']]],
['finalalpha',['FinalAlpha',['../class_otter_1_1_flash.html#a860dbdcd396e63e4cf8e4148ce72bac8',1,'Otter.Flash.FinalAlpha()'],['../class_otter_1_1_particle.html#a457092f445e497fc6c9ea7d4d4979c8a',1,'Otter.Particle.FinalAlpha()']]],
['finalangle',['FinalAngle',['../class_otter_1_1_particle.html#abe2d0e1e0dbfb87eb193c1635653d077',1,'Otter::Particle']]],
['finalcolor',['FinalColor',['../class_otter_1_1_particle.html#a6e831f82a95d64b2a2d8a7221a272bcd',1,'Otter::Particle']]],
['finalcolorb',['FinalColorB',['../class_otter_1_1_particle.html#ac3897a5e70105859369b165431322959',1,'Otter::Particle']]],
['finalcolorg',['FinalColorG',['../class_otter_1_1_particle.html#a543fe36f3c11443918b08701796e52ca',1,'Otter::Particle']]],
['finalcolorr',['FinalColorR',['../class_otter_1_1_particle.html#acf7be80d90f3bdedadad1e5b1cca57e8',1,'Otter::Particle']]],
['finalscalex',['FinalScaleX',['../class_otter_1_1_particle.html#aba1a3ed1af86b77d3bfc70db00a5db39',1,'Otter::Particle']]],
['finalscaley',['FinalScaleY',['../class_otter_1_1_particle.html#ae9aa4a7436ca774e246b4e3177cafc52',1,'Otter::Particle']]],
['finalspeeddir',['FinalSpeedDir',['../class_otter_1_1_particle.html#a183c792dd444ae2d24949a0c44e7467f',1,'Otter::Particle']]],
['finalspeedlen',['FinalSpeedLen',['../class_otter_1_1_particle.html#a637312e5b8ab790f37acaf87fcef3640',1,'Otter::Particle']]],
['finalspeedx',['FinalSpeedX',['../class_otter_1_1_particle.html#a3774bc286c6c8e34006f932bd8a3306c',1,'Otter::Particle']]],
['finalspeedy',['FinalSpeedY',['../class_otter_1_1_particle.html#a2a5c5722d8e8436f9a68c305d9aa4cd8',1,'Otter::Particle']]],
['finalx',['FinalX',['../class_otter_1_1_particle.html#a5f3a1954734f19ec1135fbaa6d0b76e5',1,'Otter::Particle']]],
['finaly',['FinalY',['../class_otter_1_1_particle.html#a3a0606ad0d335a5c64d7c8d73a5dab99',1,'Otter::Particle']]],
['finish',['Finish',['../class_otter_1_1_event_processor_event.html#a5349887023f033a124a18d59ed19b567',1,'Otter::EventProcessorEvent']]],
['firstscene',['FirstScene',['../class_otter_1_1_game.html#af69ac4b297ffa24e683123baed4f2d23',1,'Otter::Game']]],
['fixedframerate',['FixedFramerate',['../class_otter_1_1_game.html#af58e5060ad11578306d676da30b2a76d',1,'Otter::Game']]],
['flash',['Flash',['../class_otter_1_1_flash.html',1,'Otter']]],
['flash',['Flash',['../class_otter_1_1_flash.html#a4cf424cbe29d3712457f3e05e01c818b',1,'Otter::Flash']]],
['flipd',['FlipD',['../class_otter_1_1_tile_info.html#a93f7473062bc188d36f6ea01ce5348ee',1,'Otter::TileInfo']]],
['flippedx',['FlippedX',['../class_otter_1_1_image.html#a654c7269d1edd58ac7368a68cc2f4fe2',1,'Otter::Image']]],
['flippedy',['FlippedY',['../class_otter_1_1_image.html#a034ba2383622d0c6538c02c0bf48c51f',1,'Otter::Image']]],
['flipx',['FlipX',['../class_otter_1_1_tile_info.html#aa5db7dfe5c3570065b02f5b262c6f216',1,'Otter.TileInfo.FlipX()'],['../class_otter_1_1_particle.html#adf5f4953dca2b114b719af3dab040778',1,'Otter.Particle.FlipX()']]],
['flipy',['FlipY',['../class_otter_1_1_particle.html#aeb63f27a32dac5d8c2ff14cd10b3d635',1,'Otter::Particle']]],
['font',['Font',['../class_otter_1_1_rich_text_config.html#a66c24da2ed801842d115836b648abde9',1,'Otter::RichTextConfig']]],
['font',['Font',['../class_otter_1_1_font.html',1,'Otter']]],
['fonts',['Fonts',['../class_otter_1_1_fonts.html',1,'Otter']]],
['fontsize',['FontSize',['../class_otter_1_1_rich_text.html#a7a4e87e79d81b1081d5771a8d550a8db',1,'Otter.RichText.FontSize()'],['../class_otter_1_1_rich_text_config.html#a04c210dcb2c66cbc031c1108fa372082',1,'Otter.RichTextConfig.FontSize()'],['../class_otter_1_1_text.html#adf40268f0d03f2d11387a9e48c94bacb',1,'Otter.Text.FontSize()']]],
['forcedebugger',['ForceDebugger',['../class_otter_1_1_game.html#a73a753e6fc6ff0570f5cf72f4e943aee',1,'Otter::Game']]],
['forcedinput',['ForcedInput',['../class_otter_1_1_axis.html#a58b7a11208837f6214d74ec07632cf40',1,'Otter.Axis.ForcedInput()'],['../class_otter_1_1_button.html#ad5560bd25b138d8a1ef9311b67765df7',1,'Otter.Button.ForcedInput()']]],
['forcestate',['ForceState',['../class_otter_1_1_axis.html#a5432ee7a3c43845e0ae6cf74efab0ff5',1,'Otter.Axis.ForceState(float x, float y)'],['../class_otter_1_1_axis.html#adeebf15b7f4e1484a61deba96b331b13',1,'Otter.Axis.ForceState(Vector2 xy)'],['../class_otter_1_1_button.html#a3232cb91090096eba72f4c89c4c4da46',1,'Otter.Button.ForceState()']]],
['forcestatex',['ForceStateX',['../class_otter_1_1_axis.html#ad9a1e7ce22c9b5720466e4548864187c',1,'Otter::Axis']]],
['forcestatey',['ForceStateY',['../class_otter_1_1_axis.html#a41ca28b6a5dd015b5f57bca3b187ae2e',1,'Otter::Axis']]],
['frame',['Frame',['../class_otter_1_1_image_set.html#ad958ff2849270763ba2dbb979e07022d',1,'Otter::ImageSet']]],
['framecount',['FrameCount',['../class_otter_1_1_anim.html#a5b72692c052d6e6e57a88ea4d2321721',1,'Otter.Anim.FrameCount()'],['../class_otter_1_1_particle.html#a22d3ebec1a58dec40d91ecea35f8a4c5',1,'Otter.Particle.FrameCount()']]],
['framedelays',['FrameDelays',['../class_otter_1_1_anim.html#a3704589c1f590e78ad7a04cc2d87b53a',1,'Otter::Anim']]],
['frameheight',['FrameHeight',['../class_otter_1_1_atlas_texture.html#a73b297ecbf434cc08f13e2cf99e4517c',1,'Otter::AtlasTexture']]],
['frameoffset',['FrameOffset',['../class_otter_1_1_particle.html#ae49a9e55a1c8a0fa9a8a76ebd3333d62',1,'Otter::Particle']]],
['framerate',['Framerate',['../class_otter_1_1_game.html#abf2de508b45bef64625f3b44c1209154',1,'Otter::Game']]],
['frames',['Frames',['../class_otter_1_1_anim.html#a04cf79e0b4d996ec77be76c79a21f4f9',1,'Otter.Anim.Frames()'],['../class_otter_1_1_image_set.html#af9f13a4b50f0f245e64d8eecc79c79bf',1,'Otter.ImageSet.Frames()'],['../class_otter_1_1_spritemap_3_01_t_anim_type_01_4.html#a38b7c28ac15c22718539ff5da1a8783d',1,'Otter.Spritemap< TAnimType >.Frames()'],['../class_otter_1_1_particle.html#aad858411ab59f2c6a050e6fa4a3f50ba',1,'Otter.Particle.Frames()']]],
['framesrange',['FramesRange',['../class_otter_1_1_anim.html#aa5ba3ca3068dfa543bbce718d7fdb40f',1,'Otter::Anim']]],
['framewidth',['FrameWidth',['../class_otter_1_1_atlas_texture.html#a9f2b090dbef19df8cb183c8e65aab8d9',1,'Otter::AtlasTexture']]],
['framex',['FrameX',['../class_otter_1_1_atlas_texture.html#a56fe66a7891caa14364307de732f798e',1,'Otter::AtlasTexture']]],
['framey',['FrameY',['../class_otter_1_1_atlas_texture.html#a1307f869b9c9a314e114ee1992e1c7d8',1,'Otter::AtlasTexture']]],
['freeze',['Freeze',['../class_otter_1_1_basic_movement.html#ade475fe5dc3f4d9d33cd06dff040d5d7',1,'Otter::BasicMovement']]],
['freezeframe',['FreezeFrame',['../class_otter_1_1_spritemap_3_01_t_anim_type_01_4.html#a2261e3a6a7a8d7b71e88a0b42554da6b',1,'Otter::Spritemap< TAnimType >']]],
['from',['From',['../class_otter_1_1_tween.html#ab477840bcb01765479529790b0f122fa',1,'Otter::Tween']]],
['frombytes',['FromBytes',['../class_otter_1_1_color.html#ad27605d2b70102037782d933a055b672',1,'Otter::Color']]],
['fromhsv',['FromHSV',['../class_otter_1_1_color.html#afa1a1af7b7fab14daa668e2279251687',1,'Otter::Color']]],
['fromstring',['FromString',['../class_otter_1_1_shader.html#a9b4cb4538e1af1be3a10ac26b7d08e21',1,'Otter.Shader.FromString(string vertexShader, string fragmentShader)'],['../class_otter_1_1_shader.html#a78d1b9995b691f088e5f78cb59177fc1',1,'Otter.Shader.FromString(ShaderType shaderType, string shader)']]],
['function',['Function',['../class_otter_1_1_alarm.html#abb33ddac211d29b404f43a30e8ae15a3',1,'Otter::Alarm']]],
['functions',['Functions',['../class_otter_1_1_state.html#aa9fe12c03378491b2a1a88d85c02462e',1,'Otter::State']]]
];
| 136.935484 | 456 | 0.767491 |
13205a714984418e2ddc916eb4b78faaf56127dd | 713 | js | JavaScript | public/backend_asset/company/js/custom.js | ramrajparihar/blog | a96df120db6bc607b82f0a05bcff143cc748c114 | [
"MIT"
] | null | null | null | public/backend_asset/company/js/custom.js | ramrajparihar/blog | a96df120db6bc607b82f0a05bcff143cc748c114 | [
"MIT"
] | null | null | null | public/backend_asset/company/js/custom.js | ramrajparihar/blog | a96df120db6bc607b82f0a05bcff143cc748c114 | [
"MIT"
] | null | null | null | $("#showPDF").click(function(){
$(".pdfFile, .RecordTextUploaded").show();
$(".noRecordImage, .noRecordBlockText").hide();
});
function printDiv() {
window.frames["print_frame"].document.body.innerHTML = document.getElementById("printableTable").innerHTML;
window.frames["print_frame"].window.focus();
window.frames["print_frame"].window.print();
}
$(function() {
$('#frequency_filter').change(function(){
$('.frequency_selct').hide()
$('#'+ $(this).val()).show();
});
});
$('input[type="radio"]').click(function(){
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".dayDateSelect").not(targetBox).hide();
$(targetBox).show();
}); | 29.708333 | 108 | 0.618513 |
1320be32532c4c1238d094c8688fdf60bdcede53 | 12,242 | js | JavaScript | lib/generator.js | jhs67/pg-formation | f552deb481b5c0dd0f78ed0066a39f61a7d1f03e | [
"ISC"
] | null | null | null | lib/generator.js | jhs67/pg-formation | f552deb481b5c0dd0f78ed0066a39f61a7d1f03e | [
"ISC"
] | 2 | 2020-05-24T19:41:17.000Z | 2020-07-21T00:20:46.000Z | lib/generator.js | jhs67/pg-formation | f552deb481b5c0dd0f78ed0066a39f61a7d1f03e | [
"ISC"
] | null | null | null |
const objdiff = require("./objdiff");
const format = require('pg-format');
const deparser = require("./deparser");
const pgquery = require("pg-query-emscripten");
const deepEql = require("deep-eql");
function parseFunction(f) {
let r = pgquery.parse(f).parse_tree;
delete r[0].RawStmt.stmt.CreateFunctionStmt.replace;
return r;
}
generate.normalizeFunction = normalizeFunction;
function normalizeFunction(f) {
return deparser.deparse(parseFunction(f));
}
function arrify(v) {
return !v ? [] : Array.isArray(v) ? v : [v];
}
function stripLocation(obj) {
if (Array.isArray(obj)) {
return obj.map(v => stripLocation(v));
}
else if (obj && typeof obj === 'object') {
let r = {};
Object.keys(obj).filter(k => k !== "location" && k !== "stmt_len").forEach(k => r[k] = stripLocation(obj[k]));
return r;
}
else {
return obj;
}
}
function funcdiff(from, to) {
let fparse = stripLocation(parseFunction(from));
let tparse = stripLocation(parseFunction(to));
return deepEql(fparse, tparse);
}
function getColumnRefs(tl, cols) {
if ("ColumnRef" in tl) {
cols.push(deparser.deparse([tl]));
return;
}
for (const k in tl) {
if (tl[k] && typeof tl[k] === "object") {
getColumnRefs(tl[k], cols);
}
}
}
function formatIndexColumn(table, expr, deps) {
const p = pgquery.parse(`SELECT ${expr}`);
const tl = p.parse_tree[0].RawStmt.stmt.SelectStmt.targetList[0].ResTarget.val;
if ("ColumnRef" in tl) {
deps.push(`table.${table}.${expr}`);
return format("%I", expr);
}
// get any columnd references
const cols = [];
getColumnRefs(tl, cols);
cols.forEach(c => deps.push(`table.${table}.${c}`));
return expr;
}
class Generator {
constructor() {
this.cmds = [];
}
sortCmds() {
let sort = [];
while (this.cmds.length) {
for (let i = 0; ; i += 1) {
if (i === this.cmds.length)
throw new Error("circular dependencies");
const c = this.cmds[i];
// if anything we depend on isn't fully provided wait
if (c.depends.some(p => this.cmds.some(d => d.provides.some(q => q === p))))
continue;
// if what we remove is still depended on wait
if (c.removes.some(p => this.cmds.some(d => d.depends.some(q => q === p))))
continue;
this.cmds.splice(i, 1);
sort = sort.concat(c.cmd);
break;
}
}
return sort;
}
parsedTypeDep(v) {
// get the type with qualifiers and arrays removed
return `type.${deparser.deparse([{ TypeName: { names: v.TypeName.names } }])}`;
}
typeDep(n) {
// parse it as a type
let c = pgquery.parse(`CREATE TABLE t (c ${n})`);
if (c.error) return [];
// extract the type from the table
let p = c.parse_tree[0].RawStmt.stmt.CreateStmt.tableElts[0].ColumnDef.typeName;
return this.parsedTypeDep(p);
}
addCmd(cmd, provides, depends, removes) {
this.cmds.push({ cmd: arrify(cmd), provides: arrify(provides),
depends: arrify(depends), removes: arrify(removes) });
}
createIndex(table, name, def) {
const deps = [];
const cmd = format("CREATE%s INDEX %I ON %I USING %s (%s)",
def.unique ? " UNIQUE" : "", name, table,
def.method, def.columns.map(c => formatIndexColumn(table, c, deps)).join(", "));
this.addCmd(cmd, `index.${table}.${name}`, deps);
}
alterIndex(table, name, from, to) {
const deps = [];
from.columns.forEach(c => formatIndexColumn(table, c, deps));
const cmds = [
format("DROP INDEX %I", name),
format("CREATE%s INDEX %I ON %I USING %s (%s)",
to.unique ? " UNIQUE" : "", name, table,
to.method, to.columns.map(c => formatIndexColumn(table, c, deps)).join(", "))
];
this.addCmd(cmds, `index.${table}.${name}`, deps);
}
dropIndex(table, name, def) {
this.addCmd(format("DROP INDEX %I", name), [], def.columns.map(c => `table.${table}.${c}`),
`index.${table}.${name}`);
}
columnDef(name, def, deps) {
let r = [ format("%I %s", name, def.type) ];
deps.push(this.typeDep(def.type));
if (def.primarykey) {
r.push("PRIMARY KEY");
}
else {
if (def.unique)
r.push("UNIQUE");
if (def.notnull)
r.push("NOT NULL");
}
if ('default' in def) {
r.push(format("DEFAULT %L", def.default));
}
return r.join(' ');
}
createReference(name, column, def) {
if (!def.references)
return;
const deps = [`table.${name}`, `table.${name}.${column}`, `table.${def.references}`];
let p = format("ALTER TABLE %I ADD CONSTRAINT %I FOREIGN KEY(%I) REFERENCES %I",
name, `${name}_${def.references}_key`, column, def.references);
this.addCmd(p, [`reference.${name}.${column}`], deps);
}
createTable(name, def) {
let deps = [];
let cmd = format("CREATE TABLE %I (\n %s)", name,
Object.keys(def.columns).map(
n => this.columnDef(n, def.columns[n], deps)).join(",\n "));
let prov = [ `table.${name}`, ...Object.keys(def.columns).map(n => `table.${name}.${n}`)];
this.addCmd(cmd, prov, deps);
for (let i in def.indices)
this.createIndex(name, i, def.indices[i]);
for (let i in def.columns)
if (def.columns[i].references)
this.createReference(name, i, def.columns[i]);
}
alterTable(name, from, to) {
const columndiff = objdiff(from.columns, to.columns);
let p = format("ALTER TABLE %I ", name);
for (let k of columndiff.add) {
let deps = [];
let cmd = p + format("ADD %s", this.columnDef(k, to.columns[k], deps));
this.addCmd(cmd, `table.${name}.${k}`, deps);
}
for (let k of columndiff.change) {
let f = from.columns[k], t = to.columns[k];
let c = [], provides = [`table.${name}.${k}`];
let deps = [this.typeDep(t.type), this.typeDep(f.type)];
let removes = [];
if (f.type !== t.type) {
c.push(p + format("ALTER %I TYPE %s", k, t.type));
deps.push();
}
if (f.primarykey && !t.primarykey) {
c.push(p + format("DROP CONSTRAINT %I", `${name}_pkey`));
if (t.unique)
c.push(p + format("ADD UNIQUE (%I)", k));
if (!t.notnull)
c.push(p + format("ALTER %I DROP NOT NULL", k));
provides.push(`table.${name}`);
}
else if (t.primarykey && !f.primarykey) {
if (f.unique)
c.push(p + format("DROP CONSTRAINT %I", `${name}_${k}_key`));
if (f.notnull)
c.push(p + format("ALTER %I DROP NOT NULL", k));
c.push(p + format("ADD PRIMARY KEY (%I)", k));
provides.push(`table.${name}`);
}
else if (!t.primarykey) {
if (f.unique && !t.unique)
c.push(p + format("DROP CONSTRAINT %I", `${name}_${k}_key`));
if (t.unique && !f.unique)
c.push(p + format("ADD UNIQUE (%I)", k));
if (f.notnull && !t.notnull)
c.push(p + format("ALTER %I DROP NOT NULL", k));
else if (!f.notnull && t.notnull)
c.push(p + format("ALTER %I SET NOT NULL", k));
}
if (f.references && f.references != t.references) {
c.push(p + format("DROP CONSTRAINT %I", `${name}_${f.references}_key`));
deps.push(`table.${f.references}`);
removes.push(`reference.${name}.${k}`);
}
if (('default' in f) && !('default' in t))
c.push(p + format("ALTER %I DROP DEFAULT", k));
else if (('default' in t) && f.default !== t.default)
c.push(p + format("ALTER %I SET DEFAULT %L", k, t.default));
this.addCmd(c, provides, deps, removes);
}
for (let k of columndiff.remove) {
this.addCmd(p + format("DROP %I", k), [],
[ this.typeDep(from.columns[k].type) ], `table.${name}.${k}`);
}
for (let k of columndiff.add) {
let t = to.columns[k];
if (t && t.references)
this.createReference(name, k, t);
}
for (let k of columndiff.change) {
let f = from.columns[k], t = to.columns[k];
if (t.references && t.references !== f.references)
this.createReference(name, k, t);
}
const indicesdiff = objdiff(from.indices, to.indices);
for (let k of indicesdiff.add) {
this.createIndex(name, k, to.indices[k]);
}
for (let k of indicesdiff.change) {
this.alterIndex(name, k, from.indices[k], to.indices[k]);
}
for (let k of indicesdiff.remove) {
this.dropIndex(name, k, from.indices[k]);
}
}
dropTable(name, def) {
this.addCmd(format("DROP TABLE %I", name), [], [],
[ `table.${name}`, ...Object.keys(def.columns).map(n => `table.${name}.${n}`),
...Object.keys(def.indices).map(k => `index.${name}.${k}`),
...Object.entries(def.columns).filter(([, def]) => def.references).map(k => `reference.${name}.${k}`)]);
}
createType(name, def) {
this.addCmd(format("CREATE TYPE %I AS ENUM (%s)", name,
def.values.map(c => format("%L", c)).join(", ")), `type.${name}`);
}
alterType(name, from, to, src) {
let c = [];
// drop any functions depending on the old type
let fns = [];
Object.keys(src.functions).forEach(fn => {
let f = src.functions[fn];
let pf = parseFunction(f);
let m = pf[0].RawStmt.stmt.CreateFunctionStmt.parameters.some(
p => this.parsedTypeDep(p.FunctionParameter.argType) == `type.${name}`);
if (m) {
fns.push(pf);
c.push(this.dropFunctionCmd(pf[0].RawStmt.stmt.CreateFunctionStmt));
}
});
// rename the old type
c.push(format("ALTER TYPE %I RENAME TO %I", name,
`${name}_alter_type`));
// create the updated type
c.push(format("CREATE TYPE %I AS ENUM (%s)", name,
to.values.map(c => format("%L", c)).join(", ")));
// find any columns that reference the old type
Object.keys(src.tables).forEach(tn => {
let t = src.tables[tn];
Object.keys(t.columns).forEach(cn => {
let cd = t.columns[cn];
if (this.typeDep(cd.type) === `type.${name}`) {
c.push(format("ALTER TABLE %I ALTER COLUMN %I TYPE %s USING %I::text::%I",
tn, cn, name, cn, name));
}
});
});
// drop the old type
c.push(format("DROP TYPE %I", `${name}_alter_type`));
// recreate functions with new type
fns.forEach(pf => {
c.push(deparser.deparse(pf));
});
this.addCmd(c, `type.${name}`);
}
dropType(name) {
this.addCmd(format("DROP TYPE %I", name), [], [], `type.${name}`);
}
createFunction(name, def) {
let c = parseFunction(def);
let deps = c[0].RawStmt.stmt.CreateFunctionStmt.parameters.map(p => this.parsedTypeDep(p.FunctionParameter.argType));
this.addCmd(deparser.deparse(c), `function.${name}`, deps);
}
dropFunctionCmd(c) {
return deparser.deparse([ { DropStmt: {
objects: [{
ObjectWithArgs: {
objname: c.funcname,
objargs: c.parameters.filter(v => v.FunctionParameter.mode === 105)
.map(v => v.FunctionParameter.argType)
}
}],
removeType: deparser.dropFunctionType(),
}}]);
}
alterFunction(name, from, to) {
let pf = parseFunction(from);
let pt = parseFunction(to);
let deps = [...pf[0].RawStmt.stmt.CreateFunctionStmt.parameters.map(p => this.parsedTypeDep(p.FunctionParameter.argType)),
...pt[0].RawStmt.stmt.CreateFunctionStmt.parameters.map(p => this.parsedTypeDep(p.FunctionParameter.argType))];
this.addCmd([ this.dropFunctionCmd(pf[0].RawStmt.stmt.CreateFunctionStmt), deparser.deparse(pt) ], `function.${name}`, deps);
}
dropFunction(name, def) {
let pf = parseFunction(def);
let deps = [...pf[0].RawStmt.stmt.CreateFunctionStmt.parameters.map(p => this.parsedTypeDep(p.FunctionParameter.argType))];
this.addCmd(this.dropFunctionCmd(pf[0].RawStmt.stmt.CreateFunctionStmt), [], deps, `function.${name}`);
}
generate(from, to) {
const typediff = objdiff(from.types, to.types);
for (let k of typediff.add) {
this.createType(k, to.types[k]);
}
for (let k of typediff.change) {
this.alterType(k, from.types[k], to.types[k], from);
}
for (let k of typediff.remove) {
this.dropType(k);
}
const tablediff = objdiff(from.tables, to.tables);
for (let k of tablediff.add) {
this.createTable(k, to.tables[k]);
}
for (let k of tablediff.change) {
this.alterTable(k, from.tables[k], to.tables[k]);
}
for (let k of tablediff.remove) {
this.dropTable(k, from.tables[k]);
}
const functiondiff = objdiff(from.functions, to.functions, funcdiff);
for (let k of functiondiff.add) {
this.createFunction(k, to.functions[k]);
}
for (let k of functiondiff.change) {
this.alterFunction(k, from.functions[k], to.functions[k]);
}
for (let k of functiondiff.remove) {
this.dropFunction(k, from.functions[k]);
}
return this.sortCmds();
}
}
module.exports = generate;
function generate(from, to) {
let g = new Generator();
return g.generate(from, to);
}
| 28.469767 | 127 | 0.615831 |
1320ee5448e63585cf983b93fab789430d888395 | 489 | js | JavaScript | server/models/category.js | tonykevin/restserver | e7134a0b1d28ab0cf943928e93a104e1638c1e2b | [
"MIT"
] | null | null | null | server/models/category.js | tonykevin/restserver | e7134a0b1d28ab0cf943928e93a104e1638c1e2b | [
"MIT"
] | 4 | 2020-07-16T21:50:02.000Z | 2022-01-22T04:23:49.000Z | server/models/category.js | tonykevin/restserver | e7134a0b1d28ab0cf943928e93a104e1638c1e2b | [
"MIT"
] | null | null | null | const { model, Schema } = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')
const categorySchema = new Schema({
description: {
type: String,
unique: true,
required: [true, 'description is required']
},
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: [true, 'user is required']
}
})
categorySchema.plugin(uniqueValidator, { message: '{PATH} must be unique' })
module.exports = model('Category', categorySchema)
| 23.285714 | 76 | 0.676892 |
1321b34ef0610374c1a598d8dea26fe570e9d3a8 | 4,728 | js | JavaScript | src/store/modules/user.js | Hchengming/baaowei-kfq | 92c78844094660fe3b4234cbba1b9cf59106a171 | [
"MIT"
] | null | null | null | src/store/modules/user.js | Hchengming/baaowei-kfq | 92c78844094660fe3b4234cbba1b9cf59106a171 | [
"MIT"
] | null | null | null | src/store/modules/user.js | Hchengming/baaowei-kfq | 92c78844094660fe3b4234cbba1b9cf59106a171 | [
"MIT"
] | null | null | null | import { userLogin, getInfo } from '@/api/ApiUser'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { asyncRoutes } from 'mock/router'
import store from '@/store'
import { filterAsyncRoutes } from '@/store/modules/permission'
const state = {
token: getToken(),
name: '',
avatar: '',
introduction: '',
menu: [],
roles: [],
layout: 1,
drawer: false,
drawerfeedback: false,
tel: false,
layoutwidth: '10px',
emailurl: '',
searchurl: '',
applicationData: [],
resolution: true,
// 常用功能
cygn: [],
application: [],
allMenus: [],
quhui: false
}
const mutations = {
/**
* 分辨率
*/
SET_RESOLUTION: (state, resolution) => {
state.resolution = resolution
},
/**
* 分辨率
*/
SET_CYGN: (state, cygn) => {
state.cygn = cygn
},
SET_APPLICATION: (state, application) => {
state.application = application
},
/**
* 一张图地址
*/
SET_YZTURL: (state, yzturl) => {
state.yzturl = yzturl
},
/* 切换意见反馈显示*/
SET_DRAWERFEEDBACK: (state, drawerfeedback) => {
state.drawerfeedback = drawerfeedback
},
/* 切换通讯录显示*/
SET_TEL: (state, tel) => {
state.tel = tel
},
/* 切换取回显示*/
SET_QUHUI: (state, quhui) => {
state.quhui = quhui
},
SET_TOKEN: (state, token) => {
state.token = token
},
SET_INTRODUCTION: (state, introduction) => {
state.introduction = introduction
},
SET_NAME: (state, name) => {
state.name = name
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
},
SET_MENU: (state, menu) => {
state.menu = menu
}
}
const actions = {
// user login
login({ commit }, userInfo) {
const { account, password, ticket } = userInfo
return new Promise((resolve, reject) => {
userLogin({ account: (account || '').trim(), password: password, ticket: ticket }).then(response => {
const { data } = response
setToken(data.token)
localStorage.ticket = data.ticket
localStorage.ip = data.ip
localStorage.uid = data.userId
localStorage.uname = data.urName
// TODO:为了登录跳转暂时固定写死
let roles = ['editor']
if (data.isAdmin === 1) {
roles = ['admin']
}
data.roles = roles
localStorage.userInfo = JSON.stringify(data)
localStorage.menu = JSON.stringify(filterAsyncRoutes(asyncRoutes, roles))
commit('SET_TOKEN', data.token)
resolve()
}).catch(error => {
reject(error)
})
})
},
// 获取用户信息
getInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfo(state.token).then(response => {
const { data } = response
if (!data) {
reject('验证失败,请重新登录.')
}
const { roles, name, avatar, introduction, menu } = data
// roles must be a non-empty array
if (!roles || roles.length <= 0) {
reject('角色信息缺失,请重新登录!')
}
commit('SET_NAME', name)
commit('SET_AVATAR', avatar)
commit('SET_INTRODUCTION', introduction)
commit('SET_MENU', menu)
resolve(data)
}).catch(error => {
reject(error)
})
})
},
// 用户退出
// eslint-disable-next-line no-unused-vars
logout({ commit, state, dispatch }) {
// eslint-disable-next-line no-unused-vars
return new Promise((resolve, reject) => {
// TODO:不需要调用登录接口
// logout(state.token).then(() => {
commit('SET_TOKEN', '')
resetRouter()
localStorage.clear()
removeToken()
// 重置角色
store.dispatch('permission/setRoles', '')
// 重置访问过的标签
store.dispatch('tagsView/delAllViews', null, { root: true })
// 删除所有Iframe
store.dispatch('Iframe/delAllIframe')
resolve()
// }).catch(error => {
// reject(error)
// })
})
},
// 移除TOKEN
resetToken({
commit
}) {
return new Promise(resolve => {
localStorage.clear()
commit('SET_TOKEN', '')
removeToken()
resolve()
})
},
// 动态修改权限
changeRoles({
commit,
dispatch
}, role) {
return new Promise(async resolve => {
const token = role + '-token'
commit('SET_TOKEN', token)
setToken(token)
const {
roles
} = await dispatch('getInfo')
resetRouter()
// 根据角色生成路由
const accessRoutes = await dispatch('permission/generateRoutes', roles, {
root: true
})
// 动态添加可访问路由
router.addRoutes(accessRoutes)
// 重置访问过的标签
dispatch('tagsView/delAllViews', null, {
root: true
})
resolve()
})
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
| 20.828194 | 107 | 0.563029 |
1321ea92b65dce178f6886d51390debe8e694758 | 1,052 | js | JavaScript | source/js/modules/fieldsettoggleview.js | BBCVisualJournalism/newsspec_8747_aidan | 3e48bc810b83fa97f819be56e595b77761860f85 | [
"Apache-2.0"
] | null | null | null | source/js/modules/fieldsettoggleview.js | BBCVisualJournalism/newsspec_8747_aidan | 3e48bc810b83fa97f819be56e595b77761860f85 | [
"Apache-2.0"
] | null | null | null | source/js/modules/fieldsettoggleview.js | BBCVisualJournalism/newsspec_8747_aidan | 3e48bc810b83fa97f819be56e595b77761860f85 | [
"Apache-2.0"
] | null | null | null | define(
['newspec_template/js/bootstrap'],
function(bootstrap) {
var $ = bootstrap.$,
FieldsetToggleView;
FieldsetToggleView = function(el) {
this.$el = $(el);
this.$el.find('input:checked').parent().addClass('is-checked');
// TODO: Set focus when clicking an input?
// TODO: Clear focus class when focus leaves the fieldset
// FIXME: Focusing is the same as changing checked element
this.$el.on('change', 'input', $.proxy(this, 'onChange'));
this.$el.on('focus', 'input', $.proxy(this, 'onFocus'));
};
FieldsetToggleView.prototype.onChange = function(e) {
this.$el.find('.is-checked').removeClass('is-checked');
$(e.currentTarget).parent().toggleClass('is-checked', e.target.checked);
};
FieldsetToggleView.prototype.onFocus = function(e) {
this.$el.find('.is-focused').removeClass('is-focused');
$(e.currentTarget).parent()
.addClass('is-focused', e.target.checked);
};
return FieldsetToggleView;
});
| 30.057143 | 80 | 0.615019 |
1321fa7af692c92525147d86dcf6f7979eb06c22 | 75 | js | JavaScript | app/components/origami-index/component.js | knownasilya/paper-origami | dcb351b5bfe051237d001d7692461e2d155fb4a4 | [
"MIT"
] | 1 | 2017-06-04T03:11:31.000Z | 2017-06-04T03:11:31.000Z | app/components/origami-index/component.js | knownasilya/milligram-app | dcb351b5bfe051237d001d7692461e2d155fb4a4 | [
"MIT"
] | 1 | 2017-07-06T14:47:10.000Z | 2017-07-06T14:47:56.000Z | app/components/origami-index/component.js | knownasilya/milligram-app | dcb351b5bfe051237d001d7692461e2d155fb4a4 | [
"MIT"
] | null | null | null | export { default } from 'paper-origami/components/origami-index/component'; | 75 | 75 | 0.8 |
132240ca9c289e5d1dc120748fc9b49b560c4b00 | 14,972 | js | JavaScript | lib/assets/javascripts/cartodb/table/header/share_dialog.js | kod3r/cartodb | 6447964932733ff3205e1d3ba4319b6a83f0d04f | [
"BSD-4-Clause"
] | 1 | 2015-03-15T23:10:32.000Z | 2015-03-15T23:10:32.000Z | lib/assets/javascripts/cartodb/table/header/share_dialog.js | kod3r/cartodb | 6447964932733ff3205e1d3ba4319b6a83f0d04f | [
"BSD-4-Clause"
] | null | null | null | lib/assets/javascripts/cartodb/table/header/share_dialog.js | kod3r/cartodb | 6447964932733ff3205e1d3ba4319b6a83f0d04f | [
"BSD-4-Clause"
] | null | null | null |
/**
* Shows a dialog to share a map view.
*
* var share_view = new ShareDialog({
* vis: visualization_model,
* user: user_model
* })
*
* - It needs an user and visualization model.
*/
cdb.admin.ShareDialog = cdb.admin.BaseDialog.extend({
_TEXTS: {
title: _t('Publish your visualization'),
close: _t('Close')
},
options: {
vizjson_url: 'http://<%= host %>/api/v2/viz/<%= id %>/viz.json'
},
_KEYS: {
_BITLY: {
key: 'R_de188fd61320cb55d359b2fecd3dad4b',
login: 'vizzuality'
}
},
events: cdb.core.View.extendEvents({
'click .copy ul li a' : '_onMethodClick',
'click .input' : '_onInputClick'
}),
initialize: function() {
this.options = _.extend({
title: this._TEXTS.title,
description: '',
template_name: 'table/header/views/share_dialog_base',
clean_on_hide: true,
ok_button_classes: "button grey",
ok_title: this._TEXTS.close,
modal_type: "",
width: 765,
modal_class: 'share_dialog',
map_title: this.options.vis.get('name'),
map_description: this.options.vis.get('description'),
removable_logo: this.options.user.get("actions").remove_logo,
touch: (!!('ontouchstart' in window) || !!('onmsgesturechange' in window))
}, this.options);
// Do not use the same model than the big map
this.map = this.options.vis.map.clone();
// Create map options to use it in the map-share and the url-share
this.mapOptions = new cdb.core.Model({
title: true,
description: true,
search: false,
shareable: false,
cartodb_logo: true,
layer_selector: this.map.layers.getTotalDataLayers() > 1 ? true : false,
legends: this.map.layers.getTotalDataLegends() > 0 ? true : false,
scrollwheel: true,
sublayer_options: this._getSublayerOptions(),
sql: this.options.vis.map.get('dataLayer').get('query') || ''
});
// Show CartoDB logo in this case
this.map.layers.each(function(layer) {
if (layer.get('cartodb_logo') == false)
layer.set('cartodb_logo', true);
});
// Bindings
this.model = new cdb.core.Model();
this.model.bind('change:url', this._updateURL, this);
this.model.bind('change:method', this._updateSelectedOption, this);
this.map.bind('change', this._changeBounds, this);
this.mapOptions.bind('change', this._onChangeMap, this);
this.mapOptions.bind('change', this._changePreview, this);
// Add related models
this.add_related_model(this.map);
this.add_related_model(this.mapOptions);
this._enableCopy();
this.constructor.__super__.initialize.apply(this);
},
_addWidget: function(widget) {
this.addView(widget);
this.$('.cartodb-map_wrapper').append(widget.render().$el);
},
_addZoomWidget: function() {
var widget = new cdb.geo.ui.Zoom({
model: this.map,
template: this.getTemplate("table/views/zoom_control")
});
this._addWidget(widget);
},
_addLayerWidget: function() {
var widget = new cdb.geo.ui.LayerSelector({
mapView: this.mapView,
template: this.getTemplate("table/views/layer_selector"),
dropdown_template: this.getTemplate("table/views/layer_dropdown")
});
widget.bind("switchChanged", this._updateSublayerOptions, this);
this._addWidget(widget);
},
_addLegendWidget: function() {
var legendWidget = new cdb.admin.mod.LegendWidget ({
map: this.map
});
this._addWidget(legendWidget);
},
_addSearchWidget: function() {
var widget = new cdb.geo.ui.Search({
model: this.map,
template: this.getTemplate("table/views/search_control")
});
this._addWidget(widget);
},
_addSwitches: function(switches) {
var self = this;
_(switches).each(function(prop) {
var className = '.' + prop;
var sw = new cdb.forms.Switch({
model: self.mapOptions,
property: prop
});
self.addView(sw);
self.$(className).append(sw.render().el);
});
},
_addMapView: function() {
var self = this;
setTimeout(function() {
var mapViewClass = cdb.admin.LeafletMapView;
if (self.map.get('provider') === 'googlemaps') {
mapViewClass = cdb.admin.GoogleMapsMapView;
}
var el = $('<div>').addClass('cartodb-map');
self.$('.cartodb-map_wrapper').prepend(el);
self.mapView = new mapViewClass({
el: el,
map: self.map
});
self.addView(self.mapView);
self._addLayerWidget();
self._addLegendWidget();
// trigger this change to set map bounds in the url that are get from mapView
self.map.trigger('change');
// Being added layer-selector and legend change preview map checking
// if they have to be showed.
self._changePreview();
}, 300);
},
_getSublayerOptions: function() {
var layers = this.map.layers.filter(function(lyr) {
return _.contains(['CartoDB', 'torque'], lyr.get('type'));
});
return _.map(layers, function(layer) {
return layer.get("visible");
}).join("|").replace(/false/g, 0).replace(/true/g, 1);
},
_updateSublayerOptions: function() {
var sublayer_options = this._getSublayerOptions();
this.mapOptions.set("sublayer_options", sublayer_options);
},
_showTorqueWarning: function() {
var layers = this.map.layers.getLayersByType('torque');
if (layers.length) {
this.$('.torque_warning').fadeIn();
}
},
render_content: function() {
this._addZoomWidget();
this._addSearchWidget();
this._addSwitches(['title', 'description', 'search', 'shareable', 'cartodb_logo', 'layer_selector', 'legends', 'scrollwheel']);
this._addMapView();
this._showTorqueWarning();
// Set default method
this.model.set("method", "url");
// Send mixpanel event
cdb.god.trigger('mixpanel', 'Click Publish Visualization');
cdb.god.trigger('mixpanel_people', {'publish_visualization_last_clicked': new Date()});
return this;
},
_onInputClick: function(e) {
e.preventDefault();
e.stopPropagation();
var $input = $(e.target).find("input")[0] ? $(e.target).find("input") : $(e.target)
$input.select();
},
_onMethodClick: function(e) {
e.preventDefault();
e.stopPropagation();
var $link = $(e.target);
var method = $link.attr("data-method");
this.model.set("method", method);
},
_updateURL: function(obj, url) {
$url = this.$('.url');
if (url === "") {
$url.addClass('loading');
} else {
$url.removeClass('loading');
}
if ($url.is('input')) {
this.$('.url').val(url);
} else {
this.$('.url').text(url);
}
},
_updateSelectedOption: function(obj, method) {
this.$el.find(".copy .input ul li.selected").removeClass("selected");
this.$el.find(".copy .input ul li a[data-method='" + method + "']").parent().addClass("selected");
if (method == "url") this._setShortURL();
else if (method == "embed") this._setEmbedURL();
else if (method == "api") this._setAPIURL();
},
/*
* Enables copy functionality.
*/
_enableCopy: function(active) {
var self = this;
setTimeout(function() { // Hack for ZeroClipboard, it doesn't like effects :S
self.$el.find("a.copy").zclip({
path: "/assets/ZeroClipboard.swf",
copy: function(){
return $(this).parent().find("input").val();
}
})
}, 500);
// Tipsy tooltip ready!
this.$el.find(".zclip")
.tipsy({
gravity: 's',
live: true,
fade: true,
title: function() {
return _t("Copy this");
}
});
// Prevent url hash error
this.$el.find("a.tooltip").click(function(ev) {
ev.preventDefault();
});
},
_setAPIURL: function() {
var opts = { host: location.host, id: this.options.vis.get('id') };
var url = _.template(this.options.vizjson_url)(opts);
this.model.set("url", url);
},
_onChangeMap: function() {
var self = this;
var method = this.model.get("method");
if (method == "embed") this._setEmbedURL();
else if (method == "url") {
clearTimeout(this.pid);
this.pid = setTimeout(function() {
self._setShortURL();
}, 500);
}
},
_setEmbedURL: function() {
if (this.model.get("method") != "embed") return;
var tableUrl = this.options.vis.embedURL()
, opts = _.map(this.mapOptions.attributes, function(v, k) {
return k + "=" + encodeURIComponent(v);
})
, self = this;
opts = opts.join('&');
var origin = "http://" + location.host;
var url = "<iframe width='100%' height='520' frameborder='0' src='" + origin + tableUrl + "?" + opts + "'></iframe>";
if ($url.is('input')) {
this.$('.url').val(url);
} else {
this.$('.url').text(url);
}
this.model.set("url", url);
},
_setShortURL: function() {
var self = this;
if (!this.localStorage) this.localStorage = new cdb.admin.localStorage('cartodb_urls');
var
tableUrl = this.options.vis.embedURL(),
opts = _.map(this.mapOptions.attributes, function(v, k) { return k + "=" + encodeURIComponent(v); }),
origin = "http://" + location.host; // share urls are always HTTP
opts = opts.join('&');
opts = opts.replace(/'/g, "%27"); // Encode the single quotes
var url = origin + tableUrl + "?" + opts;
// If we already have retrieved this url, set it. if not, fetch from bitly
var storedShortURL = this.localStorage.search(url);
if (storedShortURL) {
this.model.set("url", storedShortURL);
} else {
this._requestShortURL(url);
}
},
_setSQL: function() {
var sql = this.options.map.get('dataLayer').get('query') || '';
this.mapOptions.set({
sql: sql
});
},
_changeBounds: function() {
var self = this;
var bounds = self.map.getViewBounds();
if(bounds) {
if(self.map.getZoom() <= 3) {
self.mapOptions
.unset('sw_lat')
.unset('sw_lon')
.unset('ne_lat')
.unset('ne_lon')
var c = self.map.get('center');
self.mapOptions.set({
zoom: self.map.getZoom(),
center_lat: c[0],
center_lon: c[1]
});
} else {
self.mapOptions
.unset('zoom')
.unset('center_lon')
.unset('center_lat')
self.mapOptions.set({
sw_lat: bounds[0][0],
sw_lon: bounds[0][1],
ne_lat: bounds[1][0],
ne_lon: bounds[1][1]
});
}
}
},
// change the map preview showing how it will look
_changePreview: function() {
var title = this.mapOptions.get('title')
, description = this.mapOptions.get('description')
, shareable = this.mapOptions.get('shareable')
, search = this.mapOptions.get('search')
, layer_selector = this.mapOptions.get('layer_selector')
, legends = this.mapOptions.get('legends')
, scrollwheel = this.mapOptions.get('scrollwheel')
, cartodb_logo = this.mapOptions.get('cartodb_logo');
var $title = this.$('div.cartodb-header h1');
var $description = this.$('div.cartodb-header p');
var $social = this.$('div.cartodb-header div.social');
var $search = this.$('div.cartodb-searchbox');
var $layer_selector = this.$('div.cartodb-layer-selector-box');
var $legends = this.$('div.cartodb-legends');
var $logo = this.$('div.cartodb-logo');
var $cartodb_text = this.$('div.cartodb-text');
function toggle(condition, $el) {
condition ? $el.fadeIn(250) : $el.fadeOut(250);
}
toggle(title, $title);
toggle(description, $description);
toggle(shareable, $social);
toggle(search, $search);
toggle(layer_selector, $layer_selector);
toggle(legends, $legends);
toggle(cartodb_logo, $logo);
// this.$('div.cartodb-logo')[cartodb_logo ? 'show':'hide']();
if (!title && !description && !shareable) {
this.$('div.cartodb-header').fadeOut(200);
} else {
this.$('div.cartodb-header').fadeIn(200);
}
// If logo is not showed, some elements need to be moved
// or hiden
this.$('div.cartodb-map_wrapper')[cartodb_logo ? 'removeClass' : 'addClass']('no-logo')
var self = this;
// Check map position if the properties change
// (we use a timeout to wait for the cartodb-header fadeOut transition)
setTimeout(function() {
self._setMapPosition();
}, 300);
if (!scrollwheel) this.map.disableScrollWheel();
else this.map.enableScrollWheel();
},
// Don't positionate the map below the header, just check
// if it is visible or not and then calculate the necessary px
_setMapPosition: function() {
var header_h = this.$('div.cartodb-header').is(":visible")
? this.$('div.cartodb-header').outerHeight()
: 0;
this.$("div.cartodb-map").css({
top: header_h
});
},
_requestShortURL: function(url) {
var self = this;
this.model.set("url", '');
$.ajax({
url:"https://api-ssl.bitly.com/v3/shorten?longUrl=" + encodeURIComponent(url)+ "&login=" + this._KEYS._BITLY.login + "&apiKey=" + this._KEYS._BITLY.key,
type:"GET",
async: false,
dataType: 'jsonp',
success: function(res) {
self._onRequestShortURLSuccess(res, url);
},
error: function(e) {
self._onRequestShortURLError(url);
}
});
},
_onRequestShortURLSuccess: function(res, url) {
if(this.model.get("method") === 'url') {
if(res.status_code && res.status_code == "200") {
var obj = {};
obj[url] = 'http://cdb.io/'+ res.data.hash;
this.localStorage.add(obj);
this.model.set("url", obj[url]);
} else {
this.model.set("url", url);
}
}
},
_onRequestShortURLError: function(url) {
this.model.set("url", url);
}
});
| 27.985047 | 160 | 0.558843 |
13233172fa08569c4c7193f4fd2ed19a34afc14f | 1,356 | js | JavaScript | 07.TechFundamentalsWithJS/26.BasicCRUDLab/Skeleton/controllers/home-controller.js | AngelMilovski/SuftUniLearning | 3628168548739aa4e1f60578eb4413e8ca799fe4 | [
"MIT"
] | null | null | null | 07.TechFundamentalsWithJS/26.BasicCRUDLab/Skeleton/controllers/home-controller.js | AngelMilovski/SuftUniLearning | 3628168548739aa4e1f60578eb4413e8ca799fe4 | [
"MIT"
] | null | null | null | 07.TechFundamentalsWithJS/26.BasicCRUDLab/Skeleton/controllers/home-controller.js | AngelMilovski/SuftUniLearning | 3628168548739aa4e1f60578eb4413e8ca799fe4 | [
"MIT"
] | null | null | null | const Product = require('../models/Product');
module.exports = {
getIndex: function (req, res) {
Product
.find({})
.then((products) => {
return res.render('index', {
products
});
})
.catch(err => console.log(err));
},
getCreate: function (req, res) {
return res.render('create');
},
postCreate: function (req, res) {
let product = req.body;
console.log(product);
Product
.create(product)
.then(() => {
return res.redirect('/');
})
.catch(err => console.log(err));
},
getEdit: function (req, res) {
let id = req.params.id;
Product
.findById(id)
.then((product) => {
return res.render('edit', {
product
});
});
},
postEdit: function (req, res) {
let newProduct = req.body;
let id = req.params.id;
Product
.findByIdAndUpdate(id, newProduct)
.then(() => {
return res.redirect('/');
})
.catch(err => console.log(err));
},
getDelete: function (req, res) {
let id = req.params.id;
return res.render('delete', {id});
},
postDelete: function (req, res) {
let id = req.params.id;
Product
.findByIdAndRemove(id)
.then(() => {
return res.redirect('/');
})
.catch(err => console.log(err));
}
}; | 22.6 | 45 | 0.516224 |
132399fabde5e08dd3141ad5e50e4204174db530 | 5,837 | js | JavaScript | app/tests/game.server.controller.test.js | rolfst/hangman | cc574c7bc5164173c8df63b4fa542e83215bd049 | [
"MIT"
] | null | null | null | app/tests/game.server.controller.test.js | rolfst/hangman | cc574c7bc5164173c8df63b4fa542e83215bd049 | [
"MIT"
] | null | null | null | app/tests/game.server.controller.test.js | rolfst/hangman | cc574c7bc5164173c8df63b4fa542e83215bd049 | [
"MIT"
] | null | null | null | /**
* Created by rolf on 12-2-15.
*/
"use strict";
var chai = require('chai')
, expect = chai.expect
, sinon = require('sinon')
, sinonChai = require('sinon-chai')
, controller = require('../controllers/game')
, mongoose = require('mongoose')
, Word = mongoose.model('Word')
, Game = mongoose.model('Game')
;
chai.use(require('chai-as-promised'));
chai.use(sinonChai);
var word, game;
describe('Games', function(){
before(function(done){
word = new Word({content: "testing"});
word.save(function(){
game = new Game({
word: word
});
// game.save(function(err, game){
done();
// });
});
});
it('testing get all games', function(done){
var req, res, spy;
req = res = {};
game.save(function(){
spy = res.json = sinon.spy();
controller.list(req, res).then(function(res) {
expect(res.json).to.have.been.calledOnce;
done();
});
});
});
it('creation of a new game', function(done){
var req, res;
req = {};
res = {
json_value: {}
, status_value: ''
, message_value: ''
,json: function(value){
this.json_value=value;}
, status: function(code){
this.status_value=code;
return this;
}
, send: function(message){
this.message_value = message;
}
};
controller.create(req, res)
.then(function(res) {
expect(res.json_value).to.be.not.empty;
expect(res.status_value).to.be.equal(201);
done();
});
});
it('creation of an erroneous new game', function(done){
var req, res;
req = {body: {ch:'23'}};
res = {
json_value: null
, status_value: ''
, message_value: ''
,json: function(value){
this.json_value=value;}
, status: function(code){
this.status_value=code;
return this;
}
, send: function(message){
this.message_value = message;
}
};
controller.update(req, res, null, game.id)
.then(function(res) {
//do noting;
},function(res) {
expect(res.json_value).to.be.null;
expect(res.status_value).to.be.equal(400);
done();
});
});
it('should be failure after 10 false tries', function(done){
var req, res;
req={body:{ch: 'l'}};
function verifyControllerActions(arr, attempts, status){
expect(arr[1].tries_left).to.be.equal(attempts);
expect(arr[1].status).to.be.equal(status);
}
game = new Game({word: word});
game.save(function(err, saved){
res = {json_value: {}
, status_value: ''
, message_value: ''
,json: function(value){
this.json_value=value;}
, status: function(code){
this.status_value=code;
return this;
}
};
controller.update(req, res, null, saved.gameId)
.then(function(arr){
verifyControllerActions(arr, 9, 'busy');
req.body.ch='k';
return controller.update(req, res, null, saved.gameId);
})
.then(function(arr){
verifyControllerActions(arr, 8, 'busy');
req.body.ch='p';
return controller.update(req, res, null, saved.gameId);
}, function(err){
console.log(err);
})
.then(function(arr){
verifyControllerActions(arr, 7, 'busy');
req.body.ch='x';
return controller.update(req, res, null, saved.gameId);
})
.then(function(arr){
verifyControllerActions(arr, 6, 'busy');
req.body.ch='q';
return controller.update(req, res, null, saved.gameId);
})
.then(function(arr){
verifyControllerActions(arr, 5, 'busy');
req.body.ch='w';
return controller.update(req, res, null, saved.gameId);
})
.then(function(arr){
verifyControllerActions(arr, 4, 'busy');
req.body.ch='o';
return controller.update(req, res, null, saved.gameId);
})
.then(function(arr){
verifyControllerActions(arr, 3, 'busy');
req.body.ch='y';
return controller.update(req, res, null, saved.gameId);
})
.then(function(arr){
verifyControllerActions(arr, 2, 'busy');
req.body.ch='v';
return controller.update(req, res, null, saved.gameId);
})
.then(function(arr){
verifyControllerActions(arr, 1, 'busy');
req.body.ch='z';
return controller.update(req, res, null, saved.gameId);
})
.then(function(arr){
verifyControllerActions(arr, 0, 'failure');
expect(arr[0].status_value).to.be.equal(400);
done();
}, function(err){
console.log(err) ;
done();
});
});
});
after(function(done){
Game.remove().exec();
Word.remove().exec();
done();
})
});
| 32.427778 | 71 | 0.458455 |
1324371b567d5204c9cd93e7955b705be6e635d2 | 166 | js | JavaScript | postcss.config.js | JoelEllis/Plaincheck | 09982277adb2019e7b4bf4ccdd954d786a307f8f | [
"MIT"
] | null | null | null | postcss.config.js | JoelEllis/Plaincheck | 09982277adb2019e7b4bf4ccdd954d786a307f8f | [
"MIT"
] | null | null | null | postcss.config.js | JoelEllis/Plaincheck | 09982277adb2019e7b4bf4ccdd954d786a307f8f | [
"MIT"
] | null | null | null | module.exports = {
sourceMap: false,
plugins: [
require("postcss-preset-env")({stage: 4}),
require("autoprefixer")(),
require("postcss-csso")
]
};
| 16.6 | 46 | 0.60241 |
13254dc5ba095a165db069d1b0dd7e68cbacba42 | 5,864 | js | JavaScript | src/Emoji0x0038.js | hamlim/react-android-emoji | 76afaa81d75888f146d4faf7a48ccfc8e23f91b7 | [
"Apache-2.0"
] | 1 | 2020-10-12T13:21:57.000Z | 2020-10-12T13:21:57.000Z | src/Emoji0x0038.js | hamlim/react-android-emoji | 76afaa81d75888f146d4faf7a48ccfc8e23f91b7 | [
"Apache-2.0"
] | 6 | 2021-03-09T10:07:35.000Z | 2022-02-26T13:38:37.000Z | src/Emoji0x0038.js | hamlim/react-android-emoji | 76afaa81d75888f146d4faf7a48ccfc8e23f91b7 | [
"Apache-2.0"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require("react");
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _extends() {
_extends =
Object.assign ||
function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function Emoji0x0038(props) {
return _react2.default.createElement(
"svg",
_extends(
{
enableBackground: "new 0 0 128 128",
viewBox: "0 0 128 128"
},
props
),
_react2.default.createElement(
"linearGradient",
{
id: "b",
x1: 5.5161,
x2: 118.82,
y1: 5.2803,
y2: 119.05,
gradientUnits: "userSpaceOnUse"
},
_react2.default.createElement("stop", {
stopColor: "#81D4FA",
offset: 0
}),
_react2.default.createElement("stop", {
stopColor: "#0094D6",
offset: 1
})
),
_react2.default.createElement("path", {
d:
"m116 124h-104c-4.42 0-8-3.58-8-8v-104c0-4.42 3.58-8 8-8h104c4.42 0 8 3.58 8 8v104c0 4.42-3.58 8-8 8z",
fill: "url(#b)"
}),
_react2.default.createElement(
"g",
{
opacity: 0.2
},
_react2.default.createElement("path", {
d:
"m116 7c2.76 0 5 2.24 5 5v104c0 2.76-2.24 5-5 5h-104c-2.76 0-5-2.24-5-5v-104c0-2.76 2.24-5 5-5h104m0-3h-104c-4.42 0-8 3.58-8 8v104c0 4.42 3.58 8 8 8h104c4.42 0 8-3.58 8-8v-104c0-4.42-3.58-8-8-8z",
fill: "#424242"
})
),
_react2.default.createElement(
"linearGradient",
{
id: "a",
x1: 21.247,
x2: 106.25,
y1: 20.744,
y2: 106.74,
gradientUnits: "userSpaceOnUse"
},
_react2.default.createElement("stop", {
stopColor: "#C2ECFF",
offset: 0
}),
_react2.default.createElement("stop", {
stopColor: "#BDEAFE",
offset: 0.157
}),
_react2.default.createElement("stop", {
stopColor: "#AEE3FA",
offset: 0.3484
}),
_react2.default.createElement("stop", {
stopColor: "#95D7F5",
offset: 0.5578
}),
_react2.default.createElement("stop", {
stopColor: "#73C7ED",
offset: 0.7789
}),
_react2.default.createElement("stop", {
stopColor: "#49B3E3",
offset: 1
})
),
_react2.default.createElement("path", {
d:
"m101 109h-74c-4.42 0-8-3.58-8-8v-74c0-4.42 3.58-8 8-8h74c4.42 0 8 3.58 8 8v74c0 4.42-3.58 8-8 8z",
fill: "url(#a)"
}),
_react2.default.createElement(
"g",
{
opacity: 0.2
},
_react2.default.createElement("path", {
d:
"m64 26c6.94 0 12.45 1.85 16.51 5.54s6.1 8.69 6.1 14.99c0 3.62-0.93 6.85-2.79 9.68s-4.4 5.05-7.62 6.68c3.86 1.8 6.83 4.25 8.92 7.37 2.08 3.12 3.12 6.64 3.12 10.57 0 6.5-2.2 11.66-6.6 15.47s-10.26 5.72-17.58 5.72c-7.35 0-13.23-1.91-17.65-5.74s-6.63-8.97-6.63-15.44c0-3.96 1.05-7.52 3.15-10.67s5.05-5.57 8.84-7.27c-3.18-1.63-5.7-3.85-7.54-6.68-1.85-2.83-2.77-6.05-2.77-9.68 0-6.3 2.03-11.29 6.1-14.99 4.04-3.7 9.53-5.55 16.44-5.55m0.05 32.06c3.15 0 5.65-1 7.49-3s2.77-4.69 2.77-8.08c0-3.22-0.93-5.87-2.79-7.95s-4.37-3.12-7.52-3.12-5.64 0.99-7.47 2.97-2.74 4.68-2.74 8.1c0 3.39 0.92 6.08 2.77 8.08 1.84 2 4.34 3 7.49 3m0 34.08c3.73 0 6.63-1.05 8.71-3.15s3.12-5.03 3.12-8.79c0-3.66-1.09-6.61-3.28-8.86s-5.07-3.38-8.66-3.38-6.46 1.12-8.61 3.35c-2.15 2.24-3.23 5.2-3.23 8.89 0 3.62 1.06 6.52 3.18 8.69s5.04 3.25 8.77 3.25m-0.05-69.14c-7.65 0-13.86 2.13-18.48 6.32-4.7 4.27-7.08 10.06-7.08 17.21 0 4.2 1.1 8.01 3.26 11.32 1.2 1.83 2.65 3.46 4.34 4.86-2.24 1.6-4.12 3.54-5.62 5.78-2.42 3.63-3.65 7.78-3.65 12.33 0 7.35 2.58 13.31 7.67 17.71 4.96 4.29 11.56 6.47 19.62 6.47 8.02 0 14.6-2.17 19.54-6.45 5.07-4.39 7.64-10.36 7.64-17.74 0-4.51-1.22-8.63-3.63-12.23-1.5-2.24-3.41-4.2-5.7-5.84 1.72-1.41 3.2-3.04 4.41-4.89 2.18-3.31 3.29-7.13 3.29-11.33 0-7.15-2.38-12.94-7.08-17.21-4.62-4.18-10.85-6.31-18.53-6.31zm0.05 32.06c-2.3 0-4.03-0.66-5.29-2.03-1.33-1.44-1.97-3.41-1.97-6.04 0-2.66 0.64-4.65 1.95-6.07 1.25-1.35 2.97-2.01 5.26-2.01 2.31 0 3.99 0.68 5.28 2.12 1.37 1.53 2.03 3.47 2.03 5.95 0 2.63-0.65 4.6-1.97 6.04-1.26 1.37-2.99 2.04-5.29 2.04zm0 34.08c-2.91 0-5.08-0.77-6.62-2.35-1.56-1.6-2.32-3.76-2.32-6.59 0-2.91 0.78-5.14 2.39-6.81 1.58-1.64 3.68-2.43 6.45-2.43s4.9 0.81 6.51 2.47c1.63 1.69 2.43 3.9 2.43 6.78 0 2.96-0.74 5.15-2.25 6.68-1.52 1.51-3.67 2.25-6.59 2.25z",
fill: "#424242"
})
),
_react2.default.createElement("path", {
d:
"m86.61 46.52c0 3.62-0.93 6.85-2.79 9.68s-4.4 5.05-7.62 6.68c3.86 1.8 6.83 4.25 8.92 7.37 2.08 3.12 3.12 6.64 3.12 10.57 0 6.5-2.2 11.66-6.6 15.47s-10.26 5.72-17.58 5.72c-7.35 0-13.23-1.91-17.65-5.74s-6.63-8.97-6.63-15.44c0-3.96 1.05-7.52 3.15-10.67s5.05-5.57 8.84-7.27c-3.18-1.63-5.7-3.85-7.54-6.68-1.85-2.83-2.77-6.05-2.77-9.68 0-6.3 2.03-11.29 6.1-14.99 4.04-3.69 9.53-5.54 16.44-5.54 6.94 0 12.45 1.85 16.51 5.54s6.1 8.68 6.1 14.98zm-10.72 33.69c0-3.66-1.09-6.61-3.28-8.86s-5.07-3.38-8.66-3.38-6.46 1.12-8.61 3.35c-2.15 2.24-3.23 5.2-3.23 8.89 0 3.62 1.06 6.52 3.18 8.69s5.04 3.25 8.76 3.25c3.73 0 6.63-1.05 8.71-3.15 2.09-2.1 3.13-5.03 3.13-8.79zm-1.58-33.23c0-3.22-0.93-5.87-2.79-7.95s-4.37-3.12-7.52-3.12-5.64 0.99-7.47 2.97-2.74 4.68-2.74 8.1c0 3.39 0.92 6.08 2.77 8.08s4.34 3 7.49 3 5.65-1 7.49-3c1.85-2 2.77-4.69 2.77-8.08z",
fill: "#FAFAFA"
})
);
}
exports.default = Emoji0x0038;
| 42.80292 | 1,780 | 0.566166 |
1325587fc95f35ab087835d9af0d09bc5ec49dbe | 793 | js | JavaScript | App.js | slakat/salud-mental | dc9985503a9c20e8b885222e81b2ac0bf6509328 | [
"MIT"
] | null | null | null | App.js | slakat/salud-mental | dc9985503a9c20e8b885222e81b2ac0bf6509328 | [
"MIT"
] | null | null | null | App.js | slakat/salud-mental | dc9985503a9c20e8b885222e81b2ac0bf6509328 | [
"MIT"
] | null | null | null | (function() {
"use strict";
var App = angular.module("App", [
"App.controllers",
"App.services",
"App.directives",
"App.filters",
"ngRoute",
"ngResource",
"ui.router",
"ngAnimate"
]);
App.run(function($state, $rootScope) {
});
App.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/view1', {
templateUrl: 'view/view1.html',
controller: 'view1Controller'
}).
when('/view2', {
templateUrl: 'view/view2.html',
controller: 'view2Controller'
}).
otherwise({
redirectTo: '/view1'
});
}]);
}());
| 20.868421 | 47 | 0.435057 |
132599b8266594fa3af0ae2709ac2651961534c2 | 176 | js | JavaScript | src/constants/SectionActionTypes.js | ndlib/beehive | a77550811ae2751aa10a9d3e7f8bc9bde8fd872e | [
"Apache-2.0"
] | 3 | 2015-04-15T21:31:28.000Z | 2018-12-14T17:05:47.000Z | src/constants/SectionActionTypes.js | ndlib/beehive | a77550811ae2751aa10a9d3e7f8bc9bde8fd872e | [
"Apache-2.0"
] | 190 | 2015-01-23T19:04:02.000Z | 2022-02-27T01:57:45.000Z | src/constants/SectionActionTypes.js | ndlib/beehive | a77550811ae2751aa10a9d3e7f8bc9bde8fd872e | [
"Apache-2.0"
] | 1 | 2016-02-08T14:17:31.000Z | 2016-02-08T14:17:31.000Z | const keyMirror = require('keymirror')
const SectionActionTypes = keyMirror({
SECTION_SET_SECTION: null,
SECTION_SHOW_WINDOW: false,
})
export default SectionActionTypes
| 19.555556 | 38 | 0.795455 |
1326482dabecf4e84f5bcf04cb1f853121129055 | 786 | js | JavaScript | src/comp/MuiProvider.js | TimSusa/json-cms | 2556249b7ce7af680b6c4727f582f62da54e03e0 | [
"MIT"
] | 1 | 2020-12-07T09:09:59.000Z | 2020-12-07T09:09:59.000Z | src/comp/MuiProvider.js | TimSusa/json-cms | 2556249b7ce7af680b6c4727f582f62da54e03e0 | [
"MIT"
] | null | null | null | src/comp/MuiProvider.js | TimSusa/json-cms | 2556249b7ce7af680b6c4727f582f62da54e03e0 | [
"MIT"
] | null | null | null | import { CssBaseline, createMuiTheme } from '@material-ui/core';
import { ThemeProvider } from '@material-ui/styles';
import React from 'react';
import PropTypes from 'prop-types';
import 'typeface-roboto';
import { darkTheme } from '../themes/dark-theme.js';
import { lightTheme } from '../themes/light-theme.js';
import App from '../app/App';
export default MuiWrappedApp;
MuiWrappedApp.propTypes = {
children: PropTypes.any,
};
MuiWrappedApp.displayName = 'MuiWrappedApp';
function MuiWrappedApp(props) {
const { isChangedTheme = false, children } = props;
const theme = createMuiTheme(isChangedTheme ? darkTheme : lightTheme);
return (
<ThemeProvider theme={theme}>
<CssBaseline />
{children ? children : <App {...props} />}
</ThemeProvider>
);
}
| 27.103448 | 72 | 0.701018 |
132832497bd716c17fb7368cb4d04ece45219461 | 1,225 | js | JavaScript | src/layouts/tokenfactory/components/TokenFactoryStepper/index.js | lightsea90/tokenhub-frontend | f2b23d9085583bc645d31ba4181e4b3d83a16023 | [
"MIT"
] | null | null | null | src/layouts/tokenfactory/components/TokenFactoryStepper/index.js | lightsea90/tokenhub-frontend | f2b23d9085583bc645d31ba4181e4b3d83a16023 | [
"MIT"
] | 10 | 2022-01-18T14:20:41.000Z | 2022-03-27T06:31:21.000Z | src/layouts/tokenfactory/components/TokenFactoryStepper/index.js | lightsea90/tokenhub-frontend | f2b23d9085583bc645d31ba4181e4b3d83a16023 | [
"MIT"
] | null | null | null | /* eslint-disable react/prop-types */
/* eslint-disable prettier/prettier */
import { Card, Grid } from "@mui/material";
import SuiAlert from "components/SuiAlert";
import SuiBox from "components/SuiBox";
import { TokenFactoryContext } from "layouts/tokenfactory/context/TokenFactoryContext";
import { observer } from "mobx-react";
import { useContext } from "react";
import CustomizedSteppers from "./CustomizedSteppers";
const TokenFactoryStepper = (props) => {
const { alert } = props;
const { tokenFactoryStore } = useContext(TokenFactoryContext);
return (
<Grid container justifyContent="center" alignItems="center">
<Grid item xs={8}>
<Card>
<CustomizedSteppers
steps={tokenFactoryStore.steps}
activeStep={tokenFactoryStore.activeStep}
/>
{alert.open && (
<Grid container justifyContent="center" alignItems="center">
<Grid item xs={10}>
<SuiBox>
<SuiAlert color={alert.color}>{alert.message}</SuiAlert>
</SuiBox>
</Grid>
</Grid>
)}
</Card>
</Grid>
</Grid>
);
};
export default observer(TokenFactoryStepper);
| 33.108108 | 87 | 0.617959 |
13284094dbcb25c788ac66ab58884def645116f6 | 2,317 | js | JavaScript | src/emailService.js | bevacqua/campaign | 291b3ce8d2fbfbb0878dc6416d2ee92099878730 | [
"MIT"
] | 506 | 2015-01-09T07:57:32.000Z | 2021-08-05T23:46:12.000Z | src/emailService.js | bevacqua/campaign | 291b3ce8d2fbfbb0878dc6416d2ee92099878730 | [
"MIT"
] | 7 | 2015-01-13T21:05:44.000Z | 2020-09-12T21:46:29.000Z | src/emailService.js | bevacqua/campaign | 291b3ce8d2fbfbb0878dc6416d2ee92099878730 | [
"MIT"
] | 36 | 2015-01-13T20:26:04.000Z | 2022-02-25T13:19:11.000Z | 'use strict';
var contra = require('contra');
function service (options) {
var templateService = require('./templateService.js')(options);
var hydrate = require('./hydrationService.js');
return {
send: function (file, model, done) {
renderer(templateService.render, file, model, true, done);
},
sendString: function (template, model, done) {
renderer(templateService.renderString, template, model, true, done);
},
render: function (file, model, done) {
renderer(templateService.render, file, model, false, done);
},
renderString: function (template, model, done) {
renderer(templateService.renderString, template, model, false, done);
}
};
function renderer (render, template, model, send, done) {
var trap = model.trap || options.trap;
var validation = require('./validationService.js')(trap);
var file = render === templateService.render ? template : null;
contra.series({
validation: contra.curry(validation, model),
hydration: contra.curry(hydrate, file, model, options),
update: contra.curry(contra.waterfall, [
contra.curry(render, template, model),
updateModel
]),
response: providerSend
}, function (err, results) {
if (err) {
done(err);
} else if (send) {
done(null, results ? results.response : results);
} else {
done(null, model.html, model);
}
});
function updateModel (html, next) {
model.html = tweak(formatting(html));
next();
}
function formatting (html) {
return options.formatting ? options.formatting(html) : html;
}
function tweak (html) {
if (trap) { // don't annoy trap recipient with weird glyphs
return html;
}
var rtweaker = /(\{{2,})([\w._-]+)(\}{2,})/g;
if (options.provider.tweakPlaceholder) {
return html.replace(rtweaker, tweaker);
}
return html;
}
function tweaker (all, left, content, right) {
var raw = left.length === 3 && right.length === 3;
return options.provider.tweakPlaceholder(content, raw);
}
function providerSend (next) {
if (send) {
options.provider.send(model, next);
} else {
next();
}
}
}
}
module.exports = service;
| 28.604938 | 75 | 0.606388 |
132a38574ecf0c2088f0d29db936688ee1046a4c | 19,049 | js | JavaScript | test/courseInfo.js | uolcano/necc_final_proj | 52353e110a0aa07b3b009adfe3cd95f733e8d860 | [
"MIT"
] | 1 | 2016-04-11T07:36:10.000Z | 2016-04-11T07:36:10.000Z | test/courseInfo.js | uolcano/necc_final_proj | 52353e110a0aa07b3b009adfe3cd95f733e8d860 | [
"MIT"
] | null | null | null | test/courseInfo.js | uolcano/necc_final_proj | 52353e110a0aa07b3b009adfe3cd95f733e8d860 | [
"MIT"
] | null | null | null | /**
* [createDomStruct 完成容器节点下的节点构建]
* @param {[DOM node]} tmpltElm [模板节点]
* @param {[DOM node]} baseNode [接收节点插入的容器节点]
* @param {[integer]} childNum [插入节点的数目]
* @return {[object]} nodes [映射到待插入的单个DOM节点的节点模板对象]
* *! 注意:要求模板字符串中的${track.propName)中的propName与ajax响应数据项中的属性名相同,
* 并且,HTML结构中的自闭合标签必须以“/>”结尾,否则会出错。
* @dataStructure {[object]} tmpNode [txt是一个完整DOM节点的字符串形式,subTree是每个模板节点的子模板节点列表,模板节点只是对应DOM的一种映射关系]
* --- {
* ------ txt: '',
* ------ subTree: [
* --------- 0:{
* ------------ txt: '',
* ------------ subTree: [0:{txt: '', subTree: [...]}]
* --------- },
* --------- 1:{
* ------------ txt: '',
* ------------ subTree: [0:{txt: '', subTree: [...]), 1:{txt: '', subTree: [...]}]
* --------- }
* ------ ]
* --- }
*/
function createDomStruct(tmpltElm, baseNode, childNum) {
var timeCnt = +new Date();
var htmlStr = maniInnerText(tmpltElm, 'get'); // the string to be converted
var isOp = !0; // !0 for getting root tmpnode, this root tmpnode is a template object
function treeWalker(node) {
var ptnOp = /^<[a-zA-Z0-9]+?.*?[^\/]>/; // for open tag
var ptnEd = /^<\/[a-zA-Z0-9]+?>/; // for close tag
var ptnOpEd = /^<.+?\/>/; // for self closed tag
var ptnTxt = /^[^>].+?(?=<)/; // for text node
var matches = null;
var flag = !0;
var cnt = 30; // prevent the unexpected infinite iteration
while (htmlStr.length && flag && cnt) {
htmlStr = htmlStr.trim(); // throw away the blank characters at the open and end of the string to match
if (matches = ptnEd.exec(htmlStr)) { // match the end tag, and terminate the iteration
htmlStr = RegExp.rightContext;
node.txt += matches[0];
break;
} else if (matches = ptnOp.exec(htmlStr)) { // match the open tag, and
htmlStr = RegExp.rightContext;
if (isOp) { // set the root tmpnode
isOp = !1;
node.txt = matches[0];
arguments.callee(node);
} else { // set the descendant nodes
var sub = { txt: matches[0], subTree: [] };
node.subTree.push(sub);
arguments.callee(sub);
sub = null;
}
} else if (matches = ptnOpEd.exec(htmlStr)) { // match the self closed tag
htmlStr = RegExp.rightContext;
node.subTree.push({ txt: matches[0], subTree: [] });
} else if (matches = ptnTxt.exec(htmlStr)) { // match the text node
htmlStr = RegExp.rightContext;
node.txt += matches[0];
} else { // template structure error
flag = !1;
console.log('Error: Invalid template structure!');
}
cnt--;
}
}
var nodes = { txt: '', subTree: [] };
treeWalker(nodes);
// console.log(nodes);
function getNodeAttr(tmpNode) {
var ptnTag = /^<([a-zA-Z0-9]+)(?=\s*)/; // capture the tag name
var ptnAttr = /^([a-zA-Z\-]+)\s*=\s*[\'\"]\s*(.+?)\s*[\'\"]/; // capture the html attributes
var ptnData = /\$\{track\.(.+?)\}/;
var txt = tmpNode.txt;
var matches = null;
var subMatch = null;
tmpNode.attrs = [];
while (txt.length) {
txt = txt.trim();
if (matches = ptnTag.exec(txt)) { // get the tag name
txt = RegExp.rightContext;
tmpNode.tagName = matches[1];
} else if (matches = ptnAttr.exec(txt)) { // get the attrs key/value pairs
txt = RegExp.rightContext;
var kv = { name: matches[1], value: matches[2] };
if (kv.name === 'class') {
kv.name = 'className';
}
if (ptnData.exec(kv.value)) { // ignore the attrs' value, which need the ajax data to fill
kv.value = '';
}
tmpNode.attrs.push(kv);
kv = null;
} else {
break;
}
}
}
isOp = !0; // mark the root tmpnode
// extract a tmpnode's some key/value pairs as the attributes of the following generated real dom node
function deepProgNode(tmpNode) {
if (isOp) { // set the root tmpnode
isOp = !1;
getNodeAttr(tmpNode);
}
for (var i = 0, len = tmpNode.subTree.length; i < len; i++) { // the tree branch tmpNode
getNodeAttr(tmpNode.subTree[i]);
arguments.callee(tmpNode.subTree[i]);
}
}
deepProgNode(nodes);
// console.log(nodes);
/**
* 优化方案一:利用文档片段,逐个添加DOM结构节点
*/
// function setNodeAttr (tmpNode, domNode) {
// var ptnDs = /^data-/;
// for (var i = 0, len = tmpNode.attrs.length; i < len; i++) {
// if (ptnDs.exec(tmpNode.attrs[i].name)) { // append dataset attribute
// var name = RegExp.rightContext;
// name = name.replace(/-([a-zA-Z0-9])/g, function (m, p) {
// return p.toUpperCase();
// });
// domNode.dataset[name] = tmpNode.attrs[i].value;
// } else {
// domNode[tmpNode.attrs[i].name] = tmpNode.attrs[i].value;
// }
// }
// }
// // generate some real dom nodes, counted as childNum, and then append to the baseNode
// function genDom (tmpNode, pNode) {// the document fragment node used to append into a base node
// var domNode = document.createElement(tmpNode.tagName);
// setNodeAttr(tmpNode, domNode);
// for (var i = 0; i < tmpNode.subTree.length; i++) {
// arguments.callee(tmpNode.subTree[i], domNode);
// }
// pNode.appendChild(domNode);
// }
// for (var i = 0; i < childNum; i++) {// generate some dom nodes of the childNum number
// var docFrag = document.createDocumentFragment();
// genDom(nodes, docFrag);
// baseNode.appendChild(docFrag);
// }
/**
* 优化方案二:利用innerHTML,快速生成DOM子树
*/
var inHtml = '';
for (var i = 0; i < childNum; i++) { // generate some dom nodes of the childNum number
inHtml += maniInnerText(tmpltElm, 'get').replace(/\$\{track\..+?\}/g, '');
}
baseNode.innerHTML = inHtml;
// console.log('timepass:', +new Date() - timeCnt);
return nodes; // return the template node object
}
var ptnTxt = />\s*\$\{track\.(.+?)\}\s*</;
var ptnKv = /([a-zA-Z\-]+)\s*=\s*[\'\"].*\$\{track\.(.+?)\}.*[\'\"]/;
var ptnKvSub = /\s([a-zA-Z\-]+)\s*=\s*[\'\"](.*?\$\{track\.(.+?)\}.*?)[\'\"]/;
function wtNodeAttr(tmpNode, domNode, item, matches) {
for (var i = 0, len = tmpNode.attrs.length; i < len; i++) {
if (tmpNode.attrs[i].name === matches[1]) {
var m = null;
if (m = /^data-(.+)/.exec(matches[1])) { // set the dataset attribute
matches[1] = m[1].replace(/-([a-zA-Z0-9])/g, function(m, p) {
return p.toUpperCase();
});
domNode.dataset[matches[1]] = matches[2].replace(/\$\{track\.(.+?)\}/, item[matches[3]]);
} else {
domNode[matches[1]] = matches[2].replace(/\$\{track\.(.+?)\}/, item[matches[3]]);
}
}
}
}
// matche the ajax data from tempNode, fill into the domNode
function matchData(tmpNode, domNode, item) {
var matches = null;
var txt = tmpNode.txt;
if (matches = ptnTxt.exec(txt)) { // text setting
var inTxt = item[matches[1]];
if (!item[matches[1]]) { // 如果ajax返回数据为空值
switch (matches[1]) {
case 'name':
case 'categoryName':
case 'provider':
case 'description':
inTxt = '暂无';
break;
case 'learnerCount':
case 'price':
inTxt = '0';
break;
default:
inTxt = 'undefined';
break;
}
}
maniInnerText(domNode, 'set', inTxt); // insert text node with the ajax data
}
if (matches = ptnKv.exec(txt)) { // attribute setting
var prevM = matches[0];
var nextM = '';
while (matches = ptnKvSub.exec(prevM)) { // throw away the too long matched string, that not matched exactly
var nextM = matches[0];
var mKv = matches;
if (prevM === nextM) break;
prevM = nextM;
txt = nextM.trim();
}
wtNodeAttr(tmpNode, domNode, item, mKv); // set the attributes filled with the ajax data
}
}
// 模板映射节点对象和DOM节点同步迭代,以ajax返回数据更新DOM节点的数据
function dbNodeTravl(tmpNode, domNode, item) {
matchData(tmpNode, domNode, item);
// }
for (var i = 0, len = tmpNode.subTree.length; i < len; i++) {
matchData(tmpNode.subTree[i], domNode.children[i], item);
arguments.callee(tmpNode.subTree[i], domNode.children[i], item);
}
}
function loadData(tmpNode, baseNode, list) {
for (var i = 0, len = list.length; i < len; i++) {
dbNodeTravl(tmpNode, baseNode.children[i], list[i]);
}
}
function throwExcept() {
console.log('AjaxError: not yet get response.');
}
var tmplts = document.querySelectorAll('.tuj-tmplt');
var tmpNodeObj = [];
var dftCrsItmNum = 20; // 默认加载的课程卡片数
var queryCrsDtNum = dftCrsItmNum; // 初次加载时请求课程卡片数等于加载的卡片节点数
var cards = document.querySelector('.tuj-cards'); // 获取课程信息区域的DOM容器节点
tmpNodeObj.push(createDomStruct(tmplts[0], cards, dftCrsItmNum)); // 获取课程信息区域的模板映射节点对象
loadPgSelr.isFirstLoad = !0; // 加载页面时,首次默认加载选页器
loadCrs();
var hotRank = document.querySelector('.tuj-rank');
tmpNodeObj.push(createDomStruct(tmplts[1], hotRank, 20)); // 默认获取20个热门课程列表项的模板映射节点对象
loadRank();
console.log(tmpNodeObj);
var tabs = document.querySelector('.tuj-tabs');
addHandler(tabs, 'click', clkTabLsnr);
var pgSelr = document.querySelector('.tuj-pgselr');
addHandler(pgSelr, 'click', clkPageLsnr);
addHandler(pgSelr, 'click', switchPageLsnr);
clkAnima(pgSelr);
clkAnima(tabs);
function loadRank() {
var url = 'http://study.163.com/webDev/hotcouresByCategory.htm';
function qryData(url, options) {
var query = url + ((typeof options === 'string' && options.length > 0) ? ('?' + options) : '');
var xhr = new XMLHttpRequest();
try {
xhr.open('get', query);
} catch (e1) {
try {
xhr = new XDomainRequest();
xhr.open('get', query);
console.log('create a cross-origin request for IE');
} catch (e2) {
console.log('Error: create request unsuccessfully.', e2);
}
}
xhr.onload = function(event) {
loadData(tmpNodeObj[1], hotRank, JSON.parse(xhr.responseText));
};
xhr.open('get', query);
xhr.send(null);
}
qryData(url);
// setTimeout(loadRank, 5000);
}
function loadCrs() {
var tabs = document.querySelector('.tuj-tabs');
var seledTab = tabs.querySelector('.tuz-crt');
var type = seledTab.dataset.type;
var pgSelr = document.querySelector('.tuj-pgselr');
var seledPg = pgSelr.querySelector('.tuz-crt');
var pageNo = seledPg.dataset.pageNo;
var preOpt = { type: type, pageNo: pageNo, psize: queryCrsDtNum };
var url = 'http://study.163.com/webDev/couresByCategory.htm';
var options = serialize(preOpt);
// console.log(options);
function getCrsData() {
var res = getServerData.response;
var list = res.list;
// console.log('load course:',res);
if (loadPgSelr.isFirstLoad) {
loadPgSelr(pgSelr, res); // 加载选页器
loadPgSelr.isFirstLoad = !1;
loadPgSelr.totalPage = res.totalPage;
}
// 给cards容器节点下的DOM节点结构插入ajax数据
loadData(tmpNodeObj[0], cards, list);
}
waitResponse(getCrsData, throwExcept, getServerData, url, options);
}
// tab切换
function clkTabLsnr(event) {
var target = getTarget(getEvent(event));
var parent = target.parentNode;
var crtTab = parent.querySelector('.tuz-crt');
if (this !== target) { // 事件目标不是事件处理程序所在对象
if (crtTab !== target) {
crtTab.classList.remove('tuz-crt');
target.classList.add('tuz-crt');
loadCrs();
}
}
}
// 加载选页器
function loadPgSelr(pgSelrElm, response) {
var pages = pgSelrElm.children;
var pageLen = pages.length - 2;
var pageIdx = response.pagination.DEFAULT_PAGE_INDEX;
var totalPg = response.totalPage;
for (var i = 1; i <= pageLen; i++) {
try {
pages[i].classList.remove('tuz-crt');
} catch (e) {
console.log(e);
}
if (i > totalPg) {
pages[i].style.display = 'none';
} else {
pages[i].dataset.pageNo = i;
maniInnerText(pages[i], 'set', i);
if (i === pageIdx) {
pages[i].classList.add('tuz-crt');
}
}
}
}
// 切换选页器
function clkPageLsnr(event) {
var target = getTarget(getEvent(event));
var pgSelr = this;
var pages = pgSelr.children;
var first = pages[0];
var last = pages[pages.length - 1];
var crtPg = this.querySelector('.tuz-crt');
if (target !== this && target !== first && target !== last && target !== crtPg) {
crtPg.classList.remove('tuz-crt');
target.classList.add('tuz-crt');
loadCrs();
}
}
// 前一页和后一页按钮
function refreshPageSelr(pgSelrElm, forwards) {
var pages = pgSelrElm.children;
var len = pages.length; // 0 ~ 9
var totalPg = loadPgSelr.totalPage || (len - 2);
function switchPgSelr(fwds) {
for (var i = 1; i < len - 1; i++) { // just need 1 ~ 8
var tmp = pages[i].dataset.pageNo - 1 + 1 + fwds;
pages[i].dataset.pageNo = tmp;
maniInnerText(pages[i], 'set', tmp);
}
}
if (forwards < 0) {
var lmt = pages[1].dataset.pageNo - 1 + 1;
if (lmt > 1) {
switchPgSelr(forwards);
loadCrs();
}
} else if (forwards > 0) {
lmt = pages[len - 2].dataset.pageNo - 1 + 1;
if (lmt < totalPg) {
switchPgSelr(forwards);
loadCrs();
}
} else {
console.log('not switch page selector');
}
}
function switchPageLsnr(event) {
var target = getTarget(getEvent(event));
var prevBtn = this.children[0];
var nextBtn = this.children[this.children.length - 1];
if (target === prevBtn) {
refreshPageSelr(this, -1);
} else if (target === nextBtn) {
refreshPageSelr(this, 1);
} else {
console.log('not click the forward or back button');
}
}
// 模拟按键效果
function clkAnima(elm) {
function mouseDn(event) {
var target = getTarget(getEvent(event));
if (target !== this) {
try {
target.classList.remove('tuz-clked');
} catch (e) {
console.log(e);
}
target.classList.add('tuz-clked');
}
}
addHandler(elm, 'mousedown', mouseDn);
function mouseUp(event) {
var target = getTarget(getEvent(event));
try {
target.classList.remove('tuz-clked');
} catch (e) {
console.log(e);
}
}
addHandler(elm, 'mouseup', mouseUp);
}
// test snippet
// var arr = extractTmplt(tmplts[0]);
// for (var i = 0, len = arr.length; i < len; i++) {
// // if (i % 2) {
// console.log(arr[i]);
// // }
// };
/**
* 简单方案一:利用String.prototype.split(),先将模板字符串分隔,
* 并替换上需要填充的内容在返回数据项中的属性名;
* 在响应数据处理函数中,将数据替换上,
* 然后通过Array.prototype.join(),中间插入空字符串,完成数据插入,
* 最后写入DOM节点的innerHTML。
* *! 注意:要求模板字符串中的${track.propName)中的propName与ajax响应数据项中的属性名相同
* @dataStructure {[array]} tmpltArr [存储了模板字符串的每一段被分割的子串,偶数项是普通子串不需要被ajax数据替换,奇数项是提取子串处理后对应待填充的ajax数据的属性名称]
* --- [
* ------ 0: 'htmlStr',
* ------ 1: 'propNameStr',
* ------ 2: 'htmlStr',
* ------ 3: 'propNameStr',
* ------ ...
* --- ]
*
*/
// function extractTmplt(tmpltElm) {// the template to be matched should not be opened or ended with a matcheable item
// var timeCnt = +new Date();
// var pattern = /\$\{track\.(.+?)\}/;
// var matches = null;
// var tmpltStr = tmpltElm.innerHTML;
// var tmpltArr = [];
// tmpltArr.tmpltStr = tmpltStr;
// while (matches = pattern.exec(tmpltStr)) {
// var arr = tmpltStr.split(matches[0]);
// tmpltArr.push(arr[0]);
// tmpltArr.push(matches[1]);
// tmpltStr = arr[1];
// }
// tmpltArr.push(RegExp.rightContext);
// // console.log('extractTmplt timepass:', +new Date() - timeCnt);
// return tmpltArr;
// }
// var tmpltArr = extractTmplt(tmplts[0]);
// function getData () {
// var res = getServerData.response;
// var list = res.list;
// var inHtml = '';
// for (var i = 0, len = list.length; i < len; i++) {
// var tmplt = [];
// var idx = 0;
// while (tmpltArr[idx]) {
// tmplt.push((idx % 2) ? (typeof list[i][tmpltArr[idx]] === null ? '' : list[i][tmpltArr[idx]]) : tmpltArr[idx]);
// idx++;
// }
// var tmpltStr = tmplt.join('');
// inHtml += tmpltStr;
// }
// cards.innerHTML = inHtml;
// }
// function except () {
// console.log('not get!');
// }
// waitResponse(getData, except, getServerData, url, options);
/**
* 简单方案二:利用
*
* *! 注意:要求模板字符串中的${track.propName)中的propName与ajax响应数据项中的属性名相同
* @dataStructure {[array]} [存储待ajax数据替换的字符串及其对应的数据项的属性名的对象,组成的数组]
* --- [
* ------ 0:{match: 'htmlStr', propName: 'propNameStr'},
* ------ 1:{match: 'htmlStr', propName: 'propNameStr'},
* ------ 2:{match: 'htmlStr', propName: 'propNameStr'},
* ------ ...
* --- ]
*/
// function getTmplt(tmpltElm) {
// var timeCnt = +new Date();
// var tmpltStr = tmpltElm.innerHTML;
// var tmpltArr = [];
// var pattern = /\$\{track\.(.+?)\}/g;
// var matches = null;
// while (matches = pattern.exec(tmpltStr)) {
// var obj = {match: matches[0], propName: matches[1]};
// tmpltArr.push(obj);
// obj = null;
// }
// tmpltArr.txt = tmpltStr;
// // console.log('getTmplt timepass:', +new Date() - timeCnt);
// return tmpltArr;
// }
// var tmpltArr = getTmplt(tmplts[0]);
// function getData () {
// var res = getServerData.response;
// var list = res.list;
// var inHtml = '';
// for (var i = 0, lstLen = list.length; i < lstLen; i++) {
// var str = tmpltArr.txt;
// for (var j = 0, tmpLen = tmpltArr.length; j < tmpLen; j++) {
// str = str.replace(tmpltArr[j].match, list[i][tmpltArr[j].propName]);
// }
// inHtml += str;
// }
// cards.innerHTML = inHtml;
// }
// function except () {
// console.log('not get!');
// }
// waitResponse(getData, except, getServerData, url, options);
| 34.697632 | 123 | 0.535881 |
132aeea885422f2e3c930fd835ef2661342f668d | 886 | js | JavaScript | server.js | sabahang/image-search-abstraction-layer | 5de52f517052668165c32fb6dc5dc8e91d0184d6 | [
"MIT"
] | null | null | null | server.js | sabahang/image-search-abstraction-layer | 5de52f517052668165c32fb6dc5dc8e91d0184d6 | [
"MIT"
] | null | null | null | server.js | sabahang/image-search-abstraction-layer | 5de52f517052668165c32fb6dc5dc8e91d0184d6 | [
"MIT"
] | null | null | null | 'use strict';
require('dotenv').load();
var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var app = express();
app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use('/common', express.static(process.cwd() + '/app/common'));
switch (app.get('env')){
case 'development':
console.log( 'Loading development configuration...' );
mongoose.connect(process.env.MONGO_URI );
break;
case 'production':
console.log( 'Loading production configuration...' );
mongoose.connect(process.env.MONGOLAB_URI);
break;
}
routes(app);
var port = process.env.PORT || 8080;
//var port = 8080;
app.listen(port, function () {
console.log('Node.js listening on port ' + port + '...');
}); | 27.6875 | 76 | 0.639955 |
132c9d908e88dc76251c873653f75eb5578f274a | 606 | js | JavaScript | client/src/components/UserSettingItem/index.js | jcstang/not-reddit | 6cbd4062d1919f8daaea74d8440bf3c1af5051f7 | [
"MIT"
] | 5 | 2020-05-17T19:59:00.000Z | 2021-04-29T05:09:58.000Z | client/src/components/UserSettingItem/index.js | Darkthistle982/not-reddit | ab481d2d7dfe0483ea87dbeea0f972bcc481b1fe | [
"MIT"
] | 3 | 2020-05-27T20:56:57.000Z | 2020-05-29T00:59:33.000Z | client/src/components/UserSettingItem/index.js | Darkthistle982/not-reddit | ab481d2d7dfe0483ea87dbeea0f972bcc481b1fe | [
"MIT"
] | 2 | 2020-05-20T04:23:02.000Z | 2020-06-11T16:36:51.000Z | import React from "react";
import InputGroup from "react-bootstrap/InputGroup";
import FormControl from "react-bootstrap/FormControl";
export default function UserSettingItem(props) {
return (
<div>
<InputGroup className="mb-3">
<InputGroup.Prepend>
<InputGroup.Text id="basic-addon1">{props.itemText}</InputGroup.Text>
</InputGroup.Prepend>
<FormControl
placeholder={props.valueText}
aria-label={props.valueText}
aria-describedby="basic-addon1"
value={props.valueText}
/>
</InputGroup>
</div>
);
}
| 27.545455 | 79 | 0.638614 |
132cfc86d4937f06ff18dbe91aeea99f8b72774c | 1,648 | js | JavaScript | react-testing-library/src/t2/App.test.js | gaaangi-learning/enjoy-react | 146946f39834373d53a33764ef8bce70f9d159c9 | [
"MIT"
] | null | null | null | react-testing-library/src/t2/App.test.js | gaaangi-learning/enjoy-react | 146946f39834373d53a33764ef8bce70f9d159c9 | [
"MIT"
] | null | null | null | react-testing-library/src/t2/App.test.js | gaaangi-learning/enjoy-react | 146946f39834373d53a33764ef8bce70f9d159c9 | [
"MIT"
] | null | null | null | import * as React from 'react'
import axios from 'axios'
import { act, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { App } from './App'
jest.mock('axios')
describe('App', () => {
test('fetches stories from an API and displays them', async () => {
const stories = [
{ objectID: '1', title: 'Hello' },
{ objectID: '2', title: 'React' },
]
axios.get.mockImplementationOnce(() =>
Promise.resolve({ data: { hits: stories } })
)
render(<App />)
await userEvent.click(screen.getByRole('button'))
const items = await screen.findAllByRole('listitem')
expect(items).toHaveLength(2)
})
test('fetches stories from an API and displays them, explicit asynchronous behavior', async () => {
const stories = [
{ objectID: '1', title: 'Hello' },
{ objectID: '2', title: 'React' },
]
const promise = Promise.resolve({ data: { hits: stories } })
axios.get.mockImplementationOnce(() => promise)
render(<App />)
await userEvent.click(screen.getByRole('button'))
await act(() => promise)
expect(screen.getAllByRole('listitem')).toHaveLength(2)
})
test('fetches stories from an API and fails', async () => {
axios.get.mockImplementationOnce(() => Promise.reject(new Error()))
render(<App />)
await userEvent.click(screen.getByRole('button'))
const message = await screen.findByText(/Something went wrong/)
expect(message).toBeInTheDocument()
})
})
| 32.313725 | 103 | 0.589806 |
132e1d01f76745c5527bf0962f4c5e600c3cb8bd | 1,149 | js | JavaScript | client/app/routes/admin-badgecodes-create.js | weinzach/hvzsite | 7b93f2e69ca3b60e23260ddf1aec8217eff844f3 | [
"MIT"
] | 3 | 2016-08-31T23:30:02.000Z | 2021-09-07T18:54:28.000Z | client/app/routes/admin-badgecodes-create.js | weinzach/hvzsite | 7b93f2e69ca3b60e23260ddf1aec8217eff844f3 | [
"MIT"
] | 31 | 2015-01-13T02:31:02.000Z | 2021-05-06T18:10:31.000Z | client/app/routes/admin-badgecodes-create.js | weinzach/hvzsite | 7b93f2e69ca3b60e23260ddf1aec8217eff844f3 | [
"MIT"
] | 6 | 2015-05-07T19:57:31.000Z | 2021-09-13T04:27:34.000Z | import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
export default Ember.Route.extend(ResetScrollMixin, {
ajax: Ember.inject.service(),
toast: Ember.inject.service(),
errorHandler: Ember.inject.service(),
user: Ember.inject.service(),
actions: {
save() {
Ember.$('#saveButton').hide();
var description = Ember.$('#badgecodeDescription').val();
var badgeID = Ember.$('#badgeID').val();
if (badgeID.trim() === '') {
this.get('toast').warning("You didn't enter a badge id for the badge code!");
Ember.$('#saveButton').show();
return;
}
for(var i = 1; i <= Ember.$('#qty').val(); i++){
this.get('ajax').post('/admin/badgecodes', {
data: {
description: description,
badgeID: badgeID.toLowerCase(),
apikey: this.get('user').getApiKey()
}
}).then((result) => {
this.get('toast').success('Created new badge code #' + result.badgecode.id);
}).catch((err) => {
this.get('errorHandler').handleError(err, 'Unable to create badge code.');
Ember.$('#saveButton').show();
});
}
this.transitionTo('admin-badgecodes');
}
}
});
| 28.725 | 81 | 0.610966 |
13307a86b99e9835154e451d6d79a03196bb06b5 | 29,721 | js | JavaScript | backend/src/tests/task.test.js | rhopensourcecontest/osc-app | a63f91989a578eecf2eb77c6288657055363c13c | [
"Apache-2.0"
] | 2 | 2019-09-26T08:57:27.000Z | 2022-02-23T10:10:41.000Z | backend/src/tests/task.test.js | bsmolicek/osc-app | a63f91989a578eecf2eb77c6288657055363c13c | [
"Apache-2.0"
] | 7 | 2019-10-17T06:28:21.000Z | 2021-07-26T09:45:42.000Z | backend/src/tests/task.test.js | bsmolicek/osc-app | a63f91989a578eecf2eb77c6288657055363c13c | [
"Apache-2.0"
] | 3 | 2019-09-27T10:27:19.000Z | 2021-04-08T18:19:58.000Z | require('./db-handler');
const mongoose = require('mongoose');
const taskService = require('../graphql/resolvers/tasks');
const Task = require('../models/task');
const Student = require('../models/student');
const Mentor = require('../models/mentor');
const { TASKS, NEX_ARGS } = require('./test-data/task');
const { STUDENTS, AUTH_S_REQ, NAUTH_S_REQ } = require('./test-data/student');
const {
MENTORS,
NAUTH_REQ,
NADMIN_REQ,
NVERIF_REQ,
ADMIN_REQ
} = require('./test-data/mentor');
/**
* Add testing Mentors, Tasks and Students.
* Register Students to Tasks.
*/
beforeEach(async () => {
for (let i = 0; i < STUDENTS.length; i++) {
let mentor = new Mentor(MENTORS[i]);
let task = new Task(TASKS[i]);
let student = new Student(STUDENTS[i]);
mentor.createdTasks.push(task);
task.creator = mentor;
// 2nd Student and 2nd Task will not be registered
if (i != 1) {
student.registeredTask = task;
task.registeredStudent = student;
}
await mentor.save();
await student.save();
await task.save();
}
});
/**
* Task test suite.
*/
describe('task', () => {
/**
* Environment test
*/
it('Testing data was added to db', async () => {
expect((await Task.find()).length).toBe(TASKS.length);
expect((await Student.find()).length).toBe(STUDENTS.length);
expect((await Mentor.find()).length).toBe(MENTORS.length);
});
/**
* Environment test
*/
it('Tasks have creators', async () => {
const tasks = await Task.find();
const mentors = await Mentor.find();
for (let i = 0; i < tasks.length; i++) {
expect(tasks[i].creator).not.toBeNull();
expect(tasks[i].creator).toEqual(mentors[i]._id);
}
});
/**
* Environment test
*/
it('Mentors have createdTasks', async () => {
const tasks = await Task.find();
const mentors = await Mentor.find();
for (let i = 0; i < tasks.length; i++) {
expect(mentors[i].createdTasks.length).toBe(1);
expect(mentors[i].createdTasks).toContainEqual(tasks[i]._id);
}
});
/**
* Environment test
*/
it('Students were registered to Tasks', async () => {
const students = await Student.find();
const tasks = await Task.find();
for (let i = 0; i < students.length; i++) {
if (i == 1) {
expect(students[i].registeredTask).toBeNull();
expect(tasks[i].registeredStudent).toBeNull();
} else {
expect(students[i].registeredTask).toEqual(tasks[i]._id);
expect(tasks[i].registeredStudent).toEqual(students[i]._id);
}
}
});
it('task() does not throw error for invalid ID', async () => {
await expect(taskService.task({ taskId: "5" })).resolves.not.toThrow();
});
it('task() returns null for invalid ID', async () => {
await expect(taskService.task({ taskId: "acb" })).resolves.toBeNull();
});
it('task() works correctly with valid ID', async () => {
const task = await Task.findOne();
const response = await taskService.task({ taskId: task._id });
expect(response).not.toBeNull();
expect(response._id).toEqual(task._id);
expect(response.title).toEqual(task.title);
expect(response.details).toEqual(task.details);
// non-existing Task with correct ID
await expect(taskService.task({ taskId: mongoose.Types.ObjectId() }))
.resolves.toBeNull();
});
it('allTasks() returns correct data', async () => {
const actual = await taskService.allTasks();
const tasks = await Task.find();
expect(actual).not.toEqual(tasks);
expect(actual.length).toBe(tasks.length);
for (let i = 0; i < tasks.length; i++) {
expect(actual[i]._id).not.toBeNull();
expect(actual[i].title).toBe(tasks[i].title);
expect(actual[i].details).toBe(tasks[i].details);
expect(actual[i].link).toBe(tasks[i].link);
expect(actual[i].isSolved).toBe(tasks[i].isSolved);
expect(actual[i].isBeingSolved).toBe(tasks[i].isBeingSolved);
expect(actual[i].creator).not.toBeNull();
if (tasks[i].registeredStudent === null) {
expect(actual[i].registeredStudent).toBeNull();
} else {
// bound Student
expect(actual[i].registeredStudent).not.toBeNull();
}
}
});
it('freeTasks() returns correct data', async () => {
const response = await taskService.freeTasks();
const tasks = await Task.find();
let expectedIds = [];
for (const t of tasks) {
if (t.registeredStudent === null) { expectedIds.push(t._id); }
}
for (const task of response) {
expect(expectedIds).toContainEqual(task._id);
}
});
it('takenTasks() returns correct data', async () => {
const response = await taskService.takenTasks();
const tasks = await Task.find();
let expectedIds = [];
for (const t of tasks) {
if (t.registeredStudent !== null) { expectedIds.push(t._id); }
}
for (const task of response) {
expect(expectedIds).toContainEqual(task._id);
}
});
// ------------------------------------------------------------------------ \\
/**
* Unauthenticated Mentor.
*/
it('createTask() throws error', async () => {
await expect(taskService.createTask(NEX_ARGS, NAUTH_REQ))
.rejects.toThrow('Unauthenticated!');
});
/**
* Unauthenticated Student.
*/
it('createTask() throws error', async () => {
await expect(taskService.createTask(NEX_ARGS, NAUTH_S_REQ))
.rejects.toThrow('Unauthenticated!');
});
/**
* Authenticated Student.
*/
it('createTask() throws error', async () => {
await expect(taskService.createTask(NEX_ARGS, AUTH_S_REQ))
.rejects.toThrow('Only Mentors can create Tasks!');
});
/**
* Non-existing Mentor.
* NADMIN_REQ generates new userId (Mentor does not exist).
*/
it('createTask() throws error', async () => {
await expect(taskService.createTask(NEX_ARGS, NADMIN_REQ))
.rejects.toThrow('Mentor not found');
});
/**
* Not verified Mentor without admin rights.
* Need to replace userId in request with an existing one.
*/
it('createTask() throws error', async () => {
const nverifMentor = await Mentor.findOne({
isVerified: false, isAdmin: false
});
await expect(taskService.createTask(
NEX_ARGS, { ...NVERIF_REQ, userId: nverifMentor._id }
)).rejects.toThrow('You are not verified Mentor');
});
/**
* Verified Mentor without admin rights.
*/
it('createTask() does not throw error', async () => {
const verifMentor = await Mentor.findOne({
isVerified: true, isAdmin: false
});
await expect(taskService.createTask(
NEX_ARGS, { ...NADMIN_REQ, userId: verifMentor._id }
)).resolves.not.toThrow();
});
/**
* Verified Mentor without admin rights.
*/
it('createTask() works correctly', async () => {
expect((await Task.find()).length).toBe(TASKS.length);
const verifMentor = await Mentor.findOne({
isVerified: true, isAdmin: false
});
const tasksCount = verifMentor.createdTasks.length;
const response = await taskService.createTask(
NEX_ARGS, { ...NADMIN_REQ, userId: verifMentor._id }
);
expect((await Task.find()).length).toBe(TASKS.length + 1);
expect((await Mentor.findById(verifMentor._id)).createdTasks.length)
.toBe(tasksCount + 1);
const resultTask = await Task.findById(response._id);
expect(resultTask._id).not.toBeNull();
expect(resultTask._id).toEqual(response._id);
expect(resultTask.title).toBe(NEX_ARGS.taskInput.title);
expect(resultTask.details).toBe(NEX_ARGS.taskInput.details);
expect(resultTask.link).not.toBeNull();
expect(resultTask.link).toBe(NEX_ARGS.taskInput.link);
expect(resultTask.isSolved).toBe(false);
expect(resultTask.isBeingSolved).toBe(false);
expect(resultTask.creator).not.toBeNull();
expect(resultTask.creator).toEqual(verifMentor._id);
expect(resultTask.registeredStudent).toBeNull();
});
/**
* Verified Mentor with admin rights.
*/
it('createTask() does not throw error', async () => {
const admin = await Mentor.findOne({
isVerified: true, isAdmin: true
});
await expect(taskService.createTask(
NEX_ARGS, { ...ADMIN_REQ, userId: admin._id }
)).resolves.not.toThrow();
});
// ------------------------------------------------------------------------ \\
/**
* Unauthenticated Mentor.
*/
it('registerTask() throws error', async () => {
await expect(taskService.registerTask({}, NAUTH_REQ))
.rejects.toThrow('Unauthenticated!');
});
/**
* Unauthenticated Student.
*/
it('registerTask() throws error', async () => {
await expect(taskService.registerTask({}, NAUTH_S_REQ))
.rejects.toThrow('Unauthenticated!');
});
/**
* Authenticated Mentor without Admin rights.
*/
it('registerTask() throws error', async () => {
await expect(taskService.registerTask({}, NADMIN_REQ))
.rejects.toThrow('Only Students and Admins can register to Tasks!');
});
/**
* Authenticated Student.
*/
it('registerTask() does not throw error', async () => {
const student = await Student.findOne({ registeredTask: null });
const task = await Task.findOne({ registeredStudent: null });
const args = { studentId: student._id, taskId: task._id };
const req = { ...AUTH_S_REQ, userId: student._id };
await expect(taskService.registerTask(args, req)).resolves.not.toThrow();
});
/**
* Authenticated Admin.
*/
it('registerTask() does not throw error', async () => {
const student = await Student.findOne({ registeredTask: null });
const task = await Task.findOne({ registeredStudent: null });
const admin = await Mentor.findOne({ isAdmin: true });
const args = { studentId: student._id, taskId: task._id };
const req = { ...ADMIN_REQ, userId: admin._id };
await expect(taskService.registerTask(args, req)).resolves.not.toThrow();
});
/**
* Authenticated Student attempting to register someone else.
*/
it('registerTask() throws error', async () => {
const args = {
studentId: mongoose.Types.ObjectId(), taskId: mongoose.Types.ObjectId()
};
await expect(taskService.registerTask(args, AUTH_S_REQ))
.rejects.toThrow('Students cannot register Tasks for others!');
});
/**
* Authenticated Admin registering non-existing Student.
*/
it('registerTask() throws error', async () => {
const args = {
studentId: mongoose.Types.ObjectId(), taskId: mongoose.Types.ObjectId()
};
await expect(taskService.registerTask(args, ADMIN_REQ))
.rejects.toThrow('Student not found.');
});
/**
* Authenticated Admin registering Student who already has a Task registered.
*/
it('registerTask() throws error', async () => {
const student = await Student.findOne({ registeredTask: { $ne: null } });
const args = { studentId: student._id, taskId: mongoose.Types.ObjectId() };
await expect(taskService.registerTask(args, ADMIN_REQ))
.rejects.toThrow('Student can only have one Task at a time.');
});
/**
* Authenticated Admin registering Student to non-existing Task.
*/
it('registerTask() throws error', async () => {
const student = await Student.findOne({ registeredTask: null });
const args = { studentId: student._id, taskId: mongoose.Types.ObjectId() };
await expect(taskService.registerTask(args, ADMIN_REQ))
.rejects.toThrow('Task not found.');
});
/**
* Authenticated Admin registering Student to taken Task.
*/
it('registerTask() throws error', async () => {
const student = await Student.findOne({ registeredTask: null });
const task = await Task.findOne({ registeredStudent: { $ne: null } });
const args = { studentId: student._id, taskId: task._id };
await expect(taskService.registerTask(args, ADMIN_REQ))
.rejects.toThrow('Task has already been taken.');
});
/**
* Authenticated Student.
*/
it('registerTask() works correctly', async () => {
const student = await Student.findOne({ registeredTask: null });
const task = await Task.findOne({ registeredStudent: null });
const args = { studentId: student._id, taskId: task._id };
const req = { ...AUTH_S_REQ, userId: student._id };
expect(student.registeredTask).toBeNull();
expect(task.registeredStudent).toBeNull();
await expect(taskService.registerTask(args, req)).resolves.not.toThrow();
const resultTask = await Task.findById(task._id);
const resultStudent = await Student.findById(student._id);
expect(resultStudent.registeredTask).toEqual(task._id);
expect(resultTask.registeredStudent).toEqual(student._id);
});
// ------------------------------------------------------------------------ \\
/**
* Unauthenticated Mentor.
*/
it('unregisterTask() throws error', async () => {
await expect(taskService.unregisterTask({}, NAUTH_REQ))
.rejects.toThrow('Unauthenticated!');
});
/**
* Unauthenticated Student.
*/
it('unregisterTask() throws error', async () => {
await expect(taskService.unregisterTask({}, NAUTH_S_REQ))
.rejects.toThrow('Unauthenticated!');
});
/**
* Authenticated Mentor without Admin rights.
*/
it('unregisterTask() throws error', async () => {
await expect(taskService.unregisterTask({}, NADMIN_REQ))
.rejects.toThrow('Only Students and Admins can unregister from Tasks!');
});
/**
* Authenticated Student.
*/
it('unregisterTask() does not throw error', async () => {
const student = await Student.findOne({ registeredTask: { $ne: null } });
const task = await Task.findOne({ registeredStudent: student._id });
const args = { studentId: student._id, taskId: task._id };
const req = { ...AUTH_S_REQ, userId: student._id };
expect(student.registeredTask).toEqual(args.taskId);
expect(task.registeredStudent).toEqual(args.studentId);
await expect(taskService.unregisterTask(args, req)).resolves.not.toThrow();
});
/**
* Authenticated Admin.
*/
it('unregisterTask() does not throw error', async () => {
const student = await Student.findOne({ registeredTask: { $ne: null } });
const task = await Task.findOne({ registeredStudent: student._id });
const admin = await Mentor.findOne({ isAdmin: true });
const args = { studentId: student._id, taskId: task._id };
const req = { ...ADMIN_REQ, userId: admin._id };
expect(student.registeredTask).toEqual(args.taskId);
expect(task.registeredStudent).toEqual(args.studentId);
await expect(taskService.unregisterTask(args, req)).resolves.not.toThrow();
});
/**
* Authenticated Student attempting to unregister some else's Task.
*/
it('unregisterTask() throws error', async () => {
const args = {
studentId: mongoose.Types.ObjectId(), taskId: mongoose.Types.ObjectId()
};
await expect(taskService.unregisterTask(args, AUTH_S_REQ))
.rejects.toThrow('Students can unregister only their own Task!');
});
/**
* Authenticated Admin trying to unregister Student registered to another Task.
*/
it('unregisterTask() throws error', async () => {
const student = await Student.findOne({ registeredTask: { $ne: null } });
const args = { studentId: student._id, taskId: mongoose.Types.ObjectId() };
await expect(taskService.unregisterTask(args, ADMIN_REQ)).rejects.toThrow(
`Student ${args.studentId} is not registered to Task ${args.taskId}`
);
});
/**
* Authenticated Admin trying to unregister Student from Task registered to
* someone else.
*/
it('unregisterTask() throws error', async () => {
let student = await Student.findOne({ registeredTask: null });
const task = await Task.findOne({ registeredStudent: { $ne: student._id } });
await student.updateOne({ registeredTask: task._id });
const args = { studentId: student._id, taskId: task._id };
await expect(taskService.unregisterTask(args, ADMIN_REQ)).rejects.toThrow(
`Task ${args.taskId} doesn't have registered Student ${args.studentId}`
);
});
/**
* Authenticated Student.
*/
it('unregisterTask() works correctly', async () => {
const student = await Student.findOne({ registeredTask: { $ne: null } });
const task = await Task.findOne({ registeredStudent: { $ne: null } });
const args = { studentId: student._id, taskId: task._id };
const req = { ...AUTH_S_REQ, userId: student._id };
expect(student.registeredTask).toEqual(task._id);
expect(task.registeredStudent).toEqual(student._id);
await expect(taskService.unregisterTask(args, req)).resolves.not.toThrow();
const resultTask = await Task.findById(task._id);
const resultStudent = await Student.findById(student._id);
expect(resultStudent.registeredTask).toBeNull();
expect(resultTask.registeredStudent).toBeNull();
});
/**
* Authenticated Admin.
*/
it('unregisterTask() clears task progress', async () => {
const admin = await Mentor.findOne({ isAdmin: true });
const student = await Student.findOne({ registeredTask: { $ne: null } });
const task = await Task.findOne({
registeredStudent: { $ne: null }, isBeingSolved: true
});
const args = { studentId: student._id, taskId: task._id };
const req = { ...ADMIN_REQ, userId: admin._id };
expect(task.registeredStudent).not.toBeNull();
expect(student.registeredTask).toEqual(task._id);
expect(task.registeredStudent).toEqual(student._id);
await expect(taskService.unregisterTask(args, req)).resolves.not.toThrow();
const resultTask = await Task.findById(task._id);
const resultStudent = await Student.findById(student._id);
// task progress should reset
expect(resultTask.isSolved).toBe(false);
expect(resultTask.isBeingSolved).toBe(false);
expect(resultStudent.registeredTask).toBeNull();
expect(resultTask.registeredStudent).toBeNull();
});
// ------------------------------------------------------------------------ \\
/**
* Unauthenticated Mentor.
*/
it('deleteTask() throws error', async () => {
await expect(taskService.deleteTask({}, NAUTH_REQ))
.rejects.toThrow('Unauthenticated!');
});
/**
* Unauthenticated Student.
*/
it('deleteTask() throws error', async () => {
await expect(taskService.deleteTask({}, NAUTH_S_REQ))
.rejects.toThrow('Unauthenticated!');
});
/**
* Authenticated Student.
*/
it('deleteTask() throws error', async () => {
await expect(taskService.deleteTask({}, AUTH_S_REQ))
.rejects.toThrow('Only Mentors and Admins can delete Tasks!');
});
/**
* Authenticated Mentor without Admin rights.
*/
it('deleteTask() works correctly', async () => {
expect((await Task.find()).length).toBe(TASKS.length);
const task = await Task.findOne({ registeredStudent: null });
const mentor = await Mentor.findOne({ createdTasks: [task._id] });
const args = { taskId: task._id };
const req = { ...NADMIN_REQ, userId: mentor._id };
await expect(taskService.deleteTask(args, req)).resolves.not.toThrow();
expect((await Task.find()).length).toBe(TASKS.length - 1);
await expect(Task.findById(task._id)).resolves.toBeNull();
});
/**
* Authenticated Admin deletes someone else's task.
*/
it('deleteTask() works correctly', async () => {
expect((await Task.find()).length).toBe(TASKS.length);
const admin = await Mentor.findOne({ isAdmin: true });
const task = await Task.findOne({ registeredStudent: null });
const args = { taskId: task._id };
const req = { ...ADMIN_REQ, userId: admin._id };
await expect(taskService.deleteTask(args, req)).resolves.not.toThrow();
expect((await Task.find()).length).toBe(TASKS.length - 1);
await expect(Task.findById(task._id)).resolves.toBeNull();
});
/**
* Authenticated Admin trying to delete non-existing Task.
*/
it('deleteTask() throws error', async () => {
const args = { taskId: mongoose.Types.ObjectId() };
await expect(taskService.deleteTask(args, ADMIN_REQ))
.rejects.toThrow(`Task ${args.taskId} does not exist.`);
});
/**
* Authenticated Admin trying to delete Task with registered Student.
*/
it('deleteTask() throws error', async () => {
expect((await Task.find()).length).toBe(TASKS.length);
const admin = await Mentor.findOne({ isAdmin: true });
const task = await Task.findOne({ registeredStudent: { $ne: null } });
const student = await Student.findById(task.registeredStudent);
const args = { taskId: task._id };
const req = { ...ADMIN_REQ, userId: admin._id };
await expect(taskService.deleteTask(args, req)).rejects.toThrow(
`Student ${student.email} is registered to this Task`
);
expect((await Task.find()).length).toBe(TASKS.length);
});
/**
* Authenticated Mentor without Admin rights trying to delete someone
* else's Task.
*/
it('deleteTask() throws error', async () => {
expect((await Task.find()).length).toBe(TASKS.length);
const mentor = await Mentor.findOne({ isAdmin: false, isVerified: true });
const task = await Task.findOne({
registeredStudent: null, creator: { $ne: mentor._id }
});
const args = { taskId: task._id };
const req = { ...NADMIN_REQ, userId: mentor._id };
await expect(taskService.deleteTask(args, req)).rejects.toThrow(
`You aren't creator of this Task and don't have Admin rights.`
);
expect((await Task.find()).length).toBe(TASKS.length);
});
// ------------------------------------------------------------------------ \\
/**
* Unauthenticated Mentor.
*/
it('editTaskProgress() throws error', async () => {
await expect(taskService.editTaskProgress({}, NAUTH_REQ))
.rejects.toThrow('Unauthenticated!');
});
/**
* Unauthenticated Student.
*/
it('editTaskProgress() throws error', async () => {
await expect(taskService.editTaskProgress({}, NAUTH_S_REQ))
.rejects.toThrow('Unauthenticated!');
});
/**
* Authenticated Student.
*/
it('editTaskProgress() works correctly', async () => {
const student = await Student.findOne({ registeredTask: { $ne: null } });
const task = await Task.findOne({ registeredStudent: student });
const args = { taskId: task._id, isSolved: true, isBeingSolved: false };
await expect(taskService.editTaskProgress(
args, { ...AUTH_S_REQ, userId: student._id }))
.resolves.not.toThrow();
const resultTask = await Task.findById(task._id);
const expectedTask = {
...task._doc, isSolved: args.isSolved, isBeingSolved: args.isBeingSolved
};
// other fields did not change
expect(resultTask._doc).toEqual(expectedTask);
});
/**
* Authenticated Student.
*/
it('editTaskProgress() returns correct data', async () => {
const student = await Student.findOne({ registeredTask: { $ne: null } });
const task = await Task.findOne({ registeredStudent: student });
const args = { taskId: task._id, isSolved: false, isBeingSolved: true };
const response = await taskService.editTaskProgress(
args, { ...AUTH_S_REQ, userId: student._id }
);
expect(response.isSolved).toBe(args.isSolved);
expect(response.isBeingSolved).toBe(args.isBeingSolved);
});
/**
* Authenticated Student not registered to Task
*/
it('editTaskProgress() throws error', async () => {
const student = await Student.findOne({ registeredTask: null });
const task = await Task.findOne({ registeredStudent: { $ne: null } });
const args = { taskId: task._id, isSolved: false, isBeingSolved: true };
await expect(taskService.editTaskProgress(args, { ...AUTH_S_REQ, userId: student._id }))
.rejects.toThrow('You are not registered to this Task!');
const resultTask = await Task.findById(task._id);
expect(resultTask.isSolved).toBe(task.isSolved);
expect(resultTask.isBeingSolved).toBe(task.isBeingSolved);
});
// ------------------------------------------------------------------------ \\
/**
* Unauthenticated Mentor.
*/
it('updateTask() throws error', async () => {
await expect(taskService.updateTask({}, NAUTH_REQ))
.rejects.toThrow('Unauthenticated!');
});
/**
* Authenticated Student.
*/
it('updateTask() throws error', async () => {
const student = await Student.findOne();
const req = { ...AUTH_S_REQ, userId: student._id };
await expect(taskService.updateTask({}, req))
.rejects.toThrow('Only Mentors can update Tasks!');
});
/**
* Authenticated Mentor without Admin rights trying to update Task not
* created by him.
*/
it('updateTask() throws error', async () => {
const mentor = await Mentor.findOne({
isAdmin: false, createdTasks: { $ne: [] }
});
const task = await Task.findOne({ creator: { $ne: mentor } });
const args = {
taskInput: {
_id: task._id, title: 'Edited', details: 'Edited', link: task.link
}
};
await expect(taskService.updateTask(
args, { ...NADMIN_REQ, userId: mentor._id })).rejects.toThrow(
`You aren't creator of this Task and don't have Admin rights.`
);
});
/**
* Authenticated creator of the Task without Admin rights.
*/
it('updateTask() works correctly', async () => {
const mentor = await Mentor.findOne({
isAdmin: false, createdTasks: { $ne: [] }
});
const task = await Task.findOne({ creator: mentor });
const args = {
taskInput: {
_id: task._id, title: 'Edited', details: 'Edited', link: task.link
}
};
const response = await taskService.updateTask(
args, { ...NADMIN_REQ, userId: mentor._id }
);
// correct response
expect(response.title).toBe(args.taskInput.title);
expect(response.details).toBe(args.taskInput.details);
expect(response.link).toBe(task.link);
// correct data in the db
const resultTask = await Task.findById(task._id);
expect(resultTask.title).toBe(args.taskInput.title);
expect(resultTask.details).toBe(args.taskInput.details);
expect(resultTask.link).toBe(task.link);
});
/**
* Authenticated Admin who did not create the Task
*/
it('updateTask() works correctly', async () => {
const admin = await Mentor.findOne({
isAdmin: true, createdTasks: { $ne: [] }
});
const task = await Task.findOne({ creator: admin });
const args = {
taskInput: {
_id: task._id,
title: 'Edited',
details: task.details,
link: 'www.edited.com'
}
};
const response = await taskService.updateTask(
args, { ...NADMIN_REQ, userId: admin._id }
);
// correct response
expect(response.title).toBe(args.taskInput.title);
expect(response.details).toBe(task.details);
expect(response.link).toBe(args.taskInput.link);
// correct data in the db
const resultTask = await Task.findById(task._id);
expect(resultTask.title).toBe(args.taskInput.title);
expect(resultTask.details).toBe(task.details);
expect(resultTask.link).toBe(args.taskInput.link);
});
/** Unauthenticated Mentor */
it('swapRegistration() throws error', async () => {
await expect(taskService.swapRegistration({}, NAUTH_REQ))
.rejects.toThrow('Unauthenticated!');
});
/** Authenticated Mentor */
it('swapRegistration() throws error', async () => {
await expect(taskService.swapRegistration({}, NADMIN_REQ))
.rejects.toThrow('Only admin can swap registration.');
});
/** Authenticated Admin */
it('swapRegistration() works correctly', async () => {
const registeredStudent = await Student.findOne({ registeredTask: { $ne: null } });
const task = await Task.findOne({ registeredStudent: registeredStudent._id });
const newStudent = await Student.findOne({ registeredTask: null });
const args = {
registeredStudentId: registeredStudent._id,
nonRegisteredStudentId: newStudent._id,
taskId: task._id
};
await expect(taskService.swapRegistration(args, ADMIN_REQ))
.resolves.not.toThrow();
expect((await Student.findById(registeredStudent._id)).registeredTask).toBeNull();
expect((await Student.findById(newStudent._id)).registeredTask).toEqual(task._id);
expect((await Task.findById(task._id)).registeredStudent).toEqual(newStudent._id);
});
/** Unauthenticated Mentor */
it('changeCreator() throws error', async () => {
await expect(taskService.changeCreator({}, NAUTH_REQ))
.rejects.toThrow('Unauthenticated!');
});
/** Authenticated Mentor */
it('changeCreator() throws error', async () => {
await expect(taskService.changeCreator({}, NADMIN_REQ))
.rejects.toThrow('Only admin can change creator.');
});
/** Authenticated Admin */
it('changeCreator() works correctly', async () => {
const oldMentor = await Mentor.findOne({ isAdmin: true });
const task = await Task.findOne({ creator: oldMentor._id });
const newMentor = await Mentor.findOne({ _id: { $ne: oldMentor._id } });
expect(task.creator).not.toBeNull();
expect(newMentor.createdTasks).not.toContainEqual(task._id);
const args = {
taskId: task._id, oldMentorId: oldMentor._id, newMentorId: newMentor._id
};
await expect(taskService.changeCreator(args, ADMIN_REQ))
.resolves.not.toThrow();
expect((await Task.findById(task._id)).creator._id).toEqual(newMentor._id);
expect((await Mentor.findById(oldMentor._id)).createdTasks)
.not.toContainEqual(task._id);
expect((await Mentor.findById(newMentor._id)).createdTasks)
.toContainEqual(task._id);
});
});
| 34.044674 | 92 | 0.641129 |
1330e7b2d186092ce0bf7ddd5de61d7272d37f00 | 161 | js | JavaScript | src/status/datastore/index.js | wetneb/karrot-frontend | 3a8763e1319178535b4b0a92f08f032b02c784e5 | [
"MIT"
] | 273 | 2017-09-11T16:12:29.000Z | 2021-11-28T10:13:19.000Z | src/status/datastore/index.js | wetneb/karrot-frontend | 3a8763e1319178535b4b0a92f08f032b02c784e5 | [
"MIT"
] | 1,802 | 2017-09-10T21:19:37.000Z | 2021-11-29T16:52:50.000Z | src/status/datastore/index.js | wetneb/karrot-frontend | 3a8763e1319178535b4b0a92f08f032b02c784e5 | [
"MIT"
] | 175 | 2017-10-13T17:12:55.000Z | 2021-11-25T17:05:21.000Z | import status, { plugin as statusPlugin } from '@/status/datastore/status'
export default {
modules: {
status,
},
plugins: [
statusPlugin,
],
}
| 14.636364 | 74 | 0.63354 |
133102e3b824e9c716dfd15aa6bdcdd595efe97e | 74 | js | JavaScript | ui/form/DateTimeField/index.js | kozhindev/yii-steroids | d3e57e00da77bc7b24948b391e1a0ba985b09a38 | [
"MIT"
] | 5 | 2018-04-02T06:25:23.000Z | 2020-05-10T19:14:11.000Z | ui/form/DateTimeField/index.js | kozhindev/yii-steroids | d3e57e00da77bc7b24948b391e1a0ba985b09a38 | [
"MIT"
] | 9 | 2021-03-09T01:32:39.000Z | 2022-02-26T14:26:42.000Z | ui/form/DateTimeField/index.js | kozhindev/yii-steroids | d3e57e00da77bc7b24948b391e1a0ba985b09a38 | [
"MIT"
] | 2 | 2018-09-05T06:02:32.000Z | 2019-07-16T10:36:53.000Z | import DateTimeField from './DateTimeField';
export default DateTimeField; | 37 | 44 | 0.837838 |
1331bdeebaf6cbfb521a7e9defbb2602b6cc0a77 | 1,587 | js | JavaScript | src/components/Footer.js | mendozammatias/bbv-website | 9f08665ace133e974ebfd742f6907a79f784b8e4 | [
"MIT"
] | null | null | null | src/components/Footer.js | mendozammatias/bbv-website | 9f08665ace133e974ebfd742f6907a79f784b8e4 | [
"MIT"
] | null | null | null | src/components/Footer.js | mendozammatias/bbv-website | 9f08665ace133e974ebfd742f6907a79f784b8e4 | [
"MIT"
] | null | null | null | import React from 'react';
import { useTranslation as useI18n } from 'react-i18next';
import { Footer } from '@blackbox-vision/ui-components';
import { Button, Grid, makeStyles, Hidden } from '@material-ui/core';
import { useTranslation } from '@hooks/useTranslation';
const useStyles = makeStyles(theme => ({
btn: {
color: theme.palette.common.white,
margin: theme.spacing(),
},
}));
const MyFooter = props => {
const translate = useTranslation();
const { i18n } = useI18n();
const classes = useStyles();
return (
<Footer
copyright={`BlackBox Vision @${new Date().getFullYear()} - ${translate(
'footer.copyright'
)}`}
LanguageButtons={
<Hidden mdUp>
<Grid alignItems="center" justify="center" container>
<Grid item>
<Button
variant="text"
onClick={() => i18n.changeLanguage('es')}
aria-label={translate(`footer.language.es`)}
className={classes.btn}
>
{translate(`footer.language.es`)}
</Button>
</Grid>
<Grid item>
<Button
variant="text"
onClick={() => i18n.changeLanguage('en')}
aria-label={translate(`footer.language.en`)}
className={classes.btn}
>
{translate(`footer.language.en`)}
</Button>
</Grid>
</Grid>
</Hidden>
}
/>
);
};
MyFooter.displayName = 'Footer';
export default MyFooter;
| 27.842105 | 77 | 0.529931 |
1332aecce0ef150239c02f5a37a80eeb243d6f31 | 53,884 | js | JavaScript | tools/bcdist.js | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | tools/bcdist.js | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | tools/bcdist.js | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// System wide constants.
// These constants are not expected to change.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var CLASSID_MTSCRIPT = "{854c316d-c854-4a77-b189-606859e4391b}";
Error.prototype.toString = Error_ToString;
Object.prototype.toString = Object_ToString;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Global constants
// These are subject to change and tuning.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var g_aProcsToKill = ["mtscript.exe", "mshta.exe", "build.exe", "nmake.exe", "mtodaemon.exe"]; // "sleep.exe" is also killed seperately.
// The lists of files to copy.
// g_aCopyBCDistDir and g_aCopyBCDistDirD are the set of files which are in the same directory as this
// script is, and are necessary for the operation of bcdist itself.
// The g_aCopyBCDistDirD files are optional and are only necessary for running a debug MTScript.exe
var g_aCopyBCDistDirScript = ['registermtscript.cmd'];
var g_aCopyBCDistDir = ['bcrunas.exe', 'sleep.exe'];
var g_aCopyBCDistDirD = ['mshtmdbg.dll', 'msvcrtd.dll'];
// The g_aCopyFromScripts files are the Build Console Scripts.
// These files are copied from either the current directory or .\mtscript
var g_aCopyFromScripts = [ 'buildreport.js', 'harness.js', 'master.js', 'msgqueue.js',
'mtscript.js', 'publicdataupdate.js', 'robocopy.js',
'sendmail.js', 'slave.js', 'slaveproxy.js', 'slavetask.js',
'staticstrings.js', 'task.js', 'types.js', 'updatestatusvalue.js',
'utils.js', 'utilthrd.js',
'config_schema.xml', 'enviro_schema.xml'
];
// The g_aCopyFromBin files are the Build Console executable files.
// These files are copied from either the current directory or .\%ARCH% (x86, axp64,...)
var g_aCopyFromBin = [ 'mtscript.exe', 'mtlocal.dll', 'mtscrprx.dll', 'mtrcopy.dll', "mtodaemon.exe", "mtodproxy.dll"];
var g_strDropServer = "\\\\ptt\\cftools\\test\\bcrel";
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Global Variables
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var g_strMyLocation;
var g_objNet;
var g_strLocalHost;
var g_objFS;
var g_strShareDir;
var g_Opts;
if (DoLocalSetup())
{
g_Opts = ParseArguments(new DefaultArguments());
if (g_Opts)
{
if (main(g_Opts))
WScript.Quit(0);
}
}
WScript.Quit(1);
// GetMachineList(objArgs) //
// //
// Reads the XML BC environment template to extract the //
// list of machines in the build. //
// //
function GetMachineList(objArgs)
{
var xml = new ActiveXObject('Microsoft.XMLDOM');
var node;
var nodelist;
var objMach;
var nIndex;
xml.async = false;
// It's unlikely they have the schema file available for this template,
// so we turn off schema validation right now. The script engine will
// validate it when we start the build.
xml.validateOnParse = false;
xml.resolveExternals = false;
if (!xml.load(objArgs.strXMLFile) || !xml.documentElement)
{
Usage("Not a valid xml file: " + objArgs.strXMLFile);
}
node = xml.documentElement.selectSingleNode('BuildManager');
if (!node)
{
Usage("Not a valid xml file: " + objArgs.strXMLFile);
}
objArgs.aMachines[0] = new MachineInfo(node.getAttribute("Name"));
objArgs.aMachines[0].WriteStatusInfo("Initializing");
nodelist = xml.documentElement.selectNodes('Machine');
for (node = nodelist.nextNode(); node; node = nodelist.nextNode())
{
// Don't initialize the build manager machine twice
// just because it is also used in the building process
if ( objArgs.aMachines[0].strName.toLowerCase() == node.getAttribute("Name").toLowerCase() )
continue;
nIndex = objArgs.aMachines.length;
objArgs.aMachines[nIndex] = new MachineInfo(node.getAttribute("Name"));
objArgs.aMachines[nIndex].WriteStatusInfo("Initializing");
}
}
// GetStringArgument(objArgs, strMember) //
// //
// Helper function for ParseArguments. Stores the //
// next argument in the "strMember" member of "objArgs". //
// Exits script with Usage() if there is no available argument. //
function GetStringArgument(objArgs, strMember)
{
if (objArgs[strMember] == null)
{
LogMsg("ParseArguments internal error: Unknown member: " + strMember);
WScript.Quit(1);
}
objArgs.argn++;
if (objArgs.argn < objArgs.objArguments.length)
objArgs[strMember] = objArgs.objArguments(objArgs.argn);
else
Usage("missing paramter");
}
function ParseArguments(objArgs)
{
var strArg;
var chArg0;
var chArg1;
var nIndex;
var fMachineList = false;
for(objArgs.argn = 0; objArgs.argn < objArgs.objArguments.length; objArgs.argn++)
{
strArg = objArgs.objArguments(objArgs.argn);
chArg0 = strArg.charAt(0);
chArg1 = strArg.toLowerCase().slice(1);
if (chArg0 != '-' && chArg0 != '/')
{
if (objArgs.strXMLFile != '')
{
Usage("Enter an XML file or a list of the machines but not both");
}
else
{
fMachineList = true;
nIndex = objArgs.aMachines.length;
objArgs.aMachines[nIndex] = new MachineInfo(strArg);
objArgs.aMachines[nIndex].WriteStatusInfo("Initializing");
}
}
else
{
// Currently, no options
switch(chArg1)
{
case 'v':
objArgs.fVerbose = true;
break;
case 'd':
objArgs.argn++;
if (objArgs.argn < objArgs.objArguments.length)
{
if (objArgs.strSrcDir == '')
objArgs.nDropNum = Number(objArgs.objArguments(objArgs.argn));
else
Usage("Only one of -src and -d may be specified");
}
else
Usage("missing parameter for -d arugment");
if (objArgs.nDropNum < 1000 || objArgs.nDropNum >= 10000)
Usage("dropnum range is 1000...9999");
break;
case 'dropsrc':
GetStringArgument(objArgs, "strDropSrc");
break;
case 'src':
GetStringArgument(objArgs, "strSrcDir");
break;
case 'dst':
GetStringArgument(objArgs, "strDstDir");
break;
case 'u':
GetStringArgument(objArgs, "strUserName");
if (objArgs.strUserName == '*')
{
objArgs.strUserName = g_objNet.UserDomain + '\\' + g_objNet.UserName;
}
break;
//case 'p':
// GetStringArgument(objArgs, "strPassword");
// break;
case 'arch':
GetStringArgument(objArgs, "strArch");
break;
case 'f': // Entered an XML file on the command line. Get the list of machines from here.
if (fMachineList)
Usage("Enter an XML file or a list of the machines but not both");
GetStringArgument(objArgs, "strXMLFile");
GetMachineList(objArgs);
nIndex = objArgs.aMachines.length;
break;
case 'debug':
objArgs.strExeType = 'debug';
break;
default:
Usage("Unknown argument: " + strArg);
break;
}
}
}
if (objArgs.aMachines.length == 0)
Usage("you must specify one or more machine names or an XML file");
if (objArgs.nDropNum)
objArgs.strSrcDir = objArgs.strDropSrc + "\\" + objArgs.nDropNum;
else if (objArgs.strSrcDir == '')
Usage("you must specify a drop number or source location");
//if (objArgs.strUserName == '' || objArgs.strPassword == '')
// Usage("username and password required");
WScript.StdOut.Write('Enter Password:');
objArgs.strPassword = WScript.StdIn.ReadLine();
delete objArgs.objArguments;
delete objArgs.argn;
return objArgs;
}
function Usage(strError)
{
WScript.Echo('');
WScript.Echo('Usage: BCDist -u domain\\username ');
WScript.Echo(' [-v] [-d nnnn [-dropsrc path] | -src path] ');
WScript.Echo(' [-dst path] [-arch x86] [-debug] machines...');
WScript.Echo(' -u d\\u = domain\\username');
WScript.Echo(' -f xmlFile = environment xml template');
WScript.Echo(' -v = verbose');
WScript.Echo(' -d = drop number');
WScript.Echo(' -dropsrc = drop source location ("' + g_strDropServer + '")');
WScript.Echo(' -src = source directory');
WScript.Echo(' -dst = destination directory');
WScript.Echo(' -arch = Specifiy x86 or alpha');
WScript.Echo(' -debug = copy debug exes instead of retail');
WScript.Echo('Do NOT enter the password on the command line');
if (strError && strError != '')
{
WScript.Echo('');
WScript.Echo('Error: ' + strError);
}
WScript.Quit(1);
}
// DefaultArguments() //
// //
// Create an options object with the default //
// options filled in. //
function DefaultArguments()
{
var obj =
{
objArguments:WScript.Arguments,
argn:0,
aMachines:new Array(),
fVerbose:false,
nDropNum:0,
strDropSrc:g_strDropServer,
strSrcDir:'',
strDstDir:'',
strArch:"x86",
strExeType:"retail",
strUserName:'',
strPassword:'',
strXMLFile:''
};
return obj;
}
// DoLocalSetup() //
// //
// Setup some globals. Necessary before arugment parsing //
// can succeed. //
// //
function DoLocalSetup()
{
var i = -1;
var objFile;
var strPath;
var objLogin;
var objRemote;
try
{
g_objNet = WScript.CreateObject("WScript.Network");
g_strLocalHost = g_objNet.ComputerName;
g_objFS = new FileSystemObject();
g_strMyLocation = SplitFileName(WScript.ScriptFullName)[0];
LogMsg("Creating local share...");
objLogin =
{
strMachine:g_strLocalHost
}
objRemote = new WMIInterface(objLogin, '');
g_strShareDir = g_strMyLocation + "bcdiststatus";
g_objFS.CreateFolder(g_strShareDir);
strPath = objRemote.RemoteShareExists("BC_DISTSTATUS");
if (strPath != "")
g_strShareDir = strPath;
else
objRemote.RemoteCreateShare("BC_DISTSTATUS", g_strShareDir, "Build Console Distribution Status");
}
catch(ex)
{
LogMsg("BCDist failed to do local setup: " + ex);
return false;
}
return true;
}
function main(objOpts)
{
var strPath;
var strPathUNC;
var fSuccess = true;
var strDomain = objOpts.strUserName.split("\\")[0];
var strUser = objOpts.strUserName.split("\\")[1];
var fLocal;
var strCmd;
LogMsg("Upgrading the following machines:");
for(i = 0; i < objOpts.aMachines.length;++i)
{
LogMsg(" " + objOpts.aMachines[i].strName);
}
for(i = 0; i < objOpts.aMachines.length;++i)
{
fLocal = false;
strCmd = '';
try
{
LogMsg("Distributing to " + objOpts.aMachines[i].strName);
var objLogin =
{
strMachine:objOpts.aMachines[i].strName,
strUser:objOpts.strUserName, // Unneccessary if the same as the current user.
strPassword:objOpts.strPassword
}
if (objLogin.strMachine.toUpperCase() == g_objNet.ComputerName.toUpperCase())
{ // On the local host you may not specify a username
if (objLogin.strUser.toUpperCase() != (g_objNet.UserDomain + '\\' + g_objNet.UserName).toUpperCase())
throw new Error(-1, "Specified username does not match current login for local machine");
delete objLogin.strUser;
delete objLogin.strPassword;
fLocal = true;
}
objOpts.aMachines[i].WriteStatusInfo("Connecting");
var objRemote = new WMIInterface(objLogin, '');
var objRegistry = new WMIRegistry(objLogin);
objOpts.aMachines[i].WriteStatusInfo("Terminating MTScript.exe");
LogMsg(" Terminating remote processes");
TerminateMTScript(objRemote, objRegistry);
strPath = DetermineInstallPoint(objOpts, objRemote, objRegistry);
strPathUNC = PathToUNC(objOpts.aMachines[i].strName, strPath);
objOpts.aMachines[i].WriteStatusInfo("Copying files");
CopyFiles(objRemote, strPathUNC, objOpts);
objOpts.aMachines[i].WriteStatusInfo("Creating share");
ResetRegistry(objRegistry, strPath);
objOpts.aMachines[i].WriteStatusInfo("Registering");
objOpts.aMachines[i].DisableWriteStatusInfo();
LogMsg(" Registering");
// We don't use BCRunAs when running on the local machine.
if (!fLocal)
{
// Usage: BCRunAs UserName Domain Password CWD Cmdline
//
strCmd = strPath + '\\BCRunAs.exe ' + strUser + ' ' +
strDomain + ' "' + objOpts.strPassword + '" "';
}
strCmd += 'cmd.exe /K ' + strPath + "\\RegisterMTScript.cmd " +
g_strLocalHost;
if (!fLocal)
{
strCmd += '"';
}
objRemote.RemoteExecuteCmd(strCmd, strPath);
// Do not write any more status after this point -- the remote machine should do it now.
}
catch(ex)
{
fSuccess = false;
objOpts.aMachines[i].WriteStatusInfo("FAILED " + ex);
}
}
if (! CheckStatus(objOpts) )
fSuccess = false;
return fSuccess;
}
function CheckStatus(objOpts)
{
var i;
var fTerminalState;
var strStatus;
var aStatus;
var aState = new Array()
var fChanged;
LogMsg("");
LogMsg("Current status on the remote machines...(Press Ctrl-C to quit)");
do
{
fTerminalState = true;
fChanged = false;
for(i = 0; i < objOpts.aMachines.length;++i)
{
strStatus = objOpts.aMachines[i].ReadStatusInfo();
aStatus = strStatus.split(" ");
if (aStatus.length == 0 || aStatus[0] != 'OK' && aStatus[0] != 'FAILED')
fTerminalState = false;
if (aState[i] == null || aState[i] != strStatus)
{
aState[i] = strStatus;
fChanged = true;
}
}
if (fChanged)
{
for(i = 0; i < objOpts.aMachines.length;++i)
LogMsg(objOpts.aMachines[i].strName + ": " + aState[i]);
if (!fTerminalState)
LogMsg("Waiting...");
LogMsg("");
}
if (!fTerminalState)
WScript.Sleep(1000);
} while(!fTerminalState);
}
// TerminateMTScript(objRemote, objRegistry) //
// //
// Using WMI, terminate processes which may be involved //
// in a build. This is neccessary before a BC upgrade can happen. //
// Also, remote "mtscript.exe" to prevent it getting restarted //
// prematurely. //
// //
function TerminateMTScript(objRemote, objRegistry)
{
var i;
var fRenamed = false;
var strMTScriptPath = ''
try
{
strMTScriptPath = objRegistry.GetExpandedStringValue(WMIRegistry.prototype.HKCR, "CLSID\\" + CLASSID_MTSCRIPT + "\\LocalServer32", '');
}
catch(ex)
{
}
if (strMTScriptPath != '')
{
if (objRemote.RemoteFileExists(strMTScriptPath + ".UpdateInProgress"))
objRemote.RemoteDeleteFile(strMTScriptPath + ".UpdateInProgress");
if (objRemote.RemoteFileExists(strMTScriptPath) &&
objRemote.RemoteRenameFile(strMTScriptPath, strMTScriptPath + ".UpdateInProgress"))
{
fRenamed = true;
}
}
for(i = 0; i < g_aProcsToKill.length; ++i)
objRemote.RemoteTerminateExe(g_aProcsToKill[i], 1);
objRemote.RemoteTerminateExe("sleep.exe", 0); // If sleep.exe sets ERRORLEVEL != 0, then the remote cmd.exe windows will not close.
if (fRenamed)
{
for( i = 3; i >= 0; --i)
{
try
{
objRemote.RemoteDeleteFile(strMTScriptPath + ".UpdateInProgress");
}
catch(ex)
{
if (i == 0)
throw ex;
WScript.Sleep(500); // It sometimes takes a little while for the remote mtscript.exe to quit.
continue;
}
break;
}
}
return true;
}
// DetermineInstallPoint(objOpts, objRemote, objRegistry) //
// //
// If the user has supplied a destination path, use that. //
// Otherwise if mtscript.exe has previously been registered on the remote machine //
// then install to the same location. //
// Else, report an error. //
function DetermineInstallPoint(objOpts, objRemote, objRegistry)
{
var strMTScriptPath = ''
if (objOpts.strDstDir != '')
return objOpts.strDstDir;
try
{
strMTScriptPath = objRegistry.GetExpandedStringValue(WMIRegistry.prototype.HKCR, "CLSID\\" + CLASSID_MTSCRIPT + "\\LocalServer32", '');
}
catch(ex)
{
}
if (strMTScriptPath != '')
strMTScriptPath = SplitFileName(strMTScriptPath)[0];
else
throw new Error(-1, "-dst must be specified -- mtscript was not previously registered");
return strMTScriptPath;
}
// CopyFiles(objRemote, strDstPath, objOpts) //
// //
// Copy the necessary files to the remote machine. //
// The files are always copied to a "flat" install -- the executables and the scripts //
// and as the same directory level. //
// The files in a daily drop are not flat - the executables and the //
// scripts are in seperate directories. //
function CopyFiles(objRemote, strDstPath, objOpts)
{
var i;
var strSourcePath;
var strDstPathUNC;
var strAltLocation;
strSourcePath = RemoveEndChar(objOpts.strSrcDir, "\\");
strDstPathUNC = RemoveEndChar(strDstPath, "\\");
Trace("Copy files from " + strSourcePath + " to " + strDstPathUNC);
g_objFS.CreateFolder(strDstPathUNC);
strAltLocation = strSourcePath + "\\" + objOpts.strArch;
CopyListOfFiles(g_aCopyBCDistDirScript, g_strMyLocation, null, strDstPathUNC, true);
if (objOpts.nDropNum)
{
LogMsg(" Copying files from drop " + strSourcePath);
CopyListOfFiles(g_aCopyFromScripts, strSourcePath + "\\scripts", null, strDstPathUNC, true);
CopyListOfFiles(g_aCopyBCDistDir, strSourcePath + "\\" + objOpts.strArch + "\\" + objOpts.strExeType, null, strDstPathUNC, true);
CopyListOfFiles(g_aCopyBCDistDirD, strSourcePath + "\\" + objOpts.strArch + "\\" + objOpts.strExeType, null, strDstPathUNC, false);
CopyListOfFiles(g_aCopyFromBin, strSourcePath + "\\" + objOpts.strArch + "\\" + objOpts.strExeType, null, strDstPathUNC, true);
}
else
{
LogMsg(" Copying files from " + strSourcePath);
CopyListOfFiles(g_aCopyFromScripts, strSourcePath, strSourcePath + "\\mtscript", strDstPathUNC, true);
CopyListOfFiles(g_aCopyBCDistDir, strSourcePath, strSourcePath + "\\" + objOpts.strArch, strDstPathUNC, true);
CopyListOfFiles(g_aCopyBCDistDirD, strSourcePath, strSourcePath + "\\" + objOpts.strArch, strDstPathUNC, false);
CopyListOfFiles(g_aCopyFromBin, strSourcePath, strSourcePath + "\\" + objOpts.strArch, strDstPathUNC, true);
}
}
// CopyListOfFiles(aFiles, strSrc, strAltSrc, strDst, fRequired) //
// //
// Copy a list of files. //
// Check for the existance of each file in either the strSrc or strAltSrc path. //
// Copy to the strDst path. //
// If a file does not exist, and fRequired is set, then throw an exception. //
function CopyListOfFiles(aFiles, strSrc, strAltSrc, strDst, fRequired)
{
var i;
for(i = 0; i < aFiles.length; ++i)
{
if (g_objFS.FileExists(strSrc + "\\" + aFiles[i]))
g_objFS.CopyFile(strSrc + "\\" + aFiles[i], strDst + "\\" + aFiles[i]);
else if (strAltSrc && g_objFS.FileExists(strAltSrc + "\\" + aFiles[i]))
g_objFS.CopyFile(strAltSrc + "\\" + aFiles[i], strDst + "\\" + aFiles[i]);
else if (fRequired)
throw new Error(-1, "File not found: " + strSrc + "\\" + aFiles[i]);
}
}
// ResetRegistry(objRegistry, strPath) //
// //
// Reset the registry entries for the script path. //
function ResetRegistry(objRegistry, strPath)
{
objRegistry.CreateKey(WMIRegistry.prototype.HKCU, "Software\\Microsoft\\MTScript\\File Paths");
objRegistry.SetStringValue(WMIRegistry.prototype.HKCU, "Software\\Microsoft\\MTScript\\File Paths", "Script Path", strPath);
objRegistry.SetStringValue(WMIRegistry.prototype.HKCU, "Software\\Microsoft\\MTScript\\File Paths", "Initial Script", "mtscript.js");
}
//*********************************************************************
//*********************************************************************
//*********************************************************************
//*********************************************************************
// Library funtions
// SplitFileName(strPath)
// Return an array of 3 elements, path,filename,extension
// [0] == "C:\path\"
// [1] == "filename"
// [2] == ".ext"
function SplitFileName(strPath)
{
var nDot = strPath.lastIndexOf('.');
var nSlash = strPath.lastIndexOf('\\');
var nColon = strPath.lastIndexOf(':');
if (nDot >= 0 && nDot > nSlash && nDot > nColon)
{
return [strPath.slice(0, nSlash + 1), strPath.slice(nSlash + 1, nDot), strPath.slice(nDot)];
}
// We get here if the file had no extension
if (nSlash >= 2) // do not slice the UNC double \ at the start of a filename.
{
return [strPath.slice(0, nSlash + 1), strPath.slice(nSlash + 1, nDot), ''];
}
return ['', strPath, ''];
}
// RemoveEndChar(str, strChar) //
// //
// If 'strChar' appears as the last character //
// in a string, remove it. //
function RemoveEndChar(str, strChar)
{
var length = str.length;
if (str.charAt(length - 1) == strChar)
str = str.slice(0, length - 1);
return str;
}
function PathToUNC(strMachineName, strPath)
{
return "\\\\" +
strMachineName +
"\\" +
strPath.charAt(0) +
"$" +
strPath.slice(2)
}
function Assert(fOK, msg)
{
if (!fOK)
{
var caller = GetCallerName(null);
LogMsg("ASSERTION FAILED :(" + caller + ") " + msg);
WScript.Quit(0);
}
}
function unevalString(str)
{
var i;
var newstr = '"';
var c;
for(i = 0; i < str.length; ++i)
{
c = str.charAt(i);
switch(c)
{
case'\\':
newstr += "\\\\";
break;
case '"':
newstr += '\\"';
break;
case "'":
newstr += "\\'";
break;
case "\n":
newstr += "\\n";
break;
case "\r":
newstr += "\\r";
break;
case "\t":
newstr += "\\t";
break;
default:
newstr += c;
break;
}
}
return newstr + '"';
}
// Object_ToString() //
// //
// Provide a useful version of conversion //
// from "object" to string - great for dumping //
// objects to the debug log. //
function Object_ToString()
{
var i;
var str = "{";
var strComma = '';
for(i in this)
{
str += strComma + i + ":" + this[i];
strComma = ', ';
}
return str + "}";
}
function Error_ToString()
{
var i;
var str = 'Exception(';
/*
Only some error messages get filled in for "ex".
Specifically the text for disk full never seems
to get set by functions such as CreateTextFile().
*/
if (this.number != null && this.description == '')
{
switch(this.number)
{
case -2147024784:
this.description = "There is not enough space on the disk.";
break;
case -2147024894:
this.description = "The system cannot find the file specified.";
break;
case -2147023585:
this.description = "There are currently no logon servers available to service the logon request.";
break;
case -2147023170:
this.description = "The remote procedure call failed.";
break;
case -2147024837:
this.description = "An unexpected network error occurred";
break;
case -2147024890:
this.description = "The handle is invalid.";
break;
default:
this.description = "Error text not set for (" + this.number + ")";
break;
}
}
if (this.description)
{
var end = this.description.length - 1;
while (this.description.charAt(end) == '\n' || this.description.charAt(end) == '\r')
{
end--;
}
this.description = this.description.slice(0, end+1);
}
for(i in this)
{
str += i + ": " + this[i] + " ";
}
return str + ")";
}
function LogMsg(msg)
{
WScript.Echo(msg);
}
function Trace(msg)
{
if (g_Opts && g_Opts.fVerbose)
WScript.Echo(" TRACE: " + msg);
}
function GetCallerName(cIgnoreCaller)
{
var tokens;
if (cIgnoreCaller == null)
cIgnoreCaller = 0;
++cIgnoreCaller;
var caller = GetCallerName.caller;
while (caller != null && cIgnoreCaller)
{
caller = caller.caller;
--cIgnoreCaller;
}
if (caller != null)
{
tokens = caller.toString().split(/ |\t|\)|,/);
if (tokens.length > 1 && tokens[0] == "function")
{
return tokens[1] + ")";
}
}
return "<undefined>";
}
// class WMIInterface(objLogin, strNameSpace) //
// //
// This class provides an easier to use interface to the WMI //
// functionality. //
// //
// You must provide login information and the WMI namespace //
// you wish to use. //
// //
// RemoteFileExists(strPath) NOTHROW //
// returns true if the given file exists on the remote machine //
// //
// RemoteRenameFile(strFrom, strTo) //
// Renames the given file. //
// Throws on any error. //
// //
// RemoteDeleteFile(strPath) //
// Delete the file. //
// Throws on any error. //
// //
// RemoteTerminateExe(strExeName) //
// Terminates all processes with the given name. //
// Does not throw if the process does not exist. //
// It will throw if the RPC to terminate a process fails. //
// Does not return error status. //
// //
// RemoteExecuteCmd(strCmd, strDirectory) //
// Runs the given command in the specified directory. //
// It will throw if the RPC to start the process fails. //
// Its not possible to retrieve status from the command //
// which is run. //
// //
// RemoteDeleteShare(strShareName) //
// If the named share exists, remove it. //
// Throw on error (except if the error is "not found") //
// //
// RemoteCreateShare(strShareName, strSharePath, strShareComment) //
// Create a share name "strShareName" with the given path and comment. //
// Throw on error (it is an error if strShareName is already shared). //
// //
// RemoteShareExists(strShareName) //
// Returns the shared path, or "" //
// does not throw any errors. //
// //
function WMIInterface(objLogin, strNameSpace)
{
try
{
WMIInterface.prototype.wbemErrNotFound = -2147217406;
WMIInterface.prototype.RemoteFileExists = _WMIInterface_FileExists;
WMIInterface.prototype.RemoteRenameFile = _WMIInterface_RenameFile;
WMIInterface.prototype.RemoteDeleteFile = _WMIInterface_DeleteFile;
WMIInterface.prototype.RemoteTerminateExe = _WMIInterface_TerminateExe;
WMIInterface.prototype.RemoteExecuteCmd = _WMIInterface__ExecuteCMD;
WMIInterface.prototype.RemoteDeleteShare = _WMIInterface__DeleteShare;
WMIInterface.prototype.RemoteCreateShare = _WMIInterface__CreateShare;
WMIInterface.prototype.RemoteShareExists = _WMIInterface__ShareExists;
// Private methods
WMIInterface.prototype._FindFiles = _WMIInterface__FindFiles;
WMIInterface.prototype._FileOperation = _WMIInterface__FileOperation;
if (!strNameSpace || strNameSpace == '')
strNameSpace = "root\\cimv2";
this._strNameSpace = strNameSpace;
this._objLogin = objLogin;
this._objLocator = new ActiveXObject("WbemScripting.SWbemLocator");
this._objService = this._objLocator.ConnectServer(this._objLogin.strMachine, this._strNameSpace, this._objLogin.strUser, this._objLogin.strPassword);
this._objService.Security_.impersonationlevel = 3
}
catch(ex)
{
LogMsg("WMIInterface logon failed " + ex);
throw ex;
}
}
function _WMIInterface__FindFiles(strPattern)
{
var objFileSet = this._objService.ExecQuery('Select * from CIM_DataFile Where name=' + unevalString(strPattern));
if (!objFileSet.Count)
throw new Error(-1, "File not found: " + strPattern);
return objFileSet;
}
function _WMIInterface__FileOperation(strPattern, strOperation, objInArgs)
{
try
{
var objFileSet = this._FindFiles(strPattern);
var enumSet = new Enumerator(objFileSet);
for (; !enumSet.atEnd(); enumSet.moveNext())
{
Trace("remote " + strOperation + " " + (objInArgs ? objInArgs : ''));
var objOut = CallMethod(enumSet.item(), strOperation, objInArgs);
break;
}
}
catch(ex)
{
ex.description = strOperation + '(' + strPattern + ')' + " Failed, " + ex.description;
throw ex;
}
return true;
}
function _WMIInterface_FileExists(strName)
{
try
{
var objFileSet = this._objService.ExecQuery('Select * from CIM_DataFile Where name=' + unevalString(strName));
if (objFileSet.Count)
return true;
}
catch(ex)
{
}
Trace("RemoteFileExists: not found " + strName);
return false;
}
function _WMIInterface_RenameFile(strFrom, strTo)
{
return this._FileOperation(strFrom, "Rename", {FileName:strTo});
}
function _WMIInterface_DeleteFile(strName)
{
return this._FileOperation(strName, "Delete");
}
function _WMIInterface_TerminateExe(strName, nExitCode)
{
var setQueryResults = this._objService.ExecQuery("Select Name,ProcessId From Win32_Process");
var enumSet = new Enumerator(setQueryResults);
var nCount = 0;
for( ; !enumSet.atEnd(); enumSet.moveNext())
{
var item = enumSet.item();
if (item.Name == strName)
{
var outParam = CallMethod(item, "Terminate", {Reason:nExitCode}); // Reason will be the return code.
Trace("Killed " + item.Name + " pid = " + item.ProcessId);
nCount++;
}
}
if (!nCount)
Trace("Cannot terminate process " + strName + ": not found");
}
function _WMIInterface__ExecuteCMD(strCmd, strDir)
{
try
{
Trace("Executing :" + strCmd);
var objInstance = this._objService.Get("Win32_Process");
var outParam = CallMethod(objInstance, "Create",
{
CommandLine:strCmd,
CurrentDirectory:strDir
});
//EnumerateSetOfProperties("outParam properties", outParam.Properties_);
Trace("ExecuteCMD " + strCmd + ", pid = " + outParam.ProcessId);
}
catch(ex)
{
ex.description = "ExecuteCMD " + strCmd + " failed " + ex.description;
throw ex;
}
}
function _WMIInterface__DeleteShare(strShareName)
{
try
{
var objInstance = this._objService.Get("Win32_Share='" + strShareName + "'");
Trace("DeleteShare " + objInstance.Name + "," + objInstance.Path);
CallMethod(objInstance, "Delete");
}
catch(ex)
{
if (ex.number != this.wbemErrNotFound)
{
ex.description = "DeleteShare " + strShareName + " failed " + ex.description;
throw ex;
}
else
Trace("DeleteShare " + strShareName + " not found");
}
}
function _WMIInterface__ShareExists(strShareName)
{
try
{
var objInstance = this._objService.Get("Win32_Share='" + strShareName + "'");
Trace("ShareExists " + objInstance.Name + "," + objInstance.Path);
return objInstance.Path;
}
catch(ex)
{
if (ex.number != this.wbemErrNotFound)
{
ex.description = "ShareExists " + strShareName + " failed " + ex.description;
throw ex;
}
else
Trace("ShareExists " + strShareName + " not found");
}
return "";
}
function _WMIInterface__CreateShare(strShareName, strSharePath, strShareComment)
{
try
{
var objInstance = this._objService.Get("Win32_Share");
var outParam = CallMethod(
objInstance,
"Create",
{
Description:strShareComment,
Name:strShareName,
Path:strSharePath,
Type:0
});
}
catch(ex)
{
ex.description = "CreateShare " + strShareName + " failed " + ex.description;
throw ex;
}
}
// class WMIRegistry(objLogin) //
// Class to enable remote registry access via WMI //
// //
// This class provides an easier to use interface to the WMI //
// functionality. //
// //
// You must provide login information and the WMI namespace //
// you wish to use. //
// //
// GetExpandedStringValue(hkey, strSubKeyName, strValueName) //
// Retieves the string value for the given registry key. //
// If strValueName == '', then retrieve the default value. //
// //
// If the value is of type REG_EXPAND_SZ, then the returned //
// string will be the expanded value. //
// //
// Throw any errors. //
// //
// SetStringValue(hkey, strSubKeyName, strValueName, strValue) //
// Sets a string value for the given registry key. //
// If strValueName == '', then set the default value. //
// Throw any errors. //
// //
// CreateKey(hkey, strSubKeyName) //
// Create the specified registry key. //
// Multiple levels of keys can be created at once. //
// It is not an error to create a key which already exists. //
// //
// Throw any errors. //
function WMIRegistry(objLogin)
{
try
{
WMIRegistry.prototype.HKCR = 0x80000000; // Required by StdRegProv
WMIRegistry.prototype.HKCU = 0x80000001; // Required by StdRegProv
WMIRegistry.prototype.GetExpandedStringValue = _WMIRegistry_GetExpandedStringValue;
WMIRegistry.prototype.SetStringValue = _WMIRegistry_SetStringValue;
WMIRegistry.prototype.CreateKey = _WMIRegistry_CreateKey;
this._objRemote = new WMIInterface(objLogin, "root\\default");
this._objInstance = this._objRemote._objService.Get("StdRegProv");
}
catch(ex)
{
LogMsg("WMIRegistry failed " + ex);
throw ex;
}
}
function _WMIRegistry_GetExpandedStringValue(hkey, strSubKeyName, strValueName)
{
try
{
var outParam = CallMethod(this._objInstance, "GetExpandedStringValue", {hDefKey:hkey, sSubKeyName:strSubKeyName, sValueName:strValueName});
return outParam.sValue;
}
catch(ex)
{
ex.description = "GetExpandedStringValue failed ('" + strSubKeyName + "', '" + strValueName + "'): " + ex.description;
throw ex;
}
}
function _WMIRegistry_SetStringValue(hkey, strSubKeyName, strValueName, strValue)
{
try
{
var outParam = CallMethod(this._objInstance, "SetStringValue", {hDefKey:hkey, sSubKeyName:strSubKeyName, sValueName:strValueName, sValue:strValue});
// outParam.ReturnValue == 0;
}
catch(ex)
{
ex.description = "SetStringValue failed ('" + strSubKeyName + "', '" + strValueName + "'): " + ex.description;
throw ex;
}
}
function _WMIRegistry_CreateKey(hkey, strSubKeyName)
{
try
{
var outParam = CallMethod(this._objInstance, "CreateKey", {hDefKey:hkey, sSubKeyName:strSubKeyName});
}
catch(ex)
{
ex.description = "CreateKey failed ('" + strSubKeyName + "', '" + strValueName + "'): " + ex.description;
throw ex;
}
}
// FileSystemObject() //
// //
// Provide enhanced file system access. //
// The primary functionaly here is to provide better error //
// reporting. //
function FileSystemObject()
{
if (!FileSystemObject.prototype.objFS)
{
FileSystemObject.prototype.objFS = new ActiveXObject("Scripting.FileSystemObject");
FileSystemObject.prototype.FileExists = _FileSystemObject_FileExists;
FileSystemObject.prototype.FolderExists = _FileSystemObject_FolderExists;
FileSystemObject.prototype.CreateFolder = _FileSystemObject_CreateFolder;
FileSystemObject.prototype.DeleteFile = _FileSystemObject_DeleteFile;
FileSystemObject.prototype.DeleteFolder = _FileSystemObject_DeleteFolder;
FileSystemObject.prototype.MoveFolder = _FileSystemObject_MoveFolder;
FileSystemObject.prototype.CopyFolder = _FileSystemObject_CopyFolder;
FileSystemObject.prototype.CopyFile = _FileSystemObject_CopyFile;
FileSystemObject.prototype.CreateTextFile = _FileSystemObject_CreateTextFile;
FileSystemObject.prototype.OpenTextFile = _FileSystemObject_OpenTextFile;
}
}
function _FileSystemObject_FileExists(str)
{
try
{
var fRet = this.objFS.FileExists(str);
Trace("FileExists('" + str + "') = " + fRet);
return fRet;
}
catch(ex)
{
ex.description = "FileExists('" + str + "') failed: " + ex.description;
throw ex;
}
}
function _FileSystemObject_FolderExists(str)
{
try
{
var fRet = this.objFS.FolderExists(str);
Trace("FolderExists('" + str + "') = " + fRet);
return fRet;
}
catch(ex)
{
Trace("FolderExists('" + str + "') failed: " + ex);
return false;
}
}
function _FileSystemObject_CreateFolder(str)
{
try
{
if (!this.FolderExists(str))
this.objFS.CreateFolder(str);
}
catch(ex)
{
ex.description = "CreateFolder('" + str + "') failed: " + ex.description;
throw ex;
}
}
function _FileSystemObject_DeleteFile(str)
{
try
{
Trace("DeleteFile '" + str + "'");
this.objFS.DeleteFile(str, true);
}
catch(ex)
{
ex.description = "DeleteFile(" + str + ") failed " + ex.description;
throw ex;
}
}
function _FileSystemObject_DeleteFolder(str)
{
try
{
Trace("DeleteFolder '" + str + "'");
this.objFS.DeleteFolder(str, true);
}
catch(ex)
{
ex.description = "DeleteFolder('" + str + "' failed: " + ex.description;
throw ex;
}
}
function _FileSystemObject_MoveFolder(str, strDst)
{
try
{
Trace("MoveFolder '" + str + "', '" + strDst + "'");
this.objFS.MoveFolder(str, strDst);
}
catch(ex)
{
ex.description = "MoveFolder('" + str + "', '" + strDst + "' failed: " + ex.description;
throw ex;
}
}
function _FileSystemObject_CreateTextFile(strFileName, fOverwrite)
{
do
{
Trace("CreateTextFile '" + strFileName + "'");
try
{
return this.objFS.CreateTextFile(strFileName, fOverwrite);
}
catch(ex)
{
if (fOverwrite && this.FileExists(strFileName))
{
Trace(" CreateTextFile: Attempt to delete " + strFileName);
this.DeleteFile(strFileName);
continue;
}
ex.description = "CreateTextFile('" + strFileName + "' failed: " + ex.description;
throw ex;
}
} while(true);
}
function _FileSystemObject_OpenTextFile(strFileName)
{
var objFile;
do
{
try
{
objFile = this.objFS.OpenTextFile(strFileName, 1);
Trace("OpenTextFile '" + strFileName + "' success");
return objFile;
}
catch(ex)
{
ex.description = "OpenTextFile('" + strFileName + "' failed: " + ex.description;
throw ex;
}
} while(true);
}
function _FileSystemObject_CopyFile(str, strDst)
{
do
{
Trace("CopyFile '" + str + "', '" + strDst + "'");
try
{
this.objFS.CopyFile(str, strDst, true);
break;
}
catch(ex)
{
if (this.FileExists(strDst))
{
Trace(" CopyFile: Attempt to delete " + strDst);
this.DeleteFile(strDst);
continue;
}
ex.description = "CopyFile('" + str + "', '" + strDst + "' failed: " + ex.description;
throw ex;
}
} while(true);
}
function _FileSystemObject_CopyFolder(str, strDst)
{
var strName;
var folder;
var fc;
try
{
Trace("CopyFolder '" + str + "', '" + strDst + "'");
this.CreateFolder(strDst);
folder = this.objFS.GetFolder(str);
fc = new Enumerator(folder.Files);
for (; !fc.atEnd(); fc.moveNext())
{
strName = String(fc.item());
this.CopyFile(strName, strDst + "\\" + fc.item().Name);
}
fc = new Enumerator(folder.SubFolders);
for (; !fc.atEnd(); fc.moveNext())
{
strName = String(fc.item());
this.CopyFolder(strName, strDst + "\\" + fc.item().Name);
}
}
catch(ex)
{
Trace("CopyFolder('" + str + "', '" + strDst + "' failed: " + ex);
throw ex;
}
}
function MachineInfo(strName)
{
this.strName = strName;
this.strStatusFile = g_strShareDir + "\\" + strName + ".txt";
this.fDisabledWriteStatus = false;
MachineInfo.prototype.ReadStatusInfo = _MachineInfo_ReadStatusInfo;
MachineInfo.prototype.WriteStatusInfo = _MachineInfo_WriteStatusInfo;
MachineInfo.prototype.DisableWriteStatusInfo = _MachineInfo_DisableWriteStatusInfo;
}
function _MachineInfo_DisableWriteStatusInfo()
{
this.fDisabledWriteStatus = true;
}
function _MachineInfo_ReadStatusInfo(strText)
{
var strText;
var objFile;
try
{
objFile = g_objFS.OpenTextFile(this.strStatusFile);
strText = objFile.ReadLine();
objFile.Close();
}
catch(ex)
{
strText = "cannot read status file";
}
return strText;
}
function _MachineInfo_WriteStatusInfo(strText)
{
var objFile;
try
{
Trace("WriteStatusInfo(" + strText + ") for " + this.strName);
if (this.fDisabledWriteStatus)
{
LogMsg("Error: Attempting to write status to " + this.strName + " after disabling");
}
else
{
objFile = g_objFS.CreateTextFile(this.strStatusFile, true);
objFile.WriteLine(strText);
objFile.Close();
}
}
catch(ex)
{
LogMsg("WriteStatusInfo(" + strText + ") for " + this.strName + " failed: " + ex);
}
}
//*********************************************************************
//*********************************************************************
// CallMethod(objInstance, strMethodName, hParameters) //
// //
// Call a method on the given object, with the supplied //
// named parameters. //
// //
// Throw if the method returns a non-zero ReturnValue. //
// Else return the outParams. //
function CallMethod(objInstance, strMethodName, hParameters)
{
try
{
Trace("CallMethod " + strMethodName + " " + (hParameters ? hParameters : ''));
var objMethod = objInstance.Methods_(strMethodName);
var inParams;
var outParam;
if (hParameters)
{
if (objMethod.inParameters)
inParams = objMethod.inParameters.SpawnInstance_();
}
var strParamName;
if (hParameters)
{
for(strParamName in hParameters)
inParams[strParamName] = hParameters[strParamName];
outParam = objInstance.ExecMethod_(strMethodName, inParams);
}
else
outParam = objInstance.ExecMethod_(strMethodName);
}
catch(ex)
{
ex.description = "CallMethod " + strMethodName + (hParameters ? hParameters : '()') + " failed " + ex.description;
throw ex;
}
if (outParam.ReturnValue != 0)
throw new Error(outParam.ReturnValue, "Method " + strMethodName + " failed");
return outParam;
}
function EnumerateSetOfProperties(strSetName, SWBemSet, strIndent)
{
var fPrint = false;
if (!strIndent)
{
strIndent = '';
fPrint = true;
}
var strMsg = strIndent + strSetName + "+\n";
strIndent += " ";
try
{
var enumSet = new Enumerator(SWBemSet);
for( ; !enumSet.atEnd(); enumSet.moveNext())
{
var item = enumSet.item();
if (item.Properties_ == null)
{
if (item.Name != "Name")
strMsg += strIndent + item.Name + " = " + item.Value + "\n";
}
else
{
strMsg += EnumerateSetOfProperties(item.Name, item.Properties_, strIndent);
}
}
if (fPrint)
LogMsg(strMsg);
}
catch(ex)
{
if (strIndent == " " && SWBemSet.Properties_ != null)
return EnumerateSetOfProperties(strSetName, SWBemSet.Properties_);
LogMsg("ERROR: " + strSetName + " " + ex);
}
return strMsg;
}
| 36.066934 | 158 | 0.498126 |
13335d11f8de5a208020315dfd522ada07a92bc2 | 1,222 | js | JavaScript | source/MongoModule/ResultHandlers/ResultHandler.js | KisanHub/mongojs | e789b18bc91961c95a02f0f70b7e9ecfbf5c011c | [
"CC0-1.0"
] | 3 | 2015-02-24T06:45:49.000Z | 2015-05-08T10:31:40.000Z | source/MongoModule/ResultHandlers/ResultHandler.js | KisanHub/mongojs | e789b18bc91961c95a02f0f70b7e9ecfbf5c011c | [
"CC0-1.0"
] | null | null | null | source/MongoModule/ResultHandlers/ResultHandler.js | KisanHub/mongojs | e789b18bc91961c95a02f0f70b7e9ecfbf5c011c | [
"CC0-1.0"
] | null | null | null | /*
This file is part of mongojs. It is subject to the licence terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/KisanHub/mongojs/master/COPYRIGHT. No part of mongojs, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
Copyright © 2015 The developers of mongojs. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/KisanHub/mongojs/master/COPYRIGHT.
*/
var VirtualMethodException = ClassModule.VirtualMethodException
ClassModule.Object.extend
(
module,
function ResultHandler()
{
this.super(ResultHandler)
},
// tuple, [true / false get more, batchSize]
function results(documents, moreAvailable, wasCursorNotFound, didGetMoreOrQueryButNotCommandFail)
{
throw new VirtualMethodException()
}
)
// in the original OP_QUERY, -(number) means return that number and close
// (number) means batchSize
// (0) means server-default batch sizes
module.ResultHandler.NoMoreResults =
{
getMore: false,
batchSize: 0
}
module.ResultHandler.AnyNumberMoreResults =
{
getMore: true,
batchSize: 0
}
| 32.157895 | 372 | 0.783142 |
1333a4e5489e6ce8328dfcf63b149dbe4baee5de | 609 | js | JavaScript | test/types/Date-type.spec.js | unexpectedjs/unexpected | e7cec598a0dfd385f836c22227d3e8d334e45d36 | [
"MIT"
] | 386 | 2015-03-03T15:44:40.000Z | 2022-01-04T08:27:44.000Z | test/types/Date-type.spec.js | unexpectedjs/unexpected | e7cec598a0dfd385f836c22227d3e8d334e45d36 | [
"MIT"
] | 546 | 2015-03-02T19:11:47.000Z | 2022-01-03T12:08:04.000Z | test/types/Date-type.spec.js | unexpectedjs/unexpected | e7cec598a0dfd385f836c22227d3e8d334e45d36 | [
"MIT"
] | 39 | 2015-04-26T19:36:14.000Z | 2021-09-12T19:24:16.000Z | /* global expect */
describe('Date type', () => {
it('inspects as an ISO string', () => {
expect(new Date(0), 'to inspect as', "new Date('1970-01-01T00:00:00Z')");
});
it('inspects with three milliseconds digits when the milliseconds field has two digits', () => {
expect(
new Date(10),
'to inspect as',
"new Date('1970-01-01T00:00:00.010Z')"
);
});
it('inspects with three milliseconds digits when the milliseconds field has three digits', () => {
expect(
new Date(100),
'to inspect as',
"new Date('1970-01-01T00:00:00.100Z')"
);
});
});
| 26.478261 | 100 | 0.577997 |
1334fb87e315448ba290138931447c0a1cd8d502 | 923 | js | JavaScript | NumberFormat.js | jpavley/eloquentjs | 9684dce20716628743f5389a19a5370420441e7c | [
"MIT"
] | null | null | null | NumberFormat.js | jpavley/eloquentjs | 9684dce20716628743f5389a19a5370420441e7c | [
"MIT"
] | null | null | null | NumberFormat.js | jpavley/eloquentjs | 9684dce20716628743f5389a19a5370420441e7c | [
"MIT"
] | null | null | null | /**
* NumberFormat.js
*/
// Special case Negative 1 in 2's Compliment
let d = "-1".padStart(2,"0");
let h = "FF".padStart(2,"0");
let b = "11111111".padStart(8,"0");
console.log(`dec ${d} hex 0x${h} bin 0b${b}`);
// from -1 to 31
for (let i = 0; i < 32; i += 1) {
let d = i.toString().padStart(2,"0").toUpperCase();
let h = i.toString(16).padStart(2,"0").toUpperCase();
let b = i.toString(2).padStart(8,"0").toUpperCase();
console.log(`dec ${d} hex 0x${h} bin 0b${b}`);
}
// characters A thru Z
console.log("| char | dec | hex | bin |");
console.log("|-----:|----:|----:|----:|");
for (let c = 'a'.charCodeAt(0); c <= 'z'.charCodeAt(0); c += 1) {
let l = String.fromCharCode(c);
let d = c.toString().padStart(2,"0").toUpperCase();
let h = c.toString(16).padStart(2,"0").toUpperCase();
let b = c.toString(2).padStart(8,"0").toUpperCase();
console.log(`| ${l} | ${d} | 0x${h} | 0b${b} |`);
} | 24.289474 | 65 | 0.551463 |
133510b45dd1df610c7e40f5ee0613d962f48f43 | 4,366 | js | JavaScript | InDevelopment/HTML_Content/javascripts/custom.js | alphagov/data-standards-demo-content- | d9e9be91968d3058c5bfe99cc6984cbcde7f4178 | [
"MIT"
] | 3 | 2019-06-20T10:34:22.000Z | 2020-03-13T07:35:42.000Z | InDevelopment/HTML_Content/javascripts/custom.js | alphagov/data-standards-demo-content- | d9e9be91968d3058c5bfe99cc6984cbcde7f4178 | [
"MIT"
] | null | null | null | InDevelopment/HTML_Content/javascripts/custom.js | alphagov/data-standards-demo-content- | d9e9be91968d3058c5bfe99cc6984cbcde7f4178 | [
"MIT"
] | 3 | 2019-07-02T14:17:24.000Z | 2021-04-10T19:32:59.000Z | /* global $ */
// Warn about using the kit in production
if (window.console && window.console.info) {
window.console.info('GOV.UK Prototype Kit - do not use for production')
}
$(document).ready(function () {
$('#CSV').hide()
$('#XLS').hide()
})
// GH content
// This populates the final display field - Generate button
function mydisplay () {
$('#creatout').html($('#crein').val())
$('#contout').html($('#conin').val())
$('#tiout').html($('#tiin').val())
$('#createdout').html($('#createdin').val())
$('#identout').html($('#ident').val())
$('#descout').html($('#desc').val())
var filedets1 = 'declare-header:' + $('#decheader').val()
var filedets2 = 'declare-data:' + $('#decdata').val()
var filedets3 = 'declare-data:' + $('#decsheet').val()
$('#filedets').html(filedets3 + '\n' + filedets1 + '\n' + filedets2)
$('#validout').html($('#valid').val())
$('#replout').html($('#replaces').val())
$('#liceout').html($('#license').val())
$('#ffpuout').html($('#ffpuid').val())
$('#ffcout').html($('#fca').val())
$('#confout').html($('#conformsTo').val())
$('#docsout').html($('#docsens').val())
$('#regout').html($('#regcol').val())
$('#regurlout').html($('#regurl').val())
}
// This copies the data
function getMytext () {
var texty = (
'creator:' + $('#crein').val() + '\n' +
'contributor:' + $('#conin').val() + '\n' +
'title:' + $('#tiin').val() + '\n' +
'created:' + $('#createdin').val() + '\n' +
'identifier:' + $('#ident').val() + '\n' +
'description:' + $('#desc').val() + '\n' +
'declare-datasheet:' + $('#decsheet').val() + '\n' +
'declare-header:' + $('#decheader').val() + '\n' +
'declare-data:' + $('#decdata').val() + '\n' +
'valid:' + $('#valid').val() + '\n' +
'replaces:' + $('#replaces').val() + '\n' +
'license:' + $('#license').val() + '\n' +
'fileformat-puid:' + $('#ffpuid').val() + '\n' +
'fileformat-creating-application:' + $('#fca').val() + '\n' +
'conformsTo:' + $('#conformsTo').val() + '\n' +
'doc-sensitivity:' + $('#docsens').val() + '\n' +
'register-column:' + $('#regcol').val() + '\n' +
'register-url:' + $('#regurl').val()
)
return texty
}
function CopyDDF() {
// eslint-disable-next-line no-undef
texty = getMytext ()
var tocopy = $('<textarea>').val(texty).appendTo('body').select()
tocopy.select()
document.execCommand('copy')
alert('Copied to clipboard' + texty)
}
function saveToFile() {
// eslint-disable-next-line no-undef
texty = getMytext ()
alert('Copied to clipboard' + texty)
}
// This downloads the data
// Added for the datatable
$(document).ready(function () {
$('.add-row').click(function () {
var col = $('#col').val()
var dtip = $('#dtip :selected').text()
var desc = $('#desc').val()
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + col + '</td><td>' + dtip + '</td><td>' + desc + '</td></tr>'
$('table tbody').append(markup)
})
// Find and remove selected table rows
$('.delete-row').click(function () {
$('table tbody').find('input[name="record"]').each(function () {
if ($(this).is(':checked')) {
$(this).parents('tr').remove()
}
})
})
})
// Show hide selection
//$('#filetip').on('change', function () {
// alert('here');
//})
$(document).ready(function(){
$("#filetip").change(function(){
switch (this.value) {
case '0':
$('#CSV').show()
$('#XLS').hide()
break
case '1':
$('#CSV').hide()
$('#XLS').show()
break
case '99':
$('#CSV').hide()
$('#XLS').hide()
break
};
});
});
// File import text
function getFilePath () {
$('input[type=file]').change(function () {
var filePath = $('#fileUpload').val()
})
}
//collapsible element
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
} | 25.383721 | 136 | 0.53596 |
13353ec8d9bf6b58b0b4cf298dbe0143ee47c894 | 2,214 | js | JavaScript | test/MemoryStoreTest.js | joshes/cache-aside | 850ff9392d1230325feb6b9fd81c6682e9f21ec8 | [
"MIT"
] | null | null | null | test/MemoryStoreTest.js | joshes/cache-aside | 850ff9392d1230325feb6b9fd81c6682e9f21ec8 | [
"MIT"
] | null | null | null | test/MemoryStoreTest.js | joshes/cache-aside | 850ff9392d1230325feb6b9fd81c6682e9f21ec8 | [
"MIT"
] | null | null | null | const assert = require('assert');
const chai = require('chai');
const should = chai.should();
const expect = chai.expect;
const spies = require('chai-spies');
chai.use(spies);
const Store = require('../index').MemoryStore;
describe('MemoryStore', () => {
describe('#get()', () => {
it('first execution should execute the provider', (done) => {
const provider = (key, cb) => {
cb(null, 'Some Data');
};
const inst = new Store(provider);
const spy = chai.spy.on(inst, '_provider');
inst.get('MyKey', (err, data) => {
assert(!err);
expect(spy).to.have.been.called.once;
done();
});
});
it('second execution should not execute the provider', (done) => {
const provider = (key, cb) => {
cb(null, 'Some Data');
};
const inst = new Store(provider);
const spy = chai.spy.on(inst, '_provider');
inst.get('MyKey', (err, data) => {
assert(!err);
inst.get('MyKey', (err, data) => {
assert(!err);
expect(spy).to.have.been.called.once;
done();
});
});
});
it('cached item should be evicted after TTL expires', (done) => {
const provider = (key, cb) => {
cb(null, 'Some Data');
};
const inst = new Store(provider, 10);
const spy = chai.spy.on(inst, '_provider');
inst.get('MyKey', (err, data) => {
assert(!err);
assert(data);
inst.get('MyKey', (err, data) => {
assert(!err);
expect(spy).to.have.been.called.once;
setTimeout(() => {
inst.get('MyKey', (err, data) => {
assert(!err);
expect(spy).to.have.been.called.twice;
done();
});
}, 20);
});
});
});
});
});
| 28.384615 | 74 | 0.409666 |
1335810288428362a3da4f5f16d4b3d6da8df41f | 22,214 | js | JavaScript | src/js/FilterModule.js | antonbobrov/vevet | 9b4300b833848a6858702d5b69ff2ef509eb3e24 | [
"MIT"
] | 4 | 2020-06-18T08:30:00.000Z | 2021-12-10T11:53:32.000Z | src/js/FilterModule.js | antonbobrov/vevet | 9b4300b833848a6858702d5b69ff2ef509eb3e24 | [
"MIT"
] | null | null | null | src/js/FilterModule.js | antonbobrov/vevet | 9b4300b833848a6858702d5b69ff2ef509eb3e24 | [
"MIT"
] | null | null | null | import Module from './Module';
import merge from './merge';
import generateId from './generateId';
const selectEl = require('select-el');
/**
* @classdesc This class is to create filters. It works together with {@linkcode Vevet.PaginationModule} <br>
* Available targets:
* <ul>
* <li>popstate - argument {@linkcode Vevet.FilterModule.PopstateCallback }</li>
* <li>save</li>
* </ul>
* <br><br> <b>import {FilterModule} from 'vevet';</b>
*
* @vevetModuleCallback { Vevet.FilterModule : popstate : Vevet.FilterModule.PopstateCallback }
* @vevetModuleCallback { Vevet.FilterModule : save : }
*
* @class
* @memberof Vevet
* @augments Vevet.Module
*/
export default class FilterModule extends Module {
/**
* @memberof Vevet.FilterModule
* @typedef {object} Properties
* @augments Vevet.Module.Properties
*
* @property {object} [selectors] - ***
* @property {string|HTMLElement|NodeList|Array<HTMLElement>} [selectors.group=.vevet-filter__group] - Group of filters.
* Each group must/may have the following data attributes:
* <ul>
* <li>data-vevet-filter-group - the name (id) of the group</li>
* <li>data-vevet-filter-multiple - an optional attribute which defines that several filters
* may be active within one group. By default, none of the groups are multiple.</li>
* </ul>
* @property {string|HTMLElement|NodeList|Array<HTMLElement>} [selectors.filter=.vevet-filter__filter] - Filter elements.
* Each element must have the following data attributes:
* <ul>
* <li>data-vevet-filter-group - to what group the filter belongs</li>
* <li>data-vevet-filter-id - the filter's ID</li>
* </ul>
*
* @property {boolean} [saveOnChange=true] - Defines if you need to save values when filters are changed.
*
* @property {string} [multipleSeparator=_]
* @property {number} [timeout=0] - Timeout before loading.
*
* @property {object} [popstate]
* @property {boolean} [popstate.event=true] - Catch popstate event.
* @property {boolean} [popstate.reload=false] - Reload on popstate.
* @property {number} [popstate.timeout=300]
*
* @property {Vevet.PaginationModule} pagination - Pagination Module.
*
*/
/**
* @alias Vevet.FilterModule
*
* @param {Vevet.FilterModule.Properties} data
*/
constructor(data) {
super(data);
}
get prefix() {
return `${this._v.prefix}filter`;
}
/**
* @readonly
* @type {Vevet.FilterModule.Properties}
*/
get defaultProp() {
let prefix = this._prefix;
return merge(super.defaultProp, {
selectors: {
group: `.${prefix}__group`,
filter: `.${prefix}__filter`
},
saveOnChange: true,
multipleSeparator: '_',
timeout: 0,
popstate: {
event: true,
reload: false,
timeout: 300
},
pagination: {}
});
}
/**
* @member Vevet.FilterModule#prop
* @memberof Vevet.FilterModule
* @readonly
* @type {Vevet.FilterModule.Properties}
*/
/**
* @member Vevet.FilterModule#_prop
* @memberof Vevet.FilterModule
* @protected
* @type {Vevet.FilterModule.Properties}
*/
/**
* @memberof Vevet.FilterModule
* @typedef {object} ChangeProperties
* @augments Vevet.FilterModule.Properties
*
* @property {Vevet.PaginationModule} [pagination]
*
*/
/**
* @function Vevet.FilterModule#changeProp
* @memberof Vevet.FilterModule
* @param {Vevet.FilterModule.ChangeProperties} [prop]
*/
// Extra constructor
_extra() {
super._extra();
let prefix = this._prefix;
/**
* @description Available data attributes.
* @member {object}
* @protected
*/
this._data = {
group: `data-${prefix}-group`,
multiple: `data-${prefix}-multiple`,
id: `data-${prefix}-id`
};
/**
* @description Filter groups.
* @member {Array<Vevet.FilterModule.Group>}
* @protected
*/
this._groups = [];
/**
* @description Filters.
* @type {Array<Vevet.FilterModule.Filter>}
* @protected
*/
this._filters = [];
/**
* @description Events that were set on filters
* @protected
* @member {Vevet.BindListener}
*/
this._filtersEvents = [];
/**
* @description Current json - current filters
* @member {string}
* @protected
*/
this._json = '{}';
/**
* @member {false|number}
* @protected
*/
this._popstateTimeout = false;
// get elements
this._elementsGet();
this.setFilters(true);
this._json = this._getFiltersQuery();
}
/**
* @description Get filters.
* @type {Array<Vevet.FilterModule.Filter>}
* @readonly
*/
get filters() {
return this._filters;
}
/**
* @description Get filter groups.
* @type {Array<Vevet.FilterModule.Group>}
* @readonly
*/
get groups() {
return this._groups;
}
/**
* @description Get elements and form arrays of groups and filters.
* @protected
*/
_elementsGet() {
// get groups
this._getGroups();
// get filters
this._getFilters();
}
/**
* @description Get groups.
* @protected
*/
_getGroups() {
// clear groups
this._groups = [];
// get dom groups
let items = selectEl.all(this._prop.selectors.group);
items.forEach(el => {
// get the group's id
let group = this._getGroupId(el);
if (group) {
// check if it is multiple
let multiple = this._getGroupMultiple(el);
// create an object and push it to the stack
this._groups.push({
el: el,
id: group,
multiple: multiple
});
}
});
}
/**
* @description Get filters.
* @protected
*/
_getFilters() {
// clear filters
this._clearFilters();
// get dom groups
let items = selectEl.all(this._prop.selectors.filter),
i = 0;
items.forEach(el => {
// get the filter's properties
let group = this._getGroupByElement(el),
id = this._getFilterID(el);
if (group !== false & id !== false) {
// create an object and push it to the stack
let obj = {
el: el,
group: group,
active: el.classList.contains(`${this._prefix}__filter_active`),
disabled: false,
unique_id: generateId(i),
id: id
};
this._filters.push(obj);
// set events
let event = this.listener(el, "click", this.filterClick.bind(this, el));
this._filtersEvents.push(event);
}
i++;
});
}
/**
* @description Remove events from filters.
* @protected
*/
_clearFilters() {
this._filtersEvents.forEach(event => {
this.removeEventListener(event);
});
this._filters = [];
this._filtersEvents = [];
}
/**
* @memberof Vevet.FilterModule
* @typedef {object} Group
*
* @property {HTMLElement} el
* @property {string} id
* @property {boolean} multiple
*
*/
/**
* @memberof Vevet.FilterModule
* @typedef {object} Filter
*
* @property {HTMLElement} el
* @property {Vevet.FilterModule.Group} group
* @property {boolean} active
* @property {boolean} disabled
* @property {string} id
* @property {string} unique_id
*
*/
/**
* @description Get group id.
* @param {HTMLElement} el
* @returns {string|false} Returns the group's id or false.
* @protected
*/
_getGroupId(el) {
let attr = el.getAttribute(this._data.group);
if (attr) {
return attr;
}
return false;
}
/**
* @description Check if the group is multiple.
* @param {HTMLElement} el
* @returns {boolean} Returns true or false.
* @protected
*/
_getGroupMultiple(el) {
let attr = el.getAttribute(this._data.multiple);
if (attr) {
return true;
}
return false;
}
/**
* @description Get group of an element.
* @param {HTMLElement} el
* @returns {Vevet.FilterModule.Group|false} Returns the group or false.
* @protected
*/
_getGroupByElement(el) {
let attr = el.getAttribute(this._data.group);
if (attr) {
let group = false;
this._groups.forEach(obj => {
if (obj.id == attr) {
group = obj;
}
});
return group;
}
return false;
}
/**
* @description Get filter by element.
* @param {HTMLElement} el
* @returns {Vevet.FilterModule.Filter|false} Returns the group or false.
* @protected
*/
_getFilterByElement(el) {
let filter = false;
this._filters.forEach(obj => {
if (obj.el == el) {
filter = obj;
}
});
return filter;
}
/**
* @description Get filter by the id of the group.
* @param {string} id
* @returns {Array<Vevet.FilterModule.Filter>} Returns filters.
* @protected
*/
_getFiltersByGroupID(id) {
let filters = [];
this._filters.forEach(obj => {
if (obj.group.id == id) {
filters.push(obj);
}
});
return filters;
}
/**
* @description Get filters' id.
* @param {HTMLElement} el
* @returns {string|false} Returns the value or false.
* @protected
*/
_getFilterID(el) {
let attr = el.getAttribute(this._data.id);
if (attr) {
return attr;
}
return false;
}
/**
* @description Save values and push them to the URL.
* @returns {boolean} Returns true if there are any changes.
*/
save() {
let query = this._getFiltersQuery();
if (query !== this._json) {
let canUpdate = this._update(query);
if (canUpdate) {
this._json = query;
this.lbt("save");
}
else {
return false;
}
}
return true;
}
/**
* @description Click on filter. It can be also imitated.
* @param {HTMLElement} el
* @param {object} [e]
* @returns {boolean} Returns true or false.
*/
filterClick(el, e = false) {
// prevent default action
if (e) {
e.preventDefault();
}
// get filter
let filter = this._getFilterByElement(el);
if (!filter) {
return false;
}
// check if event possible
if (!this._checkFilterClick(filter)) {
return false;
}
// change values of the filters
this._changeFiltersProp(filter);
// change classes of the filters
this._changeFiltersClasses(filter);
// update values if saving is enabled
if (this._prop.saveOnChange) {
return this.save();
}
// return success
return true;
}
/**
* @description Check if the change of the filter is available.
* @param {Vevet.FilterModule.Filter} filter
* @protected
* @returns {boolean} Ture or false.
*/
_checkFilterClick(filter) {
let prop = this._prop;
// check if pagination is loading
if (prop.pagination.loading) {
return false;
}
// if the filter is disabled
if (filter.disabled) {
return false;
}
return true;
}
/**
* @description Change properties of the filters within one group - active values.
* @param {Vevet.FilterModule.Filter} filter - Current filter.
* @protected
*/
_changeFiltersProp(filter) {
// get current group
let group = filter.group;
// get all filters
let allFilters = this._getFiltersByGroupID(group.id);
// change active/non-active of the current filter and other filters
// within one group
for (let i = 0; i < allFilters.length; i++) {
let obj = allFilters[i];
// make the current filter active/non-active if the group is multiple
if (group.multiple) {
if (obj.unique_id == filter.unique_id) {
obj.active = !filter.active;
}
}
// make the current filter active and others non-active
// if the group is not multiple
else {
if (obj.unique_id == filter.unique_id) {
obj.active = true;
}
else {
obj.active = false;
}
}
}
}
/**
* @description Set classes to the filters: active & disabled.
* @protected
*/
_changeFiltersClasses() {
let prefix = this._prefix;
this._filters.forEach(filter => {
// active class
let activeClass = `${prefix}__filter_active`;
if (filter.active) {
filter.el.classList.add(activeClass);
}
else {
filter.el.classList.remove(activeClass);
}
// disabled class & attribute (for selectors, buttons, etc)
let disabledClass = `${prefix}__filter_disabled`;
if (filter.disabled) {
filter.el.classList.add(disabledClass);
filter.el.disabled = true;
}
else {
filter.el.classList.remove(disabledClass);
filter.el.disabled = false;
}
});
}
/**
* @description Set filter properties and classes according to the url. This happens
* while initializing the class.
* @param {boolean} considerClasses - Set true if you need to take into consideration active classes
* of the filters. It is used on initialization.
*/
setFilters(considerClasses = false) {
const classActive = `${this._prefix}__filter_active`;
// go thru all groups and search groups that exist in the URL
this._groups.forEach(group => {
let param = this._v.url.getParam({
key: group.id
});
if(param) {
let paramValues = param.split(this._prop.multipleSeparator);
// get filters in the group
let filters = this._getFiltersByGroupID(group.id);
filters.forEach(filter => {
if (paramValues.includes(filter.id)) {
filter.active = true;
}
else {
filter.active = false;
if (considerClasses) {
if (filter.el.classList.contains(classActive)) {
filter.active = true;
}
}
}
});
}
else {
// get filters in the group
let filters = this._getFiltersByGroupID(group.id);
filters.forEach(filter => {
filter.active = false;
if (considerClasses) {
if (filter.el.classList.contains(classActive)) {
filter.active = true;
}
}
});
}
});
// set classes
this._changeFiltersClasses();
}
/**
* @description Get a url query according to the active filters.
* @protected
* @returns {string} Returns a JSON string.
*/
_getFiltersQuery() {
let groupsFilters = {};
this._filters.forEach(filter => {
// check if the filter is active
// and only then add it to its group
if (filter.active) {
// create group if doesn't exist
let groupID = filter.group.id;
if (typeof groupsFilters[groupID] == "undefined") {
groupsFilters[groupID] = [];
}
// add filter to the group
groupsFilters[groupID].push(filter.id);
}
});
// make a json of it
let json = JSON.stringify(groupsFilters);
return json;
}
/**
* @description Get active url params.
* @param {string} json
* @returns {Array<Array<string>>} Returns values.
* @protected
*/
_getURLParams(json) {
let prop = this._prop;
// create an array: key => value
let obj = JSON.parse(json),
params = [];
for (let key in obj) {
let values = obj[key].join(prop.multipleSeparator);
params.push([key, values]);
}
return params;
}
/**
* @description Update the URL & content according to active filters.
* @param {string} json
* @returns {boolean} Returns true the filters have changed.
* @protected
*/
_update(json) {
let prop = this._prop;
// check if the url changed
if (this._json == json) {
return false;
}
// create an arryy: key => value
let params = this._getURLParams(json),
paramsPrev = this._getURLParams(this._json);
// get pagination
let pagination = prop.pagination;
// reset pagination
let url = this._v.url.setParam({
key: pagination.prop.param,
value: '',
push: false
});
// reset previous params
for (let i = 0; i < paramsPrev.length; i++) {
let push = false;
if (i == paramsPrev.length - 1) {
push = params.length === 0 ? true : false;
}
url = this._v.url.setParam({
url: url,
key: paramsPrev[i][0],
value: '',
push: push
});
}
// push it to the url
for (let i = 0; i < params.length; i++) {
let push = false;
if (i == params.length - 1) {
push = true;
}
url = this._v.url.setParam({
url: url,
key: params[i][0],
value: params[i][1] == 'null' ? '' : params[i][1],
push: push
});
}
// update content
pagination.url = url;
pagination.reload(false);
// success
return true;
}
// Set events
_setEvents() {
// popstate event
this.listener(window, "popstate", this._popstate.bind(this));
}
/**
* @description Popstate events.
* @protected
*/
_popstate() {
let popstate = this._prop.popstate;
if (!popstate.event) {
if (popstate.reload) {
window.location.reload();
}
return false;
}
this._popstateLoad();
}
/**
* @description Catch popstate and load new data.
* @protected
*/
_popstateLoad() {
let prop = this._prop,
timeout = prop.popstate.timeout,
pagination = prop.pagination;
// clear timeout
if (this._popstateTimeout) {
clearTimeout(this._popstateTimeout);
this._popstateTimeout = false;
}
// check if available and then load
if (!pagination.loading) {
this._popstateTimeout = setTimeout(this._popstateForceLoad.bind(this), timeout);
}
// timeouts and callbacks if not available
else {
this._popstateTimeout = setTimeout(this._popstateBusyLoad.bind(this), timeout);
}
}
/**
* @description Popstate event when pagination is loading.
* @protected
*/
_popstateBusyLoad() {
this._prop.pagination.on("load", () => {
this._popstateLoad();
}, {
once: true
});
}
/**
* @memberof Vevet.FilterModule
* @typedef {object} PopstateCallback
*
* @property {string} href
*
*/
/**
* @description Popstate force load.
* @protected
*/
_popstateForceLoad() {
this.lbt('popstate', {
href: window.location.href
});
// set filters
this.setFilters();
// get pagination
let pagination = this._prop.pagination;
// update pagination url
pagination.url = window.location.href;
// update pagination active
let active = this._v.url.getParam({
key: pagination.prop.param
});
if (active != null) {
active = parseInt(active);
}
else {
active = 1;
}
pagination._active = active;
// reload pagination
pagination.reload(false, false);
}
} | 24.384193 | 125 | 0.502431 |
1336e2df404c103350ef699b155f2fab5c6ea6cd | 3,603 | js | JavaScript | test/data-util/inventory/finishing-printing/fp-retur-fr-byr-doc-data-util.js | kuswandanu-moonlay/dl-module | a46a59049f6429b326820918c25fd0f1d1147149 | [
"MIT"
] | null | null | null | test/data-util/inventory/finishing-printing/fp-retur-fr-byr-doc-data-util.js | kuswandanu-moonlay/dl-module | a46a59049f6429b326820918c25fd0f1d1147149 | [
"MIT"
] | 1,020 | 2016-10-05T08:02:34.000Z | 2019-04-01T02:10:55.000Z | test/data-util/inventory/finishing-printing/fp-retur-fr-byr-doc-data-util.js | kuswandanu-moonlay/dl-module | a46a59049f6429b326820918c25fd0f1d1147149 | [
"MIT"
] | 250 | 2016-08-08T03:50:33.000Z | 2019-02-14T02:01:13.000Z | 'use strict'
var helper = require("../../../helper");
var FPReturManager = require("../../../../src/managers/inventory/finishing-printing/fp-retur-fr-byr-doc-manager");
var ShipmentDataUtil = require('./fp-shipment-document-data-util');
var storageDataUtil = require('../../master/storage-data-util');
var codeGenerator = require('../../../../src/utils/code-generator');
// DB Models
var Models = require("dl-models");
var Map = Models.map;
var FPReturFromBuyerModels = Models.inventory.finishingPrinting.FPReturFromBuyerDoc;
var moment = require("moment");
class FPReturFrByrDocDataUtil {
getNewData() {
return Promise.all([ShipmentDataUtil.getNewTestData(), storageDataUtil.getRandomTestData()])
.then(results => {
var _shipmetData = results[0];
var _storage = results[1];
var code = codeGenerator();
var data = {
code : code,
destination : 'Pack I',
buyerId : _shipmetData.buyerId,
buyer : {
_id : _shipmetData.buyerId,
code : _shipmetData.buyerCode,
name : _shipmetData.buyerName,
address : _shipmetData.buyerAddress,
type : _shipmetData.buyerType
},
date :moment(new Date()).format('YYYY-MM-DD'),
spk : `spk ${code}`,
coverLetter : `sp ${code}`,
codeProduct : `code ${code}`,
storageId : _storage._id,
storageName : _storage.name,
details : [{
productionOrderId : _shipmetData.details[0].productionOrderId,
productionOrderNo : _shipmetData.details[0].productionOrderNo,
items : [{
productId:_shipmetData.details[0].items[0].packingReceiptItems[0].productId,
productCode:_shipmetData.details[0].items[0].packingReceiptItems[0].productCode,
productName:_shipmetData.details[0].items[0].packingReceiptItems[0].productName,
productDescription:'',
hasNewProduct : false,
designNumber:_shipmetData.details[0].items[0].packingReceiptItems[0].designNumber,
designCode:_shipmetData.details[0].items[0].packingReceiptItems[0].designCode,
remark:`Ket ${code}`,
colorWay:_shipmetData.details[0].items[0].packingReceiptItems[0].colorType,
returQuantity:2,
uomId:_shipmetData.details[0].items[0].packingReceiptItems[0].uomId,
uom:_shipmetData.details[0].items[0].packingReceiptItems[0].uomUnit,
length:2,
weight:2
}]
}]
};
return Promise.resolve(data);
});
}
getNewTestData() {
return helper
.getManager(FPReturManager)
.then((manager) => {
return this.getNewData().then((data) => {
return manager.create(data)
.then((id) => {
return manager.getSingleById(id)
});
});
});
}
}
module.exports = new FPReturFrByrDocDataUtil(); | 46.192308 | 114 | 0.504302 |
133720a81636d79dee43e00d6cee53a760ce0000 | 5,882 | js | JavaScript | build/static/js/9.fb87881f.chunk.js | joelerego/hubble | a7cbb657042848bda2fd4559f2788c54641f5d36 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2020-12-28T13:16:26.000Z | 2020-12-30T04:38:52.000Z | build/static/js/9.fb87881f.chunk.js | joelerego/hubble | a7cbb657042848bda2fd4559f2788c54641f5d36 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | build/static/js/9.fb87881f.chunk.js | joelerego/hubble | a7cbb657042848bda2fd4559f2788c54641f5d36 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | (this.webpackJsonphubble=this.webpackJsonphubble||[]).push([[9],{161:function(e,t,a){"use strict";function n(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}a.d(t,"a",(function(){return n}))},173:function(e,t,a){"use strict";var n=a(1),r=a(2),i=a(0),o=(a(3),a(4)),l=a(104),s=a(5),c=i.forwardRef((function(e,t){var a=e.classes,s=e.className,c=e.raised,m=void 0!==c&&c,u=Object(r.a)(e,["classes","className","raised"]);return i.createElement(l.a,Object(n.a)({className:Object(o.a)(a.root,s),elevation:m?8:1,ref:t},u))}));t.a=Object(s.a)({root:{overflow:"hidden"}},{name:"MuiCard"})(c)},174:function(e,t,a){"use strict";var n=a(1),r=a(2),i=a(0),o=(a(3),a(4)),l=a(5),s=i.forwardRef((function(e,t){var a=e.classes,l=e.className,s=e.component,c=void 0===s?"div":s,m=Object(r.a)(e,["classes","className","component"]);return i.createElement(c,Object(n.a)({className:Object(o.a)(a.root,l),ref:t},m))}));t.a=Object(l.a)({root:{padding:16,"&:last-child":{paddingBottom:24}}},{name:"MuiCardContent"})(s)},236:function(e,t,a){"use strict";a.r(t);var n=a(0),r=a.n(n),i=a(161),o=a(54),l=a(150),s=a(173),c=a(174),m=a(145),u=a(138),d=Object(u.a)((function(e){return{header:Object(i.a)({height:540,background:"linear-gradient(45deg, #2196F3 30%, #3F51B5 90%)",color:e.palette.primary.contrastText,display:"flex"},e.breakpoints.down("md"),{height:640}),headerContent:Object(i.a)({padding:24,width:"100%",marginLeft:"auto",marginRight:"auto",textAlign:"center",marginTop:128,marginBottom:128},e.breakpoints.down("sm"),{marginTop:40}),body:{color:"#5F6368",marginTop:-192,maxWidth:1366,margin:"auto"},cards:{width:"100%",marginLeft:"auto",marginRight:"auto"},badge:{backgroundColor:e.palette.error.main,color:e.palette.getContrastText(e.palette.error.main)},price:{backgroundColor:e.palette.primary[900],color:e.palette.contrastText},title:{textAlign:"center",fontSize:40},subtitle:{textAlign:"center",fontSize:20,marginTop:16},planContainer:{padding:8,margin:0},plan:{maxWidth:320},planCard:Object(i.a)({padding:16,marginLeft:8,marginRight:8},e.breakpoints.down("md"),{marginTop:32}),planHeading:{display:"block",height:"15%",color:"#5F6368",textAlign:"center",marginTop:16},planTitle:{color:"#5F6368",fontSize:24},planSubtitle:{color:"#5F6368",fontSize:16,marginLeft:8,marginRight:8,display:"block",marginTop:8},includes:{display:"block",color:"#5F6368",marginTop:16,fontSize:14},features:Object(i.a)({color:"#5F6368",textAlign:"center",height:450},e.breakpoints.down("md"),{height:430}),feature:{color:"#5F6368",fontSize:14,marginTop:16},check:{fontSize:16,color:"green"},planAction:{width:"80%",marginTop:20,marginBottom:20,marginLeft:"auto",marginRight:"auto",display:"block"}}})),p=[{title:"Free",target:"_self",href:"https://hubblesuite.com/register",subtitle:"For businesses that need simple online payments.",price:"Get Started",features:["Account, Subscription, and Plan Management","Mobile App","Email Reminders","1 API Key and Webhooks","Single Currency","1 Team","5 Collaborators","Hosted Payement Page","Upto 50 Active Subscriptions","Templates"]},{title:"Starter",target:"_blank",href:"mailto:contact@hubblesuite.com",subtitle:"For small businesses that need an economic solution.",price:"Contact sales",includes:"Includes everything in Free",features:["SMS and Whatsapp Reminders","Basic Reports","2 API Keys","Online Support","Mutiple Currencies","5 Teams","25 Collaborators","500 Active Subscriptions","Coupons","Gift Cards"]},{title:"Professional",target:"_blank",href:"mailto:contact@hubblesuite.com",subtitle:"For businesses that are growth oriented.",price:"Contact sales",includes:"Includes everything in Starter",features:["Advanced Analytics","Advanced Reports","Automated Call Reminders","10 API Keys","10 Teams","50 Collaborators","5000 Active Subscriptions","Fraud Management","Dunning Management","Audit Logs"]},{title:"Enterprise",target:"_blank",href:"mailto:contact@hubblesuite.com",subtitle:"For businesses that need flexibility and scalability.",price:"Contact sales",includes:"Includes everything in Professional",features:["Unlimited API Keys and Webhooks","Unlimited Teams","Unlimited Active Subscriptions","Professional Services","IP Whitelisting","Detected Account Manager"]}];var b=function(e){var t=d();return r.a.createElement("div",null,r.a.createElement("div",{className:t.header},r.a.createElement("div",{className:t.headerContent},r.a.createElement(o.a,{variant:"h2",color:"inherit",className:t.title},"Plans for businesses of all sizes"),r.a.createElement(o.a,{variant:"subtitle1",color:"inherit",className:t.subtitle},"The most advanced subscription management platform at simple and affordable pricing.",r.a.createElement("br",null)))),r.a.createElement("div",{className:t.body},r.a.createElement("div",{className:t.cards},r.a.createElement(l.a,{container:!0,justify:"center",className:t.planContainer},p.map((function(e){return r.a.createElement(l.a,{item:!0,lg:3,xs:12},r.a.createElement(s.a,{raised:!0,className:t.planCard},r.a.createElement("div",{className:t.planHeading},r.a.createElement(o.a,{className:t.planTitle},e.title),r.a.createElement(o.a,{color:"textSecondary",className:t.planSubtitle},e.subtitle)),r.a.createElement(c.a,{className:t.features},r.a.createElement(o.a,{color:"textSecondary",className:t.includes},e.includes),e.features.map((function(e,a){return r.a.createElement(o.a,{color:"textPrimary",className:t.feature},e)}))),r.a.createElement("a",{href:e.href,target:e.target,style:{textDecoration:"none"},rel:"noopener noreferrer"},r.a.createElement(m.a,{variant:"contained",color:"secondary",className:t.planAction},e.price))))}))))))};t.default=function(e){return Object(n.useEffect)((function(){document.title="Plans and Pricing | Hubble Subscriptions"}),[]),r.a.createElement("div",null,r.a.createElement(b,null))}}}]);
//# sourceMappingURL=9.fb87881f.chunk.js.map | 2,941 | 5,837 | 0.743115 |
1337b9dceb67866df78623d9edd0a90034552204 | 552 | js | JavaScript | public/modules/core/config/core.client.routes.js | bstjohn/whosthat | 398812778cc9850a8e23bf49fc32256c94fc5b38 | [
"MIT"
] | null | null | null | public/modules/core/config/core.client.routes.js | bstjohn/whosthat | 398812778cc9850a8e23bf49fc32256c94fc5b38 | [
"MIT"
] | null | null | null | public/modules/core/config/core.client.routes.js | bstjohn/whosthat | 398812778cc9850a8e23bf49fc32256c94fc5b38 | [
"MIT"
] | null | null | null | /**
Copyright (c) 2015 Brady St. John
This program is released under The MIT License (MIT).
Please see the file COPYING in this distribution for
license terms.
*/
'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'
});
}
]);
| 24 | 70 | 0.695652 |
13389e0a6bc75403672fe721b7fd90c3bcb5d56d | 12,224 | js | JavaScript | src/script.js | domidodo/WebExerciseSystem | 1230b56025b910dd7eacd87941df49112f7b767a | [
"MIT"
] | null | null | null | src/script.js | domidodo/WebExerciseSystem | 1230b56025b910dd7eacd87941df49112f7b767a | [
"MIT"
] | null | null | null | src/script.js | domidodo/WebExerciseSystem | 1230b56025b910dd7eacd87941df49112f7b767a | [
"MIT"
] | null | null | null | function getCookieValue(key) {
const b = document.cookie.match('(^|;)\\s*' + key + '\\s*=\\s*([^;]+)');
return b ? b.pop() : "{}";
}
function setCookieValue(key, value) {
let now = new Date();
let period = new Date(now.getTime()+1*86400000);
document.cookie=key+"="+value+";expires="+period.toGMTString()+";";
}
function useHighlighting(txt){
return txt.replaceAll("[", "<i class=\"highlight\">").replaceAll("]", "</i>");
}
function createCourseDom(e){
var newNode = document.createElement('div');
newNode.classList.add('course');
newNode.classList.add('shadow');
newNode.innerHTML += "<p>Kurs: " + e.meta.id + "</p>";
newNode.innerHTML += "<h3>" + e.meta.name + "</h3>";
newNode.addEventListener("click", function(){ showTraining(e.index); });
return newNode;
}
function setHeadline(txt){
let headline = document.getElementById('headline');
headline.innerHTML = txt;
document.title = txt;
}
function showOverview(){
document.getElementById('overview').style.display = "block";
document.getElementById('training').style.display = "none";
let div = document.getElementById('overview');
setHeadline("Alle Kurse");
div.innerHTML = "";
window.data.forEach((e, index) => {
e.index = index;
div.appendChild(createCourseDom(e));
});
}
function showTraining(courseIndex){
document.getElementById('training').style.display = "block";
document.getElementById('overview').style.display = "none";
let div = document.getElementById('content');
let course = window.data[courseIndex];
setHeadline(course.meta.name);
div.innerHTML = "<h3>Hinweise zur Durchführung</h3><ul>";
course.meta.hints.forEach(e => {
div.innerHTML += "<li>"+e+"</li>";
});
div.innerHTML += "</ul><br/><br/><b>Viel Erfolg</b>";
let buttons = document.getElementById('buttons');
buttons.innerHTML = "";
var newButton = document.createElement('button');
newButton.innerHTML = "<i class=\"icon-home\"></i><br/>Kursauswahl";
newButton.addEventListener("click", function(){ showOverview(); });
buttons.appendChild(newButton);
newButton = document.createElement('button');
newButton.innerHTML = "<i class=\"icon-moodle\"></i><br/>Moodle";
newButton.addEventListener("click", function(){ window.open(course.meta.moodleUrl, '_blank'); });
buttons.appendChild(newButton);
newButton = document.createElement('button');
newButton.classList.add('right');
newButton.innerHTML = "<i class=\"icon-learning\"></i><br/>Probeklausur";
newButton.addEventListener("click", function(){ createExam(courseIndex); });
buttons.appendChild(newButton);
newButton = document.createElement('button');
newButton.classList.add('right');
newButton.innerHTML = "<i class=\"icon-list\"></i><br/>Aufgabenliste";
newButton.addEventListener("click", function(){ showExerciseList(courseIndex); });
buttons.appendChild(newButton);
}
function showExerciseList(courseIndex){
let div = document.getElementById('content');
let course = window.data[courseIndex];
let resultCookie = null;
try{
resultCookie = JSON.parse(getCookieValue(courseIndex+"_Results"));
}catch (e) {
resultCookie = null;
}
div.innerHTML = "";
course.exercises.forEach(e => {
let correctCount = 0;
let wrongCount = 0;
if(resultCookie != null){
let questionResults = resultCookie[e.id];
if(questionResults != undefined){
correctCount = questionResults.correctCount;
wrongCount = questionResults.wrongCount;
}
}
div.innerHTML += "<div class=\"correctCount\">"+correctCount+"</div><div class=\"wrongCount\">"+wrongCount+"</div>";
div.innerHTML += "<small>"+e.id + ":</small> <b>"+useHighlighting(e.question)+"</b><br/>";
e.answers.forEach(a => {
let checked = a.correct ? "checked" : "";
div.innerHTML += "<div class=\"inputBox\"><input type=\"checkbox\" " + checked +" disabled readonly/></div>";
div.innerHTML += "<label>"+useHighlighting(a.answer) + "</label>";
});
div.innerHTML += "<br/>";
});
let buttons = document.getElementById('buttons');
buttons.innerHTML = "";
var newButton = document.createElement('button');
newButton.innerHTML = "<i class=\"icon-home\"></i><br/>Kursauswahl";
newButton.addEventListener("click", function(){ showOverview(); });
buttons.appendChild(newButton);
newButton = document.createElement('button');
newButton.innerHTML = "<i class=\"icon-moodle\"></i><br/>Moodle";
newButton.addEventListener("click", function(){ window.open(course.meta.moodleUrl, '_blank'); });
buttons.appendChild(newButton);
newButton = document.createElement('button');
newButton.classList.add('right');
newButton.innerHTML = "<i class=\"icon-learning\"></i><br/>Probeklausur";
newButton.addEventListener("click", function(){ createExam(courseIndex); });
buttons.appendChild(newButton);
}
function createExam(courseIndex){
let course = window.data[courseIndex];
let listCopy = JSON.parse(JSON.stringify(course.exercises));
window.exam = {
meta : course.meta,
exercises : [],
courseIndex : courseIndex,
currentExerciseIndex : 0,
visitedExerciseIndex : 0
};
let i = 0;
for(i = 0; i < course.meta.questionsPerExam; i++){
if(listCopy.length <= 0){
break;
}
let randomExerciseIndex = Math.floor(Math.random() * listCopy.length);
let item = listCopy.splice(randomExerciseIndex, 1);
window.exam.exercises.push(item[0]);
}
showNextExercise();
}
function showNextExercise(){
let div = document.getElementById('content');
let index = window.exam.currentExerciseIndex;
let meta = window.exam.meta;
let exercise = window.exam.exercises[index];
let questionsPerExam = window.exam.exercises.length -1;
if(window.exam.visitedExerciseIndex < index){
window.exam.visitedExerciseIndex = index;
}
div.innerHTML = "";
div.innerHTML += "<small class=\"right\">(Id: "+exercise.id+")</small><br/>";
div.innerHTML += "<h3>"+useHighlighting(exercise.question)+"</h3>";
if(exercise.img != undefined && exercise.img != ""){
div.innerHTML += "<a href=\""+exercise.img+"\" target=\"_blank\"><img src=\""+exercise.img+"\" alt=\"Bild nicht gefunden\"></a>";
}
if(exercise.description != undefined && exercise.description != ""){
div.innerHTML += "<p>"+useHighlighting(exercise.description)+"</p>";
}
let useCheckboxes = meta.hideSingleChoice;
if(!useCheckboxes){
let correctAnswerCount = 0;
exercise.answers.forEach(e => {
if(e.correct){
correctAnswerCount++;
}
});
if(correctAnswerCount > 1){
useCheckboxes = true;
}
}
exercise.answers.forEach((e, i) => {
let choice = (e.choice != undefined && e.choice);
if(useCheckboxes){
let box = document.createElement('input');
box.type = "checkbox";
box.id = i;
if(choice){
box.setAttribute("checked", "checked");
}
box.setAttribute("onchange", "updateChoice(this)");
div.appendChild(box);
let label = document.createElement('label');
label.setAttribute("for", i);
label.innerHTML = " "+useHighlighting(e.answer);
div.appendChild(label);
div.innerHTML += "<br/>";
}else{
let box = document.createElement('input');
box.type = "radio";
box.name = "radio";
box.id = i;
if(choice){
box.setAttribute("checked", "checked");
}
box.setAttribute("onchange", "updateChoice(this)");
div.appendChild(box);
let label = document.createElement('label');
label.setAttribute("for", i);
label.innerHTML = " "+useHighlighting(e.answer);
div.appendChild(label);
div.innerHTML += "<br/>";
}
});
let buttons = document.getElementById('buttons');
buttons.innerHTML = "";
let progress = document.createElement('progress');
progress.max = questionsPerExam;
progress.value = window.exam.visitedExerciseIndex;
buttons.appendChild(progress);
let newButton = document.createElement('button');
newButton.disabled = index == 0;
newButton.innerHTML = "<i class=\"icon-left\"></i><br/>Zurück";
newButton.addEventListener("click", function(){ window.exam.currentExerciseIndex--; showNextExercise(); });
buttons.appendChild(newButton);
newButton = document.createElement('button');
newButton.disabled = index >= questionsPerExam;
newButton.innerHTML = "<i class=\"icon-right\"></i><br/>Weiter";
newButton.addEventListener("click", function(){ window.exam.currentExerciseIndex++; showNextExercise(); });
buttons.appendChild(newButton);
newButton = document.createElement('button');
newButton.classList.add('right');
newButton.innerHTML = "<i class=\"icon-done\"></i><br/>Abgeben";
newButton.addEventListener("click", function(){ showResult(); });
buttons.appendChild(newButton);
}
function updateChoice(e){
let index = window.exam.currentExerciseIndex;
let exercise = window.exam.exercises[index];
let answer = exercise.answers[parseInt(e.id)];
if(e.type == "radio"){
exercise.answers.forEach(e => {
e.choice = false;
});
}
answer.choice = e.checked;
}
function showResult(){
let div = document.getElementById('content');
let course = window.exam;
let points = 0;
let resultCookie = null;
try{
resultCookie = JSON.parse(getCookieValue(course.courseIndex+"_Results"));
}catch (e) {
resultCookie = {};
}
div.innerHTML = "";
course.exercises.forEach(e => {
let isCompletelyCorrect = true;
let isPartiallyCorrect = false;
if(resultCookie[e.id] == undefined){
resultCookie[e.id] = {
correctCount : 0,
wrongCount : 0
};
}
div.innerHTML += "<small>"+e.id + ":</small> <b>"+useHighlighting(e.question)+"</b><br/>";
e.answers.forEach(a => {
let choice = (a.choice != undefined && a.choice);
let checked = choice ? "checked" : "";
let correct = (a.correct == choice);
if(!correct){
isCompletelyCorrect = false;
}
if(correct){
isPartiallyCorrect = true;
}
div.innerHTML += correct ? "<i class=\"icon-yes check\"></i> " : "<i class=\"icon-no check\"></i> ";
div.innerHTML += "<input type=\"checkbox\" " + checked +" disabled readonly/>";
div.innerHTML += "<label>" + useHighlighting(a.answer) + "</label>";
});
let newPoints = 0;
if(!isCompletelyCorrect && !isPartiallyCorrect){
newPoints = course.meta.pointsForCompletelyWrongAnswer;
resultCookie[e.id].wrongCount = (resultCookie[e.id].wrongCount + 1);
}else if(isCompletelyCorrect){
newPoints = course.meta.pointsForCompletelyCorrectAnswer;
resultCookie[e.id].correctCount = (resultCookie[e.id].correctCount + 1);
}else if(isPartiallyCorrect){
newPoints = course.meta.pointsForPartiallyCorrectAnswer;
resultCookie[e.id].wrongCount = (resultCookie[e.id].wrongCount + 1);
}
points += newPoints;
div.innerHTML += "<b class=\"right\">"+newPoints+" Punkte</b>";
div.innerHTML += "<br/><br/>";
});
setCookieValue(course.courseIndex+"_Results", JSON.stringify(resultCookie));
if(points >= course.meta.pointsToPass){
div.innerHTML = "<center><h3 style=\"color: green;\">Bestanden</h3><small>"+ points +" Punkte</small></center><br/><br/><br/>" + div.innerHTML;
}else{
div.innerHTML = "<center><h3 style=\"color: red;\">Nicht Bestanden</h3><small>"+ points +" Punkte</small></center><br/><br/><br/>" + div.innerHTML;
}
let buttons = document.getElementById('buttons');
buttons.innerHTML = "";
var newButton = document.createElement('button');
newButton.innerHTML = "<i class=\"icon-home\"></i><br/>Kursauswahl";
newButton.addEventListener("click", function(){ showOverview(); });
buttons.appendChild(newButton);
newButton = document.createElement('button');
newButton.innerHTML = "<i class=\"icon-moodle\"></i><br/>Moodle";
newButton.addEventListener("click", function(){ window.open(course.meta.moodleUrl, '_blank'); });
buttons.appendChild(newButton);
newButton = document.createElement('button');
newButton.classList.add('right');
newButton.innerHTML = "<i class=\"icon-learning\"></i><br/>Probeklausur";
newButton.addEventListener("click", function(){ createExam(course.courseIndex); });
buttons.appendChild(newButton);
newButton = document.createElement('button');
newButton.classList.add('right');
newButton.innerHTML = "<i class=\"icon-list\"></i><br/>Aufgabenliste";
newButton.addEventListener("click", function(){ showExerciseList(course.courseIndex); });
buttons.appendChild(newButton);
}
window.onload = function() {
showOverview();
};
| 34.050139 | 149 | 0.683328 |
1338a7602963e8122d442e667859bb9bde3cd01d | 3,211 | js | JavaScript | api/src/index.js | ppecheux/skate-learning | 00cf34b80c67a6cca39ca82734ec7fe560e246f3 | [
"Apache-2.0"
] | null | null | null | api/src/index.js | ppecheux/skate-learning | 00cf34b80c67a6cca39ca82734ec7fe560e246f3 | [
"Apache-2.0"
] | 7 | 2021-05-11T22:13:34.000Z | 2022-01-22T13:56:43.000Z | api/src/index.js | ppecheux/skate-learning | 00cf34b80c67a6cca39ca82734ec7fe560e246f3 | [
"Apache-2.0"
] | null | null | null | import { typeDefs } from './graphql-schema'
import { ApolloServer } from 'apollo-server-express'
import express from 'express'
import neo4j from 'neo4j-driver'
import { makeAugmentedSchema } from 'neo4j-graphql-js'
import dotenv from 'dotenv'
import { initializeDatabase } from './initialize'
import { IsAuthenticatedDirective, HasRoleDirective, HasScopeDirective } from 'graphql-auth-directives'
import { resolvers } from './resolvers'
// set environment variables from .env
dotenv.config()
/*
* Create an executable GraphQL schema object from GraphQL type definitions
* including autogenerated queries and mutations.
* Optionally a config object can be included to specify which types to include
* in generated queries and/or mutations. Read more in the docs:
* https://grandstack.io/docs/neo4j-graphql-js-api.html#makeaugmentedschemaoptions-graphqlschema
*/
const schema = makeAugmentedSchema({
typeDefs: typeDefs,
resolvers: resolvers,
schemaDirectives: {
isAuthenticated: IsAuthenticatedDirective,
hasRole: HasRoleDirective,
hasScope: HasScopeDirective
},
config: {
query: {
exclude: ['RatingCount'],
},
mutation: {
exclude: ['RatingCount', 'SignInResponse'],
},
},
})
/*
* Create a Neo4j driver instance to connect to the database
* using credentials specified as environment variables
* with fallback to defaults
*/
const driver = neo4j.driver(
process.env.NEO4J_URI || 'bolt://localhost:7687',
neo4j.auth.basic(
process.env.NEO4J_USER || 'neo4j',
process.env.NEO4J_PASSWORD || 'neo4j'
),
{
encrypted: process.env.NEO4J_ENCRYPTED ? 'ENCRYPTION_ON' : 'ENCRYPTION_OFF',
}
)
/*
* Perform any database initialization steps such as
* creating constraints or ensuring indexes are online
*
*/
const init = async (driver) => {
await initializeDatabase(driver)
}
/*
* We catch any errors that occur during initialization
* to handle cases where we still want the API to start
* regardless, such as running with a read only user.
* In this case, ensure that any desired initialization steps
* have occurred
*/
init(driver)
/*
* Create a new ApolloServer instance, serving the GraphQL schema
* created using makeAugmentedSchema above and injecting the Neo4j driver
* instance into the context object so it is available in the
* generated resolvers to connect to the database.
*/
const server = new ApolloServer({
schema: schema,
context: ({ req }) => {
return {
driver,
req,
neo4jDatabase: process.env.NEO4J_DATABASE,
};
},
introspection: true,
playground: true,
})
// Specify host, port and path for GraphQL endpoint
const port = process.env.GRAPHQL_SERVER_PORT || 4001
const path = process.env.GRAPHQL_SERVER_PATH || '/graphql'
const host = process.env.GRAPHQL_SERVER_HOST || '0.0.0.0'
const app = express()
/*
* Optionally, apply Express middleware for authentication, etc
* This also also allows us to specify a path for the GraphQL endpoint
* https://blog.logrocket.com/jwt-authentication-with-apollo-server-2-tips-and-tricks/
*/
server.applyMiddleware({ app, path })
app.listen({ host, port, path }, () => {
console.log(`GraphQL server ready at http://${host}:${port}${path}`)
})
| 28.166667 | 103 | 0.729991 |
92b80f61098816cc14f320fce3d318d5f8a0af9e | 554 | js | JavaScript | src/stores/operators/math/Cos.js | aceslowman/camogen | e014eb7ea2994563da9cf0feac3a768aced7c16e | [
"MIT"
] | 2 | 2020-06-25T05:55:45.000Z | 2021-03-10T04:37:21.000Z | src/stores/operators/math/Cos.js | aceslowman/camogen | e014eb7ea2994563da9cf0feac3a768aced7c16e | [
"MIT"
] | 1 | 2020-12-29T17:53:27.000Z | 2020-12-29T17:53:27.000Z | src/stores/operators/math/Cos.js | aceslowman/camogen | e014eb7ea2994563da9cf0feac3a768aced7c16e | [
"MIT"
] | 1 | 2021-04-24T16:23:54.000Z | 2021-04-24T16:23:54.000Z | import { types } from "mobx-state-tree";
import Operator from "../OperatorStore";
const cos = types
.model("Cos", {
type: "Cos",
value: 0,
modifier: 0,
inputs: types.optional(types.array(types.string), ["input1"])
})
.actions(self => ({
update: () => {
if (!self.parents[0] || !self.parents[0].data) return 0;
let a = self.parents[0].data.update();
self.value = Math.cos(a);
return self.value;
}
}));
const Cos = types
.compose(
Operator,
cos
)
.named("Cos");
export default Cos;
| 19.103448 | 65 | 0.568592 |
92b997489f639844f87c9de7cba20106de592393 | 686 | js | JavaScript | snippets/standalone/standalone_use-url-polyfill/use-url-polyfill.js | Mr-Hei7enberg/google-apps-script-snippets | 35246fd2933612000ab257eb0e1ddebb42c4a8ef | [
"Unlicense"
] | 108 | 2019-10-06T14:39:34.000Z | 2022-03-21T22:35:46.000Z | snippets/standalone/standalone_use-url-polyfill/use-url-polyfill.js | Mr-Hei7enberg/google-apps-script-snippets | 35246fd2933612000ab257eb0e1ddebb42c4a8ef | [
"Unlicense"
] | 30 | 2017-02-18T20:02:55.000Z | 2019-09-26T17:31:33.000Z | snippets/standalone/standalone_use-url-polyfill/use-url-polyfill.js | Mr-Hei7enberg/google-apps-script-snippets | 35246fd2933612000ab257eb0e1ddebb42c4a8ef | [
"Unlicense"
] | 25 | 2019-10-06T14:39:35.000Z | 2022-01-25T23:09:50.000Z | /**
* @file The URL constructor
* @url https://developer.mozilla.org/en-US/docs/Web/API/URL
*/
/* globals URL */
/* exported userActionRun */
/**
* User action. Runs the snippet
*/
function userActionRun() {
// Base urls
var m = 'https://developer.mozilla.org';
var a = new URL('/', m); // => 'https://developer.mozilla.org/'
Logger.log(a.toString());
var b = new URL(m); // => 'https://developer.mozilla.org/'
Logger.log(b.toString());
var d = new URL('/en-US/docs', b); // => 'https://developer.mozilla.org/en-US/docs'
Logger.log(d.toString());
Logger.log(new URL('//foo.com', 'https://example.com').toString()); // => 'https://foo.com' (see relative URLs)
}
| 29.826087 | 113 | 0.61516 |
92ba6629ab820d62e77f3d6b81d4d10955f735a1 | 1,941 | js | JavaScript | src/components/Navbars/LoginLogoutLink.js | ackoDotDev/gitwrap_front | 9679f353b281728449fced4a16fccb9f042b5afb | [
"MIT"
] | null | null | null | src/components/Navbars/LoginLogoutLink.js | ackoDotDev/gitwrap_front | 9679f353b281728449fced4a16fccb9f042b5afb | [
"MIT"
] | null | null | null | src/components/Navbars/LoginLogoutLink.js | ackoDotDev/gitwrap_front | 9679f353b281728449fced4a16fccb9f042b5afb | [
"MIT"
] | null | null | null | import React, {useContext, useState, useEffect } from 'react';
import { UserContext } from 'contexts/UserContext';
import Cookies from 'js-cookie'
function LoginLogoutLink() {
const { user, setUser } = useContext(UserContext);
const [gitLoginUrl, setGitLoginUrl] = useState("");
useEffect(() => {
async function findUser() {
await fetch('/api/auth/github', { headers: new Headers({ accept: 'application/json' }) })
.then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Something went wrong!');
})
.then((data) => setGitLoginUrl(data.url))
.catch((error) => console.error(error));
}
findUser();
}, []);
const logOutUser = (e) => {
e.preventDefault();
fetch('/api/auth/logout', { headers: new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ' + Cookies.get('user_token')
}) })
.then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Something went wrong!');
})
.then((data) => {
Cookies.remove('user_token');
setUser(null)
})
.catch((error) => console.error(error));
}
if(!user){
return (
<a href={gitLoginUrl} className="nav-link btn-rotate">
<i className="fab fa-github"></i>
<p>
<span className=" d-md-block">Log In</span>
</p>
</a>
)
}
return (
<a onClick={ logOutUser } className="nav-link btn-rotate">
<span className=" d-md-block">Log Out</span>
</a>
)
}
export default LoginLogoutLink; | 27.728571 | 101 | 0.488923 |
92bb25393266754d98cf8b9fcb08a8d3d421ccb1 | 470 | js | JavaScript | ikcamp-tutorial/6-router-prefix.js | zjgyb/koa-learning | b6a5002fe2a683964b5aff15ea23ebacd2bf44e4 | [
"MIT"
] | null | null | null | ikcamp-tutorial/6-router-prefix.js | zjgyb/koa-learning | b6a5002fe2a683964b5aff15ea23ebacd2bf44e4 | [
"MIT"
] | null | null | null | ikcamp-tutorial/6-router-prefix.js | zjgyb/koa-learning | b6a5002fe2a683964b5aff15ea23ebacd2bf44e4 | [
"MIT"
] | null | null | null | const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
// 路由前缀
const router = new Router({
prefix: '/users'
});
router.get('/', async (ctx, next) => {
ctx.body = `<h1>hello users!</h1>`;
});
router.get('/:id', async (ctx, next) => {
ctx.body = `<h1>hello users id!</h1>`;
// 获取url参数
console.log(ctx.params);
});
app.use(router.routes());
app.listen(3000, () => {
console.log('success in 3000');
}) | 18.076923 | 42 | 0.557447 |
92bb479eb33c9cedaccc0fb19c9a08fb3d32b812 | 4,701 | js | JavaScript | website/client/src/homepage/Welcome.js | erickim0919/EZCAR | 09209bb7a3587c827aeb938bc5549ad0127febcc | [
"MIT"
] | 3 | 2019-12-25T20:09:04.000Z | 2020-06-04T05:36:16.000Z | website/client/src/homepage/Welcome.js | erickim0919/EZCAR | 09209bb7a3587c827aeb938bc5549ad0127febcc | [
"MIT"
] | 1 | 2020-05-26T17:57:19.000Z | 2020-05-26T17:57:19.000Z | website/client/src/homepage/Welcome.js | erickim0919/EZCAR | 09209bb7a3587c827aeb938bc5549ad0127febcc | [
"MIT"
] | 3 | 2020-06-14T18:13:31.000Z | 2020-06-14T19:59:08.000Z | import React from "react";
import CarAppBar from "./CarAppBar";
import Grid from "@material-ui/core/Grid";
import NewCard from "../cards/NewCard";
import Button from "@material-ui/core/Button";
import axios from "axios";
import { Cookies } from "react-cookie";
// import { ThemeProvider } from '@material-ui/core';
import history from "../routing/history";
import Alert from '@material-ui/lab/Alert';
import {Snackbar} from "@material-ui/core";
class Welcome extends React.PureComponent {
constructor(props) {
const cookie = new Cookies()
console.log(cookie.get("id"));
super(props);
this.rounds = [
["Price", "Newcomer", [0, 30000]],
["Price", "Family Package", [30001, 45000]],
["Price", "Exclusive", [45001, Number.MAX_SAFE_INTEGER]],
["Type", "Convertible", "convertible"],
["Type", "SUV", "suv"],
["Type", "Sports", "coupe"],
["Seats", "Less Than 3", [0, 3]],
["Seats", "Less Than 5", [4, 5]],
["Seats", "More Than 5", [5, "unlimited"]],
];
this.state = {
selection: [],
curIndex: 0,
avails: {
Newcomer: true,
"Family Package": true,
Exclusive: true,
Convertible: true,
SUV: true,
Sports: true,
"Less Than 3": true,
"Less Than 5": true,
"More Than 5": true,
},
currentFilter: "MSRP",
open: false
};
this.choices = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "User's Choices" }),
Price: [],
Type: [],
Seats: [],
sort_by: this.state.currentFilter,
};
this.updateChoices = this.updateChoices.bind(this);
this.submitData = this.submitData.bind(this);
this.carImage = this.carImage.bind(this);
this.generateRankings = this.generateRankings.bind(this);
}
updateChoices(val) {
console.log(val);
if (!this.state.selection.includes(val[1])) {
this.setState({selection: this.state.selection.concat(val[1])})
}
else{
this.setState({selection: this.state.selection.filter(x => x != val[1])})
}
this.setState({open: true})
if (!this.choices[val[0]].includes(val[2])) this.choices[val[0]].push(val[2])
else (this.choices[val[0]] = this.choices[val[0]].filter(item => item != val[2]))
console.log(this.choices);
}
generateRankings = (filter) => {
const obj1 = { sort_by: filter };
return { ...this.choices, ...obj1 };
};
// currently in debug mode. When user is done selecting their choices, the callback fxn submitData will be auto-called
submitData = () => {
const badgePrices = axios.post("/dump_sorted", this.generateRankings("MSRP"));
const badgeRatings = axios.post(
"/dump_sorted",
this.generateRankings("RATING")
);
const badgeEfficiencies = axios.post(
"/dump_sorted",
this.generateRankings("MPG")
);
const sPrices = axios.post("dump_by", this.generateRankings("MSRP"))
const sRatings = axios.post("dump_by", this.generateRankings("RATING"))
const sEfficiencies = axios.post("dump_by", this.generateRankings("MPG"))
axios.all([badgePrices, badgeRatings, badgeEfficiencies, sPrices, sRatings, sEfficiencies]).then(
axios.spread((...responses) => {
const bPrices = responses[0].data;
const bRatings = responses[1].data;
const bEfficiencies = responses[2].data;
const regPrices = responses[3].data;
const regRatings = responses[4].data;
const regMpg = responses[5].data;
history.push({
pathname: "/results",
state: {
badgePrices: bPrices,
badgeRatings: bRatings,
badgeMpg: bEfficiencies,
sortedPrices: regPrices,
sortedRatings: regRatings,
sortedMpg: regMpg
},
});
})
);
};
carImage(index) {
const carPics = [
"newcomer.png", "family.png", "exclusive.png",
"convertible.png", "suv.png", "sports.png",
"lessThan3.png", "lessThan5.png", "moreThan5.png"
];
return carPics[index];
}
render() {
console.log(this.state.selection);
return (
<>
{<Snackbar open={this.state.open} autoHideDuration='1000' onClose={() => this.setState({open: false})} anchorOrigin = {{vertical: 'top', horizontal: 'center'}} ><Alert severity="success"> {
this.state.selection.map((value, item) => value + ", ")}
</Alert></Snackbar>}
<CarAppBar />
<Grid container>
{this.rounds.map((item, index) => {
return (
this.state.avails[item[1]] && (
<Grid item xs={4} key={index}>
<NewCard
id={index}
val={item}
func={this.updateChoices}
text={item[1]}
imgName={this.carImage(index)}
/>
</Grid>
)
);
})}
</Grid>
<Button onClick={this.submitData}>Submit Data</Button>
</>
);
}
}
export default Welcome;
| 28.319277 | 193 | 0.625399 |
92beef8739cfb60616e8668f4e58ec027fbd2e41 | 11,187 | js | JavaScript | clients/Semantic-UI-1.1.2/dist/components/progress.min.js | IonicaBizau/arc-assembler | 8f71d896103c0b3087a80e915edfe8e41c422210 | [
"MIT"
] | 5 | 2015-01-05T17:56:57.000Z | 2017-11-03T18:04:00.000Z | clients/Semantic-UI-1.1.2/dist/components/progress.min.js | IonicaBizau/arc-assembler | 8f71d896103c0b3087a80e915edfe8e41c422210 | [
"MIT"
] | null | null | null | clients/Semantic-UI-1.1.2/dist/components/progress.min.js | IonicaBizau/arc-assembler | 8f71d896103c0b3087a80e915edfe8e41c422210 | [
"MIT"
] | 1 | 2016-02-05T09:53:43.000Z | 2016-02-05T09:53:43.000Z | "use strict";
/*
* # Semantic UI
* https://github.com/Semantic-Org/Semantic-UI
* http://www.semantic-ui.com/
*
* Copyright 2014 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
!function (e, t, n, r) {
"use strict";
e.fn.progress = function (t) {
var n,
a = e(this),
o = a.selector || "",
s = new Date().getTime(),
c = [],
i = arguments[0],
l = "string" == typeof i,
u = [].slice.call(arguments, 1);return a.each(function () {
var a,
g = e.isPlainObject(t) ? e.extend(!0, {}, e.fn.progress.settings, t) : e.extend({}, e.fn.progress.settings),
p = g.className,
m = g.metadata,
v = g.namespace,
d = g.selector,
b = g.error,
f = "module-" + v,
h = e(this),
x = e(this).find(d.bar),
y = e(this).find(d.progress),
w = e(this).find(d.label),
C = this,
A = h.data(f);a = { initialize: function initialize() {
a.debug("Initializing progress", g), a.read.metadata(), a.set.initials(), a.instantiate();
}, instantiate: function instantiate() {
a.verbose("Storing instance of progress", a), A = a, h.data(f, a);
}, destroy: function destroy() {
a.verbose("Destroying previous dropdown for", h), h.removeData(f), A = r;
}, reset: function reset() {
a.set.percent(0);
}, complete: function complete() {
(a.percent === r || a.percent < 100) && a.set.percent(100);
}, read: { metadata: function metadata() {
h.data(m.percent) && (a.verbose("Current percent value set from metadata"), a.percent = h.data(m.percent)), h.data(m.total) && (a.verbose("Total value set from metadata"), a.total = h.data(m.total)), h.data(m.value) && (a.verbose("Current value set from metadata"), a.value = h.data(m.value));
}, currentValue: function currentValue() {
return a.value !== r ? a.value : !1;
} }, increment: function increment(e) {
var t,
n,
r,
o = a.total || !1;o ? (n = a.value || 0, e = e || 1, r = n + e, t = a.total, a.debug("Incrementing value by", e, n, t), r > t && (a.debug("Value cannot increment above total", t), r = t), a.set.progress(r)) : (n = a.percent || 0, e = e || a.get.randomValue(), r = n + e, t = 100, a.debug("Incrementing percentage by", e, n), r > t && (a.debug("Value cannot increment above 100 percent"), r = t), a.set.progress(r));
}, decrement: function decrement(e) {
var t,
n,
r = a.total || !1,
o = 0;r ? (t = a.value || 0, e = e || 1, n = t - e, a.debug("Decrementing value by", e, t)) : (t = a.percent || 0, e = e || a.get.randomValue(), n = t - e, a.debug("Decrementing percentage by", e, t)), o > n && (a.debug("Value cannot decrement below 0"), n = 0), a.set.progress(n);
}, get: { text: function text(e) {
var t = a.value || 0,
n = a.total || 0,
r = a.percent || 0;return e = e || "", e = e.replace("{value}", t).replace("{total}", n).replace("{percent}", r), a.debug("Adding variables to progress bar text", e), e;
}, randomValue: function randomValue() {
return a.debug("Generating random increment percentage"), Math.floor(Math.random() * g.random.max + g.random.min);
}, percent: function percent() {
return a.percent || 0;
}, value: function value() {
return a.value || !1;
}, total: function total() {
return a.total || !1;
} }, is: { success: function success() {
return h.hasClass(p.success);
}, warning: function warning() {
return h.hasClass(p.warning);
}, error: function error() {
return h.hasClass(p.error);
} }, remove: { active: function active() {
a.verbose("Removing active state"), h.removeClass(p.active);
}, success: function success() {
a.verbose("Removing success state"), h.removeClass(p.success);
}, warning: function warning() {
a.verbose("Removing warning state"), h.removeClass(p.warning);
}, error: function error() {
a.verbose("Removing error state"), h.removeClass(p.error);
} }, set: { barWidth: function barWidth(e) {
e > 100 && a.error(b.tooHigh, e), x.css("width", e + "%");
}, initials: function initials() {
g.value && (a.verbose("Current value set in settings", g.value), a.value = g.value), g.total && (a.verbose("Current total set in settings", g.total), a.total = g.total), g.percent && (a.verbose("Current percent set in settings", g.percent), a.percent = g.percent), a.percent ? a.set.percent(a.percent) : a.value && a.set.progress(a.value);
}, percent: function percent(t) {
t = "string" == typeof t ? +t.replace("%", "") : t, t > 0 && 1 > t && (a.verbose("Module percentage passed as decimal, converting"), t = 100 * t), t = Math.round(0 === g.precision ? t : 10 * t * g.precision / (10 * g.precision)), a.percent = t, a.total && (a.value = Math.round(t / 100 * a.total)), a.set.barWidth(t), a.set.barLabel(), 100 === t ? !g.autoSuccess || a.is.warning() || a.is.error() ? a.remove.active() : (a.set.success(), a.debug("Automatically triggering success at 100%")) : a.set.active(), e.proxy(g.onChange, C)(t, a.value, a.total);
}, label: function label(e) {
e = e || "", e && (e = a.get.text(e), a.debug("Setting label to text", e), w.text(e));
}, barLabel: function barLabel(e) {
e !== r ? y.text(a.get.text(e)) : "ratio" == g.label && a.total ? (a.debug("Adding ratio to bar label"), y.text(a.get.text(g.text.ratio))) : "percent" == g.label && (a.debug("Adding percentage to bar label"), y.text(a.get.text(g.text.percent)));
}, active: function active(t) {
t = t || g.text.active, a.debug("Setting active state"), g.showActivity && h.addClass(p.active), a.remove.warning(), a.remove.error(), a.remove.success(), t && a.set.label(t), e.proxy(g.onActive, C)(a.value, a.total);
}, success: function success(t) {
t = t || g.text.success, a.debug("Setting success state"), h.addClass(p.success), a.remove.active(), a.remove.warning(), a.remove.error(), a.complete(), t && a.set.label(t), e.proxy(g.onSuccess, C)(a.total);
}, warning: function warning(t) {
t = t || g.text.warning, a.debug("Setting warning state"), h.addClass(p.warning), a.remove.active(), a.remove.success(), a.remove.error(), a.complete(), t && a.set.label(t), e.proxy(g.onWarning, C)(a.value, a.total);
}, error: function error(t) {
t = t || g.text.error, a.debug("Setting error state"), h.addClass(p.error), a.remove.active(), a.remove.success(), a.remove.warning(), a.complete(), t && a.set.label(t), e.proxy(g.onError, C)(a.value, a.total);
}, total: function total(e) {
a.total = e;
}, progress: function progress(e) {
var t,
n = "string" == typeof e ? "" !== e.replace(/[^\d.]/g, "") ? +e.replace(/[^\d.]/g, "") : !1 : e;n || a.error(b.nonNumeric), a.total ? (a.value = n, t = n / a.total * 100, a.debug("Calculating percent complete from total", t), a.set.percent(t)) : (t = n, a.debug("Setting value to exact percentage value", t), a.set.percent(t));
} }, setting: function setting(t, n) {
if (a.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, g, t);else {
if (n === r) return g[t];g[t] = n;
}
}, internal: function internal(t, n) {
if (e.isPlainObject(t)) e.extend(!0, a, t);else {
if (n === r) return a[t];a[t] = n;
}
}, debug: function debug() {
g.debug && (g.performance ? a.performance.log(arguments) : (a.debug = Function.prototype.bind.call(console.info, console, g.name + ":"), a.debug.apply(console, arguments)));
}, verbose: function verbose() {
g.verbose && g.debug && (g.performance ? a.performance.log(arguments) : (a.verbose = Function.prototype.bind.call(console.info, console, g.name + ":"), a.verbose.apply(console, arguments)));
}, error: function error() {
a.error = Function.prototype.bind.call(console.error, console, g.name + ":"), a.error.apply(console, arguments);
}, performance: { log: function log(e) {
var t, n, r;g.performance && (t = new Date().getTime(), r = s || t, n = t - r, s = t, c.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: C, "Execution Time": n })), clearTimeout(a.performance.timer), a.performance.timer = setTimeout(a.performance.display, 100);
}, display: function display() {
var t = g.name + ":",
n = 0;s = !1, clearTimeout(a.performance.timer), e.each(c, function (e, t) {
n += t["Execution Time"];
}), t += " " + n + "ms", o && (t += " '" + o + "'"), (console.group !== r || console.table !== r) && c.length > 0 && (console.groupCollapsed(t), console.table ? console.table(c) : e.each(c, function (e, t) {
console.log(t.Name + ": " + t["Execution Time"] + "ms");
}), console.groupEnd()), c = [];
} }, invoke: function invoke(t, o, s) {
var c,
i,
l,
g = A;return o = o || u, s = C || s, "string" == typeof t && g !== r && (t = t.split(/[\. ]/), c = t.length - 1, e.each(t, function (n, o) {
var s = n != c ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(g[s]) && n != c) g = g[s];else {
if (g[s] !== r) return i = g[s], !1;if (!e.isPlainObject(g[o]) || n == c) return g[o] !== r ? (i = g[o], !1) : (a.error(b.method, t), !1);g = g[o];
}
})), e.isFunction(i) ? l = i.apply(s, o) : i !== r && (l = i), e.isArray(n) ? n.push(l) : n !== r ? n = [n, l] : l !== r && (n = l), i;
} }, l ? (A === r && a.initialize(), a.invoke(i)) : (A !== r && a.destroy(), a.initialize());
}), n !== r ? n : this;
}, e.fn.progress.settings = { name: "Progress", namespace: "progress", debug: !0, verbose: !0, performance: !0, random: { min: 2, max: 5 }, autoSuccess: !0, showActivity: !0, label: "percent", precision: 1, percent: !1, total: !1, value: !1, onChange: function onChange() {}, onSuccess: function onSuccess() {}, onActive: function onActive() {}, onError: function onError() {}, onWarning: function onWarning() {}, error: { method: "The method you called is not defined.", nonNumeric: "Progress value is non numeric" }, regExp: { variable: /\{\$*[A-z0-9]+\}/g }, metadata: { percent: "percent", total: "total", value: "value" }, selector: { bar: "> .bar", label: "> .label", progress: ".bar > .progress" }, text: { active: !1, error: !1, success: !1, warning: !1, percent: "{percent}%", ratio: "{value} of {total}" }, className: { active: "active", error: "error", success: "success", warning: "warning" } };
}(jQuery, window, document); | 77.151724 | 909 | 0.541074 |
92bf6a62aa536fa00d5d4b6507984a7b716158b2 | 3,924 | js | JavaScript | gui/src/app/classes/model-description.js | mbonvini/LambdaSim | 9170e0b5c620ada11ad5246ae4eaf7a8d4162c5f | [
"MIT"
] | 48 | 2017-03-27T17:12:55.000Z | 2021-08-12T10:01:19.000Z | gui/src/app/classes/model-description.js | mbonvini/LambdaSim | 9170e0b5c620ada11ad5246ae4eaf7a8d4162c5f | [
"MIT"
] | 3 | 2017-03-12T07:24:14.000Z | 2017-09-29T07:48:08.000Z | gui/src/app/classes/model-description.js | mbonvini/LambdaSim | 9170e0b5c620ada11ad5246ae4eaf7a8d4162c5f | [
"MIT"
] | 10 | 2017-04-04T13:30:39.000Z | 2020-07-12T14:58:09.000Z | import { parseString } from 'xml2js';
import log from 'loglevel';
const FMI_MODEL_DESCRIPTION = "fmiModelDescription";
const VENDOR_ANNOTATIONS = "VendorAnnotations";
const MODEL_VARIABLES = "ModelVariables";
const SCALAR_VARIABLE = "ScalarVariable";
const TOOL = "Tool";
const OBJECT = "$";
const REAL = "Real";
const BOOLEAN = "Boolean";
const INTEGER = "Integer";
const STRING = "String";
const ENUMERATION = "Enumeration"
const VAR_TYPES = [REAL, BOOLEAN, INTEGER, STRING, ENUMERATION];
export class ModelDescription {
constructor() {
this.description = null;
this.typeDefinitions = null;
this.unitDefinitions = null;
this.vendorAnnotations = null;
this.modelVariables = null;
this.modelStructure = null;
}
loadFromXml(modelDescriptionXml) {
self = this;
parseString(modelDescriptionXml, function (err, modelDescription) {
if (err) {
log.error(err);
} else {
// High level model description
if (modelDescription.hasOwnProperty(FMI_MODEL_DESCRIPTION)) {
const fmiModelDescription = modelDescription[FMI_MODEL_DESCRIPTION];
self.description = fmiModelDescription[OBJECT];
// Vendor annotations (optional)
if (fmiModelDescription.hasOwnProperty(VENDOR_ANNOTATIONS)) {
self.vendorAnnotations = fmiModelDescription[VENDOR_ANNOTATIONS].map(
function (vendorAnn) {
if (vendorAnn.hasOwnProperty(TOOL)) {
return vendorAnn[TOOL].map(
function (tool) {
return tool[OBJECT];
}
);
} else {
return [];
}
}
)
} else {
log.info("Missing " + VENDOR_ANNOTATIONS);
}
// Units (optional)
// Model scalar variables (required)
if (fmiModelDescription.hasOwnProperty(MODEL_VARIABLES)) {
if (fmiModelDescription[MODEL_VARIABLES].length > 0) {
if (fmiModelDescription[MODEL_VARIABLES][0].hasOwnProperty(SCALAR_VARIABLE)) {
const scalarVars = fmiModelDescription[MODEL_VARIABLES][0][SCALAR_VARIABLE];
self.modelVariables = scalarVars.map(
function (variable) {
let varObj = variable[OBJECT];
for(let x in VAR_TYPES){
if(variable.hasOwnProperty(VAR_TYPES[x])){
varObj['type'] = VAR_TYPES[x];
varObj['typeAttr'] = variable[VAR_TYPES[x]][0][OBJECT];
}
}
return varObj;
}
);
}else{
log.error("Missing " + SCALAR_VARIABLE);
}
}else{
log.error("No model variables");
}
} else {
log.error("Missing " + MODEL_VARIABLES);
}
} else {
log.error("Missing " + FMI_MODEL_DESCRIPTION);
}
}
});
}
} | 40.453608 | 108 | 0.43578 |
92bf9b5859ac4808503b597be8f5850a7a4838c1 | 656 | js | JavaScript | src/chui/blockui.js | Shivani4universe/chocolatechip-ui | a372709ff9562445dc152a4c24ac337d9e62dd1f | [
"MIT"
] | 39 | 2015-01-01T09:41:12.000Z | 2019-06-12T19:58:26.000Z | src/chui/blockui.js | TimothyJu1985/chocolatechip-ui | a372709ff9562445dc152a4c24ac337d9e62dd1f | [
"MIT"
] | 3 | 2015-01-20T17:50:56.000Z | 2015-03-12T04:43:16.000Z | src/chui/blockui.js | TimothyJu1985/chocolatechip-ui | a372709ff9562445dc152a4c24ac337d9e62dd1f | [
"MIT"
] | 11 | 2015-01-05T12:26:00.000Z | 2021-01-09T03:49:59.000Z | (function($) {
"use strict";
$.fn.extend({
/////////////////////////
// Block Screen with Mask
/////////////////////////
UIBlock : function ( opacity ) {
opacity = opacity ? " style='opacity:" + opacity + "'" : " style='opacity: .5;'";
$(this).before("<div class='mask'" + opacity + "></div>");
$('article.current').attr('aria-hidden',true);
return this;
},
//////////////////////////
// Remove Mask from Screen
//////////////////////////
UIUnblock : function ( ) {
$('.mask').remove();
$('article.current').removeAttr('aria-hidden');
return this;
}
});
})(window.$); | 28.521739 | 87 | 0.431402 |
92c0eae87b971eca7e621c32184a535f1a06d771 | 5,759 | js | JavaScript | Day 13/day13.js | jmjardim05/AdventOfCode2020 | ba36f48c3dbadf7a7782c02117a56f002db16ebf | [
"MIT"
] | null | null | null | Day 13/day13.js | jmjardim05/AdventOfCode2020 | ba36f48c3dbadf7a7782c02117a56f002db16ebf | [
"MIT"
] | null | null | null | Day 13/day13.js | jmjardim05/AdventOfCode2020 | ba36f48c3dbadf7a7782c02117a56f002db16ebf | [
"MIT"
] | null | null | null | /*
****** Advent Of Code 2020 ******
Solution for day 13
https://adventofcode.com/2020/day/13
Author: João Marcos Jardim
*/
const readInputFile = require("../readInput");
const busDepartures = readInputFile("Day 13");
/*
Algorithm for Day 13 - First puzzle
1. create an array of bus id's, filter out non working ones (x)
2. loop
3. divide your estimate by bus id (get the integer part only, save the remainder)
4. if result * id is lower than your estimate then wait time = bus id minus remainder of division
5. if result * id is higher than your estimate then wait time = remainder
6. get the bus id with lowest wait time
7. result is the wait time * bus id
*/
const yourEstimate = Number.parseInt(busDepartures[0]);
const busesIds = busDepartures[1].split(",").filter(value => value !== "x");
let nextBusId = 0;
let minWaitTime = Infinity;
busesIds.forEach(value => {
const busId = Number.parseInt(value);
const travels = Math.trunc(yourEstimate / busId);
const remainingMin = yourEstimate - busId * travels;
let waitTime = 0;
if (busId * travels < yourEstimate) {
waitTime = busId - remainingMin;
}
if (waitTime < minWaitTime) {
minWaitTime = waitTime;
nextBusId = busId;
}
});
console.log("\nSolution for Day 13 - First puzzle:", nextBusId * minWaitTime, " Bus Id", nextBusId, "Wait time", minWaitTime);
/*
Algorithm for Day 13 - Second puzzle
algorithm 2 - (incrementing the first bus id and looking at the other id's)
1. create an array of bus id's (now consider the non working)
2. loop
3. add first id (next bus travel)
4. set a boolean to true (means every id departed at the offset time from each other)
5. loop from second id
6. get the remainder of next bus travel + index (index will be equal to the offset) divided by current id
7. if remainder different than 0 then set boolean to false exit loop, go to next iteration of first id travel
8. else continue
9. if current bus id is 'x' continue loop
10. after exiting loop, if boolean is true exit travel iteration of first id
11. result is the last iteration of first id (current next bus travel)
NOTE: it worked for some of the test input, with less id's... need to find more efficient logic
algorithm 2 - little optimization by incrementing the min id by the value that multiplied + offset is a valid departure for max id
NOTE: It took more than 1 hour (1:12:11.574 (h:mm:ss.mmm) to be exactly), at least is the correct answer :\
algorithm 2 - final optimization - still not found a solution, I'm feeling dumb :(
*/
console.time("part2 - Optimized");
const findEarliestTimeStamp = () => {
let arr = [ ...busesIds.map(value => Number.parseInt(value)) ];
const arr2 = busDepartures[1].split(",");
const minBusId = Math.min(...arr);
const minBusIdIndex = arr2.indexOf(minBusId.toString());
let maxBusId = Math.max(...arr);
let maxBusIdIndex = arr2.indexOf(maxBusId.toString());
let offsetMinMax = maxBusIdIndex - minBusIdIndex;
const findTimeStampFactor = (i, id, offset, factor) => {
let found = false;
while (!found) {
const nextBusTravel = id * factor + offset;
const y = nextBusTravel % maxBusId;
found = y === 0;
factor += i;
}
factor -= i;
const maxId = arr.splice(arr.indexOf(maxBusId), 1)[0];
maxBusId = Math.max(...arr);
maxBusIdIndex = arr2.indexOf(maxBusId.toString());
offsetMinMax = maxBusIdIndex - minBusIdIndex;
if (offsetMinMax !== 0) {
const nextIterator = i * maxId;
factor = findTimeStampFactor(nextIterator, minBusId, offsetMinMax, factor);
}
return factor;
}
return minBusId * findTimeStampFactor(1, minBusId, offsetMinMax, 1) - minBusIdIndex;
}
console.log("\nSolution for Day 13 - Second puzzle (optimized):", findEarliestTimeStamp());
console.timeEnd("part2 - Optimized");
// this is the original (bad) code
console.time("part2");
const allBuses = busDepartures[1].split(",").reduce((prev, value, index) => {
if (value !== "x") {
prev.push([value, index]);
}
return prev;
}, []);
const maxBusId = Math.max(...busesIds.map(value => Number.parseInt(value)));
const minBusId = Math.min(...busesIds.map(value => Number.parseInt(value)));
const maxBusIdIndex = allBuses.find(value => value[0] == maxBusId)[1];
const minBusIdIndex = allBuses.find(value => value[0] == minBusId)[1];
const offsetMinMax = maxBusIdIndex - minBusIdIndex;
let next = 0;
let x = 0; // 'x' will store the next number in which the 'min id' times 'x' plus the 'offset' will be 'max id' departure timestamp
let found = false;
while (!found) {
next++;
const nextBusTravel = maxBusId * next - offsetMinMax;
const y = nextBusTravel % minBusId;
x = nextBusTravel / minBusId;
found = y === 0;
}
found = false;
let earliestTimestamp = 0;
while (!found) {
found = true;
for (let i = 0; i < allBuses.length; i++) {
const timestamp = minBusId * x - (minBusIdIndex - allBuses[i][1]);
if (i === 0) {
earliestTimestamp = timestamp;
}
if (/*allBuses[i] === "x" ||*/ allBuses[i][1] === minBusIdIndex || allBuses[i][1] === maxBusIdIndex) {
continue;
}
const busId = Number.parseInt(allBuses[i][0]);
const remainder = timestamp % busId;
if (remainder !== 0) {
found = false;
break;
}
}
x += maxBusId;
}
console.log("\nSolution for Day 13 - Second puzzle:", earliestTimestamp);
console.timeEnd("part2"); | 37.640523 | 134 | 0.637958 |
92c103b519397ced2cbb45961d9f8064910bb438 | 4,196 | js | JavaScript | lib/index.js | Melodyn/npm-autoloader | 50683f10c6cde34060f0c0c66743ae0feb1f3d8b | [
"MIT"
] | 5 | 2019-12-06T09:02:55.000Z | 2020-08-06T10:16:52.000Z | lib/index.js | Melodyn/npm-autoloader | 50683f10c6cde34060f0c0c66743ae0feb1f3d8b | [
"MIT"
] | 1 | 2021-05-10T20:39:44.000Z | 2021-05-10T20:39:44.000Z | lib/index.js | Melodyn/npm-dynamicimport | 50683f10c6cde34060f0c0c66743ae0feb1f3d8b | [
"MIT"
] | null | null | null | // @ts-check
import { promises as fs, existsSync } from 'fs';
import * as path from 'path';
const { entries } = Object;
/**
* @param filename {string}
* @returns {string[]}
*/
const processFileExtensions = filename => {
const filenameParts = filename.split('.');
return filenameParts
.pop()
.split('|')
.map(extension => filenameParts.concat(extension).join('.'));
};
/**
* @param objectsArray {object[]}
* @returns {*}
*/
const arrayToObject = objectsArray =>
objectsArray.reduce((acc, obj) => {
const [[key, value]] = entries(obj);
return { ...acc, [key]: value };
}, {});
/**
* @description black magic here
* @param projectRoot {string}
* @param modulePath {string[]}
* @returns {Promise<string|string[]>}
*/
const buildPaths = async (projectRoot, modulePath, searchFlag = '*') => {
if (modulePath.length === 0) {
return existsSync(projectRoot) ? projectRoot : '';
}
const [currentPathPart, ...tail] = modulePath;
if (currentPathPart !== searchFlag) {
return buildPaths(path.resolve(projectRoot, currentPathPart), tail, searchFlag);
}
return fs
.readdir(projectRoot, { withFileTypes: true })
.then(includes => includes.filter(obj => obj.isDirectory()))
.then(includedDirs => includedDirs.map(dir => path.resolve(projectRoot, dir.name)))
.then(subDirs => Promise.all(subDirs.map(subDir => buildPaths(subDir, tail, searchFlag))))
.then(paths => paths.flat())
.catch(() => []);
};
/**
* @param projectRoot {string}
* @param modulePath {string[]=}
* @param moduleName {string=}
* @returns {Promise<Object<string, string[]>>}
*/
const getModulesRawPaths = async (projectRoot, modulePath = [], moduleName = 'default') => {
if (!projectRoot) {
throw new Error('Missing project root');
}
if (!existsSync(projectRoot)) {
throw new Error(`Path ${projectRoot} not exists`);
}
const isPackageJsonStrategy = !modulePath || modulePath.length === 0;
if (isPackageJsonStrategy) {
const packageJsonFilePath = path.resolve(projectRoot, 'package.json');
if (!existsSync(packageJsonFilePath)) {
throw new Error(`Not found package.json in ${packageJsonFilePath}`);
}
return fs.readFile(packageJsonFilePath).then(content => {
const fields = JSON.parse(content.toString());
if (!Object.hasOwnProperty.call(fields, 'autoload')) {
throw new Error(`Missing field 'autoload' in ${packageJsonFilePath}`);
}
return fields.autoload;
});
}
return {
[moduleName]: modulePath,
};
};
/**
* @param projectRoot {string}
* @param modulePath {string[]=}
* @param moduleGroupName {string=}
* @returns {Promise<string>}
*/
const autoloader = async (projectRoot, modulePath = [], moduleGroupName = 'default') => {
const modulesRawPathsParts = await getModulesRawPaths(projectRoot, modulePath, moduleGroupName);
const modulesFilesPathsParts = entries(modulesRawPathsParts).reduce((acc, [moduleName, moduleRawPath]) => {
const rawFilename = moduleRawPath.pop();
const processedFilenames = processFileExtensions(rawFilename);
const pathsWithFilenames = processedFilenames.map(filename => moduleRawPath.concat(filename));
return { ...acc, [moduleName]: pathsWithFilenames };
}, {});
const modulesFilesPaths = await Promise.all(
entries(modulesFilesPathsParts).map(([moduleName, modulePathParts]) =>
Promise.all(modulePathParts.map(modulePathPart => buildPaths(projectRoot, modulePathPart)))
.then(paths => paths.flat().filter(processedPath => processedPath))
.then(existingPaths => ({ [moduleName]: existingPaths })),
),
);
const processedModulesFilesPaths = arrayToObject(modulesFilesPaths);
const availableModules = entries(processedModulesFilesPaths).reduce(
(acc, [moduleName, modulePaths]) => (modulePaths.length === 0 ? acc : { ...acc, [moduleName]: modulePaths }),
{},
);
return Promise.all(
entries(availableModules).map(([moduleName, modulePaths]) =>
Promise.all(modulePaths.map(moduleLoadPath => import(moduleLoadPath))).then(loadedModule => ({
[moduleName]: loadedModule,
})),
),
).then(arrayToObject);
};
export default autoloader;
| 34.113821 | 113 | 0.67183 |
92c11b2e325ee40498c7fc88103b006a14112898 | 1,241 | js | JavaScript | src/screens/profile/profile.js | roshannizar/FreshGrassets | ba6f9cdd016acc80f451e2b7c77a5f589e81faf1 | [
"MIT"
] | null | null | null | src/screens/profile/profile.js | roshannizar/FreshGrassets | ba6f9cdd016acc80f451e2b7c77a5f589e81faf1 | [
"MIT"
] | null | null | null | src/screens/profile/profile.js | roshannizar/FreshGrassets | ba6f9cdd016acc80f451e2b7c77a5f589e81faf1 | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
import { Appbar } from 'react-native-paper';
import { logoutUser } from '../../redux/actions/authActions';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
class Profile extends Component {
constructor(props) {
super(props);
this._handleLogout = this._handleLogout.bind(this);
}
_handleLogout() {
this.props.logoutUser();
Actions.authentication();
}
render() {
return (
<View style={styles.container}>
<Appbar.Header style={{ backgroundColor: 'whitesmoke' }}>
<Appbar.Content title='Profile' />
<Appbar.Action icon='logout' onPress={this._handleLogout} />
</Appbar.Header>
</View>
);
}
}
Profile.propTypes = {
logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
}
const mapStateToProps = state => ({
auth: state.auth
})
export default connect(mapStateToProps, { logoutUser })(Profile);
const styles = StyleSheet.create({
container: {
flex: 1
}
}); | 25.854167 | 80 | 0.60838 |
92c2d7d9f56a6f6a097a1e33b26e83f7246ee419 | 926 | js | JavaScript | closure-degradation/index.js | swarthy/benchmark | 848a6dc08bc001ff902f62ebdae4809095c7937d | [
"MIT"
] | 3 | 2020-11-10T16:01:27.000Z | 2020-11-14T01:31:35.000Z | closure-degradation/index.js | swarthy/benchmark | 848a6dc08bc001ff902f62ebdae4809095c7937d | [
"MIT"
] | 1 | 2021-05-09T13:58:12.000Z | 2021-05-09T13:58:12.000Z | closure-degradation/index.js | swarthy/benchmark | 848a6dc08bc001ff902f62ebdae4809095c7937d | [
"MIT"
] | null | null | null | const Benchmark = require('benchmark')
const createSelector = require('reselect').createSelector
const state = {
entities: {
users: {
1: { id: 1 },
2: { id: 2 },
3: { id: 3 }
}
}
}
function nativeTest() {
const nativeSelector = state => state.entities.users
return function() {
nativeSelector(state)
}
}
const createGeneratedSelector = key => state => state.entities[key]
function generatedTest() {
const generatedSelector = createGeneratedSelector('users')
return function() {
generatedSelector(state)
}
}
const suite = new Benchmark.Suite('closure-degradation')
function onCycle(event) {
console.log(String(event.target))
}
function onComplete() {
console.log(this.name, 'Fastest is ' + this.filter('fastest').map('name'))
}
suite
.add('native', nativeTest())
.add('generated', generatedTest())
.on('cycle', onCycle)
.on('complete', onComplete)
.run()
| 20.130435 | 76 | 0.660907 |
92c2fad7d7431380d0e520b6f537b252f3e1c0bb | 4,199 | js | JavaScript | webenmr/public/global/javascript/email_check.js | andreagia/WEBNMR | 512a8cc04cf69300796585feae722614501389a9 | [
"Apache-2.0"
] | null | null | null | webenmr/public/global/javascript/email_check.js | andreagia/WEBNMR | 512a8cc04cf69300796585feae722614501389a9 | [
"Apache-2.0"
] | null | null | null | webenmr/public/global/javascript/email_check.js | andreagia/WEBNMR | 512a8cc04cf69300796585feae722614501389a9 | [
"Apache-2.0"
] | null | null | null | function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
fits the user@domain format. It also is used to separate the username
from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
characters. We don't want to allow special characters in the address.
These characters include ( ) < > @ , ; : \ " . [ ] */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a
username or domainname. It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes). E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
rather than symbolic names. E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
/* Finally, let's start trying to figure out if the supplied address is
valid. */
/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */
alert("Email address seems incorrect (check @ and .'s)")
return false
}
var user=matchArray[1]
var domain=matchArray[2]
// See if "user" is valid
if (user.match(userPat)==null) {
// user is not valid
alert("The username doesn't seem to be valid.")
return false
}
/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
// this is an IP address
for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert("Destination IP address is invalid!")
return false
}
}
return true
}
// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
alert("The domain name doesn't seem to be valid.")
return false
}
/* domain name seems valid, but now make sure that it ends in a
three-letter word (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding
the domain or country. */
/* Now we need to break up the domain to get a count of how many atoms
it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 ||
domArr[domArr.length-1].length>3) {
// the address must end in a two letter or three letter word.
alert("The address must end in a three-letter domain, or two letter country.")
return false
}
// Make sure there's a host name preceding the domain.
if (len<2) {
var errStr="This address is missing a hostname!"
alert(errStr)
return false
}
// If we've gotten this far, everything's valid!
return true;
}
| 41.99 | 84 | 0.645392 |
92c3347319fb5bde2094ea2f1e2bb436ab4176d4 | 6,853 | js | JavaScript | bin/html2/layout.js | jsoftware/j-playground | fec7be5a9dc92d45c7326556b6058e63fb4f979a | [
"MIT"
] | 4 | 2022-01-19T04:23:49.000Z | 2022-03-28T18:55:38.000Z | bin/html2/layout.js | jsoftware/j-playground | fec7be5a9dc92d45c7326556b6058e63fb4f979a | [
"MIT"
] | 15 | 2022-02-28T13:09:29.000Z | 2022-03-11T01:15:39.000Z | bin/html2/layout.js | jsoftware/j-playground | fec7be5a9dc92d45c7326556b6058e63fb4f979a | [
"MIT"
] | 2 | 2022-01-29T13:26:27.000Z | 2022-02-23T02:43:31.000Z | // layout
// vstate 0=hidden, 1=show (view)
// v/h prop current left (vertical), top (horizontal) proportion of data panes
"use strict";
let mbarsize, tbarsize, topsize;
// ---------------------------------------------------------------------
var layout = new function() {
let r = new Object();
let O = console.log;
let hprop, vprop, vstate;
let panes;
hprop = vprop = 0.5;
vstate = 0;
// ---------------------------------------------------------------------
function centerpanes() {
vprop = hprop = 0.5;
resizer();
}
// ---------------------------------------------------------------------
r.centerpanes = centerpanes;
// ---------------------------------------------------------------------
r.closeviewer = function() {
vstate = 0;
resizer();
};
// ----------------------------------------------------------------------
r.exec = function(str) {
return eval(str);
};
// ---------------------------------------------------------------------
// for testing...
r.fini = function() {
editopen();
};
// ---------------------------------------------------------------------
r.getmainheight = function() {
return Math.max(0, getheight(mainpane) - topsize);
};
// ---------------------------------------------------------------------
r.getsideheight = function() {
return Math.max(0, getheight(sidepane) - topsize);
};
// ---------------------------------------------------------------------
r.getviewheight = function() {
return Math.max(0, getheight(viewpane) - topsize - 2);
};
// ---------------------------------------------------------------------
r.heights = function() {
O("body=" + getheight(document.body) + ", tbar=" + getheight(tbar) +
", topsize=" + topsize + ", panes=" + getheight(panes) +
", mainpane=" + getheight(mainpane) + ", main=" + getheight(main) +
", sidepane=" + getheight(sidepane) + ", side=" + getheight(side) +
", viewpane=" + getheight(viewpane) + ", view=" + getheight(view));
};
// ---------------------------------------------------------------------
// called at outset or when panes are flipped
r.init = function() {
panes = getid("panes");
topsize = getheight(maintop);
mbarsize = getwidth(vb);
tbarsize = getheight(tbar);
hb.onmousedown = slider;
vb.onmousedown = slider;
};
// ---------------------------------------------------------------------
r.openview = function() {
vstate = 1;
resizer();
};
// ---------------------------------------------------------------------
r.showedit = function(ifshow) {
if (ifshow) {
if (panex && vprop > 0.1) return;
if (!panex && hprop < 0.9) return;
centerpanes();
} else {
if (panex) vprop = 0;
else hprop = 1;
}
resizer();
};
// ---------------------------------------------------------------------
r.size = function() {
let h, m, s, t, w, bh, lh, lw, rh, rw, th, tw;
h = getheight(document.body) - tbarsize;
w = getwidth(panes);
setheight(panes, h);
// panex 0
if (panex == 0) {
setheight(vb, h);
setheight(splitpane, h);
setheight(main, h - topsize);
show(vb);
lw = Math.floor(hprop * (w - mbarsize));
setwidth(mainpane, lw);
setwidth(splitpane, w - lw - mbarsize);
if (vstate) {
rh = h - 2 * topsize - mbarsize;
th = Math.max(0, Math.floor(vprop * rh));
setheight(view, th - 1);
setheight(side, rh - th - 1);
show(hb);
show(viewpane);
} else {
hide(viewpane);
hide(hb);
setheight(side, h - topsize);
}
} else {
show(hb);
t = mbarsize;
rh = h - 2 * topsize - t;
th = topsize + Math.max(0, Math.floor(vprop * rh));
setheight(splitpane, th);
setheight(mainpane, h - th - t);
setheight(main, h - th - t - topsize);
if (vstate) {
setheight(vb, th);
show(vb);
t = getwidth(vb);
rw = w - t;
tw = Math.max(0, Math.floor(hprop * rw));
setwidth(sidepane, tw);
setheight(side, th - topsize);
setwidth(side, tw);
setwidth(viewpane, rw - tw - 2);
setheight(view, th - topsize);
setwidth(view, rw - tw - 2);
show(viewpane);
} else {
hide(viewpane);
hide(vb);
setheight(side, th - topsize);
setwidth(sidepane, w);
setwidth(side, w);
}
}
cmsetsize();
};
// ---------------------------------------------------------------------
r.state = function() {
O("vstate=" + vstate + ", panex,hprop,vprop=" + panex + ", " +
round(hprop, 0.001) + ", " + round(vprop, 0.001));
};
// ---------------------------------------------------------------------
r.toggleedit = function() {
if (panex) {
if (vprop < 0.05) centerpanes();
else vprop = 0;
} else {
if (hprop > 0.95) centerpanes();
else hprop = 1;
}
resizer();
};
// ---------------------------------------------------------------------
r.widths = function() {
O("body=" + window.innerWidth + ", tbar=" + getwidth(tbar) +
", panes=" + getwidth(panes) +
", splitpane=" + getwidth(splitpane) + ", sidepane=" + getwidth(sidepane) +
", mainpane=" + getwidth(mainpane) + ", main=" + getwidth(main));
};
// sliders ------------------------------------------------------------
function slider(e) {
e.preventDefault();
e.stopPropagation();
let em = this;
let id = em.id;
let dir = id === "vb" ? "left" : "right";
let pos = "client" + (id === "vb" ? "X" : "Y");
em.style.position = "relative";
let start = e[pos];
let diff = 0;
function slidemove(e) {
e.preventDefault();
e.stopPropagation();
diff = e[pos] - start;
em.style[dir] = diff + "px";
}
function slidend(e) {
e.preventDefault();
e.stopPropagation();
em.style[dir] = null;
em.style.position = "static";
if (id === "vb") slidevb(diff);
else slidehb(diff);
document.body.onmousemove = null;
document.body.onmouseleave = document.body.onmouseup = null;
}
document.body.onmousemove = slidemove;
document.body.onmouseleave = document.body.onmouseup = slidend;
}
// ---------------------------------------------------------------------
// d=distance moved
function slidehb(d) {
let h, p, x;
if (panex === 0) h = getheight(view);
else h = getheight(splitpane) - topsize;
x = h + d;
p = x / (getheight(panes) - 2 * topsize - mbarsize);
vprop = Math.min(1, Math.max(0, p));
resizer();
}
// ---------------------------------------------------------------------
// d=distance moved
function slidevb(d) {
let x, w;
if (panex === 0) w = getwidth(main);
else w = getwidth(side);
x = w + d;
x = x / (getwidth(panes) - getwidth(vb) - 2);
hprop = Math.max(0, Math.min(1, x));
resizer();
}
// ---------------------------------------------------------------------
return r;
}();
var state = layout.state;
// ---------------------------------------------------------------------
function showedit(ifshow) {
layout.showedit(ifshow);
}
| 26.156489 | 78 | 0.446228 |
92c35e02e93f9456e2df76b78e8df83364e571d3 | 2,062 | js | JavaScript | keywordTool/pubfiles/src/code/urdupoint/129233/default.js | dsofowote/KW-Tool | d8d9a5a6f79c33732f0301b7c72ec21d1df4d750 | [
"MIT"
] | null | null | null | keywordTool/pubfiles/src/code/urdupoint/129233/default.js | dsofowote/KW-Tool | d8d9a5a6f79c33732f0301b7c72ec21d1df4d750 | [
"MIT"
] | null | null | null | keywordTool/pubfiles/src/code/urdupoint/129233/default.js | dsofowote/KW-Tool | d8d9a5a6f79c33732f0301b7c72ec21d1df4d750 | [
"MIT"
] | null | null | null | integration.meta = {
'sectionID' : '129233',
'siteName' : 'Urdu Point - Smartphone - (UK)',
'platform' : 'smartphone'
};
integration.testParams = {
'mobile_resolution' : [0]
};
integration.flaggedTests = [];
integration.channelHome = [];
integration.params = {
'mf_siteId' : '1066960',
'plr_FluidAnchor': true,
'plr_Fluid': true,
'plr_Responsive' : true,
'plr_ShowCloseButton' : true,
'plr_ContentType': 'PAGESKINEXPRESS',
'plr_UseFullVersion': true,
'plr_UseCreativeSettings': true,
'plr_HideElementsByID' : '',
'plr_HideElementsByClass' : '',
'plr_FastInit' : true
};
integration.on('adCallResult', function(e) {
if (e.data.hasSkin) {
var headHeight = $("header").height();
$("<div id='inskinanchor'></div>").insertBefore("#main_wrap");
integration.base.setCfg({
plr_AnchorParent : "#inskinanchor",
plr_PageHeightAdjustment : -headHeight
});
integration.custom.FrameSideRight = e.data.plr_FrameSideRight;
var wWidth = $(window).width();
cWidth = wWidth - integration.custom.FrameSideRight;
$('body').addClass('inskinLoaded');
var stylesCSS = '<style type="text/css">';
stylesCSS += '.inskinLoaded div#o-wrapper, .inskinLoaded #main_wrap{overflow: visible;}';
stylesCSS += '.inskinLoaded .at-share-dock.atss{width: calc(100% - ' + integration.custom.FrameSideRight + 'px) !important; right: auto !important; z-index: 9 !important;}';
stylesCSS += '.inskinLoaded #inskinanchor{margin-top: ' + headHeight + 'px !important;}';
stylesCSS += '.inskinLoaded .header{margin-top: 0px !important;}';
stylesCSS += '</style>';
$('head').append(stylesCSS);
}
});
integration.on("adServed", function(e) {
$(".ism-frame").parent().css({
"z-index" : "10"
});
});
integration.on('adClose', function(e) {
$('body').removeClass('inskinLoaded');
});
/* Passback Tag */
window.ISMPassback = function() {
return "<script src='https://www.googletagservices.com/tag/js/gpt.js'>\n googletag.pubads().definePassback('/1001388/JPX', [1, 1]).display();\n<\\script>";
};
| 30.776119 | 175 | 0.661009 |
92c3aef4035f7f0cd76bb3d48a60f9b87685befd | 2,568 | js | JavaScript | examples/animator/blimp.anc.js | benchmarko/CPCBasic | 4e4c433993b12dc8c4df2caea58b55737cd2aa5d | [
"MIT"
] | 12 | 2019-10-01T12:22:18.000Z | 2022-03-17T06:41:00.000Z | examples/animator/blimp.anc.js | benchmarko/CPCBasic | 4e4c433993b12dc8c4df2caea58b55737cd2aa5d | [
"MIT"
] | 1 | 2020-12-28T01:01:55.000Z | 2021-07-30T15:17:30.000Z | examples/animator/blimp.anc.js | benchmarko/CPCBasic | 4e4c433993b12dc8c4df2caea58b55737cd2aa5d | [
"MIT"
] | 1 | 2022-02-27T17:30:56.000Z | 2022-02-27T17:30:56.000Z | /* globals cpcBasic */
"use strict";
cpcBasic.addItem("", function () { /*
CPCBasic;B;16384;1837;0;base64,AEASQAUFF0XuAQVHGQAeRw8A1o3/AAAAAJL/CgAAAJz/HgAAALD/LQAAAM7/NwAAAOz/NwAAAAoANwAAACgAMgAAAEYAKAAAAFAAMgAAAFoANwAAAGkANwAAAHgANwAAAHgAAAAAAHgAyf8AAGkAyf8AAGkAAAAAAGQACgAAAFoAGQAAAGQA9v8AAFoA5/8AAEYA2P8AACgAzv8AAAoAyf8AAOz/yf8AAM7/yf8AALD/0/8AAJz/4v8AAJL/9v8AAFAAzv8AAFoAyf8AAJL/CAAFAJz/GQAPALD/KAAZAM7/MAAeAOz/MAAeAAoAMAAeACgALAAZAEYAIwAUAFoAFQAMAGQABwAFAGQA+f8FAFoA6/8MAEYA3f8UACgA1P8ZAAoA0P8eAOz/0P8eAM7/0P8eALD/2v8ZAJz/5/8PAJL/9v8FAJL/BQAIAJz/DwAZALD/FwAoAM7/HAAwAOz/HAAwAAoAHAAwACgAGQAqAEYAFAAjAFoADAAUAGQABQAIAGQA+/8IAFoA9P8UAEYA7P8jACgA5/8qAAoA5P8wAOz/5P8wAM7/5P8wALD/6f8oAJz/8f8ZAJL/+/8IAJL/AAD2/5z/AADi/7D/AADT/87/AADJ/+z/AADJ/woAAADJ/ygAAADO/0YAAADY/1oAAADn/2QAAAD2/2QAAAAKAFoAAAAZAEYAAAAoACgAAAAyAAoAAAA3AOz/AAA3AM7/AAA3ALD/AAAtAJz/AAAeAJL/AAAKAFAAAADO/1oAAADJ/2kAAADJ/3gAAADJ/3gAAAAAAHgAAAA3AGkAAAA3AFoAAAA3AFAAAAAyAJL/CAD7/5z/GQDx/7D/KADn/87/MADi/+z/MADi/woAMADi/ygALADn/0YAIwDs/1oAFQD0/2QABwD7/2QA+f/7/1oA6//0/0YA3f/s/ygA1P/n/woA0P/i/+z/0P/i/87/0P/i/7D/2v/n/5z/5//x/5L/9v/7/5L/BQD4/5z/DwDn/7D/GQDY/87/HADQ/+z/HADQ/woAHADQ/ygAGQDT/0YAFADd/1oADADs/2QABQD4/2QA+//4/1oA9P/s/0YA7P/d/ygA5//T/woA5P/Q/+z/5P/Q/87/5P/Q/7D/6f/Y/5z/8f/n/5L/+/8IAND/yf/x/9D/xv8AAND/yf8PANH/zP8NANP/xP8MANb/v/8LANr/tf8JANr/tf/3/9b/v//1/9P/xP/0/9H/zP/z/9H/zP/7/9H/zP8FANb/v/8FANb/v//7/xQAy/8PABQAyf8AABQAy//x/woAuv/7/woAuv8FABIAx/8NABIAx//z/yAAy/8rACAAyf8yACAAv/83ACAAt/8yACAAsv8rACAA1f8jACAAv/8eACAAyf8jACAAy/8rACAAyf/O/yAAv//J/yAAt//O/yAAsv/V/yAAt//d/yAAv//i/yAAyf/d/x4Av/8rACMAxP8tACMAv/8yACMAuv8tACMAuv8oACMAv/8jACMAxP8oAC0AxP8tAC0Av/8yAC0Auv8tAC0Auv8oAC0Av/8jAC0AxP8oADcAv/8rACMA2P8jADcA2P8jACMA0/8PADcA2P8PACMA2P/d/zcA2P/d/yMA0//x/zcA2P/x/x4Av/8rACMAxP/T/yMAv//O/yMAuv/T/yMAuv/Y/yMAv//d/yMAxP/Y/y0AxP/T/y0Av//O/y0Auv/T/y0Auv/Y/y0Av//d/y0AxP/Y/zcAv//V/zAUAAECAwQFBgcICQoLDA0ODxAREggCEAsFEA8eHRUkEBMUFRYXGBkaGxwAR0hJSktMTU5bXF1eX2BhYmNTUlEQUE9OBBBRUlMDYRBdM1NUVVZXWFlaACAhIiMkJSYnECkqKywtLi8wMTIAMzQ1Njc4OTo7PBA9Pj9AQUJDREVGACtkZWZnaGlqa2xtbm9wcXJzdHV2dwB4eXp7fH1+f4CBEIKDhIWGh4iJiosADQEfM1pGMhx3i0d4ZAENAiA0WUUxG3aKSHllAg0DITVYRDAadYlJemYDDQQiNldDLxl0iEp7ZwQNBSM3VkIuGHOHS3xoBQ0GJDhVQS0XcoZMfWkGDQclOVRALBZxhU1+agcNCCY6Uz8rFXCETn9rCA0SJztSPioUb4NPgGwSDREoPFE9KRNuglCBbRENjI2Oj5CRkpOUlZaMjQOWj6AClZAClJECl5oCmJkJjpugn56hnZybBJahnYwFkp+ek5IJoqOkpaanqKmiCaqrrK2ur7Cxqgiys7S1tre4swe5uru8vb65BLKzub8Et8LDvQSytbu/BLK2vL8Esre9vwSyuL6/BLjAwb4FxMnPxcQFxsrQx8YHycrLzM3OyQfP0NHS09TPBMjJz9UEyMrQ1QTIy9HVBMjM0tUEyM3T1QTIztTVBAAAAAAAAQADAAAAAQAFAAAAAQAHAAAAAQcAgAGAAoADgAKAAYAAgA==
*/ });
| 321 | 2,483 | 0.875 |
92c47a6e8597d76aa7171fa9dd2a5e0ae10397d1 | 1,108 | js | JavaScript | src/editor/actions/index.js | Amazus-DevOps/apib-editor | 70263a95a16e708b2277ab79ab60b42094ed0bbd | [
"MIT"
] | 13 | 2018-01-05T12:36:49.000Z | 2019-09-05T20:06:50.000Z | src/editor/actions/index.js | Amazus-DevOps/apib-editor | 70263a95a16e708b2277ab79ab60b42094ed0bbd | [
"MIT"
] | 10 | 2017-07-01T07:57:53.000Z | 2022-02-26T02:37:21.000Z | src/editor/actions/index.js | elfrog/apib-editor | 97ebabe6e329c010fe0c43d629dc4872de727d73 | [
"MIT"
] | null | null | null |
import closeProgram from './close-program';
import openNewDocument from './open-new-document';
import loadFromFile from './load-from-file';
import loadFromRepository from './load-from-repository';
import openFile from './open-file';
import openRemoteFile from './open-remote-file';
import saveFile from './save-file';
import saveAsFile from './save-as-file';
import filterNodeList from './filter-node-list';
import selectNode from './select-node';
import changeNodeProperty from './change-node-property';
import addChildNode from './add-child-node';
import removeChildNode from './remove-child-node';
import changeNodeIndex from './change-node-index';
import copyNode from './copy-node';
import pasteNode from './paste-node';
export let actions = [
closeProgram,
openNewDocument,
loadFromFile,
loadFromRepository,
openFile,
openRemoteFile,
saveFile,
saveAsFile,
filterNodeList,
selectNode,
changeNodeProperty,
addChildNode,
removeChildNode,
changeNodeIndex,
copyNode,
pasteNode
];
export let initialState = {
rootNode: null,
activeNodeId: null,
nodeListFilter: ''
};
| 25.767442 | 56 | 0.751805 |
92c4d892cffdfd6e5aaa27d7fad66f0493c12412 | 2,123 | js | JavaScript | houtai/public/js/common/header.js | LXRepository/nodejs-houtai | 9a9c75f1ac9100e601b2f486eeb039b2aecf5458 | [
"MIT"
] | null | null | null | houtai/public/js/common/header.js | LXRepository/nodejs-houtai | 9a9c75f1ac9100e601b2f486eeb039b2aecf5458 | [
"MIT"
] | null | null | null | houtai/public/js/common/header.js | LXRepository/nodejs-houtai | 9a9c75f1ac9100e601b2f486eeb039b2aecf5458 | [
"MIT"
] | null | null | null | function header() {
this.creatDom();
this.creatlogin();
this.creatreg();
this.checklogin();
this.addlistener();
}
header.template = `<nav class="navbar navbar-inverse"">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">职位管理系统</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="position-nav">
<ul class="nav navbar-nav">
<li class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">首页</a></li>
<li><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">职位管理</a></li>
<li><a id="link_to">职位管理</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li data-toggle="modal" data-target="#resmyModal"><a href="#">登录</a></li>
<li data-toggle="modal" data-target="#myModal"><a href="#">注册</a></li>
</ul>
<ul class="nav navbar-nav navbar-right hide login_success">
<li><a href="#">欢迎您..</a></li>
<li class="logout_link"><a href="#">退出</a></li>
</ul>
</div>
</div>
</nav>`;
$.extend(header.prototype,{
creatDom:function(){
$(header.template).appendTo(".header");
},
creatlogin:function(){
new loginmodel();
},
creatreg:function(){
new register();
},
addlistener:function(){
$(".logout_link").on("click",this.handlelogout);
},
handlelogout:function(){
$.get("/api/users/logout",function(){
location.reload();
})
},
checklogin:function(){
$.get("/api/users/check",function(data){
if (data.res_code === 0) {
$(".login_success").removeClass("hide").prev("ul").hide();
$(".login_success a:first").text("欢迎您:"+data.res_body.username);
}
},"json")
}
})
| 29.901408 | 147 | 0.618935 |
92c4e2be553ba85cf63c588eed49ae0b6589f35a | 13,787 | js | JavaScript | packages/elements/task-decision/dist/esm/api/TaskDecisionResource.js | rholang/archive-old | 55d05c67b2015b646e6f3aa7c4e1fde778162eea | [
"Apache-2.0"
] | 1 | 2020-04-24T13:28:17.000Z | 2020-04-24T13:28:17.000Z | packages/elements/task-decision/dist/esm/api/TaskDecisionResource.js | rholang/archive-old | 55d05c67b2015b646e6f3aa7c4e1fde778162eea | [
"Apache-2.0"
] | 1 | 2022-03-02T07:06:35.000Z | 2022-03-02T07:06:35.000Z | packages/elements/task-decision/dist/esm/api/TaskDecisionResource.js | rholang/archive-old | 55d05c67b2015b646e6f3aa7c4e1fde778162eea | [
"Apache-2.0"
] | null | null | null | import { __assign } from "tslib";
import uuid from 'uuid';
import { utils } from '@atlaskit/util-service-support';
import { convertServiceTaskToTask, convertServiceTaskStateToBaseItem, findIndex, } from './TaskDecisionUtils';
import { PubSubSpecialEventType, } from '../types';
import { objectKeyToString, toggleTaskState, toObjectKey, } from '../type-helpers';
export var ACTION_CREATED_FPS_EVENT = 'avi:task-decision-service:created:action';
export var ACTION_EDITED_FPS_EVENT = 'avi:task-decision-service:edited:action';
export var ACTION_DELETED_FPS_EVENT = 'avi:task-decision-service:deleted:action';
export var ACTION_ARCHIVED_FPS_EVENT = 'avi:task-decision-service:archived:action';
export var ACTION_STATE_CHANGED_FPS_EVENT = 'avi:task-decision-service:stateChanged:action';
export var DECISION_CREATED_FPS_EVENT = 'avi:task-decision-service:created:decision';
export var DECISION_EDITED_FPS_EVENT = 'avi:task-decision-service:edited:decision';
export var DECISION_DELETED_FPS_EVENT = 'avi:task-decision-service:deleted:decision';
export var DECISION_ARCHIVED_FPS_EVENT = 'avi:task-decision-service:archived:decision';
export var DECISION_STATE_CHANGED_FPS_EVENT = 'avi:task-decision-service:stateChanged:decision';
export var ACTION_DECISION_FPS_EVENTS = 'avi:task-decision-service:*:*';
var RecentUpdates = /** @class */ (function () {
function RecentUpdates(pubSubClient) {
var _this = this;
this.idsByContainer = new Map();
this.listenersById = new Map();
this.onPubSubEvent = function (_event, payload) {
var objectAri = payload.objectAri;
_this.notify({ objectAri: objectAri });
};
this.pubSubClient = pubSubClient;
this.subscribeToPubSubEvents();
}
RecentUpdates.prototype.subscribe = function (objectAri, recentUpdatesListener) {
var id = uuid();
var containerIds = this.idsByContainer.get(objectAri);
if (!containerIds) {
containerIds = [];
this.idsByContainer.set(objectAri, containerIds);
}
containerIds.push(id);
this.listenersById.set(id, {
listener: recentUpdatesListener,
objectAri: objectAri,
});
// Notify of id
recentUpdatesListener.id(id);
};
RecentUpdates.prototype.unsubscribe = function (unsubscribeId) {
var listenerDetail = this.listenersById.get(unsubscribeId);
if (listenerDetail) {
this.listenersById.delete(unsubscribeId);
var objectAri = listenerDetail.objectAri;
var idsToFilter = this.idsByContainer.get(objectAri);
if (idsToFilter) {
this.idsByContainer.set(objectAri, idsToFilter.filter(function (id) { return id !== unsubscribeId; }));
}
}
};
RecentUpdates.prototype.notify = function (recentUpdateContext) {
var _this = this;
var objectAri = recentUpdateContext.objectAri;
var subscriberIds = this.idsByContainer.get(objectAri);
if (subscriberIds) {
subscriberIds.forEach(function (subscriberId) {
var listenerDetail = _this.listenersById.get(subscriberId);
if (listenerDetail) {
var listener = listenerDetail.listener;
listener.recentUpdates(recentUpdateContext);
}
});
}
};
RecentUpdates.prototype.destroy = function () {
this.unsubscribeFromPubSubEvents();
};
RecentUpdates.prototype.subscribeToPubSubEvents = function () {
if (this.pubSubClient) {
this.pubSubClient.on(ACTION_DECISION_FPS_EVENTS, this.onPubSubEvent);
}
};
RecentUpdates.prototype.unsubscribeFromPubSubEvents = function () {
if (this.pubSubClient) {
this.pubSubClient.off(ACTION_DECISION_FPS_EVENTS, this.onPubSubEvent);
}
};
return RecentUpdates;
}());
export { RecentUpdates };
var ItemStateManager = /** @class */ (function () {
function ItemStateManager(serviceConfig) {
var _this = this;
this.debouncedTaskStateQuery = null;
this.debouncedTaskToggle = new Map();
this.subscribers = new Map();
this.trackedObjectKeys = new Map();
this.cachedItems = new Map();
this.batchedKeys = new Map();
this.onTaskUpdatedEvent = function (_event, payload) {
var objectAri = payload.objectAri, localId = payload.localId;
var objectKey = { objectAri: objectAri, localId: localId };
var cached = _this.getCached(objectKey);
if (!cached) {
// ignore unknown task
return;
}
var lastUpdateDate = new Date(payload.lastUpdateDate);
if (lastUpdateDate > cached.lastUpdateDate) {
_this.updateCache(convertServiceTaskStateToBaseItem(payload));
_this.notifyUpdated(objectKey, payload.state);
return;
}
};
this.onReconnect = function () {
_this.refreshAllTasks();
};
this.serviceConfig = serviceConfig;
this.subscribeToPubSubEvents();
}
ItemStateManager.prototype.destroy = function () {
if (this.debouncedTaskStateQuery) {
clearTimeout(this.debouncedTaskStateQuery);
}
this.debouncedTaskToggle.forEach(function (timeout) {
clearTimeout(timeout);
});
this.unsubscribeFromPubSubEvents();
};
ItemStateManager.prototype.toggleTask = function (objectKey, state) {
var _this = this;
var stringKey = objectKeyToString(objectKey);
var timeout = this.debouncedTaskToggle.get(stringKey);
if (timeout) {
clearTimeout(timeout);
this.debouncedTaskToggle.delete(stringKey);
}
// Update cache optimistically
this.updateCache(__assign(__assign({}, objectKey), { lastUpdateDate: new Date(), type: 'TASK', state: state }));
// Optimistically notify subscribers that the task have been updated so that they can re-render accordingly
this.notifyUpdated(objectKey, state);
return new Promise(function (resolve, reject) {
_this.debouncedTaskToggle.set(stringKey, window.setTimeout(function () {
var options = {
path: 'tasks/state',
requestInit: {
method: 'PUT',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify(__assign(__assign({}, objectKey), { state: state })),
},
};
utils
.requestService(_this.serviceConfig, options)
.then(convertServiceTaskToTask)
.then(function (task) {
_this.updateCache(task);
resolve(state);
// Notify subscribers that the task have been updated so that they can re-render accordingly
_this.notifyUpdated(objectKey, state);
})
.catch(function () {
// Undo optimistic change
var previousState = toggleTaskState(state);
_this.updateCache(__assign(__assign({}, objectKey), { lastUpdateDate: new Date(), type: 'TASK', state: previousState }));
_this.notifyUpdated(objectKey, previousState);
reject();
});
}, 500));
});
};
ItemStateManager.prototype.refreshAllTasks = function () {
this.queueAllItems();
this.scheduleGetTaskState();
};
ItemStateManager.prototype.subscribe = function (objectKey, handler, item) {
var key = objectKeyToString(objectKey);
var handlers = this.subscribers.get(key) || [];
handlers.push(handler);
this.subscribers.set(key, handlers);
this.trackedObjectKeys.set(key, objectKey);
var cached = this.getCached(objectKey);
if (cached) {
this.notifyUpdated(objectKey, cached.state);
return;
}
if (this.serviceConfig.disableServiceHydration && item) {
this.updateCache(item);
return;
}
this.queueItem(objectKey);
this.scheduleGetTaskState();
};
ItemStateManager.prototype.unsubscribe = function (objectKey, handler) {
var key = objectKeyToString(objectKey);
var handlers = this.subscribers.get(key);
if (!handlers) {
return;
}
var index = findIndex(handlers, function (h) { return h === handler; });
if (index !== -1) {
handlers.splice(index, 1);
}
if (handlers.length === 0) {
this.subscribers.delete(key);
this.trackedObjectKeys.delete(key);
}
else {
this.subscribers.set(key, handlers);
}
};
ItemStateManager.prototype.getTaskState = function (keys) {
var options = {
path: 'tasks/state',
requestInit: {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify({
taskKeys: keys,
}),
},
};
return utils.requestService(this.serviceConfig, options);
};
ItemStateManager.prototype.notifyUpdated = function (objectKey, state) {
var key = objectKeyToString(objectKey);
var handlers = this.subscribers.get(key);
if (!handlers) {
return;
}
handlers.forEach(function (handler) {
handler(state);
});
};
ItemStateManager.prototype.updateCache = function (item) {
var stringKey = objectKeyToString(toObjectKey(item));
this.cachedItems.set(stringKey, item);
};
ItemStateManager.prototype.getCached = function (objectKey) {
return this.cachedItems.get(objectKeyToString(objectKey));
};
ItemStateManager.prototype.subscribeToPubSubEvents = function () {
if (this.serviceConfig.pubSubClient) {
this.serviceConfig.pubSubClient.on(ACTION_STATE_CHANGED_FPS_EVENT, this.onTaskUpdatedEvent);
this.serviceConfig.pubSubClient.on(PubSubSpecialEventType.RECONNECT, this.onReconnect);
}
};
ItemStateManager.prototype.unsubscribeFromPubSubEvents = function () {
if (this.serviceConfig.pubSubClient) {
this.serviceConfig.pubSubClient.off(ACTION_STATE_CHANGED_FPS_EVENT, this.onTaskUpdatedEvent);
this.serviceConfig.pubSubClient.off(PubSubSpecialEventType.RECONNECT, this.onReconnect);
}
};
ItemStateManager.prototype.queueAllItems = function () {
this.batchedKeys = new Map(this.trackedObjectKeys);
};
ItemStateManager.prototype.queueItem = function (objectKey) {
var key = objectKeyToString(objectKey);
if (this.batchedKeys.get(key)) {
return;
}
this.batchedKeys.set(key, objectKey);
};
ItemStateManager.prototype.dequeueItem = function (objectKey) {
var key = objectKeyToString(objectKey);
this.batchedKeys.delete(key);
};
ItemStateManager.prototype.scheduleGetTaskState = function () {
var _this = this;
if (this.debouncedTaskStateQuery) {
clearTimeout(this.debouncedTaskStateQuery);
}
this.debouncedTaskStateQuery = window.setTimeout(function () {
_this.getTaskState(Array.from(_this.batchedKeys.values())).then(function (tasks) {
tasks.forEach(function (task) {
var objectAri = task.objectAri, localId = task.localId;
var objectKey = { objectAri: objectAri, localId: localId };
_this.updateCache(convertServiceTaskStateToBaseItem(task));
_this.dequeueItem(objectKey);
_this.notifyUpdated(objectKey, task.state);
});
});
}, 1);
};
return ItemStateManager;
}());
export { ItemStateManager };
var TaskDecisionResource = /** @class */ (function () {
function TaskDecisionResource(serviceConfig) {
this.recentUpdates = new RecentUpdates(serviceConfig.pubSubClient);
this.itemStateManager = new ItemStateManager(serviceConfig);
}
TaskDecisionResource.prototype.unsubscribeRecentUpdates = function (id) {
this.recentUpdates.unsubscribe(id);
};
TaskDecisionResource.prototype.notifyRecentUpdates = function (recentUpdateContext) {
this.recentUpdates.notify(recentUpdateContext);
this.itemStateManager.refreshAllTasks();
};
TaskDecisionResource.prototype.toggleTask = function (objectKey, state) {
return this.itemStateManager.toggleTask(objectKey, state);
};
TaskDecisionResource.prototype.subscribe = function (objectKey, handler, item) {
this.itemStateManager.subscribe(objectKey, handler, item);
};
TaskDecisionResource.prototype.unsubscribe = function (objectKey, handler) {
this.itemStateManager.unsubscribe(objectKey, handler);
};
/**
* Usually only needed for testing to ensure no outstanding requests
* are sent to a server (typically mocked).
*/
TaskDecisionResource.prototype.destroy = function () {
this.recentUpdates.destroy();
this.itemStateManager.destroy();
};
return TaskDecisionResource;
}());
export default TaskDecisionResource;
//# sourceMappingURL=TaskDecisionResource.js.map | 43.355346 | 141 | 0.621092 |
92c4fb6a75881508e84a25cd2295d455765ab75e | 1,163 | js | JavaScript | helpers/readme-helper.js | DistributedCollective/solidoc2 | c5931ddb2dec11c2b77b5dc56e1aaa6d42c5208c | [
"Apache-2.0"
] | 3 | 2021-06-30T11:19:03.000Z | 2022-03-11T12:06:24.000Z | helpers/readme-helper.js | DistributedCollective/solidoc2 | c5931ddb2dec11c2b77b5dc56e1aaa6d42c5208c | [
"Apache-2.0"
] | null | null | null | helpers/readme-helper.js | DistributedCollective/solidoc2 | c5931ddb2dec11c2b77b5dc56e1aaa6d42c5208c | [
"Apache-2.0"
] | 2 | 2021-08-14T20:26:23.000Z | 2022-01-21T01:05:22.000Z | const fs = require('fs')
const path = require('path')
const fixLinks = (config, contents) => {
const { pathToRoot, outputPath } = config
const toDocs = path.relative(pathToRoot, outputPath)
const toRoot = path.relative(outputPath, pathToRoot)
contents = contents.replace(/\[(.*?)\]\((.*md?)\)/gi, `[$1](${toDocs}/$2)`)
contents = contents.replace(/\[(.*?)\]\((.*sol?)\)/gi, (_x, y, z) => `[${y}](${z.replace(toRoot, '')})`)
return contents
}
const removePrevious = (contents) => {
return contents.replace(/\[comment\]: #solidoc \(Start\).*\[comment\]: #solidoc \(End\)/gms, '{{{doc}}}')
}
const insertRoot = (contents, replacable) => {
const toReplace = `[comment]: #solidoc (Start)\n${replacable}\n[comment]: #solidoc (End)`
return contents.replace(/{{{doc}}}/g, toReplace)
}
const set = (replacable, config) => {
const { readMe } = config
if (!fs.existsSync(readMe)) {
return
}
replacable = fixLinks(config, replacable)
let contents = fs.readFileSync(readMe).toString()
contents = removePrevious(contents)
contents = insertRoot(contents, replacable)
fs.writeFileSync(readMe, contents)
}
module.exports = { set }
| 28.365854 | 107 | 0.641445 |
92c570cdc4ad69dd25dc37d9df4a3ceb733ba4a1 | 1,706 | js | JavaScript | src/__tests__/unit-tests/Presentation/presentation.spec.js | burakkeser260/dnd-builder | e84b8da167e3b6ba99c03352cbc73d7f7af915e1 | [
"MIT"
] | 22 | 2021-04-12T14:04:48.000Z | 2022-03-11T15:25:53.000Z | src/__tests__/unit-tests/Presentation/presentation.spec.js | burakkeser260/dnd-builder | e84b8da167e3b6ba99c03352cbc73d7f7af915e1 | [
"MIT"
] | 1 | 2021-11-29T09:38:36.000Z | 2021-11-29T09:38:36.000Z | src/__tests__/unit-tests/Presentation/presentation.spec.js | burakkeser260/dnd-builder | e84b8da167e3b6ba99c03352cbc73d7f7af915e1 | [
"MIT"
] | 5 | 2021-10-01T14:58:50.000Z | 2022-01-06T13:10:30.000Z | import React from 'react';
import Presentation from '../../../components/Presentation/Presentation';
import { BuilderProvider } from '../../../utils/builderContext';
import { PropProvider } from '../../../utils/propContext';
import { PresentationProvider } from '../../../utils/presentationContext';
import PresentationWrapper from '../../../components/Presentation/PresentationWrapper';
import ReportWrapper from '../../../components/ReportWrapper';
import Print from '../../../components/Print';
describe('Presentation Component Tree', () => {
const presentation = shallow(<Presentation {...Presentation.defaultProps} />);
it('Should Always Render PresentationProvider in Presentation', () => {
expect(presentation.find(PresentationProvider)).toHaveLength(1);
});
it('Should Always Render PropProvider in Presentation', () => {
expect(presentation.find(PropProvider)).toHaveLength(1);
});
it('Should Always Render BuilderProvider in Presentation', () => {
expect(presentation.find(BuilderProvider)).toHaveLength(1);
});
it('Should Always Render ReportWrapper in Presentation', () => {
expect(presentation.find(ReportWrapper)).toHaveLength(1);
});
it('Should Always Render PresentationWrapper in Presentation', () => {
expect(presentation.find(PresentationWrapper)).toHaveLength(1);
});
it('Should Always Render Print in Presentation', () => {
expect(presentation.find(Print)).toHaveLength(1);
});
it('ReportWrapper contains PresentationWrapper and Print', () => {
expect(presentation.find(PresentationWrapper).parent().is(ReportWrapper)).toEqual(true);
expect(presentation.find(Print).parent().is(ReportWrapper)).toEqual(true);
});
});
| 42.65 | 92 | 0.712192 |
92c5eb00fb4e8d61759ebfbae41c3f89927cf653 | 1,119 | js | JavaScript | JS-Applications/cookbook/lesson-02/src/login.js | DeanDupalov/JS-Advanced | 6768db6e08501aced3c6a1b8bf7ae3c2a292b7fa | [
"MIT"
] | null | null | null | JS-Applications/cookbook/lesson-02/src/login.js | DeanDupalov/JS-Advanced | 6768db6e08501aced3c6a1b8bf7ae3c2a292b7fa | [
"MIT"
] | null | null | null | JS-Applications/cookbook/lesson-02/src/login.js | DeanDupalov/JS-Advanced | 6768db6e08501aced3c6a1b8bf7ae3c2a292b7fa | [
"MIT"
] | null | null | null | window.addEventListener('load', async () => {
const form = document.querySelector('form');
form.addEventListener('submit', onLogin)
});
async function onLogin(e) {
const url = 'http://localhost:3030/users/login'
e.preventDefault();
const form = e.target;
const formData = new FormData(form);
const email = formData.get('email').trim();
const password = formData.get('password').trim();
try {
const options = {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email,
password
})
}
const response = await fetch(url, options)
if (response.ok !== true){
const error = await response.json();
throw new Error(error.message)
}
const data = await response.json();
const token = data.accessToken;
localStorage.setItem('token', token);
window.location = '/cookbook/lesson-02/index.html'
}catch (error) {
alert(error.message)
}
} | 27.975 | 58 | 0.548704 |
92c63b106b14f548d5da5602152227e7dfee8452 | 1,330 | js | JavaScript | modules/page_context.js | ngeojiajun/blog-nodejs-pub | d6c6d71f2e7f04f65a74da9ed410de1cb221d179 | [
"BSD-3-Clause"
] | null | null | null | modules/page_context.js | ngeojiajun/blog-nodejs-pub | d6c6d71f2e7f04f65a74da9ed410de1cb221d179 | [
"BSD-3-Clause"
] | null | null | null | modules/page_context.js | ngeojiajun/blog-nodejs-pub | d6c6d71f2e7f04f65a74da9ed410de1cb221d179 | [
"BSD-3-Clause"
] | null | null | null | const loader=require("./loader.js");
function expandTag(tags){
let list=Object.keys(tags);
return list.filter(x=>x!=="class").map(x=>`${x}:${tags[x]}`).join(";");
}
function generateUrl(post){
let manifest=loader.getManifest(post);
let base=manifest.properties["base"]||"/";
let name=manifest.properties["url"]||post;
return `${base}/${name}`.replace(/\/\//g,"/")
}
function getTitle(post){
let manifest=loader.getManifest(post);
return manifest.properties["nav-title"]||manifest.title;
}
function inPage(target,page,base){
if(loader.isMetaPage(target)){
return (base!==""?base:page)===loader.getManifest(target).properties["base"];
}
else{
let url=generateUrl(target);
return url===(`${base||"/"}/${page}`.replace(/\/\//g,"/"));
}
}
function getTagLink(x){
let link=loader.getMetaTagUrl(x);
if(link)return link;
return `/tags/${encodeURIComponent(x)}/`
}
function getPage(type){
return {
type:type,
expandTag:expandTag,
generateUrl:generateUrl,
getTitle:getTitle,
inPage:inPage,
pinned:loader.getPages(),
getManifest:loader.getManifest,
getMetaTagUrl:loader.getMetaTagUrl,
isMeta:loader.isMetaLink,
getTagLink:getTagLink
}
}
module.exports = {
getPage:getPage,
generateUrl:generateUrl
};
| 27.708333 | 82 | 0.64812 |
92c6979a1e3f8662bdc57c33e06eec561c2c5a23 | 4,448 | js | JavaScript | webpack/extra-webpack.config.js | lhncbc/fhir-obs-viewer | 911f80205f8aa349fac30b0f95b8c7cc910f08c6 | [
"Apache-2.0"
] | 5 | 2021-07-05T14:07:52.000Z | 2022-03-03T21:05:09.000Z | webpack/extra-webpack.config.js | lhncbc/fhir-obs-viewer | 911f80205f8aa349fac30b0f95b8c7cc910f08c6 | [
"Apache-2.0"
] | 4 | 2020-04-01T22:45:14.000Z | 2020-12-14T16:09:01.000Z | webpack/extra-webpack.config.js | lhncbc/fhir-obs-viewer | 911f80205f8aa349fac30b0f95b8c7cc910f08c6 | [
"Apache-2.0"
] | 3 | 2020-08-06T14:40:52.000Z | 2021-08-09T17:30:49.000Z | const path = require('path');
const fs = require('fs');
const readXlsxFile = require('read-excel-file/node');
const JSON5 = require('json5');
const json5Writer = require('json5-writer');
const xlsxFolder = './src/conf/xlsx';
const csvFolder = './src/conf/csv';
const settingsPath = './src/assets/settings.json5';
const definitionsFilePropName = 'definitionsFile';
/**
* Converts array of cell values to CSV row
* @param {Array} row
* @return {string}
*/
function createCsvRow(row) {
return row
.map((cell) => {
if (/["\s,]/.test(cell)) {
return '"' + cell.replace(/"/g, '""') + '"';
} else {
return cell;
}
})
.join(',');
}
/**
* Returns an object which maps service base URLs to CSV data extracted from XLSX files.
* @returns {Promise<Object>}
*/
async function prepareCsvData() {
// Cell value to mark the beginning of data
const marker = '---SERVICE BASE URL:';
// Index offset of the row from which the data starts relative to the row with URL
const dataOffset = 3;
// Read all XLSX files in the folder
const fileNames = fs.readdirSync(xlsxFolder);
const url2desc = {};
for (let i = 0; i < fileNames.length; i++) {
if (/(.*)\.xlsx$/.test(fileNames[i])) {
const filename = RegExp.$1;
const fromFilename = filename + '.xlsx';
const sheets = await readXlsxFile(xlsxFolder + '/' + fromFilename, {
getSheets: true
});
for (let j = 1; j <= sheets.length; j++) {
const rows = await readXlsxFile(xlsxFolder + '/' + fromFilename, {
sheet: j
});
const urlIndex = rows.findIndex((row) => row[0] === marker);
const urls = rows[urlIndex][1].split(',');
const desc = rows.slice(urlIndex + dataOffset).filter(
([, , type, , hideShow, , ,]) =>
// Skip hidden search parameters
type !== 'search parameter' || hideShow !== 'hide'
);
urls.forEach((url) => {
url2desc[url] = (url2desc[url] || []).concat(desc);
});
}
}
}
return url2desc;
}
/**
* Updates settings.json5 and creates CSV-files.
* @param {Object} url2desc - object which maps service base URLs to CSV
* data extracted from XLSX files.
*/
function updateAppSettings(url2desc) {
const allUrls = Object.keys(url2desc);
const updateSettingsObj = { default: {}, customization: {} };
const settingsJsonString = fs.readFileSync(settingsPath).toString();
const settings = JSON5.parse(settingsJsonString);
for (let i = 0; i < allUrls.length; i++) {
const url = allUrls[i];
const toFilename = 'desc-' + i + '.csv';
if (url === 'default') {
updateSettingsObj.default[definitionsFilePropName] = toFilename;
} else {
updateSettingsObj.customization[url] = {
[definitionsFilePropName]: toFilename
};
}
fs.writeFileSync(
csvFolder + '/' + toFilename,
url2desc[url].map((row) => createCsvRow(row)).join('\n')
);
}
// json5-writer will remove any property that does not exist in updateSettingsObj.
// To keep an existing properties, we need to pass undefined.
Object.keys(settings.default).forEach((key) => {
if (key !== definitionsFilePropName) {
updateSettingsObj.default[key] = undefined;
}
});
Object.keys(settings.customization).forEach((url) => {
if (!updateSettingsObj.customization[url]) {
updateSettingsObj.customization[url] = {};
}
Object.keys(settings.customization[url]).forEach((key) => {
if (key !== definitionsFilePropName) {
updateSettingsObj.customization[url][key] = undefined;
}
});
});
const settingsWriter = json5Writer.load(settingsJsonString);
settingsWriter.write(updateSettingsObj);
fs.writeFileSync(settingsPath, settingsWriter.toSource());
}
module.exports = async (config) => {
updateAppSettings(await prepareCsvData());
config.module.rules.push(
{
test: /definitions\/index.json$/,
use: [
{
loader: path.resolve(
'prev/source/js/search-parameters/definitions/webpack-loader.js'
),
options: require(path.resolve(
'prev/source/js/search-parameters/definitions/webpack-options.json'
))
}
]
},
{
test: /package.json$/,
use: [
{
loader: path.resolve('webpack/package-json-loader.js')
}
]
}
);
return config;
};
| 29.653333 | 88 | 0.610162 |
92c70a1c4817b3f5130e6e9be93fa68a15bdcbbc | 2,803 | js | JavaScript | src/vcontroller/controller.js | whatGUI/VGpad-server | 1d1d61f9541d88d3ffb4fd7ef401c69d787cdf31 | [
"MIT"
] | null | null | null | src/vcontroller/controller.js | whatGUI/VGpad-server | 1d1d61f9541d88d3ffb4fd7ef401c69d787cdf31 | [
"MIT"
] | null | null | null | src/vcontroller/controller.js | whatGUI/VGpad-server | 1d1d61f9541d88d3ffb4fd7ef401c69d787cdf31 | [
"MIT"
] | null | null | null | //
// 定义所有按钮及摇杆的功能和虚拟控制器的操作交互
// Define all buttons and axes functions
//
module.exports = class VGamepad {
constructor(controller) {
this.controller = controller;
}
getInfo() {
console.log("Index:", this.controller.index);
console.log("User index:", this.controller.userIndex);
}
disconnect() {
this.controller.disconnect();
}
// buttons
START(value) {
this.controller.button.START.setValue(value);
}
BACK(value) {
this.controller.button.BACK.setValue(value);
}
LEFT_SHOULDER(value) {
this.controller.button.LEFT_SHOULDER.setValue(value);
}
RIGHT_SHOULDER(value) {
this.controller.button.RIGHT_SHOULDER.setValue(value);
}
LEFT_THUMB(value){
this.controller.button.LEFT_THUMB.setValue(value);
}
RIGHT_THUMB(value){
this.controller.button.RIGHT_THUMB.setValue(value);
}
A(value) {
this.controller.button.A.setValue(value);
}
B(value) {
this.controller.button.B.setValue(value);
}
X(value) {
this.controller.button.X.setValue(value);
}
Y(value) {
this.controller.button.Y.setValue(value);
}
// special buttons
LEFT_TRIGGER(value) {
if (value === true) {
this.controller.axis.leftTrigger.setValue(1);
} else {
this.controller.axis.leftTrigger.setValue(0);
}
}
RIGHT_TRIGGER(value) {
if (value === true) {
this.controller.axis.rightTrigger.setValue(1);
} else {
this.controller.axis.rightTrigger.setValue(0);
}
}
DPAD_DOWN(value) {
if (value === true) {
this.controller.axis.dpadHorz.setValue(0);
this.controller.axis.dpadVert.setValue(-1);
} else {
this.controller.axis.dpadHorz.setValue(0);
this.controller.axis.dpadVert.setValue(0);
}
}
DPAD_RIGHT(value) {
if (value === true) {
this.controller.axis.dpadHorz.setValue(1);
this.controller.axis.dpadVert.setValue(0);
} else {
this.controller.axis.dpadHorz.setValue(0);
this.controller.axis.dpadVert.setValue(0);
}
}
DPAD_UP(value) {
if (value === true) {
this.controller.axis.dpadHorz.setValue(0);
this.controller.axis.dpadVert.setValue(1);
} else {
this.controller.axis.dpadHorz.setValue(0);
this.controller.axis.dpadVert.setValue(0);
}
}
DPAD_LEFT(value) {
if (value === true) {
this.controller.axis.dpadHorz.setValue(-1);
this.controller.axis.dpadVert.setValue(0);
} else {
this.controller.axis.dpadHorz.setValue(0);
this.controller.axis.dpadVert.setValue(0);
}
}
// axis
LEFT_AXIS(x, y) {
this.controller.axis.leftX.setValue(x);
this.controller.axis.leftY.setValue(y);
}
RIGHT_AXIS(x, y) {
this.controller.axis.rightX.setValue(x);
this.controller.axis.rightY.setValue(y);
}
};
| 21.728682 | 58 | 0.648234 |
92c7356ce19031857db5be10181dd7f987703c4d | 21,869 | js | JavaScript | node_modules/@zippytech/react-toolkit/Accordion/src/AccordionTabTitle.js | lauriefacer/Facer | ff9f5ca4af302926fed49a4b9b442ff00ea212be | [
"MIT"
] | null | null | null | node_modules/@zippytech/react-toolkit/Accordion/src/AccordionTabTitle.js | lauriefacer/Facer | ff9f5ca4af302926fed49a4b9b442ff00ea212be | [
"MIT"
] | null | null | null | node_modules/@zippytech/react-toolkit/Accordion/src/AccordionTabTitle.js | lauriefacer/Facer | ff9f5ca4af302926fed49a4b9b442ff00ea212be | [
"MIT"
] | null | null | null | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CLASS_NAME = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _autoBind = require('@zippytech/react-class/autoBind');
var _autoBind2 = _interopRequireDefault(_autoBind);
var _NotifyResize = require('../../NotifyResize');
var _shouldComponentUpdate2 = require('./shouldComponentUpdate');
var _shouldComponentUpdate3 = _interopRequireDefault(_shouldComponentUpdate2);
var _join = require('./join');
var _join2 = _interopRequireDefault(_join);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) 2015-present, Zippy Technologies
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var CLASS_NAME = exports.CLASS_NAME = 'zippy-react-toolkit-accordion__tab-title';
function defaultRenderExpandTool(params) {
var EXPAND_TOOL_SIZE = 20;
var className = params.rootClassName || CLASS_NAME;
var style = {
width: EXPAND_TOOL_SIZE,
height: EXPAND_TOOL_SIZE,
transition: params.transition ? 'all ' + params.transitionDuration + 'ms ' + params.transitionFunction : '',
transform: params.expanded ? 'rotate(180deg)' : 'rotate(0deg)'
};
return _react2.default.createElement(
'div',
{
style: style,
className: (0, _join2.default)(className + '__expand-tool', params.disabled && className + '__expand-tool--disabled')
},
_react2.default.createElement(
'svg',
{
height: EXPAND_TOOL_SIZE,
viewBox: '0 0 24 24',
width: EXPAND_TOOL_SIZE
},
_react2.default.createElement('path', { d: 'M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z' }),
_react2.default.createElement('path', { d: 'M0 0h24v24H0z', fill: 'none' })
)
);
}
var ZippyAccordionTabTitle = function (_Component) {
_inherits(ZippyAccordionTabTitle, _Component);
function ZippyAccordionTabTitle(props) {
_classCallCheck(this, ZippyAccordionTabTitle);
var _this = _possibleConstructorReturn(this, (ZippyAccordionTabTitle.__proto__ || Object.getPrototypeOf(ZippyAccordionTabTitle)).call(this, props));
(0, _autoBind2.default)(_this);
_this.state = {
expanded: _this.props.expanded,
focused: _this.props.expanded,
heightOfContent: null,
heightOfContainer: null
};
return _this;
}
_createClass(ZippyAccordionTabTitle, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
return (0, _shouldComponentUpdate3.default)(this, nextProps, nextState);
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this.computeRotatedAccordionTitleDimmensions();
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
this.computeRotatedAccordionTitleDimmensions(this.props, this.onResize);
}
// if text overflow ellipsis happens, we must add a title attribute on the
// title. This requires that the DOM be present
// http://stackoverflow.com/questions/7738117/html-text-overflow-ellipsis-detection#answer-10017343
}, {
key: 'applyTooltipIfNeeded',
value: function applyTooltipIfNeeded() {
if (typeof window !== 'undefined') {
var tabTitleText = this.refs.tabTitleText;
this.setState({
tabTitleTooltip: tabTitleText.offsetWidth < tabTitleText.scrollWidth
});
}
}
}, {
key: 'isLocked',
value: function isLocked() {
return this.props.locked;
}
}, {
key: 'isDisabled',
value: function isDisabled() {
return this.props.disabled;
}
}, {
key: 'isActionable',
value: function isActionable() {
return !(this.isLocked() || this.isDisabled());
}
}, {
key: '_mapAlignPropToProperValue',
value: function _mapAlignPropToProperValue(tabTitleAlign) {
switch (tabTitleAlign) {
case 'left':
case 'top':
return 'start';
case 'right':
case 'bottom':
return 'end';
default:
return tabTitleAlign;
}
}
}, {
key: 'onResize',
value: function onResize() {
this.computeRotatedAccordionTitleDimmensions(this.props);
this.applyTooltipIfNeeded();
}
}, {
key: 'getComputedStylesForRotatedTitle',
value: function getComputedStylesForRotatedTitle() {
var _props = this.props,
orientation = _props.orientation,
tabTitleRotate = _props.tabTitleRotate,
rtl = _props.rtl;
var _state = this.state,
heightOfContainer = _state.heightOfContainer,
heightOfContent = _state.heightOfContent;
if (heightOfContainer != null && heightOfContent != null) {
var computedTransform = void 0;
if (orientation === 'horizontal') {
if (tabTitleRotate === -90) {
if (rtl) {
computedTransform = 'rotate(-90deg) translate(' + heightOfContent + 'px)';
} else {
computedTransform = 'rotate(-90deg) translate(' + heightOfContent + 'px, -' + (heightOfContainer - heightOfContent) + 'px)';
}
return {
transform: computedTransform,
transformOrigin: '100% 100%'
};
}
if (rtl) {
computedTransform = 'rotate(90deg) translate(0, -' + heightOfContainer + 'px';
} else {
computedTransform = 'rotate(90deg) translate(0, -' + heightOfContent + 'px)';
}
return {
transform: computedTransform,
transformOrigin: '0% 0%'
};
}
}
}
}, {
key: 'renderTabTitle',
value: function renderTabTitle(tabDOMProps, tabProps) {
return _react2.default.createElement('div', tabDOMProps);
}
}, {
key: 'renderExpandTool',
value: function renderExpandTool(params) {
var expandTool = this.props.expandTool;
var typeofExpandTool = typeof expandTool === 'undefined' ? 'undefined' : _typeof(expandTool);
if (typeofExpandTool === 'function') {
return expandTool(params);
}
return expandTool;
}
}, {
key: 'getClassNames',
value: function getClassNames() {
var _props2 = this.props,
className = _props2.className,
locked = _props2.locked,
expanded = _props2.expanded,
nextAfterExpanded = _props2.nextAfterExpanded,
disabled = _props2.disabled,
focused = _props2.focused,
firstTab = _props2.firstTab,
lastTab = _props2.lastTab,
expandOnToolOnly = _props2.expandOnToolOnly,
tabTitleEllipsis = _props2.tabTitleEllipsis,
tabTitleAlign = _props2.tabTitleAlign,
tabTitleVerticalAlign = _props2.tabTitleVerticalAlign,
orientation = _props2.orientation,
rootClassName = _props2.rootClassName,
rtl = _props2.rtl,
tabTitleRotate = _props2.tabTitleRotate;
return (0, _join2.default)(className, rootClassName, rootClassName + '--' + orientation, rootClassName + '--align-' + this._mapAlignPropToProperValue(tabTitleAlign), rootClassName + '--vertical-align-' + tabTitleVerticalAlign, tabTitleEllipsis && rootClassName + '--ellipsis', locked && rootClassName + '--locked', rtl ? rootClassName + '--rtl' : rootClassName + '--ltr', expanded && rootClassName + '--expanded', !expanded && rootClassName + '--collapsed', firstTab && rootClassName + '--first-tab-collapsed', expanded && !firstTab && rootClassName + '--multi-expand', nextAfterExpanded && rootClassName + '--next-after-expanded', focused && rootClassName + '--focused', disabled && rootClassName + '--disabled', firstTab && rootClassName + '--firstTab', lastTab && rootClassName + '--lastTab', expandOnToolOnly && rootClassName + '--expand-on-tooltip-only', orientation === 'horizontal' && tabTitleRotate === 90 ? (0, _join2.default)(firstTab && rootClassName + '--rotated-first-tab', lastTab && expanded && rootClassName + '--expanded-rotated-last-tab', lastTab && !expanded && rootClassName + '--collapsed-rotated-last-tab', expanded && rootClassName + '--expanded-rotated', nextAfterExpanded && rootClassName + '--next-after-expanded-rotated') : '');
}
}, {
key: 'computeRotatedAccordionTitleDimmensions',
value: function computeRotatedAccordionTitleDimmensions(props, cb) {
var _this2 = this;
var _ref = props || this.props,
orientation = _ref.orientation;
if (orientation === 'vertical') {
if (this.state.heightOfContainer != null || this.state.heightOfContent != null) {
this.setState({
heightOfContainer: null,
heightOfContent: null
});
}
} else {
var heightOfContainer = this.refs.tabTitleContainer.offsetHeight;
var heightOfContent = this.refs.tabWrapper.offsetHeight;
var setHeightOfContent = function setHeightOfContent() {
if (_this2.state.heightOfContent != heightOfContent) {
_this2.setState({
heightOfContent: heightOfContent
}, function () {
cb && cb();
});
} else {
cb && cb();
}
};
if (this.state.heightOfContainer != heightOfContainer) {
this.setState({
heightOfContainer: heightOfContainer
}, setHeightOfContent);
} else {
setHeightOfContent();
}
}
}
}, {
key: 'getRenderTabTitleProps',
value: function getRenderTabTitleProps() {
var _props3 = this.props,
expanded = _props3.expanded,
index = _props3.index,
activeTabs = _props3.activeTabs,
disabled = _props3.disabled,
multiExpand = _props3.multiExpand,
collapsible = _props3.collapsible,
focused = _props3.focused,
rootClassName = _props3.rootClassName,
transition = _props3.transition,
transitionDuration = _props3.transitionDuration,
transitionFunction = _props3.transitionFunction;
var activeIndex = multiExpand ? activeTabs : activeTabs[0];
var transitionProps = { transition: transition };
if (transition) {
transitionProps = {
transition: transition,
transitionDuration: transitionDuration,
transitionFunction: transitionFunction
};
}
return _extends({
expanded: expanded,
index: index,
activeIndex: activeIndex,
disabled: disabled,
multiExpand: multiExpand,
collapsible: collapsible,
focused: focused,
rootClassName: rootClassName
}, transitionProps);
}
}, {
key: 'getRenderTabTitleDOMProps',
value: function getRenderTabTitleDOMProps() {
var _props4 = this.props,
tabTitle = _props4.tabTitle,
expandToolPosition = _props4.expandToolPosition,
rtl = _props4.rtl,
showTooltip = _props4.showTooltip;
var rootClassName = this.props.rootClassName;
var tabTitleTooltip = this.state.tabTitleTooltip;
var typeOfTabTitle = typeof tabTitle === 'undefined' ? 'undefined' : _typeof(tabTitle);
if (typeOfTabTitle === 'function') {
tabTitle = tabTitle(this.getRenderTabTitleProps());
}
var className = void 0;
if (expandToolPosition === 'end') {
if (rtl === false) {
className = rootClassName + '__content-end';
} else {
className = rootClassName + '__content-start';
}
}
if (expandToolPosition === 'start') {
if (rtl === false) {
className = rootClassName + '__content-start';
} else {
className = rootClassName + '__content-end';
}
}
var domProps = {
className: (0, _join2.default)(rootClassName + '__content', className),
children: _react2.default.createElement(
'div',
{ className: rootClassName + '-label' },
tabTitle
),
ref: 'tabTitleText'
};
if (typeOfTabTitle === 'string' && showTooltip) {
domProps['data-tooltip'] = tabTitle;
}
return domProps;
}
}, {
key: 'renderRotatedLayout',
value: function renderRotatedLayout() {
var _props5 = this.props,
orientation = _props5.orientation,
rootClassName = _props5.rootClassName;
var _state2 = this.state,
heightOfContent = _state2.heightOfContent,
heightOfContainer = _state2.heightOfContainer;
return _react2.default.createElement(
'div',
{
ref: 'tabTitleContainer',
className: rootClassName + '__wrapper',
style: { width: heightOfContent }
},
_react2.default.createElement(
'div',
{
className: rootClassName + '__content-wrapper',
style: { width: heightOfContainer }
},
_react2.default.createElement(
'div',
{ style: this.getComputedStylesForRotatedTitle() },
this.renderTabTitleAndTool()
)
)
);
}
}, {
key: 'renderNormalLayout',
value: function renderNormalLayout() {
var _props6 = this.props,
orientation = _props6.orientation,
rootClassName = _props6.rootClassName;
return _react2.default.createElement(
'div',
{ ref: 'tabTitleContainer', className: rootClassName + '__wrapper' },
_react2.default.createElement(
'div',
{ className: rootClassName + '__content-wrapper' },
this.renderTabTitleAndTool()
)
);
}
}, {
key: 'renderTabTitleAndTool',
value: function renderTabTitleAndTool() {
var _props7 = this.props,
locked = _props7.locked,
expandOnToolOnly = _props7.expandOnToolOnly,
activateEvent = _props7.activateEvent,
onToggle = _props7.onToggle,
tabTitleStyle = _props7.tabTitleStyle,
rootClassName = _props7.rootClassName,
customRenderTabTitle = _props7.renderTabTitle;
var containerDOMProps = {
className: this.getClassNames(),
ref: 'tabWrapper',
style: tabTitleStyle
};
var tooltipDOMProps = {
className: rootClassName + '__expand-tool-wrapper'
};
if (!locked) {
if (expandOnToolOnly) {
tooltipDOMProps[activateEvent] = onToggle;
} else {
containerDOMProps[activateEvent] = onToggle;
}
}
var subComponentProps = this.getRenderTabTitleProps();
var expandToolContent = this.renderExpandTool(subComponentProps);
var renderTabTitle = customRenderTabTitle ? customRenderTabTitle : this.renderTabTitle;
return _react2.default.createElement(
'div',
containerDOMProps,
_react2.default.createElement(_NotifyResize.NotifyResize, { rafOnResize: true, onResize: this.onResize }),
renderTabTitle(this.getRenderTabTitleDOMProps(), subComponentProps),
expandToolContent && _react2.default.createElement(
'div',
tooltipDOMProps,
expandToolContent
)
);
}
}, {
key: 'render',
value: function render() {
var orientation = this.props.orientation;
if (orientation === 'horizontal') {
return this.renderRotatedLayout();
}
return this.renderNormalLayout();
}
}]);
return ZippyAccordionTabTitle;
}(_react.Component);
ZippyAccordionTabTitle.defaultProps = {
expanded: false,
disabled: false,
tabTitleEllipsis: true,
activateEvent: 'onClick',
tabTitleAlign: 'start',
expandTool: defaultRenderExpandTool,
expandToolPosition: 'end',
orientation: 'vertical',
tabTitleRotate: -90,
rtl: false,
rootClassName: CLASS_NAME,
locked: null,
activeTabs: []
};
ZippyAccordionTabTitle.propTypes = {
shouldComponentUpdate: _propTypes2.default.func,
expanded: _propTypes2.default.bool,
nextAfterExpanded: _propTypes2.default.bool,
focused: _propTypes2.default.bool,
locked: _propTypes2.default.bool,
rtl: _propTypes2.default.bool,
activeTabs: _propTypes2.default.array,
tabTitle: _propTypes2.default.any,
tabTitleStyle: _propTypes2.default.object,
tabTitleAlign: _propTypes2.default.oneOf(['start', 'end', 'center', 'top', 'left', 'right', 'bottom']),
tabTitleVerticalAlign: _propTypes2.default.oneOf(['middle', 'top', 'bottom']),
tabTitleEllipsis: _propTypes2.default.bool,
tabTitleRotate: _propTypes2.default.oneOf([90, -90]),
renderTabTitle: _propTypes2.default.func,
rootClassName: _propTypes2.default.string,
activateEvent: _propTypes2.default.oneOf(['onClick', 'onMouseDown', 'onMouseEnter']),
expandTool: _propTypes2.default.oneOfType([_propTypes2.default.func, _propTypes2.default.object, _propTypes2.default.string]),
expandOnToolOnly: _propTypes2.default.bool,
expandToolPosition: _propTypes2.default.oneOf(['start', 'end']),
orientation: _propTypes2.default.oneOf(['vertical', 'horizontal'])
};
exports.default = ZippyAccordionTabTitle; | 40.800373 | 1,261 | 0.572866 |
92c77e34d7057d5a71bc00faae2666c74d5ade7d | 172 | js | JavaScript | storybook-static/main.404c77bad7c424dcb26d.bundle.js | tech-wizards/monorepo | e412e7e7ba7de38792376802b543228464fb2b0c | [
"MIT"
] | null | null | null | storybook-static/main.404c77bad7c424dcb26d.bundle.js | tech-wizards/monorepo | e412e7e7ba7de38792376802b543228464fb2b0c | [
"MIT"
] | null | null | null | storybook-static/main.404c77bad7c424dcb26d.bundle.js | tech-wizards/monorepo | e412e7e7ba7de38792376802b543228464fb2b0c | [
"MIT"
] | null | null | null | (window.webpackJsonp=window.webpackJsonp||[]).push([[0],{352:function(n,o,p){p(353),p(434),n.exports=p(720)},434:function(n,o,p){"use strict";p.r(o);p(435)}},[[352,1,2]]]); | 172 | 172 | 0.639535 |
92c85471a27fe162043367ee6912426cf2db32fa | 1,000 | js | JavaScript | migrations/20170703201056-clean-domain-demoDomain.js | StarLord07/federalist | 69b91b869018400d63e1bfe86608796988edbfcc | [
"CC0-1.0"
] | 372 | 2015-05-28T21:31:56.000Z | 2022-03-07T18:09:05.000Z | migrations/20170703201056-clean-domain-demoDomain.js | StarLord07/federalist | 69b91b869018400d63e1bfe86608796988edbfcc | [
"CC0-1.0"
] | 2,655 | 2015-05-30T16:04:09.000Z | 2022-03-30T21:55:47.000Z | migrations/20170703201056-clean-domain-demoDomain.js | isabella232/federalist | 609ed20f89b0c498863cb66297ce41ba20cfd0f1 | [
"CC0-1.0"
] | 102 | 2015-06-05T11:07:53.000Z | 2022-03-17T17:53:34.000Z |
// if field value starts with 'http://',
// then replace 'http://' with 'https://'
const httpToHttps = field => (`UPDATE site SET "${field}" = replace("${field}", 'http://', 'https://') `
+ `WHERE "${field}" like 'http://%'`);
// if field value is not empty or null and doesn't start with 'https://',
// then prepend with 'https://'
const prependHttps = field => (`UPDATE site SET "${field}" = 'https://' || "${field}" `
+ `WHERE "${field}" <> '' AND `
+ `"${field}" NOT LIKE 'https://%'`);
exports.up = function up(db) {
return db
.runSql(httpToHttps('domain'))
.then(() => {
db.runSql(prependHttps('domain'));
})
.then(() => {
db.runSql(httpToHttps('demoDomain'));
})
.then(() => {
db.runSql(prependHttps('demoDomain'));
})
.catch((err) => {
console.log(err); // eslint-disable-line no-console
});
};
exports.down = function down(db, callback) {
// noop reversal for this migration
callback();
};
| 28.571429 | 104 | 0.544 |
92c858419ff0873a5ac9777670837b4bbfa336e6 | 10,957 | js | JavaScript | src/clincoded/static/components/group_submit.js | ClinGen/clincoded | 5624c74546ce2a44eda00ee632a8de8c2099da10 | [
"MIT"
] | 30 | 2015-09-23T20:38:57.000Z | 2021-03-10T03:12:46.000Z | src/clincoded/static/components/group_submit.js | ClinGen/clincoded | 5624c74546ce2a44eda00ee632a8de8c2099da10 | [
"MIT"
] | 2,132 | 2015-06-08T21:50:35.000Z | 2022-02-15T22:44:18.000Z | src/clincoded/static/components/group_submit.js | ClinGen/clincoded | 5624c74546ce2a44eda00ee632a8de8c2099da10 | [
"MIT"
] | 10 | 2015-09-25T20:11:25.000Z | 2020-12-09T02:58:44.000Z | "use strict";
import React from 'react';
import createReactClass from 'create-react-class';
import _ from 'underscore';
import { RestMixin } from './rest';
import { queryKeyValue, curator_page } from './globals';
import { Form, FormMixin, Input } from '../libs/bootstrap/form';
import { Panel } from '../libs/bootstrap/panel';
import * as curator from './curator';
const RecordHeader = curator.RecordHeader;
const PmidSummary = curator.PmidSummary;
var GroupSubmit = module.exports.GroupSubmit = createReactClass({
mixins: [FormMixin, RestMixin],
// Keeps track of values from the query string
queryValues: {},
getInitialState: function() {
return {
gdm: null, // GDM object given in query string
group: null, // Group object given in query string
annotation: null, // Annotation object given in query string
haveFamily: 'none', // Setting of have-family switch
disabled: false
};
},
// Handle value changes in the form
handleChange: function(ref, e) {
if (ref === 'havefamily') {
this.setState({haveFamily: this.refs[ref].getValue(), disabled: true});
}
},
// Load objects from query string into the state variables. Must have already parsed the query string
// and set the queryValues property of this React class.
loadData: function() {
var gdmUuid = this.queryValues.gdmUuid;
var groupUuid = this.queryValues.groupUuid;
var annotationUuid = this.queryValues.annotationUuid;
// Make an array of URIs to query the database. Don't include any that didn't include a query string.
var uris = _.compact([
gdmUuid ? '/gdm/' + gdmUuid : '',
groupUuid ? '/groups/' + groupUuid : '',
annotationUuid ? '/evidence/' + annotationUuid : ''
]);
// With all given query string variables, get the corresponding objects from the DB.
this.getRestDatas(
uris
).then(datas => {
// See what we got back so we can build an object to copy in this React object's state to rerender the page.
var stateObj = {};
datas.forEach(function(data) {
switch(data['@type'][0]) {
case 'gdm':
stateObj.gdm = data;
break;
case 'group':
stateObj.group = data;
break;
case 'annotation':
stateObj.annotation = data;
break;
default:
break;
}
});
// Set all the state variables we've collected
this.setState(stateObj);
// Not passing data to anyone; just resolve with an empty promise.
return Promise.resolve();
}).catch(function(e) {
console.log('OBJECT LOAD ERROR: %s — %s', e.statusText, e.url);
});
},
// After the Family Curation page component mounts, grab the GDM, group, family, and annotation UUIDs (as many as given)
// from the query string and retrieve the corresponding objects from the DB, if they exist. Note, we have to do this after
// the component mounts because AJAX DB queries can't be done from unmounted components.
componentDidMount: function() {
// Get the 'evidence', 'gdm', and 'group' UUIDs from the query string and save them locally.
this.loadData();
},
render: function() {
var gdm = this.state.gdm;
var group = this.state.group;
var annotation = this.state.annotation;
var session = (this.props.session && Object.keys(this.props.session).length) ? this.props.session : null;
// Get the query strings. Have to do this now so we know whether to render the form or not. The form
// uses React controlled inputs, so we can only render them the first time if we already have the
// family object read in.
this.queryValues.gdmUuid = queryKeyValue('gdm', this.props.href);
this.queryValues.groupUuid = queryKeyValue('group', this.props.href);
this.queryValues.annotationUuid = queryKeyValue('evidence', this.props.href);
// Build the link to go back and edit the newly created group page
var editGroupLink = (gdm && group && annotation) ? '/group-curation/?gdm=' + gdm.uuid + '&evidence=' + annotation.uuid + '&group=' + group.uuid : '';
return (
<div>
<RecordHeader gdm={gdm} omimId={gdm && gdm.omimId} session={session} linkGdm={true} pmid={annotation ? annotation.article.pmid : null} />
<div className="container">
{annotation && annotation.article ?
<div className="curation-pmid-summary">
<PmidSummary article={annotation.article} displayJournal />
</div>
: null}
{group ?
<div className="viewer-titles submit-titles">
<h1>Group Information: {group.label}</h1> <a href={editGroupLink} className="btn btn-info">Edit</a>
</div>
: null}
<div className="row">
<div className="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1">
<Panel panelClassName="submit-results-panel" panelBodyClassName="bg-info">
<Form formClassName="form-horizontal form-std">
<Input type="select" ref="havefamily" label="Do any of the probands or other individuals in this Group have Family Information?" defaultValue={this.state.haveFamily}
handleChange={this.handleChange} labelClassName="group-submit-results-label" wrapperClassName="group-submit-results-switch" groupClassName="submit-results-wrapper">
<option value="none" disabled={this.state.disabled}>No Selection</option>
<option disabled="disabled"></option>
<option value="y">Yes</option>
<option value="n">No</option>
</Input>
</Form>
<p className="submit-results-panel-info">
<em><strong>Note</strong>: Family Information includes any information about a proband in the group that is part of family and any relatives of the proband
(e.g. average age of onset, race, family ethnicity, etc.) and information about segregation of phenotype(s) and variant(s).</em>
</p>
</Panel>
{(this.state.haveFamily === 'y' && gdm && annotation && group) ?
<Panel panelClassName="submit-results-panel submit-results-response">
<p>
<em>Any variant associated with a proband in a Family is captured at the Family level.</em>
</p>
<div className="group-submit-results-choices">
<span className="group-submit-results-btn">
<div className="submit-results-note">To associate segregation, variant, or any other information for a family, <strong>Add New Family for this Group</strong>.</div>
<a className="btn btn-default" href={'/family-curation/?gdm=' + gdm.uuid + '&evidence=' + annotation.uuid + '&group=' + group.uuid}>Add New Family for this Group</a>
</span>
<span className="submit-results-choices-sep">OR</span>
<span className="group-submit-results-btn">
<div className="submit-results-note">If you have previously created an entry for this Family, <strong>Return to Record Curation page</strong> to add this Family to the newly created Group.</div>
<a className="btn btn-default" href={'/curation-central/?gdm=' + gdm.uuid + '&pmid=' + annotation.article.pmid}>Return to Record Curation page <i className="icon icon-briefcase"></i></a>
</span>
</div>
</Panel>
: ((this.state.haveFamily === 'n' && gdm && annotation && group) ?
<Panel panelClassName="submit-results-panel submit-results-response">
<p>
<em>Any variant associated with an individual that is a member of a Group but not part of a Family is captured at the Individual level.</em>
</p>
<div className="group-submit-results-choices">
<span className="group-submit-results-btn">
<div className="submit-results-note">To associate a variant and/or information such as age, race, etc. with an individual in the Group, <strong>Add New Individuals for this Group</strong>.</div>
<a className="btn btn-default" href={'/individual-curation/?gdm=' + gdm.uuid + '&evidence=' + annotation.uuid + '&group=' + group.uuid}>Add New Individuals for this Group</a>
</span>
<span className="submit-results-choices-sep">OR</span>
<span className="group-submit-results-btn">
<div className="submit-results-note">If you have previously created an entry for this Individual, <strong>Return to Record Curation page</strong> to add this Individual to the newly created Group.</div>
<a className="btn btn-default" href={'/curation-central/?gdm=' + gdm.uuid + '&pmid=' + annotation.article.pmid}>Return to Record Curation page <i className="icon icon-briefcase"></i></a>
</span>
</div>
</Panel>
: null)}
</div>
</div>
</div>
</div>
);
}
});
curator_page.register(GroupSubmit, 'curator_page', 'group-submit');
| 59.548913 | 246 | 0.527973 |
92c9155b3a6796fec8ecad4258625c4ac96211e0 | 382 | js | JavaScript | server.js | FHGBotDev/Nudes_R_Us | 259bf811cc41e7387f5f10c7696dbb5628919807 | [
"Apache-2.0"
] | 5 | 2020-10-17T21:56:36.000Z | 2022-01-13T21:15:23.000Z | server.js | FHGBotDev/Nudes_R_Us | 259bf811cc41e7387f5f10c7696dbb5628919807 | [
"Apache-2.0"
] | null | null | null | server.js | FHGBotDev/Nudes_R_Us | 259bf811cc41e7387f5f10c7696dbb5628919807 | [
"Apache-2.0"
] | null | null | null | // Dependencies
var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
var server = http.Server(app);
// Routing
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname, 'index.html'));
});
// Starts the server.
server.listen(5000, function() {
console.log('Starting server on port 5000');
});
| 21.222222 | 56 | 0.675393 |
92cb05f00eb4fd843315f009c7c78fc060c33c0b | 533 | js | JavaScript | cartzilla-dev-cs---cartzilla-dev-cs/web-pages/shop-single-v3/content-pages/shop-single-v3.en.webpage.custom_javascript.js | Cloudstrucc/PowerApps-Cartzilla | e0999e45b3881fe5855d489da15f484328dcc201 | [
"MIT"
] | 5 | 2021-12-26T04:22:06.000Z | 2021-12-30T18:49:14.000Z | cartzilla-dev-cs---cartzilla-dev-cs/web-pages/shop-single-v3/content-pages/shop-single-v3.en.webpage.custom_javascript.js | Cloudstrucc/PowerApps-Cartzilla | e0999e45b3881fe5855d489da15f484328dcc201 | [
"MIT"
] | null | null | null | cartzilla-dev-cs---cartzilla-dev-cs/web-pages/shop-single-v3/content-pages/shop-single-v3.en.webpage.custom_javascript.js | Cloudstrucc/PowerApps-Cartzilla | e0999e45b3881fe5855d489da15f484328dcc201 | [
"MIT"
] | 2 | 2021-12-29T15:32:34.000Z | 2022-02-21T17:45:39.000Z |
var btn = document.getElementById("addToCart");
btn.addEventListener("click", makeorder);
const data = { name: "Jack Snead" , ispricelocked : "false" };
async function makeorder(e) {
const response = await fetch("https://cartzilla-dev-cs.crm3.dynamics.com/api/data/v9.0/salesorders", {
method: 'Post',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+''
}
});
const myJson = await response.status;
alert("request status " + myJson);
} | 26.65 | 104 | 0.652908 |
92cf21d0977686683219369efbd44717beb0ddea | 2,724 | js | JavaScript | client/src/app/modules/music/albums.js | RiderExMachina/webinterface.arch | 90181e1a7af5448dbb8b5f4c1e860369c27e1b9d | [
"MIT"
] | 35 | 2015-08-16T04:14:18.000Z | 2021-05-29T22:51:30.000Z | client/src/app/modules/music/albums.js | Acidburn0zzz/webinterface.arch | 97697bd4b9aeb0d0db5abf488bf925cf860092e9 | [
"MIT"
] | 29 | 2015-07-27T23:40:18.000Z | 2022-01-22T10:06:27.000Z | client/src/app/modules/music/albums.js | Acidburn0zzz/webinterface.arch | 97697bd4b9aeb0d0db5abf488bf925cf860092e9 | [
"MIT"
] | 22 | 2015-08-25T23:37:28.000Z | 2020-10-28T12:51:39.000Z | angular.module('app')
.controller('MusicAlbumsCtrl', ['$scope', '$stateParams', 'storage',
function MusicAlbumsCtrl($scope, $stateParams, storage) {
$scope.loading = true;
$scope.fetching = false;
$scope.empty = false;
$scope.requestItemsBy = 50;
$scope.total = Infinity;
$scope.filter = $stateParams.filter;
$scope.albums =[];
var filter = null;
if ($scope.filter) {
$scope.filterId = parseInt($stateParams.filterId);
filter = {
key: $scope.filter,
value: $scope.filterId
};
}
function onSongsFromSource (result) {
$scope.songs = result.songs;
$scope.loading = false;
}
function onArtistFromSource (artist) {
$scope.artist = artist;
var songFilter = {
key : 'artistid',
value : $scope.albums[0].artistid[0]
}
$scope.xbmc.getSongs(songFilter, onSongsFromSource, {start:0, end:200});
};
function onAlbumsFromSource(result) {
var albums = result && result.albums ? result.albums : [];
$scope.total = result ? result.limits.total : Infinity;
$scope.albums = $scope.albums.concat(albums);
$scope.empty = !$scope.albums.length;
if ($scope.filter) {
$scope.xbmc.getArtistDetails(albums[0].artistid[0], onArtistFromSource);
} else {
$scope.loading = false;
$scope.fetching = false;
}
};
function onLoad() {
var limits = {
'start' : 0,
'end' : $scope.requestItemsBy
};
$scope.xbmc.getAlbums(filter, onAlbumsFromSource, limits);
};
if ($scope.xbmc.isConnected()) {
onLoad();
} else {
$scope.xbmc.register('Websocket.OnConnected', {
fn: onLoad,
scope: this
});
}
$scope.isPartOf = function (album) {
return function (song) {
return song.albumid === album.albumid;
};
};
$scope.hasCover = function(album) {
return album.thumbnail !== '';
};
$scope.loadMore = function () {
if($scope.albums.length < $scope.total) {
$scope.fetching = true;
var limits = {
'start' : $scope.albums.length,
'end' : Math.min($scope.albums.length+$scope.requestItemsBy, $scope.total)
};
$scope.xbmc.getAlbums(filter, onAlbumsFromSource, limits);
}
};
var detail = document.querySelector('.songs-wrapper.detail');
if(detail) {
detail.onscroll = function () {
if(detail.scrollTop > 250) {
if(!detail.classList.contains('affixable')) {
detail.classList.add('affixable');
}
} else {
detail.classList.remove('affixable');
};
};
}
}
]); | 26.705882 | 84 | 0.568282 |
92cfd5ff1a84f71eb1df71fb62ec99e415d672f2 | 430 | js | JavaScript | test/language/expressions/compound-assignment/11.13.2-19-s.js | katemihalikova/test262 | aaf4402b4ca9923012e61830fba588bf7ceb6027 | [
"BSD-3-Clause"
] | 2,602 | 2015-01-02T10:45:13.000Z | 2022-03-30T23:04:17.000Z | test/language/expressions/compound-assignment/11.13.2-19-s.js | katemihalikova/test262 | aaf4402b4ca9923012e61830fba588bf7ceb6027 | [
"BSD-3-Clause"
] | 2,157 | 2015-01-06T05:01:55.000Z | 2022-03-31T17:18:08.000Z | test/language/expressions/compound-assignment/11.13.2-19-s.js | katemihalikova/test262 | aaf4402b4ca9923012e61830fba588bf7ceb6027 | [
"BSD-3-Clause"
] | 527 | 2015-01-08T16:04:26.000Z | 2022-03-24T03:34:47.000Z | // Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 11.13.2-19-s
description: >
ReferenceError isn't thrown if the LeftHandSideExpression of a Compound
Assignment operator(+=) evaluates to a resolvable reference
---*/
var _11_13_2_19 = -1
_11_13_2_19 += 10;
assert.sameValue(_11_13_2_19, 9, '_11_13_2_19');
| 28.666667 | 75 | 0.704651 |
92d17816d3828b6e5b178b353963e346ca7adf3c | 2,794 | js | JavaScript | icsToJson.js | alanhagerman/CalendarToVoice | f23ff10c742cbf2c9a31abe9dbbeb4a9d480f89e | [
"BSD-3-Clause"
] | 2 | 2019-03-05T14:13:08.000Z | 2020-09-16T01:47:19.000Z | icsToJson.js | alanhagerman/CalendarToVoice | f23ff10c742cbf2c9a31abe9dbbeb4a9d480f89e | [
"BSD-3-Clause"
] | 2 | 2019-04-12T10:58:57.000Z | 2021-05-08T05:54:21.000Z | icsToJson.js | alanhagerman/CalendarToVoice | f23ff10c742cbf2c9a31abe9dbbeb4a9d480f89e | [
"BSD-3-Clause"
] | 2 | 2019-03-05T14:13:27.000Z | 2019-03-05T14:19:17.000Z | /* eslint-disable require-unicode-regexp */
/* eslint-disable no-const-assign */
/* eslint-disable no-continue */
/* eslint-disable no-plusplus */
/* eslint-disable arrow-parens */
/* eslint-disable func-style */
const NEW_LINE = /\r\n|\n|\r/;
const EVENT = "VEVENT";
const EVENT_START = "BEGIN";
const EVENT_END = "END";
const START_DATE = "DTSTART";
const END_DATE = "DTEND";
const DESCRIPTION = "DESCRIPTION";
const SUMMARY = "SUMMARY";
const LOCATION = "LOCATION";
const ALARM = "VALARM";
const RRULE = "RRULE";
const DURATION = "DURATION";
const keyMap = {
[START_DATE]: "startDate",
[END_DATE]: "endDate",
[DESCRIPTION]: "description",
[SUMMARY]: "summary",
[LOCATION]: "location",
[RRULE]: "rrule",
[DURATION]:"duration"
};
const clean = string => unescape(string).trim();
const icsToJson = icsData => {
const array = [];
let currentObj = {};
let lastKey = "";
const lines = icsData.split(NEW_LINE);
let isAlarm = false;
for (let i = 0, iLen = lines.length; i < iLen; ++i) {
const line = lines[i];
const lineData = line.split(":");
let key = lineData[0];
let value = lineData[1];
if (key.indexOf(";") !== -1) {
const keyParts = key.split(";");
key = keyParts[0];
// Maybe do something with that second part later
}
if (lineData.length < 2) {
if (key.startsWith(" ") && lastKey !== undefined && lastKey.length) {
currentObj[lastKey] += clean(line.substr(1));
}
continue;
} else {
lastKey = keyMap[key];
}
switch (key) {
case EVENT_START:
if (value === EVENT) {
currentObj = {};
} else if (value === ALARM) {
isAlarm = true;
}
break;
case EVENT_END:
isAlarm = false;
if (value === EVENT) array.push(currentObj);
break;
case START_DATE:
currentObj[keyMap[START_DATE]] = value;
break;
case END_DATE:
currentObj[keyMap[END_DATE]] = value;
break;
case DESCRIPTION:
if (!isAlarm) currentObj[keyMap[DESCRIPTION]] = clean(value);
break;
case SUMMARY:
if ( lineData.length > 2) {
// summary had colon's in the text, recombine
lineData.shift();
value = lineData.join(":"); // remove the key and then join remaining back seperated by :
}
currentObj[keyMap[SUMMARY]] = clean(value);
break;
case LOCATION:
currentObj[keyMap[LOCATION]] = clean(value);
break;
case RRULE:
currentObj[keyMap[RRULE]] = clean(value);
break;
case DURATION:
currentObj[keyMap[DURATION]] = clean(value);
break;
default:
continue;
}
}
return array;
};
module.exports = {
icsToJson
}
| 24.946429 | 100 | 0.578024 |
92d1a2245d5c6287dfde6cbc03f34e44d3620a75 | 1,054 | js | JavaScript | lib/get-safe-filename.js | jeanbmar/payload-s3-upload | d675aa0be2adc8677382840f4b26c0c4dc0b1c92 | [
"MIT"
] | 6 | 2021-10-07T10:14:21.000Z | 2022-03-14T16:12:37.000Z | lib/get-safe-filename.js | jeanbmar/payload-s3-upload | d675aa0be2adc8677382840f4b26c0c4dc0b1c92 | [
"MIT"
] | 2 | 2022-02-12T09:11:29.000Z | 2022-03-16T12:24:14.000Z | lib/get-safe-filename.js | jeanbmar/payload-s3-upload | d675aa0be2adc8677382840f4b26c0c4dc0b1c92 | [
"MIT"
] | null | null | null | // forked from src/uploads/getSafeFilename.ts
const sanitize = require('sanitize-filename');
const fileExists = require('./file-exists');
const incrementName = (name) => {
const extension = name.split('.').pop();
const baseFilename = sanitize(name.substr(0, name.lastIndexOf('.')) || name);
let incrementedName = baseFilename;
const regex = /(.*)-(\d)$/;
const found = baseFilename.match(regex);
if (found === null) {
incrementedName += '-1';
} else {
const matchedName = found[1];
const matchedNumber = found[2];
const incremented = Number(matchedNumber) + 1;
incrementedName = `${matchedName}-${incremented}`;
}
return `${incrementedName}.${extension}`;
};
module.exports = async (payload, slug, desiredFilename) => {
let modifiedFilename = desiredFilename;
// eslint-disable-next-line no-await-in-loop
while (await fileExists(payload, slug, modifiedFilename)) {
modifiedFilename = incrementName(modifiedFilename);
}
return modifiedFilename;
};
| 34 | 81 | 0.651803 |
92d23a813d154b4301d231dfe6d74b670ca756ac | 154 | js | JavaScript | public/javascripts/main.js | jthiller/personal-website | 4238bdf566295b6a990494816774800b58fc6aa1 | [
"MIT"
] | null | null | null | public/javascripts/main.js | jthiller/personal-website | 4238bdf566295b6a990494816774800b58fc6aa1 | [
"MIT"
] | null | null | null | public/javascripts/main.js | jthiller/personal-website | 4238bdf566295b6a990494816774800b58fc6aa1 | [
"MIT"
] | null | null | null | 'use strict';
$(function() {
$('.pageframe').addClass('loaded');
$('.pageframe').removeClass('headeranim');
// setTimeout(function(){
// },2500);
}); | 19.25 | 43 | 0.597403 |
92d48c42e9240badf99088dff38ea3543a1c90b5 | 1,297 | js | JavaScript | colorlog.js | Metotron/colorlog | 3b216edcfda2818ed9405224a28b46b1c6b731ba | [
"BSD-2-Clause"
] | null | null | null | colorlog.js | Metotron/colorlog | 3b216edcfda2818ed9405224a28b46b1c6b731ba | [
"BSD-2-Clause"
] | null | null | null | colorlog.js | Metotron/colorlog | 3b216edcfda2818ed9405224a28b46b1c6b731ba | [
"BSD-2-Clause"
] | null | null | null | (function() {
'use strict'
let consoleStyles = {
'font-size' : '14px',
'padding' : '2px 5px',
'color' : '#499e4b',
//'background-color' : '#282828'
},
floatPrecision = 0 // Количество знаков после запятой для дробных чисел. 0 — вывод строкой
/* Сохраняем нативную функцию */
console.log_ = console.log
/* Переопределяем функцию */
console.log = function(...params) {
let styles = [], // Стили для вывода
logParams = [] // Параметры для console.log
params.forEach(param => {
let type = 's'
switch (typeof(param)) {
case 'object':
type = 'o'
break
case 'number':
if (param % 1 != 0) {
if (floatPrecision != 0)
type = `.${floatPrecision}f`
}
else
type = 'd'
break
}
let constyle = []
for (let styleName in consoleStyles)
constyle.push(styleName + ':' + consoleStyles[styleName])
// Если перед этим выводили не объект, то стили заново вставлять не нужно, они ещё действуют
if (type != 'o' && styles.length && styles[styles.length - 1] != '%c%o')
styles.push(`%${type}`)
else {
styles.push(`%c%${type}`)
logParams.push(constyle.join(';'))
}
logParams.push(param)
})
console.log_(styles.join(' '), ...logParams)
}
})()
| 24.942308 | 98 | 0.570547 |
92d4e12d5c54cac6dc0a51399b47fdfc5ec10d6c | 134 | js | JavaScript | src/utils/backend.js | dylanhz/dblab_frontend | 705c6f79928e4b2e70aff0307ba9d5d50c0bab46 | [
"MIT"
] | null | null | null | src/utils/backend.js | dylanhz/dblab_frontend | 705c6f79928e4b2e70aff0307ba9d5d50c0bab46 | [
"MIT"
] | null | null | null | src/utils/backend.js | dylanhz/dblab_frontend | 705c6f79928e4b2e70aff0307ba9d5d50c0bab46 | [
"MIT"
] | null | null | null | const BACKEND_HOST = 'be.dblab.why2001.top'
const BACKEND_PORT = 8002
export const BACKEND = `http://${BACKEND_HOST}:${BACKEND_PORT}`
| 33.5 | 63 | 0.753731 |
92d51d15152b2e9fb8340855daffc97aa33a9b49 | 470 | js | JavaScript | src/hooks/setSiteSnippet.js | 2manypistachios/FunctionalColors | 783934a8321246c501f2ff27017b44f14246aee7 | [
"MIT"
] | 2 | 2021-09-17T21:38:16.000Z | 2021-09-22T20:39:35.000Z | src/hooks/setSiteSnippet.js | 2manypistachios/FunctionalColors | 783934a8321246c501f2ff27017b44f14246aee7 | [
"MIT"
] | null | null | null | src/hooks/setSiteSnippet.js | 2manypistachios/FunctionalColors | 783934a8321246c501f2ff27017b44f14246aee7 | [
"MIT"
] | null | null | null | import useStore from "@/store/useStore"
// Not a real hook
const SetSiteSnippet = ({ hex, harmony, loop, brightFunc, satFunc }) => {
const [setHex, setHarmony, setLoop, setBrightFunc, setSatFunc] = useStore('setHex, setHarmony, setLoop, setBrightFunc, setSatFunc')
const changeAlgo = () => {
setHex(hex);
setHarmony(harmony)
setLoop(loop)
setBrightFunc(brightFunc)
setSatFunc(satFunc)
}
return changeAlgo;
}
export default SetSiteSnippet; | 26.111111 | 133 | 0.708511 |