code stringlengths 2 1.05M |
|---|
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
module('JobsStateController', function(hooks) {
setupTest(hooks);
// Replace this with your real tests.
test('it exists', function(assert) {
var controller = this.owner.lookup('controller:jobs/state');
assert.ok(controller);
});
});
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M12 10.9c-.61 0-1.1.49-1.1 1.1s.49 1.1 1.1 1.1c.61 0 1.1-.49 1.1-1.1s-.49-1.1-1.1-1.1zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm2.19 12.19L6 18l3.81-8.19L18 6l-3.81 8.19z"
}), 'Explore'); |
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var GameObjectFactory = require('../../GameObjectFactory');
var IsoTriangle = require('./IsoTriangle');
/**
* Creates a new IsoTriangle Shape Game Object and adds it to the Scene.
*
* Note: This method will only be available if the IsoTriangle Game Object has been built into Phaser.
*
* The IsoTriangle Shape is a Game Object that can be added to a Scene, Group or Container. You can
* treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling
* it for input or physics. It provides a quick and easy way for you to render this shape in your
* game without using a texture, while still taking advantage of being fully batched in WebGL.
*
* This shape supports only fill colors and cannot be stroked.
*
* An IsoTriangle is an 'isometric' triangle. Think of it like a pyramid. Each face has a different
* fill color. You can set the color of the top, left and right faces of the triangle respectively
* You can also choose which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties.
*
* You cannot view an IsoTriangle from under-neath, however you can change the 'angle' by setting
* the `projection` property. The `reversed` property controls if the IsoTriangle is rendered upside
* down or not.
*
* @method Phaser.GameObjects.GameObjectFactory#isotriangle
* @since 3.13.0
*
* @param {number} [x=0] - The horizontal position of this Game Object in the world.
* @param {number} [y=0] - The vertical position of this Game Object in the world.
* @param {number} [size=48] - The width of the iso triangle in pixels. The left and right faces will be exactly half this value.
* @param {number} [height=32] - The height of the iso triangle. The left and right faces will be this tall. The overall height of the iso triangle will be this value plus half the `size` value.
* @param {boolean} [reversed=false] - Is the iso triangle upside down?
* @param {number} [fillTop=0xeeeeee] - The fill color of the top face of the iso triangle.
* @param {number} [fillLeft=0x999999] - The fill color of the left face of the iso triangle.
* @param {number} [fillRight=0xcccccc] - The fill color of the right face of the iso triangle.
*
* @return {Phaser.GameObjects.IsoTriangle} The Game Object that was created.
*/
GameObjectFactory.register('isotriangle', function (x, y, size, height, reversed, fillTop, fillLeft, fillRight)
{
return this.displayList.add(new IsoTriangle(this.scene, x, y, size, height, reversed, fillTop, fillLeft, fillRight));
});
|
/*
server.js
=========
Testem's server. Serves up the HTML, JS, and CSS required for
running the tests in a browser.
*/
var Express = require('express')
, SocketIO = require('socket.io')
, BrowserRunner = require('./browser_runner')
, fs = require('fs')
, path = require('path')
, util = require('util')
, async = require('async')
, glob = require('glob')
, isa = require('./isa')
, log = require('winston')
, EventEmitter = require('events').EventEmitter
, Backbone = require('backbone')
, path = require('path')
, Mustache = require('consolidate').mustache
, http = require('http')
//, log = new (require('log'))('info', fs.createWriteStream('testem.log2'))
require('./socket.io.patch')
function Server(config){
this.config = config
this.ieCompatMode = null
}
Server.prototype = {
__proto__: EventEmitter.prototype
, start: function(){
this.createExpress()
// Start the server!
// Create socket.io sockets
this.server = http.createServer(this.express)
this.io = SocketIO.listen(this.server)
this.io.sockets.on('connection', this.onClientConnected.bind(this))
this.server.listen(this.config.get('port'))
process.nextTick(function(){
this.emit('server-start')
}.bind(this))
}
, stop: function(callback){
this.server.close(callback)
}
, createExpress: function(){
var self = this
var app = this.express = Express()
this.configureExpress(app)
app.get('/', function(req, res){
self.serveHomePage(req, res)
})
app.get(/\/([0-9]+)$/, function(req, res){
self.serveHomePage(req, res)
})
app.get('/testem.js', function(req, res){
self.serveTestemClientJs(req, res)
})
app.get(/^\/(?:[0-9]+)(\/.+)$/, serveStaticFile)
app.post(/^\/(?:[0-9]+)(\/.+)$/, serveStaticFile)
app.get(/^(.+)$/, serveStaticFile)
app.post(/^(.+)$/, serveStaticFile)
function serveStaticFile(req, res){
self.serveStaticFile(req.params[0], req, res)
}
}
, configureExpress: function(app){
var self = this
app.configure(function(){
app.engine("html", Mustache)
app.set("view options", {layout: false})
app.use(Express.bodyParser())
app.use(function(req, res, next){
if (self.ieCompatMode)
res.setHeader('X-UA-Compatible', 'IE=' + self.ieCompatMode)
next()
})
app.use(Express.static(__dirname + '/../public'))
})
}
, renderRunnerPage: function(err, files, res){
var config = this.config
var framework = config.get('framework') || 'jasmine'
var css_files = config.get('css_files')
var templateFile = {
jasmine: 'jasminerunner.html'
, qunit: 'qunitrunner.html'
, mocha: 'mocharunner.html'
, 'mocha+chai': 'mochachairunner.html'
, buster: 'busterrunner.html'
, custom: 'customrunner.html'
}[framework]
res.render(__dirname + '/../views/' + templateFile, {
scripts: files,
styles: css_files
})
}
, renderDefaultTestPage: function(req, res){
res.header('Cache-Control', 'No-cache')
res.header('Pragma', 'No-cache')
var self = this
var config = this.config
var test_page = config.get('test_page')
if (test_page){
if (test_page[0] === "/") {
test_page = encodeURIComponent(test_page)
}
var base = req.path === '/' ?
req.path : req.path + '/'
var url = base + test_page + '#testem'
res.redirect(url)
} else {
config.getServeFiles(function(err, files){
self.renderRunnerPage(err, files, res)
})
}
}
, serveHomePage: function(req, res){
var config = this.config
var routes = config.get('routes') || config.get('route') || {}
if (routes['/']){
this.serveStaticFile('/', req, res)
}else{
this.renderDefaultTestPage(req, res)
}
}
, serveTestemClientJs: function(req, res){
res.setHeader('Content-Type', 'text/javascript')
res.write(';(function(){')
var files = [
'socket.io.js'
, 'json2.js'
, 'jasmine_adapter.js'
, 'qunit_adapter.js'
, 'mocha_adapter.js'
, 'buster_adapter.js'
, 'testem_client.js'
]
async.forEachSeries(files, function(file, done){
file = __dirname + '/../public/testem/' + file
fs.readFile(file, function(err, data){
if (err){
res.write('// Error reading ' + file + ': ' + err)
}else{
res.write('\n//============== ' + path.basename(file) + ' ==================\n\n')
res.write(data)
}
done()
})
}, function(){
res.write('}());')
res.end()
})
}
, killTheCache: function killTheCache(req, res){
res.setHeader('Cache-Control', 'No-cache')
res.setHeader('Pragma', 'No-cache')
delete req.headers['if-modified-since']
delete req.headers['if-none-match']
}
, route: function route(uri){
var config = this.config
var routes = config.get('routes') || config.get('route') || {}
var bestMatchLength = 0
var bestMatch = null
for (var prefix in routes){
if (uri.substring(0, prefix.length) === prefix){
if (bestMatchLength < prefix.length){
bestMatch = routes[prefix] + '/' + uri.substring(prefix.length)
bestMatchLength = prefix.length
}
}
}
return {
routed: !!bestMatch
, uri: bestMatch || uri.substring(1)
}
}
, serveStaticFile: function(uri, req, res){
var self = this
var config = this.config
var routeRes = this.route(uri)
uri = routeRes.uri
var wasRouted = routeRes.routed
this.killTheCache(req, res)
var allowUnsafeDirs = config.get('unsafe_file_serving')
var filePath = path.resolve(config.resolvePath(uri))
var ext = path.extname(filePath)
var isPathPermitted = filePath.indexOf(config.cwd()) !== -1
if (!wasRouted && !allowUnsafeDirs && !isPathPermitted) {
res.status(403)
res.write('403 Forbidden')
res.end()
} else if (ext === '.html') {
config.getTemplateData(function(err, data){
res.render(filePath, data)
self.emit('file-requested', filePath)
})
} else {
fs.stat(filePath, function(err, stat){
self.emit('file-requested', filePath)
if (err) return res.sendfile(filePath)
if (stat.isDirectory()){
fs.readdir(filePath, function(err, files){
var dirListingPage = __dirname + '/../views/directorylisting.html'
res.render(dirListingPage, {files: files})
})
}else{
res.sendfile(filePath)
}
})
}
}
, onClientConnected: function(client){
var self = this
client.once('browser-login', function(browserName, id){
log.info('New client connected: ' + browserName + ' ' + id)
self.emit('browser-login', browserName, id, client)
})
}
}
module.exports = Server
|
module = module.exports = (function () {
var _ = {};
_.extract3x3 = function (model, screen, oldpos) {
function getValue(offset) {
var
x = oldpos.col + offset.x,
y = oldpos.row + offset.y;
if (x < 0 || y < 0 || x >= model.gridCols || y >= model.gridRows)
return ' ';
return screen.lines[y][x];
}
return [
[getValue({x: -1, y: -1}), getValue({x: 0, y: -1}), getValue({x: 1, y: -1})],
[getValue({x: -1, y: 0}), getValue({x: 0, y: 0}), getValue({x: 1, y: 0})],
[getValue({x: -1, y: 1}), getValue({x: 0, y: 1}), getValue({x: 1, y: 1})]
];
};
_.apply3x3 = function (model, matrix, screen, oldpos) {
function setValue(offset, value) {
var
x = oldpos.col + offset.x,
y = oldpos.row + offset.y;
if (x < 0 || y < 0 || x >= model.gridCols || y >= model.gridRows)
return;
screen.lines[y][x] = value;
}
for(var x = 0; x < 3; x++) {
for(var y = 0; y < 3; y++) {
setValue({x: x-1, y: y-1}, matrix[y][x]);
}
}
};
return _;
})();
|
import React from 'react'
import Icon from 'react-icon-base'
const IoFork = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m21.1 11.6z m3.9 1.4c0 2-1.2 3.7-2.9 4.5-0.9 0.5-0.8 0.9-0.8 0.9s1.2 15.6 1.2 16.6-0.2 1.4-0.7 1.9-1.2 0.6-1.8 0.6-1.2-0.2-1.7-0.6-0.8-1-0.8-1.9 1.3-16.6 1.3-16.6 0-0.5-0.9-0.9c-1.7-0.8-2.9-2.5-2.9-4.5 0-3.4 1.2-7.3 1.9-10.5h0.6v9.1c0 0.5 0.2 0.9 0.7 0.9s0.7-0.3 0.8-0.8v-0.1l0.7-9.1h0.6l0.8 9.1v0.1c0.1 0.5 0.2 0.8 0.7 0.8s0.7-0.4 0.7-0.9v-9.1h0.6c0.7 3.1 1.9 7.1 1.9 10.5z"/></g>
</Icon>
)
export default IoFork
|
/**
* Created by hooxin on 14-10-12.
*/
Ext.define('Techsupport.view.sysadmin.dictItem.Detail', {
extend: 'Techsupport.view.base.BaseDetail',
alias: 'widget.dictItemDetail',
initComponent: function () {
this.callParent(arguments)
this.down('form').add({
xtype: 'panel',
border: false,
layout: 'column',
defaults: {
margin: {left: 5, top: 0, bottom: 5, right: 5}
}
})
Ext.apply(this.down('form>panel').defaults, {columnWidth: .33, anchor: '100%', labelWidth: '50%'})
this.down('form>panel').add([
{xtype: 'textfield',
name: 'id',
fieldLabel: 'ID',
hidden: true
},
{xtype: 'textfield',
name: 'dictcode',
fieldLabel: 'ๅญๅ
ธไปฃ็ ',
allowBlank: false,
blankText: 'ๅญๅ
ธไปฃ็ ไธ่ฝไธบ็ฉบ',
vtype: 'alphanum',
readOnly:true
},
{xtype: 'textfield',
name: 'displayName',
fieldLabel: 'ๆพ็คบๅผ',
allowBlank: false,
blankText: 'ๆพ็คบๅผไธ่ฝไธบ็ฉบ'
},
{xtype: 'textfield',
name: 'factValue',
fieldLabel: '็ๅฎๅผ',
allowBlank: false,
blankText: '็ๅฎๅผไธ่ฝไธบ็ฉบ'
},
{xtype: 'textfield',
name: 'appendValue',
fieldLabel: '้ๅ ๅผ'
},
{xtype: 'textfield',
name: 'superItemId',
fieldLabel: 'ไธ็บงID',
hidden: true
},
{xtype: 'textfield',
name: 'sibOrder',
fieldLabel: 'ๅบๅท',
allowBlank: false,
blankText: 'ๅบๅทไธ่ฝไธบ็ฉบ',
vtype:'number'
},
{xtype: 'combobox',
store: 'YN',
displayField: 'text',
valueField: 'value',
triggerAction: 'all',
editable: false,
emptyText: '่ฏท้ๆฉ',
queryMode: 'local',
name: 'isleaf',
fieldLabel: 'ๅญ่็น',
allowBlank: false,
blankText: 'ๅญ่็นไธ่ฝไธบ็ฉบ',
hidden: true
},
{xtype: 'combobox',
store: 'DictItemDisplayFlag',
displayField: 'text',
valueField: 'value',
triggerAction: 'all',
editable: false,
emptyText: '่ฏท้ๆฉ',
queryMode: 'local',
name: 'displayFlag',
fieldLabel: 'ๆพ็คบๆ ๅฟ',
allowBlank: false,
blankText: 'ๆพ็คบๆ ๅฟไธ่ฝไธบ็ฉบ'
},
{xtype: 'combobox',
store: 'OneZero',
displayField: 'text',
valueField: 'value',
triggerAction: 'all',
editable: false,
emptyText: '่ฏท้ๆฉ',
queryMode: 'local',
name: 'isValid',
fieldLabel: 'ๆฏๅฆๅฏ็จ',
allowBlank: false,
blankText: 'ๆฏๅฆๅฏ็จไธ่ฝไธบ็ฉบ'
},
{xtype: 'textfield',
name: 'itemSimplePin',
fieldLabel: '็ฎๆผ'
},
{xtype: 'textfield',
name: 'itemAllPin',
fieldLabel: 'ๅ
จๆผ'
}
])
}
}) |
'use strict';
/* global
VALID_CLASS: false,
INVALID_CLASS: false,
PRISTINE_CLASS: false,
DIRTY_CLASS: false,
ngModelMinErr: false
*/
// Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
var ISO_DATE_REGEXP = /^\d{4,}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+(?:[+-][0-2]\d:[0-5]\d|Z)$/;
// See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
// Note: We are being more lenient, because browsers are too.
// 1. Scheme
// 2. Slashes
// 3. Username
// 4. Password
// 5. Hostname
// 6. Port
// 7. Path
// 8. Query
// 9. Fragment
// 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999
var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
// eslint-disable-next-line max-len
var EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
var PARTIAL_VALIDATION_TYPES = createMap();
forEach('date,datetime-local,month,time,week'.split(','), function(type) {
PARTIAL_VALIDATION_TYPES[type] = true;
});
var inputType = {
/**
* @ngdoc input
* @name input[text]
*
* @description
* Standard HTML text input with angular data binding, inherited by most of the `input` elements.
*
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Adds `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
* does not match a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
* This parameter is ignored for input[type=password] controls, which will never trim the
* input.
*
* @example
<example name="text-input-directive" module="textInputExample">
<file name="index.html">
<script>
angular.module('textInputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.example = {
text: 'guest',
word: /^\s*\w*\s*$/
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Single word:
<input type="text" name="input" ng-model="example.text"
ng-pattern="example.word" required ng-trim="false">
</label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
</div>
<code>text = {{example.text}}</code><br/>
<code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
<code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
<code>myForm.$valid = {{myForm.$valid}}</code><br/>
<code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('example.text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('guest');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if multi word', function() {
input.clear();
input.sendKeys('hello world');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'text': textInputType,
/**
* @ngdoc input
* @name input[date]
*
* @description
* Input with date validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
* date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
* modern browsers do not yet support this input type, it is important to provide cues to users on the
* expected input format via a placeholder or label.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
* (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
* constraint validation.
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
* a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
* (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
* constraint validation.
* @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
* the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
* @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
* the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="date-input-directive" module="dateInputExample">
<file name="index.html">
<script>
angular.module('dateInputExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2013, 9, 22)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label for="exampleInput">Pick a date in 2013:</label>
<input type="date" id="exampleInput" name="input" ng-model="example.value"
placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.date">
Not a valid date!</span>
</div>
<tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
var valid = element(by.binding('myForm.input.$valid'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (see https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-10-22');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01-01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'date': createDateInputType('date', DATE_REGEXP,
createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
'yyyy-MM-dd'),
/**
* @ngdoc input
* @name input[datetime-local]
*
* @description
* Input with datetime validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
* This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
* inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
* Note that `min` will also add native HTML5 constraint validation.
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
* This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
* inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
* Note that `max` will also add native HTML5 constraint validation.
* @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
* the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
* @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
* the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="datetimelocal-input-directive" module="dateExample">
<file name="index.html">
<script>
angular.module('dateExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2010, 11, 28, 14, 57)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label for="exampleInput">Pick a date between in 2013:</label>
<input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.datetimelocal">
Not a valid date!</span>
</div>
<tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
var valid = element(by.binding('myForm.input.$valid'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2010-12-28T14:57:00');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01-01T23:59:00');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
'yyyy-MM-ddTHH:mm:ss.sss'),
/**
* @ngdoc input
* @name input[time]
*
* @description
* Input with time validation and transformation. In browsers that do not yet support
* the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
* Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
* This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
* attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
* native HTML5 constraint validation.
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
* This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
* attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
* native HTML5 constraint validation.
* @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
* `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
* @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
* `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="time-input-directive" module="timeExample">
<file name="index.html">
<script>
angular.module('timeExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(1970, 0, 1, 14, 57, 0)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label for="exampleInput">Pick a time between 8am and 5pm:</label>
<input type="time" id="exampleInput" name="input" ng-model="example.value"
placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.time">
Not a valid date!</span>
</div>
<tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "HH:mm:ss"'));
var valid = element(by.binding('myForm.input.$valid'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('14:57:00');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('23:59:00');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'time': createDateInputType('time', TIME_REGEXP,
createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
'HH:mm:ss.sss'),
/**
* @ngdoc input
* @name input[week]
*
* @description
* Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
* the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* week format (yyyy-W##), for example: `2013-W02`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
* This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
* attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
* native HTML5 constraint validation.
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
* This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
* attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
* native HTML5 constraint validation.
* @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
* the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
* @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
* the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="week-input-directive" module="weekExample">
<file name="index.html">
<script>
angular.module('weekExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2013, 0, 3)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label>Pick a date between in 2013:
<input id="exampleInput" type="week" name="input" ng-model="example.value"
placeholder="YYYY-W##" min="2012-W32"
max="2013-W52" required />
</label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.week">
Not a valid date!</span>
</div>
<tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-Www"'));
var valid = element(by.binding('myForm.input.$valid'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-W01');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-W01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
/**
* @ngdoc input
* @name input[month]
*
* @description
* Input with month validation and transformation. In browsers that do not yet support
* the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* month format (yyyy-MM), for example: `2009-01`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
* If the model is not set to the first of the month, the next view to model update will set it
* to the first of the month.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
* This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
* attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
* native HTML5 constraint validation.
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
* This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
* attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
* native HTML5 constraint validation.
* @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
* the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
* @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
* the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="month-input-directive" module="monthExample">
<file name="index.html">
<script>
angular.module('monthExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2013, 9, 1)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label for="exampleInput">Pick a month in 2013:</label>
<input id="exampleInput" type="month" name="input" ng-model="example.value"
placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.month">
Not a valid month!</span>
</div>
<tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-MM"'));
var valid = element(by.binding('myForm.input.$valid'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-10');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'month': createDateInputType('month', MONTH_REGEXP,
createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
'yyyy-MM'),
/**
* @ngdoc input
* @name input[number]
*
* @description
* Text input with number validation and transformation. Sets the `number` validation
* error if not a valid number.
*
* <div class="alert alert-warning">
* The model must always be of type `number` otherwise Angular will throw an error.
* Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
* error docs for more information and an example of how to convert your model if necessary.
* </div>
*
* ## Issues with HTML5 constraint validation
*
* In browsers that follow the
* [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
* `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
* If a non-number is entered in the input, the browser will report the value as an empty string,
* which means the view / model values in `ngModel` and subsequently the scope value
* will also be an empty string.
*
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
* Can be interpolated.
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
* Can be interpolated.
* @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`,
* but does not trigger HTML5 native validation. Takes an expression.
* @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`,
* but does not trigger HTML5 native validation. Takes an expression.
* @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint.
* Can be interpolated.
* @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint,
* but does not trigger HTML5 native validation. Takes an expression.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
* does not match a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="number-input-directive" module="numberExample">
<file name="index.html">
<script>
angular.module('numberExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.example = {
value: 12
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Number:
<input type="number" name="input" ng-model="example.value"
min="0" max="99" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.number">
Not valid number!</span>
</div>
<tt>value = {{example.value}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
it('should initialize to model', function() {
expect(value.getText()).toContain('12');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if over max', function() {
input.clear();
input.sendKeys('123');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'number': numberInputType,
/**
* @ngdoc input
* @name input[url]
*
* @description
* Text input with URL validation. Sets the `url` validation error key if the content is not a
* valid URL.
*
* <div class="alert alert-warning">
* **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
* used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
* the built-in validators (see the {@link guide/forms Forms guide})
* </div>
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
* does not match a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="url-input-directive" module="urlExample">
<file name="index.html">
<script>
angular.module('urlExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.url = {
text: 'http://google.com'
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>URL:
<input type="url" name="input" ng-model="url.text" required>
<label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
</div>
<tt>text = {{url.text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('url.text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('url.text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('http://google.com');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if not url', function() {
input.clear();
input.sendKeys('box');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'url': urlInputType,
/**
* @ngdoc input
* @name input[email]
*
* @description
* Text input with email validation. Sets the `email` validation error key if not a valid email
* address.
*
* <div class="alert alert-warning">
* **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
* used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
* use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
* </div>
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
* does not match a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="email-input-directive" module="emailExample">
<file name="index.html">
<script>
angular.module('emailExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.email = {
text: 'me@example.com'
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Email:
<input type="email" name="input" ng-model="email.text" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
</div>
<tt>text = {{email.text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('email.text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('email.text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('me@example.com');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if not email', function() {
input.clear();
input.sendKeys('xxx');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'email': emailInputType,
/**
* @ngdoc input
* @name input[radio]
*
* @description
* HTML radio button.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string} value The value to which the `ngModel` expression should be set when selected.
* Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
* too. Use `ngValue` if you need complex models (`number`, `object`, ...).
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
* is selected. Should be used instead of the `value` attribute if you need
* a non-string `ngModel` (`boolean`, `array`, ...).
*
* @example
<example name="radio-input-directive" module="radioExample">
<file name="index.html">
<script>
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.color = {
name: 'blue'
};
$scope.specialValue = {
"id": "12345",
"value": "green"
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>
<input type="radio" ng-model="color.name" value="red">
Red
</label><br/>
<label>
<input type="radio" ng-model="color.name" ng-value="specialValue">
Green
</label><br/>
<label>
<input type="radio" ng-model="color.name" value="blue">
Blue
</label><br/>
<tt>color = {{color.name | json}}</tt><br/>
</form>
Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
</file>
<file name="protractor.js" type="protractor">
it('should change state', function() {
var inputs = element.all(by.model('color.name'));
var color = element(by.binding('color.name'));
expect(color.getText()).toContain('blue');
inputs.get(0).click();
expect(color.getText()).toContain('red');
inputs.get(1).click();
expect(color.getText()).toContain('green');
});
</file>
</example>
*/
'radio': radioInputType,
/**
* @ngdoc input
* @name input[range]
*
* @description
* Native range input with validation and transformation.
*
* The model for the range input must always be a `Number`.
*
* IE9 and other browsers that do not support the `range` type fall back
* to a text input without any default values for `min`, `max` and `step`. Model binding,
* validation and number parsing are nevertheless supported.
*
* Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`
* in a way that never allows the input to hold an invalid value. That means:
* - any non-numerical value is set to `(max + min) / 2`.
* - any numerical value that is less than the current min val, or greater than the current max val
* is set to the min / max val respectively.
* - additionally, the current `step` is respected, so the nearest value that satisfies a step
* is used.
*
* See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))
* for more info.
*
* This has the following consequences for Angular:
*
* Since the element value should always reflect the current model value, a range input
* will set the bound ngModel expression to the value that the browser has set for the
* input element. For example, in the following input `<input type="range" ng-model="model.value">`,
* if the application sets `model.value = null`, the browser will set the input to `'50'`.
* Angular will then set the model to `50`, to prevent input and model value being out of sync.
*
* That means the model for range will immediately be set to `50` after `ngModel` has been
* initialized. It also means a range input can never have the required error.
*
* This does not only affect changes to the model value, but also to the values of the `min`,
* `max`, and `step` attributes. When these change in a way that will cause the browser to modify
* the input value, Angular will also update the model value.
*
* Automatic value adjustment also means that a range input element can never have the `required`,
* `min`, or `max` errors.
*
* However, `step` is currently only fully implemented by Firefox. Other browsers have problems
* when the step value changes dynamically - they do not adjust the element value correctly, but
* instead may set the `stepMismatch` error. If that's the case, the Angular will set the `step`
* error on the input, and set the model to `undefined`.
*
* Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do
* not set the `min` and `max` attributes, which means that the browser won't automatically adjust
* the input value based on their values, and will always assume min = 0, max = 100, and step = 1.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation to ensure that the value entered is greater
* than `min`. Can be interpolated.
* @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.
* Can be interpolated.
* @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`
* Can be interpolated.
* @param {string=} ngChange Angular expression to be executed when the ngModel value changes due
* to user interaction with the input element.
* @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the
* element. **Note** : `ngChecked` should not be used alongside `ngModel`.
* Checkout {@link ng.directive:ngChecked ngChecked} for usage.
*
* @example
<example name="range-input-directive" module="rangeExample">
<file name="index.html">
<script>
angular.module('rangeExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.value = 75;
$scope.min = 10;
$scope.max = 90;
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
Model as range: <input type="range" name="range" ng-model="value" min="{{min}}" max="{{max}}">
<hr>
Model as number: <input type="number" ng-model="value"><br>
Min: <input type="number" ng-model="min"><br>
Max: <input type="number" ng-model="max"><br>
value = <code>{{value}}</code><br/>
myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
myForm.range.$error = <code>{{myForm.range.$error}}</code>
</form>
</file>
</example>
* ## Range Input with ngMin & ngMax attributes
* @example
<example name="range-input-directive-ng" module="rangeExample">
<file name="index.html">
<script>
angular.module('rangeExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.value = 75;
$scope.min = 10;
$scope.max = 90;
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
Model as range: <input type="range" name="range" ng-model="value" ng-min="min" ng-max="max">
<hr>
Model as number: <input type="number" ng-model="value"><br>
Min: <input type="number" ng-model="min"><br>
Max: <input type="number" ng-model="max"><br>
value = <code>{{value}}</code><br/>
myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
myForm.range.$error = <code>{{myForm.range.$error}}</code>
</form>
</file>
</example>
*/
'range': rangeInputType,
/**
* @ngdoc input
* @name input[checkbox]
*
* @description
* HTML checkbox.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {expression=} ngTrueValue The value to which the expression should be set when selected.
* @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="checkbox-input-directive" module="checkboxExample">
<file name="index.html">
<script>
angular.module('checkboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.checkboxModel = {
value1 : true,
value2 : 'YES'
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Value1:
<input type="checkbox" ng-model="checkboxModel.value1">
</label><br/>
<label>Value2:
<input type="checkbox" ng-model="checkboxModel.value2"
ng-true-value="'YES'" ng-false-value="'NO'">
</label><br/>
<tt>value1 = {{checkboxModel.value1}}</tt><br/>
<tt>value2 = {{checkboxModel.value2}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should change state', function() {
var value1 = element(by.binding('checkboxModel.value1'));
var value2 = element(by.binding('checkboxModel.value2'));
expect(value1.getText()).toContain('true');
expect(value2.getText()).toContain('YES');
element(by.model('checkboxModel.value1')).click();
element(by.model('checkboxModel.value2')).click();
expect(value1.getText()).toContain('false');
expect(value2.getText()).toContain('NO');
});
</file>
</example>
*/
'checkbox': checkboxInputType,
'hidden': noop,
'button': noop,
'submit': noop,
'reset': noop,
'file': noop
};
function stringBasedInputType(ctrl) {
ctrl.$formatters.push(function(value) {
return ctrl.$isEmpty(value) ? value : value.toString();
});
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
}
function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var type = lowercase(element[0].type);
// In composition mode, users are still inputting intermediate text buffer,
// hold the listener until composition is done.
// More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
if (!$sniffer.android) {
var composing = false;
element.on('compositionstart', function() {
composing = true;
});
element.on('compositionend', function() {
composing = false;
listener();
});
}
var timeout;
var listener = function(ev) {
if (timeout) {
$browser.defer.cancel(timeout);
timeout = null;
}
if (composing) return;
var value = element.val(),
event = ev && ev.type;
// By default we will trim the value
// If the attribute ng-trim exists we will avoid trimming
// If input type is 'password', the value is never trimmed
if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
value = trim(value);
}
// If a control is suffering from bad input (due to native validators), browsers discard its
// value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
// control's value is the same empty value twice in a row.
if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
ctrl.$setViewValue(value, event);
}
};
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
element.on('input', listener);
} else {
var deferListener = function(ev, input, origValue) {
if (!timeout) {
timeout = $browser.defer(function() {
timeout = null;
if (!input || input.value !== origValue) {
listener(ev);
}
});
}
};
element.on('keydown', /** @this */ function(event) {
var key = event.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
deferListener(event, this, this.value);
});
// if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
if ($sniffer.hasEvent('paste')) {
element.on('paste cut', deferListener);
}
}
// if user paste into input using mouse on older browser
// or form autocomplete on newer browser, we need "change" event to catch it
element.on('change', listener);
// Some native input types (date-family) have the ability to change validity without
// firing any input/change events.
// For these event types, when native validators are present and the browser supports the type,
// check for validity changes on various DOM events.
if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {
if (!timeout) {
var validity = this[VALIDITY_STATE_PROPERTY];
var origBadInput = validity.badInput;
var origTypeMismatch = validity.typeMismatch;
timeout = $browser.defer(function() {
timeout = null;
if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
listener(ev);
}
});
}
});
}
ctrl.$render = function() {
// Workaround for Firefox validation #12102.
var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
if (element.val() !== value) {
element.val(value);
}
};
}
function weekParser(isoWeek, existingDate) {
if (isDate(isoWeek)) {
return isoWeek;
}
if (isString(isoWeek)) {
WEEK_REGEXP.lastIndex = 0;
var parts = WEEK_REGEXP.exec(isoWeek);
if (parts) {
var year = +parts[1],
week = +parts[2],
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 0,
firstThurs = getFirstThursdayOfYear(year),
addDays = (week - 1) * 7;
if (existingDate) {
hours = existingDate.getHours();
minutes = existingDate.getMinutes();
seconds = existingDate.getSeconds();
milliseconds = existingDate.getMilliseconds();
}
return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
}
}
return NaN;
}
function createDateParser(regexp, mapping) {
return function(iso, date) {
var parts, map;
if (isDate(iso)) {
return iso;
}
if (isString(iso)) {
// When a date is JSON'ified to wraps itself inside of an extra
// set of double quotes. This makes the date parsing code unable
// to match the date string and parse it as a date.
if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') {
iso = iso.substring(1, iso.length - 1);
}
if (ISO_DATE_REGEXP.test(iso)) {
return new Date(iso);
}
regexp.lastIndex = 0;
parts = regexp.exec(iso);
if (parts) {
parts.shift();
if (date) {
map = {
yyyy: date.getFullYear(),
MM: date.getMonth() + 1,
dd: date.getDate(),
HH: date.getHours(),
mm: date.getMinutes(),
ss: date.getSeconds(),
sss: date.getMilliseconds() / 1000
};
} else {
map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
}
forEach(parts, function(part, index) {
if (index < mapping.length) {
map[mapping[index]] = +part;
}
});
return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
}
}
return NaN;
};
}
function createDateInputType(type, regexp, parseDate, format) {
return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
badInputChecker(scope, element, attr, ctrl);
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
var timezone = ctrl && ctrl.$options.getOption('timezone');
var previousDate;
ctrl.$$parserName = type;
ctrl.$parsers.push(function(value) {
if (ctrl.$isEmpty(value)) return null;
if (regexp.test(value)) {
// Note: We cannot read ctrl.$modelValue, as there might be a different
// parser/formatter in the processing chain so that the model
// contains some different data format!
var parsedDate = parseDate(value, previousDate);
if (timezone) {
parsedDate = convertTimezoneToLocal(parsedDate, timezone);
}
return parsedDate;
}
return undefined;
});
ctrl.$formatters.push(function(value) {
if (value && !isDate(value)) {
throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
}
if (isValidDate(value)) {
previousDate = value;
if (previousDate && timezone) {
previousDate = convertTimezoneToLocal(previousDate, timezone, true);
}
return $filter('date')(value, format, timezone);
} else {
previousDate = null;
return '';
}
});
if (isDefined(attr.min) || attr.ngMin) {
var minVal;
ctrl.$validators.min = function(value) {
return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
};
attr.$observe('min', function(val) {
minVal = parseObservedDateValue(val);
ctrl.$validate();
});
}
if (isDefined(attr.max) || attr.ngMax) {
var maxVal;
ctrl.$validators.max = function(value) {
return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
};
attr.$observe('max', function(val) {
maxVal = parseObservedDateValue(val);
ctrl.$validate();
});
}
function isValidDate(value) {
// Invalid Date: getTime() returns NaN
return value && !(value.getTime && value.getTime() !== value.getTime());
}
function parseObservedDateValue(val) {
return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
}
};
}
function badInputChecker(scope, element, attr, ctrl) {
var node = element[0];
var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
if (nativeValidation) {
ctrl.$parsers.push(function(value) {
var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
return validity.badInput || validity.typeMismatch ? undefined : value;
});
}
}
function numberFormatterParser(ctrl) {
ctrl.$$parserName = 'number';
ctrl.$parsers.push(function(value) {
if (ctrl.$isEmpty(value)) return null;
if (NUMBER_REGEXP.test(value)) return parseFloat(value);
return undefined;
});
ctrl.$formatters.push(function(value) {
if (!ctrl.$isEmpty(value)) {
if (!isNumber(value)) {
throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
}
value = value.toString();
}
return value;
});
}
function parseNumberAttrVal(val) {
if (isDefined(val) && !isNumber(val)) {
val = parseFloat(val);
}
return !isNumberNaN(val) ? val : undefined;
}
function isNumberInteger(num) {
// See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066
// (minus the assumption that `num` is a number)
// eslint-disable-next-line no-bitwise
return (num | 0) === num;
}
function countDecimals(num) {
var numString = num.toString();
var decimalSymbolIndex = numString.indexOf('.');
if (decimalSymbolIndex === -1) {
if (-1 < num && num < 1) {
// It may be in the exponential notation format (`1e-X`)
var match = /e-(\d+)$/.exec(numString);
if (match) {
return Number(match[1]);
}
}
return 0;
}
return numString.length - decimalSymbolIndex - 1;
}
function isValidForStep(viewValue, stepBase, step) {
// At this point `stepBase` and `step` are expected to be non-NaN values
// and `viewValue` is expected to be a valid stringified number.
var value = Number(viewValue);
// Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or
// `0.5 % 0.1 !== 0`), we need to convert all numbers to integers.
if (!isNumberInteger(value) || !isNumberInteger(stepBase) || !isNumberInteger(step)) {
var decimalCount = Math.max(countDecimals(value), countDecimals(stepBase), countDecimals(step));
var multiplier = Math.pow(10, decimalCount);
value = value * multiplier;
stepBase = stepBase * multiplier;
step = step * multiplier;
}
return (value - stepBase) % step === 0;
}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
badInputChecker(scope, element, attr, ctrl);
numberFormatterParser(ctrl);
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
var minVal;
var maxVal;
if (isDefined(attr.min) || attr.ngMin) {
ctrl.$validators.min = function(value) {
return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
};
attr.$observe('min', function(val) {
minVal = parseNumberAttrVal(val);
// TODO(matsko): implement validateLater to reduce number of validations
ctrl.$validate();
});
}
if (isDefined(attr.max) || attr.ngMax) {
ctrl.$validators.max = function(value) {
return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
};
attr.$observe('max', function(val) {
maxVal = parseNumberAttrVal(val);
// TODO(matsko): implement validateLater to reduce number of validations
ctrl.$validate();
});
}
if (isDefined(attr.step) || attr.ngStep) {
var stepVal;
ctrl.$validators.step = function(modelValue, viewValue) {
return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
isValidForStep(viewValue, minVal || 0, stepVal);
};
attr.$observe('step', function(val) {
stepVal = parseNumberAttrVal(val);
// TODO(matsko): implement validateLater to reduce number of validations
ctrl.$validate();
});
}
}
function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {
badInputChecker(scope, element, attr, ctrl);
numberFormatterParser(ctrl);
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',
minVal = supportsRange ? 0 : undefined,
maxVal = supportsRange ? 100 : undefined,
stepVal = supportsRange ? 1 : undefined,
validity = element[0].validity,
hasMinAttr = isDefined(attr.min),
hasMaxAttr = isDefined(attr.max),
hasStepAttr = isDefined(attr.step);
var originalRender = ctrl.$render;
ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?
//Browsers that implement range will set these values automatically, but reading the adjusted values after
//$render would cause the min / max validators to be applied with the wrong value
function rangeRender() {
originalRender();
ctrl.$setViewValue(element.val());
} :
originalRender;
if (hasMinAttr) {
ctrl.$validators.min = supportsRange ?
// Since all browsers set the input to a valid value, we don't need to check validity
function noopMinValidator() { return true; } :
// non-support browsers validate the min val
function minValidator(modelValue, viewValue) {
return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;
};
setInitialValueAndObserver('min', minChange);
}
if (hasMaxAttr) {
ctrl.$validators.max = supportsRange ?
// Since all browsers set the input to a valid value, we don't need to check validity
function noopMaxValidator() { return true; } :
// non-support browsers validate the max val
function maxValidator(modelValue, viewValue) {
return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;
};
setInitialValueAndObserver('max', maxChange);
}
if (hasStepAttr) {
ctrl.$validators.step = supportsRange ?
function nativeStepValidator() {
// Currently, only FF implements the spec on step change correctly (i.e. adjusting the
// input element value to a valid value). It's possible that other browsers set the stepMismatch
// validity error instead, so we can at least report an error in that case.
return !validity.stepMismatch;
} :
// ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would
function stepValidator(modelValue, viewValue) {
return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
isValidForStep(viewValue, minVal || 0, stepVal);
};
setInitialValueAndObserver('step', stepChange);
}
function setInitialValueAndObserver(htmlAttrName, changeFn) {
// interpolated attributes set the attribute value only after a digest, but we need the
// attribute value when the input is first rendered, so that the browser can adjust the
// input value based on the min/max value
element.attr(htmlAttrName, attr[htmlAttrName]);
attr.$observe(htmlAttrName, changeFn);
}
function minChange(val) {
minVal = parseNumberAttrVal(val);
// ignore changes before model is initialized
if (isNumberNaN(ctrl.$modelValue)) {
return;
}
if (supportsRange) {
var elVal = element.val();
// IE11 doesn't set the el val correctly if the minVal is greater than the element value
if (minVal > elVal) {
elVal = minVal;
element.val(elVal);
}
ctrl.$setViewValue(elVal);
} else {
// TODO(matsko): implement validateLater to reduce number of validations
ctrl.$validate();
}
}
function maxChange(val) {
maxVal = parseNumberAttrVal(val);
// ignore changes before model is initialized
if (isNumberNaN(ctrl.$modelValue)) {
return;
}
if (supportsRange) {
var elVal = element.val();
// IE11 doesn't set the el val correctly if the maxVal is less than the element value
if (maxVal < elVal) {
element.val(maxVal);
// IE11 and Chrome don't set the value to the minVal when max < min
elVal = maxVal < minVal ? minVal : maxVal;
}
ctrl.$setViewValue(elVal);
} else {
// TODO(matsko): implement validateLater to reduce number of validations
ctrl.$validate();
}
}
function stepChange(val) {
stepVal = parseNumberAttrVal(val);
// ignore changes before model is initialized
if (isNumberNaN(ctrl.$modelValue)) {
return;
}
// Some browsers don't adjust the input value correctly, but set the stepMismatch error
if (supportsRange && ctrl.$viewValue !== element.val()) {
ctrl.$setViewValue(element.val());
} else {
// TODO(matsko): implement validateLater to reduce number of validations
ctrl.$validate();
}
}
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
// Note: no badInputChecker here by purpose as `url` is only a validation
// in browsers, i.e. we can always read out input.value even if it is not valid!
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
ctrl.$$parserName = 'url';
ctrl.$validators.url = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
};
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
// Note: no badInputChecker here by purpose as `url` is only a validation
// in browsers, i.e. we can always read out input.value even if it is not valid!
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
ctrl.$$parserName = 'email';
ctrl.$validators.email = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
};
}
function radioInputType(scope, element, attr, ctrl) {
var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false';
// make the name unique, if not defined
if (isUndefined(attr.name)) {
element.attr('name', nextUid());
}
var listener = function(ev) {
var value;
if (element[0].checked) {
value = attr.value;
if (doTrim) {
value = trim(value);
}
ctrl.$setViewValue(value, ev && ev.type);
}
};
element.on('click', listener);
ctrl.$render = function() {
var value = attr.value;
if (doTrim) {
value = trim(value);
}
element[0].checked = (value === ctrl.$viewValue);
};
attr.$observe('value', ctrl.$render);
}
function parseConstantExpr($parse, context, name, expression, fallback) {
var parseFn;
if (isDefined(expression)) {
parseFn = $parse(expression);
if (!parseFn.constant) {
throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
'`{1}`.', name, expression);
}
return parseFn(context);
}
return fallback;
}
function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
var listener = function(ev) {
ctrl.$setViewValue(element[0].checked, ev && ev.type);
};
element.on('click', listener);
ctrl.$render = function() {
element[0].checked = ctrl.$viewValue;
};
// Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
// This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
// it to a boolean.
ctrl.$isEmpty = function(value) {
return value === false;
};
ctrl.$formatters.push(function(value) {
return equals(value, trueValue);
});
ctrl.$parsers.push(function(value) {
return value ? trueValue : falseValue;
});
}
/**
* @ngdoc directive
* @name textarea
* @restrict E
*
* @description
* HTML textarea element control with angular data-binding. The data-binding and validation
* properties of this element are exactly the same as those of the
* {@link ng.directive:input input element}.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
* length.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
* does not match a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
*
* @knownIssue
*
* When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily
* insert the placeholder value as the textarea's content. If the placeholder value contains
* interpolation (`{{ ... }}`), an error will be logged in the console when Angular tries to update
* the value of the by-then-removed text node. This doesn't affect the functionality of the
* textarea, but can be undesirable.
*
* You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of
* `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can
* find more details on `ngAttr` in the
* [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the
* Developer Guide.
*/
/**
* @ngdoc directive
* @name input
* @restrict E
*
* @description
* HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
* input state control, and validation.
* Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
*
* <div class="alert alert-warning">
* **Note:** Not every feature offered is available for all input types.
* Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
* </div>
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {boolean=} ngRequired Sets `required` attribute if set to true
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
* length.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
* value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
* This parameter is ignored for input[type=password] controls, which will never trim the
* input.
*
* @example
<example name="input-directive" module="inputExample">
<file name="index.html">
<script>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}]);
</script>
<div ng-controller="ExampleController">
<form name="myForm">
<label>
User name:
<input type="text" name="userName" ng-model="user.name" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span>
</div>
<label>
Last name:
<input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
</label>
<div role="alert">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span>
</div>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
<tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
</div>
</file>
<file name="protractor.js" type="protractor">
var user = element(by.exactBinding('user'));
var userNameValid = element(by.binding('myForm.userName.$valid'));
var lastNameValid = element(by.binding('myForm.lastName.$valid'));
var lastNameError = element(by.binding('myForm.lastName.$error'));
var formValid = element(by.binding('myForm.$valid'));
var userNameInput = element(by.model('user.name'));
var userLastInput = element(by.model('user.last'));
it('should initialize to model', function() {
expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
expect(userNameValid.getText()).toContain('true');
expect(formValid.getText()).toContain('true');
});
it('should be invalid if empty when required', function() {
userNameInput.clear();
userNameInput.sendKeys('');
expect(user.getText()).toContain('{"last":"visitor"}');
expect(userNameValid.getText()).toContain('false');
expect(formValid.getText()).toContain('false');
});
it('should be valid if empty when min length is set', function() {
userLastInput.clear();
userLastInput.sendKeys('');
expect(user.getText()).toContain('{"name":"guest","last":""}');
expect(lastNameValid.getText()).toContain('true');
expect(formValid.getText()).toContain('true');
});
it('should be invalid if less than required min length', function() {
userLastInput.clear();
userLastInput.sendKeys('xx');
expect(user.getText()).toContain('{"name":"guest"}');
expect(lastNameValid.getText()).toContain('false');
expect(lastNameError.getText()).toContain('minlength');
expect(formValid.getText()).toContain('false');
});
it('should be invalid if longer than max length', function() {
userLastInput.clear();
userLastInput.sendKeys('some ridiculously long name');
expect(user.getText()).toContain('{"name":"guest"}');
expect(lastNameValid.getText()).toContain('false');
expect(lastNameError.getText()).toContain('maxlength');
expect(formValid.getText()).toContain('false');
});
</file>
</example>
*/
var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
function($browser, $sniffer, $filter, $parse) {
return {
restrict: 'E',
require: ['?ngModel'],
link: {
pre: function(scope, element, attr, ctrls) {
if (ctrls[0]) {
(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
$browser, $filter, $parse);
}
}
}
};
}];
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
/**
* @ngdoc directive
* @name ngValue
*
* @description
* Binds the given expression to the value of the element.
*
* It is mainly used on {@link input[radio] `input[radio]`} and option elements,
* so that when the element is selected, the {@link ngModel `ngModel`} of that element (or its
* {@link select `select`} parent element) is set to the bound value. It is especially useful
* for dynamically generated lists using {@link ngRepeat `ngRepeat`}, as shown below.
*
* It can also be used to achieve one-way binding of a given expression to an input element
* such as an `input[text]` or a `textarea`, when that element does not use ngModel.
*
* @element input
* @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
* and `value` property of the element.
*
* @example
<example name="ngValue-directive" module="valueExample">
<file name="index.html">
<script>
angular.module('valueExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.names = ['pizza', 'unicorns', 'robots'];
$scope.my = { favorite: 'unicorns' };
}]);
</script>
<form ng-controller="ExampleController">
<h2>Which is your favorite?</h2>
<label ng-repeat="name in names" for="{{name}}">
{{name}}
<input type="radio"
ng-model="my.favorite"
ng-value="name"
id="{{name}}"
name="favorite">
</label>
<div>You chose {{my.favorite}}</div>
</form>
</file>
<file name="protractor.js" type="protractor">
var favorite = element(by.binding('my.favorite'));
it('should initialize to model', function() {
expect(favorite.getText()).toContain('unicorns');
});
it('should bind the values to the inputs', function() {
element.all(by.model('my.favorite')).get(0).click();
expect(favorite.getText()).toContain('pizza');
});
</file>
</example>
*/
var ngValueDirective = function() {
/**
* inputs use the value attribute as their default value if the value property is not set.
* Once the value property has been set (by adding input), it will not react to changes to
* the value attribute anymore. Setting both attribute and property fixes this behavior, and
* makes it possible to use ngValue as a sort of one-way bind.
*/
function updateElementValue(element, attr, value) {
element.prop('value', value);
attr.$set('value', value);
}
return {
restrict: 'A',
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function ngValueConstantLink(scope, elm, attr) {
var value = scope.$eval(attr.ngValue);
updateElementValue(elm, attr, value);
};
} else {
return function ngValueLink(scope, elm, attr) {
scope.$watch(attr.ngValue, function valueWatchAction(value) {
updateElementValue(elm, attr, value);
});
};
}
}
};
};
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h5.47L13 7v1h4V5.33C17 4.6 16.4 4 15.67 4z" /><path d="M13 12.5h2L11 20v-5.5H9L12.47 8H7v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8h-4v4.5z" /></g></React.Fragment>
, 'BatteryCharging90TwoTone');
|
import errors from 'restify-errors'
import joi from 'joi'
import User from '../models/user'
import logger from '../lib/logger'
import { send200, send201, send400, send500 } from '../lib/rest-helper'
async function get(req, res, next) {
let data
const inputSchema = joi
.object({
locnNbr: joi.number().integer().required(),
itemBrcd: joi.string().required(),
})
.unknown()
.required()
try {
const input = {
locnNbr: req.query.locnNbr,
itemBrcd: req.query.itemBrcd,
}
joi.attempt(input, inputSchema)
data = await User.read(input)
send200(res, next, data)
} catch (err) {
logger.error(err)
send500(res, next, new errors.InternalServerError())
}
}
async function post(req, res, next) {
let result
const inputSchema = joi
.object({
locnNbr: joi.number().integer().required(),
itemBrcd: joi.string().required(),
})
.unknown()
.required()
try {
res.setHeader('Content-Type', req.contentType())
const data = req.body
joi.attempt(data, inputSchema)
result = await User.insert(data)
send201(res, next, result)
} catch (err) {
logger.error(err)
send400(res, next, new errors.InvalidContentError())
}
}
function error(req, res, next) {
try {
throw new errors.RestError('This is expected')
} catch (err) {
logger.error(err)
send400(res, next, err)
}
}
export default { get, post, error }
|
const DrawCard = require('../../../drawcard.js');
class Lady extends DrawCard {
setupCardAbilities(ability) {
this.whileAttached({
effect: ability.effects.modifyStrength(2)
});
this.action({
title: 'Pay 1 gold to attach Lady to another character',
method: 'reAttach',
limit: ability.limit.perPhase(1)
});
}
reAttach(player) {
this.oldOwner = this.parent;
if(!this.oldOwner || this.controller.gold < 1) {
return false;
}
player.moveCard(this, 'play area');
this.game.promptForSelect(this.controller, {
cardCondition: card => this.canAttach(player, card) && card.location === 'play area',
activePromptTitle: 'Select a different character for attachment',
waitingPromptTitle: 'Waiting for opponent to move attachment',
onSelect: (player, card) => this.moveAttachment(player, card)
});
return true;
}
canAttach(player, card) {
if(card.getType() !== 'character' || !card.isFaction('stark') || card === this.oldOwner) {
return false;
}
return super.canAttach(player, card);
}
moveAttachment(player, newOwner) {
var targetPlayer = this.game.getPlayerByName(newOwner.controller.name);
targetPlayer.attach(player, this, newOwner.uuid);
player.gold -= 1;
if(newOwner.name === 'Sansa Stark' && newOwner.kneeled) {
player.standCard(newOwner);
this.game.addMessage('{0} pays 1 gold to attach {1} from {2} to {3} and then stands {3}', player, this, this.oldOwner, newOwner);
} else {
this.game.addMessage('{0} pays 1 gold to attach {1} from {2} to {3}', player, this, this.oldOwner, newOwner);
}
this.oldOwner = null;
return true;
}
}
Lady.code = '02004';
module.exports = Lady;
|
/**
* @class AccessProfile
* @classdesc The AccessProfile class has been added to the DOCUMENTS PortalScripting API to gain full access to the DOCUMENTS access profiles by scripting means.
* A SystemUser can be assigned to an AccessProfile. At the filetype it is possible to define several rights depending on the AccessProfile. You can get an AccessProfile object by different methods like Context.findAccessProfile(String ProfileName) or from the AccessProfileIterator.
* @since ELC 3.50b / otrisPORTAL 5.0b
* @summary With the new method is it possible to create a new AccessProfile.
* @description If an access profile with the profile name already exist, the method return the existing access profile.
* Since ELC 3.50b / otrisPORTAL 5.0b
* @param {string} nameAccessProfile
* @deprecated since ELC 3.60i / otrisPORTAL 6.0i use Context.createAccessProfile() instead
* @example
* var newAP = new AccessProfile("supportteam");
* if (!newAP)
* util.out("Creation of AccessProfile failed.");
*/
/**
* @memberof AccessProfile
* @summary The technical name of the AccessProfile.
* @member {string} name
* @instance
* @since ELC 3.50b / otrisPORTAL 5.0b
* @example
* var su = context.getSystemUser(); // current user
* if (su)
* {
* var apIter = su.getAccessProfiles();
* for (var ap = apIter.first(); ap; ap = apIter.next())
* {
* util.out(ap.name);
* }
* }
**/
/**
* @memberof AccessProfile
* @summary Access to the property cache of the AccessProfile.
* @member {PropertyCache} propCache
* @instance
* @since DOCUMENTS 5.0
* @see [PropertyCache,SystemUser.propCache]{@link PropertyCache,SystemUser#propCache}
* @example
* var ap = context.findAccessProfile("Everybody");
* if (!ap.propCache.hasProperty("Contacts"))
* {
* util.out("Creating cache");
* ap.propCache.Contacts = ["Peter", "Paul", "Marry"];
* }
**/
/**
* @memberof AccessProfile
* @function addCustomProperty
* @instance
* @summary Creates a new CustomProperty for the AccessProfile.
* @param {string} name String value defining the name
* @param {string} type String value defining the type
* @param {string} value String value defining the value
* @returns {CustomProperty} CustomProperty
* @since DOCUMENTS 5.0
* @see [AccessProfile.setOrAddCustomProperty]{@link AccessProfile#setOrAddCustomProperty}
* @see [AccessProfile.getCustomProperties]{@link AccessProfile#getCustomProperties}
* @example
* var office = context.findAccessProfile("office");
* if (!office) throw "office is null";
*
* var custProp = office.addCustomProperty("favorites", "string", "peachit");
* if (!custProp)
* util.out(office.getLastError());
**/
/**
* @memberof AccessProfile
* @function getAttribute
* @instance
* @summary Get the String value of an attribute of the AccessProfile.
* @description
* Note: This function is only for experts. Knowledge about the ELC-database schema is necessary!
* @param {string} attribute String containing the name of the desired attribute
* @returns {string} String containing the value of the desired attribute
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof AccessProfile
* @function getCustomProperties
* @instance
* @summary Get a CustomPropertyIterator with custom properties of the current AccessProfile.
* @param {string} [nameFilter] String value defining an optional filter depending on the name
* @param {string} [typeFilter] String value defining an optional filter depending on the type
* @returns {CustomPropertyIterator} CustomPropertyIterator
* @since DOCUMENTS 5.0
* @see [context.findCustomProperties]{@link context#findCustomProperties}
* @see [AccessProfile.setOrAddCustomProperty]{@link AccessProfile#setOrAddCustomProperty}
* @see [AccessProfile.addCustomProperty]{@link AccessProfile#addCustomProperty}
* @example
* var office = context.findAccessProfile("office");
* if (!office) throw "office is null";
*
* var itProp = office.getCustomProperties();
* for (var prop = itProp.first(); prop; prop = itProp.next())
* {
* util.out(prop.name + ": " + prop.value);
* }
**/
/**
* @memberof AccessProfile
* @function getLastError
* @instance
* @summary If you call a method at an AccessProfile object and an error occurred, you can get the error description with this function.
* @returns {string} Text of the last error as String
* @since ELC 3.50b / otrisPORTAL 5.0b
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof AccessProfile
* @function getOID
* @instance
* @summary Returns the object-id.
* @description
* Since DOCUMENTS 5.0 (new parameter oidLow)
* @param {boolean} [oidLow] Optional flag:
* If <code>true</code> only the id of the filetype object (<code>m_oid</code>) will be returned.
* If <code>false</code> the id of the filetype object will be returned together with the id of the corresponding class in the form <code>class-id:m_oid</code>.
* The default value is <code>false</code>.
* @returns {string} <code>String</code> with the object-id
* @since ELC 3.60c / otrisPORTAL 6.0c
**/
/**
* @memberof AccessProfile
* @function getSystemUsers
* @instance
* @summary Retrieve a list of desired SystemUser which are assigned to the current AccessProfile.
* @description
* Since DOCUMENTS 5.0c HF2 (new parameters includeLockedUsers and includeInvisibleUsers)
* @param {boolean} [includeLockedUsers] Optional flag indicating whether locked users also should be returned. The default value is <code>true</code>.
* @param {boolean} [includeInvisibleUsers] Optional flag indicating whether the method also should return users for which the option "Display user in DOCUMENTS lists" in the Documents Manager is not checkmarked. The default value is <code>true</code>.
* @returns {SystemUserIterator} SystemUserIterator containing a list of SystemUser
* @since ELC 3.51e / otrisPORTAL 5.1e
* @example
* var ap = context.findAccessProfile("supportteam");
* if (ap)
* {
* var itSU = ap.getSystemUsers();
* for (var su = itSU.first(); su; su = itSU.next())
* util.out(su.login);
* }
* else
* util.out("AccessProfile does not exist.");
**/
/**
* @memberof AccessProfile
* @function setAttribute
* @instance
* @summary Set the String value of an attribute of the AccessProfile to the desired value.
* @description
* Note: This function is only for experts. Knowledge about the ELC-database schema is necessary!
* @param {string} attribute String containing the name of the desired attribute
* @param {string} value String containing the desired value of the attribute
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof AccessProfile
* @function setOrAddCustomProperty
* @instance
* @summary Creates a new CustomProperty or modifies a CustomProperty according the name and type for the AccessProfile.
* @description This method creates or modifies a unique CustomProperty for the AccessProfile. The combination of the name and the type make the CustomProperty unique for the AccessProfile.
* @param {string} name String value defining the name
* @param {string} type String value defining the type
* @param {string} value String value defining the value
* @returns {CustomProperty} CustomProperty
* @since DOCUMENTS 5.0
* @see [AccessProfile.getCustomProperties]{@link AccessProfile#getCustomProperties}
* @see [AccessProfile.addCustomProperty]{@link AccessProfile#addCustomProperty}
* @example
* var office = context.findAccessProfile("office");
* if (!office) throw "office is null";
*
* var custProp = office.setOrAddCustomProperty("favorites", "string", "peachit");
* if (!custProp)
* util.out(office.getLastError());
**/
/**
* @memberof AccessProfile
* @function setParentProfile
* @instance
* @summary Set the parent profile of the current profile.
* @param {AccessProfile} parentProfile optional AccessProfile object being the parent profile of the current profile. If no parent profile is defined, the current profile will be moved to the top level.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 5.0d
* @example
* var parentProfile = context.createAccessProfile("parentProfile");
* if (parentProfile)
* {
* var subProfile = context.createAccessProfile("subProfile");
* if (subProfile)
* {
* var success = subProfile.setParentProfile(parentProfile);
* if (!success)
* util.out(subProfile.getLastError());
*
* // We can move subProfile to the top level as follows:
* success = subProfile.setParentProfile();
* }
* }
**/
/**
* @interface AccessProfileIterator
* @summary The AccessProfileIterator class has been added to the DOCUMENTS PortalScripting API to gain full access to the DOCUMENTS access profiles by scripting means.
* @description The objects of this class represent lists of AccessProfile objects and allow to loop through such a list of profiles. The following methods return an AccessProfileIterator: Context.getAccessProfiles(), SystemUser.getAccessProfiles().
* @since ELC 3.50b / otrisPORTAL 5.0b
* @example
* // take a certain Systemuser object (stored in user) and assign all availabe
* // accessprofiles to this user
* var itRoles = context.getAccessProfiles();
* if (itRoles && itRoles.size() > 0)
* {
* for (var ap = itRoles.first(); ap; ap = itRoles.next())
* {
* user.addToAccessProfile(ap); // add user to profile
* }
* }
*/
/**
* @memberof AccessProfileIterator
* @function first
* @instance
* @summary Retrieve the first AccessProfile object in the AccessProfileIterator.
* @returns {AccessProfile} AccessProfile or <code>null</code> in case of an empty AccessProfileIterator
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof AccessProfileIterator
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since ELC 3.50b / otrisPORTAL 5.0b
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof AccessProfileIterator
* @function next
* @instance
* @summary Retrieve the next AccessProfile object in the AccessProfileIterator.
* @returns {AccessProfile} AccessProfile or <code>null</code> if end of AccessProfileIterator is reached.
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof AccessProfileIterator
* @function size
* @instance
* @summary Get the amount of AccessProfile objects in the AccessProfileIterator.
* @returns {number} integer value with the amount of AccessProfile objects in the AccessProfileIterator
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @interface ArchiveConnection
* @summary The ArchiveConnection class allows low level access to the EAS Interface, EBIS and the EASY ENTERPRISE XML-Server.
*/
/**
* @memberof ArchiveConnection
* @summary String value containing the version of the archive interface.
* @member {string} id
* @instance
* @since ELC 3.60h / otrisPORTAL 6.0h
**/
/**
* @memberof ArchiveConnection
* @function downloadBlob
* @instance
* @summary Download an attachment from the XML-Server.
* @description With this method you can download an attachment from the EASYWARE ENTERPRISE archive using the XML-Server. The method returns an object of the class <code>ArchiveConnectionBlob</code>. This object allows you to access the attachment. If the method fails the return value is NULL. You can retrieve the error message by executing <code>ArchiveConnection.getLastError()</code>.
* Note: Method is only available for EE.x using XML-Server
* @param {string} fileKey String containing the key of the file
* @param {string} docKey String containing the key of the attachment
* @returns {ArchiveConnectionBlob} <code>ArchiveConnectionBlob</code> or <code>NULL</code>, if failed
* @since ELC 3.60h / otrisPORTAL 6.0h
* @example
* var xmlserver = context.getArchiveConnection();
* if (xmlserver)
* {
* var fileKey = "Unit=Default/Instance=Default/Pool=DEMO/Pool=RECHNUNGEN/Document=RECHNUNGEN.41D3694E2B1E11DD8A9A000C29FACDC2"
* var docKey = "41D3695F2B1E11DD8A9A000C29FACDC2"
* var path = xmlserver.downloadBlob(fileKey, docKey);
* if (!res)
* util.out(xmlserver.getLastError());
* else
* util.out(res.localPath)
* }
**/
/**
* @memberof ArchiveConnection
* @function downloadBlobs
* @instance
* @summary Download multiple attachments from the XML-Server.
* @description This method allows downloading multiple attachments from the EASYWARE ENTERPRISE archive using the XML-Server. The method returns an object of the class <code>ArchiveConnectionBlobIterator</code>. This object allows you to access the attachments. If the method fails the return value is NULL. You can retrieve the error message by executing <code>ArchiveConnection.getLastError()</code>.
* Note: Method is only available for EE.x using XML-Server
* @param {string} fileKey String Array containing the keys of the files
* @param {string} docKey String Array containing the keys of the attachments
* @returns {ArchiveConnectionBlobIterator} <code>ArchiveConnectionBlobIterator</code> or <code>NULL</code>, if failed
* @since ELC 3.60h / otrisPORTAL 6.0h
* @example
* var fileKeys = new Array();
* var docKeys = new Array();
*
* var fileKey1 = "Unit=Default/Instance=Defaul...";
* var docKey1 = "41D3695F2B1E11DD8A9A000C29FACDC2";
* var fileKey2 = "Unit=Default/Instance=Defaul...";
* var docKey2 = "28CDB49ECE1B11DB9FC3000C29FACDC2";
*
* fileKeys[0] = fileKey1;
* docKeys[0] = docKey1;
* fileKeys[1] = fileKey2;
* docKeys[1] = docKey2;
*
* var itArchDoc = xmlserver.downloadBlobs(fileKeys, docKeys);
* if (!itArchDoc)
* {
* util.out(xmlserver.getLastError())
* return -1;
* }
*
* for (var archDoc=itArchDoc.first(); archDoc; archDoc=itArchDoc.next())
* {
* util.out(archDoc.name);
* util.out(archDoc.localPath);
* }
**/
/**
* @memberof ArchiveConnection
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since ELC 3.60h / otrisPORTAL 6.0h
**/
/**
* @memberof ArchiveConnection
* @function putBlob
* @instance
* @summary Upload an attachment to the XML-Server.
* @description This method performs a "putblob" request to an installed EASY XML-Server.
*
* Note: You may use util.getUniqueId() to create a blobreference. However this may be not unique enough, if several portal servers are connected to the same XML-server in this way.
* Note: Method is only available for EE.x using XML-Server
* @param {Document} doc
* @param {string} blobreference
* @returns {boolean}
* @since ELC 3.60h / otrisPORTAL 6.0h
* @example
* var xmlserver = context.getArchiveConnection();
* if (!xmlserver)
* throw "Error: no ArchiveConnection"
*
* // Create a unique id as BlobReference for the upload
* var blobRef = util.getUniqueId();
*
* // take a Document object and upload it to the ArchiveConnection
* if (!xmlserver.putBlob(doc, blobRef))
* throw "Upload failed";
*
* // Now the blobRef can be used e.g. for an IMPORT request
**/
/**
* @memberof ArchiveConnection
* @function queryRawEEx
* @instance
* @summary Sends a query EQL to the EE.x XML-Server and returns the response XML.
* @description With this method you can send a query EQL to the XML-Server of EASY ENTERPRISE.x If the method succeed the return value is the response-xml, otherwise it returns NULL. If the value is NULL you can retrieve the error message by executing ArchiveConnection.getLastError()
* Note: Method is only available for EE.x using XML-Server
* @param {string} eql String containing the EQL
* @param {number} [wantedHits] Int with the number of currently wanted hits (optional)
* @param {number} [maxHits] Int with the max. number of hits, that the ArchiveConnection should respond (optional)
* @returns {string} String with the response (xml) or NULL in case of any error
* @since ELC 3.60h / otrisPORTAL 6.0h
* @example
* var xmlserver = context.getArchiveConnection();
* if (xmlserver)
* {
* var eql = "SELECT @Finance.Type FROM @Finance WHERE isnewestversion(FIBU) ORDER BY FIBU.BUCHUNGSTYP ASC";
* var res = xmlserver.queryRawEEx(eql);
* if (!res)
* util.out(xmlserver.getLastError());
* else
* util.out(res);
* }
**/
/**
* @memberof ArchiveConnection
* @function sendEbisRequest
* @instance
* @summary Sends a request to the EBIS interface and returns the response.
* @description With this method you can send a GET or a POST request to an EBIS interface. If the request succeeds, the return value is the HTTP-content of the response. Otherwise the function returns an empty String. Call ArchiveConnection.getLastError() subsequently to test for eventual errors. If the interface reports an error, it will be prefixed with "[EBIS] ".
* Note: The function is unable to handle a response with binary data. The function does not check the parameters for illegal characters, such as linefeeds in the extraHeaders, for example.
* Note: Method is only available for EBIS
* @param {string} resourceIdentifier String containing the REST resource identifier (in other words: the back part of the URL).
* @param {string} [postData] A optional String with content data of a HTTP-POST request. If the parameter is missing or empty, the function generates a GET request.
* @param {string[]} [extraHeaders] A optional Array of Strings with an even number of elements. The first element of each pair must contain the name, the second one the value of an additional HTTP header element.
* @returns {string} A String with the response. This may be an XML or plain text. It depends on the request.
* @since DOCUMENTS 5.0a
* @example
* //
* // Example for GET
* //
* var ebisConn = context.getArchiveConnection("ebisStore1");
* if (ebisConn)
* {
* var factoryInfo = ebisConn.sendEbisRequest("/factory");
* var eText = ebisConn.getLastError();
* if(eText == "")
* util.out(factoryInfo);
* else
* util.out(eText);
* }
*
*
* //
* // Example for POST (do a query on EBIS with JSON)
* //
* var req = {};
* req.maxHits = 250;
* req.pageSize = 20;
* req.unformattedResult = true;
* req.includeTextmarkers = true;
*
* // search sources
* req.sources = ["Unit=Default/Instance=Default/View=Store01"];
*
* // hitlist fields
* req.fields = [];
* req.fields.push({field: "TITLE", sort: "NONE"})
* req.fields.push({field: "MODIFIED_DATE", sort: "NONE"})
* req.fields.push({field: "_type", sort: "NONE"})
*
* // search condition: all files of filetype "Simple"
* req.conditions = {};
* req.conditions.type = "set";
* req.conditions.conditions = [{type : "compare", field : "_type", value : "Simple", or : true, not : false}];
*
* var json = JSON.stringify(req);
*
* var archiveServer = context.getArchiveServer("ebisStore1");
* var ebisConn = archiveServer.getArchiveConnection();
*
* var headers = ["Content-Type", "application/json"];
* var res = ebisConn.sendEbisRequest("/search", json, headers);
* util.out(res);
*
* => EBIS returns query id { id : "8c31d9352240a1c507d8d5f163e49085", columns : [ ], infos : [ ], executed : false }
**/
/**
* @memberof ArchiveConnection
* @function sendRequest
* @instance
* @summary Sends a request to the ArchiveConnection and returns the response XML.
* @description With this method you can send a request to the XML-Server of EASY ENTERPRISE. If the method succeeds the return value is the response-xml, otherwise it returns NULL. If the value is NULL you can retrieve the error message by executing ArchiveConnection.getLastError()
* Note: Method is only available for EE.x using XML-Server
* @param {string} request String containing the request
* @returns {string} an String with the response (xml) or NULL in case of any error
* @since ELC 3.60h / otrisPORTAL 6.0h
* @example
* var xmlserver = context.getArchiveConnection();
* if (xmlserver)
* {
* var req = "<INFO REQUESTID=\"1\"/>";
* var res = xmlserver.sendRequest(req);
* if (!res)
* util.out(xmlserver.getLastError());
* else
* util.out(res);
* }
**/
/**
* @interface ArchiveConnectionBlob
* @summary The ArchiveConnectionBlob class provides access to each single attachment of files in the archive.
* @description This class holds data like name, extension, size etc. of attachments in the archive. The existance of an object means, that an attachment exists in the archive. If you want to access the attachment (blob) itself in the PortalServer, you have to download the attachment from the archive with the <code>ArchiveConnectionBlob.download()</code> method. Then the attachment will be transferred to the PortalServer machine (localPath).
* Note: You can not create objects of this class. Objects of this class are available only as return value of other functions, e.g. ArchiveConnection.downloadBlob(String fileKey, String docKey).
* Note: Class is only available for an ArchiceConnection to a XML-Server
* @since ELC 3.60i / otrisPORTAL 6.0i available for archive files
*/
/**
* @memberof ArchiveConnectionBlob
* @summary Integer containing the filesize of an attachment in the archive.
* @description This property contains the filesize of the attachment in bytes (83605).
*
* @member {number} bytes
* @instance
* @example
* ....
* var archDoc = xmlserver.downloadBlob(....);
* util.out(archDoc.bytes);
**/
/**
* @memberof ArchiveConnectionBlob
* @summary String containing the key of the attachment in the archive.
* @member {string} docKey
* @instance
* @example
* ....
* var archDoc = xmlserver.downloadBlob(....);
* util.out(archDoc.docKey);
**/
/**
* @memberof ArchiveConnectionBlob
* @summary boolean that indicates whether an attachment of the archive is locally available at the PortalServer.
* @description If the attachment in the archive is locally available at the PortalServer's file system, this value is <code>true</code>.
*
* @member {boolean} downloaded
* @instance
* @example
* ....
* var archDoc = ...
* if (archDoc.downloaded)
* util.out(archDoc.localPath);
**/
/**
* @memberof ArchiveConnectionBlob
* @summary String containing the key of the file the attachment belongs to in the archive.
* @member {string} fileKey
* @instance
* @example
* ....
* var archDoc = xmlserver.downloadBlob(....);
* util.out(archDoc.fileKey);
**/
/**
* @memberof ArchiveConnectionBlob
* @summary String with the local path to the attachment (blob).
* @description This path is only available if the attribute <code>ArchiveConnectionBlob.downloaded</code> is <code>true</code>
*
* @member {string} localPath
* @instance
* @example
* ....
* var archDoc = ...
* if (archDoc.downloaded)
* util.out(archDoc.localPath);
**/
/**
* @memberof ArchiveConnectionBlob
* @summary String containing the mime-type of an attachment in the archive.
* @description This property contains the mime-type of the attachment, e.g image/jpeg.
*
* @member {string} mimeType
* @instance
* @example
* ....
* var archDoc = xmlserver.downloadBlob(....);
* util.out(archDoc.mimeType);
**/
/**
* @memberof ArchiveConnectionBlob
* @summary String containing the name of the attachment in the archive.
* @member {string} name
* @instance
* @example
* ....
* var archDoc = xmlserver.downloadBlob(....);
* util.out(archDoc.name);
**/
/**
* @memberof ArchiveConnectionBlob
* @summary String containing the filesize of an attachment in the archive.
* @description This property contains the filesize of the attachment in as readable way (81.6 KB).
*
* @member {string} size
* @instance
* @example
* ....
* var archDoc = xmlserver.downloadBlob(....);
* util.out(archDoc.size);
**/
/**
* @memberof ArchiveConnectionBlob
* @function download
* @instance
* @summary Download the attachment to the PortalServer's machine (localPath)
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.60h / otrisPORTAL 6.0h
* @example
* var archFile = .....
* if (!archFile.downloaded)
* {
* var res = archFile.download();
* if (!res)
* util.out(archFile.getLastError());
* else
* util.out(archFile.localPath);
* }
**/
/**
* @memberof ArchiveConnectionBlob
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since ELC 3.60h / otrisPORTAL 6.0h
**/
/**
* @interface ArchiveConnectionBlobIterator
* @summary The ArchiveConnectionBlobIterator class is an iterator that holds a list of objects of the class ArchiveConnectionBlob.
* @description You may access ArchiveConnectionBlobIterator objects by the ArchiveConnection.downloadBlobs() method described in the ArchiceConnection chapter.
* Note: Class is only available for an ArchiceConnection to a XML-Server
* @since ELC 3.60h / otrisPORTAL 6.0h
*/
/**
* @memberof ArchiveConnectionBlobIterator
* @function first
* @instance
* @summary Retrieve the first ArchiveConnectionBlob object in the ArchiveConnectionBlobIterator.
* @returns {ArchiveConnectionBlob} ArchiveConnectionBlob or <code>null</code> in case of an empty ArchiveConnectionBlobIterator
* @since ELC 3.60h / otrisPORTAL 6.0h
**/
/**
* @memberof ArchiveConnectionBlobIterator
* @function next
* @instance
* @summary Retrieve the next ArchiveConnectionBlob object in the ArchiveConnectionBlobIterator.
* @returns {ArchiveConnectionBlob} ArchiveConnectionBlob or <code>NULL</code> if end of ArchiveConnectionBlobIterator is reached
* @since ELC 3.60h / otrisPORTAL 6.0h
**/
/**
* @memberof ArchiveConnectionBlobIterator
* @function size
* @instance
* @summary Get the amount of ArchiveConnectionBlob objects in the ArchiveConnectionBlobIterator.
* @returns {number} integer value with the amount of ArchiveConnectionBlob objects in the ArchiveConnectionBlobIterator
* @since ELC 3.60h / otrisPORTAL 6.0h
**/
/**
* @class ArchiveFileResultset
* @classdesc The ArchiveFileResultset class supports basic functions to loop through a list of ArchiveFile objects.
* @summary Create a new ArchiveFileResultset object.
* @description Like in other programming languages you create a new object with the <code>new</code> operator (refer to example below).
* Note: Important: The resultset may contain less hits than really exist. For EE.i and EE.x the limit of returned hits is the value of the DOCUMENTS property "MaxArchiveHitsFolder". If the property is not set, the limit is the XML-Server's default hit count. For EAS, The limit is either the "MaxArchiveHitsFolder" value or the limit of free research hitlists. The method is the same for dynamic folders and link-registers.
* @param {string} archiveKey String containing the key of the desired view or archive
* @param {string} filter String containing an filter criterium; use empty String ('') if you don't want to filter at all
* @param {string} sortOrder String containing an sort order; use empty String ('') if you don't want to sort at all
* @param {string} hitlist String containing the hitlist that you want to use (optional fรผr EE.i / mandatory for EE.x
* @param {boolean} [unlimitedHits] boolean that indicates if the archive hit limit must be ignored
* @since ELC 3.60i / otrisPORTAL 6.0i
* @example
* // Example for EE.i:
* var archiveKey = "$(#STANDARD)\\EINRECH";
* archiveKey += "@myeei"; // since Documents 4.0 using multi archive server
* var filter = "Kreditor='ALFKI'";
* var sortOrder = "BelegNr+";
* var hitlist = "STANDARD";
* var myAFRS = new ArchiveFileResultset(archiveKey, filter, sortOrder, hitlist);
* var archFile = null;
* while (true)
* {
* try
* {
* archFile = archFile ? myAFRS.next() : myAFRS.first();
* if (!archFile) // end of ArchiveFileResultset
* break;
*
* util.out(archFile.getArchiveKey());
* }
* catch (err)
* {
* util.out("Unable to load archFile: " + err);
* }
* }
* @example
* // Example for EE.x:
* var archiveKey = "Unit=Default/Instance=Default/View=Scanners";
* archiveKey += "@myeex"; // since Documents 4.0 using multi archive server
* var filter = "Speed=10";
* var sortOrder = "";
* var hitlist = "Default";
* var myAFRS = new ArchiveFileResultset(archiveKey, filter, sortOrder, hitlist);
* @example
* // Example for EAS:
* var archiveKey = "Order";
* archiveKey += "@myeas"; // since Documents 4.0 using multi archive server
* var filter = "company=A*";
* var sortOrder = "company+";
* var myAFRS = new ArchiveFileResultset(archiveKey, filter, sortOrder);
*/
/**
* @memberof ArchiveFileResultset
* @function first
* @instance
* @summary Retrieve the first DocFile object in the ArchiveFileResultset.
* @returns {DocFile} DocFile, <code>null</code> in case of an empty ArchiveFileResultset, throws an exception on error loading archive file.
* @since ELC 3.60i / otrisPORTAL 6.0i
**/
/**
* @memberof ArchiveFileResultset
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since ELC 3.60i / otrisPORTAL 6.0i
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof ArchiveFileResultset
* @function last
* @instance
* @summary Retrieve the last DocFile object in the ArchiveFileResultset.
* @returns {DocFile} DocFile or <code>null</code> if end of ArchiveFileResultset is reached.
* @since ELC 3.60j / otrisPORTAL 6.0j
**/
/**
* @memberof ArchiveFileResultset
* @function next
* @instance
* @summary Retrieve the next DocFile object in the ArchiveFileResultset.
* @returns {DocFile} DocFile, <code>null</code> if end of ArchiveFileResultset is reached, throws an exception on error loading archive file.
* @since ELC 3.60i / otrisPORTAL 6.0i
**/
/**
* @memberof ArchiveFileResultset
* @function size
* @instance
* @summary Get the amount of DocFile objects in the ArchiveFileResultset.
* @returns {number} integer value with the amount of DocFile objects in the ArchiveFileResultset
* @since ELC 3.60i / otrisPORTAL 6.0i
**/
/**
* @interface ArchiveServer
* @summary The ArchiveServer class has been added to the DOCUMENTS PortalScripting API to gain full access to the DOCUMENTS ArchiveServer by scripting means.
* @since DOCUMENTS 5.0a
*/
/**
* @memberof ArchiveServer
* @summary The technical name of the ArchiveServer.
* @member {string} name
* @instance
* @since DOCUMENTS 5.0a
**/
/**
* @memberof ArchiveServer
* @function getArchiveConnection
* @instance
* @summary Retrieve the archive connection object for EAS, EBIS or EASY Enterprise XML-Server.
* @description The ArchiveConnection object can be used for low level call directly on the archive interface.
* @returns {ArchiveConnection} <code>ArchiveConnection</code> object if successful, <code>NULL</code> in case of any error
* @since DOCUMENTS 5.0a
**/
/**
* @memberof ArchiveServer
* @function getAttribute
* @instance
* @summary Get the String value of an attribute of the ArchiveServer.
* @description
* Note: This function is only for experts. Knowledge about the DOCUMENTS-database schema is necessary!
* @param {string} attribute String containing the name of the desired attribute
* @returns {string} String containing the value of the desired attribute
* @since DOCUMENTS 5.0a
**/
/**
* @memberof ArchiveServer
* @function getLastError
* @instance
* @summary If you call a method at an ArchiveServer object and an error occurred, you can get the error description with this function.
* @returns {string} Text of the last error as String
* @since DOCUMENTS 5.0a
**/
/**
* @memberof ArchiveServer
* @function getOID
* @instance
* @summary Returns the object-id.
* @param {boolean} [oidLow] Optional flag:
* If <code>true</code> only the id of the filetype object (<code>m_oid</code>) will be returned.
* If <code>false</code> the id of the filetype object will be returned together with the id of the corresponding class in the form <code>class-id:m_oid</code>.
* The default value is <code>false</code>.
* @returns {string} <code>String</code> with the object-id
* @since DOCUMENTS 5.0a
**/
/**
* @memberof ArchiveServer
* @function setAttribute
* @instance
* @summary Set the String value of an attribute of the ArchiveServer to the desired value.
* @description
* Note: This function is only for experts. Knowledge about the DOCUMENTS-database schema is necessary!
* @param {string} attribute String containing the name of the desired attribute
* @param {string} value String containing the desired value of the attribute
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 5.0a
**/
/**
* @memberof ArchiveServer
* @function submitChanges
* @instance
* @summary After changes on the ArchiveServer with scripting methods, it is necessary to submit them to make them immediately valid.
* @description The settings of the ArchiveServer will be cached in a connection pool to the archive system. The pool does not recognize changes in the ArchiveServer object automatically, therefore it is necessary to call this method after all.
*
* @returns {void}
* @since DOCUMENTS 5.0c
* @example
* var as = context.getArchiveServerByName("EDA_2017");
* if (as)
* {
* as.setAttribute("Host", "127.0.0.1");
* as.submitChanges();
* }
**/
/**
* @interface ArchiveServerIterator
* @summary The ArchiveServerIterator class has been added to the DOCUMENTS PortalScripting API to gain full access to the DOCUMENTS ArchiveSerevrby scripting means.
* @since DOCUMENTS 5.0a
*/
/**
* @memberof ArchiveServerIterator
* @function first
* @instance
* @summary Retrieve the first ArchiveServer object in the ArchiveServerIterator.
* @returns {AccessProfile} ArchiveServer or <code>null</code> in case of an empty ArchiveServerIterator
* @since DOCUMENTS 5.0a
**/
/**
* @memberof ArchiveServerIterator
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since DOCUMENTS 5.0a
**/
/**
* @memberof ArchiveServerIterator
* @function next
* @instance
* @summary Retrieve the next ArchiveServer object in the ArchiveServerIterator.
* @returns {AccessProfile} ArchiveServer or <code>null</code> if end of ArchiveServerIterator is reached.
* @since DOCUMENTS 5.0a
**/
/**
* @memberof ArchiveServerIterator
* @function size
* @instance
* @summary Get the amount of ArchiveServer objects in the ArchiveServerIterator.
* @returns {number} integer value with the amount of ArchiveServer objects in the ArchiveServerIterator
* @since DOCUMENTS 5.0a
**/
/**
* @class ArchivingDescription
* @classdesc The ArchivingDescription class has been added to the DOCUMENTS PortalScripting API to improve the archiving process of DOCUMENTS files by scripting means.
* For instance this allows to use different target archives for each file as well as to influence the archiving process by the file's contents itself. The ArchivingDescription object can only be used as parameter for the method DocFile.archive(ArchivingDescription)
* Note: By default, archiving with an ArchivingDescription does not include any attachments. To archive some attachments, the script needs to call addRegister() on this object.
* Since EE.x: ELC 3.60a / otrisPORTAL 6.0a
* Since EAS: ELC 4.0 / otrisPORTAL 7
* @since EE.i: ELC 3.51c / otrisPORTAL 5.1c
* @summary Create a new ArchivingDescription object.
* @description Like in other programming languages you create a new object with the <code>new</code> operator (refer to example below).
* Since EE.i: ELC 3.51c / otrisPORTAL 5.1c
* Since EE.x: ELC 3.60a / otrisPORTAL 6.0a
* Since EAS: ELC 4.0 / otrisPORTAL 7
* @see [DocFile.archive]{@link DocFile#archive}
* @example
* // Example for EE.i:
* var docFile = context.file;
* if (!docFile)
* {
* // error handling
* }
* var ad = new ArchivingDescription();
* ad.targetArchive = "$(#DEMO)\\BELEGE";
* ad.archiveServer = "myeei"; // since Documents 4.0 using multi archive server
* // Note: This example does not archive any attachments
* var success = docFile.archive(ad);
* if (!success)
* {
* util.out(docFile.getLastError());
* }
* @example
* // Example for EE.x:
* var docFile = context.file;
* if (!docFile)
* {
* // error handling
* }
* var ad = new ArchivingDescription();
* ad.targetView = "Unit=Default/Instance=Default/View=DeliveryNotes";
* ad.targetSchema = "Unit=Default/Instance=Default/DocumentSchema=LIEFERSCHEINE";
* ad.archiveServer = "myeex"; // since Documents 4.0 using multi archive server
* ad.archiveMonitor = true;
* // Note: This example does not archive any attachments
* var success = docFile.archive(ad);
* if (!success)
* {
* util.out(docFile.getLastError());
* }
* @example
* // Example for EAS:
* var docFile = context.file;
* if (!docFile)
* {
* // error handling
* }
* var ad = new ArchivingDescription();
* ad.archiveServer = "myeas";
* ad.archiveMonitor = true;
* // Note: This example does not archive any attachments
* var success = docFile.archive(ad);
* if (success)
* util.out(docFile.getArchiveKey());
* else
* util.out(docFile.getLastError());
*/
/**
* @memberof ArchivingDescription
* @summary boolean value whether to archive the monitor of the file.
* @description Like on the filetype in the Portal Client you may decide whether you want to archive the monitor of the file along with the file. If so, the file's monitor will be transformed to a HTML file named monitor.html, and it will be part of the archived file in the desired target archive.
* Since EE.x: ELC 3.60a / otrisPORTAL 6.0a
* Since EAS: ELC 4.0 / otrisPORTAL 7
* @member {boolean} archiveMonitor
* @instance
* @since EE.i: ELC 3.51c / otrisPORTAL 5.1c
* @example
* var ad = new ArchivingDescription();
* ad.archiveMonitor = true; // archive monitor of file as HTML page as well
**/
/**
* @memberof ArchivingDescription
* @summary String containing the name of the archive server in a multi archive server environment.
* @description You need to define the archive server if you want to archive in an archive server that is different from the main archives server. If you want to archive into the main archive you can leave this value empty.
*
* Note: This value has only to be set if you habe multiple archive servers
* @member {string} archiveServer
* @instance
* @since ELC 4.0 / otrisPORTAL 7 (EE.i, EE.x, EAS)
* @example
* var ad = new ArchivingDescription();
* ad.archiveServer = "myeei"";
**/
/**
* @memberof ArchivingDescription
* @summary boolean value whether to archive the status of the file.
* @description Like on the filetype in the Portal Client you may decide whether you want to archive the status of the file along with the file. If so, the file's status will be transformed to a HTML file named status.html, and it will be part of the archived file in the desired target archive.
* Since EE.x: ELC 3.60a / otrisPORTAL 6.0a
* Since EAS: ELC 4.0 / otrisPORTAL 7
* @member {boolean} archiveStatus
* @instance
* @since EE.i: ELC 3.51c / otrisPORTAL 5.1c
* @example
* var ad = new ArchivingDescription();
* ad.archiveStatus = true; // archive status of file as HTML page as well
**/
/**
* @memberof ArchivingDescription
* @summary String containing the complete address of the target archive for archiving to EE.i.
* @description You need to define the target archive including the "Storageplace".
* Note: This value has only to be set if you want to archive to EE.i. If you want to archive to EE.x, you have to set targetView and targetSchema. It is important to know that the target archive String must use the socalled XML-Server syntax. It is as well neccessary to use a double backslash (\\) if you define your target archive as an PortalScript String value, because a single backslash is a special character.
* @member {string} targetArchive
* @instance
* @since EE.i: ELC 3.51c / otrisPORTAL 5.1c
* @example
* var ad = new ArchivingDescription();
* ad.targetArchive = "$(#DEMO)\\BELEGE"; // archiving to "DEMO\BELEGE"
**/
/**
* @memberof ArchivingDescription
* @summary String containing the complete address of the target schema used for archiving to EE.x.
* @description You need to define the target schema you want to archive into.
* Note: This value has only to be set if you want to archive to EE.x.
* @member {string} targetSchema
* @instance
* @since ELC 3.60a / otrisPORTAL 6.0a
* @example
* var ad = new ArchivingDescription();
* ad.targetView = "Unit=Default/Instance=Default/DocumentSchema=LIEFERSCHEINE";
**/
/**
* @memberof ArchivingDescription
* @summary String containing the complete address of the target view used for archiving to EE.x.
* @description You need to define the target view (write pool) you want to archive into.
* Note: This value has only to be set if you want to archive to EE.x.
* @member {string} targetView
* @instance
* @since ELC 3.60a / otrisPORTAL 6.0a
* @example
* var ad = new ArchivingDescription();
* ad.targetView = "Unit=Default/Instance=Default/View=DeliveryNotes";
**/
/**
* @memberof ArchivingDescription
* @summary boolean value whether to use the versioning technique in the archive.
* @description If the DocFile has already been archived and if you define this attribute to be true, a new version of the archive file will be created otherwise a independent new file in the archive will be created.
* Since EE.x: ELC 3.60a / otrisPORTAL 6.0a
* Since EAS: ELC 4.0 / otrisPORTAL 7
* @member {boolean} versioning
* @instance
* @since EE.i: ELC 3.51c / otrisPORTAL 5.1c
* @example
* var ad = new ArchivingDescription();
* ad.versioning = true; // use versioning for archived file
**/
/**
* @memberof ArchivingDescription
* @function addRegister
* @instance
* @summary flag an additional (document) register to be archived with the file.
* @description You may add the technical names of different document registers to an internal list of your ArchivingDescription object. This allows for example to archive only part of your documents of your DocFile.
* Since EE.x: ELC 3.60a / otrisPORTAL 6.0a
* Since EAS: ELC 4.0 / otrisPORTAL 7
* @param {string} registerName String containing the technical name of the register to be archived. Pass "all_docs" to archive all attachments of your DocFile.
* @returns {void}
* @since EE.i: ELC 3.51c / otrisPORTAL 5.1c
* @example
* var docFile = context.file;
* var ad = new ArchivingDescription();
* ad.targetArchive = "$(#DEMO)\\BELEGE";
* ad.addRegister("Documents");
* ad.addRegister("InternalDocuments");
* docFile.archive(ad);
**/
/**
* @namespace context
* @summary The Context class is the basic anchor for the most important attributes and methods to customize DOCUMENTS through PortalScripting.
* @description There is exactly ONE implicit object of the class <code>Context</code> which is named <code>context</code>. The implicit object <code>context</code> is the root object in any script. With the <code>context</code> object you are able to access to the different DOCUMENTS objects like DocFile, Folder etc. Some of the attributes are only available under certain conditions. It depends on the execution context of the PortalScript, whether a certain attribute is accessible or not. For example, <code>context.selectedFiles</code> is available in a folder userdefined action script, but not in a script used as a signal exit.
* Note: It is not possible to create objects of the class Context, since the context object is always available.
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_INVOICE
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_FP_HENR
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_LDAP
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_CONTRACT
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_OUTLOOK_WEB
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_OUTLOOK_SYNC
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_WORDML
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_MOBILE
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_BUSINESS_UNITS
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_CONTROLLING
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_REPORTING
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_EASYHR
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_CONTRACT_SAP
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_GADGETS
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_INBOX
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_IMS
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_CGC
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_CGC_ENT
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_CGC_ENT_PLUS
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_CREATOR
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_DOC_TREE
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_RISK_MANAGEMENT
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @description
* <br> This constant is member of constant group: PEM Module Constants<br>
* These constants build an enumeration of the possible values of the pem license.
* @instance
* @member {number} PEM_MODULE_MOBILE_APP
* @readonly
* @since DOCUMENTS 5.0c HF2
* @see [context.hasPEMModule]{@link context#hasPEMModule}
*/
/**
* @memberof context
* @summary Id of the client / thread which is the execution context of the script.
* @description This property is helpful to identify the clients at scripts running concurrently (for debugging purposes).
* Note: This property is readonly.
* @member {string} clientId
* @instance
* @since ELC 3.51e / otrisPORTAL 5.1e
* @example
* util.out(context.clientId);
**/
/**
* @memberof context
* @summary Login of the user who has triggered the script execution.
* @description If the script is running e.g. as action in the workflow the user is the logged in user, who has initiated the action.
* Note: This property is readonly.
* @member {string} currentUser
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* util.out(context.currentUser);
**/
/**
* @memberof context
* @summary Document object representing the current document that the script is executed at.
* @description
* Note: This property is readonly. If the script is not executed in a document context then the return value is null.
* @member {Document} document
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var doc = context.document;
**/
/**
* @memberof context
* @summary Error message text to be returned by the script.
* @description The error message will be displayed as Javascript alert box in the web client if the script is called in context of a web client.
* Note: You can get and set this property.
* @member {string} errorMessage
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* context.errorMessage = "You are not authorized to run this script";
* return -1; // neccessary to indicate an error
**/
/**
* @memberof context
* @summary Event which triggered the script execution.
* @description According to the context where the portal script has been called this property contains a key name for this event.
*
*
* The following events are available:
* <ul>
* <li><code>"afterMail"</code></li>
* <li><code>"afterSave"</code></li>
* <li><code>"attributeSetter"</code></li>
* <li><code>"autoText"</code></li>
* <li><code>"condition"</code></li>
* <li><code>"custom"</code></li>
* <li><code>"fileAction"</code></li>
* <li><code>"folderAction"</code></li>
* <li><code>"moveTrash"</code></li>
* <li><code>"newFile"</code></li>
* <li><code>"onAutoLogin"</code></li>
* <li><code>"onArchive"</code></li>
* <li><code>"onDelete"</code></li>
* <li><code>"onDeleteAll"</code></li>
* <li><code>"onEdit"</code></li>
* <li><code>"onLogin"</code></li>
* <li><code>"onSave"</code></li>
* <li><code>"test"</code></li>
* <li><code>"workflow"</code></li>
* </ul>
*
* Note: This property is readonly.
* @member {string} event
* @instance
* @since ELC 3.50n / otrisPORTAL 5.0n
* @example
* if (context.event == "fileAction")
* {
* util.out("Action at the file");
* }
**/
/**
* @memberof context
* @summary Returns in an enumeration script the name of the field where the script is executed for.
* @description If the script is an enumeration script, this member contains the field name of the current field where the script is executed. This is particularly helpful when the script is set at more than one enumeration field and the behaviour of the script should depend on the field.
*
* Note: This property is readonly.
* @member {string} fieldName
* @instance
* @since DOCUMENTS 5.0c HF2
**/
/**
* @memberof context
* @summary DocFile object representing the current file that the script is executed at.
* @description
* Note: This property is readonly. If the script is not executed in a file context then the return value is null.
* @member {DocFile} file
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var file = context.file;
**/
/**
* @memberof context
* @summary Technical name of the filetype of the file which is the execution context of the script.
* @description This property contains the technical name of the filetype of the file which is the execution context of the script.
* Note: This property is readonly.
* @member {string} fileType
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @see [context.file]{@link context#file}
* @example
* util.out(context.fileType);
**/
/**
* @memberof context
* @summary Current folder in which context the script is running.
* @description
* Note: This property is readonly.
* @member {Folder} folder
* @instance
* @since DOCUMENTS 5.0d
* @example
* var folder = context.folderFiles;
**/
/**
* @memberof context
* @summary FileResultset with all files of a folder.
* @description This property allows to retrieve a list of all files of a folder if this script is run as user defined action at the folder. You can then iterate through this list for further use of the distinct files.
*
* Note: This property is readonly. If there is no file inside the folder you will receive a valid empty FileResultset.
* @member {FileResultset} folderFiles
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var it = context.folderFiles;
**/
/**
* @memberof context
* @summary Technical name of the folder the script is called from.
* @description This property contains the technical name of the folder which is the execution context of the script.
* Note: This property is readonly.
* @member {string} folderName
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* util.out(context.folderName);
**/
/**
* @memberof context
* @summary Register object representing the current register that the script is executed at.
* @description
* Note: This property is readonly. If the script is not executed in a register context then the return value is null.
* @member {Register} register
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var reg = context.register;
**/
/**
* @memberof context
* @summary Type of the return value that the script returns.
* @description User defined actions attached to a file or a folder allow to influence the behaviour of the Web-Client. As soon as you define a return type you explicitely have to return a value.
*
*
* The following types of return values are available:
* <ul>
* <li><code>"html"</code> - The return value contains html-content. </li>
* <li><code>"stay"</code> - The continues to display the current file (this is the default behaviour). </li>
* <li><code>"showFile"</code> - The return value contains the file-id and optional the register-id of a file to be displayed after the script has been executed. Syntax: <code>file-id[&dlcRegisterId=register-id]</code>. </li>
* <li><code>"showFolder"</code> - The return value contains the folder-id of a folder to be displayed. </li>
* <li><code>"updateTree"</code> - The return value contains the folder-id of a folder to be displayed. The folder tree will be updated as well. </li>
* <li><code>"showNewFile"</code> - The return value contains the file-id of a file to be displayed. This file will automatically open in edit mode and will be deleted at cancellation by the user. </li>
* <li><code>"showEditFile"</code> - The return value contains the file-id of a file to be displayed. This file will automatically open in edit mode. </li>
* <li><code>"file:filename"</code> - The web user will be asked to download the content of the return value (usually a String variable) to his client computer; The filename <code>filename</code> will be proposed as a default. </li>
* <li><code>"download:filename"</code> - The web user will be asked to download the blob, that is specified in the return value (server-sided path to the blob), to his client computer; The filename <code>filename</code> will be proposed as a default.</li>
* </ul>
*
* Note: You may read from and write to this property.
* Since DOCUMENTS 4.0c showFile with return value of file-id and register-id
* @member {string} returnType
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0 resp. ELC 3.50c / otrisPORTAL 5.0c (showNewFile, updateTree, file)
* @example
* // Example 1: showFile
* context.returnType = "showFile";
* var idFile = docFile.getAutoText("id");
* return idFile;
* @example
* // Example 2: showFile with specific register
* context.returnType = "showFile";
* var idFile = docFile.getAutoText("id");
* var idRegister = docFile.getRegisterByName("internal_documents").getAttribute("id");
* return idFile + "&dlcRegisterId=" + idRegister;
* @example
* // Example 3:
* var itFolders = context.getFoldersByName("Invoice");
* var folder = itFolders.first();
* if (folder == null)
* {
* context.returnType = "html";
* return "<h1>Unable to find folder Invoice</h1>";
* }
* context.returnType = "showFolder";
* return folder.id;
* @example
* // Example 4:
* var csv = "row11;row12;row13\n";
* csv += "row21;row22;row23";
* context.returnType = "file:example.csv";
* return csv;
**/
/**
* @memberof context
* @summary Name of the executed script.
* @description
* Note: This property is readonly.
* @member {string} scriptName
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* util.out(context.scriptName);
**/
/**
* @memberof context
* @summary Iterator with the selected archive files of a folder.
* @description This property allows to retrieve a list of the selected archive files of a folder if this script is run as user defined action at the folder. You can then iterate through this list for further use of the distinct files.
*
* Note: This property is readonly. If there is no file selected you will receive a valid empty ArchiveFileResultset.
* @member {ArchiveFileResultset} selectedArchiveFiles
* @instance
* @since ELC 3.60j / otrisPORTAL 6.0j
* @example
* var it = context.selectedArchiveFiles;
* var archiveFile = it.first()
* while (archiveFile)
* {
* util.out(archiveFile.getAutoText("title"));
* archiveFile = it.next();
* }
**/
/**
* @memberof context
* @summary Array with the keys of the selected archive files of a folder.
* @description This property allows to retrieve an array with the keys of the selected archive files of a folder if this script is run as user defined action at the folder.
* Note: This property is readonly. If there is no archive file selected you will receive a valid empty array.
* @member {string[]} selectedArchiveKeys
* @instance
* @since ELC 3.60j / otrisPORTAL 6.0j
* @example
* var keys = context.selectedArchiveKeys;
* util.out(keys.length)
**/
/**
* @memberof context
* @summary DocumentIterator with the selected Documents (attachments) of the current document register.
* @description This property allows to retrieve a list of all selected Documents of a register if this script is run as user defined action at the register.
* Note: This property is readonly. If there is no document inside the Register you will receive a valid empty DocumentIterator.
* @member {DocumentIterator} selectedDocuments
* @instance
* @since DOCUMENTS 4.0b HF1
* @example
* var it = context.selectedDocuments;
**/
/**
* @memberof context
* @summary Iterator with the selected files of a folder.
* @description This property allows to retrieve a list of the selected files of a folder if this script is run as user defined action at the folder. You can then iterate through this list for further use of the distinct files.
*
* Note: This property is readonly. If there is no file selected you will receive a valid empty FileResultset.
* @member {FileResultset} selectedFiles
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var it = context.selectedFiles;
**/
/**
* @memberof context
* @summary Script source code of the script after including other scripts by the #import rule.
* @description This property is useful for debugging purposes, if you need to have a look for a certain line of code to find an error, but the script contains other imported sub scripts which mangle the line numbering.
* Note: This property is readonly.
* @member {string} sourceCode
* @instance
* @since ELC 3.50b / otrisPORTAL 5.0b
* @example
* util.out(context.sourceCode);
**/
/**
* @memberof context
* @summary Id of the locking WorkflowStep for the user for the current file.
* @description
* Note: This property is readonly.
* @member {string} workflowActionId
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* util.out(context.workflowActionId);
**/
/**
* @memberof context
* @summary Name of the locking WorkflowStep for the user for the current file.
* @description
* Note: This property is readonly.
* @member {string} workflowActionName
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* util.out(context.workflowActionName);
**/
/**
* @memberof context
* @summary Id of the ControlFlow the current file currently passes.
* @description
* Note: This property is readonly.
* @member {string} workflowControlFlowId
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* util.out(context.workflowControlFlowId);
**/
/**
* @memberof context
* @summary Name of the ControlFlow the current file currently passes.
* @description
* Note: This property is readonly.
* @member {string} workflowControlFlowName
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* util.out(context.workflowControlFlowName);
**/
/**
* @memberof context
* @summary Returns the current workflowstep if the script is run in context of a workflow.
* @description E.g. as guard or decision script.
*
* Note: This property is readonly.
* @member {string} workflowStep
* @instance
* @since DOCUMENTS 5.0
**/
/**
* @memberof context
* @function addCustomProperty
* @instance
* @summary Creates a new global custom property.
* @param {string} name String value defining the name
* @param {string} type String value defining the type
* @param {string} value String value defining the value
* @returns {CustomProperty} CustomProperty
* @since DOCUMENTS 5.0
* @see [context.setOrAddCustomProperty]{@link context#setOrAddCustomProperty}
* @see [context.getCustomProperties]{@link context#getCustomProperties}
* @example
* var custProp = context.addCustomProperty("favorites", "string", "peachit");
* if (!custProp)
* util.out(context.getLastError());
**/
/**
* @memberof context
* @function addTimeInterval
* @instance
* @summary Adds a time interval to a Date object.
* @description Since date manipulation in Javascript is odd sometimes, this useful function allows to conveniently add a given period of time to a given date, e.g. to calculate a due date based upon the current date plus <code>xx</code> days
* @param {Date} ts Date object to which the period of time should be added
* @param {number} amount integer value of the period of time to be added
* @param {string} [unit] String value representing the time unit of the period of time. You may use one of the following unit values:
* <ul>
* <li><code>"minutes"</code></li>
* <li><code>"hours"</code></li>
* <li><code>"days"</code></li>
* <li><code>"weeks"</code></li>
* </ul>
*
* @param {boolean} [useWorkCalendar] <code>true</code> if work calendar should be taken into account, <code>false</code> if not. The work calendar has to be defined at Documents->Settings
* @returns {Date} Date object with the new date.
* @since ELC 3.50e / otrisPORTAL 5.0e
* @see [context.getDatesDiff]{@link context#getDatesDiff} [util.convertDateToString]{@link util#convertDateToString} [util.convertStringToDate]{@link util#convertStringToDate}
* @example
* var actDate = new Date(); // actDate contains now the current date
* var newDate = context.addTimeInterval(actDate, 14, "days", false);
* util.out(newDate); // should two weeks in the future
**/
/**
* @memberof context
* @function changeScriptUser
* @instance
* @summary Change the user context of the PortalScript.
* @description In some cases, especially if you make heavy use of access privileges both with files and file fields, it might be neccessary to run a script in a different user context than the user who triggered the script execution. For example, if the current user is not allowed to change any field values, a PortalScript running in this user's context will fail, if it tries to change a field value. In this case it is best practice to switch the user context to some superuser who is allowed to perform the restricted action before that restricted action is executed. You may change the script's user context as often as you need, a change only applies to the instructions following the changeScriptUser() call.
* @param {string} login String value containing the login name of the user to switch to
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51b / otrisPORTAL 5.1b
* @example
* var currentUserLogin = context.currentUser;
* var success = context.changeScriptUser("schreiber");
* // code runs now in the context of user "schreiber"
* ....
* ....
* // switch back to the original user
* success = context.changeScriptUser(currentUserLogin);
**/
/**
* @memberof context
* @function clearEnumvalCache
* @instance
* @summary Clears the cached enumval at the specified PortalScript.
* @param {string} scriptName String with the name of the PortalScript
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 5.0c HF1
* @example
* var ret = context.clearEnumvalCache("lcmGetAllUser");
* if (!ret)
* util.out(context.getLastError());
**/
/**
* @memberof context
* @function convertDateToString
* @instance
* @summary Convert a Date object representing a date into a String.
* @description The output String is in the date format of the specified locale. If you leave the locale parameter away the current locale of the script context will be used.
* @param {Date} dateOrTimeStamp Date/Timestamp object representing the desired date
* @param {string} [locale]
* @returns {string}
* @since DOCUMENTS 4.0c HF1
* @see [util.convertDateToString]{@link util#convertDateToString}
* @example
* var date1 = new Date(2014, 1, 14);
* util.out(context.convertDateToString(date1, "de"));
* // Output: 14.02.2014
*
* util.out(context.convertDateToString(date1));
* // Output: depends on the locale of the script context
*
* var date2 = new Date(2014, 1, 14, 12, 59);
* util.out(context.convertDateToString(date2, "en"));
* // Output: 02/14/2014 12:59
**/
/**
* @memberof context
* @function convertNumericToString
* @instance
* @summary Converts a Number into a formatted String.
* @description The output String may have any format you like. The following parameters defines the format to configure the fromat of the numeric String.
* @param {number} value Numeric object representing the number
* @param {string} decimalSep Decimal-Separator as String
* @param {string} thousandSep Thousend-Separator as String
* @param {number} [precision] Precision as number (default=2)
* @returns {string} String representing the desired number
* @since ELC 3.60c / otrisPORTAL 6.0c
* @see [context.convertNumericToString]{@link context#convertNumericToString}
* @example
* var numVal = 1000 * Math.PI;
* context.out(context.convertNumericToString(numVal, ",", ".", 2));
* Output: 3.141,59
**/
/**
* @memberof context
* @function convertNumericToString
* @instance
* @summary Converts a Number into a formatted String.
* @description The output String is formatted like the definition in the locale. If the locale is not defined by parameter, the locale of the current user will be used.
* @param {number} value Numeric object representing the number
* @param {string} [locale] Locale as String
* @param {number} [precision]
* @returns {string} String representing the desired number
* @since ELC 3.60c / otrisPORTAL 6.0c
* @see [context.convertNumericToString]{@link context#convertNumericToString}
* @example
* var numVal = 1000 * Math.PI;
* context.out(context.convertNumericToString(numVal, "en", 2));
* Output: 3,141.59
**/
/**
* @memberof context
* @function convertStringToDate
* @instance
* @summary Convert a String representing a date into a Date object.
* @description The output Date is in the date format of the specified locale. If you omit the locale parameter the current locale of the script context will be used.
* @param {string} dateOrTimeStamp String representing a date has to be formatted as the definition in the specified locale, e.g. "TT.MM.JJJJ" for the locale "de".
* @param {string} locale Optional String value with the locale abbreviation (according to the principal's configuration).
* @returns {Date}
* @since DOCUMENTS 5.0a HF2
* @see [util.convertStringToDate]{@link util#convertStringToDate}
* @example
* var dateString = "19.09.1974";
* var birthDay = context.convertStringToDate(dateString, "de");
**/
/**
* @memberof context
* @function convertStringToNumeric
* @instance
* @summary Converts a formated String into a number.
* @description The input String may have any format you like. The following parameters defines the format to configure the format of the numeric String.
* @param {string} numericValue Formatted numeric String
* @param {string} decimalSep Decimal-Separator as String
* @param {string} thousandSep Thousend-Separator as String
* @returns {number} the numeric number (float) or NULL if fail
* @since ELC 3.60c / otrisPORTAL 6.0c
* @see [context.convertStringToNumeric]{@link context#convertStringToNumeric}
* @example
* var numString = "1.000,99";
* var floatVal = context.convertStringToNumeric(numString, ",", ".");
**/
/**
* @memberof context
* @function convertStringToNumeric
* @instance
* @summary Converts a formated String into a number.
* @description The input String has to be formatted like the definition in the locale. If the locale is not defined by parameter, the locale of the current user will be used.
* @param {string} numericValue Formatted numeric String
* @param {string} [locale] Locale as String
* @returns {number} the numeric number (float) or NULL if fail
* @since ELC 3.60c / otrisPORTAL 6.0c
* @see [context.convertStringToNumeric]{@link context#convertStringToNumeric}
* @example
* var numString = "1,000.99";
* var floatVal = context.convertStringToNumeric(numString, "en");
**/
/**
* @memberof context
* @function countPoolFiles
* @instance
* @summary Retrieve the amount of pool files of the specified filetype in the system.
* @description
* Note: This function is only for experts.
* @param {string} fileType the technical name of the desired filetype
* @returns {number} Integer amount of pool files
* @since ELC 3.50j / otrisPORTAL 5.0j
* @see [context.createPoolFile]{@link context#createPoolFile}
* @example
* var fileType = "Standard"; // filetype
* var poolSize = context.countPoolFiles(fileType); // amount of pool files
* for (var i = poolSize; i < 3000; i++)
* {
* context.createPoolFile(fileType);
* }
**/
/**
* @memberof context
* @function createAccessProfile
* @instance
* @summary Create a new access profile in the DOCUMENTS environment.
* @description If the access profile already exist, the method returns an error.
* @param {string} profileName technical name of the access profile
* @returns {AccessProfile} AccessProfile object as a representation of the access profile in DOCUMENTS, <code>null</code> in case of any error
* @since ELC 3.60i / otrisPORTAL 6.0i
* @example
* var office = context.createAccessProfile("office");
* if (!office)
* util.out(context.getLastError());
**/
/**
* @memberof context
* @function createArchiveServer
* @instance
* @summary Create a new ArchiveServer.
* @description This function creates a new ArchiveServer for the specified archive software on the top level. These types are available:
* <ul>
* <li><code>EEI</code></li>
* <li><code>EEX_native</code></li>
* <li><code>EBIS_store</code></li>
* <li><code>NOAH</code></li>
* <li><code>None</code></li>
* </ul>
*
* @param {string} name The technical name of the ArchiveServer to be created.
* @param {string} type The desired archive software of the ArchiveServer.
* @returns {ArchiveServer} New created ArchiveServer object or <code>null</code> if failed.
* @since DOCUMENTS 5.0a
* @example
* var as = context.createArchiveServer("Invoice2016", "NOAH") // EDA
* if (as)
* util.out(as.name);
* else
* util.out(context.getLastError());
**/
/**
* @memberof context
* @function createFellow
* @instance
* @summary Create a new fellow in the DOCUMENTS environment.
* @description
* Note: The license type "shared" is only available for pure archive retrieval users. It is not possible to create a shared user with DOCUMENTS access!
* Since DOCUMENTS 4.0d HF3 / DOCUMENTS 5.0 (new licenseType "concurrent_standard", "concurrent_open")
* @param {string} loginName login of the fellow
* @param {boolean} isDlcUser automatically grant DOCUMENTS access (true/false)
* @param {string} [licenseType] optional definition of the license type for that user (allowed values are <code>"named"</code>, <code>"concurrent_standard"</code>, <code>"concurrent_open"</code> and <code>"shared"</code> (deprecated: <code>"concurrent"</code>)
* @returns {SystemUser} SystemUser object as a representation of the newly created fellow; if the creation fails (e.g. due to a lack of appropriate licenses), the method returns <code>null</code>
* @since ELC 3.60f / otrisPORTAL 6.0f
* @see [context.deleteSystemUser]{@link context#deleteSystemUser}
* @example
* var schreiber = context.createFellow("schreiber", true, "named"); // this will create a named user with DOCUMENTS access
**/
/**
* @memberof context
* @function createFile
* @instance
* @summary Create a new file of the specified filetype.
* @description This function creates a new file of the given filetype. Since the script is executed in the context of a particular user, it is mandatory that user possesses sufficient access privileges to create new instances of the desired filetype, otherwise the method will fail.
*
* If an error occurs during creation of the file the return value will be <code>null</code> and you can access an error message describing the error with getLastError().
* Note: DOCUMENTS 5.0c HF1 and newer: The function directly creates a file for an EAS or EBIS store, if "@server" has been appended to the filetype's name and if appropriate permissions are granted. In this case the returned DocFile must be saved with DocFile.commit() instead of DocFile.sync().
* Since DOCUMENTS 5.0c HF1 (support for EDA/EAS and EBIS stores)
* @param {string} fileType Name of the filetype
* @returns {DocFile} New created file as DocFile object or <code>null</code> if failed.
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var newFile = context.createFile("Standard");
* if (newFile)
* util.out(newFile.getAutoText("title"));
* else
* util.out(context.getLastError());
**/
/**
* @memberof context
* @function createFolder
* @instance
* @summary Create a new folder of the specified type on the top level.
* @description This function creates a new folder of the specified type on the top level. There are three types available:
* <ul>
* <li><code>public</code></li>
* <li><code>dynamicpublic</code></li>
* <li><code>onlysubfolder</code></li>
* </ul>
*
* @param {string} name The technical name of the folder to be created.
* @param {string} type The desired type of the folder.
* @returns {Folder} New created folder as Folder object or <code>null</code> if failed.
* @since DOCUMENTS 4.0c
* @example
* var folder = context.createFolder("myFolder", "public")
* if (folder)
* util.out(folder.type);
* else
* util.out(context.getLastError());
**/
/**
* @memberof context
* @function createPoolFile
* @instance
* @summary Create a new pool file of the specified filetype.
* @description The script must run in the context of a user who has sufficient access privileges to create new files of the specified filetype, otherwise this method will fail.
* @param {string} fileType the technical name of the desired filetype
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50j / otrisPORTAL 5.0j
* @see [context.countPoolFiles]{@link context#countPoolFiles}
**/
/**
* @memberof context
* @function createSystemUser
* @instance
* @summary Create a new user in the DOCUMENTS environment.
* @description
* Note: The license type "shared" is only available for pure archive retrieval users. It is not possible to create a shared user with DOCUMENTS access!
* Since DOCUMENTS 4.0d HF3 / DOCUMENTS 5.0 (new licenseType "concurrent_standard", "concurrent_open")
* @param {string} loginName login of the user
* @param {boolean} isDlcUser automatically grant DOCUMENTS access (true/false)
* @param {string} [licenseType] optional definition of the license type for that user (allowed values are <code>"named"</code>, <code>"concurrent"</code> and <code>"shared"</code>)
* @returns {SystemUser} SystemUser object as a representation of the newly created user; if the creation fails (e.g. due to a lack of appropriate licenses), the method returns <code>null</code>
* @since ELC 3.51e / otrisPORTAL 5.1e
* @see [context.deleteSystemUser]{@link context#deleteSystemUser}
* @example
* var schreiber = context.createSystemUser("schreiber", true, "concurrent"); // this will create a concurrent user with DOCUMENTS access
**/
/**
* @memberof context
* @function deleteAccessProfile
* @instance
* @summary Delete a certain access profile in the DOCUMENTS environment.
* @param {string} profileName technical name of the access profile
* @returns {boolean} <code>true</code> in case of successful deletion, <code>false</code> in case of any error
* @since ELC 3.51b / otrisPORTAL 5.1b
* @example
* var profileName = "office"
* var success = context.deleteAccessProfile(profileName);
* if (success)
* {
* util.out("Deletion of access profile " + profileName + " successful");
* }
**/
/**
* @memberof context
* @function deleteFolder
* @instance
* @summary Delete a folder in DOCUMENTS.
* @param {Folder} folderObj an object of the Class Folder which represents the according folder in DOCUMENTS
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
* @example
* var itFD = context.getFoldersByName("Invoice");
* var fd = itFD.first();
* if (fd)
* {
* var success = context.deleteFolder(fd);
* }
**/
/**
* @memberof context
* @function deleteSystemUser
* @instance
* @summary Delete a user in the DOCUMENTS environment.
* @param {string} loginName login of the user
* @returns {boolean} <code>true</code> if the deletion was successful, <code>false</code> in case of any error
* @since ELC 3.50e / otrisPORTAL 5.0e
* @see [context.createSystemUser]{@link context#createSystemUser}
* @example
* var login = "schreiber";
* var success = context.deleteSystemUser(login);
* if (success)
* {
* util.out("Successfully deleted user " + login);
* }
**/
/**
* @memberof context
* @function doMaintenance
* @instance
* @summary Calls the specified maintenance operation.
* @param {string} operationName String with the name of the maintenance operation
* @returns {string} <code>String</code> with the return message of the of the maintenance operation.
* @since DOCUMENTS 5.0c HF1
* @example
* var msg = context.doMaintenance("BuildAclCache lcmContract");
* util.out(msg);
**/
/**
* @memberof context
* @function enableModules
* @instance
* @summary Allow dynamic imports of other scripts as modules.
* @description This function defines a function named <code>require()</code>, either in a passed object or in the global scope of the calling script. In sequence <code>require</code>('<scriptname>') can be used to import other portal scripts, which are implemented in the style of Node.js modules.
* Note: Only top-level scripts should call enableModules() and they should call it only once. Scripts loaded by require() always see the function as a global parameter. DOCUMENTS exposes a generic 'module' and an initially empty 'exports' object to each imported script. Other features of the module concept of Node.js are not available.
* @param {Object} root An optional Object to define the require() function as a property. Use this parameter, if the name "require" is already reserved in the script's global namespace.
* @returns {void} undefined.
* @since DOCUMENTS 5.0d
* @example
* // The main script
* context.enableModules();
* var mymath = require('MyMath');
* var test = mymath.square(42);
* util.out("square(42) is " + test);
* // End of main script
*
*
* // The 'MyMath' module script
* // "module.exports" is initially an empty object.
* // require() will return whatever the script places here.
* //
* // "exports" is a shortcut reference to "module.exports".
* // This works as long as only properties need to be added.
* // Directly assigning a new value to "exports" or
* // "module.exports" would break the reference.
* exports.square = function(x) { return x*x; };
* // End of module script
**/
/**
* @memberof context
* @function extCall
* @instance
* @summary Perform an external command shell call on the Portalserver.
* @description In the context of a work directory, an external command shell call is executed, usually a batch file. You can decide whether the scripting engine must wait for the external call to complete or whether the script execution continues asynchonously. If the script waits for the external call to complete, this method returns the errorcode of the external call as an integer value.
* @param {string} workDir String containing a complete directory path which should be used as the working directory
* @param {string} cmd String containing the full path and filename to the batch file which shall be executed
* @param {boolean} synced boolean value which defines whether the script must wait for the external call to finish (<code>true</code>) or not (<code>false</code>)
* @returns {boolean} integer value containing the errorcode (ERRORLEVEL) of the batch call
* @since ELC 3.51 / otrisPORTAL 5.1
* @example
* // execute testrun.bat in "c:\tmp" and wait for the call to complete
* var errorLevel = context.extCall("c:\\tmp", "c:\\tmp\\testrun.bat", true);
* util.out(errorLevel);
**/
/**
* @memberof context
* @function extProcess
* @instance
* @summary Perform an external process call on the Portalserver and returns the exitcode of the external process and the standard output.
* @description An external process call is executed, e.g. a batch file. The methods returns an array of the size 2. The first array value is the exitcode of the external process. The second array value contains the content that the external process has written to the standard output.
* @param {string} cmd String containing the full path and filename to the program which shall be executed
* @returns {any[]} an array with the exitcod and the content of the standard output
* @since ELC 3.60g / otrisPORTAL 6.0g
* @example
* // execute testrun.bat and wait for the call to complete
* var res = context.extProcess("c:\\tmp\\testrun.bat");
* var exitcode = res[0];
* var stdout = res[1];
* util.out(exitcode + ": " + stdout);
**/
/**
* @memberof context
* @function findAccessProfile
* @instance
* @summary Find a certain access profile in the DOCUMENTS environment.
* @param {string} profileName technical name of the access profile
* @returns {AccessProfile} AccessProfile object as a representation of the access profile in DOCUMENTS, <code>null</code> in case of any error
* @since ELC 3.50b / otrisPORTAL 5.0b
* @example
* var office = context.findAccessProfile("office");
**/
/**
* @memberof context
* @function findCustomProperties
* @instance
* @summary Searches for CustomProperties.
* @param {string} filter Optional String value defining the search filter (specification see example)
* @returns {CustomPropertyIterator} CustomPropertyIterator
* @since DOCUMENTS 5.0
* @see [context.getCustomProperties]{@link context#getCustomProperties}
* @see [AccessProfile.getCustomProperties]{@link AccessProfile#getCustomProperties}
* @see [SystemUser.getCustomProperties]{@link SystemUser#getCustomProperties}
* @example
* // Specification of the filter:
* // ----------------------------
* // Possible filter-columns:
* // name: String - name of the custom property
* // type: String - type of the custom property
* // to_Systemuser: Integer (oid-low) - connected SystemUser
* // to_AccessProfile: Integer (oid-low) - connected AccessProfile
* // to_DlcFile : Integer (oid-low) - connected Filetype
* //
* // Operators:
* // &&: AND
* // ||: OR
*
* var oidUser = context.findSystemUser("schreiber").getOID(true);
* var oidAP1 = context.findAccessProfile("Service").getOID(true);
* var oidAP2 = context.findAccessProfile("Customer").getOID(true);
* var oidFileType = context.getFileTypeOID("ftRecord", true);
*
* var filter = "name='Prop1'";
* filter += "&& to_Systemuser=" + oidUser;
* filter += "&& (to_AccessProfile=" + oidAP1 + " || to_AccessProfile=" + oidAP2 + ")";
* filter += "&& to_DlcFile =" + oidFileType;
*
* var it = context.findCustomProperties(filter);
* for (var cp=it.first(); cp; cp=it.next())
* {
* util.out(cp.value);
* }
**/
/**
* @memberof context
* @function findSystemUser
* @instance
* @summary Retrieve a user by his/her login.
* @description If the user does not exist, then the return value will be <code>null</code>.
* @param {string} login name of the user
* @returns {SystemUser} User as SystemUser object
* @since ELC 3.50b / otrisPORTAL 5.0b
* @see [context.findSystemUserByAlias]{@link context#findSystemUserByAlias} [context.getSystemUser]{@link context#getSystemUser} [context.getSystemUsers]{@link context#getSystemUsers} [AccessProfile.getSystemUsers]{@link AccessProfile#getSystemUsers}
* @example
* var myUser = context.findSystemUser("schreiber");
**/
/**
* @memberof context
* @function findSystemUserByAlias
* @instance
* @summary Retrieve a user by an alias name.
* @description If the alias does not exist or is not connected to a user then the return value will be <code>null</code>.
* @param {string} alias technical name of the desired alias
* @returns {SystemUser} User as SystemUser object
* @since ELC 3.51c / otrisPORTAL 5.1c
* @see [context.findSystemUser]{@link context#findSystemUser} [context.getSystemUser]{@link context#getSystemUser} [context.getSystemUsers]{@link context#getSystemUsers}
* @example
* var myUser = context.findSystemUserByAlias("CEO");
**/
/**
* @memberof context
* @function getAccessProfiles
* @instance
* @summary Get an iterator with all access profiles of in the DOCUMENTS environment.
* @description
* Note: This method can only return access profiles which are checkmarked as being visible in DOCUMENTS lists.
* Since ELC 3.60e / otrisPORTAL 6.0e (new parameter includeInvisibleProfiles)
* @param {boolean} [includeInvisibleProfiles] optional boolean value to define, if access profiles that are not checkmarked as being visible in DOCUMENTS lists should be included
* @returns {AccessProfileIterator} AccessProfileIterator object with all AccessProfile in DOCUMENTS
* @since ELC 3.51g / otrisPORTAL 5.1g
* @example
* var itAP = context.getAccessProfiles(false);
* for (var ap = itAP.first(); ap; ap = itAP.next())
* {
* util.out(ap.name);
* }
**/
/**
* @memberof context
* @function getArchiveConnection
* @instance
* @summary Get an ArchiveConnection object.
* @description With this method you can get an ArchiveConnection object. This object offers several methods to use the EAS Interface, EBIS or the EASY ENTERPRISE XML-Server.
* @param {string} archiveServerName Optional string containing the archive server name; If the archive server is not defined, then the main archive server will be used
* @returns {ArchiveConnection} ArchiveConnection-Object or NULL, if failed
* @since DOCUMENTS 5.0a
* @see [ArchiveServer.getArchiveConnection]{@link ArchiveServer#getArchiveConnection}
* @example
* var xmlserver = context.getArchiveConnection("myeex")
* if (!xmlserver) // failed
* util.out(context.getLastError());
* else
* {
* ...
* }
**/
/**
* @memberof context
* @function getArchiveFile
* @instance
* @summary Get a file from the archive.
* @description With this method you can get a file from the archive using the archive key. You need the necessary access rights on the archive side.
* @param {string} key
* @returns {DocFile} <code>DocFile</code> or <code>NULL</code>, if failed
* @since ELC 3.60e / otrisPORTAL 6.0e
* @example
* var key = "Unit=Default/Instance=Default/Pool=DEMO/Pool=PRESSE/Document=Waz.4E1D1F7E28C611DD9EE2000C29FACDC2@eex1";
* var file = context.getArchiveFile(key)
* if (!file) // failed
* util.out(context.getLastError());
* else
* {
* ...
* }
**/
/**
* @memberof context
* @function getArchiveServer
* @instance
* @summary Get an ArchiveServer identified by its name.
* @param {string} name The technical name of the ArchiveServer.
* @returns {ArchiveServer} ArchiveServer object or <code>null</code> if failed.
* @since DOCUMENTS 5.0a
* @example
* var as = context.getArchiveServer("ebis1");
* if (as)
* util.out(as.name);
**/
/**
* @memberof context
* @function getArchiveServers
* @instance
* @summary Get an iterator with all ArchiveServers in the DOCUMENTS environment.
* @returns {ArchiveServerIterator}
* @since DOCUMENTS 5.0a
* @example
* var itAS = context.getArchiveServers();
* for (var as = itAS.first(); as; as = itAS.next())
* {
* util.out(as.name);
* }
**/
/**
* @memberof context
* @function getAutoText
* @instance
* @summary Get the String value of a DOCUMENTS autotext.
* @param {string} autoText the rule to be parsed
* @returns {string} String containing the parsed value of the autotext
* @since ELC 3.50e / otrisPORTAL 5.0e
* @example
* util.out(context.getAutoText("currentDate"));
**/
/**
* @memberof context
* @function getClientLang
* @instance
* @summary Get the abbreviation of the current user's portal language.
* @description If you want to return output messages through scripting, taking into account that your users might use different portal languages, this function is useful to gain knowledge about the portal language used by the current user, who is part of the script's runtime context. This function returns the current language as the two letter abbreviation as defined in the principal's settings in the Windows Portal Client (e.g. "de" for German).
* @returns {string} String containing the abbreviation of the current user's portal language
* @since ELC 3.51 / otrisPORTAL 5.1
* @see [context.setClientLang]{@link context#setClientLang} [context.getEnumErgValue]{@link context#getEnumErgValue} [context.getFieldErgName]{@link context#getFieldErgName} [context.getFileTypeErgName]{@link context#getFileTypeErgName} [context.getEnumValues]{@link context#getEnumValues} [context.getFromSystemTable]{@link context#getFromSystemTable}
* @example
* util.out(context.getClientLang());
**/
/**
* @memberof context
* @function getClientSystemLang
* @instance
* @summary Get the script's execution context portal language index.
* @returns {number} integer value of the index of the current system language
* @since ELC 3.51g / otrisPORTAL 5.1g
* @see [context.getEnumErgValue]{@link context#getEnumErgValue} [context.getFieldErgName]{@link context#getFieldErgName} [context.getFileTypeErgName]{@link context#getFileTypeErgName} [context.getEnumValues]{@link context#getEnumValues} [context.getFromSystemTable]{@link context#getFromSystemTable}
* @example
* util.out(context.getClientSystemLang());
* var erg = context.setClientSystemLang(0); // first portal language
**/
/**
* @memberof context
* @function getClientType
* @instance
* @summary Get the connection info of the client connection.
* @description You can analyze the connection info to identify e.g. a client thread of the HTML5 Web-Client
* HTML5-Client: CL[Windows 7/Java 1.7.0_76], POOL[SingleConnector], INF[SID[ua:docsclient, dca:2.0, docs_cv:5.0]]
* Classic-Client: CL[Windows 7/Java 1.7.0_76], POOL[SingleConnector]
* SOAP-Client: Documents-SOAP-Proxy (In-Server-Client-Library) on Win32
*
*
* @returns {string}
* @since DOCUMENTS 5.0
* @example
* function isHTML5Client()
* {
* return context.getClientType().indexOf("docs_cv:5.0") > -1;
* }
* if (isHTML5Client())
* util.out("HTML5-Client");
* else
* util.out("NO HTML5-Client");
**/
/**
* @memberof context
* @function getCurrentUserAttribute
* @instance
* @summary Get the String value of an attribute of the current user.
* @param {string} attributeName the technical name of the desired attribute
* @returns {string} String containing the value of the attribute
* @since ELC 3.50f / otrisPORTAL 5.0f
* @see [context.getPrincipalAttribute]{@link context#getPrincipalAttribute} [context.setPrincipalAttribute]{@link context#setPrincipalAttribute}
* @example
* util.out(context.getCurrentUserAttribute("particulars.lastName"));
**/
/**
* @memberof context
* @function getCustomProperties
* @instance
* @summary Get a CustomPropertyIterator with global custom properties.
* @param {string} [nameFilter] String value defining an optional filter depending on the name
* @param {string} [typeFilter] String value defining an optional filter depending on the type
* @returns {CustomPropertyIterator} CustomPropertyIterator
* @since DOCUMENTS 5.0
* @see [context.findCustomProperties]{@link context#findCustomProperties}
* @see [context.setOrAddCustomProperty]{@link context#setOrAddCustomProperty}
* @see [context.addCustomProperty]{@link context#addCustomProperty}
* @example
* var itProp = context.getCustomProperties();
* for (var prop = itProp.first(); prop; prop = itProp.next())
* {
* util.out(prop.name + ": " + prop.value);
* }
**/
/**
* @memberof context
* @function getDatesDiff
* @instance
* @summary Subtract two Date objects to get their difference.
* @description This function calculates the time difference between two Date objects, for example if you need to know how many days a business trip takes. By default this function takes the work calendar into account if it is configured and enabled for the principal.
* @param {Date} earlierDate Date object representing the earlier date
* @param {Date} laterDate Date object representing the later date
* @param {string} [unit] optional String value defining the unit, allowed values are <code>"minutes"</code>, <code>"hours"</code> and <code>"days"</code> (default)
* @param {boolean} [useWorkCalendar] optional boolean to take office hours into account or not (requires enabled and configured work calendar)
* @returns {number} integer value representing the difference between the two dates
* @since ELC 3.51b / otrisPORTAL 5.1b
* @example
* var start = util.convertStringToDate("01.04.2006", "dd.mm.yyyy");
* var end = util.convertStringToDate("05.04.2006", "dd.mm.yyyy");
* var duration = context.getDatesDiff(start, end) ;
* util.out("Difference: " + duration); // should be 4
**/
/**
* @memberof context
* @function getEnumAutoText
* @instance
* @summary Get an array with the values of an enumeration autotext.
* @param {string} autoText to be parsed
* @returns {string[]} Array containing the values for the autotext
* @since ELC 3.60e / otrisPORTAL 6.0e
* @example
* var values = context.getEnumAutoText("%accessProfile%")
* if (values)
* {
* for (var i = 0; i < values.length; i++)
* {
* util.out(values[i]);
* }
* }
**/
/**
* @memberof context
* @function getEnumErgValue
* @instance
* @summary Get the ergonomic label of a multilanguage enumeration list value.
* @description Enumeration lists in multilanguage DOCUMENTS installations usually are translated into the different portal languages as well. This results in the effect that only a technical value for an enumeration is stored in the database. So, if you need to display the label which is usually visible instead in the enumeration field through scripting, this function is used to access that ergonomic label.
* @param {string} fileType String value containing the technical name of the desired filetype
* @param {string} field String value containing the technical name of the desired enumeration field
* @param {string} techEnumValue String value containing the desired technical value of the enumeration entry
* @param {string} [locale] optional String value with the locale abbreviation (according to the principal's configuration); if omitted, the current user's portal language is used automatically
* @returns {string} String containing the ergonomic value of the enumeration value in the appropriate portal language
* @since ELC 3.51 / otrisPORTAL 5.1
* @see [context.getEnumErgValue]{@link context#getEnumErgValue} [context.getFieldErgName]{@link context#getFieldErgName} [context.getFileTypeErgName]{@link context#getFileTypeErgName} [context.getEnumValues]{@link context#getEnumValues} [context.getFromSystemTable]{@link context#getFromSystemTable}
* @example
* util.out(context.getEnumErgValue("Standard", "Priority", "1", "de"));
**/
/**
* @memberof context
* @function getEnumValues
* @instance
* @summary Get an array with enumeration list entries.
* @description In some cases it might be useful not only to access the selected value of an enumeration file field, but the list of all possible field values as well. This function creates an Array of String values (zero-based), and each index is one available value of the enumeration field. If the enumeration field is configured to sort the values alphabetically, this option is respected.
* @param {string} fileType String value containing the technical name of the desired filetype
* @param {string} field String value containing the technical name of the desired enumeration field
* @returns {string} Array containing all possible values of the enumeration field
* @since ELC 3.51 / otrisPORTAL 5.1
* @see [context.getEnumErgValue]{@link context#getEnumErgValue} [context.getFieldErgName]{@link context#getFieldErgName} [context.getFileTypeErgName]{@link context#getFileTypeErgName} [context.getEnumValues]{@link context#getEnumValues} [context.getFromSystemTable]{@link context#getFromSystemTable}
* @example
* var valueList = context.getEnumValues("Standard", "Priority");
* if (valueList.length > 0)
* {
* for (var i = 0; i < valueList.length; i++)
* {
* util.out(valueList[i]);
* }
* }
**/
/**
* @memberof context
* @function getFieldErgName
* @instance
* @summary Get the ergonomic label of a file field.
* @description In multilanguage DOCUMENTS environments, usually the file fields are translated to the different locales by using the well known ergonomic label hack. The function is useful to output scripting generated information in the appropriate portal language of the web user who triggered the script execution.
* @param {string} fileType String value containing the technical name of the desired filetype
* @param {string} field String value containing the technical name of the desired field
* @param {string} [locale] optional String value with the locale abbreviation (according to the principal's configuration); if omitted, the current user's portal language is used automatically
* @returns {string} String containing the ergonomic description of the file field in the appropriate portal language
* @since ELC 3.51 / otrisPORTAL 5.1
* @see [context.getEnumErgValue]{@link context#getEnumErgValue} [context.getFieldErgName]{@link context#getFieldErgName} [context.getFileTypeErgName]{@link context#getFileTypeErgName} [context.getEnumValues]{@link context#getEnumValues} [context.getFromSystemTable]{@link context#getFromSystemTable}
* @example
* util.out(context.getFieldErgName("Standard", "Prioritaet", "de"));
**/
/**
* @memberof context
* @function getFileById
* @instance
* @summary Get the file by its unique file-id.
* @description If the file does not exist or the user in whose context the script is executed is not allowed to access the file, then the return value will be <code>null</code>.
* @param {string} idFile Unique id of the file
* @returns {DocFile} File as DocFile object.
* @since ELC 3.51b / otrisPORTAL 5.1b
* @see [context.file]{@link context#file}
* @example
* var file = context.getFileById("toastupfi_20070000002081");
* if (file)
* util.out(file.getAutoText("title"));
* else
* util.out(context.getLastError());
**/
/**
* @memberof context
* @function getFileTypeErgName
* @instance
* @summary Get the ergonomic label of a filetype.
* @description In multilanguage DOCUMENTS environments, usually the filetypes are translated to the different locales by using the well known ergonomic label hack. The function is useful to output scripting generated information in the appropriate portal language of the web user who triggered the script execution.
* @param {string} fileType String value containing the technical name of the desired filetype
* @param {string} [locale] optional String value with the locale abbreviation (according to the principal's configuration); if omitted, the current user's portal language is used automatically
* @returns {string} String containing the ergonomic description of the filetype in the appropriate portal language
* @since ELC 3.51 / otrisPORTAL 5.1
* @see [context.getEnumErgValue]{@link context#getEnumErgValue} [context.getFieldErgName]{@link context#getFieldErgName} [context.getFileTypeErgName]{@link context#getFileTypeErgName} [context.getEnumValues]{@link context#getEnumValues} [context.getFromSystemTable]{@link context#getFromSystemTable}
* @example
* util.out(context.getFileTypeErgName("Standard", "de"));
**/
/**
* @memberof context
* @function getFileTypeOID
* @instance
* @summary Returns the object-id of a filetype.
* @param {string} nameFiletype String value containing the technical name of the filetype.
* @param {boolean} [oidLow] Optional flag:
* If <code>true</code> only the id of the filetype object (<code>m_oid</code>) will be returned.
* If <code>false</code> the id of the filetype object will be returned together with the id of the corresponding class in the form <code>class-id:m_oid</code>.
* The default value is <code>false</code>.
* @returns {string} <code>String</code> with the object-id or <code>false</code> if filetype does not exist
* @since DOCUMENTS 5.0
**/
/**
* @memberof context
* @function getFolderPosition
* @instance
* @summary Retrieve the position of a top level folder in the global context.
* @description This method can be used to get the position of a top level folder (public, public dynamic or only subfolders folder with no parent) in the global context.
* @param {Folder} folder Folder object whose position to be retrieved.
* @returns {number} internal position number of the folder as integer or -1 in case of any error.
* @since DOCUMENTS 5.0a
* @see [context.setFolderPosition]{@link context#setFolderPosition} [Folder.getPosition]{@link Folder#getPosition} [Folder.setPosition]{@link Folder#setPosition}
* @example
* var folder = context.getFoldersByName("MyPublicFolder").first();
* var pos = context.getFolderPosition(folder);
* if (pos < 0)
* throw context.getLastError();
**/
/**
* @memberof context
* @function getFoldersByName
* @instance
* @summary Retrieve a list of folders with identical name.
* @description Different folders might match an identical pattern, e.g. <code>"DE_20*"</code> for each folder like <code>"DE_2004"</code>, <code>"DE_2005"</code> and so on. If you need to perform some action with the different folders or their contents, it might be useful to retrieve an iterator (a list) of all these folders to loop through that list.
* @param {string} folderPattern the name pattern of the desired folder(s)
* @param {string} [type] optional parameter, a String value defining the type of folders to look for; allowed values are <code>"public"</code>, <code>"dynamicpublic"</code> and <code>"onlysubfolder"</code>
* @returns {FolderIterator} FolderIterator containing a list of all folders matching the specified name pattern
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
* @example
* var folderIter = context.getFoldersByName("Inv*");
**/
/**
* @memberof context
* @function getFromSystemTable
* @instance
* @summary Retrieve the desired entry of the system messages table.
* @description It might be inconvenient to maintain the different output Strings of localized PortalScripts, if this requires to edit the scripts themselves. This function adds a convenient way to directly access the system messages table which you may maintain in the Windows Portal Client. This enables you to add your own system message table entries in your different portal languages and to directly access them in your scripts.
* @param {string} identifier String value containing the technical identifer of a certain system message table entry
* @returns {string} String containing the value of the desired entry in the current user's portal language
* @since ELC 3.50o / otrisPORTAL 5.0o
* @see [context.getEnumErgValue]{@link context#getEnumErgValue} [context.getFieldErgName]{@link context#getFieldErgName} [context.getFileTypeErgName]{@link context#getFileTypeErgName} [context.getEnumValues]{@link context#getEnumValues} [context.getFromSystemTable]{@link context#getFromSystemTable}
* @example
* // requires an entry with that name in your system message table
* util.out(context.getFromSystemTable("myOwnTableEntry"));
**/
/**
* @memberof context
* @function getJSObject
* @instance
* @summary Get a JS_Object by object id.
* @description With this method you can get a JS-Object by the object id. Depending of the class of the object you get a JS-Object of the classes AccessProfile, DocFile, Document, Folder, Register, SystemUser or WorkflowStep
* @param {string} oid String containing the id of the object
* @returns {object} JS-Object or NULL, if failed
* @since ELC 3.60c / otrisPORTAL 6.0c
* @example
* var docFile1 = context.file;
* var objectId = docFile1.getOID();
* var docFile2 = context.getJSObject(objectId);
* // docFile1 and docFile2 are both of the class DocFile
* // and reference the same ELC-file object
**/
/**
* @memberof context
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @description
* Note: All classes have their own error functions. Only global errors are available through the context getLastError() method.
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @returns {string} Text of the last error as String
* @since ELC 3.50 / otrisPORTAL 5.0
* @see [DocFile.getLastError]{@link DocFile#getLastError}
* @example
* util.out(context.getLastError());
**/
/**
* @memberof context
* @function getLocaleValue
* @instance
* @summary Get the value/label of a String with the format "de:rot;en:red;fr:rouge" in the current or defined portal language.
* @param {string} value String with the complete value string
* @param {string} [locale] Optional String value with the locale abbreviation (according to the principal's configuration); if omitted, the current user's portal language is used automatically.
* @returns {string} <code>String</code> containing the valuein the appropriate portal language.
* @since DOCUMENTS 5.0c HF1
* @example
* var title = "de:Rechnung 001; en:Invoice 001"
*
* var deVal = context.getLocaleValue(title, "de");
* util.out(deVal); // deVal = Rechnung 001
*
* var valInCurrentLanguage = context.getLocaleValue(title);
**/
/**
* @memberof context
* @function getPrincipalAttribute
* @instance
* @summary Get the String value of an attribute of the DOCUMENTS principal.
* @param {string} attributeName the technical name of the desired attribute
* @returns {string} String containing the value of the attribute
* @since ELC 3.50f / otrisPORTAL 5.0f
* @see [context.getCurrentUserAttribute]{@link context#getCurrentUserAttribute} [context.setPrincipalAttribute]{@link context#setPrincipalAttribute}
* @example
* util.out(context.getPrincipalAttribute("executive.eMail"));
**/
/**
* @memberof context
* @function getProgressBar
* @instance
* @summary Gets the current progress value in % of the progress bar in the Documents-Manager during the PortalScript execution.
* @returns {number} <code>progress</code> as float (value >= 0 and value <= 100)
* @since DOCUMENTS 5.0c
* @see [context.setProgressBarText]{@link context#setProgressBarText} [context.setProgressBar]{@link context#setProgressBar}
* @example
* context.setProgressBarText("Calculating...");
* context.setProgressBar(0.0); // set progress bar to 0.0%
* for (var i; i<100; i++) {
* // do something
* context.setProgressBar(i);
* }
**/
/**
* @memberof context
* @function getQueryParams
* @instance
* @summary Get the actual search parameters within an "OnSearch" or "FillSearchScript" exit.
* @description
* Note: The return value is null, if the calling script is not running as an "OnSearch" or "FillSearchMask" handler. It can also be null, if the script has called changeScriptUser(). In order to access the search parameters, the script needs to restore the original user context.
* @returns {DocQueryParams} A DocQueryParams object on success, otherwise <code>null</code>.
* @since DOCUMENTS 4.0c
* @example
* var queryParams = context.getQueryParams();
**/
/**
* @memberof context
* @function getRegisterErgName
* @instance
* @summary Get the ergonomic label of a register.
* @param {string} fileTypeName String value containing the technical name of the desired filetype
* @param {string} registerName String value containing the technical name of the desired register
* @param {string} [locale] optional String value with the locale abbreviation (according to the principal's configuration); if omitted, the current user's portal language is used automatically
* @returns {string} String containing the ergonomic description of the register in the appropriate portal language
* @since DOCUMENTS 4.0d HF1
* @see [context.getFieldErgName]{@link context#getFieldErgName} [context.getFileTypeErgName]{@link context#getFileTypeErgName}
* @example
* util.out(context.getRegisterErgName("Standard", "Reg1", "de"));
**/
/**
* @memberof context
* @function getServerInstallPath
* @instance
* @summary Create a String containing the installation path of the portal server.
* @returns {string} String containing the portal server installation path
* @since ELC 3.60a / otrisPORTAL 6.0a
* @example
* var installDir = context.getServerInstallPath();
* util.out(installDir);
**/
/**
* @memberof context
* @function getSystemUser
* @instance
* @summary Get the current user as a SystemUser object.
* @returns {SystemUser} SystemUser object representing the current user.
* @since ELC 3.51b / otrisPORTAL 5.1b
* @see [context.findSystemUser]{@link context#findSystemUser} [context.findSystemUserByAlias]{@link context#findSystemUserByAlias} [context.getSystemUsers]{@link context#getSystemUsers}
* @example
* var su = context.getSystemUser();
* if (su)
* util.out(su.login); // output login name of current user
**/
/**
* @memberof context
* @function getSystemUsers
* @instance
* @summary Get a list of all users created in the system.
* @description
* Note: The method can only return users which are checkmarked as being visible in DOCUMENTS lists.
* Since DOCUMENTS 4.0c new optional parameter includeLockedUsers
* @param {boolean} [includeLockedUsers] optional definition, if locked users also should be returned
* @returns {SystemUserIterator} SystemUserIterator object containing a list of all (visible) users created in the system.
* @since ELC 3.50b / otrisPORTAL 5.0b
* @see [context.findSystemUser]{@link context#findSystemUser} [context.getSystemUser]{@link context#getSystemUser} [context.findSystemUserByAlias]{@link context#findSystemUserByAlias}
* @example
* var itSU = context.getSystemUsers();
* for (var su = itSU.first(); su; su = itSU.next())
* {
* util.out(su.login);
* }
**/
/**
* @memberof context
* @function getTempPathByToken
* @instance
* @summary Returns the temporary server path, that was ordered by the gadget API for the token.
* @param {string} accessToken String value with the token
* @param {boolean} [dropToken] Optional Boolean value that indicates the server to forget the token
* @returns {string} String with temporary path or Emptystring if accessToken is unknown
* @since DOCUMENTS 5.0d
**/
/**
* @memberof context
* @function getTmpFilePath
* @instance
* @summary Create a String containing a complete path and filename to a temporary file.
* @description The created file path may be used without any danger of corrupting any important data by accident, because DOCUMENTS assures that there is no such file with the created filename yet.
* @returns {string} String containing the complete "safe" path and filename
* @since ELC 3.50n / otrisPORTAL 5.0n
* @example
* var tmpFilePath = context.getTmpFilePath();
* util.out(tmpFilePath);
**/
/**
* @memberof context
* @function getXMLServer
* @instance
* @summary Get an ArchiveConnection object.
* @description With this method you can get an ArchiveConnection object. This object offers several methods to use the EAS Interface, EBIS or the EASY ENTERPRISE XML-Server.
* Since archiveServerName: Documents 4.0
* @param {string} [archiveServerName] Optional string containing the archive server name; If the archive server is not defined, then the main archive server will be used
* @returns {ArchiveConnection} ArchiveConnection-Object or NULL, if failed
* @since ELC 3.60d / otrisPORTAL 6.0d
* @deprecated since DOCUMENTS 5.0a - Use Context.getArchiveConnection(String archiveServerName) instead
**/
/**
* @memberof context
* @function hasPEMModule
* @instance
* @summary Function to check if a module is licenced in the pem.
* @param {number} moduleConst from PEM Module Constants.
* @returns {Boolean} <code>true</code> if licenced, otherwise \ false
* @since DOCUMENTS 5.0c HF2
* @example
* util.out(context.hasPEMModule(context.PEM_MODULE_GADGETS));
**/
/**
* @memberof context
* @function sendTCPStringRequest
* @instance
* @summary Send a String as TCP-Request to a server.
* @description With this method it is possible to send a String via TCP to a server. The return value of the function is the response of the server. Optional you can define a timeout in ms this function waits for the response of a server
* @param {string} server String containing the IP address or server host
* @param {number} port int containing the port on which the server is listening
* @param {string} request String with the request that should be sent to the server
* @param {number} [responseTimeout] int with the timeout for the response in ms. Default value is 3000ms
* @returns {string} String containing the response and NULL on error
* @since ELC 3.60b / otrisPORTAL 6.0b
* @example
* var response = context.sendTCPStringRequest("192.168.1.1", "4010", "Hello World", 5000);
* if (!response)
* util.out(context.getLastError());
* else
* util.out(response);
**/
/**
* @memberof context
* @function setClientLang
* @instance
* @summary Set the abbreviation of the current user's portal language.
* @description If you want to set the portal language different from the current users language, you can use this method. As parameter you have to use the two letter abbreviation as defined in the principal's settings in the Windows DOCUMENTS Manager (e.g. "de" for German).
* @param {string} locale String containing the two letter abbreviation for the locale
* @returns {string} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0c
* @see [context.getClientLang]{@link context#getClientLang}
* @example
* context.setClientLang("en"));
**/
/**
* @memberof context
* @function setClientSystemLang
* @instance
* @summary Set the script's execution context portal language to the desired language.
* @param {number} langIndex integer value of the index of the desired system language
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51g / otrisPORTAL 5.1g
* @deprecated since DOCUMENTS 4.0c use setClientLang(String locale) instead
* @example
* util.out(context.getClientSystemLang());
* var erg = context.setClientSystemLang(0); // first portal language
**/
/**
* @memberof context
* @function setFolderPosition
* @instance
* @summary Place a top level folder a at given position in the global context.
* @description This method can be used to set the position of a top level folder (public, public dynamic or only subfolders folder with no parent) in the global context.
* @param {Folder} folder Folder object whose position to be set.
* @param {number} position new internal position number of folder.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 5.0a
* @see [context.getFolderPosition]{@link context#getFolderPosition} [Folder.getPosition]{@link Folder#getPosition} [Folder.setPosition]{@link Folder#setPosition}
* @example
* // Create a folder B and place it before a folder A
* var folderA = context.getFoldersByName("folderA").first();
* var posA = context.getFolderPosition(folderA);
*
* var folderB = context.createFolder("folderB", "public");
* if (!context.setFolderPosition(folderB, posA - 1))
* throw context.getLastError();
**/
/**
* @memberof context
* @function setOrAddCustomProperty
* @instance
* @summary Creates or modifies a global custom property according the name and type.
* @param {string} name String value defining the name
* @param {string} type String value defining the type
* @param {string} value String value defining the value
* @returns {CustomProperty} CustomProperty
* @since DOCUMENTS 5.0
* @see [context.getCustomProperties]{@link context#getCustomProperties}
* @see [context.addCustomProperty]{@link context#addCustomProperty}
* @example
* var custProp = context.setOrAddCustomProperty("favorites", "string", "peachit");
* if (!custProp)
* util.out(context.getLastError());
**/
/**
* @memberof context
* @function setPrincipalAttribute
* @instance
* @summary Set an attribute of the DOCUMENTS principal to the desired value.
* @param {string} attributeName the technical name of the desired attribute
* @param {string} value the value that should be assigned
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51b / otrisPORTAL 5.1b
* @see [context.getCurrentUserAttribute]{@link context#getCurrentUserAttribute} [context.getPrincipalAttribute]{@link context#getPrincipalAttribute}
* @example
* context.setPrincipalAttribute("executive.eMail", "test@mail.de");
* util.out(context.getPrincipalAttribute("executive.eMail"));
**/
/**
* @memberof context
* @function setProgressBar
* @instance
* @summary Sets the progress (%) of the progress bar in the Documents-Manager during the PortalScript execution.
* @param {number} value Float with in % of the execution (value >= 0 and value <= 100)
* @returns {void}
* @since DOCUMENTS 5.0c
* @see [context.setProgressBarText]{@link context#setProgressBarText} [context.getProgressBar]{@link context#getProgressBar}
* @example
* context.setProgressBarText("Calculating...");
* context.setProgressBar(0.0); // set progress bar to 0.0%
* for (var i; i<100; i++) {
* // do something
* context.setProgressBar(i);
* }
**/
/**
* @memberof context
* @function setProgressBarText
* @instance
* @summary Sets the progress bar text in the Documents-Manager during the PortalScript execution.
* @param {string} text String with the text to displayed in the progress bar
* @returns {void}
* @since DOCUMENTS 5.0c
* @see [context.setProgressBar]{@link context#setProgressBar} [context.getProgressBar]{@link context#getProgressBar}
* @example
* context.setProgressBarText("Calculating...");
* context.setProgressBar(0.0); // set progress bar to 0.0%
* for (var i; i<100; i++) {
* // do something
* context.setProgressBar(i);
* }
**/
/**
* @interface ControlFlow
* @summary The ControlFlow class has been added to the DOCUMENTS PortalScripting API to gain full control over a file's workflow by scripting means.
* @description You may access ControlFlow objects of a certain WorkflowStep by the different methods described in the WorkflowStep chapter. The objects of this class reflect only outgoing control flows of a WorkflowStep object.
* Note: This class and all of its methods and attributes require a full workflow engine license, it does not work with pure submission lists.
* @since ELC 3.51e / otrisPORTAL 5.1e
*/
/**
* @memberof ControlFlow
* @summary String value containing the unique internal ID of the ControlFlow.
* @description
* Note: This property requires a full workflow engine license, it does not work with pure submission lists. The property is readonly.
* @member {string} id
* @instance
* @since ELC 3.51e / otrisPORTAL 5.1e
**/
/**
* @memberof ControlFlow
* @summary String value containing the ergonomic label of the ControlFlow.
* @description This is usually the label of the according button in the web surface.
* Note: This property requires a full workflow engine license, it does not work with pure submission lists. The property is readonly.
* @member {string} label
* @instance
* @since ELC 3.51e / otrisPORTAL 5.1e
**/
/**
* @memberof ControlFlow
* @summary String value containing the technical name of the ControlFlow.
* @description
* Note: This property requires a full workflow engine license, it does not work with pure submission lists. The property is readonly.
* @member {string} name
* @instance
* @since ELC 3.51e / otrisPORTAL 5.1e
**/
/**
* @memberof ControlFlow
* @function getAttribute
* @instance
* @summary Get the String value of an attribute of the ControlFlow.
* @description
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @param {string} attribute String containing the name of the desired attribute
* @returns {string} String containing the value of the desired attribute
* @since ELC 3.51e / otrisPORTAL 5.1e
**/
/**
* @memberof ControlFlow
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @description
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @returns {string} Text of the last error as String
* @since ELC 3.51e / otrisPORTAL 5.1e
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof ControlFlow
* @function setAttribute
* @instance
* @summary Set the String value of an attribute of the ControlFlow to the desired value.
* @description
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @param {string} attribute String containing the name of the desired attribute
* @param {string} value String containing the desired value of the attribute
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51e / otrisPORTAL 5.1e
**/
/**
* @interface ControlFlowIterator
* @summary The ControlFlowIterator class has been added to the DOCUMENTS PortalScripting API to gain full control over a file's workflow by scripting means.
* @description You may access ControlFlowIterator objects of a certain WorkflowStep by the different methods described in the WorkflowStep chapter. The objects of this class reflect a list of outgoing control flows of a WorkflowStep object.
* Note: This class and all of its methods and attributes require a full workflow engine license, it does not work with pure submission lists.
* @since ELC 3.51e / otrisPORTAL 5.1e
*/
/**
* @memberof ControlFlowIterator
* @function first
* @instance
* @summary Retrieve the first ControlFlow object in the ControlFlowIterator.
* @description
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @returns {ControlFlow} ControlFlow or <code>null</code> in case of an empty ControlFlowIterator
* @since ELC 3.51e / otrisPORTAL 5.1e
**/
/**
* @memberof ControlFlowIterator
* @function next
* @instance
* @summary Retrieve the next ControlFlow object in the ControlFlowIterator.
* @description
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @returns {ControlFlow} ControlFlow or <code>null</code> if end of ControlFlowIterator is reached.
* @since ELC 3.51e / otrisPORTAL 5.1e
**/
/**
* @memberof ControlFlowIterator
* @function size
* @instance
* @summary Get the amount of ControlFlow objects in the ControlFlowIterator.
* @description
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @returns {number} integer value with the amount of ControlFlow objects in the ControlFlowIterator
* @since ELC 3.51e / otrisPORTAL 5.1e
**/
/**
* @interface CustomProperty
* @summary The CustomProperty class provides access to the user properties.
* @description The class CustomProperty provides a container where used specific data can be stored. E.g it will be used to store the last search masks. You can save project specific data using this class. The scripting classes SystemUser, AccessProfile and Context have the following access methods available:
* <ul>
* <li>getCustomProperties() </li>
* <li>addCustomProperty() </li>
* <li>setOrAddCustomProperty() </li>
* </ul>
*
* In the DOCUMENTS-Manager you can find the CustomProperty on the relation-tab properties at the fellow and user account, access profiles and file types. The global custom properties are listed in Documents > Global properties. A global custom property must not belong to a SystemUser, an AccessProfile, a file type and another custom property. All custom properties are located in Documents > All properties.
* @description Since DOCUMENTS 5.0 available for AccessProfile and Context
* @since DOCUMENTS 4.0a
* @see [SystemUser.getCustomProperties]{@link SystemUser#getCustomProperties}
* @see [SystemUser.setOrAddCustomProperty]{@link SystemUser#setOrAddCustomProperty}
* @see [SystemUser.addCustomProperty]{@link SystemUser#addCustomProperty}
* @example
* var user = context.findSystemUser("schreiber");
* if (!user)
* throw "invalid user";
*
* // Creation of an unique (name, type) CustomProperty
* var custProp = user.setOrAddCustomProperty("superior", "person", "oppen");
* if (!custProp)
* throw "unable to create CustomProperty " + user.getLastError();
*
* util.out("New CustomProperty: " + custProp.name);
* custProp.deleteCustomProperty();
*
*
* // Creation of multiple equal (name, type) CustomProperty
* for (var i=0; i<5; i++)
* {
* var custProp = user.addCustomProperty("favorites", "something", "value_" + i);
* }
*
*
* var name = "favorites";
* var type = "";
*
* var it = user.getCustomProperties(name, type);
* for (var prop = it.first(); prop; prop = it.next())
* {
* if (prop.type == "something")
* prop.deleteCustomProperty();
* }
*/
/**
* @memberof CustomProperty
* @summary String containing the name of the CustomProperty.
* @member {string} name
* @instance
**/
/**
* @memberof CustomProperty
* @summary String containing the type of the CustomProperty.
* @member {string} type
* @instance
**/
/**
* @memberof CustomProperty
* @summary String containing the value of the CustomProperty.
* @member {string} value
* @instance
**/
/**
* @memberof CustomProperty
* @function addSubProperty
* @instance
* @summary Creates a new subproperty for the custom property.
* @param {string} name String value defining the name
* @param {string} type String value defining the type
* @param {string} value String value defining the value
* @returns {CustomProperty} CustomProperty
* @since DOCUMENTS 5.0
* @see [CustomProperty.setOrAddSubProperty]{@link CustomProperty#setOrAddSubProperty}
* @see [CustomProperty.getSubProperties]{@link CustomProperty#getSubProperties}
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* var custProp = currentUser.setOrAddCustomProperty("superior", "string", "oppen");
* if (!custProp)
* util.out(currentUser.getLastError());
* else
* custProp.addSubProperty("Address", "string", "Dortmund");
**/
/**
* @memberof CustomProperty
* @function deleteCustomProperty
* @instance
* @summary Deletes the CustomProperty.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0a
**/
/**
* @memberof CustomProperty
* @function getAttribute
* @instance
* @summary Get the String value of an attribute of the CustomProperty.
* @description Valid attribute names are <code>name</code>, <code>type</code> and <code>value</code>
* @param {string} attribute String containing the name of the desired attribute
* @returns {string} String containing the value of the desired attribute
* @since DOCUMENTS 4.0a
**/
/**
* @memberof CustomProperty
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since DOCUMENTS 4.0a
**/
/**
* @memberof CustomProperty
* @function getSubProperties
* @instance
* @summary Get a CustomPropertyIterator with subproperties of the custom property.
* @param {string} [nameFilter] String value defining an optional filter depending on the name
* @param {string} [typeFilter] String value defining an optional filter depending on the type
* @returns {CustomPropertyIterator} CustomPropertyIterator
* @since DOCUMENTS 5.0
* @see [CustomProperty.setOrAddSubProperty]{@link CustomProperty#setOrAddSubProperty}
* @see [CustomProperty.addSubProperty]{@link CustomProperty#addSubProperty}
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* var itProp = currentUser.getCustomProperties();
* for (var prop = itProp.first(); prop; prop = itProp.next())
* {
* util.out(prop.name + ": " + prop.value);
* var itSubprop = prop.getSubProperties();
* for (var subprop = itSubprop.first(); subprop; subprop = itSubprop.next())
* {
* util.out("Subproperty name: " + subprop.name + " Value: " + subprop.value);
* }
* }
**/
/**
* @memberof CustomProperty
* @function setAccessProfile
* @instance
* @summary Connects a custom property to an AccessProfile.
* @description An empty profile name disconnects the AccessProfile
*
* @param {string} [nameAccessProfile]
* @returns {boolean}
* @since DOCUMENTS 5.0
* @see [CustomProperty.setSystemUser]{@link CustomProperty#setSystemUser}
* @see [CustomProperty.setFiletype]{@link CustomProperty#setFiletype}
* @example
* if (!custProp.setAccessProfile("Service"))
* throw custProp.getLastError();
*
* custProp.setAccessProfile(""); // disconnects AccessProfile
**/
/**
* @memberof CustomProperty
* @function setAttribute
* @instance
* @summary Set the String value of an attribute of the CustomProperty to the desired value.
* @description Valid attribute names are <code>name</code>, <code>type</code> and <code>value</code>
* @param {string} attribute String containing the name of the desired attribute
* @param {string} value String containing the desired value of the attribute
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0a
**/
/**
* @memberof CustomProperty
* @function setFiletype
* @instance
* @summary Connects a custom property to a filetype.
* @description An empty filetype name disconnects the filetype
*
* @param {string} [nameFiletype]
* @returns {boolean}
* @since DOCUMENTS 5.0
* @see [CustomProperty.setSystemUser]{@link CustomProperty#setSystemUser}
* @see [CustomProperty.setAccessProfile]{@link CustomProperty#setAccessProfile}
* @example
* if (!custProp.setFiletype("ftInvoice"))
* throw custProp.getLastError();
*
* custProp.setFiletype(""); // disconnects filetype
**/
/**
* @memberof CustomProperty
* @function setOrAddSubProperty
* @instance
* @summary Creates a new subproperty or modifies a subproperty according the name and type for the custom property.
* @description This method creates or modifies a unique subproperty for the custom property. The combination of the name and the type make the subproperty unique for the custom property.
* @param {string} name String value defining the name
* @param {string} type String value defining the type
* @param {string} value String value defining the value
* @returns {CustomProperty} CustomProperty
* @since DOCUMENTS 5.0
* @see [CustomProperty.getSubProperties]{@link CustomProperty#getSubProperties}
* @see [CustomProperty.addSubProperty]{@link CustomProperty#addSubProperty}
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* var custProp = currentUser.setOrAddCustomProperty("superior", "string", "oppen");
* if (!custProp)
* util.out(currentUser.getLastError());
* else
* custProp.setOrAddSubProperty("Address", "string", "Dortmund");
**/
/**
* @memberof CustomProperty
* @function setSystemUser
* @instance
* @summary Connects a custom property to a SystemUser.
* @description An empty login disconnects the SystemUser
*
* @param {string} [login]
* @returns {boolean}
* @since DOCUMENTS 5.0
* @see [CustomProperty.setFiletype]{@link CustomProperty#setFiletype}
* @see [CustomProperty.setAccessProfile]{@link CustomProperty#setAccessProfile}
* @example
* if (!custProp.setSystemUser("schreiber"))
* throw custProp.getLastError();
*
* custProp.setSystemUser(""); // disconnects SystemUser
**/
/**
* @interface CustomPropertyIterator
* @summary The CustomPropertyIterator class is an iterator that holds a list of objects of the class CustomProperty.
* @since DOCUMENTS 4.0a
*/
/**
* @memberof CustomPropertyIterator
* @function first
* @instance
* @summary Retrieve the first CustomProperty object in the CustomPropertyIterator.
* @returns {CustomProperty} CustomProperty or <code>null</code> in case of an empty CustomPropertyIterator
* @since DOCUMENTS 4.0a
**/
/**
* @memberof CustomPropertyIterator
* @function next
* @instance
* @summary Retrieve the next CustomProperty object in the CustomPropertyIterator.
* @returns {CustomProperty} CustomProperty or <code>NULL</code> if end of CustomPropertyIterator is reached
* @since DOCUMENTS 4.0a
**/
/**
* @memberof CustomPropertyIterator
* @function size
* @instance
* @summary Get the amount of CustomProperty objects in the CustomPropertyIterator.
* @returns {number} integer value with the amount of CustomProperty objects in the CustomPropertyIterator
* @since DOCUMENTS 4.0a
**/
/**
* @class DBConnection
* @classdesc The DBConnection class allows to connect to external databases.
* With the help of the DBResultSet class you can obtain information from these external databases, and it is possible to execute any other SQL statement on the external databases.
* Note: Important: Please consider the restrictions according the order of reading of the columns of the DBResultSet. Read the example!
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myDB = null;
* var myRS = null;
* try {
* // create DB-Connection to ODBC-64 Datasource "Nordwind"
* myDB = new DBConnection("odbc", "Nordwind");
* if (myDB.getLastError() != null)
* throw "Error connection the database: " + myDB.getLastError();
*
* myRS = myDB.executeQuery("SELECT Nachname, Vorname FROM Personal");
* if (!myRS)
* throw "Error in SELECT statement: " + myDB.getLastError();
*
* // read all persons from the result set
* while (myRS.next()) {
* var fullName = myRS.getString(0) + ", " + myRS.getString(1);
* // var fullName = myRS.getString(1) + ", " + myRS.getString(0); // Fails, because you must read the columns in the correct order!
* // var fullName = myRS.getString(0) + ", " + myRS.getString(0); // Fails, because it is not allowed to read a value twice!
* util.out(fullName);
* }
* } catch (err) {
* util.out(err);
* } finally {
* // Important: free resources!
* if (myRS)
* myRS.close();
* if (myDB)
* myDB.close();
* }
* @summary The constructor is neccessary to connect to the external database.
* @description The resulting DBConnection object may only be used by <b>one</b> single DBResultSet at once, so if you need to open several DBResultSet objects at the same time, you need a separate DBConnection object for each of them.
* Note: At the usage of ODBC datasources it depends on the ODBC client driver, if the credentials for the connection has to be specified at the DSN configuration, or as parameter in the DBConnection constructor. If you have specified the credentials (user, password) at the DSN configuration (ODBC data source administrator), then leave the user and password away at the DBConnection constructor.
* Since ELC 3.50 / otrisPORTAL 5.0
* @param {string} connType String defining the type of database connection. Allowed values are <code>"odbc"</code> and <code>"oracle"</code>
* @param {string} connString String containing the complete connection String; for ODBC connections this is the datasource name (DSN)
* @param {string} user optional String containing the login name used to authenticate against the external database
* @param {string} password optional String containing the (plaintext) password of the user utilized to connect to the database
* @see [DBResultSet]{@link DBResultSet}
*/
/**
* @class DBConnection
* @classdesc The DBConnection class allows to connect to external databases.
* With the help of the DBResultSet class you can obtain information from these external databases, and it is possible to execute any other SQL statement on the external databases.
* Note: Important: Please consider the restrictions according the order of reading of the columns of the DBResultSet. Read the example!
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myDB = null;
* var myRS = null;
* try {
* // create DB-Connection to ODBC-64 Datasource "Nordwind"
* myDB = new DBConnection("odbc", "Nordwind");
* if (myDB.getLastError() != null)
* throw "Error connection the database: " + myDB.getLastError();
*
* myRS = myDB.executeQuery("SELECT Nachname, Vorname FROM Personal");
* if (!myRS)
* throw "Error in SELECT statement: " + myDB.getLastError();
*
* // read all persons from the result set
* while (myRS.next()) {
* var fullName = myRS.getString(0) + ", " + myRS.getString(1);
* // var fullName = myRS.getString(1) + ", " + myRS.getString(0); // Fails, because you must read the columns in the correct order!
* // var fullName = myRS.getString(0) + ", " + myRS.getString(0); // Fails, because it is not allowed to read a value twice!
* util.out(fullName);
* }
* } catch (err) {
* util.out(err);
* } finally {
* // Important: free resources!
* if (myRS)
* myRS.close();
* if (myDB)
* myDB.close();
* }
* @summary The constructor is neccessary to connect to the currently used DOCUMENTS 5 database.
* @description The resulting DBConnection object may only be used by <b>one</b> single DBResultSet at once, so if you need to open several DBResultSet objects at the same time, you need a separate DBConnection object for each of them.
* Since DOCUMENTS 4.0
* @see [DBResultSet]{@link DBResultSet}
*/
/**
* @memberof DBConnection
* @function close
* @instance
* @summary Close the database connection and free the server ressources.
* @description
* Note: It is strongly recommanded to close each DBConnection object you have created, since database connections are so-called expensive ressources and should be used carefully.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
* @see [DBResultSet.close]{@link DBResultSet#close}
**/
/**
* @memberof DBConnection
* @function executeQuery
* @instance
* @summary Execute a SELECT statement and retrieve a DBResultSet containing the result rows found by the statement.
* @description
* Note: This instruction should only be used to SELECT on the external database, since the method always tries to create a DBResultSet. If you need to execute different SQL statements, refer to the DBConnection.executeStatement() method.
* Note: x64/UTF-8 DOCUMENTS version: since DOCUMENTS 4.0a HF2 the method handles the statement as UTF-8-String
* @param {string} sqlStatement String containing the SELECT statement you want to execute in the database
* @returns {DBResultSet} DBResultSet containing the result rows generated by the SELECT instruction
* @since ELC 3.50 / otrisPORTAL 5.0
* @see [DBConnection.executeStatement]{@link DBConnection#executeStatement}
**/
/**
* @memberof DBConnection
* @function executeQueryUC
* @instance
* @summary Execute a SELECT statement using a x64/UTF-8 DOCUMENTS and retrieve a DBResultSet containing the result rows found by the statement.
* @description
* Note: This instruction should only be used to SELECT on the external database, since the method always tries to create a DBResultSet. If you need to execute different SQL statements, refer to the DBConnection.executeStatement() method.
* @param {string} sqlStatement String containing the SELECT statement you want to execute in the database
* @returns {DBResultSet} DBResultSet containing the result rows generated by the SELECT instruction
* @since DOCUMENTS 4.0
* @see [DBConnection.executeStatementUC]{@link DBConnection#executeStatementUC}
* @deprecated since DOCUMENTS 4.0a HF2 use DBConnection.executeQuery() instead
**/
/**
* @memberof DBConnection
* @function executeStatement
* @instance
* @summary Execute any SQL statement on the external database.
* @description You can execute any SQL statement, as long as the database driver used for the connection supports the type of instruction. Use this method especially if you want to INSERT or UPDATE or DELETE data rows in tables of the external database. If you need to SELECT table rows, refer to the DBConnection.executeQuery() method.
* Note: x64/UTF-8 DOCUMENTS version: since DOCUMENTS 4.0a HF2 the method handles the statement as UTF-8-String
* @param {string} sqlStatement
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
* @see [DBConnection.executeQuery]{@link DBConnection#executeQuery}
**/
/**
* @memberof DBConnection
* @function executeStatementUC
* @instance
* @summary Execute any SQL statement using a x64/UTF-8 DOCUMENTS on the external database.
* @description You can execute any SQL statement, as long as the database driver used for the connection supports the type of instruction. Use this method especially if you want to INSERT or UPDATE or DELETE data rows in tables of the external database. If you need to SELECT table rows, refer to the DBConnection.executeQueryUC() method.
* @param {string} sqlStatement
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0
* @see [DBConnection.executeQueryUC]{@link DBConnection#executeQueryUC}
* @deprecated since DOCUMENTS 4.0a HF2 use DBConnection.executeStatement() instead
**/
/**
* @memberof DBConnection
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since ELC 3.50 / otrisPORTAL 5.0
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @interface DBResultSet
* @summary The DBResultSet class contains a list of resultset rows.
* @description You need an active DBConnection object to execute an SQL query which is used to create a DBResultSet.
* Note: Important: Please consider the restrictions according the order of reading of the columns of the DBResultSet. Read the example!
* The following data types for database columns will be supported:
* <table border=1 cellspacing=0>
* <tr><td><b>SQL data type</b></td><td><b>access method</b></td></tr>
* <tr><td>SQL_INTEGER</td><td>getInt(), getString()</td></tr>
* <tr><td>SQL_SMALLINT</td><td>getInt(), getString()</td></tr>
* <tr><td>SQL_BIGINT</td><td>getInt(), getString()</td></tr>
* <tr><td>SQL_FLOAT</td><td>getFloat(), getInt(), getString()</td></tr>
* <tr><td>SQL_DECIMAL</td><td>getFloat(), getInt(), getString()</td></tr>
* <tr><td>SQL_NUMERIC</td><td>getFloat(), getInt(), getString()</td></tr>
* <tr><td>SQL_BIT</td><td>getBool(), getString()</td></tr>
* <tr><td>SQL_TIMESTAMP</td><td>getTimestamp(), getString()</td></tr>
* <tr><td>SQL_DATE</td><td>getDate(), getString()</td></tr>
* <tr><td>SQL_GUID</td><td>getString()</td></tr>
* <tr><td>SQL_VARCHAR</td><td>getString()</td></tr>
* <tr><td>SQL_CHAR</td><td>getString()</td></tr>
* <tr><td>all other types</td><td>getString()</td></tr>
* </table>
*
* @description Since DOCUMENTS 5.0c HF1 (support for SQL_GUID)
* @since ELC 3.50 / otrisPORTAL 5.0
* @see [DBConnection]{@link DBConnection}
* @example
* // create DB-Connection to ODBC-64 Datasource "Nordwind"
* var myDB = new DBConnection("odbc", "Nordwind");
* if (myDB && myDB.getLastError() == null)
* {
* var myRS = myDB.executeQuery("SELECT Nachname, Vorname FROM Personal");
* if (myRS)
* {
* // read all persons from the result set
* while (myRS.next())
* {
* var fullName = myRS.getString(0) + ", " + myRS.getString(1);
* // var fullName = myRS.getString(1) + ", " + myRS.getString(0); // Fails, because you must read the columns in the correct order!
* // var fullName = myRS.getString(0) + ", " + myRS.getString(0); // Fails, because it is not allowed to read a value twice!
* util.out(fullName);
* }
* // Important: free resource!
* myRS.close()
* }
* else
* util.out("Error in SELECT statement: " + myDB.getLastError());
*
* // Important: free resource!
* myDB.close();
* }
* else
* util.out("Error connection the database: " + myDB.getLastError())
*/
/**
* @memberof DBResultSet
* @function close
* @instance
* @summary Close the DBResultSet and free the server ressources.
* @description
* Note: It is strongly recommanded to close each DBResultSet object you have created, since database connections and resultsets are so-called expensive ressources and should be used carefully.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
* @see [DBConnection.close]{@link DBConnection#close}
**/
/**
* @memberof DBResultSet
* @function getBool
* @instance
* @summary Read the indicated column of the current row of the DBResultSet as a boolean value.
* @param {number} colNo integer value (zero based) indicating the desired column of the current row of the DBResultSet
* @returns {boolean} boolean value representing the indicated column of the current row
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof DBResultSet
* @function getColName
* @instance
* @summary Function returns the name of a column.
* @param {number} colNo integer value (zero based) indicating the desired column
* @returns {string} Column name as String
* @since DOCUMENTS 5.0
**/
/**
* @memberof DBResultSet
* @function getDate
* @instance
* @summary Read the indicated column of the current row of the DBResultSet as a Date object.
* @description
* Note: The return value will be null if the content of the indicated column cannot be converted to a Date object.
* Note: every value of a DBResultSet can only be read one time and in the correct order!
* @param {number} colNo integer value (zero based) indicating the desired column of the current row of the DBResultSet
* @returns {Date} Date object representing the indicated column of the current row or <code>NULL</code> if is null-value
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof DBResultSet
* @function getFloat
* @instance
* @summary Read the indicated column of the current row of the DBResultSet as a float value.
* @description
* Note: The return value will be NaN if the content of the indicated column cannot be converted to a float value.
* Note: every value of a DBResultSet can only be read one time and in the correct order!
* @param {number} colNo integer value (zero based) indicating the desired column of the current row of the DBResultSet
* @returns {number} float value representing the indicated column of the current row or <code>NULL</code> if is null-value
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof DBResultSet
* @function getInt
* @instance
* @summary Read the indicated column of the current row of the DBResultSet as an integer value.
* @description
* Note: The return value will be NaN if the content of the indicated column cannot be converted to an integer value.
* Note: every value of a DBResultSet can only be read one time and in the correct order!
* @param {number} colNo integer value (zero based) indicating the desired column of the current row of the DBResultSet
* @returns {number} integer value representing the indicated column of the current row or <code>NULL</code> if is null-value
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof DBResultSet
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since ELC 3.50 / otrisPORTAL 5.0
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof DBResultSet
* @function getNumCols
* @instance
* @summary Function returns the amount of columns of the DBResultSet.
* @returns {number} Column count as int
* @since DOCUMENTS 5.0
**/
/**
* @memberof DBResultSet
* @function getString
* @instance
* @summary Read the indicated column of the current row of the DBResultSet as a String.
* @description
* Note: x64/UTF-8 DOCUMENTS version: since DOCUMENTS 4.0a HF2 the method transcode the fetched data to UTF-8
* Note: every value of a DBResultSet can only be read one time and in the correct order!
* @param {number} colNo integer value (zero based) indicating the desired column of the current row of the DBResultSet
* @returns {string} String representing the indicated column of the current row or <code>NULL</code> if is null-value
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof DBResultSet
* @function getTimestamp
* @instance
* @summary Read the indicated column of the current row of the DBResultSet as a Date object including the time.
* @description
* Note: The return value will be null if the content of the indicated column cannot be converted to a Date object.
* Note: every value of a DBResultSet can only be read one time and in the correct order!
* @param {number} colNo integer value (zero based) indicating the desired column of the current row of the DBResultSet
* @returns {Date} Date object (including time) representing the indicated column of the current row or <code>NULL</code> if is null-value
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof DBResultSet
* @function getUCString
* @instance
* @summary Read the indicated column of the current row of the DBResultSet on a x64/UTF-8 DOCUMENTS as a String.
* @description
* Note: every value of a DBResultSet can only be read one time and in the correct order!
* @param {number} colNo integer value (zero based) indicating the desired column of the current row of the DBResultSet
* @returns {string} String representing the indicated column of the current row or <code>NULL</code> if is null-value
* @since DOCUMENTS 4.0
* @deprecated since DOCUMENTS 4.0a HF2 use DBResultSet.getString() instead
**/
/**
* @memberof DBResultSet
* @function next
* @instance
* @summary Move the resultset pointer to the next row of the DBResultSet.
* @description The method must be called at least once after retrieving a DBResultSet, because the newly created object does not point to the first result row but to BOF (beginning of file).
* Note: every value of a DBResultSet can only be read one time and in the correct order!
* @returns {boolean} <code>true</code> if the DBResultSet now points to the next row, <code>false</code> if there is no further result row
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @interface DocFile
* @summary The DocFile class implements the file object of DOCUMENTS.
* @description You may access a single DocFile with the help of the attribute <code>context.file</code> or by creating a FileResultset. There are no special properties available, but each field of a file is mapped to an according property. You can access the different field values with their technical names.
*
* For this reason it is mandatory to use programming language friendly technical names, meaning
* <ul>
* <li>only letters, digits and the underscore "_" are allowed. </li>
* <li>no whitespaces or any special characters are allowed. </li>
* <li>the technical name must not start with a digit. </li>
* <li>only the first 32 characters of the technical name are significant to identify the field.</li>
* </ul>
*
* @example
* var myFile = context.file;
* var priority = myFile.Priority; // read a field value
* myFile.Remark = "Just a remark"; // assign a value to a field
* myFile.sync(); // apply changes in field values to the file
*/
/**
* @memberof DocFile
* @summary The technical name of a field.
* @description Each field of a DocFile is mapped to an according property. You can access the field value with the technical name.
* @member {any} fieldName
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myFile = context.file;
* var strValue = myFile.stringField;
* myFile.dateField = new Date();
* myFile.sync();
**/
/**
* @memberof DocFile
* @function abort
* @instance
* @summary Cancel edit mode for a file.
* @description If you switched a file to edit mode with the startEdit() method and if you want to cancel this (e.g. due to some error that has occurred in the mean time) this function should be used to destroy the scratch copy which has been created by the startEdit() instruction.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
* @see [DocFile.startEdit]{@link DocFile#startEdit} [DocFile.commit]{@link DocFile#commit}
* @example
* var myFile = context.file;
* myFile.startEdit();
* myFile.Field = "value";
* myFile.abort(); // effect: "value" is not applied!
**/
/**
* @memberof DocFile
* @function addDocumentFromFileSystem
* @instance
* @summary Add a file as a new Document from the server's filesystem to a given Register.
* @description It is possible to parse Autotexts inside the source file to fill the Document with the contents of index fields of a DocFile object. The max. file size for the source file is 512 KB.
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {string} pathDocument String value containing the complete filepath to the source file on the server
* @param {string} targetRegister String value containing the technical name of the desired Register
* @param {string} targetFileName String value containing the desired filename of the uploaded Document
* @param {boolean} [deleteDocumentAtFileSystem] optional boolean value to decide whether to delete the source file on the server's filesystem
* @param {boolean} [parseAutoText] optional boolean value to decide whether to parse the AutoText values inside the source file. Note: if you want to make use of AutoTexts in this kind of template files, you need to use double percentage signs instead of single ones, e.g. %%Field1%% instead of %Field1%!
* @param {DocFile} [referencFileToParse] optional DocFile object to be used to parse the AutoTexts inside the template. If you omit this parameter, the current DocFile object is used as the data source.
* @returns {Document} <code>Document</code> if successful, <code>null</code> in case of any error
* @since ELC 3.51f / otrisPORTAL 5.1f
* @example
* var f = context.file;
* var success = f.addDocumentFromFileSystem("c:\\temp\\test.rtf", "Documents", "parsedRTFFile.rtf", false, true);
**/
/**
* @memberof DocFile
* @function addPDF
* @instance
* @summary Create a PDF file containing the current DocFile's contents and store it on a given document register.
* @description The different document types of your documents on your different tabs require the appropriate PDF filter programs to be installed and configured in DOCUMENTS. To successfully add the created PDF file to a register the DocFile needs to be in edit mode (via startEdit() method), and the changes have to be applied via commit().
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {string} pathCoverXML String containing full path and filename of the template xml file to parse
* @param {boolean} createCover boolean whether to create a field list or to only take the documents
* @param {string} pdfFileName String value for the desired file name of the created PDF
* @param {string} targetRegister String value containing the technical name of the target document register
* @param {any[]} sourceRegisterNames Array with the technical names of the document registers you want to include
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50a / otrisPORTAL 5.0a
* @example
* var source = new Array();
* source.push("FirstRegister");
* source.push("SecondRegister");
*
* var docFile = context.file;
* docFile.startEdit();
*
* docFile.addPDF("c:\\tmp\\cover.xml",
* true,
* "GeneratedPDF.pdf",
* "MyTargetRegister",
* source
* );
* docFile.commit();
**/
/**
* @memberof DocFile
* @function archive
* @instance
* @summary Archive the DocFile object.
* @description The target archive has to be configured in the filetype definition (in the Windows Portal Client) as the default archive. If no default archive is defined, the execution of this operation will fail.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myFile = context.file;
* myFile.archive();
**/
/**
* @memberof DocFile
* @function archive
* @instance
* @summary Archive the DocFile object to the desired archive.
* @description If the target archive key is misspelled or if the target archive does not exist, the operation will fall back to the default archive, as long as it is configured in the filetype definition. So the function will only fail if both the target archive and the default archive are missing.
* Note: For EE.i: It is important to know that the target archive String must use the socalled XML-Server syntax. The old EAG syntax is not supported. It is as well neccessary to use a double backslash (\\) if you define your target archive as an ECMAScript String value, because a single backslash is a special character.
* Since EE.x: ELC 3.60a / otrisPORTAL 6.0a
* Since EAS: Documents 4.0
* @param {string} archiveKey String value containing the complete archive key for EE.i or schema|view for EE.x of the desired target archive
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since EE.i: ELC 3.51c / otrisPORTAL 5.1c
* @example
* // Example for EE.i:
* var myFile = context.file;
* var targetArchive = "$(#TOASTUP)\\STANDARD";
* targetArchive += "@myeei"; // since Documents 4.0 using multi archive server
* myFile.archive(targetArchive);
* @example
* // Example for EE.x:
* var myFile = context.file;
* var view = "Unit=Default/Instance=Default/View=DeliveryNotes";
* var schema = "Unit=Default/Instance=Default/DocumentSchema=LIEFERSCHEINE";
* var target = schema + "|" + view;
* target += "@myeex"; // since Documents 4.0 using multi archive server
* myFile.archive(target);
* @example
* // Example for EAS:
* var myFile = context.file;
* myFile.archive("@myeas"); // using multi archive server
**/
/**
* @memberof DocFile
* @function archive
* @instance
* @summary Archive the DocFile object according to the given ArchivingDescription object.
* @description This is the most powerful way to archive a file through scripting, since the ArchivingDescription object supports a convenient way to influence which parts of the DocFile should be archived.
* Since EE.x: ELC 3.60a / otrisPORTAL 6.0a
* Since EAS: Documents 4.0
* @param {ArchivingDescription} desc ArchivingDescription object that configures several archiving options
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since EE.i: ELC 3.51c / otrisPORTAL 5.1c
* @see [ArchivingDescription]{@link ArchivingDescription}
* @example
* // Example for EE.i:
* var myFile = context.file;
* var ad = new ArchivingDescription();
* ad.targetArchive = "$(#TOASTUP)\\STANDARD";
* ad.archiveServer = "myeei"; // since Documents 4.0 using multi archive server
* ad.archiveStatus = true;
* ad.archiveMonitor = true;
* ad.addRegister("all_docs"); // archive all attachments
* var success = myFile.archive(ad);
* if (success)
* {
* context.returnType = "html";
* return ("<p>ArchiveFileID: " + myFile.getAttribute("Key") + "<p>");
* }
* @example
* // Example for EE.x:
* var myFile = context.file;
* var ad = new ArchivingDescription();
* ad.targetView = "Unit=Default/Instance=Default/View=DeliveryNotes";
* ad.targetSchema = "Unit=Default/Instance=Default/DocumentSchema=LIEFERSCHEINE";
* ad.archiveServer = "myeex"; // since Documents 4.0 using multi archive server
* ad.archiveStatus = true;
* ad.archiveMonitor = true;
* ad.addRegister("all_docs"); // archive all attachments
* var success = myFile.archive(ad);
* if (success)
* {
* context.returnType = "html";
* return ("<p>ArchiveFileID: " + myFile.getArchiveKey() + "</p>");
* }
* @example
* // Example for EAS:
* var myFile = context.file;
* var ad = new ArchivingDescription();
* ad.archiveServer = "myeas"; // using multi archive server
* ad.archiveStatus = true;
* ad.archiveMonitor = true;
* ad.addRegister("all_docs"); // archive all attachments
* var success = myFile.archive(ad);
* if (success)
* {
* context.returnType = "html";
* return ("<p>ArchiveFileID: " + myFile.getArchiveKey() + "</p>");
* }
**/
/**
* @memberof DocFile
* @function archiveAndDelete
* @instance
* @summary Archive the DocFile object and remove the DOCUMENTS file.
* @description The target archive has to be configured in the filetype definition (in the Windows Portal Client) as the default archive. It depends on the filetype settings as well, whether Status and Monitor will be archived as well. If no default archive is defined, the execution of this operation will fail.
* Note: It is strictly forbidden to access the DocFile object after this function has been executed successfully; if you try to access it, your script will fail, because the DocFile does not exist any longer in DOCUMENTS. For the same reason it is strictly forbidden to execute this function in a signal exit PortalScript.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myFile = context.file;
* myFile.archiveAndDelete();
**/
/**
* @memberof DocFile
* @function asJSON
* @instance
* @summary Creates a JSON-String of this file.
* @description
* Available DocFile attributes:
* <ul>
* <li><code>"DlcFile_Title"</code></li>
* <li><code>"DlcFile_Owner"</code></li>
* <li><code>"DlcFile_Created"</code></li>
* <li><code>"DlcFile_LastEditor"</code></li>
* <li><code>"DlcFile_LastModified"</code>undefinedundefinedundefinedundefinedundefined</li>
* </ul>
*
* @param {string[]} [fieldList] optional String array, that specifies the DocFile attributes and field names, that will be part of JSON export
* @returns {string}
**/
/**
* @memberof DocFile
* @function cancelWorkflow
* @instance
* @summary Cancel the current workflow for the file.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51e / otrisPORTAL 5.1e
* @example
* var f = context.file;
* f.cancelWorkflow();
**/
/**
* @memberof DocFile
* @function changeFiletype
* @instance
* @summary Change the filetype of this file.
* @param {string} nameFiletype String containing the technical name of the filetype.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0e
* @example
* var file = context.file;
* if (!file.changeFiletype("newFiletype"))
* util.out(file.getLastError());
**/
/**
* @memberof DocFile
* @function checkWorkflowReceiveSignal
* @instance
* @summary Checks the receive signals of the workflow for the DocFile object.
* @description This method can only be used for a DocFile, that runs in a workflow and the workflow has receive signals. Usually the receive signals of the workflow step will be checked by a periodic job. Use this method to trigger the check of the receive signals for the DocFile.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0a
* @example
* var myFile = context.file;
* var succ = myFile.checkWorkflowReceiveSignal();
* if (!succ)
* util.out(myFile.getLastError());
**/
/**
* @memberof DocFile
* @function clearFollowUpDate
* @instance
* @summary Clear a followup date for a desired user.
* @param {SystemUser} pUser SystemUser object of the desired user
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51b / otrisPORTAL 5.1b
* @see [DocFile.setFollowUpDate]{@link DocFile#setFollowUpDate}
* @example
* var docFile = context.file;
* var su = context.getSystemUser();
* docFile.clearFollowUpDate(su);
**/
/**
* @memberof DocFile
* @function commit
* @instance
* @summary Commit any changes to the DocFile object.
* @description This method is mandatory to apply changes to a file that has been switched to edit mode with the startEdit() method. It is strictly prohibited to execute the commit() method in a script which is attached to the onSave scripting hook.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
* @see [DocFile.startEdit]{@link DocFile#startEdit} [DocFile.sync]{@link DocFile#sync} [DocFile.abort]{@link DocFile#abort}
* @example
* var myFile = context.file;
* myFile.startEdit();
* myFile.Field = "value";
* myFile.commit();
**/
/**
* @memberof DocFile
* @function connectFolder
* @instance
* @summary Store a reference to the current file in the desired target folder.
* @description The (public) folder must be a real folder, it must not be a dynamic filter, nor a "only subfolder" object.
* @param {Folder} fObj Folder object representing the desired target public folder
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since ELC 3.51h / otrisPORTAL 5.1h
* @see [DocFile.disconnectFolder]{@link DocFile#disconnectFolder}
* @example
* var f = context.file;
* var fObj = context.getFoldersByName("Invoices").first();
* var success = f.connectFolder(fObj);
**/
/**
* @memberof DocFile
* @function countFields
* @instance
* @summary Count fields with a desired name in the file.
* @description
* Note: When this function is called on an EE.x DocFile with an empty field name, the return value may be greater than expected. The DOCUMENTS image of such a file can include EE.x system fields and symbolic fields for other imported scheme attributes (blob content, notice content).
* @param {string} fieldName String containing the technical name of the fields to be counted.
* @returns {number} The number of fields als an Integer.
* @since DOCUMENTS 4.0c HF2
* @example
* var key = "Unit=Default/Instance=Default/Pool=DEMO/Pool=RECHNUNGEN/Document=RECHNUNGEN.41D3694E2B1E11DD8A9A000C29FACDC2@eex1"
* var docFile = context.getArchiveFile(key);
* if (!docFile)
* throw "archive file does not exist: " + key;
* else
* util.out(docFile.countFields("fieldName"));
**/
/**
* @memberof DocFile
* @function createMonitorFile
* @instance
* @summary Creates a workflow monitor file in the server's file system.
* @description This method creates a monitor file in the server's file system with the workflow monitor content of the DocFile. The file will be created as a html-file.
* Note: This generated file will no be automatically added to the DocFile
* @param {boolean} [asPDF] boolean parameter that indicates that a pdf-file must be created instead of a html-file
* @param {string} [locale] String (de, en,..) in which locale the file must be created (empty locale = log-in locale)
* @returns {string} String containing the path of the created file
* @since DOCUMENTS 4.0a HF2
**/
/**
* @memberof DocFile
* @function createStatusFile
* @instance
* @summary Creates a status file in the server's file system.
* @description This method creates a status file in the server's file system with the status content of the DocFile. The file will be created as a html-file.
* Note: This generated file will no be automatically added to the DocFile
* @param {boolean} [asPDF] boolean parameter that indicates that a pdf-file must ge created instead of a html-file
* @param {string} [locale] String (de, en,..) in which locale the file must be created (empty locale = log-in locale)
* @returns {string} String containing the path of the created file
* @since DOCUMENTS 4.0a HF2
**/
/**
* @memberof DocFile
* @function deleteFile
* @instance
* @summary Delete the DocFile object.
* @description If there's another PortalScript attached to the onDelete scripting hook, it will be executed right before the deletion takes place.
* Note: It is strictly forbidden to access the DocFile object after this function has been executed successfully; if you try to access it, your script will fail, because the DocFile does not exist any longer in DOCUMENTS. For the same reason it is strictly forbidden to execute this function in a signal exit PortalScript.
* Note: The parameters moveTrash, movePool are ignored for archive files. The parameter allVersions requires an EAS/EDA file and is ignored otherwise.
* Since ELC 3.50n / otrisPORTAL 5.0n (moveTrash parameter)
* Since ELC 3.51f / otrisPORTAL 5.1f (movePool parameter)
* Since DOCUMENTS 4.0a HF1 (available for archive files)
* Since DOCUMENTS 4.0e (all versions)
* @param {boolean} [moveTrash] optional boolean parameter to decide whether to move the deleted file to the trash folder
* @param {boolean} [movePool] optional boolean parameter to decide whether to move the deleted file's object to the file pool
* @param {boolean} [allVersions] optional boolean parameter to delete all versions of an EAS archive file at once.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myFile = context.file;
* myFile.deleteFile(false, true);
**/
/**
* @memberof DocFile
* @function disconnectArchivedFile
* @instance
* @summary Uncouple an active file from the archived version.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0d
* @see [DocFile.archive]{@link DocFile#archive}
* @example
* var f = context.file;
* var f.archive();
* var success = f.disconnectArchivedFile();
**/
/**
* @memberof DocFile
* @function disconnectFolder
* @instance
* @summary Remove a reference to the current file out of the desired target folder.
* @description The (public) folder must be a real folder, it must not be a dynamic filter, nor a "only subfolder" object.
* @param {Folder} fObj Folder object representing the desired target public folder
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since ELC 3.51h / otrisPORTAL 5.1h
* @see [DocFile.connectFolder]{@link DocFile#connectFolder}
* @example
* var f = context.file;
* var fObj = context.getFoldersByName("Invoices").first();
* var success = f.disconnectFolder(fObj);
**/
/**
* @memberof DocFile
* @function exportXML
* @instance
* @summary Export the file as an XML file.
* @description
* Since ELC 3.60e / otrisPORTAL 6.0e (Option: export of status & monitor)
* @param {string} pathXML String containing full path and filename of the desired target xml file
* @param {boolean} withDocuments boolean value to include the documents. The value must be set to <code>true</code> in case status or monitor information are to be inserted.
* @param {boolean} [withStatus] boolean value to include status information. The value must be set to <code>true</code> in order to add the status. Status Information will then be generated into a file which will be added to the documents. Please note that therefore <code>withDocuments</code> must be set to true in order to get Status information.
* @param {boolean} [withMonitor] boolean value to include Monitor information. The value must be set to <code>true</code> in order to add the monitor. Monitor Information will then be generated into a file which will be added to the documents. Please note that therefore <code>withDocuments</code> must be set to true in order to get Monitor information.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50a / otrisPORTAL 5.0a
* @example
* var docFile = context.file;
* docFile.exportXML("c:\\tmp\\myXmlExport.xml", true, false, true);
**/
/**
* @memberof DocFile
* @function forwardFile
* @instance
* @summary Forward file in its workflow via the given control flow.
* @description This method only works if the file is inside a workflow and inside a workflow action that is accessible by a user of the web interface. Based on that current workflowstep you need to gather the ID of one of the outgoing control flows of that step. The access privileges of the current user who tries to execute the script are taken into account. Forwarding the file will only work if that control flow is designed to forward without query.
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @param {string} controlFlowId String containing the technical ID of the outgoing control flow that should be passed
* @param {string} [comment] optional String value containing a comment to be automatically added to the file's monitor
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var docFile = context.file;
* var step = docFile.getCurrentWorkflowStep();
* var flowId = step.firstControlFlow;
* docFile.forwardFile(flowId);
**/
/**
* @memberof DocFile
* @function fromJSON
* @instance
* @summary Updates a file from a JSON-String.
* @param {string} jsonstring
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 5.0 HF1
* @see [DocFile.asJSON]{@link DocFile#asJSON}
**/
/**
* @memberof DocFile
* @function getAllLockingWorkflowSteps
* @instance
* @summary Get a list of all locking workflow step that currently lock the file.
* @description The locking workflow steps do not need to be locked by the current user executing the script, this function as well returns all locking steps which refer to different users.
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @returns {WorkflowStepIterator} WorkflowStepIterator object which represents a list of all locking workflow steps for the file
* @since ELC 3.51e / otrisPORTAL 5.1e
* @see [DocFile.getCurrentWorkflowStep]{@link DocFile#getCurrentWorkflowStep} [DocFile.getFirstLockingWorkflowStep]{@link DocFile#getFirstLockingWorkflowStep}
* @example
* var f = context.file;
* var stepIter = f.getAllLockingWorkflowSteps();
* if (stepIter.size() > 0)
* util.out("File is locked by " + stepIter.size() + " workflow steps");
**/
/**
* @memberof DocFile
* @function getAllWorkflowSteps
* @instance
* @summary Get a list of all workflow step of the file.
* @description The methd will return all workflow steps, the currently locking and the previous ones.
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @returns {WorkflowStepIterator} WorkflowStepIterator object which represents a list of all workflow steps for the file
* @since DOCUMENTS 5.0b
* @see [DocFile.getCurrentWorkflowStep]{@link DocFile#getCurrentWorkflowStep} [DocFile.getFirstLockingWorkflowStep]{@link DocFile#getFirstLockingWorkflowStep}
* @example
* var f = context.file;
* var stepIter = f.getAllWorkflowSteps();
**/
/**
* @memberof DocFile
* @function getArchiveKey
* @instance
* @summary After archiving of a file this method returns the key of the file in the archive.
* @description
* Note: If the file is not archived or archived without versioning or uncoupled from the achived file the key is empty.
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {boolean} [withServer] optional boolean value to indicate, if the key should include an "@archiveServerName" appendix
* @returns {string} String containing the key.
* @since ELC 3.60a / otrisPORTAL 6.0a
* @see [DocFile.archive]{@link DocFile#archive}
* @example
* var f = context.file;
* if (f.archive())
* util.out(f.getArchiveKey());
* else
* util.out(f.getLastError());
**/
/**
* @memberof DocFile
* @function getAsPDF
* @instance
* @summary Create a PDF file containing the current DocFile's contents and returns the path in the file system.
* @description The different document types of your documents on your different tabs require the appropriate PDF filter programs to be installed and configured in DOCUMENTS.
* @param {string} nameCoverTemplate String containing the name of the pdf cover template defined at the filetype
* @param {boolean} createCover boolean whether to create a field list or to only take the documents
* @param {any[]} sourceRegisterNames Array with the technical names of the document registers you want to include
* @returns {string} <code>String</code> with file path of the pdf, an empty string in case of any error
* @since DOCUMENTS 4.0b
* @example
* var source = new Array();
* source.push("FirstRegister");
* source.push("SecondRegister");
*
* var docFile = context.file;
*
* var pathPdfFile = docFile.getAsPDF("pdfcover", true, source);
* if (pathPdfFile == "")
* throw docFile.getLastError();
* util.out("Size: " + util.fileSize(pathPdfFile))
**/
/**
* @memberof DocFile
* @function getAttribute
* @instance
* @summary Get the String value of an attribute of the file.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {string} attribute String containing the name of the desired attribute
* @returns {string} String containing the value of the desired attribute
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myFile = context.file;
* util.out(myFile.getAttribute("hasInvoicePlugin"));
**/
/**
* @memberof DocFile
* @function getAutoText
* @instance
* @summary Get the String value of a DOCUMENTS autotext.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {string} autoText the rule to be parsed
* @returns {string} String containing the parsed value of the autotext
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myFile = context.file;
* util.out(myFile.getAutoText("fileOwner"));
**/
/**
* @memberof DocFile
* @function getCopy
* @instance
* @summary Duplicate a file.
* @description This function creates a real 1:1 copy of the current file which may be submitted to its own workflow.
* @param {string} copyMode optional String that defines how to handle the documents of the originating file.
* There are three different parameter values allowed:
* <ul>
* <li><code>"NoDocs"</code> copied DocFile does not contain any documents </li>
* <li><code>"ActualVersion"</code> copied DocFile contains only the latest (published) version of each document </li>
* <li><code>"AllVersions"</code> copied DocFile contains all versions (both published and locked) of each document </li>
* </ul>
*
* @returns {DocFile} DocFile object representing the copied file
* @since ELC 3.51c / otrisPORTAL 5.1c
* @example
* var docFile = context.file;
* var newFile = docFile.getCopy("AllVersions");
**/
/**
* @memberof DocFile
* @function getCreationDate
* @instance
* @summary Returns the creation date (timestamp) of a DocFile.
* @returns {Date} <code>Date</code> object, if the date is valid, <code>null</code> for an invalid data.
* @since DOCUMENTS 5.0c
* @see [DocFile.getCreator]{@link DocFile#getCreator}
* @see [DocFile.getLastModificationDate]{@link DocFile#getLastModificationDate}
* @example
* var file = context.file;
* var c_ts = file.getCreationDate();
* if (c_ts)
* util.out(c_ts);
**/
/**
* @memberof DocFile
* @function getCreator
* @instance
* @summary Returns the SystemUser object or fullname as String of the creator of the DocFile.
* @param {boolean} [asObject] optional boolean value, that specifies, if the SystemUser object or the fullname should be returned.
* @returns {any} <code>asObject=true:</code><code>SystemUser</code> object or <code>null</code> (if user does not exist anymore)
* @since DOCUMENTS 5.0c
* @see [DocFile.getLastModifier]{@link DocFile#getLastModifier}
* @see [DocFile.getCreationDate]{@link DocFile#getCreationDate}
* @example
* var file = context.file;
* var su = file.getCreator(true);
* if (su)
* util.out(su.login);
* else
* util.out(file.getCreator());
**/
/**
* @memberof DocFile
* @function getCurrentWorkflowStep
* @instance
* @summary Get the current workflow step of the current user locking the file.
* @description The function returns a valid WorkflowStep object if there exists one for the current user. If the current user does not lock the file, the function returns <code>null</code> instead.
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
*
* @returns {WorkflowStep} WorkflowStep object
* @since ELC 3.51e / otrisPORTAL 5.1e
* @see [DocFile.getFirstLockingWorkflowStep]{@link DocFile#getFirstLockingWorkflowStep}
* @example
* var f = context.file;
* var step = f.getCurrentWorkflowStep();
* if (!step)
* step = f.getFirstLockingWorkflowStep();
* // still no workflow steps found? File not in workflow
* if (!step)
* util.out("File is not in a workflow");
**/
/**
* @memberof DocFile
* @function getDocFileComment
* @instance
* @summary Returns the comment value for a DocFile.
* @returns {DocFileDataField} <code>DocFileDataField</code> object or <code>null</code>.
* @since DOCUMENTS 5.0d
**/
/**
* @memberof DocFile
* @function getEnumAutoText
* @instance
* @summary Get an array with the values of an enumeration autotext.
* @param {string} autoText to be parsed
* @returns {any[]} Array containing the values for the autotext
* @since ELC 3.60e / otrisPORTAL 6.0e
* @example
* var values = context.getEnumAutoText("%accessProfile%")
* if (values)
* {
* for (var i=0; i < values.length; i++)
* {
* util.out(values[i]);
* }
* }
**/
/**
* @memberof DocFile
* @function getFieldAttribute
* @instance
* @summary Get the String value of an attribute of the desired file field.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {string} fieldName String containing the technical name of the desired field
* @param {string} attrName String containing the name of the desired attribute
* @returns {string} String containing the value of the desired field attribute
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myFile = context.file;
* util.out(myFile.getFieldAttribute("Samplefield", "Value"));
**/
/**
* @memberof DocFile
* @function getFieldAutoText
* @instance
* @summary Returns an AutoText value of a specified field of the DocFile.
* @description The following AutoTexts are available
* <ul>
* <li><code>"[locale]"</code> - field value in the user locale or specified locale. </li>
* <li><code>"key"</code> - key value (e.g. at refence fields, enumeration fields, etc.). </li>
* <li><code>"fix"</code> - fix format value (e.g. at numeric fields, date fields, etc.). </li>
* <li><code>"pos"</code> - order position of the field value at enumeration fields. </li>
* <li><code>"raw"</code> - database field value. </li>
* <li><code>"label[.locale]"</code> - label of the field in user locale or specified locale.</li>
* </ul>
*
* @param {string} fieldName Name of the field as String
* @param {string} [autoText]
* @returns {string} <code>String</code> with the AutoText.
* @since DOCUMENTS 5.0c
* @example
* var file = context.file;
* util.out(file.getFieldAutoText("erpInvoiceDate")); // => 31.12.2017
* util.out(file.getFieldAutoText("erpInvoiceDate", "en")); // => 12/31/2017
* util.out(file.getFieldAutoText("erpInvoiceDate", "fix")); // => 20171231
* util.out(file.getFieldAutoText("erpInvoiceDate", "label")); // => Rechnungsdatum
* util.out(file.getFieldAutoText("erpInvoiceDate", "label.en")); // => Invoice date
**/
/**
* @memberof DocFile
* @function getFieldName
* @instance
* @summary Get the technical name of the n-th field of the file.
* @description This allows generic scripts to be capable of different versions of the same filetype, e.g. if you changed details of the filetype, but there are still older files of the filetype in the system.
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {number} index integer index of the desired field
* @returns {string} String containing the technical name of the file field, <code>false</code> if index is out of range
* @since ELC 3.50e / otrisPORTAL 5.0e
* @example
* var myFile = context.file;
* var fieldName = "Samplefield";
* var fields = new Array();
* var i = 0;
* // get all field names
* while (myFile.getFieldName(i))
* {
* fields[i] = myFile.getFieldName(i)
* i++;
* }
* // check for field existance
* var found = false;
* for (var j = 0; j < fields.length; j++)
* {
* if (fields[j] == fieldName)
* {
* found = true;
* break;
* }
* }
**/
/**
* @memberof DocFile
* @function getFieldValue
* @instance
* @summary Get the value of the desired file field.
* @description
* Since DOCUMENTS 4.0c HF2 available for multi-instance fields of an EE.i/EE.x archive file
* @param {string} fieldName String containing the technical field name can be followed by the desired instance number in form techFieldName[i] for multi-instance fields of an EE.i/EE.x archive file.
* <b>Note:</b> The index <code>i</code> is zero-based. The specification of field instance is olny available for an EE.i/EE.x archive file, it will be ignored for other files. If the parameter contains no instance information, the first field instance is used. The field instance order is determined by the field order in the file.
* @returns {any} The field value, its type depends on the field type, such as a Date object returned for a field of type 'Timestamp'.
* @since DOCUMENTS 4.0c
* @example
* var myFile = context.file;
* util.out(myFile.getFieldValue("Samplefield"));
*
* // Since DOCUMENTS 4.0c HF2
* var key = "Unit=Default/Instance=Default/Pool=FeldZ/Document=Feldzahlen.86C94C30438011E2B925080027B22D11@eex1";
* var eexFile = context.getArchiveFile(key);
* util.out(eexFile.getFieldValue("multiInstanceField[2]"));
**/
/**
* @memberof DocFile
* @function getFileOwner
* @instance
* @summary Get the file owner of the file.
* @returns {SystemUser} SystemUser object representing the user who owns the file
* @since ELC 3.51d / otrisPORTAL 5.1d
* @example
* var docFile = context.file;
* var su = docFile.getFileOwner();
* util.out(su.login);
**/
/**
* @memberof DocFile
* @function getFirstLockingWorkflowStep
* @instance
* @summary Get the first locking workflow step that currently locks the file.
* @description The first locking workflow step does not need to be locked by the current user executing the script, this function as well returns the first locking step if it is locked by a different user. If no locking step is found at all, the function returns <code>null</code> instead.
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @returns {WorkflowStep} WorkflowStep object
* @since ELC 3.50e / otrisPORTAL 5.0e
* @see [DocFile.getCurrentWorkflowStep]{@link DocFile#getCurrentWorkflowStep}
* @example
* var f = context.file;
* var step = f.getCurrentWorkflowStep();
* if (!step)
* {
* step = f.getFirstLockingWorkflowStep();
* }
* // still no workflow steps found? File not in workflow
* if (!step)
* {
* util.out("File is not in a workflow");
* }
**/
/**
* @memberof DocFile
* @function getid
* @instance
* @summary Returns the file id of the DocFile.
* @returns {string} <code>String</code> with the file id.
* @since DOCUMENTS 5.0c
* @example
* var file = context.file;
* util.out(file.getid());
**/
/**
* @memberof DocFile
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myFile = context.file;
* // do something which may go wrong
* if (hasError)
* {
* util.out(myFile.getLastError());
* }
**/
/**
* @memberof DocFile
* @function getLastModificationDate
* @instance
* @summary Returns the last modification date (timestamp) of a DocFile.
* @returns {Date} <code>Date</code> object, if the date is valid, <code>null</code> for an invalid data.
* @since DOCUMENTS 5.0c
* @see [DocFile.getLastModifier]{@link DocFile#getLastModifier}
* @see [DocFile.getCreationDate]{@link DocFile#getCreationDate}
* @example
* var file = context.file;
* var c_ts = file.getLastModificationDate();
* if (c_ts)
* util.out(c_ts);
**/
/**
* @memberof DocFile
* @function getLastModifier
* @instance
* @summary Returns the fullname as String of the last editor of the DocFile.
* @returns {string} <code>String</code> with the fullname.
* @since DOCUMENTS 5.0c
* @see [DocFile.getCreator]{@link DocFile#getCreator}
* @see [DocFile.getLastModificationDate]{@link DocFile#getLastModificationDate}
* @example
* var file = context.file;
* util.out(file.getLastModifier());
**/
/**
* @memberof DocFile
* @function getOID
* @instance
* @summary Returns the object-id.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* Since DOCUMENTS 5.0 (new parameter oidLow)
* @param {boolean} [oidLow] Optional flag:
* If <code>true</code> only the id of the filetype object (<code>m_oid</code>) will be returned.
* If <code>false</code> the id of the filetype object will be returned together with the id of the corresponding class in the form <code>class-id:m_oid</code>.
* The default value is <code>false</code>.
* @returns {string} <code>String</code> with the object-id
* @since ELC 3.60c / otrisPORTAL 6.0c
**/
/**
* @memberof DocFile
* @function getOriginal
* @instance
* @summary Get the orginal file for a scratch copy.
* @description If you run a scipt on a scratch copy (e.g. a onSave script), you can get the orginal file with this function.
* @returns {DocFile} DocFile
* @since DOCUMENTS 4.0 (EAS)
* @example
* var scratchCopy = context.file;
* var origFile = scratchCopy.getOriginal();
* if (!origFile)
* util.out(scratchFile.getLastError();
* else
* {
* if (scratchCopy.FieldA != origFile.FieldA)
* util.out("Field A changed");
* else
* util.out("Field A not changed");
* }
**/
/**
* @memberof DocFile
* @function getReferenceFile
* @instance
* @summary Get the file referred by a reference field in the current file.
* @description If the current file's filetype is connected to a superior filetype by a reference field, this function allows to easily access the referred file, e.g. if you are in an invoice file and you want to access data of the referring company.
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {string} referenceFileField String value containing the technical name of the file field contianing the definition to the referred filetype
* @returns {DocFile} DocFile object representing the referred file
* @since ELC 3.51c / otrisPORTAL 5.1c
* @example
* var docFile = context.file;
* var company = docFile.getReferenceFile("crmCompany");
* util.out(company.crmCompanyName);
**/
/**
* @memberof DocFile
* @function getRegisterByName
* @instance
* @description
* Note: Until version 5.0c this method ignored the access rights of the user to the register. With the optional parameter checkAccessRight this can now be done. For backward compatibility the default value is set to false.
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* Since DOCUMENTS 5.0c (new optional parameter checkAccessRight)
* @param {string} registerName String value containing the technical name of the desired register
* @param {boolean} [checkAccessRight] optional boolean value, that indicates if the access rights should be considered.
* @returns {Register} Register object representing the desired register
* @since ELC 3.50n / otrisPORTAL 5.0n
* @see [DocFile.getRegisters]{@link DocFile#getRegisters}
* @example
* var docFile = context.file;
* var reg = docFile.getRegisterByName("Documents");
**/
/**
* @memberof DocFile
* @function getRegisters
* @instance
* @summary Get an iterator with the registers of the file for the specified type.
* @description
* Note: Until version 5.0c this method ignored the access rights of the user to the register. With the optional parameter checkAccessRight this can now be done. For backward compatibility the default value is set to false.
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* Since DOCUMENTS 5.0c (new optional parameter checkAccessRight)
* @param {string} [type] optional String value to filter for a desired register type. Default type is <code>documents</code>
* Allowed values:
* <ul>
* <li><code>documents</code></li>
* <li><code>fields</code></li>
* <li><code>links</code></li>
* <li><code>archiveddocuments</code></li>
* <li><code>externalcall</code></li>
* <li><code>all</code> (returns all registers independent of the type) </li>
* </ul>
*
* @param {boolean} [checkAccessRight] optional boolean value, that indicates if the access rights should be considered.
* @returns {RegisterIterator} RegisterIterator with all registers (matching the filter)
* @since ELC 3.50n / otrisPORTAL 5.0n
* @see [RegisterIterator]{@link RegisterIterator} [DocFile.getRegisterByName]{@link DocFile#getRegisterByName}
* @example
* var docFile = context.file;
* var regIter = docFile.getRegisters("documents");
**/
/**
* @memberof DocFile
* @function getTitle
* @instance
* @summary Returns the title of the DocFile.
* @description
* Note: the special locale raw returns the title in all locales
* @param {string} [locale]
* @returns {string} <code>String</code> with the title.
* @since DOCUMENTS 5.0c
* @example
* var file = context.file;
* util.out(file.getTitle("en"));
**/
/**
* @memberof DocFile
* @function getUserStatus
* @instance
* @summary Get the status of the file for a desired user.
* @param {string} login String containing the login name of the desired user
* @returns {string} String with the status. Possible values:
* <ul>
* <li><code>standard</code></li>
* <li><code>new</code></li>
* <li><code>fromFollowup</code></li>
* <li><code>toForward</code></li>
* <li><code>forInfo</code></li>
* <li><code>task</code></li>
* <li><code>workflowCanceled</code></li>
* <li><code>backFromDistribution</code></li>
* <li><code>consultation</code></li>
* </ul>
*
* @since DOCUMENTS 4.0c HF1
* @see [DocFile.setUserStatus]{@link DocFile#setUserStatus}
* @example
* var docFile = context.file;
* util.out(docFile.getUserStatus("schreiber"));
**/
/**
* @memberof DocFile
* @function hasField
* @instance
* @summary Gather information whether the current file has the field with the desired name.
* @param {string} fieldName String containing the technical name of the field.
* @returns {boolean} <code>true</code> if the file has the field, <code>false</code> if not
* @since DOCUMENTS 4.0d
* @example
* var file = context.file;
* if (file.hasField("address"))
* util.out(file.address);
**/
/**
* @memberof DocFile
* @function insertStatusEntry
* @instance
* @summary Add an entry to the status tab of the file.
* @description This function is especially useful in connection with PortalScripts being used as decision guards in workflows, because this allows to comment and describe the decisions taken by the scripts. This increases transparency concerning the life cycle of a file in DOCUMENTS.
* @param {string} action String containing a brief description
* @param {string} comment optional String containing a descriptive comment to be added to the status entry
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51b / otrisPORTAL 5.1b
* @example
* var docFile = context.file;
* docFile.insertStatusEntry("Executed Guard Script","all conditions met");
**/
/**
* @memberof DocFile
* @function isArchiveFile
* @instance
* @summary Gather information whether the current file is an archive file.
* @returns {boolean} <code>true</code> if is an archive file, <code>false</code> if not
* @since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @example
* var key = "Unit=Default/Instance=Default/Pool=DEMO/Pool=RECHNUNGEN/Document=RECHNUNGEN.41D3694E2B1E11DD8A9A000C29FACDC2"
* var docFile = context.getArchiveFile(key);
* if (docFile)
* util.out(docFile.isArchiveFile());
**/
/**
* @memberof DocFile
* @function isDeletedFile
* @instance
* @summary Gather information whether the current file is a deleted file of a trash folder.
* @returns {boolean} <code>true</code> if is a deleted file, <code>false</code> if not
* @since ELC 3.60e / otrisPORTAL 6.0e
* @example
* ...
* var trashFolder = user.getPrivateFolder("trash");
* if (trashFolder)
* {
* var it = trashFolder.getFiles();
* for (var file = it.first(); file; file = it.next())
* {
* if (file.isDeletedFile())
* util.out("ok");
* else
* util.out("Error: Found undeleted file in trash folder!");
* }
* }
**/
/**
* @memberof DocFile
* @function isNewFile
* @instance
* @summary Gather information whether the current file is a new file.
* @returns {boolean} <code>true</code> if new file, <code>false</code> if not
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
* @example
* var docFile = context.file;
* util.out(docFile.isNewFile());
**/
/**
* @memberof DocFile
* @function reactivate
* @instance
* @summary Reactivate an archive file to a file of the correspondending filetype.
* @returns {boolean} <code>true</code> if successful, <code>false</code> if not - get error message with getLastError()
* @since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @example
* var key = "Unit=Default/Instance=Default/Pool=DEMO/Pool=RECHNUNGEN/Document=RECHNUNGEN.41D3694E2B1E11DD8A9A000C29FACDC2@eex1"
* var docFile = context.getArchiveFile(key);
* if (!docFile)
* throw "archive file does not exist: " + key;
* if (!docFile.reactivate())
* throw "Reactivation failed: " + docFile.getLastError();
*
* docFile.startWorkflow....
**/
/**
* @memberof DocFile
* @function sendFileAdHoc
* @instance
* @summary Send the DocFile directly.
* @param {any[]} receivers Array with the names of the users or groups to which to send the DocFile. You need to specify at least one recipient.
* @param {string} sendMode String containing the send type. The following values are available:
* <ul>
* <li><code>sequential</code> - one after the other </li>
* <li><code>parallel_info</code> - concurrently for information </li>
* </ul>
*
* @param {string} task String specifying the task for the recipients of the DocFile
* @param {boolean} backWhenFinished boolean indicating whether the DocFile should be returned to the own user account after the cycle.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 5.0
* @example
* var docFile = context.createFile("Filetype1");
* var success = docFile.sendFileAdHoc(["user2", "user3"], "parallel_info", "test task", true);
* if (!success)
* util.out(docFile.getLastError());
**/
/**
* @memberof DocFile
* @function sendMail
* @instance
* @summary Send the file as email to somebody.
* @description You must define an email template in the Windows Portal Client at the filetype of your DocFile object. This template may contain autotexts that can be parsed and replaced with their appropriate field values.
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* Since DOCUMENTS 4.0d new parameter bcc
* @param {string} from String value containing the sender's email address
* @param {string} templateName String value containing the technical name of the email template. This must be defined on the email templates tab of the filetype.
* @param {string} to String value containing the email address of the recipient
* @param {string} cc Optional String value for an additional recipient ("cc" means "carbon copy")
* @param {boolean} addDocs optional boolean value whether to include the documents of the file
* @param {string} bcc Optional String value for the email addresses of blind carbon-copy recipients (remaining invisible to other recipients).
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50b / otrisPORTAL 5.0b
* @example
* var docFile = context.file;
* docFile.sendMail("schreiber@toastup.de", "MyMailTemplate",
* "oppen@toastup.de", "", true
* );
**/
/**
* @memberof DocFile
* @function setAttribute
* @instance
* @summary Set the String value of an attribute of the file to the desired value.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {string} attribute String containing the name of the desired attribute
* @param {string} value String containing the desired value of the attribute
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myFile = context.file;
* myFile.setAttribute("hasInvoicePlugin", "true");
**/
/**
* @memberof DocFile
* @function setFieldAttribute
* @instance
* @summary Set the value of an attribute of the desired file field.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {string} fieldName String containing the technical name of the desired field
* @param {string} attrName String containing the name of the desired attribute
* @param {string} value String value containing the desired field attribute value
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myFile = context.file;
* myFile.setFieldAttribute("Samplefield", "Value", "1");
**/
/**
* @memberof DocFile
* @function setFieldValue
* @instance
* @summary Set the value of the desired file field.
* @description
* Since DOCUMENTS 4.0c HF2 available for multi-instance fields of an EE.i/EE.x archive file
* @param {string} fieldName String containing the technical field name can be followed by the desired instance number in form techFieldName[i] for multi-instance fields of an EE.i/EE.x archive file.
* <b>Note:</b> The index <code>i</code> is zero-based. The specification of field instance is olny available for an EE.i/EE.x archive file, it will be ignored for other files. If the parameter contains no instance information, the first field instance is used. The field instance order is determined by the field order in the file.
* @param {any} value The desired field value of the proper type according to the field type, e.g. a Date object as value of a field of type 'Timestamp'.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var myFile = context.file;
* myFile.setFieldValue("NumericField", 3.14);
* myFile.setFieldValue("TimestampField", new Date());
* myFile.setFieldValue("BoolField", true);
* myFile.setFieldValue("StringField", "Hello");
* myFile.sync();
*
* // Since DOCUMENTS 4.0c HF2
* var key = "Unit=Default/Instance=Default/Pool=FeldZ/Document=Feldzahlen.86C94C30438011E2B925080027B22D11@eex1";
* var eexFile = context.getArchiveFile(key);
* eexFile.startEdit();
* eexFile.setFieldValue("multiInstanceField[2]", "Hello");
* eexFile.commit();
**/
/**
* @memberof DocFile
* @function setFileOwner
* @instance
* @summary Set the file owner of the file to the desired user.
* @param {SystemUser} owner SystemUser object representing the desired new file owner
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51d / otrisPORTAL 5.1d
* @example
* var docFile = context.file;
* var su = context.getSystemUser();
* docFile.setFileOwner(su);
**/
/**
* @memberof DocFile
* @function setFollowUpDate
* @instance
* @summary Set a followup date for a desired user.
* @param {SystemUser} pUser SystemUser object of the desired user
* @param {Date} followUpDate Date object representing the desired followup date
* @param {string} comment optional String value containing a comment that is displayed as a task as soon as the followup is triggered
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51b / otrisPORTAL 5.1b
* @see [DocFile.clearFollowUpDate]{@link DocFile#clearFollowUpDate}
* @example
* var docFile = context.file;
* var su = context.getSystemUser();
* var followup = util.convertStringToDate("31.12.2008", "dd.mm.yyyy");
* docFile.setFollowUpDate(su, followup, "Silvester");
**/
/**
* @memberof DocFile
* @function setUserRead
* @instance
* @summary Mark the file as read or unread for the desired user.
* @description
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @param {string} login String containing the login name of the desired user
* @param {boolean} fileRead boolean whether the file should be markes as read (<code>true</code>) or unread (<code>false</code>)
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50b / otrisPORTAL 5.0b
* @example
* var docFile = context.file;
* docFile.setUserRead("schreiber", true);
**/
/**
* @memberof DocFile
* @function setUserStatus
* @instance
* @summary Set the status of the file for a desired user to a desired value.
* @description The file icon in the list view and file view depends on this status.
* Since DOCUMENTS 4.0c (status values extended)
* @param {string} login String containing the login name of the desired user
* @param {string} status String value containing the desired status
* Allowed values:
* <ul>
* <li><code>standard</code></li>
* <li><code>new</code></li>
* <li><code>fromFollowup</code></li>
* <li><code>toForward</code></li>
* <li><code>forInfo</code></li>
* <li><code>task</code></li>
* <li><code>workflowCanceled</code></li>
* <li><code>backFromDistribution</code></li>
* <li><code>consultation</code></li>
* </ul>
*
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50b / otrisPORTAL 5.0b
* @see [DocFile.getUserStatus]{@link DocFile#getUserStatus}
* @example
* var docFile = context.file;
* docFile.setUserStatus("schreiber", "new");
**/
/**
* @memberof DocFile
* @function startEdit
* @instance
* @summary Switch a DocFile to edit mode.
* @description Switching a file to edit mode with this function has the same effect as the "Edit" button in the web surface of DOCUMENTS. This means, a scratch copy of the file is created, and any changes you apply to the file are temporarily stored in the scratch copy - until you <code>commit()</code> your changes back to the original file. There are a few scripting event hooks which disallow the use of this function at all costs:
* <ul>
* <li><code>onEdit</code> hook - the system has already created the scratch copy. </li>
* <li><code>onCreate</code> hook - a newly created file is always automatically in edit mode.</li>
* </ul>
*
* You should avoid using this function in scripts that are executed inside a workflow (signal exits, decisions etc.).
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
* @see [DocFile.abort]{@link DocFile#abort}
* @example
* var myFile = context.file;
* myFile.startEdit();
* myFile.Field = "value";
* myFile.commit(); // apply changes
**/
/**
* @memberof DocFile
* @function startWorkflow
* @instance
* @summary Start a workflow for the DocFile object.
* @param {string} workflowName String containing the technical name and optional the version number of the workflow. The format of the workflowName is <code>technicalName</code>[-version]. If you don't specify the version of the workflow, the workflow with the highest workflow version number will be used. If you want to start a specific version you have to use technicalName-version e.g. (Invoice-2) as workflowName.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myFile = context.file;
* myFile.startWorkflow("Invoice"); // starts the latest version of the workflow "Invoice"
* myFile.startWorkflow("Invoice-2"); // starts the version 2 of the workflow "Invoice"
**/
/**
* @memberof DocFile
* @function sync
* @instance
* @summary Synchronize any changes to the DocFile object back to the real file.
* @description If you want to apply changes to file fields through a script that is executed as a signal exit inside a workflow, you should rather prefer sync() than the <code>startEdit() / commit()</code> instruction pair.
* Note: If there's a scratch copy of the file in the system (e.g. by some user through the web surface), committing the changes in the scratch copy results in the effect that your synced changes are lost. So be careful with the usage of this operation.
* Since DOCUMENTS 5.0a (new parameter updateRefFields)
* Since DOCUMENTS 5.0a HF2 (new parameter updateModifiedDate)
* @param {boolean} [checkHistoryFields] optional boolean parameter has to be set to true, if the file contains history fields, that are modified
* @param {boolean} [notifyHitlistChange] optional boolean parameter indicates the web client to refresh the current hitlist
* @param {boolean} [updateRefFields] optional boolean parameter indicates to update reference fields if using the property UpdateByRefFields
* @param {boolean} [updateModifiedDate] optional boolean parameter indicates to update the modification date of the file
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0 (checkHistoryFields parameter since ELC 3.60i / otrisPORTAL 6.0i)
* @see [DocFile.startEdit]{@link DocFile#startEdit} [DocFile.commit]{@link DocFile#commit}
* @example
* var myFile = context.file;
* myFile.Field = "value";
* myFile.sync();
**/
/**
* @memberof DocFile
* @function undeleteFile
* @instance
* @summary Relive a deleted file.
* @description Sets the status active to a file and redraws it from the trash folder. Deleted files are not searchable by a <code>FileResultSet</code>. You can only retrieve deleted files by iterating throw the trash-folder of the users
* @returns {boolean} <code>true</code> if successful, <code>false</code> if not
* @since ELC 3.60e / otrisPORTAL 6.0e
* @example
* ...
* var trashFolder = user.getPrivateFolder("trash");
* if (trashFolder)
* {
* var it = trashFolder.getFiles();
* for (var file = it.first(); file; file = it.next())
* {
* if (file.isDeletedFile())
* {
* file.undeleteFile();
* // now e.g. search a private folder and add the file...
* }
* }
* }
**/
/**
* @interface DocFileDataField
* @summary The JS_DocFileDataField class represents the special comment field at the DocFile.
* @since DOCUMENTS 5.0d
*/
/**
* @memberof DocFileDataField
* @summary Hash value of the last field value.
* @member {string} hash
* @instance
* @since DOCUMENTS 5.0d
**/
/**
* @memberof DocFileDataField
* @summary Name of the field.
* @member {string} name
* @instance
* @since DOCUMENTS 5.0d
**/
/**
* @memberof DocFileDataField
* @summary Access-right to read the field.
* @member {string} readAccess
* @instance
* @since DOCUMENTS 5.0d
**/
/**
* @memberof DocFileDataField
* @summary Access-right to write the field.
* @member {string} writeAccess
* @instance
* @since DOCUMENTS 5.0d
**/
/**
* @memberof DocFileDataField
* @function getLastError
* @instance
* @summary If you call a method at a DocFileDataField object and an error occurred, you can get the error description with this function.
* @returns {string} Text of the last error as String
* @since DOCUMENTS 5.0d
**/
/**
* @memberof DocFileDataField
* @function getValue
* @instance
* @summary Get the comment as String.
* @returns {string} String containing the comment
* @since DOCUMENTS 5.0d
**/
/**
* @memberof DocFileDataField
* @function setValue
* @instance
* @summary Set the comment as String.
* @param {string} value String containing the new comment
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 5.0d
**/
/**
* @interface DocHit
* @summary The DocHit class presents the hit object collected by a HitResultset.
* @description Objects of this class cannot be created directly. You may access a single DocHit by creating a HitResultset, which provides functions to retrieve its hit entries.
* @since DOCUMENTS 4.0b
* @see [HitResultset.first]{@link HitResultset#first} [HitResultset.getAt]{@link HitResultset#getAt}
* @example
* var searchResource = "Standard";
* var filter = "";
* var sortOrder = "";
* var myFile;
* var myHRS = new HitResultset(searchResource, filter, sortOrder);
* for (var myHit = myHRS.first(); myHit; myHit = myHRS.next())
* {
* if (myHit.isArchiveHit())
* myFile = myHit.getArchiveFile();
* else
* myFile = myHit.getFile();
*
* if (myFile)
* util.out(myFile.getAutoText("title"));
* else
* util.out(myHit.getLastError());
* }
*/
/**
* @memberof DocHit
* @summary Field value, addressed by a known column name.
* @description Each field in a DocHit is mapped to an according property. You can read the value on the basis of the column name.
* Note: Overwriting values in a DocHit is not allowed. Each attempt will raise an exception. To read dates and numbers in DOCUMENTS' storage format, see getTechValueByName().
* @member {any} columnName
* @instance
* @since DOCUMENTS 5.0HF2
* @example
* function logValue(label, value)
* {
* util.out(label +" [" + typeof(value) + "] " + value);
* }
*
* var HRS = new HitResultset("ftOrder", "", "", "HL2");
* var hitline = HRS.first();
* if(hitline)
* {
* // We assume, "ftOrder" has got a string field "company", a
* // date field "orderDate" and a numeric field "netPrice".
* var checkVal = hitline.company;
* logValue("company: ", checkVal);
* checkVal = hitline.orderDate;
* logValue("orderDate: ", checkVal);
*
* // The next example shows a different way to read "hitline.netPrice".
* // This style is necessary, if the name of a column contains
* // critical characters, or if the name equals a reserved JavaScript keyword.
* checkVal = hitline["netPrice"];
* logValue("orderDate: ", checkVal);
*
* // Columns can also be addressed by number (0..n-1)
* checkVal = hitline[0];
* logValue("first column: ", checkVal);
* }
**/
/**
* @memberof DocHit
* @function getArchiveFile
* @instance
* @summary Get a file from the archive associated to the archive hit.
* @description You need the necessary access rights on the archive side.
* Note: This function creates a complete DOCUMENTS image of the archived file, except for the content of attachments. This is a time-consuming workstep. If a script calls this function for each hit in the set, it will not run any faster than a script, which uses a conventional ArchiveFileResultset instead of this class.
* @returns {DocFile} <code>DocFile</code> or <code>NULL</code>, if failed.
* @since DOCUMENTS 4.0b
* @see [getFile]{@link getFile}
**/
/**
* @memberof DocHit
* @function getArchiveKey
* @instance
* @summary Retrieve the key of the associated archive file object.
* @param {boolean} [withServer] optional boolean value to indicate, if the key should include an "@archiveServerName" appendix
* @returns {string} The archive file's key as a String, but an empty String, if the hit does not refer to an archive file.
* @since DOCUMENTS 4.0b
* @see [getFileId]{@link getFileId}
**/
/**
* @memberof DocHit
* @function getBlobInfo
* @instance
* @summary Function to get the blob info of the hit as xml.
* @returns {string} String with xml content
* @since DOCUMENTS 5.0c
**/
/**
* @memberof DocHit
* @function getFile
* @instance
* @summary Get the file associated to the hit.
* @description If the file does not exist or the user in whose context the script is executed is not allowed to access the file, then the return value will be <code>NULL</code>.
* @returns {DocFile} <code>DocFile</code> or <code>NULL</code>, if failed.
* @since DOCUMENTS 4.0b
* @see [getArchiveFile]{@link getArchiveFile}
**/
/**
* @memberof DocHit
* @function getFileId
* @instance
* @summary Get the file id of the associated file object.
* @returns {string} The file id as String, if the associated file is an active file, but an empty String otherwise.
* @since DOCUMENTS 4.0b
* @see [getArchiveKey]{@link getArchiveKey}
**/
/**
* @memberof DocHit
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since DOCUMENTS 4.0b
**/
/**
* @memberof DocHit
* @function getLocalValue
* @instance
* @summary Get the local value of an available column.
* @param {number} colIndex The zero-based index of the column.
* @returns {string} The local value of the given column as String.
* @since DOCUMENTS 4.0b
* @see [getLocalValueByName]{@link getLocalValueByName}
**/
/**
* @memberof DocHit
* @function getLocalValueByName
* @instance
* @summary Get the local value of an available column.
* @description
* Note: Accesing a column by its index is a bit faster than by its name.
* @param {string} colName The name of the column.
* @returns {string} The local value of the given column as String.
* @since DOCUMENTS 4.0b
* @see [getLocalValue]{@link getLocalValue}
**/
/**
* @memberof DocHit
* @function getSchema
* @instance
* @summary Get a schema identifier of the archive hit.
* @description
* Note: For EE.i, the value is an archive identifier in the XML-Server's notation. For EDA it is just the name of a filetype. All values come with an "@Servername" appendix.
* @returns {string} The schema identifier as a String.
* @since DOCUMENTS 4.0b
**/
/**
* @memberof DocHit
* @function getTechValue
* @instance
* @summary Get the technical value of an available column.
* @description
* Note: The function returns dates, timestamps and numbers in DOCUMENTS' storage format. (In the DOCUMENTS Manager see menu 'Documents/Settings', dialog page 'Locale/format', group 'Format settings'.) If you prefer JavaScript numbers and dates, simply use the object like an array: myDocHit[colIndex].
* @param {number} colIndex The zero-based index of the column.
* @returns {string} The technical value of the given column as a String.
* @since DOCUMENTS 4.0b
* @see [getTechValueByName]{@link getTechValueByName}
**/
/**
* @memberof DocHit
* @function getTechValueByName
* @instance
* @summary Get the technical value of an available column.
* @description
* Note: Accessing a column by its index is a bit faster than by its name.
* Note: The function returns dates, timestamps and numbers in DOCUMENTS' storage format. (In the DOCUMENTS Manager see menu 'Documents/Settings', dialog page 'Locale/format', group 'Format settings'.) If you prefer JavaScript numbers and dates, you can simply read the columns as a property DocHit.columnName.
* @param {string} colName The name of the column.
* @returns {string} The technical value of the given column as String.
* @since DOCUMENTS 4.0b
* @see [getTechValue,DocHit.columnName]{@link getTechValue,DocHit#columnName}
**/
/**
* @memberof DocHit
* @function isArchiveHit
* @instance
* @summary Function to test whether the associated file is an archive file.
* @returns {boolean} <code>true</code>, if the associated file is an archive file, <code>false</code> otherwise.
* @since DOCUMENTS 4.0b
**/
/**
* @interface DocQueryParams
* @summary This class encapsulates the basic parameters of a Documents search request.
* @description Only the script-exits "OnSearch" and "FillSearchMask" provide access to such an object. See also Context.getQueryParams().
* Scripts can modify the parameters only in the following ways.
* <ol>
* <li>A project-related "OnSearch" script may detect in advance, if an individual query won't find any hits in a specified searchable resource. In this case, the script can call removeSource() for each zero-hits resource to reduce the workload on the database and/or archive systems. However the very first listed resource cannot be removed, because it regularly owns the selected hit list. As a result, removeSource() is not suitable for implementing extraordinary permission restrictions. </li>
* <li>A "OnSearch" script can substitute the relational operator or the value in a search field. This practice is not recommended, because it may make the user find something competely different than he sought for. </li>
* <li>A "OnSearch" script may cancel some special search requests and submit a custom message. The type (or origin) of the search request determines, if and where this message will be displayed. </li>
* <li>A "FillSearchMask" script can place default values in the search fields. </li>
* </ol>
*
* @since DOCUMENTS 4.0d
* @example
* util.out("*********** onSearch start *************");
*
* var params = context.getQueryParams();
* if(params)
* {
* // First write the contents of the object to the server window
* util.out("got retrieval parameter object");
* var requestType = params.requestType;
* util.out("queryType = " + requestType);
*
* // Print the list of searchable resources.
* var count = params.sourceCount;
* util.out("sourceCount = " + count);
* var cnt;
* for(cnt = 0; cnt < count; ++cnt)
* {
* var source = params.getSource(cnt);
* if(source)
* {
* util.out("<Source " + (cnt+1) + ">");
* util.out("resId = " + source.resId);
* util.out("type = " + source.type);
* util.out("server = " + source.server);
* }
* else
* util.out("got a NULL source");
* }
*
* // Print the list of all search fields.
* // This dump may include many empty fields.
* count = params.searchFieldCount;
* util.out("\r\nsearch fields = " + count);
* for(cnt = 0; cnt < count; ++cnt)
* {
* var sfield = params.getSearchField(cnt);
* if(sfield)
* {
* util.out("<Searchfield " + (cnt+1) + ">");
* var filter = sfield.name + sfield.compOp + sfield.valueExpr;
* util.out("Condition: " + filter);
* util.out("fieldType = " + sfield.type);
* util.out("label = " + sfield.label);
* }
* else
* util.out("got a NULL field");
* }
*
* // Print the search fields again, but this time ignore all empty
* // fields.
* count = params.filledSearchFieldCount;
* util.out("\r\nfilled search fields = " + count);
* for(cnt = 0; cnt < count; ++cnt)
* {
* sfield = params.getSearchField(cnt, true);
* if(sfield)
* {
* util.out("<Searchfield " + (cnt+1) + ">");
* var filter = sfield.name + sfield.compOp + sfield.valueExpr;
* util.out("Condition: " + filter);
* util.out("fieldType = " + sfield.type);
* util.out("label = " + sfield.label);
* }
* else
* util.out("got a NULL field");
* }
*
* // The subsequent test code requires at least one filled in search field
* if(count > 0)
* {
* sfield = params.getSearchField(0, true);
* var testExpr = sfield.valueExpr;
*
* // Test 1:
* // Let's assume we have got a bunch of EDA stores. We know,
* // that the value "rarely" is frequently searched across many
* // stores, but it never can appear in a store named "Playground".
* // We can try to exclude this store from the search request to
* // reduce the workload.
* if(testExpr == "rarely")
* {
* // Note: Source #0 cannot not be removed.
* for(cnt = 1; cnt < params.sourceCount; ++cnt)
* {
* source = params.getSource(cnt);
* if(source.server == "Playground")
* {
* params.removeSource(cnt--);
* // About the "--": removeSource() has implicitly
* // decreased the index number of all subsequent
* // sources and also the "sourceCount" property.
* // To skip nothing, the loop needs to run with
* // the same index once again.
* }
* }
* }
*
* // Test 2:
* // If the OnSearchScript triggers a search request itself, it
* // ends up in a recursive call! This section does nothing serious.
* // It just demonstrates the effect with a few log messages.
* if(testExpr == "recurse")
* {
* if(requestType == DocQueryParams.API)
* util.out("OnSearchScript avoiding another recursion");
* else
* {
* util.out("OnSearchScript before recursion");
* var iter = new FileResultset("ftEmployee", "hrRemarks=recurse", "");
* var o = iter.first();
* util.out("OnSearchScript after recursion");
* }
* }
*
* // Test 3:
* // Generate an error for a specific search expression.
* if((requestType == DocQueryParams.DIRECT
* || requestType == DocQueryParams.EXTENDED)
* && testExpr == "want an error")
* {
* context.errorMessage = "Here is the error message you desired!";
* return -142;
* }
*
* // Test 4:
* // Substitute a search expression (not recommended; just a demo)
* if(requestType == DocQueryParams.EXTENDED && (testExpr == "U" ||testExpr == "u"))
* sfield.valueExpr = "X";
* }
* }
* else
* util.out("No retrieval parameters available.");
*
* util.out("********* onSearch end **************");
*/
/**
* @memberof DocQueryParams
* @summary Integer code for the requestType "direct fultext search".
* @description
* <br> This constant is member of constant group: Request Type Constants<br>
* These constants are equally available in each instance of DocQueryParams and in the constructor object.
* @instance
* @member {number} DIRECT
* @readonly
*/
/**
* @memberof DocQueryParams
* @summary Integer code for the requestType "extended search".
* @description
* <br> This constant is member of constant group: Request Type Constants<br>
* These constants are equally available in each instance of DocQueryParams and in the constructor object.
* @instance
* @member {number} EXTENDED
* @readonly
*/
/**
* @memberof DocQueryParams
* @summary Integer code for the requestType "static folder".
* @description In the current release, this type can occur only, if the Documents setting "search field in folder" is enabled.
* <br> This constant is member of constant group: Request Type Constants<br>
* These constants are equally available in each instance of DocQueryParams and in the constructor object.
* @instance
* @member {number} FOLDER_S
* @readonly
*/
/**
* @memberof DocQueryParams
* @summary Integer code for the requestType "dynamic folder".
* @description Listing the contents of such a folder already triggers a search request.
* <br> This constant is member of constant group: Request Type Constants<br>
* These constants are equally available in each instance of DocQueryParams and in the constructor object.
* @instance
* @member {number} FOLDER_D
* @readonly
*/
/**
* @memberof DocQueryParams
* @summary Integer code for the requestType "link register".
* @description
* <br> This constant is member of constant group: Request Type Constants<br>
* These constants are equally available in each instance of DocQueryParams and in the constructor object.
* @instance
* @member {number} REGISTER
* @readonly
*/
/**
* @memberof DocQueryParams
* @summary Integer code for the request type "reference field destination selection".
* @description This request type originates from the web dialog, which opens, when a user is editing a file and presses a reference fields select button.
* <br> This constant is member of constant group: Request Type Constants<br>
* These constants are equally available in each instance of DocQueryParams and in the constructor object.
* @instance
* @member {number} REFERENCE
* @readonly
*/
/**
* @memberof DocQueryParams
* @summary Integer code for the requestType "API search".
* @description (Archive-)FileResultsets, HitResultSets and the SOAP report functions belong to this category.
* <br> This constant is member of constant group: Request Type Constants<br>
* These constants are equally available in each instance of DocQueryParams and in the constructor object.
* @instance
* @member {number} API
* @readonly
*/
/**
* @memberof DocQueryParams
* @summary Integer code for the requestType "filing plan node".
* @description
* <br> This constant is member of constant group: Request Type Constants<br>
* These constants are equally available in each instance of DocQueryParams and in the constructor object.
* @instance
* @member {number} FILING_PLAN
* @readonly
*/
/**
* @memberof DocQueryParams
* @summary Integer code for the requestType "quick view".
* @description
* Note: Quick view URLs with just an id-Parameter do not trigger a search.
* <br> This constant is member of constant group: Request Type Constants<br>
* These constants are equally available in each instance of DocQueryParams and in the constructor object.
* @instance
* @member {number} QUICK_VIEW
* @readonly
*/
/**
* @memberof DocQueryParams
* @summary Integer code for the request type "script controlled hit tree generation".
* @description This is a special feature, where a script in the web server process sends a seach request and immediately generates a hit tree from the results. The tabular list is not displayed in this case.
* <br> This constant is member of constant group: Request Type Constants<br>
* These constants are equally available in each instance of DocQueryParams and in the constructor object.
* @instance
* @member {number} SCRIPT_TREE
* @readonly
*/
/**
* @memberof DocQueryParams
* @summary The number of filled in search fields in the query (read-only).
* @description This is in other words the number of conditions in the query.
* Note: Attaching a default value to a search field does not fill it in this context. Default values are being stored separately from concrete search values, for technical reasons.
* @member {number} filledSearchFieldCount
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DocQueryParams
* @summary The type (or trigger) of the search request (read-only).
* @description See the enumeration constants in this class. If Documents encounters a request, which it cannot categorize exactly, it will return the nearest match with respect to the server's internal interfaces.
* @member {number} requestType
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DocQueryParams
* @summary The number of declared search fields in the query (read-only).
* @description This count may include fields from a search mask, which have not been filled in.
* @member {number} searchFieldCount
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DocQueryParams
* @summary The (technical) name of the selected search mask, if available (read only).
* @description
* Note: The value is an empty string, if the query has been prepared without a search mask or with an anonymous mask (controlled by "show in search mask" checkboxes).
*
* Search mask names are unique with regard to a single searchable resource. As soon as multiple resources are involved, the names are often ambiguous, because each resource may supply a search mask with the same name.
*
* To obtain a better identifier, the script may combine the mask's name and the resId of the first selected resource.
*
* However, even this identifier is not always unique. If a user has selected multiple EE.x views and the DOCUMENTS property "UseMainArchives" is undefined or zero, the query does not specify a main resource. DOCUMENTS then passes the RetrievalSource objects with random order. In this case the script cannot distinguish search masks with equal names.
* @member {string} searchMaskName
* @instance
* @since DOCUMENTS 4.0e
* @see [getSource,sourceCount]{@link getSource,sourceCount}
**/
/**
* @memberof DocQueryParams
* @summary The number of searchable resources involved in the query (read-only).
* @member {number} sourceCount
* @instance
* @since DOCUMENTS 4.0c undefined
**/
/**
* @memberof DocQueryParams
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DocQueryParams
* @function getSearchField
* @instance
* @summary Get a descriptive object of one of the search fields (conditions), which are declared in the query.
* @description
* Note: If the request has been prepared with any kind of searck mask in the background, all available fields of that mask appear in the internal list, not only those, which the user has filled in. The skipEmpty flag provides a simple opportunity to examine only effective search conditions.
*
* Internally generated conditions (for example ACL-filters) cannot be returned by this function.
*
* Attaching a default value to a field does not modify its "empty" state in terms of this function.
* @param {number} index The index of the desired search field. The valid range is 0 to (filledSearchFieldCount - 1), if the flag <code>skipEmpty</code> is set. Otherwise the range is 0 to (searchFieldCount - 1).
* @param {boolean} skipEmpty An optional boolean to treat all empty search fields as non-existing. By default all fields can be examined.
* @returns {RetrievalField} A RetrievalField object, which contains a search field name, an operator and (sometimes) a value expression.
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DocQueryParams
* @function getSource
* @instance
* @summary Get a descriptive object of one selected search resource.
* @param {number} index The integer index of the resource in the internal list. Range: 0 to (sourceCount - 1)
* @returns {RetrievalSource} A RetrievalSource object on success, otherwise <code>null</code>.
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DocQueryParams
* @function removeSource
* @instance
* @summary Remove a search resource from the query.
* @description
* Note: The access to this function is restricted. Only the "OnSearchScript" can effectively use it.
* Note: The id can be read from the property RetrievalSource.resId. Valid index values range from 1 to (sourceCount - 1). The resource at index 0 cannot be removed (see the class details). After a succesful call, the sourceCount and the index of each subsequent resource in the list are decreased by one.
*
* The method does not perform type-checking on the refSource parameter. It interprets a value like "12345" always as an index, even when this value has been passed as a string.
* @param {any} refSource Either the current integer index or the id of the resource.
* @returns {boolean} A boolean value, which indicates a succesful call.
* @since DOCUMENTS 4.0c
**/
/**
* @interface Document
* @summary The Document class has been added to the DOCUMENTS PortalScripting API to gain full access to the documents stored on registers of a DOCUMENTS file by scripting means.
* @description Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @since ELC 3.50n / otrisPORTAL 5.0n
*/
/**
* @memberof Document
* @summary The file size of the Document object.
* @member {string} bytes
* @instance
* @since DOCUMENTS 4.0e
**/
/**
* @memberof Document
* @summary Info, if the blob is encrypted in the repository.
* @member {boolean} encrypted
* @instance
* @since DOCUMENTS 4.0d HF3
**/
/**
* @memberof Document
* @summary The extension of the Document object.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @member {string} extension
* @instance
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @memberof Document
* @summary The complete filename (name plus extension) of the Document object.
* @description
* Since ELC 3.50n / otrisPORTAL 5.0n
* @member {string} fullname
* @instance
* @since ELC 3.60i / otrisPORTAL 6.0i available for archive files
**/
/**
* @memberof Document
* @summary The name (without extension) of the Document object.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @member {string} name
* @instance
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @memberof Document
* @summary The file size of the Document object.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @member {string} size
* @instance
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @memberof Document
* @function deleteDocument
* @instance
* @summary Delete the Document object.
* @description With the necessary rights you can delete a document of the file. Do this only on scratch copies (startEdit, commit)
* Note: It is strictly forbidden to access the Document object after this function has been executed successfully; if you try to access it, your script will fail, because the Document does not exist any longer in DOCUMENTS.
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.60b / otrisPORTAL 6.0b
* @example
* // Deletion of the first document of the register "docs"
* var myFile = context.file;
* if (!myFile)
* {
* util.out("missing file");
* return -1;
* }
*
* var myReg = myFile.getRegisterByName("docs");
* if (!myReg)
* {
* util.out("missing >docs< register");
* return -1;
* }
*
* var firstDoc = myReg.getDocuments().first();
* if (!firstDoc)
* {
* return 0; // Nothing to do
* }
*
* if (!myFile.startEdit())
* {
* util.out("Unable to create scratch copy: " + myFile.getLastError());
* return -1;
* }
*
* if (!firstDoc.deleteDocument())
* {
* util.out(firstDoc.getLastError());
* myFile.abort();
* return -1;
* }
*
* if (!myFile.commit())
* {
* util.out("commit failed: " + myFile.getLastError());
* myFile.abort();
* return -1;
* }
* return 0;
**/
/**
* @memberof Document
* @function downloadDocument
* @instance
* @summary Download the Document to the server's filesystem for further use.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* Since DOCUMENTS 4.0 (new parameter filePath)
* Since DOCUMENTS 4.0d (new parameter version)
* @param {string} [filePath] Optional string specifying where the downloaded Document to be stored.
* Note: A file path containing special characters can be modified due to the encoding problem. The modified file path will be returned.
* @param {string} [version] Optional string value specifying which version of this Document to be downloaded (e.g. "2.0"). The default value is the active version.
* Note: This parameter is ignored for an archive document.
* @returns {string} String containing full path and file name of the downloaded Document, an empty string in case of any error.
* @since ELC 3.50n / otrisPORTAL 5.0n
* @example
* // Example 1
* var docFile = context.file;
* var reg = docFile.getRegisterByName("Documents");
* var docIter = reg.getDocuments();
* if (docIter && docIter.size() > 0)
* {
* var doc = docIter.first();
* var docPath = doc.downloadDocument();
* var txtFile = new File(docPath, "r+t");
* if (txtFile.ok())
* {
* var stringVar = txtFile.readLine(); // read the first line
* txtFile.close();
* }
* }
* @example
* // Example 2
* var docFile = context.file;
* var reg = docFile.getRegisterByName("Documents");
* var docIter = reg.getDocuments();
* if (docIter && docIter.size() > 0)
* {
* var doc = docIter.first();
* var docPath = "C:\\tmp\\test.txt";
* docPath = doc.downloadDocument(docPath, "2.0"); // since DOCUMENTS 4.0d
* if (docPath == "")
* util.out(doc.getLastError());
* }
**/
/**
* @memberof Document
* @function getAsPDF
* @instance
* @summary Create a PDF file containing the current Document's contents and return the path in the file system.
* @description The different document types of your documents require the appropriate PDF filter programs to be installed and configured in DOCUMENTS.
* @returns {string} <code>String</code> with file path of the PDF, an empty string in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var docFile = context.file;
* var reg = docFile.getRegisterByName("Doc1");
* var docIt = reg.getDocuments();
* for (doc = docIt.first(); doc; doc = docIt.next())
* {
* var pathPdfFile = doc.getAsPDF();
* if (pathPdfFile == "")
* util.out(doc.getLastError());
* else
* util.out("File path: " + pathPdfFile);
* }
**/
/**
* @memberof Document
* @function getAttribute
* @instance
* @summary Get the String value of an attribute of the Document.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {string} attribute String containing the name of the desired attribute
* @returns {string} String containing the value of the desired attribute
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @memberof Document
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @returns {string} Text of the last error as String
* @since ELC 3.50n / otrisPORTAL 5.0n
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof Document
* @function getOID
* @instance
* @summary Returns the object-id.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* Since DOCUMENTS 5.0 (new parameter oidLow)
* @param {boolean} [oidLow] Optional flag:
* If <code>true</code> only the id of the filetype object (<code>m_oid</code>) will be returned.
* If <code>false</code> the id of the filetype object will be returned together with the id of the corresponding class in the form <code>class-id:m_oid</code>.
* The default value is <code>false</code>.
* @returns {string} <code>String</code> with the object-id
* @since ELC 3.60c / otrisPORTAL 6.0c
**/
/**
* @memberof Document
* @function getRegister
* @instance
* @summary Returns the Register the Document belongs to.
* @returns {Register} Register object or <code>null</code> if missing
* @since DOCUMENTS 5.0c HF1
* @example
* var file = context.file;
* var reg1 = file.getRegisterByName("RegisterA");
* var firstDoc = reg1.getDocuments().first();
* if (firstDoc)
* {
* var reg = firstDoc.getRegister();
* if (reg)
* util.out(reg.name); // "RegisterA"
* }
**/
/**
* @memberof Document
* @function moveToRegister
* @instance
* @summary Move the Document to another document Register of the file.
* @description With the necessary rights you can move the Document to another document Register of the file.
* Note: This operation is not available for a Document located in an archive file.
* @param {Register} regObj The Register this Document will be moved to.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0c
* @example
* var file = context.file;
* if (!file.isArchiveFile())
* {
* var regDoc1 = file.getRegisterByName("Doc1");
* var regDoc2 = file.getRegisterByName("Doc2");
* var docIt = regDoc2.getDocuments();
* for (var doc = docIt.first(); doc; doc = docIt.next())
* {
* if (!doc.moveToRegister(regDoc1))
* util.out(doc.getLastError());
* }
* }
**/
/**
* @memberof Document
* @function setAttribute
* @instance
* @summary Set the String value of an attribute of the Document to the desired value.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {string} attribute String containing the name of the desired attribute
* @param {string} value String containing the desired value of the attribute
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @memberof Document
* @function uploadDocument
* @instance
* @summary Upload a file stored on the server's filesystem for replacing or versioning this Document.
* @description
* Note: After successful upload of the Document the source file on the server's directory structure is removed!
* @param {string} sourceFilePath String containing the path of the desired file to be uploaded.
* Note: Backslashes contained in the filepath must be quoted with a leading backslash, since the backslash is a special char in ECMAScript!
* @param {boolean} [versioning] Optional flag: <code>true</code> for versioning the Document and <code>false</code> for replacing it.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @example
* var docFile = context.file;
* var reg = docFile.getRegisterByName("Documents");
* var docIter = reg.getDocuments();
* if (docIter && docIter.size() > 0)
* {
* var doc = docIter.first();
* if (!doc.uploadDocument("c:\\tmp\\test.txt", true))
* util.out(doc.getLastError());
* }
**/
/**
* @interface DocumentIterator
* @summary The DocumentIterator class has been added to the DOCUMENTS PortalScripting API to gain full access to the documents stored on registers of a DOCUMENTS file by scripting means.
* @description Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @since ELC 3.50n / otrisPORTAL 5.0n
* @example
* var docFile = context.file;
* if (docFile)
* {
* var docreg = docFile.getRegisterByName("Documents");
* if (docreg)
* {
* var docs = docreg.getDocuments();
* if (docs && docs.size() > 0)
* {
* for (var d = docs.first(); d; d = docs.next())
* {
* util.out(d.Fullname);
* }
* }
* }
* }
*/
/**
* @memberof DocumentIterator
* @function first
* @instance
* @summary Retrieve the first Document object in the DocumentIterator.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @returns {Document} Document or <code>null</code> in case of an empty DocumentIterator
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @memberof DocumentIterator
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since ELC 3.50n / otrisPORTAL 5.0n
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof DocumentIterator
* @function next
* @instance
* @summary Retrieve the next Document object in the DocumentIterator.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @returns {Document} Document or <code>null</code> if end of DocumentIterator is reached.
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @memberof DocumentIterator
* @function size
* @instance
* @summary Get the amount of Document objects in the DocumentIterator.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @returns {number} integer value with the amount of Document objects in the DocumentIterator
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @interface DOMAttr
* @summary This class models a single attribute of a DOMElement.
* @description DOMAttrs cannot be created directly. This applies to all kinds of DOMNodes.
* <b>Remarks about W3C conformity</b>
*
* The class covers the Attribute interface of DOM level 1. The underlying native library already supports at least level 2.
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMAttr
* @summary The name of the attribute.
* @description This property is readonly.
* @member {string} name
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMAttr
* @summary A flag to test, whether the attribute's value has been explicitly specified.
* @description The flag is <code>true</code>, if the value was explicitly contained in a parsed document. The flag is also <code>true</code>, if the script has set the property "value" of this DOMAttr object. The flag is <code>false</code>, if the value came from a default value declared in a DTD. The flag is readonly.
* @member {boolean} specified
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMAttr
* @summary The value of the attribute as a string.
* @description Character and general entity references are replaced with their values.
* @member {string} value
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @interface DOMCharacterData
* @summary DOMCharacterData represents text-like nodes in the DOM tree.
* @description An object of this class can represent either a text node, a comment node or a CDATA section. Scripts should use the inherited nodeType attribute to distinguish these node types.
* <b>Remarks about W3C conformity</b>
*
* The class covers the CharacterData interface of DOM level 1. The underlying native library already supports at least level 2. The W3C has defined several derived interfaces, namely "Text", "Comment" and "CDATASection". With respect to code size (and work) this API omits the corresponding subclasses "DOMText", "DOMComment" and "DOMCDATASection". The only additional method "DOMText.splitText()" has been moved into this class.
*
* This simplification has got only one little disadvantage. Scripts cannot distinguish the three node types using the JavaScript <code>instanceof</code> operator. They must use the nodeType attribute instead.
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMCharacterData
* @summary The text data in the node.
* @member {string} data
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMCharacterData
* @summary The text length in the node.
* @description This property is readonly.
* @member {number} length
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMCharacterData
* @function appendData
* @instance
* @summary Append some string to the text.
* @param {string} arg The string to append.
* @returns {void}
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMCharacterData
* @function deleteData
* @instance
* @summary Delete a section of the text.
* @param {number} offset The zero-based position of the first character to delete.
* @param {number} count The number of characters to delete.
* @returns {void}
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMCharacterData
* @function insertData
* @instance
* @summary Insert some string into the text.
* @param {number} offset A zero-based position. On return, the inserted string will begin here.
* @param {string} arg The string to insert.
* @returns {void}
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMCharacterData
* @function replaceData
* @instance
* @summary Replace a section of the text with a new string.
* @param {number} offset The zero-based position of the first character to be replaced.
* @param {number} count The number of characters to replace.
* @param {string} arg The string replacing the old one.
* @returns {void}
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMCharacterData
* @function splitText
* @instance
* @summary Split a text node into two.
* @description The new node becomes the next sibling of this node in the tree, and it has got the same nodeType.
* Note: Future releases of the API may expose this method only in a new subclass DOMText. See also the W3C conformity remarks in the class description. If a script calls this method on a "Comment" node. it will trigger a JavaScript error, because "Comment" is not derived from "Text" in the standard API.
* @param {number} offset The zero-based index of the character, which will become the first character of the new node.
* @returns {DOMCharacterData} The new text node.
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMCharacterData
* @function substringData
* @instance
* @summary Extract a substring of the node's text.
* @param {number} offset The zero-based index of the first character to extract.
* @param {number} count The number of characters to extract.
* @returns {string} The requested substring.
* @since DOCUMENTS 4.0c
**/
/**
* @class DOMDocument
* @classdesc The DOMDocument is the root of a DOM tree.
* The constructor of this class always creates an empty document structure. Use the class DOMParser to obtain the structure of an existing XML. To create any new child nodes, a script must call the appropriate create method of the DOMDocument. It is not possible to create child nodes standalone.
* After a DOMDocument has been deleted by the scripting engine's garbage collector, accessing any nodes and lists of that document may issue an error. You should avoid code like the following.
* function buildSomeElement()
* {
* var domDoc = new DOMDocument("root");
* var someElement = domDoc.createElement("Test");
*
* // This is an error: Some operations on the DOMElement may no
* // longer work, when the owning DOMDocument has already died.
* return someElement;
* }
*
* <b>Remarks about W3C conformity</b>
*
* The class covers much of the Document interface of DOM level 1, but the following properties and functions have not been implemented until now.
* <ul>
* <li>DocumentType doctype</li>
* <li>DOMImplementation implementation</li>
* <li>DocumentFragment createDocumentFragment()</li>
* <li>ProcessingInstruction createProcessingInstruction(String target, String data)</li>
* <li>EntityReference createEntityReference(in String name)</li>
* </ul>
*
* The native DOM library behind the scripting API already supports at least DOM level 2. This is worth knowing, because the behaviour of a few operations might have changed with level 2.
* @since DOCUMENTS 4.0c
* @summary Create a new empty XML document structure.
* Since DOCUMENTS 4.0c
* @param {string} rootElementName A qualified name for the document element.
*/
/**
* @memberof DOMDocument
* @summary The node, which represents the outermost structure element of the document.
* @description This property is readonly.
* Note: Unlike written in older versions of this document, the documentElement is not necessarily the first child of the DOMDocument. A DocumentType node, for example, may precede it in the list of direct children.
* @member {DOMElement} documentElement
* @instance
* @since DOCUMENTS 4.0d
**/
/**
* @memberof DOMDocument
* @function createAttribute
* @instance
* @summary Create a new atttribute within this document.
* @param {string} name The name of the attribute.
* @returns {DOMAttr} A new DOMAttr object, which may initially appear anywhere or nowhere in the DOM tree.
* @since DOCUMENTS 4.0c
* @see [DOMElement.setAttributeNodetoplacethenodewithinthetree.]{@link DOMElement#setAttributeNodetoplacethenodewithinthetree#}
**/
/**
* @memberof DOMDocument
* @function createCDATASection
* @instance
* @summary Create a new CDATA section within this document.
* @description <b>Remarks about W3C conformity</b>
*
* The W3C specifies the return type as "CDATASection". Considering code size (and work) the actual implementation omits a class CDATASection and presents the only additional member (splitText(), inherited from "Text") directly in the second level base class. Scripts can examine DOMNode.nodeType to distinguish different types of character data, if necessary.
* @param {string} data The data for the node
* @returns {DOMCharacterData} A new DOMCharacterData object, which may initially appear anywhere or nowhere in the DOM tree.
* @since DOCUMENTS 4.0c
* @see [DOMNode.appendChildtoplacethenodewithinthetree.]{@link DOMNode#appendChildtoplacethenodewithinthetree#}
**/
/**
* @memberof DOMDocument
* @function createComment
* @instance
* @summary Create a new comment node within this document.
* @description <b>Remarks about W3C conformity</b>
*
* The W3C specifies the return type as "Comment". Considering code size (and work) the actual implementation omits a class DOMComment, which would not get any more members apart from the inherited ones. Scripts can examine DOMNode.nodeType to distinguish different types of character data, if necessary.
* @param {string} data The data for the node
* @returns {DOMCharacterData} A new DOMCharacterData object, which may initially appear anywhere or nowhere in the DOM tree.
* @since DOCUMENTS 4.0c
* @see [DOMNode.appendChildtoplacethenodewithinthetree.]{@link DOMNode#appendChildtoplacethenodewithinthetree#}
**/
/**
* @memberof DOMDocument
* @function createElement
* @instance
* @summary Create a new DOMElement within this document.
* @param {string} tagName The name of the element.
* @returns {DOMElement} A new DOMElement, which may initially appear anywhere or nowhere in the DOM tree.
* @since DOCUMENTS 4.0c
* @see [DOMNode.appendChildtoplacetheelementwithinthetree.]{@link DOMNode#appendChildtoplacetheelementwithinthetree#}
**/
/**
* @memberof DOMDocument
* @function createTextNode
* @instance
* @summary Create a new text node within this document.
* @description <b>Remarks about W3C conformity</b>
*
* The W3C specifies the return type as "Text". Considering code size (and work) the actual implementation omits a class DOMText and presents the only additional member (splitText()) directly in the base class. Scripts can examine DOMNode.nodeType to distinguish different types of character data, if necessary.
* @param {string} data The data for the node
* @returns {DOMCharacterData} A new DOMCharacterData object, which may initially appear anywhere or nowhere in the DOM tree.
* @since DOCUMENTS 4.0c
* @see [DOMNode.appendChildtoplacethenodewithinthetree.]{@link DOMNode#appendChildtoplacethenodewithinthetree#}
**/
/**
* @memberof DOMDocument
* @function getElementsByTagName
* @instance
* @summary List all DOMElements in the document with a certain tag name.
* @description The order of the elements in the returned list corresponds to a preorder traversal of the DOM tree.
* @param {string} tagName The name to match on. The special value "*" matches all tags.
* @returns {DOMNodeList} A dynamic list of the found elements.
* @since DOCUMENTS 4.0c
* @see [DOMNodeList.]{@link DOMNodeList#}
**/
/**
* @interface DOMElement
* @summary An object of this class represents a HTML or XML element in the DOM.
* @description DOMElements cannot be created directly. This applies to all kinds of DOMNodes.
* <b>Remarks about W3C conformity</b>
*
* The class covers the Element interface of DOM level 1. The underlying native library already supports at least level 2.
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMElement
* @summary The name of the element.
* @description This property is readonly.
* @member {string} tagName
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMElement
* @function getAttribute
* @instance
* @summary Get the string value of an attribute of this element.
* @param {string} name The name of the attribute
* @returns {string} The atrribute's value or the empty string, if the attribute is not specified and has not got a default value.
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMElement
* @function getAttributeNode
* @instance
* @summary Get an attribute of this element.
* @param {string} name The attribute's name
* @returns {DOMAttr} The object, which represents the attribute in the DOM. If no attribute of the given name exists, the value is <code>null</code>.
**/
/**
* @memberof DOMElement
* @function getElementsByTagName
* @instance
* @summary List all DOMElements in the subtree with a certain tag name.
* @description The order of the elements in the returned list corresponds to a preorder traversal of the DOM tree.
* @param {string} tagName The name to match on. The special value "*" matches all tags.
* @returns {DOMNodeList} A dynamic list of the found elements.
* @since DOCUMENTS 4.0c
* @see [DOMNodeList.]{@link DOMNodeList#}
**/
/**
* @memberof DOMElement
* @function removeAttribute
* @instance
* @summary Remove an attribute from this element by name.
* @param {string} name The attribute's name
* @returns {void}
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMElement
* @function removeAttributeNode
* @instance
* @summary Remove an attribute node from this element.
* @param {DOMAttr} oldAttr The attribute object to remove
* @returns {DOMAttr} The removed attribute node.
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMElement
* @function setAttribute
* @instance
* @summary Set an attribute of this element by string.
* @description If an attribute of the given name exists, the method only updates its value. Otherwise it creates the attribute.
* @param {string} name The attribute's name
* @param {string} value The new value of the attribute
* @returns {void}
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMElement
* @function setAttributeNode
* @instance
* @summary Attach an attribute node to this element.
* @param {DOMAttr} newAttr The DOMAttr object, which defines the attribute to add or replace.
* @returns {DOMAttr} The formerly attached DOMAttr, if the call has replaced an attribute with the same name. Otherwise the method returns <code>null</code>.
* @since DOCUMENTS 4.0c
**/
/**
* @interface DOMException
* @summary Many of the DOM API functions throw a DOMException, when an error has occurred.
* @description <b>Remarks about W3C conformity</b>
*
* The class implements the DOMException exception type with the error codes specified in DOM level 2.
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary The index or size is negative, or greater than the allowed value.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} INDEX_SIZE_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary The specified range of text does not fit into a DOMString.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} DOMSTRING_SIZE_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary Any node is inserted somewhere it doesn't belong.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} HIERARCHY_REQUEST_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary A node is used in a different document than the one that created it.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} WRONG_DOCUMENT_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary An invalid or illegal character is specified, such as in a name.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} INVALID_CHARACTER_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary Data is specified for a node which does not support data.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} NO_DATA_ALLOWED_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary An attempt is made to modify an object where modifications are not allowed.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} NO_MODIFICATION_ALLOWED_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary An attempt is made to reference a node in a context where it does not exist.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} NOT_FOUND_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary The implementation does not support the requested type of object or operation.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} NOT_SUPPORTED_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary An attempt is made to add an attribute that is already in use elsewhere.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} INUSE_ATTRIBUTE_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary An attempt is made to use an object that is not, or is no longer, usable.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} INVALID_STATE_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary An invalid or illegal string is specified.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} SYNTAX_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary An attempt is made to modify the type of the underlying object.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} INVALID_MODIFICATION_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} NAMESPACE_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary A parameter or an operation is not supported by the underlying object.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} INVALID_ACCESS_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @summary A call to a method such as insertBefore or removeChild would make the Node invalid with respect to "partial validity", this exception would be raised and the operation would not be done.
* @description
* <br> This constant is member of constant group: Error Code Constants<br>
* All these constants are also available as properties of the constructor.
* @instance
* @member {number} VALIDATION_ERR
* @readonly
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMException
* @readonly
* @summary An error code.
* @description See the error constants in this class.
* @member {number} code
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMException
* @readonly
* @summary An error message.
* @member {string} message
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @interface DOMNamedNodeMap
* @summary A DOMNamedNodeMap is a kind of index for a set of DOMNodes, in which each node has got a unique name.
* @description The attributes of a DOMElement are organized in a DOMNamedNodeMap. See DOMElement.attributes. The attached nodes can be accessed either by the name or by an integer index. When using an index, the output order of the nodes is not determined. Objects of this class cannot be created directly.
* <b>Remarks about W3C conformity</b>
*
* The class covers the NamedNodeMap interface of DOM level 1. The underlying native library already supports at least level 2.
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMNamedNodeMap
* @summary The number of nodes in the map.
* @description This property is readonly.
* @member {number} length
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMNamedNodeMap
* @function getNamedItem
* @instance
* @summary Get a node from the map by its unique name.
* @param {string} name The name.
* @returns {DOMNode} The node, respectively <code>null</code>, if no node with the name is in the map.
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMNamedNodeMap
* @function item
* @instance
* @summary Get the a node from the map at a certain position.
* @description This is useful only to iterate over all nodes in the map.
* Note: It is also possible to access the nodes using square brackets, as if the object would be an array.
* @param {number} index the zero based index of the element.
* @returns {DOMNode} The requested DOMNode Object. If the index is invalid, the method returns <code>null</code>.
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMNamedNodeMap
* @function removeNamedItem
* @instance
* @summary Remove a node from the map.
* @param {string} name The unique node name.
* @returns {DOMNode} The removed node.
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMNamedNodeMap
* @function setNamedItem
* @instance
* @summary Add a node to the map or replace an existing one.
* @param {DOMNode} arg The node to add. The name for indexing is the value of the attribute DOMNode.nodeName,
* @returns {DOMNode} If a node with the same name has already been added, the method removes that node and returns it. Otherwise it returns <code>null</code>.
* @since DOCUMENTS 4.0c
**/
/**
* @interface DOMNode
* @summary DOMNode is the base class of all tree elements in a DOMDocument.
* @description DOMNodes cannot be created with <code>new</code>. Different create methods of DOMDocument can be used to create different types of nodes.
* Note: Accessing any node may generate a JavaScript error, when the owning document has been deleted or "garbage collected". See the negative example at class DOMDocument.<b>Remarks about W3C conformity</b>
*
* The class covers the Node interface of DOM level 1. The underlying native library already supports at least level 2.
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMNode
* @summary Constant for the nodeType "Element". The actual subclass is DOMElement.
* @description
* <br> This constant is member of constant group: Node Type Constants<br>
* These constants build an enumeration of the possible values of the property nodeType. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} ELEMENT_NODE
* @readonly
*/
/**
* @memberof DOMNode
* @summary Constant for the nodeType "Attr". The actual subclass is DOMAttr.
* @description
* <br> This constant is member of constant group: Node Type Constants<br>
* These constants build an enumeration of the possible values of the property nodeType. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} ATTRIBUTE_NODE
* @readonly
*/
/**
* @memberof DOMNode
* @summary Constant for the nodeType "Text". The actual subclass is DOMCharacterData, differing from the standard.
* @description
* <br> This constant is member of constant group: Node Type Constants<br>
* These constants build an enumeration of the possible values of the property nodeType. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} TEXT_NODE
* @readonly
*/
/**
* @memberof DOMNode
* @summary Constant for the nodeType "CDATASection". The actual subclass is DOMCharacterData, differing from the standard.
* @description
* <br> This constant is member of constant group: Node Type Constants<br>
* These constants build an enumeration of the possible values of the property nodeType. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} CDATA_SECTION_NODE
* @readonly
*/
/**
* @memberof DOMNode
* @summary Constant for the nodeType "EntityReference". The actual implementation does not provide a subclass for this type.
* @description
* <br> This constant is member of constant group: Node Type Constants<br>
* These constants build an enumeration of the possible values of the property nodeType. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} ENTITY_REFERENCE_NODE
* @readonly
*/
/**
* @memberof DOMNode
* @summary Constant for the nodeType "Entity". The actual implementation does not provide a subclass for this type.
* @description
* <br> This constant is member of constant group: Node Type Constants<br>
* These constants build an enumeration of the possible values of the property nodeType. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} ENTITY_NODE
* @readonly
*/
/**
* @memberof DOMNode
* @summary Constant for the nodeType "ProcessingInstruction". The actual implementation does not provide a subclass for this type.
* @description
* <br> This constant is member of constant group: Node Type Constants<br>
* These constants build an enumeration of the possible values of the property nodeType. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} PROCESSING_INSTRUCTION_NODE
* @readonly
*/
/**
* @memberof DOMNode
* @summary Constant for the nodeType "Comment". The actual subclass is DOMCharacterData, differing from the standard.
* @description
* <br> This constant is member of constant group: Node Type Constants<br>
* These constants build an enumeration of the possible values of the property nodeType. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} COMMENT_NODE
* @readonly
*/
/**
* @memberof DOMNode
* @summary Constant for the nodeType "Document". The actual subclass is DOMDocument.
* @description
* <br> This constant is member of constant group: Node Type Constants<br>
* These constants build an enumeration of the possible values of the property nodeType. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} DOCUMENT_NODE
* @readonly
*/
/**
* @memberof DOMNode
* @summary Constant for the nodeType "DocumentType". The actual implementation does not provide a subclass for this type.
* @description
* <br> This constant is member of constant group: Node Type Constants<br>
* These constants build an enumeration of the possible values of the property nodeType. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} DOCUMENT_TYPE_NODE
* @readonly
*/
/**
* @memberof DOMNode
* @summary Constant for the nodeType "DocumentFragment". The actual implementation does not provide a subclass for this type.
* @description
* <br> This constant is member of constant group: Node Type Constants<br>
* These constants build an enumeration of the possible values of the property nodeType. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} DOCUMENT_FRAGMENT_NODE
* @readonly
*/
/**
* @memberof DOMNode
* @summary Constant for the nodeType "Notation". The actual implementation does not provide a subclass for this type.
* @description
* <br> This constant is member of constant group: Node Type Constants<br>
* These constants build an enumeration of the possible values of the property nodeType. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} NOTATION_NODE
* @readonly
*/
/**
* @memberof DOMNode
* @summary A map of DOM attributes. If this node is not a DOMElement, the value is null. The property is readonly.
* @member {DOMNamedNodeMap} attributes
* @instance
**/
/**
* @memberof DOMNode
* @summary A list of all children of this node. The property is readonly.
* @member {DOMNodeList} childNodes
* @instance
**/
/**
* @memberof DOMNode
* @summary The first child node, otherwise null. The property is readonly.
* @member {DOMNode} firstChild
* @instance
**/
/**
* @memberof DOMNode
* @summary The last child node, otherwise null. The property is readonly.
* @member {DOMNode} lastChild
* @instance
**/
/**
* @memberof DOMNode
* @summary The next sibling node, otherwise null. The property is readonly.
* @member {DOMNode} nextSibling
* @instance
**/
/**
* @memberof DOMNode
* @summary The name of this node. The property is readonly.
* @member {string} nodeName
* @instance
**/
/**
* @memberof DOMNode
* @summary The type or subclass of a this node, encoded as an integer. The property is readonly.
* @member {number} nodeType
* @instance
**/
/**
* @memberof DOMNode
* @summary The value of the node, which depends on the type.
* @description For several node types, the value is constantly an empty string. See also the [W3C documentation in the internet]{@link http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html}.
* @member {string} nodeValue
* @instance
**/
/**
* @memberof DOMNode
* @summary The document, which owns this node. The property is readonly.
* @member {DOMDocument} ownerDocument
* @instance
**/
/**
* @memberof DOMNode
* @summary The parent node or null. The property is readonly.
* @member {DOMNode} parentNode
* @instance
**/
/**
* @memberof DOMNode
* @summary The previous sibling node, otherwise null. The property is readonly.
* @member {DOMNode} previousSibling
* @instance
**/
/**
* @memberof DOMNode
* @function appendChild
* @instance
* @summary Append a new node to the list of child nodes.
* @param {DOMNode} newChild The DOMNode to append.
* @returns {DOMNode} The node added.
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMNode
* @function cloneNode
* @instance
* @summary Create a duplicate of this node.
* @description
* Note: The returned node initially has not got a parent.
* @param {boolean} deep <code>true</code> to clone also the whole subtree, <code>false</code> to clone only the node (including the attributes, if it is a DOMElement).
* @returns {DOMNode} The copy. The actual type equals the type of <code>this</code>.
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMNode
* @function hasAttributes
* @instance
* @summary Test, whether a node has got any associated attributes.
* @returns {boolean}
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMNode
* @function hasChildNodes
* @instance
* @summary Test, whether a node has got any associated child nodes.
* @returns {boolean}
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMNode
* @function insertBefore
* @instance
* @summary Insert a new node into the list of child nodes.
* @param {DOMNode} newChild The DOMNode to insert.
* @param {DOMNode} refChild An existing DOMNode, which already is a child of <code>this</code>, and which shall become the next sibling of <code>newChild</code>.
* @returns {DOMNode} The node inserted.
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMNode
* @function normalize
* @instance
* @summary Normalize the node ans its subtree.
* @description This method restructures a DOMDocument (or a subtree of it) as if the document was written to a string and reparsed from it. Subsequent "Text" nodes without any interjacent markup are combined into one node, for example.
* @returns {void}
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMNode
* @function removeChild
* @instance
* @summary Remove a node from the list of child nodes.
* @param {DOMNode} oldChild The child DOMNode being removed.
* @returns {DOMNode} The node removed.
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMNode
* @function replaceChild
* @instance
* @summary Replace a node in the list of child nodes.
* @param {DOMNode} newChild The DOMNode to insert.
* @param {DOMNode} oldChild The child DOMNode being replaced.
* @returns {DOMNode} The node replaced.
* @since DOCUMENTS 4.0c
**/
/**
* @interface DOMNodeList
* @summary A dynamic, ordered list of DOMNodes.
* @description These lists always reflect the actual state of the DOM tree, which can differ from that state, when the list has been created. Getting the nodes from the list works with an integer index in square brackets, as if the list object would be an Array. DOMNodeLists cannot be created directly. Some methods or properties of DOMNode and its subclasses can create them.
* <b>Remarks about W3C conformity</b>
*
* The class covers the NodeList interface of DOM level 1. The underlying native library already supports at least level 2.
* @since DOCUMENTS 4.0c
*/
/**
* @memberof DOMNodeList
* @summary The actual number of nodes in the list.
* @member {number} length
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMNodeList
* @function item
* @instance
* @summary Returns the element at a certain position.
* @description This is just the same as using the square brackets on the object.
* @param {number} index The zero-based position of the requested element
* @returns {DOMNode} The DOMNode at the requested index. In the case of an invalid index the return value is <code>null</code>.
* @since DOCUMENTS 4.0c
**/
/**
* @class DOMParser
* @classdesc This class provides basic methods to parse or synthesize XML documents using the Document Object Model (DOM).
* @since DOCUMENTS 4.0c
* @summary The constructor actually takes no arguments.
*/
/**
* @memberof DOMParser
* @summary This constant with the value zero indicates "no error".
* @description
* <br> This constant is member of constant group: Error Constants<br>
* In contrast to many other methods of the DOM API, the method does not forward exceptions of the native parser to the calling script. It rather stores the error text in a buffer, which the script can read with . The return value signals the type of the exception, which equals one of these constants. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} ErrCatNone
* @readonly
*/
/**
* @memberof DOMParser
* @summary This constant represents errors detected by interface code outside the native parser.
* @description
* <br> This constant is member of constant group: Error Constants<br>
* In contrast to many other methods of the DOM API, the method does not forward exceptions of the native parser to the calling script. It rather stores the error text in a buffer, which the script can read with . The return value signals the type of the exception, which equals one of these constants. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} ErrCatEnv
* @readonly
*/
/**
* @memberof DOMParser
* @summary This constant represents a caught exception of the type "XMLException".
* @description
* <br> This constant is member of constant group: Error Constants<br>
* In contrast to many other methods of the DOM API, the method does not forward exceptions of the native parser to the calling script. It rather stores the error text in a buffer, which the script can read with . The return value signals the type of the exception, which equals one of these constants. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} ErrCatXML
* @readonly
*/
/**
* @memberof DOMParser
* @summary This constant represents a caught exception of the type "SAXException".
* @description
* <br> This constant is member of constant group: Error Constants<br>
* In contrast to many other methods of the DOM API, the method does not forward exceptions of the native parser to the calling script. It rather stores the error text in a buffer, which the script can read with . The return value signals the type of the exception, which equals one of these constants. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} ErrCatSAX
* @readonly
*/
/**
* @memberof DOMParser
* @summary This constant represents a caught exception of the type "DOMException".
* @description
* <br> This constant is member of constant group: Error Constants<br>
* In contrast to many other methods of the DOM API, the method does not forward exceptions of the native parser to the calling script. It rather stores the error text in a buffer, which the script can read with . The return value signals the type of the exception, which equals one of these constants. The constants are also properties of the constructor, so it is possible to read them in the style .
* @instance
* @member {number} ErrCatDOM
* @readonly
*/
/**
* @memberof DOMParser
* @function getDocument
* @instance
* @summary This returns the root of the DOM tree after a successful call of parse(), otherwise null.
* @returns {DOMDocument}
**/
/**
* @memberof DOMParser
* @function getLastError
* @instance
* @summary This returns the text of the last occurred error.
* @returns {string}
**/
/**
* @memberof DOMParser
* @function parse
* @instance
* @summary Parse an XML document, either from a String or from a local file.
* @description
* Note: On success, call getDocument() to access the DOM tree. On error use getLastError() to obtain an error text.
*
* The encapsulated native DOM library supports the following character encodings: ASCII, UTF-8, UTF-16, UCS4, EBCDIC code pages IBM037, IBM1047 and IBM1140, ISO-8859-1 (aka Latin1) and Windows-1252. (no guarantee)
* @param {string} xml Either the XML itself or the path and file name of a local file
* @param {boolean} fromFile <code>true</code> to parse a local file, otherwise <code>false</code>.
* @returns {number} An integer, which describes an error category. See ErrCatNone and further constants.
* @since DOCUMENTS 4.0c
**/
/**
* @memberof DOMParser
* @function write
* @instance
* @summary Build an XML document from a DOM tree.
* @description
* Note: Saving to a local file is not supported on all platforms. If a script tries it while the version of the native DOM library is too old, the method just throws a JavaScript error.
* Note: To obtain an error message use getLastError(). When the message is just "NULL pointer", the native DOM library may have failed to open the output file for writing. When the method writes to a string, the encoding is always the server application's internal encoding.
*
* The encapsulated native DOM library supports the following character encodings: ASCII, UTF-8, UTF-16, UCS4, EBCDIC code pages IBM037, IBM1047 and IBM1140, ISO-8859-1 (aka Latin1) and Windows-1252. (no guarantee)
* Since Parameter prettyPrint since DOCUMENTS 5.0b HF3
* @param {DOMNode} node The root node to build the document from. Though the interface accepts any DOMNode, only a DOMDocument should be passed. Otherwise the output may be a fragment which is not a valid XML.
* @param {string} path Optional path and filename to save the XML in the local file system.
* @param {string} encoding Optional encoding specification for the file. Only used when <em>path</em> is also specified.
* @param {boolean} prettyPrint Optional boolean value.
* @returns {any} The return type depends on the parameters. After saving to a local file, the method returns a boolean value, which indicates the success of the operation. Otherwise the return value is a String with the XML itself, or an empty string after an error.
* @since DOCUMENTS 4.0c
**/
/**
* @interface E4X
* @description Use DOMParser instead.
* @deprecated XMLParser E4X is deprecated since DOCUMENTS 4.0c and was removed in DOCUMENTS 5.0.
*/
/**
* @class Email
* @classdesc The Email class allows to create and send an email.
* All the email settings for the principal (such as SMTP server and authentication) are used when sending an email.
* @since DOCUMENTS 4.0d
* @example
* var mail = new Email("receiver@domain.de", "sender@domain.de", "Test", "This is a test email.");
* mail.addAttachment("log.txt", "C:\\tmp\\changelog.txt");
* mail.setBCC("somebody1@domain.de,somebody2@domain.com");
* mail.setDeleteAfterSending(true);
* if (!mail.send())
* util.out(mail.getLastError());
* @summary Create a new instance of the Email class.
* @description In case of multiple recipients for the parameters <code>to</code>, <code>cc</code> or <code>bcc</code>, the individual email addresses are to be separated by a comma (,). It is not allowed to send an email without any primary recipients specified by the parameter <code>to</code>. To send a HTML email the body must begin with the <HTML> tag. Emails in following cases are stored in the folder <code>Administration > Sent eMails</code> in the DOCUMENTS Manager:
* <ul>
* <li>They are to be sent in the future (specified by <code>sendingTime</code>); </li>
* <li>Sending them failed; </li>
* <li>The parameter <code>deleteAfterSending</code> is set to <code>false</code>.</li>
* </ul>
*
* Since DOCUMENTS 4.0d
* @param {string} to String value containing the email addresses of primary recipients.
* @param {string} from Optional string value containing the sender's email address. If no sender is specified, the default sender for the principal is used.
* @param {string} subject Optional string value containing the subject of the email.
* @param {string} body Optional string value containing the content of the email.
* @param {string} cc Optional string value containing the email addresses of carbon-copy recipients (appearing in the header of the email).
* @param {string} bcc Optional string value containing the email addresses of blind carbon-copy recipients (remaining invisible to other recipients).
* @param {Date} sendingTime Optional Date object specifying when the email is to be sent. If sending time is not specified, the email will be sent immediately by calling send().
* @param {boolean} deleteAfterSending Optional flag indicating whether the email is to be deleted after successful sending. The default value is <code>true</code>.
*/
/**
* @memberof Email
* @function addAttachment
* @instance
* @summary Add an attachment to the email.
* @param {any} attachment Document object or string value containing the attachment name of the Email.
* @param {string} sourceFilePath Optional string value containing the path of the file to be attached and stored on the server's filesystem in case the first parameter is a string specifying the attachment name. You may only delete this file after calling the function send().
* Note: This Parameter is ignored in case the first parameter is a Document object.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @example
* var mail = new Email("receiver@domain.de", "sender@domain.de", "Test", "This is a test.");
* if (!mail.addAttachment("log.txt", "C:\\tmp\\changelog.txt"))
* util.out(mail.getLastError());
**/
/**
* @memberof Email
* @function getLastError
* @instance
* @summary Get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since DOCUMENTS 4.0d
**/
/**
* @memberof Email
* @function send
* @instance
* @summary Send the email to recipients.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @example
* var mail = new Email("receiver@domain.de");
* mail.setSubject("Test");
* mail.setBody("This is a test mail.");
* if (!mail.send())
* util.out(mail.getLastError());
**/
/**
* @memberof Email
* @function setBCC
* @instance
* @summary Set blind carbon-copy recipients of the email.
* @param {string} bcc String containing the email addresses of blind carbon-copy recipients.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
**/
/**
* @memberof Email
* @function setBody
* @instance
* @summary Set the content of the email.
* @param {string} body String containing the content of the email.
* Note: To send a HTML email the body must begin with the <HTML> tag.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @example
* var mail = new Email("receiver@domain.de");
* mail.setSubject("Test");
* mail.setBody("<HTML>This is a <HTML> mail.");
* if (!mail.send())
* util.out(mail.getLastError());
**/
/**
* @memberof Email
* @function setCC
* @instance
* @summary Set carbon-copy recipients of the email.
* @param {string} cc String containing the email addresses of carbon-copy recipients.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
**/
/**
* @memberof Email
* @function setDeleteAfterSending
* @instance
* @summary Decide on whether the email is to be deleted after successful sending.
* @param {boolean} deleteAfterSending boolean value indicating whether the email is to be deleted after successful sending.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
**/
/**
* @memberof Email
* @function setFrom
* @instance
* @summary Set the sender's email address.
* @param {string} from String containing the sender's email address.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
**/
/**
* @memberof Email
* @function setSendingTime
* @instance
* @summary Set sending time of the email.
* @param {Date} sendingTime Date object representing the sending time.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @example
* var mail = new Email("receiver@domain.de", "sender@domain.de", "Test", "This is a test.");
* var actDate = new Date();
* var newDate = context.addTimeInterval(actDate, 2, "days", false);
* mail.setSendingTime(newDate);
**/
/**
* @memberof Email
* @function setSubject
* @instance
* @summary Set the subject of the email.
* @param {string} subject String containing the desired subject of the email.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
**/
/**
* @memberof Email
* @function setTo
* @instance
* @summary Set the primary recipients of the email.
* @param {string} to String containing the email addresses of primary recipients.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
**/
/**
* @class File
* @classdesc The File class allows full access to files stored on the Portal Server's filesystem.
* @since ELC 3.50 / otrisPORTAL 5.0
* @summary The constructor has the purpose to open a file handle to the desired file.
* @description Once created, you cannot change the access mode of the file handle. If you need to change the access mode, you would have to close the file and reopen it.
* Note: File handles are so-called expensive ressources, thus it is strongly recommanded to close them as soon as possible. Refer to File.close() for further information.
* Since ELC 3.50 / otrisPORTAL 5.0
* @param {string} pathFileName String value containing the complete path and filename of the desired file
* @param {string} mode String representing the access mode for the file handle. Allowed values are:
* <ul>
* <li><code>r</code> read mode </li>
* <li><code>r+</code> read mode plus write access; if the file does not yet exist, an error is raised </li>
* <li><code>w</code> write mode; if the file already exists, it will be completely overwritten </li>
* <li><code>w+</code> write mode plus read access; if the file already exists, it will be completely overwritten </li>
* <li><code>a</code> write mode with append; if the file does not yet exist, it is created, otherwise the data you write to the file will be appended </li>
* <li><code>a+</code> write mode with append plus read access; if the file does not yet exist, it is created, otherwise the data you write to the file will be appended </li>
* <li><code>t</code> open the file in text mode (ASCII 127) </li>
* <li><code>b</code> open the file in binary mode </li>
* </ul>
*
* @see [File.close]{@link File#close}
* @example
* // Text-Sample
* var fso = new File("c:\\tmp\\test.txt", "w+t");
* if (!fso.ok())
* throw fso.error();
* var int_val = 65;
* fso.write("Hello world: ", int_val);
* fso.close();
* // result: test.txt: Hello world: 65
*
* // Binary-Sample
* var fso = new File("c:\\tmp\\test.txt", "w+b");
* if (!fso.ok())
* throw fso.error();
* var int_val = 65;
* fso.write("Hello world: ", int_val);
* fso.close();
* // result: test.txt: Hello world: A
*
* // Binary-Sample with Byte-Array
* var fso = new File("c:\\tmp\\test.txt", "w+b");
* if (!fso.ok())
* throw fso.error();
* var byteArr = [];
* byteArr.push(72);
* byteArr.push(101);
* byteArr.push(108);
* byteArr.push(108);
* byteArr.push(111);
* byteArr.push(0); // 0-Byte
* byteArr.push(87);
* byteArr.push(111);
* byteArr.push(114);
* byteArr.push(108);
* byteArr.push(100);
* fso.write(byteArr);
* fso.close();
* // result: test.txt: Hello{0-Byte}World
*/
/**
* @memberof File
* @function close
* @instance
* @summary Close the file handle.
* @description
* Note: Since file handles are so-called expensive ressources it is strongly recommanded to close each file handle you prior created in your scripts as soon as possible.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
* @see [File.File]{@link File#File}
**/
/**
* @memberof File
* @function eof
* @instance
* @summary Report whether the file pointer points to EOF (end of file).
* @returns {boolean} <code>true</code> if EOF, <code>false</code> if not
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof File
* @function error
* @instance
* @summary Retrieve the error message of the last file access error as String.
* @description The error message (as long there is one) and its language depend on the operating system used on the Portal Server's machine. If there is no error, the method returns <code>null</code>.
* @returns {string} String with the content of the last file access error message, <code>null</code> in case of no error
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof File
* @function ok
* @instance
* @summary Report whether an error occurred while accessing the file handle.
* @returns {boolean} <code>true</code> if no error occurred, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof File
* @function read
* @instance
* @summary Retrieve a block of data from the file, containing a maximum of charsNo byte.
* @description After the method has been performed, the data pointer of the file handle is moved right after the block which has been read. This might as well trigger the EOF flag, if the end of file has been reached.
* @param {number} charsNo integer value indicating how many characters (resp. byte in binary mode) should be read
* @returns {string} String containing up to <code>charsNo</code> characters/byte of data of the file.
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof File
* @function readLine
* @instance
* @summary Retrieve one line of data from the file.
* @description This method requires to have the file opened in text mode to work flawlessly, because the end of line is recognized by the linefeed character. After the readLine() method has been performed, the data pointer of the file handle is moved to the beginning of the next line of data.
* @returns {string} String containing one line of data of the file.
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof File
* @function write
* @instance
* @summary Write binary data to the file.
* @description This requires to have the file handle opened with write access (meaning modes <code>r+</code>, <code>w/w+</code>, <code>a/a+</code>) and binary mode <code>b</code>.
* @param {number[]} byteArray Array of integers containing any data you want to write to the file
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0
* @see [File.close]{@link File#close}
* @example
* // Binary-Sample with Byte-Array
* var fso = new File("c:\\tmp\\test.txt", "w+b");
* if (!fso.ok())
* throw fso.error();
* var byteArr = [];
* byteArr.push(72);
* byteArr.push(101);
* byteArr.push(108);
* byteArr.push(108);
* byteArr.push(111);
* byteArr.push(0); // 0-Byte
* byteArr.push(87);
* byteArr.push(111);
* byteArr.push(114);
* byteArr.push(108);
* byteArr.push(100);
* fso.write(byteArr);
* fso.close();
* // result: test.txt: Hello{0-Byte}World
**/
/**
* @memberof File
* @function write
* @instance
* @summary Write data to the file.
* @description This requires to have the file handle opened with write access (meaning modes <code>r+</code>, <code>w/w+</code>, <code>a/a+</code>). You may concatenate as many strings as you want.
* @param {string} a String containing any data you want to write to the file
* @param {string} b String containing any data you want to write to the file
* @param {any[]} ...restParams
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof File
* @function writeBuffer
* @instance
* @summary Write data to the file.
* @description This requires to have the file handle opened with write access (meaning modes <code>r+</code>, <code>w/w+</code>, <code>a/a+</code>).
* @param {string} data String containing any data you want to write to the file.
* @param {number} charsNo integer value indicating how many characters should be written.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @class FileResultset
* @classdesc The FileResultset class supports basic functions to loop through a list of DocFile objects.
* You can manually create a FileResultset as well as access the (selected) files of a (public) Folder.
* @summary Create a new FileResultset object.
* @description Like in other programming languages you create a new object with the <code>new</code> operator (refer to example below).
* Note: Details for the filter expression you find in section Using filter expressions with FileResultSets
* Note: Further samples are in FileResultset filter examples
* @param {string} fileType String containing the technical name of the desired filetype
* @param {string} [filter] String containing an optional filter criterium; use empty String ('') if you don't want to filter at all
* @param {string} [sortOrder] String containing an optional sort order; use empty String ('') if you don't want to sort at all
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var fileType = "Standard";
* var filter = "";
* var sortOrder = "";
* var myFRS = new FileResultset(fileType, filter, sortOrder);
*/
/**
* @memberof FileResultset
* @function first
* @instance
* @summary Retrieve the first DocFile object in the FileResultset.
* @returns {DocFile} DocFile or <code>null</code> in case of an empty FileResultset
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myFRS = new FileResultset("Standard", "", "");
* var myFile = myFRS.first();
**/
/**
* @memberof FileResultset
* @function getIds
* @instance
* @summary Returns an array with all file ids in the FileResultset.
* @returns {string[]} Array of String with file ids of the FileResultset
* @since DOCUMENTS 5.0c
* @example
* var myFRS = new FileResultset("Standard", "", "");
* util.out(myFRS.getIds());
**/
/**
* @memberof FileResultset
* @function last
* @instance
* @summary Retrieve the last DocFile object in the FileResultset.
* @returns {DocFile} DocFile or <code>null</code> if end of FileResultset is reached.
* @since ELC 3.60j / otrisPORTAL 6.0j
**/
/**
* @memberof FileResultset
* @function next
* @instance
* @summary Retrieve the next DocFile object in the FileResultset.
* @returns {DocFile} DocFile or <code>null</code> if end of FileResultset is reached.
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myFRS = new FileResultset("Standard", "", "");
* for (var myFile = myFRS.first(); myFile; myFile = myFRS.next())
* {
* // do something with each DocFile object
* }
**/
/**
* @memberof FileResultset
* @function size
* @instance
* @summary Get the amount of DocFile objects in the FileResultset.
* @returns {number} integer value with the amount of DocFile objects in the FileResultset
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* var myFRS = new FileResultset("Standard", "", "");
* util.out(myFRS.size());
**/
/**
* @interface Folder
* @summary The Folder class has been added to the DOCUMENTS PortalScripting API to gain full access to the DOCUMENTS folders by scripting means.
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
*/
/**
* @memberof Folder
* @summary This property specifies whether the action 'Archive' is available for the folder.
* @member {boolean} allowArchive
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof Folder
* @summary This property specifies whether the action 'Copy to' is available for the folder.
* @member {boolean} allowCopyTo
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof Folder
* @summary This property specifies whether the action 'PDF creation (Print)' is available for the folder.
* @member {boolean} allowCreatePDF
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof Folder
* @summary This property specifies whether the action 'Delete' is available for the folder.
* @member {boolean} allowDelete
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof Folder
* @summary This property specifies whether the action 'Export' is available for the folder.
* @member {boolean} allowExport
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof Folder
* @summary This property specifies whether the action 'Forward' is available for the folder.
* @member {boolean} allowForward
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof Folder
* @summary This property specifies whether the action 'Store in' is available for the folder.
* @member {boolean} allowMoveTo
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof Folder
* @summary The comparator for the first filter of the Folder object.
* @description
* Note: This attribute only exists if the Folder represents a dynamic folder
* @member {string} comparator1
* @instance
**/
/**
* @memberof Folder
* @summary The comparator for the second filter of the Folder object.
* @description
* Note: This attribute only exists if the Folder represents a dynamic folder
* @member {string} comparator2
* @instance
**/
/**
* @memberof Folder
* @summary The comparator for the third filter of the Folder object.
* @description
* Note: This attribute only exists if the Folder represents a dynamic folder
* @member {string} comparator3
* @instance
**/
/**
* @memberof Folder
* @summary The expression of the filter of the folder.
* @description
* Note: This property is only available if the Folder represents a dynamic folder and the filter style 'Extended' is used.
* @member {string} filterExpression
* @instance
* @since DOCUMENTS 4.0c
* @see [UsingfilterexpressionswithFileResultSets]{@link UsingfilterexpressionswithFileResultSets}
**/
/**
* @memberof Folder
* @summary The field to use for the first filter of the Folder object.
* @description
* Note: This attribute only exists if the Folder represents a dynamic folder
* @member {string} filterfieldname1
* @instance
**/
/**
* @memberof Folder
* @summary The field to use for the second filter of the Folder object.
* @description
* Note: This attribute only exists if the Folder represents a dynamic folder
* @member {string} filterfieldname2
* @instance
**/
/**
* @memberof Folder
* @summary The field to use for the third filter of the Folder object.
* @description
* Note: This attribute only exists if the Folder represents a dynamic folder
* @member {string} filterfieldname3
* @instance
**/
/**
* @memberof Folder
* @summary The filter style of the folder.
* @description There are two filter styles available:
* <ul>
* <li><code>Standard</code></li>
* <li><code>Extended</code></li>
* </ul>
*
* @member {string} filterStyle
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof Folder
* @summary The icon to use in the folder tree.
* @member {string} icon
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof Folder
* @summary The internal id of the Folder object.
* @member {string} id
* @instance
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
**/
/**
* @memberof Folder
* @summary This property specifies whether the folder is invisible to the users.
* @description
* Note: This property is not operative if the folder is not released.
* @member {boolean} invisible
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof Folder
* @summary The entire label defined for the Folder object.
* @member {string} label
* @instance
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
* @see [Folder.getLocaleLabel]{@link Folder#getLocaleLabel}
**/
/**
* @memberof Folder
* @summary The technical name of the Folder object.
* @member {string} name
* @instance
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
**/
/**
* @memberof Folder
* @summary This property specifies whether the folder is available to the users.
* @member {boolean} released
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof Folder
* @summary The column used to sort the entries in the folder.
* @description The following sort columns are available:
* <ul>
* <li><code>Title</code></li>
* <li><code>LastModifiedAt</code></li>
* <li><code>LastEditor</code></li>
* <li><code>CreateAt</code></li>
* <li><code>Owner</code></li>
* <li><code>CustomField</code></li>
* </ul>
*
* @member {string} sortColumn
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof Folder
* @summary This property specifies the sort order of the entries in the folder.
* @member {boolean} sortDescending
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof Folder
* @summary The technical name of the custom field used to sort the entries in the folder.
* @description
* Note: This field is only available if the Folder.sortColumn is set to 'CustomField'.
* @member {string} sortFieldName
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof Folder
* @summary Returns the owner of a private folder.
* @description
* Note: If the folder is a private folder (e.g. inbox) this property returns the owning SystemUser
* @member {SystemUser} systemUser
* @instance
* @since DOCUMENTS 5.0d
**/
/**
* @memberof Folder
* @summary The type of the Folder object.
* @member {string} type
* @instance
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
**/
/**
* @memberof Folder
* @summary The desired field value to use for the first filter of the Folder object.
* @description
* Note: This attribute only exists if the Folder represents a dynamic folder
* @member {string} value1
* @instance
**/
/**
* @memberof Folder
* @summary The desired field value to use for the second filter of the Folder object.
* @description
* Note: This attribute only exists if the Folder represents a dynamic folder
* @member {string} value2
* @instance
**/
/**
* @memberof Folder
* @summary The desired field value to use for the third filter of the Folder object.
* @description
* Note: This attribute only exists if the Folder represents a dynamic folder
* @member {string} value3
* @instance
**/
/**
* @memberof Folder
* @function addAccessProfile
* @instance
* @summary Add a folder access right for the user group defined by an access profile to the folder.
* @param {string} accessProfileName The technical name of the access profile.
* @param {boolean} allowInsertFiles Flag indicating whether inserting files into the folder is allowed.
* @param {boolean} allowRemoveFiles Flag indicating whether removing files from the folder is allowed.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var folder = context.createFolder("testFolder", "public");
* var success = folder.addAccessProfile("AccessProfile1", true, false);
* if (!success)
* util.out(folder.getLastError());
**/
/**
* @memberof Folder
* @function addFile
* @instance
* @summary Store a reference to a desired DocFile object in the current Folder.
* @description
* Note: This only works in case the Folder is a real public Folder. The Folder must not represent a dynamic folder, since a dynamic folder is sort of a hardcoded search, not a "real" folder.
* @param {DocFile} docFile DocFile object which shall be available in the given Folder
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51h / otrisPORTAL 5.1h
**/
/**
* @memberof Folder
* @function addFilterEDAServer
* @instance
* @summary Add an EDA server to the filter of the folder.
* @description
* Note: This function is only available for a Folder of type 'dynamicpublic'.
* @param {string} serverName The technical name of the desired EDA server.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var folder = context.createFolder("testFolder", "dynamicpublic");
* var success = folder.addFilterEDAServer("eas1");
* if (!success)
* util.out(folder.getLastError());
**/
/**
* @memberof Folder
* @function addFilterEEiArchive
* @instance
* @summary Add an EE.i archive to the filter of the folder.
* @description
* Note: This function is only available for a Folder of type 'dynamicpublic'.
* @param {string} archiveKey The key of the desired EE.i archive.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var folder = context.createFolder("testFolder", "dynamicpublic");
* var archiveKey = "$(#STANDARD)\\REGTEST@eei1";
* var success = folder.addFilterEEiArchive(archiveKey);
* if (!success)
* util.out(folder.getLastError());
**/
/**
* @memberof Folder
* @function addFilterEExView
* @instance
* @summary Add an EE.x view to the filter of the folder.
* @description
* Note: This function is only available for a Folder of type 'dynamicpublic'.
* @param {string} viewKey The key of the desired EE.x view.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var folder = context.createFolder("testFolder", "dynamicpublic");
* var viewKey = "Unit=Default/Instance=Default/View=REGTEST";
* var success = folder.addFilterEExView(viewKey);
* if (!success)
* util.out(folder.getLastError());
**/
/**
* @memberof Folder
* @function addFilterFileType
* @instance
* @summary Add a file type to the filter of the folder.
* @description
* Note: This function is only available for a Folder of type 'dynamicpublic'.
* @param {string} fileType The technical name of the desired file type.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var folder = context.createFolder("testFolder", "dynamicpublic");
* var success = folder.addFilterFileType("Filetype1");
* if (!success)
* util.out(folder.getLastError());
**/
/**
* @memberof Folder
* @function addSystemUser
* @instance
* @summary Add a folder access right for a system user to the folder.
* @param {string} loginName The login name of the system user.
* @param {boolean} allowInsertFiles Flag indicating whether inserting files into the folder is allowed.
* @param {boolean} allowRemoveFiles Flag indicating whether removing files from the folder is allowed.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var folder = context.createFolder("testFolder", "public");
* var success = folder.addSystemUser("user1", true, false);
* if (!success)
* util.out(folder.getLastError());
**/
/**
* @memberof Folder
* @function addToOutbar
* @instance
* @summary Add the folder to an outbar.
* @param {string} outbarName The technical name of the outbar.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0d HF2
* @example
* var folder = context.createFolder("testFolder", "public");
* var success = folder.addToOutbar("testOutbar");
* if (!success)
* util.out(folder.getLastError());
**/
/**
* @memberof Folder
* @function copyFolder
* @instance
* @summary The current Folder object is duplicated to create a new Folder object.
* @description The new Folder object is placed at the same hierarchical stage as the Folder used as its source object. After the duplication of the Folder you can change all its public attributes, e.g. to modify the filter definition of a dynamic public folder.
* @param {boolean} includeSubFolders boolean whether to duplicate any subfolders contained in the source folder as well
* @param {boolean} copyRights boolean whether to assign the same access privileges as those assigned to the source Folder
* @param {boolean} copyActions boolean whether to duplicate any userdefined actions attached to the source folder as well
* @returns {Folder} Folder object generated by the function call
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
**/
/**
* @memberof Folder
* @function createSubFolder
* @instance
* @summary Create a new subfolder of the specified folder type.
* @description
* Note: There are three possible types available:
* <ul>
* <li><code>public</code></li>
* <li><code>dynamicpublic</code></li>
* <li><code>onlysubfolder</code></li>
* </ul>
*
* @param {string} name The technical name of the subfolder to be created.
* @param {string} type The desired type of the subfolder.
* @returns {Folder} New created subfolder as Folder object or <code>null</code> if failed.
* @since DOCUMENTS 4.0c
* @see [context.createFolder]{@link context#createFolder}
* @example
* var parentFolder = context.createFolder("parentFolder", "public");
* if (parentFolder)
* {
* var subFolder = parentFolder.createSubFolder("subFolder", "dynamicpublic");
* if (subFolder)
* util.out(subFolder.type);
* else
* util.out(parentFolder.getLastError());
* }
**/
/**
* @memberof Folder
* @function deleteFolder
* @instance
* @summary Delete the folder in DOCUMENTS.
* @description
* Note: All subfolders are also deleted recursively.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @see [context.deleteFolder]{@link context#deleteFolder}
* @example
* var folder = context.createFolder("testFolder", "onlysubfolder");
* if (folder)
* {
* var success = folder.deleteFolder();
* if (success)
* {
* var itFolder = context.getFoldersByName("testFolder", "onlysubfolder");
* util.out(itFolder.size() == 0);
* }
* }
**/
/**
* @memberof Folder
* @function getActionByName
* @instance
* @summary Retrieve a user-defined action of the Folder.
* @param {string} actionName String value containing the desired action name.
* @returns {UserAction} UserAction object representing the user-defined action.
* @since DOCUMENTS 4.0d
* @example
* var it = context.getFoldersByName("testFolder");
* var folder = it.first();
* if (folder)
* {
* var action = folder.getActionByName("testAction");
* if (action)
* {
* action.type = "PortalScript";
* action.setPortalScript("testScript");
* }
* else
* util.out(folder.getLastError());
* }
**/
/**
* @memberof Folder
* @function getAttribute
* @instance
* @summary Get the String value of an attribute of the Folder.
* @param {string} attribute String containing the name of the desired attribute
* @returns {string} String containing the value of the desired attribute
* @since ELC 3.51b / otrisPORTAL 5.1b
**/
/**
* @memberof Folder
* @function getFiles
* @instance
* @summary Retrieve a FileResultset of all the DocFile objects stored in the Folder.
* @description
* Note: It does not matter whether the Folder is a real public folder or a dynamic folder.
* @returns {FileResultset} FileResultset containing a list of all DocFile objects stored in the Folder
* @since ELC 3.51b / otrisPORTAL 5.1b
**/
/**
* @memberof Folder
* @function getFilterFileTypes
* @instance
* @summary Retrieve the filter file types of the folder.
* @returns {any[]} Array of strings containing the technical names of the file types.
* @since DOCUMENTS 5.0a HF2
* @example
* var folder = context.createFolder("testFolder", "dynamicpublic");
* var success = folder.addFilterFileType("Filetype1");
* if (!success)
* util.out(folder.getLastError());
*
* var fileTypes = folder.getFilterFileTypes();
* if (fileTypes)
* {
* for (var i=0; i < fileTypes.length; i++)
* {
* util.out(fileTypes[i]);
* }
* }
* else
* util.out(folder.getLastError());
**/
/**
* @memberof Folder
* @function getHitResultset
* @instance
* @summary Create a HitResultset, which summarizes all DocFiles in the folder.
* @description This function executes an empty (=unfiltered) search in the folder. It creates a HitResultset, which summarizes all the Folder's files. The Resultset contains the same columns as the folder's default web view.
* Note: The function operates on dynamic and on static folders, but not on the special folders "tasks" and "resubmision".
* Note: Reading from a lean HitResultset with only a few columns can be faster than reading from a FileResultset. Sometimes this effect outweighs the time-related costs of a search. If the folder addresses an archive, the time needed to create temporary DocFiles can be saved with this function. On a failed search request the function does not throw errors. To detect this kind of errors scripts should read the returned object's properties lastErrorCode and lastError.
* @returns {HitResultset} A HitResultset, which contains column headers and a list of DocHit objects.
* @since DOCUMENTS 5.0c
* @see [getFiles]{@link getFiles}
**/
/**
* @memberof Folder
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof Folder
* @function getLocaleLabel
* @instance
* @summary Get the ergonomic label of the Folder.
* @param {string} locale Optional String value with the locale abbreviation (according to the principal's configuration); if omitted, the current user's portal language is used automatically.
* @returns {string} <code>String</code> containing the ergonomic label of the Folder in the appropriate portal language.
* @since DOCUMENTS 4.0b HF2
**/
/**
* @memberof Folder
* @function getOID
* @instance
* @summary Returns the object-id.
* @description
* Since DOCUMENTS 5.0 (new parameter oidLow)
* @param {boolean} [oidLow] Optional flag:
* If <code>true</code> only the id of the filetype object (<code>m_oid</code>) will be returned.
* If <code>false</code> the id of the filetype object will be returned together with the id of the corresponding class in the form <code>class-id:m_oid</code>.
* The default value is <code>false</code>.
* @returns {string} <code>String</code> with the object-id
* @since ELC 3.60c / otrisPORTAL 6.0c
**/
/**
* @memberof Folder
* @function getPosition
* @instance
* @summary Retrieve the position of a subfolder within the subfolder list.
* @param {Folder} subFolder Folder object whose position to be retrieved.
* @returns {number} The zero-based position of the subfolder as integer or -1 in case of any error.
* @since DOCUMENTS 4.0c
* @see [Folder.setPosition]{@link Folder#setPosition} [context.setFolderPosition]{@link context#setFolderPosition}
* @example
* var parentFolder = context.createFolder("parentFolder", "public");
* if (parentFolder)
* {
* var subFolder1 = parentFolder.createSubFolder("subFolder1", "dynamicpublic");
* var subFolder2 = parentFolder.createSubFolder("subFolder2", "onlysubfolder");
* if (subFolder1 && subFolder2)
* {
* var pos = parentFolder.getPosition(subFolder2);
* util.out(pos == 1);
* }
* }
**/
/**
* @memberof Folder
* @function getSubFolders
* @instance
* @summary Retrieve a FolderIterator containing all Folder objects which represent subfolders of the given Folder.
* @returns {FolderIterator} FolderIterator with all subfolders one hierarchical level below the given Folder
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
**/
/**
* @memberof Folder
* @function hasFiles
* @instance
* @summary Retrieve information whether the Folder is empty or not.
* @returns {boolean} <code>true</code> if DocFile objects available inside the Folder, <code>false</code> in case the Folder is empty
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
**/
/**
* @memberof Folder
* @function removeAccessProfile
* @instance
* @summary Remove all folder access rights of the user group defined by an access profile from the folder.
* @param {string} accessProfileName The technical name of the access profile.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var folder = context.createFolder("testFolder", "public");
* var success = folder.addAccessProfile("AccessProfile1", true, false);
* if (success)
* {
* success = folder.removeAccessProfile("AccessProfile1");
* if (!success)
* util.out(folder.getLastError());
* }
**/
/**
* @memberof Folder
* @function removeFile
* @instance
* @summary Remove the reference to a desired DocFile object out of the current Folder.
* @description
* Note: This only works in case the Folder is a real public Folder. The Folder must not represent a dynamic folder, since a dynamic folder is sort of a hardcoded search, not a "real" folder.
* @param {DocFile} docFile DocFile object which shall be removed from the given Folder
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51h / otrisPORTAL 5.1h
**/
/**
* @memberof Folder
* @function removeFilterEDAServer
* @instance
* @summary Remove an EDA server from the filter of the folder.
* @description
* Note: This function is only available for a Folder of type 'dynamicpublic'.
* @param {string} serverName The technical name of the desired EDA server.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var folder = context.createFolder("testFolder", "dynamicpublic");
* var success = folder.addFilterEDAServer("eas1");
* if (success)
* {
* success = folder.removeFilterEDAServer("eas1");
* if (!success)
* util.out(folder.getLastError());
* }
**/
/**
* @memberof Folder
* @function removeFilterEEiArchive
* @instance
* @summary Remove an EE.i archive from the filter of the folder.
* @description
* Note: This function is only available for a Folder of type 'dynamicpublic'.
* @param {string} archiveKey The key of the desired EE.i archive.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var folder = context.createFolder("testFolder", "dynamicpublic");
* var archiveKey = "$(#STANDARD)\\REGTEST@eei1";
* var success = folder.addFilterEEiArchive(archiveKey);
* if (success)
* {
* success = folder.removeFilterEEiArchive(archiveKey);
* if (!success)
* util.out(folder.getLastError());
* }
**/
/**
* @memberof Folder
* @function removeFilterEExView
* @instance
* @summary Remove an EE.x view from the filter of the folder.
* @description
* Note: This function is only available for a Folder of type 'dynamicpublic'.
* @param {string} viewKey The key of the desired EE.x view.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var folder = context.createFolder("testFolder", "dynamicpublic");
* var viewKey = "Unit=Default/Instance=Default/View=REGTEST";
* var success = folder.addFilterEExView(viewKey);
* if (success)
* {
* success = folder.removeFilterEExView(viewKey);
* if (!success)
* util.out(folder.getLastError());
* }
**/
/**
* @memberof Folder
* @function removeFilterFileType
* @instance
* @summary Remove a file type from the filter of the folder.
* @description
* Note: This function is only available for a Folder of type 'dynamicpublic'.
* @param {string} fileType The technical name of the desired file type.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var folder = context.createFolder("testFolder", "dynamicpublic");
* var success = folder.addFilterFileType("Filetype1");
* if (success)
* {
* success = folder.removeFilterFileType("Filetype1");
* if (!success)
* util.out(folder.getLastError());
* }
**/
/**
* @memberof Folder
* @function removeFromOutbar
* @instance
* @summary Remove the folder from an outbar.
* @param {string} outbarName The technical name of the outbar.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0d HF2
* @example
* var itFolder = context.getFoldersByName("testFolder", "public");
* var folder = itFolder.first();
* if (folder)
* {
* var success = folder.removeFromOutbar("testOutbar");
* if (!success)
* util.out(folder.getLastError());
* }
**/
/**
* @memberof Folder
* @function removeSystemUser
* @instance
* @summary Remove all folder access rights of a system user from the folder.
* @param {string} loginName The login name of the system user.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var folder = context.createFolder("testFolder", "public");
* var success = folder.addSystemUser("user1", true, false);
* if (success)
* {
* success = folder.removeSystemUser("user1");
* if (!success)
* util.out(folder.getLastError());
* }
**/
/**
* @memberof Folder
* @function setAllowedActionScript
* @instance
* @summary Set the script containing the allowed user-defined actions.
* @param {string} scriptName The name of the desired script; use empty string ('') if you want to remove the associated action script.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var folder = context.createFolder("testFolder", "public");
* var success = folder.setAllowedActionScript("testScript");
* if (!success)
* util.out(folder.getLastError());
*
* // We can remove the action script as follows:
* success = folder.setAllowedActionScript('');
**/
/**
* @memberof Folder
* @function setAttribute
* @instance
* @summary Set the String value of an attribute of the Folder to the desired value.
* @param {string} attribute String containing the name of the desired attribute
* @param {string} value String containing the desired value of the attribute
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51b / otrisPORTAL 5.1b
**/
/**
* @memberof Folder
* @function setParentFolder
* @instance
* @summary Set the parent folder of the current folder.
* @param {Folder} parentFolder optional Folder object being the parent folder of the current folder. If no parent folder is defined, the current folder will be moved to the top level.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0c
* @example
* var parentFolder = context.createFolder("parentFolder", "public");
* if (parentFolder)
* {
* var subFolder = context.createFolder("subFolder", "dynamicpublic");
* if (subFolder)
* {
* var success = subFolder.setParentFolder(parentFolder);
* if (!success)
* util.out(subFolder.getLastError());
*
* // We can move subFolder to the top level as follows:
* success = subFolder.setParentFolder();
* }
* }
**/
/**
* @memberof Folder
* @function setPosition
* @instance
* @summary Place a subfolder at the given position in the subfolder list.
* @description
* Note: 0 at the beginning and -1 at the end.
* @param {Folder} subFolder Folder object to be placed at the given position.
* @param {number} position The 0-based position for the subfolder.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @see [Folder.getPosition]{@link Folder#getPosition} [context.setFolderPosition]{@link context#setFolderPosition}
* @example
* var parentFolder = context.createFolder("parentFolder", "public");
* if (parentFolder)
* {
* var subFolder1 = parentFolder.createSubFolder("subFolder1", "dynamicpublic");
* var subFolder2 = parentFolder.createSubFolder("subFolder2", "onlysubfolder");
* if (subFolder1 && subFolder2)
* {
* var pos = parentFolder.getPosition(subFolder2);
* util.out(pos == 1);
* parentFolder.setPosition(subFolder1, -1);
* pos = parentFolder.getPosition(subFolder2);
* util.out(pos == 0);
* }
* }
**/
/**
* @interface FolderIterator
* @summary The FolderIterator class has been added to the DOCUMENTS PortalScripting API to gain full access to the DOCUMENTS folders by scripting means.
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
* @example
* if (context.getFoldersByName(lstName, "public").size() == 0)
* {
* var folderIter = context.getFoldersByName("TemplateFolder", "public");
* if (folderIter && folderIter.size() > 0)
* {
* var source = folderIter.first(); // fetch list folder
* var target = source.copyFolder(true, true, true);
* target.Name = lstName;
* target.Label = docFile.crmName;
* target.Type = "public";
* }
* }
*/
/**
* @memberof FolderIterator
* @function first
* @instance
* @summary Retrieve the first Folder object in the FolderIterator.
* @returns {Folder} Folder or <code>null</code> in case of an empty FolderIterator
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
**/
/**
* @memberof FolderIterator
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof FolderIterator
* @function next
* @instance
* @summary Retrieve the next Folder object in the FolderIterator.
* @returns {Folder} Folder or <code>null</code> if end of FolderIterator is reached.
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
**/
/**
* @memberof FolderIterator
* @function size
* @instance
* @summary Get the amount of Folder objects in the FolderIterator.
* @returns {number} integer value with the amount of Folder objects in the FolderIterator
* @since ELC 3.50l01 / otrisPORTAL 5.0l01
**/
/**
* @class HitResultset
* @classdesc The HitResultset class allows comprehensive search operations in Documents and in connected archives.
* While the constructor of this class launches a search operation, the created object stores the results and exposes them as a list of DocHit objects. Compared with the classes <code>FileResultset</code> and <code>ArchiveFileResultset</code> this class has got the following characteristics.
* <ul>
* <li>Several filetypes and archives can be searched at one time.</li>
* <li>Extracting archive hits from a HitResultSet does not make DOCUMENTS create a temporary DocFile for each hit. This can save a lot of time.</li>
* <li>Objects of this class may allocate large amounts of memory, because they sustain a complete hit list instead of a lean id-list. To save memory, scripts should prefer hit lists with as few columns as possible.</li>
* </ul>
*
*
* @since DOCUMENTS 4.0b
* @example
* var searchResources = "Filetype1 Filetype2";
* var filter = "";
* var sortOrder = "";
* var myFile;
* var myHRS = new HitResultset(searchResources, filter, sortOrder);
* for (var myHit = myHRS.first(); myHit; myHit = myHRS.next())
* {
* myFile = myHit.getFile();
* if (myFile)
* util.out(myFile.getAutoText("id"));
* else
* util.out(myHit.getLastError());
* }
* @example
* var searchResources = ["$(#STANDARD)\\REGTEST@myeei", "Filetype1@myeas", "Filetype1"];
* var filter = "";
* var sortOrder = "";
* var hitlist = "MYHITLIST";
* var pageSize = 3;
* var pos = 6;
* var unlimitedHits = true;
* var fullColumnLength = true;
* var myHRS = new HitResultset(searchResources, filter, sortOrder, hitlist, pageSize, unlimitedHits, fullColumnLength);
* if (myHRS.size() > pos)
* {
* while (pos >= myHRS.fetchedSize())
* myHRS.fetchNextPage();
* var myHit = myHRS.getAt(pos);
* if (myHit)
* {
* if (myHit.isArchiveHit())
* util.out(myHit.getArchiveKey());
* else
* util.out(myHit.getFileId());
* }
* }
* @example
* var searchResources = "Unit=Default/Instance=Default/View=REGTEST@myeex";
* var filter = "";
* var sortOrder = "myField+";
* var hitlist = "myHitlist";
* var pageSize = 10;
* var myFile;
* var myHRS = new HitResultset(searchResources, filter, sortOrder, hitlist, pageSize);
* // Iterate only the hit entries on the first page.
* for (var myHit = myHRS.first(); myHit; myHit = myHRS.next())
* {
* myFile = myHit.getArchiveFile();
* if (myFile)
* util.out(myFile.getAttribute("Key"));
* else
* util.out(myHit.getLastError());
* }
* @summary Perform a search and create a new HitResultset object.
* @description
* Note: On a failed search request the constructor does not throw errors. To detect this kind of errors scripts should read the object's properties lastErrorCode and lastError.<b>Resource identifiers: </b>
* A "resource identifier" can be one of the following: [ examples in brackets ]
* <ul>
* <li>a filetype name [ ftOrder ]</li>
* <li>a filetype name for use with an EDA store [ ftOrder@peachitStore1 ]</li>
* <li>a filetype name for use with all EDA stores [ ftOrder@ALLEAS ]</li>
* <li>a EE.x view key [ Unit=Default/Instance=Default/View=Orders@MyEEX ]</li>
* <li>a EE.i archive key [ $(#STANDARD)\ORDERS@STDARC_360 ]</li>
* </ul>
*
* Archive resource identifiers should always get a "@Servername" appendix, though Documents recognizes EE.x and EE.i resources of the primary archive server without that appendix.
* <b>Resource ordering and hitlist specification</b>
* The resource, which owns a specified hitlist, has to be passed in the first position of the list. Search requests in EE.i/EE.x-archives do not work with a filetype's hitlist. These archives require a hitlist of their own. For this reason, a list of resources of different types must be ordered in the following way: EE.x before EE.i before anything else. Requests, which involve more than one Easy Enterprise server can work only, if a hitlist of the given name exists in each resource of these servers.
* <b>Automatic hitlist selection</b>
* If the parameter "hitlist" is an empty string, Documents scans the search resources for a named hitlist. If no named hitlist exists, Documents initializes an old-fashioned anonymous hitlist, which is based on the "Display in hit list" option of fields in the Documents Manager and on corresponding options for particular DocFile attributes (title, created, owner, last modified, last editor). An anonymous hitlist does actually not work with EE.x. It partially works with EE.i. In this case, Documents externally uses the setting "CommonDefaultHitlist" of the configuration file "ArchiveXML.ini" and transfers matching columns into the internal hitlist. As long as named hitlists become imported with the archive structure, it does not matter.
* Search requests, which involve more than one Easy Enterprise server cannot rely on the automatic selection feature. Scripts should always pass an appropriate hitlist name for these requests.
*
* Since DOCUMENTS 4.0b
* Since DOCUMENTS 4.0d HF1 new parameter fullColumnLength
* Since DOCUMENTS 5.0 (New option for hitlist parameter: an array of field names instead of a hitlist name)
* @param {any} searchResources The list of resources to search through. The resource identifiers may be passed either as an array of strings or as an ordinary string with one identifier per line of text. Please read the remarks section about restrictions.
* @param {string} filter A filter expression. Pass an empty string, if no filter ist required.
* @param {string} sortOrder A sort expression. Pass an empty string, if no sorting is required.
* @param {any} hitlist The technical name of a hitlist or an array of field names, which specifies the available columns in the resultset. If the parameter is left empty, Documents tries to choose a hitlist automatically. Details follow in the remarks section.
* <b>Note:</b> If this parameter is an array of field names, a search in EE.i or EE.x is not allowed and the field names must not contain commas (,).
* @param {number} [pageSize] This is a memory-saving and performance-tuning option. If the parameter is zero, Documents will load all available hits at once. If the parameter is a positive value, Documents will initially load only the requested number of hits as a first page. In order to access each further page, a call to fetchNextPage() is necessary. A negative pageSize value will be replaced by the current user's "hits per page" preference setting.
* @param {boolean} [unlimitedHits] A boolean that indicates, if the general hit limitations on filetypes and archives must be ignored. A wasteful use of this option may cause issues with the system performance or situations with low free memory.
* @param {boolean} [fullColumnLength] A boolean that indicates, if the general hit column length limitations must be ignored. The default column length is 50 characters (if not a different value is defined by the property Documents-Settings: MaxHitfieldLength). If a field value exeeds this size, the first 50 characters will be displayed followed by '...'. If the parameter fullColumnLength is set to <code>true</code>, no truncation will be done.
* @param {boolean} [withBlobInfo] A boolean that indicates, if the HitResultset should contain blob-information that can be fetched with DocHit.getBlobInfo()
* @see [UsingfilterexpressionswithFileResultSets,Filterexamples]{@link UsingfilterexpressionswithFileResultSets,Filterexamples}
*/
/**
* @memberof HitResultset
* @function dispose
* @instance
* @summary Free most of the memory of the HitResultset.
* @description This function explicitly frees the memory used by the object. The Resultset itself becomes empty. All extracted DocHit objects become invalid and must no longer be used. Long-running scripts should use this function instead of waiting for the garbage collector to clean up.
* @returns {any} The function does not return a value.
* @since DOCUMENTS 4.0b
**/
/**
* @memberof HitResultset
* @function fetchedSize
* @instance
* @summary Get the number of already loaded hits in the set.
* @description
* Note: If the object has been created with a non-zero page size, this value is often smaller than the total amount of hits.
* @returns {number} integer value with the number of hits, which can actually be read from the resultset.
* @since DOCUMENTS 4.0b
* @see [size]{@link size}
**/
/**
* @memberof HitResultset
* @function fetchNextPage
* @instance
* @summary Load the next page of hits into the Resultset.
* @description If the object has been created with a non-zero page size, each call of this function appends another page of hits to the resultset until all hits are loaded.
* @returns {boolean} The value indicates, if any more hits have been loaded.
* @since DOCUMENTS 4.0b
**/
/**
* @memberof HitResultset
* @function first
* @instance
* @summary Retrieve the first DocHit in the HitResultset.
* @returns {DocHit} DocHit object, <code>null</code> in case of an empty HitResultset
* @since DOCUMENTS 4.0b
* @see [next]{@link next}
**/
/**
* @memberof HitResultset
* @function getAt
* @instance
* @summary Retrieve the DocHit object at a given position in the HitResultset.
* @description
* Note: Valid positions range from 0 to fetchedSize()-1.
* @param {number} pos Integer position of the hit, beginning with 0
* @returns {DocHit} DocHit object or <code>null</code> if the position is out of bounds.
* @since DOCUMENTS 4.0b
**/
/**
* @memberof HitResultset
* @function getColumnCount
* @instance
* @summary Get the number of available columns in the set of hits.
* @returns {number} The number of columns as an Integer.
* @since DOCUMENTS 4.0b
**/
/**
* @memberof HitResultset
* @function getColumnIndex
* @instance
* @summary Find the index of a column with a defined name.
* @description
* Note: The function tests for a technical column name prior to a localized name.
* @param {string} colName The name of the column.
* @returns {number} The zero-based index of the column or a -1, which indicates an unknown column name.
* @since DOCUMENTS 4.0b
**/
/**
* @memberof HitResultset
* @function getColumnNames
* @instance
* @summary List the names of all columns in the set of hits.
* @description
* Note: If the resultset is bases on an EE.i hitlist, the function usually returns field numbers instead of technical names, because column descriptions of an EE.i hitlist only consist of the field number and a label. The label would not be a reliable identifier of the column.
* Columns, which correspond to a DocFile attribute may be given a special constant name instead of the name in an archive's scheme. "TITLE" on EE.x and "110" on EE.i may be presented as "DlcFile_Title", for example.
* @param {boolean} [local] A boolean option to read the localized names instead of the technical names.
* @returns {any[]} Array of strings with the column names.
* @since DOCUMENTS 4.0b
**/
/**
* @memberof HitResultset
* @function getHitIds
* @instance
* @summary Returns an array with all Hit-Ids (file ids or archive file keys) of the HitResultset.
* @param {boolean} [withServer] optional boolean value to indicate, if the archive file keys should include an "@archiveServerName" appendix.
* @returns {string[]} Array of String with file ids and archive file keys of the HitResultset.
* @since DOCUMENTS 5.0d
* @see [FileResultset.getIds]{@link FileResultset#getIds}
* @example
* var searchResources = ["Filetype1@myeas", "Filetype1"];
* var myHRS = new HitResultset(searchResources, "", "");
* util.out(myHRS.getHitIds());
**/
/**
* @memberof HitResultset
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since DOCUMENTS 4.0b
* @see [getLastErrorCode]{@link getLastErrorCode}
**/
/**
* @memberof HitResultset
* @function getLastErrorCode
* @instance
* @summary Function to get a numeric code of the last error, that occurred.
* @description
* Note: The value 0 means "no error". Positive values indicate warnings or minor errors, while negative values indicate serious errors. After a serious error no hits should be processed. After a minor error, the resultset may be unsorted or truncated, but the contained data is still valid.
* @returns {number} Integer error code.
* @since DOCUMENTS 4.0b
* @see [getLastError]{@link getLastError}
**/
/**
* @memberof HitResultset
* @function next
* @instance
* @summary Retrieve the next DocHit in the HitResultset.
* @description
* Note: Calls of getAt() do not affect the internal cursor of next().
* @returns {DocHit} DocHit object, <code>null</code> if either the end of the resultset or the end of the loaded pages is reached.
* @since DOCUMENTS 4.0b
* @see [first]{@link first}
**/
/**
* @memberof HitResultset
* @function size
* @instance
* @summary Get the total amount of hits in the set.
* @description
* Note: If the object has been created with a non-zero page size, this value is often greater than the amount of already accessible hits.
* @returns {number} integer value with the total amount of hits. The value -1 may be returned to indicate, that the search continues in the background, and the final number is not yet known.
* @since DOCUMENTS 4.0b
* @see [fetchedSize]{@link fetchedSize}
**/
/**
* @interface PropertyCache
* @summary The PropertyCache class is a util class that allows it to store / cache data over the end of the run time of a script.
* @description There is exactly one global implicit object of the class <code>PropertyCache</code> which is named <code>propCache</code>. At the SystemUser and the AccessProfile are also PropertyCache objects (<code>SystemUser.propCache, AccessProfile.propCache</code>).
* <ul>
* <li>You can define named members (properties) at this object to store the data: <code>propCache.Name1 = one_value;</code><code>propCache.Name2 = another_value;</code></li>
* <li>The stored data can be integer, boolean, string or array values </li>
* <li>There is no limit (except the memory of the OS) in the amount of properties or in the length of an array </li>
* <li>Every principal has it's own propCache object </li>
* </ul>
*
* Note: It is not possible to create objects of the class PropertyCache, since the propCache object is always available.
* @example
* // If you have an enumeration field at a filetype and the enumeration
* // values (enumval) are defined by a PortalScript, then every time a
* // file of that filetype will be displayed, the PortalScript has to be
* // excecuted. If now in the PortalScript the enum values are the result
* // of a query on a filetype or an external DB (DBResultset), then this
* // is a very "expensive" resource. It is recommanded to cache this data.
*
* if (!propCache.hasProperty("Contacts"))
* {
* util.out("Creating cache");
* propCache.Contacts = getEmployees();
* }
*
* util.out("Using cache");
*
* // copy values to enumval "manually" - concat etc. not possible
* // with the global object enumval
* copyArray(propCache.Contacts, enumval);
*
* return;
*
* function getEmployees()
* {
* var myList = new Array();
* var sort = "hrLastName+,hrFirstName+";
* var it = new FileResultset("ftEmployee", "", sort);
* for (var empl=it.first(); empl; empl=it.next())
* myList.push(empl.hrLastName + ", " + empl.hrFirstName);
*
* return myList;
* }
*
* function copyArray(srcList, trgList)
* {
* for (var cnt=0; cnt<srcList.length; cnt++)
* trgList.push(srcList[cnt]);
* }
*/
/**
* @memberof PropertyCache
* @function hasProperty
* @instance
* @summary Function to check if a named property exists in the PropertyCache.
* @param {string} name
* @returns {boolean} <code>true</code> if the property exists, <code>false</code> if not
* @since DOCUMENTS 4.0
**/
/**
* @memberof PropertyCache
* @function listProperties
* @instance
* @summary Function to list all properties in the PropertyCache.
* @returns {string[]} Array with the names of the properties in the PropertyCache.
* @since DOCUMENTS 5.0c
**/
/**
* @memberof PropertyCache
* @function removeProperty
* @instance
* @summary Function to delete a named property exists in the PropertyCache.
* @param {string} name
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0
**/
/**
* @interface Register
* @summary The Register class has been added to the DOCUMENTS PortalScripting API to gain full access to the registers of a DOCUMENTS file by scripting means.
* @since ELC 3.50n / otrisPORTAL 5.0n
*/
/**
* @memberof Register
* @summary The ergonomic label of the Register object.
* @description
* Note: This property is readonly and cannot be overwritten.
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @member {string} label
* @instance
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @memberof Register
* @summary The technical name of the Register object.
* @description
* Note: This property is readonly and cannot be overwritten.
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @member {string} name
* @instance
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @memberof Register
* @summary The type of the Register object.
* @description The possible values of the type attribute are listed below:
* <ul>
* <li><code>documents</code></li>
* <li><code>fields</code></li>
* <li><code>links</code></li>
* <li><code>archiveddocuments</code></li>
* <li><code>externalcall</code></li>
* </ul>
*
* Note: This property is readonly and cannot be overwritten.
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @member {string} type
* @instance
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @memberof Register
* @function addFileLink
* @instance
* @summary Adds a file to a file link register.
* @param {DocFile} file
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 5.0d
* @example
* var file = context.file;
* var linkFile = context.createFile("Filetype1");
* var reg = file.getRegisterByName("flReg");
* if (!reg.addFileLink(linkFile))
* util.out(reg.getLastError());
**/
/**
* @memberof Register
* @function deleteDocument
* @instance
* @summary Delete a Document at the Register.
* @description With the necessary access rights the user can delete a Document at the Register.
* @param {Document} doc Document to delete
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.60d / otrisPORTAL 6.0d
* @example
* // deleting all documents at a register
* var docFile = context.file;
* var reg = docFile.getRegisterByName("Documents");
* if (reg)
* {
* var docs = reg.getDocuments();
* for (var doc = docs.first(); doc; doc = docs.next())
* reg.deleteDocument(doc);
* }
**/
/**
* @memberof Register
* @function getAttribute
* @instance
* @summary Get the String value of an attribute of the Register.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {string} attribute String containing the name of the desired attribute
* @returns {string} String containing the value of the desired attribute
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @memberof Register
* @function getDocuments
* @instance
* @summary Retrieve a list of all Documents stored on the given Register.
* @description This method is available for documents registers only. You cannot use it with different types of Register objects.
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @returns {DocumentIterator} DocumentIterator containing the Document objects stored on the Register
* @since ELC 3.50n / otrisPORTAL 5.0n
* @example
* var docFile = context.file;
* var reg = docFile.getRegisterByName("Documents");
* var docIter = reg.getDocuments();
* for (var doc = docIter.first(); doc; doc = docIter.next())
* {
* util.out(doc.Fullname);
* }
**/
/**
* @memberof Register
* @function getFile
* @instance
* @summary Returns the DocFile the Register belongs to.
* @returns {DocFile} DocFile object or <code>null</code> if missing
* @since DOCUMENTS 5.0c HF1
* @example
* var file = context.file;
* var reg = file.getRegisterByName("RegisterA");
* var alwaysTrue = reg.getFile().getid() == file.getid();
**/
/**
* @memberof Register
* @function getFiles
* @instance
* @summary Retrieve a FileResultset of all DocFile objects linked to the register.
* @returns {FileResultset} FileResultset containing a list of all DocFile objects linked to the register.
* @since DOCUMENTS 4.0b
* @example
* var docFile = context.file;
* var reg = docFile.getRegisterByName("LinksReg");
* if (reg)
* {
* var myFRS = reg.getFiles();
* for (var file = myFRS.first(); file; file = myFRS.next())
* util.out(file.getAutoText("title"));
* }
**/
/**
* @memberof Register
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @returns {string} Text of the last error as String
* @since ELC 3.50n / otrisPORTAL 5.0n
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof Register
* @function getOID
* @instance
* @summary Returns the object-id.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* Since DOCUMENTS 5.0 (new parameter oidLow)
* @param {boolean} [oidLow] Optional flag:
* If <code>true</code> only the id of the filetype object (<code>m_oid</code>) will be returned.
* If <code>false</code> the id of the filetype object will be returned together with the id of the corresponding class in the form <code>class-id:m_oid</code>.
* The default value is <code>false</code>.
* @returns {string} <code>String</code> with the object-id
* @since ELC 3.60c / otrisPORTAL 6.0c
**/
/**
* @memberof Register
* @function removeFileLink
* @instance
* @summary Removes a file from a file link register.
* @param {DocFile} file
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 5.0d
* @example
* var file = context.file;
* var reg = file.getRegisterByName("flReg");
* var frs = reg.getFiles();
* for (var linkFile = frs.first(); linkFile; linkFile = frs.next())
* {
* if (!reg.removeFileLink(linkFile))
* util.out(reg.getLastError());
* }
**/
/**
* @memberof Register
* @function setAttribute
* @instance
* @summary Set the String value of an attribute of the Register to the desired value.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {string} attribute String containing the name of the desired attribute
* @param {string} value String containing the desired value of the attribute
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @memberof Register
* @function uploadDocument
* @instance
* @summary Upload a new Document stored on the server's filesystem to the Register.
* @description The filePath parameter must contain not only the directory path but the filename as well. Otherwise the server will take the first file to be found in the given filePath. The registerFileName parameter has the purpose to allow to rename the Document already while uploading it.
* Note: After successful upload of the Document the source file on the server's directory structure is removed!
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @param {string} filePath String containing the filePath and filename of the desired file to be uploaded. Note: Backslashes contained in the filepath must be quoted with a leading backslash, since the backslash is a special char in ECMAScript!
* @param {string} registerFileName String containing the desired target filename of the Document on the Register
* @returns {Document} <code>Document</code> if successful, <code>null</code> in case of any error
* @since ELC 3.50n / otrisPORTAL 5.0n
* @example
* var docFile = context.file;
* var reg = docFile.getRegisterByName("Documents");
* var newDoc = reg.uploadDocument("c:\\tmp\\sourcefile.rtf", "Filename_on_Register.rtf");
* if (!newDoc)
* util.out("Error while uploading the file! " + reg.getLastError());
* else
* util.out(newDoc.Name);
**/
/**
* @interface RegisterIterator
* @summary The RegisterIterator class has been added to the DOCUMENTS PortalScripting API to gain full access to the registers of a DOCUMENTS file by scripting means.
* @description Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @since ELC 3.50n / otrisPORTAL 5.0n
* @example
* var docFile = context.file;
* if (docFile)
* {
* var docregs = docFile.getRegisters("documents");
* if (docregs && docregs.size() > 0)
* {
* for (var d = docregs.first(); d; d = docregs.next())
* {
* util.out(d.Name + ", " + d.Label);
* }
* }
* }
*/
/**
* @memberof RegisterIterator
* @function first
* @instance
* @summary Retrieve the first Register object in the RegisterIterator.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @returns {Register} Register or <code>null</code> in case of an empty RegisterIterator
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @memberof RegisterIterator
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @returns {string} Text of the last error as String
* @since ELC 3.50n / otrisPORTAL 5.0n
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof RegisterIterator
* @function next
* @instance
* @summary Retrieve the next Register object in the RegisterIterator.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @returns {Register} Register or <code>null</code> if end of RegisterIterator is reached.
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @memberof RegisterIterator
* @function size
* @instance
* @summary Get the amount of Register objects in the RegisterIterator.
* @description
* Since ELC 3.60i / otrisPORTAL 6.0i available for archive files
* @returns {number} integer value with the amount of Register objects in the RegisterIterator
* @since ELC 3.50n / otrisPORTAL 5.0n
**/
/**
* @interface RetrievalField
* @summary This class represents one search field or one conditon within a DOCUMENTS search request.
* @since DOCUMENTS 4.0c HF2
* @see [DocQueryParams]{@link DocQueryParams}
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "String" (single line)
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_STRING
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "Text" (multiple lines)
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_TEXT
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "boolean".
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_BOOL
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "Date".
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_DATE
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "Enumeration" (not extensible)
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_ENUM
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "Numeric".
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_NUMERIC
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "File reference".
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_REFERENCE
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "History".
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_HISTORY
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "Double select list".
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_DOUBLE_LIST
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "Checkbox".
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_CHECKBOX
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "Horizontal seperator" (actually ignored by the retrieval system)
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_SEPARATOR
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "User defeined".
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_USER_DEFINED
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "Text (fixed font)".
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_TEXT_FIXED_FONT
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "E-mail address".
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_E_MAIL
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "URL".
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_URL
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "Time stamp".
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_TIMESTAMP
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "Filing plan".
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_FILING_PLAN
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "HTML".
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_HTML
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Reserved constant for a possible future use.
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_FILING_STRUCTURE
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for the field type "Gadget" (actually ignored by the retrieval system)
* @description
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_GADGET
* @readonly
*/
/**
* @memberof RetrievalField
* @summary Integer code for fields with an unspecified data type.
* @description This constant has been added for completeness. Fields in this state should never appear in the retrieval system.
* <br> This constant is member of constant group: Field Types<br>
* These constants are equally available in each instance of RetrievalField and in the constructor object.
* @instance
* @member {number} FT_UNDEFINED
* @readonly
*/
/**
* @memberof RetrievalField
* @summary The comparison operator / relational operator as a String.
* @description For a list of valid operators see the page: Using filter expressions with FileResultSets.
* Note: The access to this property is restricted. Only the "OnSearchScript" can effectively modify it. Modifying the operator is risky, since it can produce unexpected results from the user's point of view.
* @member {string} compOp
* @instance
* @since DOCUMENTS 4.0c HF2
**/
/**
* @memberof RetrievalField
* @summary The actual default value of the field (read-only).
* @description
* Note: Actually only the "FillSearchMask" exit can attach default values (see setDefault()). There might exist another method in a future version. To improve upward compatibility a "FillSearchMask" script may check for external default values, and leave them unmodified.
* @member {string} defaultValue
* @instance
* @since DOCUMENTS 4.0d
**/
/**
* @memberof RetrievalField
* @summary The UI write protection state of the defautValue (read-only)
* @member {boolean} defValWriteProt
* @instance
* @since DOCUMENTS 4.0d
* @see [setDefault]{@link setDefault}
**/
/**
* @memberof RetrievalField
* @summary The localized label of the field. Maybe an empty String.
* @description
* Note: If the field has not got a label, DOCUMENTS falls back to the technical name. So there is no need to specify a label always. A few reserved internal fields, which are usualli never displayed on a search mask or a hit list, also come along without any label. An example is the special field "Search_EEIFileNr", which DOCUMENTS uses internally to implement a version listing for an ENTERPRISE.i file.
* @member {string} label
* @instance
* @since DOCUMENTS 4.0c HF2
**/
/**
* @memberof RetrievalField
* @summary The name of the look-up field (read-only).
* @member {string} name
* @instance
* @since DOCUMENTS 4.0c HF2
**/
/**
* @memberof RetrievalField
* @summary The field type coded as an integer (read-only).
* @description See the enumeration constants in this class.
* @member {number} type
* @instance
* @since DOCUMENTS 4.0c HF2
**/
/**
* @memberof RetrievalField
* @summary The value sought after. If the operator is "~", it can be a composed value expression.
* @description
* Note: The access to this property is restricted. Only the "OnSearchScript" can effectively modify it. Modifying the value is risky, because it can produce unexpected results from the user's point of view. Within a "FillSearchMask" exit this property contains always an empty string.
* @member {string} valueExpr
* @instance
* @since DOCUMENTS 4.0c HF2
**/
/**
* @memberof RetrievalField
* @function setDefault
* @instance
* @summary Place a default value in a search field.
* @description A "FillSearchMask" script-exit can call this function to place default values in an extended search formular. Calls from other scripts will rather deposit a "LastError" message in the superior DocQueryParams object.
* Note: The DocumentsServer only forwards these parameters to the client application. If a special client implementation will ignore them, the server would not enforce the defaults, because such a behaviour would confuse users.
*
* Calling this function does not modify the "empty" state in terms of DocQueryParams.getSearchField().
* @param {string} value The initial text in the search field. Dates and numbers must be formatted with the current user's locale settings.
* @param {boolean} writeProtect Indicates, if the user interface shall write-protect the field.
* @returns {any} No return value.
* @since DOCUMENTS 4.0d
**/
/**
* @interface RetrievalSource
* @summary This class describes a searchable resource in the DOCUMENTS retrieval system.
* @since DOCUMENTS 4.0c HF2
*/
/**
* @memberof RetrievalSource
* @summary Integer code of the source type "DOCUMENTS file type".
* @description
* <br> This constant is member of constant group: Searchable Resource<br>
* These constants are equally available in each instance of RetrievalSource and in the constructor object. Resource macroes can only occur in the "FillSearchMask" exit. Within an "OnSearch" exit they have already been replaced by their single components.
* @instance
* @member {number} ST_DLC_FILETYPE
* @readonly
*/
/**
* @memberof RetrievalSource
* @summary Integer code of the source type "EASY ENTERPRISE.i archive".
* @description
* <br> This constant is member of constant group: Searchable Resource<br>
* These constants are equally available in each instance of RetrievalSource and in the constructor object. Resource macroes can only occur in the "FillSearchMask" exit. Within an "OnSearch" exit they have already been replaced by their single components.
* @instance
* @member {number} ST_EEI_ARCHIVE
* @readonly
*/
/**
* @memberof RetrievalSource
* @summary Integer code of the source type "EASY ENTERPRISE.x view".
* @description
* <br> This constant is member of constant group: Searchable Resource<br>
* These constants are equally available in each instance of RetrievalSource and in the constructor object. Resource macroes can only occur in the "FillSearchMask" exit. Within an "OnSearch" exit they have already been replaced by their single components.
* @instance
* @member {number} ST_EEX_VIEW
* @readonly
*/
/**
* @memberof RetrievalSource
* @summary Integer code of the source type "EASY ENTERPRISE.x user specific view".
* @description
* <br> This constant is member of constant group: Searchable Resource<br>
* These constants are equally available in each instance of RetrievalSource and in the constructor object. Resource macroes can only occur in the "FillSearchMask" exit. Within an "OnSearch" exit they have already been replaced by their single components.
* @instance
* @member {number} ST_EEX_USERVIEW
* @readonly
*/
/**
* @memberof RetrievalSource
* @summary Integer code of the source type "DOCUMENTS file type within an EAS/EDA store".
* @description
* <br> This constant is member of constant group: Searchable Resource<br>
* These constants are equally available in each instance of RetrievalSource and in the constructor object. Resource macroes can only occur in the "FillSearchMask" exit. Within an "OnSearch" exit they have already been replaced by their single components.
* @instance
* @member {number} ST_EAS_FILETYPE
* @readonly
*/
/**
* @memberof RetrievalSource
* @summary Integer code of the macro source type "EAS server" (Apply selected file types also to the identified EDA-store)
* @description
* <br> This constant is member of constant group: Searchable Resource<br>
* These constants are equally available in each instance of RetrievalSource and in the constructor object. Resource macroes can only occur in the "FillSearchMask" exit. Within an "OnSearch" exit they have already been replaced by their single components.
* @instance
* @member {number} MST_EAS_SERVER
* @readonly
*/
/**
* @memberof RetrievalSource
* @summary Integer code of the macro source type "EAS only" (Remove standard file type sources after MST_EAS_SERVER macro expansion)
* @description
* Note: A "FillSearchMask" script can usually find a source of this type, when the user has deselected the "actual processes" checkbox. This source has not got any parameters. If there are user accounts in the system, for which the checkbox does not show up, the script code should not interpret this source type at all.
* <br> This constant is member of constant group: Searchable Resource<br>
* These constants are equally available in each instance of RetrievalSource and in the constructor object. Resource macroes can only occur in the "FillSearchMask" exit. Within an "OnSearch" exit they have already been replaced by their single components.
* @instance
* @member {number} MST_EAS_ONLY
* @readonly
*/
/**
* @memberof RetrievalSource
* @summary A identifier of the resource.
* @description For conventional file type resources the identifier equals the technical name of the file type. Archive related identifiers consist of a software dependent key or name plus an "@serverName" appendix.
* Note: Modifications of this property won't be forwarded to the retrieval system.
* @member {string} resId
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof RetrievalSource
* @summary For archive resources: the technical name of the archive server. Otherwise empty.
* @description
* Note: Modifications of this property won't be forwarded to the retrieval system.
* @member {string} server
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof RetrievalSource
* @summary The resource type encoded as an integer. See the enumeration constants in this class.
* @description
* Note: Modifications of this property won't be forwarded to the retrieval system.
* @member {number} type
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @class ScriptCall
* @classdesc This class allows asynchronous calling a script from another script.
* You should deliberate whether a script call can be waitable or not. Only waitable script calls can be managed e.g. waiting for a script call to finish or checking whether a call is still running.
* @since DOCUMENTS 4.0d
* @summary Create a new ScriptCall object.
* @description The following properties of the execution context of the called script are carried over from the execution context of the script where this ScriptCall object is created:
* <ul>
* <li>file </li>
* <li>register </li>
* <li>document </li>
* <li>event </li>
* </ul>
*
* You can change these context properties with the available set-methods.
* Since DOCUMENTS 4.0d
* @param {any} systemUser The system user who triggers execution of the called script and can be specified as follows:
* <ul>
* <li>String containing the login name of the system user. </li>
* <li>SystemUser object representing the system user. </li>
* </ul>
*
* @param {string} scriptName String with the name of the called script.
* @param {boolean} waitable boolean flag indicating whether this script call is waitable.
*/
/**
* @memberof ScriptCall
* @function addParameter
* @instance
* @summary Add a parameter to the called script.
* @param {string} name String value containing the parameter name.
* @param {string} value String value containing the parameter value.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 5.0
* @example
* var call = new ScriptCall("schreiber", "testScript", false);
* call.addParameter("testParam", "testValue");
**/
/**
* @memberof ScriptCall
* @function getLastError
* @instance
* @summary Get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @example
* var call = new ScriptCall("schreiber", "testScript", true);
* if (!call.launch())
* util.out(call.getLastError());
**/
/**
* @memberof ScriptCall
* @function getReturnValue
* @instance
* @summary Get the return value of the called script.
* @description
* Note: This function is only available for a waitable ScriptCall.
* @returns {string} The return value as String if the waitable ScriptCall was successfully completed, otherwise the string "Undefined".
* @since DOCUMENTS 5.0
* @example
* var call = new ScriptCall("schreiber", "testScript", true);
* if (call.launch())
* {
* if (call.waitForFinish())
* util.out(call.getReturnValue());
* }
**/
/**
* @memberof ScriptCall
* @function isRunning
* @instance
* @summary Check whether the script call is running.
* @description
* Note: This function is only available for a waitable script call.
* @returns {boolean} <code>true</code> if the script call is running, otherwise <code>false</code>
* @since DOCUMENTS 4.0d
* @example
* var call = new ScriptCall("schreiber", "testScript", true);
* if (call.launch())
* {
* if (call.isRunning())
* {
* // do something
* }
* }
**/
/**
* @memberof ScriptCall
* @function launch
* @instance
* @summary Launch the script call.
* @description In case of successful launch the script will be executed in an own context.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @example
* var call = new ScriptCall("schreiber", "testScript", true);
* if (!call.launch())
* util.out(call.getLastError());
**/
/**
* @memberof ScriptCall
* @function setDocFile
* @instance
* @summary Set the execution context file of the called script.
* @param {DocFile} docFile DocFile object representing the desired execution context file.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @see [context.file]{@link context#file}
* @example
* var user = context.findSystemUser("schreiber");
* var call = new ScriptCall(user, "testScript", true);
* var file = context.getFileById("peachit_fi20120000000016");
* if (file)
* call.setDocFile(file);
**/
/**
* @memberof ScriptCall
* @function setDocument
* @instance
* @summary Set the execution context document of the called script.
* @param {Document} doc Document object representing the desired execution context document.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @see [context.document]{@link context#document}
* @example
* var call = new ScriptCall("schreiber", "testScript", false);
* var file = context.getFileById("peachit_fi20120000000016");
* if (file)
* {
* var reg = file.getRegisterByName("Doc1");
* if (reg)
* {
* var it = reg.getDocuments();
* if (it.size() > 0)
* call.setDocument(it.first());
* }
* }
**/
/**
* @memberof ScriptCall
* @function setEvent
* @instance
* @summary Set the execution context event of the called script.
* @param {string} scriptEvent String value containing the desired script event of the execution context.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @see [context.event]{@link context#event}
* @example
* var call = new ScriptCall("schreiber", "testScript", false);
* call.setEvent("onArchive");
**/
/**
* @memberof ScriptCall
* @function setFolder
* @instance
* @summary Set the execution context folder of the called script.
* @param {Folder} folder Folder object representing the desired execution context folder.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 5.0d
* @see [context.folder]{@link context#folder}
* @example
* var call = new ScriptCall("schreiber", "testScript", false);
* call.setFolder(context.folder);
**/
/**
* @memberof ScriptCall
* @function setRegister
* @instance
* @summary Set the execution context register of the called script.
* @param {Register} register Register object representing the desired execution context register.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @see [context.register]{@link context#register}
* @example
* var call = new ScriptCall("schreiber", "testScript", false);
* var file = context.getFileById("peachit_fi20120000000016");
* if (file)
* {
* var reg = file.getRegisterByName("Doc1");
* call.setRegister(reg);
* }
**/
/**
* @memberof ScriptCall
* @function waitForFinish
* @instance
* @summary Wait for the script call to finish.
* @description
* Note: This function is only available for a waitable script call.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @example
* var call = new ScriptCall("schreiber", "testScript", true);
* if (call.launch())
* {
* if (call.waitForFinish())
* {
* // do something
* }
* else
* util.out(call.getLastError());
* }
**/
/**
* @interface SystemUser
* @summary The SystemUser class has been added to the DOCUMENTS PortalScripting API to gain full access to the DOCUMENTS users by scripting means.
* @description There are several functions implemented in different classes to retrieve a SystemUser object.
* @since ELC 3.50b / otrisPORTAL 5.0b
*/
/**
* @memberof SystemUser
* @summary Annotations right flag in the access mask.
* @description
* Note: The access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} ANNOTATIONS
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @summary Archive right flag in the access mask.
* @description The bit that specifies the right to archive files.
* Note: The access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} ARCHIVE
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @summary Change filetype right flag in the access mask.
* @description The bit that specifies the right to change the filetype of a file.
* Note: The access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} CHANGE_TYPE
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @summary Change workflow right flag in the access mask.
* @description The bit that specifies the right to change a workflow assigned to a file.
* Note: The access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} CHANGE_WORKFLOW
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @summary Copy right flag in the access mask.
* @description The bit that specifies the right to copy files to a personal or public folder.
* Note: The access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} COPY
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @summary Create right flag in the access mask.
* @description The bit that specifies the right to create new files.
* Note: The access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} CREATE
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @summary Create workflow right flag in the access mask.
* @description
* Note: The access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} CREATE_WORKFLOW
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @summary String value containing the email address of the SystemUser.
* @member {string} email
* @instance
* @since DOCUMENTS 5.0a
**/
/**
* @memberof SystemUser
* @summary String value containing the first name of the SystemUser.
* @member {string} firstName
* @instance
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof SystemUser
* @summary String value containing the last name of the SystemUser.
* @member {string} lastName
* @instance
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof SystemUser
* @summary String value containing the unique login name of the SystemUser.
* @member {string} login
* @instance
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof SystemUser
* @summary Mail right flag in the access mask.
* @description The bit that specifies the right to send files via an e-mail system.
* Note: The access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} MAIL
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @summary Move right flag in the access mask.
* @description The bit that specifies the right to move files to a personal or public folder.
* Note: The access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} MOVE
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @summary Create PDF right flag in the access mask.
* @description The bit that specifies the right to create a PDF of a file.
* Note: The access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} PDF
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @summary Access to the property cache of the SystemUser.
* @description
* var user = context.getSystemUser();
* if (!user.propCache.hasProperty("Contacts"))
* {
* util.out("Creating cache");
* user.propCache.Contacts = ["Peter", "Paul", "Marry"];
* }
*
* @member {PropertyCache} propCache
* @instance
* @since DOCUMENTS 5.0
* @see [PropertyCache,AccessProfile.propCache]{@link PropertyCache,AccessProfile#propCache}
**/
/**
* @memberof SystemUser
* @summary Read right flag in the access mask.
* @description The bit that specifies the right to see files.
* Note: the access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} READ
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @summary Remove right flag in the access mask.
* @description The bit that specifies the right to delete files.
* Note: the access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} REMOVE
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @summary Start workflow flag in the access mask.
* @description
* Note: The access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} START_WORKFLOW
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @summary Versioning right flag in the access mask.
* @description
* Note: The access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} VERSION
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @summary Write right flag in the access mask.
* @description The bit that specifies the right for changing index fields or documents in files.
* Note: the access mask is returned by SystemUser.getAccess(DocFile)
* @member {number} WRITE
* @instance
* @see [SystemUser.getAccess]{@link SystemUser#getAccess}
**/
/**
* @memberof SystemUser
* @function addCustomProperty
* @instance
* @summary Creates a new CustomProperty for the user.
* @param {string} name String value defining the name
* @param {string} type String value defining the type
* @param {string} value String value defining the value
* @returns {CustomProperty} CustomProperty
* @since DOCUMENTS 4.0a
* @see [SystemUser.setOrAddCustomProperty]{@link SystemUser#setOrAddCustomProperty}
* @see [SystemUser.getCustomProperties]{@link SystemUser#getCustomProperties}
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* var custProp = currentUser.addCustomProperty("favorites", "string", "peachit");
* if (!custProp)
* util.out(currentUser.getLastError());
**/
/**
* @memberof SystemUser
* @function addFileTypeAgent
* @instance
* @summary Create file type agents for the user.
* @param {any} fileTypes The desired file types may be passed as follows:
* <ul>
* <li>String containing the technical name of the desired file type; </li>
* <li>Array of strings containing the technical names of the desired file types; </li>
* <li>String constant "*" indicating all file types. </li>
* </ul>
*
* @param {any[]} loginNames Array of strings containing the login names of the agents.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 5.0a
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* var loginNames = new Array();
* loginNames.push("user1");
* loginNames.push("user2");
* if (!currentUser.addFileTypeAgent("testFileType", loginNames))
* util.out("Error: " + currentUser.getLastError());
* else
* util.out("OK.");
**/
/**
* @memberof SystemUser
* @function addFileTypeAgentScript
* @instance
* @summary Create file type agents for the user, whereby the agents are specified by the desired script.
* @param {any} fileTypes The desired file types may be passed as follows:
* <ul>
* <li>String containing the technical name of the desired file type; </li>
* <li>Array of strings containing the technical names of the desired file types; </li>
* <li>String constant "*" indicating all file types. </li>
* </ul>
*
* @param {string} scriptName String containing the name of the script specifying the file type agents.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 5.0a
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* if (!currentUser.addFileTypeAgentScript("*", "testScript"))
* util.out("Error: " + currentUser.getLastError());
* else
* util.out("OK.");
**/
/**
* @memberof SystemUser
* @function addToAccessProfile
* @instance
* @summary Make the SystemUser a member of the desired AccessProfile.
* @description
* Note: If the user is already logged in, it is necessary to invalidate the cache of the user s. SystemUser.invalidateAccessProfileCache()
* Since DOCUMENTS 4.0b HF1 for Fellows
* @param {AccessProfile} ap AccessProfile the user should be a member of
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50b / otrisPORTAL 5.0b for PartnerAccounts
**/
/**
* @memberof SystemUser
* @function checkPassword
* @instance
* @summary Evaluate if the password is correct.
* @param {string} passwd String value containing the plain password
* @returns {boolean} <code>true</code> if correct, otherwise <code>false</code>
* @since ELC 3.60d / otrisPORTAL 6.0d
**/
/**
* @memberof SystemUser
* @function delegateFilesOfAbsentUser
* @instance
* @summary Move the files from the inbox of an absent user to his agent.
* @description If a Systemuser is set to absent, then all new files are redirected to his agent. The currently existing files (that came into the inbox before the was absent) can be moved to the agent with this method. If the user is not absent this method returns an error.
* @returns {boolean} <code>true</code> if succeeded, otherwise <code>false</code> - an error message describing the error with getLastError().
* @since ELC 3.60g / otrisPORTAL 6.0g
* @see [booleansetAbsent]{@link booleansetAbsent}
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* if (!currentUser.delegateFilesOfAbsentUser())
* util.out("Error: " + currentUser.getLastError());
* else
* util.out("OK.");
**/
/**
* @memberof SystemUser
* @function getAccess
* @instance
* @summary Retrieve an access mask whose bits correspond to the user's access rights supported by the given DocFile or filetype.
* @description
* Note: There is a constant for any right flag in the access mask (e.g. SystemUser.READ specifies the read right).
* @param {DocFile} docFile DocFile object to which the access rights should be retrieved.
* @returns {number} 32-bit value whose bits correspond to the user's access rights.
* @since DOCUMENTS 5.0a HF2
* @see [e.g.]{@link e#g#}
* @example
* var docFile = context.file;
* var currentUser = context.getSystemUser();
* if (!currentUser)
* throw "currentUser is NULL";
* var accessMask = currentUser.getAccess(docFile);
* if(SystemUser.READ & accessMask)
* util.out("The user " + currentUser.login + " has read access!");
**/
/**
* @memberof SystemUser
* @function getAccessProfiles
* @instance
* @summary Retrieve an AccessProfileIterator representing a list of all AccessProfiles the user is a member of.
* @returns {AccessProfileIterator} AccessProfileIterator containing a list of all AccessProfiles which are assigned to the user; <code>null</code> in case of any error
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof SystemUser
* @function getAgents
* @instance
* @summary Get a SystemUserIterator with the agents of the user.
* @description This method returns a SystemUserIterator with the agents of the user, if the user is absent.
* @returns {SystemUserIterator} SystemUserIterator
* @since ELC 3.60g / otrisPORTAL 6.0g
* @see [booleansetAbsent]{@link booleansetAbsent}
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* var itSU = currentUser.getAgents();
* for (var su = itSU.first(); su; su = itSU.next())
* {
* util.out(su.login);
* }
**/
/**
* @memberof SystemUser
* @function getAllFolders
* @instance
* @summary Retrieve a list of private and public Folders of the Systemuser.
* @returns {FolderIterator} FolderIterator containing a list of the folders.
* @since DOCUMENTS 5.0c
* @see [SystemUser.getAllFolders]{@link SystemUser#getAllFolders}
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser)
* throw "currentUser is null";
*
* var folderIter = currentUser.getAllFolders();
**/
/**
* @memberof SystemUser
* @function getAttribute
* @instance
* @summary Get the String value of an attribute of the SystemUser.
* @param {string} attribute String containing the name of the desired attribute
* @returns {string} String containing the value of the desired attribute
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof SystemUser
* @function getBackDelegatedFiles
* @instance
* @summary Get back the delegated files.
* @description If the user is not present this method returns an error.
* @param {boolean} removeFromAgentInbox Optional boolean indicating whether the files are removed from agent inbox after getting back by the user. If this parameter is not specified, the value from the user settings in the absent dialog on the web is used.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0d
* @see [booleansetAbsent]{@link booleansetAbsent}
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* if (!currentUser.getBackDelegatedFiles(true))
* util.out("Error: " + currentUser.getLastError());
* else
* util.out("OK.");
**/
/**
* @memberof SystemUser
* @function getCustomProperties
* @instance
* @summary Get a CustomPropertyIterator with all CustomProperty of the user.
* @description This method returns a CustomPropertyIterator with the CustomProperty of the user.
* @param {string} [nameFilter] String value defining an optional filter depending on the name
* @param {string} [typeFilter] String value defining an optional filter depending on the type
* @returns {CustomPropertyIterator} CustomPropertyIterator
* @since DOCUMENTS 4.0a
* @see [context.findCustomProperties]{@link context#findCustomProperties}
* @see [SystemUser.setOrAddCustomProperty]{@link SystemUser#setOrAddCustomProperty}
* @see [SystemUser.addCustomProperty]{@link SystemUser#addCustomProperty}
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* var itProp = currentUser.getCustomProperties();
* for (var prop = itProp.first(); prop; prop = itProp.next())
* {
* util.out(prop.name + prop.value);
* }
**/
/**
* @memberof SystemUser
* @function getIndividualFolders
* @instance
* @summary Retrieve a list of individual Folders of the Systemuser.
* @returns {FolderIterator} FolderIterator containing a list of all individual folders.
* @since DOCUMENTS 4.0d
* @see [SystemUser.getPrivateFolder]{@link SystemUser#getPrivateFolder}
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser)
* throw "currentUser is null";
*
* var folderIter = currentUser.getIndividualFolders();
**/
/**
* @memberof SystemUser
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since ELC 3.50b / otrisPORTAL 5.0b
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof SystemUser
* @function getOID
* @instance
* @summary Returns the object-id.
* @description
* Since DOCUMENTS 5.0 (new parameter oidLow)
* @param {boolean} [oidLow] Optional flag:
* If <code>true</code> only the id of the filetype object (<code>m_oid</code>) will be returned.
* If <code>false</code> the id of the filetype object will be returned together with the id of the corresponding class in the form <code>class-id:m_oid</code>.
* The default value is <code>false</code>.
* @returns {string} <code>String</code> with the object-id
* @since ELC 3.60c / otrisPORTAL 6.0c
**/
/**
* @memberof SystemUser
* @function getPrivateFolder
* @instance
* @summary Try to retrieve a particular private Folder of the Systemuser.
* @description In addition to the public folders you may define in DOCUMENTS, each DOCUMENTS user has a set of private folders. You might need to access a particular private folder to access its contents, for example.
* @param {string} folderType String value defining the kind of private folder you want to access.
* You may choose between
* <ul>
* <li><code>"individual"</code> individual folder undefinedNote: This function returns only the first individual folder on the top level. Using SystemUser.getIndividualFolders() to retrieve all individual folders. </li>
* <li><code>"favorites"</code> favorites folder </li>
* <li><code>"inbox"</code> the user's inbox </li>
* <li><code>"sent"</code> the user's sent folder </li>
* <li><code>"sendingfinished"</code> user's folder containing files which finished their workflow </li>
* <li><code>"inwork"</code> folder containing the files the SystemUser created himself </li>
* <li><code>"resubmission"</code> folder containing files with a resubmission defined for the SystemUser</li>
* <li><code>"trash"</code> folder containing files the user has deleted </li>
* <li><code>"tasks"</code> folder containing all files the user has a task to perform to </li>
* <li><code>"lastused"</code> folder containing the files the SystemUser accessed latest, sorted in descending chronological order </li>
* <li><code>"introuble"</code> folder containing files which ran into some workflow error. This folder is only available for editors and only if it has been added manually by the administrator. </li>
* </ul>
*
* @returns {Folder} Folder object representing the desired folder, <code>null</code> in case of any error
* @since ELC 3.51b / otrisPORTAL 5.1b
* @see [SystemUser.getIndividualFolders]{@link SystemUser#getIndividualFolders}
**/
/**
* @memberof SystemUser
* @function getSuperior
* @instance
* @summary Get the SystemUser object representing the superior of the user.
* @returns {SystemUser} SystemUser object representing the superior or null if no superior available
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof SystemUser
* @function getUserdefinedInboxFolders
* @instance
* @summary Retrieve a list of userdefined inbox Folders of the Systemuser.
* @returns {FolderIterator} FolderIterator containing a list of all userdefined inbox folders.
* @since DOCUMENTS 4.0d
* @see [SystemUser.getPrivateFolder]{@link SystemUser#getPrivateFolder}
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser)
* throw "currentUser is null";
*
* var folderIter = currentUser.getUserdefinedInboxFolders();
**/
/**
* @memberof SystemUser
* @function hasAccessProfile
* @instance
* @summary Retrieve information whether the SystemUser is a member of a particular AccessProfile which is identified by its technical name.
* @param {string} profileName String value containing the technical name of an AccessProfile
* @returns {boolean} <code>true</code> if the SystemUser is a member of the desired profile, otherwise <code>false</code>
* @since ELC 3.50e / otrisPORTAL 5.0e
**/
/**
* @memberof SystemUser
* @function invalidateAccessProfileCache
* @instance
* @summary Invalidates the server sided cache of the access profiles for the SystemUser.
* @returns {boolean} <code>true</code> if successful, otherwise <code>false</code>
* @since DOCUMENTS 4.0 (HF1)
**/
/**
* @memberof SystemUser
* @function listAgentFileTypes
* @instance
* @summary Retrieve a list of file types for them an agent exists.
* @returns {any[]} Array of strings containing the technical names of the file types.
* If the flag 'all filetypes' for a file type agent is set, the array contains only the string "*".
* @since DOCUMENTS 5.0a
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* var fileTypes = currentUser.listAgentFileTypes();
* if (fileTypes)
* {
* for (var i=0; i < fileTypes.length; i++)
* {
* util.out(fileTypes[i]);
* }
* }
* else
* util.out("Error: " + currentUser.getLastError());
**/
/**
* @memberof SystemUser
* @function listFileTypeAgents
* @instance
* @summary Retrieve a list of all agents for the desired file type of the user.
* @param {string} fileType String containing the technical name of the file type.
* @returns {any[]} Array of strings containing login names of all agents for the desired file type.
* @since DOCUMENTS 5.0a
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* var loginNames = currentUser.listFileTypeAgents("testFileType");
* if (loginNames)
* {
* for (var i=0; i < loginNames.length; i++)
* {
* util.out(loginNames[i]);
* }
* }
* else
* util.out("Error: " + currentUser.getLastError());
**/
/**
* @memberof SystemUser
* @function notifyFileReturnedFromSending
* @instance
* @summary Define whether to notify the user by e-mail of files returned from sending.
* @param {boolean} [notifying] boolean indicating whether files returned from sending are to be notified to the user. The default value is <code>true</code>.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 5.0a
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* if (!currentUser.notifyFileReturnedFromSending(true))
* util.out("Error: " + currentUser.getLastError());
* else
* util.out("OK.");
**/
/**
* @memberof SystemUser
* @function notifyNewFileInInbox
* @instance
* @summary Define whether to notify the user by e-mail of new files in inbox.
* @param {boolean} [notifying] boolean indicating whether new files in inbox are to be notified to the user. The default value is <code>true</code>.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 5.0a
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* if (!currentUser.notifyNewFileInInbox(true))
* util.out("Error: " + currentUser.getLastError());
* else
* util.out("OK.");
**/
/**
* @memberof SystemUser
* @function removeFileTypeAgent
* @instance
* @summary Remove file type agents from the user.
* @param {any} fileTypes The desired file types may be passed as follows:
* <ul>
* <li>String containing the technical name of the desired file type; </li>
* <li>Array of strings containing the technical names of the desired file types; </li>
* <li>String constant "*" indicating all file types. </li>
* </ul>
*
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 5.0a
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* var fileTypes = new Array();
* fileTypes.push("Filetype1");
* fileTypes.push("Filetype2");
* if (!currentUser.removeFileTypeAgent(fileTypes))
* util.out("Error: " + currentUser.getLastError());
* else
* util.out("OK.");
**/
/**
* @memberof SystemUser
* @function removeFromAccessProfile
* @instance
* @summary Clear the SystemUser's membership in the given AccessProfile.
* @description
* Note: If the user is already logged in, it is necessary to invalidate the cache of the user s. SystemUser.invalidateAccessProfileCache()
* Since DOCUMENTS 4.0b HF1 for Fellows
* @param {AccessProfile} ap
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50b / otrisPORTAL 5.0b for PartnerAccounts
**/
/**
* @memberof SystemUser
* @function resetSuperior
* @instance
* @summary Clear the user's relation to a superior.
* @returns {boolean} true if successful, false in case of any error
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof SystemUser
* @function setAbsent
* @instance
* @summary Set a Systemuser absent or present.
* @description If a Systemuser is on holiday with this function it is possible to set the user absent. After his return you can set him present. You can also define one or more agents for the absent user. The agent will get new files for the absent user in substitution. With the agent list you set the agents for the user (you overwrite the existing agents!). With an empty agent list you remove all agents.
* Since DOCUMENTS 4.0d (Option: removeFromAgentInbox)
* Since DOCUMENTS 5.0a (Option: from and until)
* @param {boolean} absent boolean <code>true</code>, if the user should be set absent, <code>false</code>, if the user is present
* @param {boolean} [filesDueAbsenceToInfo] boolean set to <code>true</code>, if the user should get the files due absence to info in his inbox
* @param {string[]} [agents] Array with the login-names of the agents
* @param {boolean} [removeFromAgentInbox] Optional boolean indicating whether the files are removed from agent inbox after getting back by the user. If this parameter is not specified, the value from the user settings in the absent dialog on the web is used.
* @param {Date} [from] Optional Date object specifying when the absence begins.
* @param {Date} [until] Optional Date object specifying when the absence ends.
* @returns {boolean} <code>true</code> if correct, otherwise <code>false</code> an error message describing the error with getLastError().
* @since ELC 3.60g / otrisPORTAL 6.0g
* @see [boolean]{@link boolean}
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* // set user absent
* var agents = new Array();
* agents.push("oppen");
* agents.push("buch");
* var from = new Date();
* var until = context.addTimeInterval(from, 3, "days", false);
* if (!currentUser.setAbsent(true, false, agents, true, from, until))
* util.out("Error: " + currentUser.getLastError());
* else
* util.out("OK.");
*
*
* // set user present
* if (!currentUser.setAbsent(false))
* util.out("Error: " + currentUser.getLastError());
* else
* util.out("OK.");
**/
/**
* @memberof SystemUser
* @function setAbsentMail
* @instance
* @summary Define if an absence mail for the absent user will be sent to the sender of the file.
* @description If a Systemuser is absent and get a file in the inbox, an absence mail to the sender of this file can be send.
* @param {boolean} sendMail boolean <code>true</code>, if an absent mail should be sent, otherwise <code>false</code>
* @param {string} [message] String with an additional e-mail message from the absent user
* @returns {boolean} <code>true</code> if succeeded, otherwise <code>false</code> - an error message describing the error with getLastError().
* @since ELC 3.60g / otrisPORTAL 6.0g
* @see [booleansetAbsent]{@link booleansetAbsent}
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* if (!currentUser.setAbsentMail(true, "I will be back on 12/31 2009"))
* util.out("Error: " + currentUser.getLastError());
* else
* util.out("OK.");
**/
/**
* @memberof SystemUser
* @function setAccessProfiles
* @instance
* @summary Set the AccessProfiles for an user.
* @description All existing AccessProfiles will be removed and the AccessProfiles from the parameters will be set.
* @param {any} apNames1 String or Array with the names of the AccessProfiles
* @param {any} apNames2 String or Array with the names of the AccessProfiles
* @param {any[]} ...restParams
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 5.0c HF2
* @example
* var val1 = ["AP1", "AP2"];
* var val2 = "AP3\r\nAP4";
* var user = context.getSystemUser();
* if (!user.setAccessProfiles(val1, val2))
* throw user.getLastError();
**/
/**
* @memberof SystemUser
* @function setAttribute
* @instance
* @summary Set the String value of an attribute of the SystemUser to the desired value.
* @param {string} attribute String containing the name of the desired attribute
* @param {string} value String containing the desired value of the attribute
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof SystemUser
* @function setEasywareAuthentication
* @instance
* @summary Turn EASYWARE Authentication on or off.
* @param {boolean} value boolean <code>true</code> to turn authentication on <code>false</code> to turn it off.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 5.0c HF2
**/
/**
* @memberof SystemUser
* @function setOrAddCustomProperty
* @instance
* @summary Creates a new CustomProperty or modifies a CustomProperty according the name and type for the user.
* @description This method creates or modifies a unique CustomProperty for the user. The combination of the name and the type make the CustomProperty unique for the user.
* @param {string} name String value defining the name
* @param {string} type String value defining the type
* @param {string} value String value defining the value
* @returns {CustomProperty} CustomProperty
* @since DOCUMENTS 4.0a
* @see [SystemUser.getCustomProperties]{@link SystemUser#getCustomProperties}
* @see [SystemUser.addCustomProperty]{@link SystemUser#addCustomProperty}
* @example
* var currentUser = context.getSystemUser();
* if (!currentUser) throw "currentUser is NULL";
*
* var custProp = currentUser.setOrAddCustomProperty("superior", "string", "oppen");
* if (!custProp)
* util.out(currentUser.getLastError());
**/
/**
* @memberof SystemUser
* @function setPassword
* @instance
* @summary Set the password of the user represented by the SystemUser object to the desired new value.
* @param {string} newPwd String containing the plaintext new password
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof SystemUser
* @function setSuperior
* @instance
* @summary Set the SystemUser object representing the superior of the user to the desired object.
* @param {SystemUser} sup Systemuser object representing the new superior of the user
* @returns {boolean} true if successful, false in case of any error
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @interface SystemUserIterator
* @summary The SystemUserIterator class has been added to the DOCUMENTS PortalScripting API to gain full access to the DOCUMENTS users by scripting means.
* @description The objects of this class represent lists of Systemuser objects and allow to loop through such a list of users.
* @since ELC 3.50b / otrisPORTAL 5.0b
*/
/**
* @memberof SystemUserIterator
* @function first
* @instance
* @summary Retrieve the first SystemUser object in the SystemUserIterator.
* @returns {SystemUser} SystemUser or <code>null</code> in case of an empty SystemUserIterator
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof SystemUserIterator
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since ELC 3.50b / otrisPORTAL 5.0b
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof SystemUserIterator
* @function next
* @instance
* @summary Retrieve the next SystemUser object in the SystemUserIterator.
* @returns {SystemUser} SystemUser or <code>null</code> if end of SystemUserIterator is reached.
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @memberof SystemUserIterator
* @function size
* @instance
* @summary Get the amount of SystemUser objects in the SystemUserIterator.
* @returns {number} integer value with the amount of SystemUser objects in the SystemUserIterator
* @since ELC 3.50b / otrisPORTAL 5.0b
**/
/**
* @class UserAction
* @classdesc The UserAction class represents the user-defined action of DOCUMENTS.
* @since DOCUMENTS 4.0d
* @example
* var folder = context.createFolder("test", "public");
* var action = new UserAction("testAction");
* action.widget = "DropdownList";
* action.setFileTypeForNewFile("FileType1");
* if (!action.addToFolder(folder))
* util.out(action.getLastError());
* @summary Create a new instance of the UserAction class.
* Since DOCUMENTS 4.0d
* @param {string} name String value containing the desired user action name.
* @param {string} [label] String value containing the desired user action label.
* @param {string} [widget] String value containing the desired user action widget.
* @param {string} [type] String value containing the desired user action type.
* @param {string} [scope] String value containting the desired user action scope.
* @see [UserAction.widget,UserAction.type,UserAction.scope]{@link UserAction#widget,UserAction#type,UserAction#scope}
* @example
* var action = new UserAction("testAction", "de:Aktion;en:Action", "DropdownList", "PortalScript", "ProcessesOnly");
*/
/**
* @memberof UserAction
* @summary The entire label defined for the UserAction object.
* @member {string} label
* @instance
* @since DOCUMENTS 4.0d
**/
/**
* @memberof UserAction
* @summary The technical name of the UserAction object.
* @member {string} name
* @instance
* @since DOCUMENTS 4.0d
**/
/**
* @memberof UserAction
* @summary The scope of the UserAction object.
* @member {string} scope
* @instance
* @since DOCUMENTS 4.0d
**/
/**
* @memberof UserAction
* @summary The type of the UserAction object.
* @member {string} type
* @instance
* @since DOCUMENTS 4.0d
**/
/**
* @memberof UserAction
* @summary The widget identifier of the UserAction object.
* @member {string} widget
* @instance
* @since DOCUMENTS 4.0d
**/
/**
* @memberof UserAction
* @function addToFolder
* @instance
* @summary Add the user action to a Folder.
* @param {Folder} folder Folder object representing the desired Folder.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @example
* var it = context.getFoldersByName("testFolder");
* var folder = it.first();
* if (folder)
* {
* var action = new UserAction("testAction");
* if (action)
* {
* if (!action.addToFolder(folder))
* util.out(action.getLastError());
* }
* }
**/
/**
* @memberof UserAction
* @function getLastError
* @instance
* @summary Get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since DOCUMENTS 4.0d
**/
/**
* @memberof UserAction
* @function getOID
* @instance
* @summary Returns the object-id.
* @description
* Since DOCUMENTS 5.0 (new parameter oidLow)
* @param {boolean} [oidLow] Optional flag:
* If <code>true</code> only the id of the filetype object (<code>m_oid</code>) will be returned.
* If <code>false</code> the id of the filetype object will be returned together with the id of the corresponding class in the form <code>class-id:m_oid</code>.
* The default value is <code>false</code>.
* @returns {string} <code>String</code> with the object-id or an empty string in case the user action has not yet been added to a proper parent object.
* @since DOCUMENTS 4.0d
**/
/**
* @memberof UserAction
* @function getPosition
* @instance
* @summary Retrieve the position of the user action within the user-defined action list of the parent object.
* @returns {number} The zero-based position of the user action as integer or -1 in case of any error.
* @since DOCUMENTS 4.0d
* @example
* var it = context.getFoldersByName("testFolder");
* var folder = it.first();
* if (folder)
* {
* var action = folder.getActionByName("testAction");
* if (action)
* util.out(action.getPosition());
* }
**/
/**
* @memberof UserAction
* @function remove
* @instance
* @summary Remove the user action from the parent object.
* @description
* Note: If the user action has not yet been added to a proper parent object, this function does nothing.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @example
* var it = context.getFoldersByName("testFolder");
* var folder = it.first();
* if (folder)
* {
* var action = folder.getActionByName("testAction");
* if (action)
* action.remove();
* }
**/
/**
* @memberof UserAction
* @function setContext
* @instance
* @summary Set the context for a user action of type JSP.
* @description
* Note: This function is only available for a user action of type JSP.
* @param {string} context String containing the desired context.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @example
* var action = new UserAction("testAction");
* action.type = "JSP";
* if (!action.setContext("myContext"))
* util.out(action.getLastError());
**/
/**
* @memberof UserAction
* @function setCreateDefaultWorkflow
* @instance
* @summary Set the flag whether to create the default workflow for a user action of type NewFile.
* @description
* Note: This function is only available for a user action of type NewFile.
* @param {boolean} createDefaultWorkflow Flag indicating whether to create the default workflow for a new file.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @example
* var action = new UserAction("testAction");
* if (!action.setCreateDefaultWorkflow(false))
* util.out(action.getLastError());
**/
/**
* @memberof UserAction
* @function setFileTypeForNewFile
* @instance
* @summary Set the file type for a user action of type NewFile.
* @description
* Note: This function is only available for a user action of type NewFile.
* @param {string} fileType The technical name of the desired file type; use empty string ('') if you want to remove the associated file type.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @example
* var action = new UserAction("testAction");
* if (!action.setFileTypeForNewFile("Filetype1"))
* util.out(action.getLastError());
*
* // You can remove the file type as follows:
* action.setFileTypeForNewFile('');
**/
/**
* @memberof UserAction
* @function setPortalScript
* @instance
* @summary Set the portal script for a user action of type PortalScript.
* @description
* Note: This function is only available for a user action of type PortalScript.
* @param {string} scriptName The name of the desired portal script; use empty string ('') if you want to remove the associated script.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @example
* var action = new UserAction("testAction");
* action.type = "PortalScript";
* if (!action.setPortalScript("testScript"))
* util.out(action.getLastError());
*
* // You can remove the script as follows:
* action.setPortalScript('');
**/
/**
* @memberof UserAction
* @function setPosition
* @instance
* @summary Place the user action at the given position in the user-defined action list of the parent object.
* @description
* Note: 0 at the beginning and -1 at the end.
* @param {number} position The 0-based position for the user action.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0d
* @example
* var it = context.getFoldersByName("testFolder");
* var folder = it.first();
* if (folder)
* {
* var action = folder.getActionByName("testAction");
* if (action)
* action.setPosition(-1);
* }
**/
/**
* @namespace util
* @summary The Util class supports some functions that do not need any user or file context.
* @description These functions allow customizable Date/String conversions and other useful stuff. There is exactly ONE implicit object of the class <code>Util</code> which is named <code>util</code>.
* Note: It is not possible to create objects of the class Util. There are no properties in this class, it supports only the help functions as documented below.
*/
/**
* @memberof util
* @summary Build version number of the PortalServer.
* @description This property allows to retrieve the build version number of the PortalServer to customize your PortalScripts in dependence of the used PortalServer.
*
* Note: This property is readonly.
* @member {number} buildNo
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* if (util.buildNo > 1826)
* {
* // do update
* }
**/
/**
* @memberof util
* @summary Database using by the PortalServer.
* @description The following databases are supported by the PortalServer:
* <ul>
* <li><code>oracle</code></li>
* <li><code>mysql</code></li>
* <li><code>mssql</code></li>
* </ul>
*
* Note: This property is readonly.
* @member {string} DB
* @instance
* @since DOCUMENTS 4.0
**/
/**
* @memberof util
* @summary Memory model of the PortalServer.
* @description There are two possible memory models available : x64 or x86.
*
* Note: This property is readonly.
* @member {string} memoryModel
* @instance
* @since DOCUMENTS 4.0
**/
/**
* @memberof util
* @summary Main version number of the PortalServer.
* @description This property allows to retrieve the version number of the PortalServer to customize your PortalScripts in dependence of the used PortalServer. For example:
* <ul>
* <li>otrisPORTAL 5.1 / ELC 3.51 returns 5100 </li>
* <li>otrisPORTAL 6.0 / ELC 3.60 returns 6000 </li>
* <li>DOCUMENTS 4.0 returns 7000</li>
* </ul>
*
* Note: This property is readonly.
* @member {number} version
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
* @example
* if (util.version < 6000)
* {
* // do update
* }
**/
/**
* @memberof util
* @function base64Decode
* @instance
* @summary Decodes a base64 string and returns a string or byte-array.
* @param {string} value String to decode
* @param {boolean} [returnArray] boolean as an optional parameter to define if the return value must be a byte-array or string (default)
* @returns {any} decoded string or byte-array
* @since DOCUMENTS 4.0c HF1
* @example
* var b64Str = util.base64Encode("Hello World");
* util.out(b64Str); // SGVsbG8gV29ybGQ=
*
* var str = util.base64Decode(b64Str);
* util.out(str); // Hello World
*
* var byteArr = util.base64Decode(b64Str, true);
* util.out(byteArr); // 72,101,108,108,111,32,87,111,114,108,100
*
* b64Str = util.base64Encode(byteArr);
* util.out(b64Str); // SGVsbG8gV29ybGQ=
**/
/**
* @memberof util
* @function base64Encode
* @instance
* @summary Encodes a byte-array or string to base64 and returns the base 64 string.
* @param {any} value String or byte-array to encode
* @param {boolean} [returnArray] boolean as an optional parameter to define if the return value must be a byte-array or string (default)
* @returns {string} base64 encoded string
* @since DOCUMENTS 4.0c HF1
* @example
* var b64Str = util.base64Encode("Hello World");
* util.out(b64Str); // SGVsbG8gV29ybGQ=
*
* var str = util.base64Decode(b64Str);
* util.out(str); // Hello World
*
* var byteArr = util.base64Decode(b64Str, true);
* util.out(byteArr); // 72,101,108,108,111,32,87,111,114,108,100
*
* b64Str = util.base64Encode(byteArr);
* util.out(b64Str); // SGVsbG8gV29ybGQ=
**/
/**
* @memberof util
* @function beep
* @instance
* @summary Plays a beep sound at the PortalServer's system.
* @description For testing purposes a beep sound can be played at the server
* @param {number} frequency int with the frequency in hertz
* @param {number} duration int with the length of the sound in milliseconds (ms)
* @returns {void}
* @since ELC 3.60e / otrisPORTAL 6.0e
* @example
* util.beep(1250, 3000);
**/
/**
* @memberof util
* @function concatPDF
* @instance
* @summary Concatenate the given PDFs together into one PDF.
* @param {any[]} pdfFilePaths Array containing the file paths of PDFs to be concatenated.
* @param {boolean} [deleteSinglePdfs] Optional boolean value to decide whether to delete the single PDFs on the server's filesystem after concatenating.
* @returns {string} String with file path of the PDF, an empty string in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var arr = ["C:\\temp\\number1.pdf", "C:\\temp\\number2.pdf"];
* var filePath = util.concatPDF(arr, false);
* util.out("PDF file path: " + filePath);
**/
/**
* @memberof util
* @function convertBlobToPDF
* @instance
* @summary Convert a file to a PDF file and return the path in the file system.
* @description The different file types require the appropriate PDF filter programs to be installed and configured in DOCUMENTS.
* @param {string} sourceFilePath String containing the path of the file to be converted.
* @returns {string} <code>String</code> with file path of the PDF, an empty string in case of any error.
* @since DOCUMENTS 4.0d HF3
* @example
* var pathPdfFile = util.convertBlobToPDF("C:\\tmp\\testFile.doc");
* util.out(pathPdfFile);
**/
/**
* @memberof util
* @function convertDateToString
* @instance
* @summary Convert a Date object representing a date into a String.
* @description The output String may have any format you like. The second parameter defines the format to configure which part of the date String should match the according properties of the Date object.
* Since DOCUMENTS 5.0a (new: Special formats @date and @timestamp)
* @param {Date} timeStamp Date object representing the desired date
* @param {string} format String defining the date format of the output String, e.g. "dd.mm.yyyy".
* The possible format parts are:
* <ul>
* <li><code>dd</code> = two digit day </li>
* <li><code>mm</code> = two digit month </li>
* <li><code>yy</code> = two digit year </li>
* <li><code>yyyy</code> = four digit year </li>
* <li><code>HH</code> = two digit hour (24 hour format) </li>
* <li><code>MM</code> = two digit minute </li>
* <li><code>SS</code> = two digit second</li>
* </ul>
* Special formats:
* <ul>
* <li><code>@date</code> = @yyyymmdd (locale independant format for filter in a FileResultset, HitResultset) </li>
* <li><code>@timestamp</code> = @yyyymmddHHMMSS (locale independant format for filter in a FileResultset, HitResultset) </li>
* </ul>
*
* @returns {string} String representing the desired date
* @since ELC 3.50e / otrisPORTAL 5.0e
* @see [util.convertStringToDate]{@link util#convertStringToDate}
* @see [context.convertDateToString]{@link context#convertDateToString}
* @example
* var format = "dd.mm.yyyy HH:MM";
* var now = new Date();
* util.out(util.convertDateToString(now, format));
**/
/**
* @memberof util
* @function convertStringToDate
* @instance
* @summary Convert a String representing a date into a Date object.
* @description The String may contain a date or timestamp in any date format you like. The second parameter defines the format to configure which part of the date String should match the according properties of the Date object.
* Since DOCUMENTS 5.0a (new: Special formats @date and @timestamp)
* @param {string} dateOrTimeStamp String representing a date, e.g. "19.09.1974"
* @param {string} format String defining the date format of the input String, e.g. "dd.mm.yyyy".
* The possible format parts are:
* <ul>
* <li><code>dd</code> = two digit day </li>
* <li><code>mm</code> = two digit month </li>
* <li><code>yy</code> = two digit year </li>
* <li><code>yyyy</code> = four digit year </li>
* <li><code>HH</code> = two digit hour (24 hour format) </li>
* <li><code>MM</code> = two digit minute </li>
* <li><code>SS</code> = two digit second</li>
* </ul>
* Special formats:
* <ul>
* <li><code>@date</code> = @yyyymmdd (locale independant format for filter in a FileResultset, HitResultset) </li>
* <li><code>@timestamp</code> = @yyyymmddHHMMSS (locale independant format for filter in a FileResultset, HitResultset) </li>
* </ul>
*
* @returns {Date} Date object representing the desired date
* @since ELC 3.50e / otrisPORTAL 5.0e
* @see [util.convertDateToString]{@link util#convertDateToString}
* @example
* var format = "dd.mm.yyyy HH:MM";
* var dateString = "19.09.1974";
* var birthDay = util.convertStringToDate(dateString, format);
**/
/**
* @memberof util
* @function cryptPassword
* @instance
* @summary Encrypt a plain password into an MD5 hash.
* @param {string} pwPlain String containing the plain password
* @returns {string} String containing the encrypted password
* @since ELC 3.50o / otrisPORTAL 5.0o
* @example
* var cryptPW = util.cryptPassword("Hello World");
* util.out(cryptPW);
**/
/**
* @memberof util
* @function decodeUrlCompatible
* @instance
* @summary Decode URL parameter from DOCUMENTS Urls.
* @param {string} encodedParam String containing the encoded URL param
* @returns {string} <code>String</code> with decoded URL param.
* @since DOCUMENTS 5.0a
* @see [util.encodeUrlCompatible]{@link util#encodeUrlCompatible}
* @example
* // URL with an archive key
* var encUrl = "http://localhost:8080/documents/UserLoginSuccessAction.act;cnvid=n0RIshUTRnOH3qAn?
* pri=easyhr&lang=de#fi_96:3020/
* id_{ehrmEmployeeDocument$EAstore2$HMUnit$DNDefault$CPInstance$DNDefault$CPPool$DNAdaptive
* $CPPool$DNAdaptive02$CPDocument$DNADAPTIVE$CO060C8A9C3A1811E6B75A000C29E0A93B}
* /ri_FileCover/di_easyhrdc0000000000000497";
*
* var decUrl = util.decodeUrlCompatible(encUrl);
*
* decUrl == "http://localhost:8080/documents/UserLoginSuccessAction.act;cnvid=n0RIshUTRnOH3qAn
* ?pri=easyhr&lang=de#fi_96:3020/
* id_{ehrmEmployeeDocument@store2|Unit=Default/Instance=Default/Pool=Adaptive/Pool=
* Adaptive02/Document=ADAPTIVE.060C8A9C3A1811E6B75A000C29E0A93B}
* /ri_FileCover/di_easyhrdc0000000000000497";
**/
/**
* @memberof util
* @function decryptString
* @instance
* @summary Decrypts a String value hat was encrypted with the method Util.encryptString(String input)
* @param {string} input The string that will be decrypted
* @returns {string} String decrypted value
* @since DOCUMENTS 5.0b
* @see [util.encryptString]{@link util#encryptString}
* @example
* var text = "I'm a secret password";
*
* var encryptedText = util.encryptString(text);
* util.out(encryptedText); // NABPIGCGBHEBBOMECMJHDBHIIHOCDNOMODEILCABDKOLJBMFBKDDOFDABNAMCLJC
*
* var decryptedText = util.decryptString(encryptedText);
* util.out(decryptedText); // I'm a secret password
**/
/**
* @memberof util
* @function deleteFile
* @instance
* @summary Delete a file (file system object) at the PortalServer's system.
* @description This functions provides a simple delete method for files on the server's file system.
* @param {string} filePath String with the file path
* @returns {string} empty String if successful, the error message in case of any error
* @since ELC 3.60e / otrisPORTAL 6.0e
* @example
* var errMsg = util.deleteFile("c:\\Test.log");
* if (errMsg.length > 0)
* util.out(errMsg);
* else
* util.out("Ok.");
**/
/**
* @memberof util
* @function encodeUrlCompatible
* @instance
* @summary Encode URL parameter for DOCUMENTS Urls.
* @description Some parameters in DOCUMENTS urls must be encoded. E.g. the archive keys can contain invalid characters like / etc.
* @param {string} param String containing the value to encode
* @returns {string} <code>String</code> with encoded value.
* @since DOCUMENTS 5.0a
* @see [util.decodeUrlCompatible]{@link util#decodeUrlCompatible}
* @example
* // URL with an archive key
* var url = "http://localhost:8080/documents/UserLoginSuccessAction.act;cnvid=n0RIshUTRnOH3qAn?
* pri=easyhr&lang=de#fi_96:3020/
* id_{ehrmEmployeeDocument@store2|Unit=Default/Instance=Default/Pool=Adaptive/Pool=
* Adaptive02/Document=ADAPTIVE.060C8A9C3A1811E6B75A000C29E0A93B}
* /ri_FileCover/di_easyhrdc0000000000000497";
*
* // The archive key is the value between id_{ }
* // "ehrmEmployeeDocument@store2|Unit=Default/Instance=Default/Pool=
* // Adaptive/Pool=Adaptive02/Document=ADAPTIVE.060C8A9C3A1811E6B75A000C29E0A93B"
* // this key must be encoded
*
* var encUrl = encodeURL(url);
* encUrl == "http://localhost:8080/documents/UserLoginSuccessAction.act;cnvid=n0RIshUTRnOH3qAn?
* pri=easyhr&lang=de#fi_96:3020/
* id_{ehrmEmployeeDocument$EAstore2$HMUnit$DNDefault$CPInstance$DNDefault$CPPool$DNAdaptive
* $CPPool$DNAdaptive02$CPDocument$DNADAPTIVE$CO060C8A9C3A1811E6B75A000C29E0A93B}
* /ri_FileCover/di_easyhrdc0000000000000497";
*
* function encodeURL(url)
* {
* // RegEx to split the url in it's parts
* var reg = /(.*id_{)(.*)(}.*)/
* if (!completeURL.match(reg))
* throw "unable to encode";
* var part1 = RegExp.$1;
* var partKey = RegExp.$2;
* var part3 = RegExp.$3;
* return encoded = part1 + util.encodeUrlCompatible(partKey) + part3;
* }
**/
/**
* @memberof util
* @function encryptString
* @instance
* @summary Encrypts a String value with the AES 256 CBC algorithm for symmetric encryption/decryption.
* @description The length of the input String is limited to 1024 bytes. The encrypted value depends on the principal name. Usage is e.g. storing of passwords in the database for authorization against 3rd party web services.
* @param {string} input The string that will be encrypted
* @returns {string} String encrypted value
* @since DOCUMENTS 5.0b
* @see [util.decryptString]{@link util#decryptString}
* @example
* var text = "I'm a secret password";
*
* var encryptedText = util.encryptString(text);
* util.out(encryptedText); // NABPIGCGBHEBBOMECMJHDBHIIHOCDNOMODEILCABDKOLJBMFBKDDOFDABNAMCLJC
*
* var decryptedText = util.decryptString(encryptedText);
* util.out(decryptedText); // I'm a secret password
**/
/**
* @memberof util
* @function fileCopy
* @instance
* @summary Copy a file (file system object) at the PortalServer's system.
* @description This functions provides a simple copy method for files on the server's file system.
* @param {string} sourceFilePath String with the source file path
* @param {string} targetFilePath String with the target file path
* @returns {string} empty String if successful, the error message in case of any error
* @since ELC 3.60e / otrisPORTAL 6.0e
* @see [util.fileMove]{@link util#fileMove}
* @example
* var errMsg = util.fileCopy("c:\\Test.log", "d:\\Test.log");
* if (errMsg.length > 0)
* util.out(errMsg);
* else
* util.out("Ok.");
**/
/**
* @memberof util
* @function fileMove
* @instance
* @summary Move a file (file system object) at the PortalServer's system from a source file path to the target file path.
* @description This functions provides a simple move method for files on the server's file system.
* @param {string} sourceFilePath String with the source file path
* @param {string} targetFilePath String with the target file path
* @returns {string} empty String if successful, the error message in case of any error
* @since ELC 3.60e / otrisPORTAL 6.0e
* @see [util.fileCopy]{@link util#fileCopy}
* @example
* var errMsg = util.fileMove("c:\\Test.log", "d:\\Test.log");
* if (errMsg.length > 0)
* util.out(errMsg);
* else
* util.out("Ok.");
**/
/**
* @memberof util
* @function fileSize
* @instance
* @summary Retrieve the filesize of a file (file system object) at the PortalServer's system.
* @description This functions returns the filesize of a file.
* @param {string} filePath String with the file path
* @returns {number} Int with file size if successful, the value -1 in case of any error
* @since ELC 3.60e / otrisPORTAL 6.0e
* @example
* var size = util.fileSize("c:\\Test.log");
* if (size < 0)
* util.out("File does not exist.");
* else
* util.out(size);
**/
/**
* @memberof util
* @function generateChecksum
* @instance
* @summary Creates a MD5 checksum for the String value.
* @param {string} input The string for that the checksum will be generated
* @returns {string} String with the checksum
* @since DOCUMENTS 4.0c
* @example
* var text = "I'm some type of text";
* var md5 = util.generateChecksum(text);
* if (md5 != "a77c16d60b9939295c0af4c7242b6c02")
* util.out("wrong md5!");
**/
/**
* @memberof util
* @function getDir
* @instance
* @summary Retrieving files and subdirectories of a specified directory.
* @description This function retrieve the content (files, subdirectories) of a specified directory of the PortalServer's file system. It expected two empty Arrays, which the function fill with the filenames and subdirectory names. The names will not contain the full path, only the name itself. This function will not work recursively.
* @param {string} dirname String containing the name of the wanted directory
* @param {any[]} files Empty array for the filenames
* @param {any[]} subDirs Empty array for the subdirectory names
* @returns {string} empty String if successful, the error message in case of any error
* @since ELC 3.60e / otrisPORTAL 6.0e
* @example
* var files = new Array();
* var dirs = new Array();
* util.getDir("c:\\Test", files, dirs);
*
* var i=0;
* for (i=0; i < files.length; i++)
* util.out(files[i])
*
* for (i=0; i < dirs.length; i++)
* util.out(dirs[i])
**/
/**
* @memberof util
* @function getEnvironment
* @instance
* @summary Reads an environment variable of the PortalServer's system.
* @description With this function an environment variable in the server's context can be read.
* @param {string} variableName String with the name of the variable
* @returns {string} Environment value as String
* @since ELC 3.60e / otrisPORTAL 6.0e
* @example
* util.out(util.getEnvironment("HOME"));
**/
/**
* @memberof util
* @function getFileContentAsString
* @instance
* @summary Get the content of a file at the PortalServer's system as string in base64 format.
* @param {string} filePath String with the file path.
* @returns {string} String containing the file content in base64 format.
* @since DOCUMENTS 4.0c
**/
/**
* @memberof util
* @function getQuoted
* @instance
* @summary Returns the input string enclosed in either double or single quotation marks.
* @description This function is designed to simplify the composition of filter expressions for a FileResultSet or an ArchiveFileResultSet. If the input string does not contain any double quotation mark ("), the function returns the input enclosed in double quotation marks. Otherwise the function tests if it can use single quotation marks (') instead. If both quotation styles are already used within the input, the function throws an exception.
*
* @param {string} input
* @returns {string}
* @since DOCUMENTS 4.0b
**/
/**
* @memberof util
* @function getSourceLineInfo
* @instance
* @summary Retrieve the scriptName with the current line no of this methed.
* @description This functions returns the scriptName and line no for debugging or logging purposes
* @returns {string} String with the scriptName and line no
* @since DOCUMENTS 5.0a
**/
/**
* @memberof util
* @function getTmpPath
* @instance
* @summary Get the path to the temporary directory on the Portalserver.
* @returns {string} String containing the complete path to the temporary directory
* @since ELC 3.51 / otrisPORTAL 5.1
* @example
* util.out(util.getTmpPath());
**/
/**
* @memberof util
* @function getUniqueId
* @instance
* @summary Get a unique id from the system.
* @description The length of the id is 40 characters and the id contains only the characters 'a' to 'z'. This unique id can e.g. be used for file names etc.
* @returns {string} String containing the unique id
* @since ELC 3.60 / otrisPORTAL 6.0
* @example
* var uniqueId = util.getUniqueId();
* util.out(uniqueId);
**/
/**
* @memberof util
* @function getUsedPrivateBytes
* @instance
* @summary Returns the current usage of private bytes memory of the documensserver process.
* @returns {number} integer value with the used memory in KBytes
* @since DOCUMENTS 5.0b
**/
/**
* @memberof util
* @function hmac
* @instance
* @summary Generates a hash-based message authentication code (hmac) of a message string using a secret key.
* @description These hash functions are supported:
* <ul>
* <li><code>"sha1"</code></li>
* <li><code>"sha224"</code></li>
* <li><code>"sha256"</code></li>
* <li><code>"sha384"</code></li>
* <li><code>"sha512"</code></li>
* <li><code>"md4"</code></li>
* <li><code>"md5"</code></li>
* </ul>
*
* @param {string} hashfunction Name of the hash function.
* @param {string} key Secret key.
* @param {string} message Message string to be hashed.
* @param {Boolean} [rawOutput] Optional flag:
* If set to <code>true</code>, the function outputs the raw binary representation of the hmac.
* If set to <code>false</code>, the function outputs the hexadecimal representation of the hmac.
* The default value is <code>false</code>.
* @returns {string} String containing the hash-based message authentication code (hmac) of the message (see rawOutput for representation).
* @since DOCUMENTS 5.0a HF2
* @example
* var key = "MySecretKey";
* var msg = "Hello world!";
* var hmac = util.hmac("sha1", key, msg);
* util.out(hmac);
**/
/**
* @memberof util
* @function isEncryptedBlob
* @instance
* @summary Checks, if the current blob is encrypted (Repository encryption) or not.
* @param {string} blobFilePath String containing the path of the file to be checked.
* @returns {boolean} <code>boolean</code> value that indicates if the blob is encrypted.
* @since DOCUMENTS 4.0d HF3
**/
/**
* @memberof util
* @function length_u
* @instance
* @summary Returns the number of characters of a UTF-8 string.
* @description You can use this function in a x64 / UTF-8 server to count the characters in a UTF-8 string.
* Note: for use in x64 / UTF-8 versions
* @param {string} value UTF-8 String of which the number of characters will be counted
* @returns {number} Integer with the length in characters
* @since DOCUMENTS 4.0a HF1
* @example
* var text = "Kรถln is a german city";
* util.out(text.length); // => 22 bytes
* util.out(util.length_u(text)); // => 21 characters
**/
/**
* @memberof util
* @function log
* @instance
* @summary Log a String to the DOCUMENTS server window.
* @description Same as util.out() with additional debugging information (script name and line number) You may output whatever information you want. This function is useful especially for debugging purposes. Be aware that you should run the Portalserver as an application if you want to make use of the <code>out()</code> function, otherwise the output is stored in the Windows Eventlog instead.
* @param {string} output String you want to output to the Portalserver Window
* @returns {any}
* @since ELC 3.50e / otrisPORTAL 5.0e
* @example
* util.log("Hello World");
**/
/**
* @memberof util
* @function makeFullDir
* @instance
* @summary Creates a directory with subdirectories at the PortalServer's file system.
* @description This functions provides a simple method for directory creation on the file system.
* @param {string} dirPath String with the directory path
* @returns {string} empty String if successful, the error message in case of any error
* @since ELC 3.60e / otrisPORTAL 6.0e
* @example
* var errMsg = util.makeFullDir("c:\\log\\ELC");
* if (errMsg.length > 0)
* util.out(errMsg);
* else
* util.out("Ok.");
**/
/**
* @memberof util
* @function makeGACLValue
* @instance
* @summary Makes a valid GACL value from the parameters.
* @description This method helps to create valid GACL values when set by PortalScripting.
* As separator for the single GACL values a <code>\r\n</code> (<code>%CRLF%</code>) will be used. The values will be trimed (leading and ending whitespaces) and multiple values will be removed.
* The method returns a String value in the format <code>\r\n</code> AP1 <code>\r\n</code> AP2 <code>\r\n</code> .... <code>\r\n</code> APx <code>\r\n</code>
*
* @param {any} val1
* @param {any} val2
* @param {any[]} ...restParams
* @returns {string}
* @since DOCUMENTS 5.0c HF2
* @example
* var sep = context.getAutoText("%CRLF%"); // \r\n
* var val1 = ["AP1", "AP2"];
* var val2 = "AP3" + sep + "AP4";
* var val3 = " AP5";
* var val4 = "AP3";
* var gaclVal = util.makeGACLValue(val1, val2, val3, val4);
* util.out(gaclVal);
* =>
*
* AP1
* AP2
* AP3
* AP4
* AP5
*
* <=
**/
/**
* @memberof util
* @function makeHTML
* @instance
* @summary Masks all HTML-elements of a String.
* @description This function masks the following characters for HTML output:
* <table border=1 cellspacing=0>
* <tr><td><code>></code></td><td>> </td></tr>
* <tr><td><code><</code></td><td>< </td></tr>
* <tr><td><code>\n</code></td><td><br> </td></tr>
* <tr><td><code>&</code></td><td>& </td></tr>
* <tr><td><code>"</code></td><td>" </td></tr>
* </table>
*
* If the String is in UTF-8 Format, all UTF-8 characters will be replaced with the according HTML entities.
* @param {string} val String to be masked
* @param {boolean} [isUTF8] boolean flag, if the val is in UTF-8 format
* @returns {string} HTML-String
* @since ELC 3.60e / otrisPORTAL 6.0e
**/
/**
* @memberof util
* @function out
* @instance
* @summary Output a String to the Portalserver window.
* @description You may output whatever information you want. This function is useful especially for debugging purposes. Be aware that you should run the Portalserver as an application if you want to make use of the <code>out()</code> function, otherwise the output is stored in the Windows Eventlog instead.
* @param {string} output String you want to output to the Portalserver Window
* @returns {any}
* @since ELC 3.50e / otrisPORTAL 5.0e
* @example
* util.out("Hello World");
**/
/**
* @memberof util
* @function searchInArray
* @instance
* @summary Search for a String in an Array.
* @description This functions provides a simple search method for Arrays to find the position of a string in an array.
* @param {any[]} theArray Array in that the String will be searched
* @param {string} searchedString String that will be searched
* @param {number} [occurence] Integer that define the wanted position at a multi-occurence of the String in the Array
* @returns {number} Integer with the position of the String in the array, -1 in case of the String isn't found
* @since ELC 3.60e / otrisPORTAL 6.0e
* @example
* enumval[0] = "This";
* enumval[1] = "is";
* enumval[2] = "a";
* enumval[3] = "sample";
* var pos = util.searchInArray(enumval, "is");
* util.out(pos); // should be the value 1
**/
/**
* @memberof util
* @function sha256
* @instance
* @summary Generates the SHA256 hash of any string.
* @param {string} message Message string to be hashed.
* @returns {string} SHA256 hash of the message.
* @since DOCUMENTS 5.0a HF2
**/
/**
* @memberof util
* @function sleep
* @instance
* @summary Let the PortalScript sleep for a defined duration.
* @param {number} duration Integer containing the duration in milliseconds
* @returns {void}
* @since DOCUMENTS 5.0a
**/
/**
* @memberof util
* @function substr_u
* @instance
* @summary Returns a substring of a UTF-8 string.
* @description You can use this function in a x64 / UTF-8 server to get a substring of a UTF-8 string.
* Note: for use in x64 / UTF-8 versions
* @param {string} value UTF-8 String of which the substring is wanted
* @param {number} startIndex int with the 0-based start index of the substring
* @param {number} length int with the length in characters of the substring
* @returns {string} UTF-8 String with the wanted substring
* @since DOCUMENTS 4.0a HF1
* @example
* var text = "Kรถln is a german city";
* util.out(util.substr_u(text, 0, 4)); // => Kรถln
* util.out(util.substr_u(text, 5)); // => is a german city
* // but
* util.out(text.substr(0, 4)); // => Kรถl
**/
/**
* @memberof util
* @function transcode
* @instance
* @summary Transcode a String from encoding a to encoding b.
* @description This method performs an transcoding for a String from a source encoding to a target encoding.
* The following encodings are supported:
* <ul>
* <li><code>Local</code>: The standard system encoding for Windows systems is <code>Windows-1252</code> and for Linux systems <code>ISO-8859-1</code> or <code>UTF-8</code>. </li>
* <li><code>UTF-8</code>: Unicode-characterset as ASCII-compatible 8-Bit-coding. </li>
* <li><code>ISO-8859-1</code>: West-European characterset without Euro-Symbol. </li>
* <li><code>ISO-8859-15</code>: West-European characterset with Euro-Symbol. </li>
* <li><code>Windows-1252</code></li>
* <li><code>Windows-1250</code></li>
* </ul>
*
* @param {string} nameSourceEncoding
* @param {string} text
* @param {string} nameTargetEncoding
* @returns {string}
* @since ELC 3.60d / otrisPORTAL 6.0d
* @example
* var text = "Kรถln is a german city"
* var utf8Text = util.transcode("windows-1252", text, "UTF-8");
* util.out(utf8Text);
* text = util.transcode("UTF-8", utf8Text, "windows-1252");
* util.out(text);
**/
/**
* @memberof util
* @function unlinkFile
* @instance
* @summary Delete a physical file on the server's file system.
* @param {string} filePath String containing the full path and filename to the desired physical file
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51 / otrisPORTAL 5.1
* @example
* var success = util.unlinkFile("c:\\tmp\\tempfile.txt");
**/
/**
* @interface WorkflowStep
* @summary The WorkflowStep class allows access to the according object type of DOCUMENTS.
* @description You may access WorkflowStep objects by the different methods described in the DocFile chapter.
* Note: This class and all of its methods and attributes require a full workflow engine license, it does not work with pure submission lists.
*/
/**
* @memberof WorkflowStep
* @summary String value containing the locking user group of the WorkflowStep.
* @description
* Note: This property requires a full workflow engine license, it does not work with pure submission lists. The property is readonly.
* @member {string} executiveGroup
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof WorkflowStep
* @summary String value containing the type of recipient of the WorkflowStep.
* @description
* Note: This property requires a full workflow engine license, it does not work with pure submission lists. The property is readonly.
* @member {string} executiveType
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof WorkflowStep
* @summary String value containing the locking user of the WorkflowStep.
* @description
* Note: This property requires a full workflow engine license, it does not work with pure submission lists. The property is readonly.
* @member {string} executiveUser
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof WorkflowStep
* @summary String value containing the unique internal ID of the first outgoing ControlFlow.
* @description
* Note: This property requires a full workflow engine license, it does not work with pure submission lists. The property is readonly.
* @member {string} firstControlFlow
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof WorkflowStep
* @summary String value containing the unique internal ID of the WorkflowStep.
* @description
* Note: This property requires a full workflow engine license, it does not work with pure submission lists. The property is readonly.
* @member {string} id
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof WorkflowStep
* @summary String value containing the technical name of the WorkflowStep.
* @description
* Note: This property requires a full workflow engine license, it does not work with pure submission lists. The property is readonly.
* @member {string} name
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof WorkflowStep
* @summary String value containing the status of the WorkflowStep.
* @description
* Note: This property requires a full workflow engine license, it does not work with pure submission lists. The property is readonly.
* @member {string} status
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof WorkflowStep
* @summary String value containing the unique internal ID of the Workflow template.
* @description
* Note: This property requires a full workflow engine license, it does not work with pure submission lists. The property is readonly.
* @member {string} templateId
* @instance
* @since ELC 3.50 / otrisPORTAL 5.0
**/
/**
* @memberof WorkflowStep
* @function forwardFile
* @instance
* @summary Forward the file to its next WorkflowStep.
* @description This requires the internal ID (as a String value) of the ControlFlow you want the file to pass through. The optional comment parameter will be stored as a comment in the file's monitor.
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
*
* The current user's permissions are not checked when using this function!
* @param {string} controlFlowId String value containing the internal ID of the ControlFlow you want to pass through.
* @param {string} [comment] optional String value containing your desired comment for the file's monitor.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50e / otrisPORTAL 5.0e
**/
/**
* @memberof WorkflowStep
* @function getAttribute
* @instance
* @summary Get the String value of an attribute of the WorkflowStep.
* @description
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @param {string} attribute String containing the name of the desired attribute
* @returns {string} String containing the value of the desired attribute
* @since ELC 3.51e / otrisPORTAL 5.1e
**/
/**
* @memberof WorkflowStep
* @function getControlFlows
* @instance
* @summary Retrieve an iterator representing a list of all outgoing ControlFlows of the WorkflowStep.
* @description
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @returns {ControlFlowIterator} ControlFlowIterator containing the outgoing ControlFlows of the current WorkflowStep object.
* @since ELC 3.51e / otrisPORTAL 5.1e
**/
/**
* @memberof WorkflowStep
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @description
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @returns {string} Text of the last error as String
* @since ELC 3.50 / otrisPORTAL 5.0
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof WorkflowStep
* @function getOID
* @instance
* @summary Returns the object-id.
* @description
* Since DOCUMENTS 5.0 (new parameter oidLow)
* @param {boolean} [oidLow] Optional flag:
* If <code>true</code> only the id of the filetype object (<code>m_oid</code>) will be returned.
* If <code>false</code> the id of the filetype object will be returned together with the id of the corresponding class in the form <code>class-id:m_oid</code>.
* The default value is <code>false</code>.
* @returns {string} <code>String</code> with object-id
* @since ELC 3.60c / otrisPORTAL 6.0c
**/
/**
* @memberof WorkflowStep
* @function getWorkflowName
* @instance
* @summary Retrieve the name of the workflow, the WorkflowStep belongs to.
* @description
* Note: This function is only available for workflows, but not submission lists.
* @returns {string} String containing the workflow name
* @since ELC 3.60d / otrisPORTAL 6.0d
* @see [WorkflowStep.getWorkflowVersion]{@link WorkflowStep#getWorkflowVersion}
**/
/**
* @memberof WorkflowStep
* @function getWorkflowProperty
* @instance
* @summary Retrieve a property value of the workflow action, the WorkflowStep belongs to.
* @description
* Note: This function is only available for workflows, but not submission lists.
* @param {string} propertyName String containing the name of the desired property
* @returns {string} String containing the property value
* @since DOCUMENTS 4.0a
**/
/**
* @memberof WorkflowStep
* @function getWorkflowVersion
* @instance
* @summary Retrieve the version number of the workflow, the WorkflowStep belongs to.
* @description
* Note: This function is only available for workflows, but not submission lists.
* @returns {string} String containing the workflow version number
* @since ELC 3.60d / otrisPORTAL 6.0d
* @see [WorkflowStep.getWorkflowName]{@link WorkflowStep#getWorkflowName}
**/
/**
* @memberof WorkflowStep
* @function setAttribute
* @instance
* @summary Set the String value of an attribute of the WorkflowStep to the desired value.
* @description
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @param {string} attribute String containing the name of the desired attribute
* @param {string} value String containing the desired value of the attribute
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51e / otrisPORTAL 5.1e
**/
/**
* @memberof WorkflowStep
* @function setNewExecutiveGroup
* @instance
* @summary Reassign the current WorkflowStep object to the given user group.
* @description
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @param {string} accessProfileName String containing the technical name of the access profile.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0c
* @example
* var f = context.file;
* var step = f.getCurrentWorkflowStep();
* if (!step)
* step = f.getFirstLockingWorkflowStep();
* if (!step)
* util.out("File is not in a workflow.");
*
* if (!step.setNewExecutiveGroup("AccessProfile1"))
* util.out(step.getLastError());
**/
/**
* @memberof WorkflowStep
* @function setNewExecutiveUser
* @instance
* @summary Reassigns the current WorkflowStep object to the given user.
* @description
* Note: This function requires a full workflow engine license, it does not work with pure submission lists.
* @param {string} loginUser String containing the login name of the desired user.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.50e / otrisPORTAL 5.0e
**/
/**
* @interface WorkflowStepIterator
* @summary The WorkflowStepIterator class has been added to the DOCUMENTS PortalScripting API to gain full control over a file's workflow by scripting means.
* @description You may access WorkflowStepIterator objects by the getAllLockingWorkflowSteps() method described in the DocFile chapter.
* Note: This class and all of its methods and attributes require a full workflow engine license, it does not work with pure submission lists.
* @since ELC 3.51e / otrisPORTAL 5.1e
*/
/**
* @memberof WorkflowStepIterator
* @function first
* @instance
* @summary Retrieve the first WorkflowStep object in the WorkflowStepIterator.
* @returns {WorkflowStep} WorkflowStep or <code>null</code> in case of an empty WorkflowStepIterator
* @since ELC 3.51e / otrisPORTAL 5.1e
**/
/**
* @memberof WorkflowStepIterator
* @function next
* @instance
* @summary Retrieve the next WorkflowStep object in the WorkflowStepIterator.
* @returns {WorkflowStep} WorkflowStep or <code>null</code> if end of WorkflowStepIterator is reached.
* @since ELC 3.51e / otrisPORTAL 5.1e
**/
/**
* @memberof WorkflowStepIterator
* @function size
* @instance
* @summary Get the amount of WorkflowStep objects in the WorkflowStepIterator.
* @returns {number} integer value with the amount of WorkflowStep objects in the WorkflowStepIterator
* @since ELC 3.51e / otrisPORTAL 5.1e
**/
/**
* @class XMLExport
* @classdesc The XMLExport class allows to export DOCUMENTS elements as an XML file by scripting means.
* The exported XML structure may then, for example, be used for further manipulation by an external ERP environment. The following elements can be exported:
* <ul>
* <li>DocFile</li>
* <li>PortalScript </li>
* <li>Filetype </li>
* <li>Folder</li>
* <li>Workflow </li>
* <li>Distribution List </li>
* <li>Editor (Fellow) </li>
* <li>AccessProfile</li>
* <li>Alias </li>
* <li>Filing Plan </li>
* <li>Outbar </li>
* <li>DocumentsSettings </li>
* <li>CustomProperties </li>
* </ul>
*
* The XML files may also be reimported into another (or the same) Portal environment by the Docimport application for DocFile objects and by the XML-import of DOCUMENTS Manager for the remaining elements, respectively.
* Since DOCUMENTS 4.0c available for PortalScript, Filetype, Folder, Workflow, Distribution List, Editor, AccessProfile, Alias and Filing Plan
* Since DOCUMENTS 4.0d available for Outbar
* Since DOCUMENTS 4.0e available for DocumentsSettings
* Since DOCUMENTS 5.0d available for CustomProperties
* @since ELC 3.51b / otrisPORTAL 5.1b available for DocFile
* @example
* var f = context.file;
* if (f)
* {
* // create a new XMLExport
* var xml = new XMLExport("c:\\tmp\\" + f.getAutoText("id") + ".xml");
* xml.addFile(f); // add the current file to the export
* xml.saveXML(); // perform the export operation
* var xmlString = xml.getXML(); // get XML as String for further use
* xml.clearXML(); // empty XMLExport object
* }
* @summary Create a new instance of the XMLExport class.
* @description The constructor is neccessary to initialize the XMLExport object with some basic settings. The pathFileName parameter is mandatory, the path must be an existing directory structure, and the target file should not yet exist in that directory structure.
* Since ELC 3.51b / otrisPORTAL 5.1b
* Since DOCUMENTS 4.0c (new parameter exportDocFile)
* @param {string} pathFileName String containing full path and file name of the desired target output XML file
* @param {boolean} [exportDocFile] Optional boolean value:
* <ul>
* <li><code>true</code> indicating that the created XMLExport instance is only able to export DocFile objects; </li>
* <li><code>false</code> indicating the created XMLExport instance is able to export the following elements:
* <ul>
* <li>PortalScript </li>
* <li>Filetype </li>
* <li>Folder</li>
* <li>Workflow </li>
* <li>Distribution List </li>
* <li>Editor (Fellow) </li>
* <li>AccessProfile</li>
* <li>Alias </li>
* <li>Filing Plan </li>
* <li>Outbar </li>
* <li>DocumentsSettings </li>
* <li>CustomProperties </li>
* </ul>
* </li>
* </ul>
* The default value is <code>true</code>.
*/
/**
* @memberof XMLExport
* @function addAccessProfile
* @instance
* @summary Add the desired access profile to the XMLExport.
* @param {any} accessProfile The desired access profile to be added to the XML output and specified as follows:
* <ul>
* <li>String containing the technical name of the access profile </li>
* <li>AccessProfile object </li>
* </ul>
*
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0c
* @example
* var path = "C:\\temp\\expAccessProfile.xml";
* var xmlExp = new XMLExport(path, false);
* var success = xmlExp.addAccessProfile("AccessProfile1");
* if (success)
* xmlExp.saveXML();
* else
* util.out(xmlExp.getLastError());
**/
/**
* @memberof XMLExport
* @function addAlias
* @instance
* @summary Add the desired alias to the XMLExport.
* @param {string} aliasName String value containing the technical name of the alias to be added to the XML output.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0c
* @example
* var xmlExp = new XMLExport("C:\\temp\\expAlias.xml", false);
* var success = xmlExp.addAlias("alias1");
* if (success)
* xmlExp.saveXML();
* else
* util.out(xmlExp.getLastError());
**/
/**
* @memberof XMLExport
* @function addCustomProperty
* @instance
* @summary Add the desired global custom property to the XMLExport.
* @param {string} propName The technical name of the desired global custom property to be added to the XML output.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 5.0d
* @example
* var path = "C:\\temp\\expCustomProperty.xml";
* var xmlExp = new XMLExport(path, false);
* var success = xmlExp.addCustomProperty("testProp");
* if (success)
* xmlExp.saveXML();
* else
* util.out(xmlExp.getLastError());
**/
/**
* @memberof XMLExport
* @function addDistributionList
* @instance
* @summary Add the desired distribution list to the XMLExport.
* @param {string} distributionListName String containing the name of the distribution list to be added to the XML output.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0c
* @example
* var path = "C:\\temp\\expDistributionList.xml";
* var xmlExp = new XMLExport(path, false);
* var success = xmlExp.addDistributionList("DistributionList1");
* if (success)
* xmlExp.saveXML();
* else
* util.out(xmlExp.getLastError());
**/
/**
* @memberof XMLExport
* @function addDocumentsSettings
* @instance
* @summary Add the DOCUMENTS settings data to the XMLExport.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0e
**/
/**
* @memberof XMLExport
* @function addFellow
* @instance
* @summary Add the desired editor (fellow) to the XMLExport.
* @description
* Since DOCUMENTS 4.0c HF2 (new parameter includePrivateFolders)
* @param {any} editor The editor to be added to the XML output and specified as follows:
* <ul>
* <li>String containing the login name of the editor. </li>
* <li>SystemUser object representing the editor. </li>
* </ul>
*
* @param {boolean} [includePrivateFolders] boolean value indicating whether to export the private folders of the fellow
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0c
* @example
* var path = "C:\\temp\\expFellow.xml";
* var xmlExp = new XMLExport(path, false);
* var success = xmlExp.addFellow("editor1");
* if (success)
* xmlExp.saveXML();
* else
* util.out(xmlExp.getLastError());
**/
/**
* @memberof XMLExport
* @function addFile
* @instance
* @summary Add the desired DocFile object to the XMLExport.
* @param {DocFile} docFile An object of the DocFile class which should be added to the XML output
* @param {any} [exportCondition] Optional export conditions specified as follows:
* <ul>
* <li>boolean value indicating whether the file id should be exported as update key. </li>
* <li>XMLExportDescription object defining serveral conditions for the exporting process of the DocFile object. </li>
* </ul>
* The default value is true.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51b / otrisPORTAL 5.1b
* @example
* var path = "C:\\temp\\expDocFile.xml";
* var xmlExp = new XMLExport(path, true);
* var success = xmlExp.addFile(context.file);
* if (success)
* xmlExp.saveXML();
* else
* util.out(xmlExp.getLastError());
**/
/**
* @memberof XMLExport
* @function addFileType
* @instance
* @summary Add the desired file type to the XMLExport.
* @description The XML output is able to update the same file type (Update-XML).
* @param {string} fileTypeName The technical name of the file type to be added to the XML output.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0c
* @example
* var path = "C:\\temp\\expFileType.xml";
* var xmlExp = new XMLExport(path, false);
* var success = xmlExp.addFileType("Filetype1");
* if (success)
* xmlExp.saveXML();
* else
* util.out(xmlExp.getLastError());
**/
/**
* @memberof XMLExport
* @function addFilingPlan
* @instance
* @summary Add the desired filing plan to the XMLExport.
* @description The XML output is able to update the same filing plan (Update-XML).
* @param {string} filingPlanName String containing the technical name of the filing plan to be added to the XML output.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0c
* @example
* var path = "C:\\temp\\expFilingPlan.xml";
* var xmlExp = new XMLExport(path, false);
* var success = xmlExp.addFilingPlan("myFilingPlan");
* if (success)
* xmlExp.saveXML();
* else
* util.out(xmlExp.getLastError());
**/
/**
* @memberof XMLExport
* @function addFolder
* @instance
* @summary Add the desired Folder object to the XMLExport.
* @description This function is able to add the folder structure or the files in the folder to the XMLExport.
* @param {Folder} folder The Folder object to be added to the XML output.
* @param {boolean} exportStructure boolean value indicating whether to export the folder structure or the files in the folder, on which the current user has read rights. If you want to export the files in the folder, an XMLExport instance being able to export DocFile should be used.
* @param {any} exportCondition The export conditions can be specified as follows:
* <ul>
* <li>boolean value
* <ul>
* <li>indicating whether the file id should be exported as update key in case of exporting files in the folder; </li>
* <li>indicating whether the subfolders should be exported in case of exporting the folder structure. </li>
* </ul>
* </li>
* <li>XMLExportDescription object defining serveral conditions for the exporting process of the files in the folder. </li>
* </ul>
*
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0c
* @example
* var xmlExpFiles = new XMLExport("C:\\temp\\expFolderFiles.xml", true); // for exporting the files in the folder
* var xmlExpStructure = new XMLExport("C:\\temp\\expFolderStructure.xml", false); // for exporting the folder structure
* var it = context.getFoldersByName("myFolder", "dynamicpublic");
* var folder = it.first();
* if (folder)
* {
* var success = xmlExpFiles.addFolder(folder, false); // add the files in the folder to the XML output
* if (success)
* xmlExpFiles.saveXML();
*
* success = xmlExpStructure.addFolder(folder, true, true); // add the folder structure to the XML output
* if (success)
* xmlExpStructure.saveXML();
* }
**/
/**
* @memberof XMLExport
* @function addNumberRange
* @instance
* @summary Add the desired number range alias to the XMLExport.
* @param {string} name String value containing the technical name of the number range to be added to the XML output.
* @param {boolean} [withCounter] boolean value indicating whether to export the actual counter value of the number range
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d HF1
**/
/**
* @memberof XMLExport
* @function addOutbar
* @instance
* @summary Add the desired outbar to the XMLExport.
* @param {string} outbarName String value containing the technical name of the outbar to be added to the XML output.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d
* @example
* var xmlExp = new XMLExport("C:\\temp\\expOutbar.xml", false);
* var success = xmlExp.addOutbar("outbar1");
* if (success)
* xmlExp.saveXML();
* else
* util.out(xmlExp.getLastError());
**/
/**
* @memberof XMLExport
* @function addPartnerAccount
* @instance
* @summary Add the desired user account (not fellow) to the XMLExport.
* @param {any} userAccount The user account to be added to the XML output and specified as follows:
* <ul>
* <li>String containing the login name of the user account. </li>
* <li>SystemUser object representing the user account. </li>
* </ul>
*
* @param {boolean} [includePrivateFolders] boolean value indicating whether to export the private folders of the user account
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 5.0 HF2
* @example
* var path = "C:\\temp\\expUserAccount.xml";
* var xmlExp = new XMLExport(path, false);
* var success = xmlExp.addPartnerAccount("login1");
* if (success)
* xmlExp.saveXML();
* else
* util.out(xmlExp.getLastError());
**/
/**
* @memberof XMLExport
* @function addPortalScript
* @instance
* @summary Add all PortalScripts with the desired name pattern to the XMLExport.
* @description
* Note: The XML files exported in DOCUMENTS 5.0 format are incompatible with DOCUMENTS 4.0.
* Since DOCUMENTS 5.0 HF1 (default format is 5.0)
* @param {string} namePattern The name pattern of the PortalScripts to be added to the XML output.
* @param {string} [format] Optional String value defining the desired export format. The following formats are available:
* <ul>
* <li>4.0 (DOCUMENTS 4.0) </li>
* <li>5.0 (DOCUMENTS 5.0) </li>
* </ul>
* The default value is "5.0".
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0c
* @example
* var path = "C:\\temp\\expPortalScript.xml";
* var xmlExp = new XMLExport(path, false);
* var success = xmlExp.addPortalScript("test*", "4.0");
* if (success)
* xmlExp.saveXML();
* else
* util.out(xmlExp.getLastError());
**/
/**
* @memberof XMLExport
* @function addPortalScriptCall
* @instance
* @summary Defines a PortalScript, that will be executed after the XML-import.
* @description This method does not export the content of a PortalScript (see XMLExport.addPortalScript()), but executes a PortalScript at the end of the XML-Import of the whole xml file.
* @param {string} nameScript The name of the PortalScript, that should be executed.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 5.0c HF1
* @example
* var path = "C:\\temp\\expPortalScript.xml";
* var xmlExp = new XMLExport(path, false);
* ...
* var success = xmlExp.addPortalScriptCall("updateSolution");
* ...
* if (success)
* xmlExp.saveXML();
* else
* util.out(xmlExp.getLastError());
**/
/**
* @memberof XMLExport
* @function addPortalScriptsFromCategory
* @instance
* @summary Add all PortalScripts belonging to the desired category to the XMLExport.
* @description
* Note: The XML files exported in DOCUMENTS 5.0 format are incompatible with DOCUMENTS 4.0.
* Since DOCUMENTS 5.0 HF1 (default format is 5.0)
* @param {string} nameCategory The category name of the PortalScripts to be added to the XML output.
* @param {string} [format] Optional String value defining the desired export format. The following formats are available:
* <ul>
* <li>4.0 (DOCUMENTS 4.0) </li>
* <li>4.0 (DOCUMENTS 5.0) </li>
* </ul>
* The default value is "5.0".
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0d HF1
* @example
* var path = "C:\\temp\\expPortalScript.xml";
* var xmlExp = new XMLExport(path, false);
* var success = xmlExp.addPortalScriptsFromCategory("testScripts", "5.0");
* if (success)
* xmlExp.saveXML();
* else
* util.out(xmlExp.getLastError());
**/
/**
* @memberof XMLExport
* @function addSystemUser
* @instance
* @summary Add the desired SystemUser (user account or fellow) to the XMLExport.
* @param {any} systemUser The SystemUser to be added to the XML output and specified as follows:
* <ul>
* <li>String containing the login name of the SystemUser. </li>
* <li>SystemUser object representing the user account. </li>
* </ul>
*
* @param {boolean} [includePrivateFolders] boolean value indicating whether to export the private folders of the SystemUser
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 5.0 HF2
* @example
* var path = "C:\\temp\\expSystemUser.xml";
* var xmlExp = new XMLExport(path, false);
* var success = xmlExp.addSystemUser("login1");
* if (success)
* xmlExp.saveXML();
* else
* util.out(xmlExp.getLastError());
**/
/**
* @memberof XMLExport
* @function addWorkflow
* @instance
* @summary Add the desired workflow to the XMLExport.
* @param {string} workflowName String containing the technical name and optional the version number of the workflow to be added to the XML output. The format of the workflowName is <code>technicalName</code>[-version]. If you don't specify the version of the workflow, the workflow with the highest workflow version number will be used. If you want to add a specific version, you have to use technicalName-version e.g. "Invoice-2" as workflowName.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since DOCUMENTS 4.0c
* @example
* var path = "C:\\temp\\expWorkflow.xml";
* var xmlExp = new XMLExport(path, false);
* xmlExp.addWorkflow("Invoice"); // add the latest version of the workflow "Invoice"
* xmlExp.addWorkflow("Invoice-2"); // add the version 2 of the workflow "Invoice"
* xmlExp.saveXML();
**/
/**
* @memberof XMLExport
* @function clearXML
* @instance
* @summary Remove all references to DocFile objects from the XMLExport object.
* @description After the execution of this method the XMLExport object is in the same state as right after its construction.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51b / otrisPORTAL 5.1b
**/
/**
* @memberof XMLExport
* @function getLastError
* @instance
* @summary Function to get the description of the last error that occurred.
* @returns {string} Text of the last error as String
* @since ELC 3.51b / otrisPORTAL 5.1b
* @see [DocFile.getLastError]{@link DocFile#getLastError}
**/
/**
* @memberof XMLExport
* @function getXML
* @instance
* @summary Retrieve the XML structure of the DocFile objects already added to the XMLExport.
* @description The XML structure is returned as a String, so it is possible to further manipulate it (e.g. with the E4X scripting extension (not discussed in this documentation) before outputting it to its final destination.
* @returns {string} String containing the complete XMl structure of the XMLExport
* @since ELC 3.51b / otrisPORTAL 5.1b
**/
/**
* @memberof XMLExport
* @function saveXML
* @instance
* @summary Performs the final save process of the XML structure.
* @description Not earlier than when executing this instruction the XML file is created in the target file path.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error
* @since ELC 3.51b / otrisPORTAL 5.1b
**/
/**
* @class XMLExportDescription
* @classdesc The XMLExportDescription class has been added to the DOCUMENTS PortalScripting API to improve the XML Export process of DOCUMENTS files by scripting means.
* For instance this allows to use different target archives for each file as well as to influence the archiving process by the file's contents itself. The XMLExportDescription object can only be used as parameter for the method XMLExport.addFile(XMLExportDescription)
* @since DOCUMENTS 4.0c
* @summary Create a new XMLExportDescription object.
* @description Like in other programming languages you create a new object with the <code>new</code> operator (refer to example below).
* Since DOCUMENTS 4.0c
* @see [XMLExport.addFile]{@link XMLExport#addFile}
* @example
* var docFile = context.file;
* if (!docFile)
* {
* // error handling
* }
*
* var desc = new XMLExportDescription();
* desc.exportFileId = true;
* desc.exportOwner = true;
* desc.exportLastModifiedBy = true;
* desc.exportCreatedAt = true;
* desc.exportLastModifiedAt = true;
*
* // create a new XMLExport
* var xml = new XMLExport("c:\\tmp\\" + docFile.getAutoText("id") + ".xml");
* xml.addFile(docFile, desc); // add the current file to the export
* xml.saveXML(); // perform the export operation
*/
/**
* @memberof XMLExportDescription
* @summary boolean value whether export the create timestamp of the file.
* @member {boolean} exportCreatedAt
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof XMLExportDescription
* @summary boolean value whether export the id of the file.
* @member {boolean} exportFileId
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof XMLExportDescription
* @summary boolean value whether export the timestamp of the last modification of the file.
* @member {boolean} exportLastModifiedAt
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof XMLExportDescription
* @summary boolean value whether export the name of the last editor of the file.
* @member {boolean} exportLastModifiedBy
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @memberof XMLExportDescription
* @summary boolean value whether export the name of the owner of the file.
* @member {boolean} exportOwner
* @instance
* @since DOCUMENTS 4.0c
**/
/**
* @class XMLHTTPRequest
* @classdesc The XMLHTTPRequest class represents a HTTP request.
* Though the name of this class traditionally refers to XML, it can be used to transfer arbitrary strings or binary data. The interface is based on the definition of the class <code>IXMLHTTPRequest</code> from MSXML. As http-library the libcurl is used. To send a HTTP request the following steps are needed:
* <ul>
* <li>Creating an instance of this class. </li>
* <li>Initializing the request via open(). Possibly also adding header data by means of addRequestHeader(). </li>
* <li>Sending the request via send(). </li>
* <li>In case of asynchronous request checking for completion of the request operation via XMLHTTPRequest.readyState. </li>
* <li>Evaluating the result via e.g. XMLHTTPRequest.status, XMLHTTPRequest.response and getAllResponseHeaders().</li>
* </ul>
*
* @since DOCUMENTS 4.0
* @example
* // synchron
* var xmlHttp = new XMLHTTPRequest();
* var async = false;
* var url = "http://localhost:11001/";
* xmlHttp.open("GET", url + "?wsdl", async);
* xmlHttp.send();
* util.out(xmlHttp.response);
* @example
* // asynchron
* var xmlHttp = new XMLHTTPRequest();
* var async = true;
* var url = "http://localhost:11001/";
* xmlHttp.open("GET", url + "?wsdl", async);
* xmlHttp.send();
* while(xmlHttp.status != xmlHttp.COMPLETED) {
* util.sleep(500); // sleep 500 ms
* }
* util.out(xmlHttp.response);
* @summary Create a new XMLHTTPRequest object.
* @description
* Note: On windows OS: If no proxy is specified as first parameter, the proxy settings of the Internet Explorer and and the WinHTTP configuration will be checked, and a defined proxy setting will be used.
* Since DOCUMENTS 4.0
* Since DOCUMENTS 5.0c (on windows OS support of system proxy configuration)
* @param {string} [proxy] Optional string value specifying the hostname of the proxy server being resolvable by the nameserver. On windows OS: If this parameter is not specified, the windows proxy configuration will be used. E.g. the proxy server specified in Internet Explorer is used in the <em>registry</em>.
* @param {number} [proxyPort] Optional number of the port on which the <em>proxy</em> accepts requests.
* @param {string} [proxyUser] Optional string value specifying the desired login name for the proxy
* @param {string} [proxyPasswd] Optional string value specifying the password for logging in to the proxy
* @see [XMLHTTPRequest.canProxy]{@link XMLHTTPRequest#canProxy}
*/
/**
* @memberof XMLHTTPRequest
* @summary Flag indicating whether asynchronous requests are possible on the used plattform.
* @description
* Note: This property is readonly.
* @member {boolean} canAsync
* @instance
* @since DOCUMENTS 4.0
**/
/**
* @memberof XMLHTTPRequest
* @summary Flag indicating whether the implementation on the used plattform allows the direct specifying of a proxy server.
* @description
* Note: This property is readonly.
* @member {boolean} canProxy
* @instance
* @since DOCUMENTS 4.0
**/
/**
* @memberof XMLHTTPRequest
* @summary The constant 4 for XMLHTTPRequest.readyState.
* @description In this state the request is completed. All the data are available now.
*
* Note: This property is readonly.
* @member {number} COMPLETED
* @instance
* @since DOCUMENTS 4.0
**/
/**
* @memberof XMLHTTPRequest
* @summary Optional File size indicator for sending pure sequential files.
* @description When uploading files, the send() function usually detects the file size and forwards it to lower APIs. This is helpful in most cases, because old simple HTTP servers do not support the transfer mode "chunked". Web services may reject uploads without an announced content-length, too.
*
* However, the auto-detection will fail, if a given file is not rewindable (a named pipe, for instance). To avoid errors this property should be set before sending such a special file. After the transmission the property should be either set to "-1" or deleted.
*
* The value is interpreted in the following way.
* <ul>
* <li>Values > 0 specify a precise file size in bytes.</li>
* <li>The value -1 has the same effect as leaving the property undefined (enable auto-detection).</li>
* <li>The value -2 disables file size detection and enforces a chunked transfer.</li>
* </ul>
*
*
* Note: This property serves as a hidden optional parameter to the send() function. On new objects it is undefined. Assigning an incorrect value >= 0 may trigger deadlocks or timeouts.
* @member {number} FileSizeHint
* @instance
* @since DOCUMENTS 5.0c
* @see [send]{@link send}
**/
/**
* @memberof XMLHTTPRequest
* @summary The constant 3 for XMLHTTPRequest.readyState.
* @description In this state the request is partially completed. This means that some data has been received.
*
* Note: This property is readonly.
* @member {number} INTERACTIVE
* @instance
* @since DOCUMENTS 4.0
**/
/**
* @memberof XMLHTTPRequest
* @summary The constant 1 for XMLHTTPRequest.readyState.
* @description In this state the object has been initialized, but not sent yet.
*
* Note: This property is readonly.
* @member {number} NOTSENT
* @instance
* @since DOCUMENTS 4.0
**/
/**
* @memberof XMLHTTPRequest
* @summary The current state of the asynchronous request.
* @description The following states are available:
* <ul>
* <li>XMLHTTPRequest.UNINITIALIZED = 0 : the method open() has not been called. </li>
* <li>XMLHTTPRequest.NOTSENT = 1: the object has been initialized, but not sent yet. </li>
* <li>XMLHTTPRequest.SENT = 2 : the object has been sent. No data is available yet. </li>
* <li>XMLHTTPRequest.INTERACTIVE = 3: the request is partially completed. This means that some data has been received. </li>
* <li>XMLHTTPRequest.COMPLETED = 4: the request is completed. All the data are available now.</li>
* </ul>
*
* Note: This property is readonly.
* @member {number} readyState
* @instance
* @since DOCUMENTS 4.0
**/
/**
* @memberof XMLHTTPRequest
* @summary The response received from the HTTP server or null if no response is received.
* @description
* Note: This property is readonly. Starting with DOCUMENTS 5.0c its data type is influenced by the optional property responseType. The default type is String. For requests with an attached responseFile this value can be truncated after a few kBytes.
* @member {any} response
* @instance
* @since DOCUMENTS 4.0
* @see [responseType,responseFile]{@link responseType,responseFile}
* @example
* var xmlHttp = new XMLHTTPRequest();
* var async = false;
* var url = "http://localhost:11001/";
* xmlHttp.open("POST", url, async);
* if (xmlHttp.send(content))
* util.out(xmlHttp.response);
**/
/**
* @memberof XMLHTTPRequest
* @summary An optional writable file for streaming a large response.
* @description To achieve an efficient download scripts can create a writable <code>File</code> an attach it to the request. The complete response will then be written into this file. The value of the <code>response</code> property, however, will be truncated after the first few kBytes.
*
* Note: On new objects this property is undefined.
*
* When send() is called, the request takes exclusive ownership of the attached file. The property will then be reset to null. Even in asynchronous mode send() seems to close the file immediately. In fact, send() detaches the native file handle from the JavaScript object to ensure exclusive access.
*
* Received content will be written to the file, disregarding the HTTP status.
* @member {File} responseFile
* @instance
* @since DOCUMENTS 5.0c
* @see [response,responseType,File]{@link response,responseType,File}
* @example
* var url = "http://localhost:8080/documents/img/documents/skin/black/module/dashboard/48/view.png";
* var req = new XMLHTTPRequest;
* req.open("GET", url);
*
* var file = new File("E:\\test\\downloaded.png", "wb");
* if(!file.ok())
* return "Cannot open response file for writing";
* req.responseFile = file;
* req.send();
* return req.status;
**/
/**
* @memberof XMLHTTPRequest
* @summary Preferred output format of the response property (optional).
* @description By default, the object expects text responses and stores them in a String. If the application expects binary data, it may request an ArrayBuffer by setting this property to "arraybuffer".
* Note: On new objects this property is undefined. ArrayBuffer responses are created only once after each request. If a script changes the received buffer, the response property will reflect these changes until a new request starts.
* @member {string} responseType
* @instance
* @since DOCUMENTS 5.0c
* @see [response,responseFile]{@link response,responseFile}
**/
/**
* @memberof XMLHTTPRequest
* @summary The constant 2 for XMLHTTPRequest.readyState.
* @description In this state the object has been sent. No data is available yet.
*
* Note: This property is readonly.
* @member {number} SENT
* @instance
* @since DOCUMENTS 4.0
**/
/**
* @memberof XMLHTTPRequest
* @summary The HTTP status code of the request.
* @description
* Note: This property is readonly.
* @member {number} status
* @instance
* @since DOCUMENTS 4.0
* @see [XMLHTTPRequest.statusText]{@link XMLHTTPRequest#statusText}
**/
/**
* @memberof XMLHTTPRequest
* @summary The HTTP status text of the request.
* @description
* Note: This property is readonly.
* @member {string} statusText
* @instance
* @since DOCUMENTS 4.0
* @see [XMLHTTPRequest.status]{@link XMLHTTPRequest#status}
**/
/**
* @memberof XMLHTTPRequest
* @summary The constant 0 for XMLHTTPRequest.readyState.
* @description In this state the method open() has not been called.
*
* Note: This property is readonly.
* @member {number} UNINITIALIZED
* @instance
* @since DOCUMENTS 4.0
**/
/**
* @memberof XMLHTTPRequest
* @summary Constant for CA Certificate verification if using HTTPS.
* @description This option activate the verification of the host.
*
* Note: This property is readonly.
* @member {number} VERIFYHOST
* @instance
* @since DOCUMENTS 5.0c
* @see [XMLHTTPRequest.setCAInfo]{@link XMLHTTPRequest#setCAInfo}
**/
/**
* @memberof XMLHTTPRequest
* @summary Constant for CA Certificate verification if using HTTPS.
* @description This option activate the verification of the certificate chain.
*
* Note: This property is readonly.
* @member {number} VERIFYPEER
* @instance
* @since DOCUMENTS 5.0c
* @see [XMLHTTPRequest.setCAInfo]{@link XMLHTTPRequest#setCAInfo}
**/
/**
* @memberof XMLHTTPRequest
* @function abort
* @instance
* @summary Abort an asynchronous request if it already has been sent.
* @returns {boolean} <code>true</code> if successful, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0
* @example
* var xmlHttp = new XMLHTTPRequest();
* var async = true;
* var url = "http://localhost:11001/";
* xmlHttp.open("POST", url, async);
* xmlHttp.send(content);
* var timeout = 3000; // milliseconds
* var idle = 200; // 200 ms
* var timeoutTS = (new Date()).getTime() + timeout;
* while (httpCon.readyState != httpCon.COMPLETED) {
* if ((new Date()).getTime() > timeoutTS) {
* xmlHttp.abort();
* xmlHttp = null;
* }
* util.sleep(idle);
* }
* if (xmlHttp)
* util.out(xmlHttp.status);
**/
/**
* @memberof XMLHTTPRequest
* @function addRequestHeader
* @instance
* @summary Add a HTTP header to the request to be sent.
* @description
* Note: The request must be initialized via open() before.
* @param {string} name String specifying the header name.
* @param {string} value String specifying the header value.
* @returns {boolean} <code>true</code> if the header was added successfully, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0
* @example
* var xmlHttp = new XMLHTTPRequest();
* var async = true;
* var url = "http://localhost:11001/";
* xmlHttp.open("POST", url, async);
* xmlHttp.addRequestHeader("Content-Type", "text/xml");
* xmlHttp.send(c);
**/
/**
* @memberof XMLHTTPRequest
* @function getAllResponseHeaders
* @instance
* @summary Get all response headers as a string.
* @description Each entry is in a separate line and has the form 'name:value'.
*
* @returns {string}
* @since DOCUMENTS 4.0
* @example
* var xmlHttp = new XMLHTTPRequest();
* var async = false;
* var url = "http://localhost:11001/";
* xmlHttp.open("POST", url, async);
* if (xmlHttp.send(content))
* util.out(xmlHttp.getAllResponseHeaders());
**/
/**
* @memberof XMLHTTPRequest
* @function getResponseHeader
* @instance
* @summary Get the value of the specified response header.
* @param {string} name String specifying the response header name.
* @returns {string} String with the value of the response header, an empty string in case of any error.
* @since DOCUMENTS 4.0
* @example
* var xmlHttp = new XMLHTTPRequest();
* var async = false;
* var url = "http://localhost:11001/";
* xmlHttp.open("POST", url, async);
* if (xmlHttp.send(content))
* util.out(xmlHttp.getResponseHeader("Content-Type"));
**/
/**
* @memberof XMLHTTPRequest
* @function open
* @instance
* @summary Initialize a HTTP request.
* @param {string} method String specifying the used HTTP method. The following methods are available:
* <ul>
* <li>GET: Sending a GET request, for example, for querying a HTML file. </li>
* <li>PUT: Sending data to the HTTP server. The data must be passed in the send() call. The URI represents the name under which the data should be stored. Under this name, the data are then normally retrievable. </li>
* <li>POST: Sending data to the HTTP server. The data must be passed in the send() call. The URI represents the name of the consumer of the data. </li>
* <li>DELETE: Sending a DELETE request. </li>
* </ul>
*
* @param {string} url String containing the URL for this request.
* @param {boolean} [async] Optional flag indicating whether to handle the request asynchronously. In this case the operation send() returns immediately, in other word, it will not be waiting until a response is received. Asynchronous sending is only possible, when XMLHTTPRequest.canAsync returns <code>true</code>. If asynchronous sending is not possible, this flag will be ignored. For an asynchronous request you can use XMLHTTPRequest.readyState to get the current state of the request.
* @param {string} [user] Optional user name must be specified only if the HTTP server requires authentication.
* @param {string} [passwd] Optional password must also be specified only if the HTTP server requires authentication.
* @returns {boolean} <code>true</code> if the request was successfully initialized, <code>false</code> in case of any error.
* @since DOCUMENTS 4.0
* @see [XMLHTTPRequest.send,XMLHTTPRequest.canAsync]{@link XMLHTTPRequest#send,XMLHTTPRequest#canAsync}
* @example
* var xmlHttp = new XMLHTTPRequest();
* var async = false;
* var url = "http://localhost:11001/";
* xmlHttp.open("GET", url + "?wsdl", async);
* xmlHttp.send();
**/
/**
* @memberof XMLHTTPRequest
* @function send
* @instance
* @summary Send the request to the HTTP server.
* @description The request must be prepared via <code>open()</code> before.
*
* Note: The request must be initialized via open() before. You can use XMLHTTPRequest.readyState to get the current state of an asynchronous request. The properties XMLHTTPRequest.status and XMLHTTPRequest.statusText return the status of the completed request while using getResponseHeader() and XMLHTTPRequest.response the actual result of the request can be retrieved. An asynchronous request can be canceled using abort().
* Note: The type of the content parameter can be one of the following: String, ArrayBuffer, File. Caution: all other types will be converted to a string! Given a conventional array, the function will only send a string like "[object Array]".
*
* About files
*
* Passed files must be opened in binary read mode. If the file is not rewindable (a named pipe, for instance), the property FileSizeHint should be set before sending. The property is useful to supress an automatic length scan. The function implicitly closes the File object, though the file may remain open for asynchronous operation. When an asynchronous request is completed, its associated files become closed outside the JavaScript environment.
* About Arraybuffers
*
* Passing a TypedArray (UInt8Array, Int16Array etc.) instead of an ArrayBuffer is possible, but not recommended. The actual implementation always sends the complete associated buffer. The result can be unexpected, if the TypedArray covers only a section of a bigger buffer. This behaviour might change in future releases.
* Since DOCUMENTS 5.0c (Support for sending File and ArrayBuffer)
* @param {string} [content]
* @returns {boolean}
* @since DOCUMENTS 4.0
* @see [XMLHTTPRequest.open,FileSizeHint]{@link XMLHTTPRequest#open,FileSizeHint}
* @example
* var xmlHttp = new XMLHTTPRequest();
* var async = false;
* if (xmlHttp.canAsync)
* async = true;
* var url = "http://localhost:11001/";
* xmlHttp.open("GET", url + "?wsdl", async);
* xmlHttp.send(null);
* if (async) {
* while(xmlHttp.status != xmlHttp.COMPLETED) {
* util.sleep(500); // sleep 500 ms
* }
* }
* util.out(xmlHttp.status); // should be 200
* @example
* var file = new File("E:\\test\\Lighthouse.jpg", "rb");
* if(!file || !file.ok())
* throw "File not found";
* var req = new XMLHTTPRequest();
* var url = "http://localhost:8080/myUploadServlet";
* req.open("PUT", url, false);
*
* // Uncomment the following instruction to suppress the
* // "100-continue" communication cycle, if the target server
* // does not support it. This might also speed up very little
* // uploads. Otherwise better keep the default behaviour.
* // req.addRequestHeader("Expect", " ");
*
* req.addRequestHeader("Filename", "Lighthouse.jpg");
* req.send(file);
* util.out(req.status);
* util.out(req.response);
* // No need to close file here; send() already did.
* util.out(req.status); // should be 200
**/
/**
* @memberof XMLHTTPRequest
* @function setCAInfo
* @instance
* @summary Set one or more certificates to verify the peer if using HTTPS.
* @param {string} pemFile String with the path to pem-file with the servers certificates (bundle of X.509 certificates in PEM format).
* @param {number} options Integer with a bitmask of verification-options (XMLHTTPRequest.VERIFYPEER, XMLHTTPRequest.VERIFYHOST)
* @returns {void}
* @since DOCUMENTS 5.0c
* @example
* var url = "https://someserver:443/";
* var xmlHttp = new XMLHTTPRequest();
* xmlHttp.setCAInfo("c:\\certs\\cabundle.pem", XMLHTTPRequest.VERIFYPEER + XMLHTTPRequest.VERIFYHOST);
* var async = false;
* xmlHttp.open("POST", url, async);
* if (xmlHttp.send(content))
* util.out(xmlHttp.getAllResponseHeaders());
**/
|
var Simwp = (function($){
var simwp = {};
simwp.locale = 'en';
// ajax options
simwp.set = function(key, val){
$.ajax({
url : '.',
data : {
key : val
},
method : 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
};
simwp.trigger = function(action, options){
$(document).trigger(action, options);
};
simwp.bind = function(action, fn){
$(document).on(action, fn);
};
simwp.view = {};
simwp.view.noticeRemove = function(s){
$(s).on('click', function removeNotice(){
simwp.set('---simwp-removed-notices', this.id.replace('simwp-notice-', ''));
siwmp.trigger('simwp_notice_removed', [$(this)]);
});
};
simwp.view.lineRemoveButton = function(s){
$(s).on('click', function removeLine(){
var row = $(this).closest('tr'),
holder = row.parent();
simwp.trigger('simwp_line_removed', [row, holder]);
row.remove();
});
};
function addLine(){
// test trim
if(this.value.replace(/^\s+|\s+$/g, '') === '') {
return;
}
var id = this.id.replace('simwp-input-lines-edit-', '');
var currentRow = $(this).parent().parent();
// create new row
var row = $('<tr>');
// add label
row.html('<td><input class="hidden" name="' + id + '[]" value="' + this.value + '" type="text" readonly> <label> ' + this.value + ' </label></td>');
// reset input
this.value = '';
// add delete button
var button = $('<button>', {type : 'button' , class : 'delete' }).text('x');
simwp.view.lineRemoveButton(button);
$('<td>').append(button).appendTo(row);
row.insertBefore(currentRow);
currentRow.closest('table');
simwp.trigger('simwp_line_added', [row, $(this)]);
}
simwp.view.lineAddInput = function(s){
$(s).on('keydown', function enter(e){
var code = e.code || e.which;
if(code === 13){
e.preventDefault();
addLine.apply(this);
}
});
};
simwp.view.lineAddButton = function(s){
$(s).click(function addLineButton(){
var id = this.id.replace('simwp-input-lines-button-', '');
addLine.apply($('#simwp-input-lines-edit-' + id)[0]);
});
};
simwp.view.lines = function(s){
var lines = $(s);
simwp.view.lineRemoveButton(lines.find('button.delete'));
simwp.view.lineAddInput(lines.find('.simwp-input-lines-edit'));
simwp.view.lineAddButton(lines.find('.simwp-input-lines-button'));
};
simwp.view.imageSelect = function(s){
$(s).click(function pickImage(e){
var _this = this;
e.preventDefault();
var image = wp.media({
title: 'Upload Image',
// mutiple: true if you want to upload multiple files at once
multiple: false
}).on('select', function(e){
// This will return the selected image from the Media Uploader, the result is an object
var uploaded_image = image.state().get('selection').first();
// We convert uploaded_image to a JSON object to make accessing it easier
// Output to the console uploaded_image
// console.log(uploaded_image);
var image_url = uploaded_image.toJSON().url;
// Let's assign the url value to the input field
var parent = $(_this).parent();
parent.children('img').attr('src', image_url);
parent.children('input').val(image_url);
// src, target
simwp.trigger('simwp_image_selected', [image_url, parent]);
}).open();
});
};
simwp.view.imageRemove = function(s){
$(s).click(function removeImage(){
var parent = $(this).parent(),
img = parent.children('img');
img.attr('src', '');
img.attr('src', '//placehold.it/' + img.width() + 'x' + img.height() + '/ddd/fdfdfd');
parent.children('input').val('');
// target
simwp.trigger('simwp_image_removed', [parent]);
});
};
simwp.view.imagePicker = function(s){
var images = $(s);
simwp.view.imageSelect(images.children('button.add'));
simwp.view.imageRemove(images.children('button.delete'));
};
simwp.view.tags = function(s, options){
options = options || {};
if($.fn.tagEditor){
$(s).tagEditor(options);
}
};
simwp.view.colorPicker = function(s){
if($.fn.wpColorPicker){
$(s).wpColorPicker();
}
};
function timePad(t){
if(t < 10){
return '0' + t;
}
return '' + t;
}
function defaultDate(){
var time = new Date(),
idate = [
time.getFullYear(),
timePad(time.getMonth() + 1),
timePad(time.getDate()),
];
return idate.join('-');
}
function dateTimePicker(s, options){
if($.datetimepicker){
$.datetimepicker.setLocale(simwp.locale);
$(s).each(function(){
if($(this).val() == ''){
options.startDate = defaultDate();
}
$(this).datetimepicker(options);
});
}
}
simwp.view.dateTimePicker = function(s){
dateTimePicker(s, {
format:'Y-m-d H:i:s',
mask : true,
lazyInit:true,
step : 30
});
};
simwp.view.datePicker = function(s){
dateTimePicker(s, {
format:'Y-m-d',
mask : true,
lazyInit:true,
timepicker : false,
step : 30
});
};
// Install components
$(function(){
var bodyLocale = $('body').attr('class').match(/locale-(\w{2})/);
if(bodyLocale){
simwp.locale = bodyLocale[1];
}
simwp.view.noticeRemove('.notice.is-removable');
simwp.view.colorPicker('.simwp-color-field');
simwp.view.tags('.simwp-tags');
simwp.view.datePicker('.simwp-date-field');
simwp.view.dateTimePicker('.simwp-datetime-field');
simwp.view.imagePicker('.simwp-input-image');
simwp.view.lines('.simwp-input-lines');
});
return simwp;
})(jQuery);
|
'use strict';
/* Need to load them manually when doing jscover */
require('../models/article');
require('../../../users/server-cov/models/user');
var mongoose = require('mongoose');
var Article = mongoose.model('Article');
var User = mongoose.model('User');
exports.addFriend = function(req, res) {
User.update({
_id: req.user._id
}, {
$addToSet: { friends: req.body.username }
}, function(err, results) {
if (err) {
console.log('addFriend: ' + err);
return res.json(500, {
error: 'Cannot add friend: ' + err
});
}
});
res.json(req.user || null);
};
/**
* Find article by id
*/
exports.article = function(req, res, next, id) {
Article.load(id, function(err, article) {
if (err) return next(err);
if (!article) return next(new Error('Failed to load article ' + id));
req.article = article;
next();
});
};
/**
* Create an article
*/
exports.create = function(req, res) {
User.find({'username': req.body.user }, function (err, username) {
if (err) {
return res.json(500, {
error: 'Cannot save the article: ' + err
});
}
var article = new Article({
'content': req.body.content,
'user': username[0],
'author': req.user
});
article.save(function(err) {
if (err) {
return res.json(500, {
error: 'Cannot save the article: ' + err
});
}
res.json(article);
});
});
};
/**
* Delete an article
*/
exports.destroy = function(req, res) {
var article = req.article;
article.remove(function(err) {
if (err) {
return res.json(500, {
error: 'Cannot delete the article'
});
}
res.json(article);
});
};
/**
* Show an article
*/
exports.show = function(req, res) {
res.json(req.article);
};
/**
* List of Articles
*/
exports.all = function(req, res) {
var username = req.query.username;
if (username === undefined)
if (req.user !== undefined)
username = req.user.username;
if (username !== undefined) {
User.find({'username': username }, function (err, results) {
if (results.length) {
Article.find({'user': results[0]._id})
.sort('-created')
.populate('user', 'name username')
.populate('author', 'name username')
.exec(function(err, articles) {
if (err) {
return res.json(500, {error: 'Cannot list the articles'});
}
res.json(articles);
});
}
});
} else {
res.json([]);
}
};
|
(function() {
'use strict';
angular
.module('groceries')
.controller('LoginController', LoginController);
LoginController.$inject = ['$location', 'groceriesService', 'localStorageService'];
function LoginController($location, groceriesService, localStorageService) {
var vm = this;
vm.login = login;
vm.password = '';
vm.username = '';
activate();
function activate() {
if (localStorageService.get('token')) {
redirect();
}
}
function login() {
return groceriesService.login(vm.username, vm.password)
.then(loginComplete);
function loginComplete(token) {
localStorageService.set('token', token);
redirect();
}
}
function redirect() {
$location.path('/list');
}
}
})();
|
/**
* gollum.editor.js
* A jQuery plugin that creates the Gollum Editor.
*
* Usage:
* $.GollumEditor(); on DOM ready.
*/
(function($) {
// Editor options
var DefaultOptions = {
MarkupType: 'markdown',
EditorMode: 'code',
NewFile: false,
HasFunctionBar: true,
Debug: false,
NoDefinitionsFor: []
};
var ActiveOptions = {};
/**
* $.GollumEditor
*
* You don't need to do anything. Just run this on DOM ready.
*/
$.GollumEditor = function( IncomingOptions ) {
ActiveOptions = $.extend( DefaultOptions, IncomingOptions );
debug('GollumEditor loading');
if ( EditorHas.baseEditorMarkup() ) {
if ( EditorHas.titleDisplayed() ) {
$('#gollum-editor-title-field').addClass('active');
}
if ( EditorHas.editSummaryMarkup() ) {
$.GollumEditor.Placeholder.add($('#gollum-editor-edit-summary input'));
$('#gollum-editor form[name="gollum-editor"]').submit(function( e ) {
e.preventDefault();
// Do not clear default place holder text
// Updated home (markdown)
// $.GollumEditor.Placeholder.clearAll();
debug('submitting');
$(this).unbind('submit');
$(this).submit();
});
}
if ( EditorHas.collapsibleInputs() ) {
$('#gollum-editor .collapsed a.button, ' +
'#gollum-editor .expanded a.button').click(function( e ) {
e.preventDefault();
$(this).parent().toggleClass('expanded');
$(this).parent().toggleClass('collapsed');
});
}
if ( EditorHas.previewButton() ) {
var formAction =
$('#gollum-editor #gollum-editor-preview').click(function() {
// make a dummy form, submit to new target window
// get form fields
var oldAction = $('#gollum-editor form').attr('action');
var $form = $($('#gollum-editor form').get(0));
$form.attr('action', this.href || '/preview');
$form.attr('target', '_blank');
var paths = window.location.pathname.split('/');
$form.attr('page', paths[ paths.length - 1 ] || '')
$form.submit();
$form.attr('action', oldAction);
$form.removeAttr('target');
return false;
});
}
// Initialize the function bar by loading proper definitions
if ( EditorHas.functionBar() ) {
var htmlSetMarkupLang =
$('#gollum-editor-body').attr('data-markup-lang');
if ( htmlSetMarkupLang ) {
ActiveOptions.MarkupType = htmlSetMarkupLang;
}
// load language definition
LanguageDefinition.setActiveLanguage( ActiveOptions.MarkupType );
if ( EditorHas.formatSelector() ) {
FormatSelector.init(
$('#gollum-editor-format-selector select') );
}
if ( EditorHas.help() ) {
$('#gollum-editor-help').hide();
$('#gollum-editor-help').removeClass('jaws');
}
} // EditorHas.functionBar
} // EditorHas.baseEditorMarkup
};
/**
* $.GollumEditor.defineLanguage
* Defines a set of language actions that Gollum can use.
* Used by the definitions in langs/ to register language definitions.
*/
$.GollumEditor.defineLanguage = function( language_name, languageObject ) {
if ( typeof languageObject == 'object' ) {
LanguageDefinition.define( language_name, languageObject );
} else {
debug('GollumEditor.defineLanguage: definition for ' + language_name +
' is not an object');
}
};
/**
* debug
* Prints debug information to console.log if debug output is enabled.
*
* @param mixed Whatever you want to dump to console.log
* @return void
*/
var debug = function(m) {
if ( ActiveOptions.Debug &&
typeof console != 'undefined' ) {
console.log( m );
}
};
/**
* LanguageDefinition
* Language definition file handler
* Loads language definition files as necessary.
*/
var LanguageDefinition = {
_ACTIVE_LANG: '',
_LOADED_LANGS: [],
_LANG: {},
/**
* Defines a language
*
* @param name string The name of the language
* @param name object The definition object
*/
define: function( name, definitionObject ) {
LanguageDefinition._ACTIVE_LANG = name;
LanguageDefinition._LOADED_LANGS.push( name );
if ( typeof $.GollumEditor.WikiLanguage == 'object' ) {
var definition = {};
$.extend(definition, $.GollumEditor.WikiLanguage, definitionObject);
LanguageDefinition._LANG[name] = definition;
} else {
LanguageDefinition._LANG[name] = definitionObject;
}
},
getActiveLanguage: function() {
return LanguageDefinition._ACTIVE_LANG;
},
setActiveLanguage: function( name ) {
// On first load _ACTIVE_LANG.length is 0 and evtChangeFormat isn't called.
if ( LanguageDefinition._ACTIVE_LANG != null && LanguageDefinition._ACTIVE_LANG.length <= 0 ) {
FormatSelector.updateCommitMessage( name );
}
if(LanguageDefinition.getHookFunctionFor("deactivate")) {
LanguageDefinition.getHookFunctionFor("deactivate")();
}
if ( !LanguageDefinition.isLoadedFor(name) ) {
LanguageDefinition._ACTIVE_LANG = null;
LanguageDefinition.loadFor( name, function(x, t) {
if ( t != 'success' ) {
debug('Failed to load language definition for ' + name);
// well, fake it and turn everything off for this one
LanguageDefinition.define( name, {} );
}
// update features that rely on the language definition
if ( EditorHas.functionBar() ) {
FunctionBar.refresh();
}
if ( LanguageDefinition.isValid() && EditorHas.formatSelector() ) {
FormatSelector.updateSelected();
}
if(LanguageDefinition.getHookFunctionFor("activate")) {
LanguageDefinition.getHookFunctionFor("activate")();
}
function hotkey( e, cmd ) {
e.preventDefault();
var def = LanguageDefinition.getDefinitionFor( cmd );
if ( typeof def == 'object' ) {
FunctionBar.executeAction( def );
}
// Prevent bubbling of hotkey.
return false;
}
Mousetrap.bind(['command+1', 'ctrl+1'], function( e ){ hotkey( e, 'function-h1' ); });
Mousetrap.bind(['command+2', 'ctrl+2'], function( e ){ hotkey( e, 'function-h2' ); });
Mousetrap.bind(['command+3', 'ctrl+3'], function( e ){ hotkey( e, 'function-h3' ); });
Mousetrap.bind(['command+b', 'ctrl+b'], function( e ){ hotkey( e, 'function-bold' ); });
Mousetrap.bind(['command+i', 'ctrl+i'], function( e ){ hotkey( e, 'function-italic' ); });
Mousetrap.bind(['command+s', 'ctrl+s'], function( e ){
e.preventDefault();
$("#gollum-editor-submit").trigger("click");
return false;
});
} );
} else {
LanguageDefinition._ACTIVE_LANG = name;
FunctionBar.refresh();
if(LanguageDefinition.getHookFunctionFor("activate")) {
LanguageDefinition.getHookFunctionFor("activate")();
}
}
},
getHookFunctionFor: function(attr, specified_lang) {
if ( !specified_lang ) {
specified_lang = LanguageDefinition._ACTIVE_LANG;
}
if ( LanguageDefinition.isLoadedFor(specified_lang) &&
LanguageDefinition._LANG[specified_lang][attr] &&
typeof LanguageDefinition._LANG[specified_lang][attr] == 'function' ) {
return LanguageDefinition._LANG[specified_lang][attr];
}
return null;
},
/**
* gets a definition object for a specified attribute
*
* @param string attr The specified attribute.
* @param string specified_lang The language to pull a definition for.
* @return object if exists, null otherwise
*/
getDefinitionFor: function( attr, specified_lang ) {
if ( !specified_lang ) {
specified_lang = LanguageDefinition._ACTIVE_LANG;
}
if ( LanguageDefinition.isLoadedFor(specified_lang) &&
LanguageDefinition._LANG[specified_lang][attr] &&
typeof LanguageDefinition._LANG[specified_lang][attr] == 'object' ) {
return LanguageDefinition._LANG[specified_lang][attr];
}
return null;
},
/**
* loadFor
* Asynchronously loads a definition file for the current markup.
* Definition files are necessary to use the code editor.
*
* @param string markup_name The markup name you want to load
* @return void
*/
loadFor: function( markup_name, on_complete ) {
// Keep us from hitting 404s on our site, check the definition blacklist
if ( ActiveOptions.NoDefinitionsFor.length ) {
for ( var i=0; i < ActiveOptions.NoDefinitionsFor.length; i++ ) {
if ( markup_name == ActiveOptions.NoDefinitionsFor[i] ) {
// we don't have this. get out.
if ( typeof on_complete == 'function' ) {
on_complete( null, 'error' );
return;
}
}
}
}
// attempt to load the definition for this language
var script_uri = baseUrl + '/javascript/editor/langs/' + markup_name + '.js';
$.ajax({
url: script_uri,
dataType: 'script',
complete: function( xhr, textStatus ) {
if ( typeof on_complete == 'function' ) {
on_complete( xhr, textStatus );
}
}
});
},
/**
* isLoadedFor
* Checks to see if a definition file has been loaded for the
* specified markup language.
*
* @param string markup_name The name of the markup.
* @return boolean
*/
isLoadedFor: function( markup_name ) {
if ( LanguageDefinition._LOADED_LANGS.length === 0 ) {
return false;
}
for ( var i=0; i < LanguageDefinition._LOADED_LANGS.length; i++ ) {
if ( LanguageDefinition._LOADED_LANGS[i] == markup_name ) {
return true;
}
}
return false;
},
isValid: function() {
return ( LanguageDefinition._ACTIVE_LANG &&
typeof LanguageDefinition._LANG[LanguageDefinition._ACTIVE_LANG] ==
'object' );
}
};
/**
* EditorHas
* Various conditionals to check what features of the Gollum Editor are
* active/operational.
*/
var EditorHas = {
/**
* EditorHas.baseEditorMarkup
* True if the basic editor form is in place.
*
* @return boolean
*/
baseEditorMarkup: function() {
return ( $('#gollum-editor').length &&
$('#gollum-editor-body').length );
},
/**
* EditorHas.collapsibleInputs
* True if the editor contains collapsible inputs for things like the
* sidebar or footer, false otherwise.
*
* @return boolean
*/
collapsibleInputs: function() {
return $('#gollum-editor .collapsed, #gollum-editor .expanded').length;
},
/**
* EditorHas.formatSelector
* True if the editor has a format selector (for switching between
* language types), false otherwise.
*
* @return boolean
*/
formatSelector: function() {
return $('#gollum-editor-format-selector select').length;
},
/**
* EditorHas.functionBar
* True if the Function Bar markup exists.
*
* @return boolean
*/
functionBar: function() {
return ( ActiveOptions.HasFunctionBar &&
$('#gollum-editor-function-bar').length );
},
/**
* EditorHas.ff4Environment
* True if in a Firefox 4.0 Beta environment.
*
* @return boolean
*/
ff4Environment: function() {
var ua = new RegExp(/Firefox\/4.0b/);
return ( ua.test( navigator.userAgent ) );
},
/**
* EditorHas.editSummaryMarkup
* True if the editor has a summary field (Gollum's commit message),
* false otherwise.
*
* @return boolean
*/
editSummaryMarkup: function() {
return ( $('input#gollum-editor-message-field').length > 0 );
},
/**
* EditorHas.help
* True if the editor contains the inline help sector, false otherwise.
*
* @return boolean
*/
help: function() {
return ( $('#gollum-editor #gollum-editor-help').length &&
$('#gollum-editor #function-help').length );
},
/**
* EditorHas.previewButton
* True if the editor has a preview button, false otherwise.
*
* @return boolean
*/
previewButton: function() {
return ( $('#gollum-editor #gollum-editor-preview').length );
},
/**
* EditorHas.titleDisplayed
* True if the editor is displaying a title field, false otherwise.
*
* @return boolean
*/
titleDisplayed: function() {
return ( ActiveOptions.NewFile );
}
};
/**
* FunctionBar
*
* Things the function bar does.
*/
var FunctionBar = {
isActive: false,
/**
* FunctionBar.activate
* Activates the function bar, attaching all click events
* and displaying the bar.
*
*/
activate: function() {
debug('Activating function bar');
// check these out
$('#gollum-editor-function-bar a.function-button').each(function() {
if ( LanguageDefinition.getDefinitionFor( $(this).attr('id') ) ) {
$(this).click( FunctionBar.evtFunctionButtonClick );
$(this).removeClass('disabled');
}
else if ( $(this).attr('id') != 'function-help' ) {
$(this).addClass('disabled');
}
});
// show bar as active
$('#gollum-editor-function-bar').addClass( 'active' );
FunctionBar.isActive = true;
},
deactivate: function() {
$('#gollum-editor-function-bar a.function-button').unbind('click');
$('#gollum-editor-function-bar').removeClass( 'active' );
FunctionBar.isActive = false;
},
/**
* FunctionBar.evtFunctionButtonClick
* Event handler for the function buttons. Traps the click and
* executes the proper language action.
*
* @param jQuery.Event jQuery event object.
*/
evtFunctionButtonClick: function(e) {
e.preventDefault();
var def = LanguageDefinition.getDefinitionFor( $(this).attr('id') );
if ( typeof def == 'object' ) {
FunctionBar.executeAction( def );
}
},
/**
* FunctionBar.executeAction
* Executes a language-specific defined action for a function button.
*
*/
executeAction: function( definitionObject ) {
// get the selected text from the textarea
var txt = $('#gollum-editor-body').val();
// hmm, I'm not sure this will work in a textarea
var selPos = FunctionBar
.getFieldSelectionPosition( $('#gollum-editor-body') );
var selText = FunctionBar.getFieldSelection( $('#gollum-editor-body') );
var repText = selText;
var reselect = true;
var cursor = null;
// execute a replacement function if one exists
if ( definitionObject.exec &&
typeof definitionObject.exec == 'function' ) {
definitionObject.exec( txt, selText, $('#gollum-editor-body') );
return;
}
// execute a search/replace if they exist
var searchExp = /([^\n]+)/gi;
if ( definitionObject.search &&
typeof definitionObject.search == 'object' ) {
debug('Replacing search Regex');
searchExp = null;
searchExp = new RegExp ( definitionObject.search );
debug( searchExp );
}
debug('repText is ' + '"' + repText + '"');
// replace text
if ( definitionObject.replace &&
typeof definitionObject.replace == 'string' ) {
debug('Running replacement - using ' + definitionObject.replace);
var rt = definitionObject.replace;
repText = escape( repText );
repText = repText.replace( searchExp, rt );
// remove backreferences
repText = repText.replace( /\$[\d]/g, '' );
repText = unescape( repText );
if ( repText === '' ) {
debug('Search string is empty');
// find position of $1 - this is where we will place the cursor
cursor = rt.indexOf('$1');
// we have an empty string, so just remove backreferences
repText = rt.replace( /\$[\d]/g, '' );
// if the position of $1 doesn't exist, stick the cursor in
// the middle
if ( cursor == -1 ) {
cursor = Math.floor( rt.length / 2 );
}
}
}
// append if necessary
if ( definitionObject.append &&
typeof definitionObject.append == 'string' ) {
if ( repText == selText ) {
reselect = false;
}
repText += definitionObject.append;
}
if ( repText ) {
FunctionBar.replaceFieldSelection( $('#gollum-editor-body'),
repText, reselect, cursor );
}
},
/**
* getFieldSelectionPosition
* Retrieves the selection range for the textarea.
*
* @return object the .start and .end offsets in the string
*/
getFieldSelectionPosition: function( $field ) {
if ($field.length) {
var start = 0, end = 0;
var el = $field.get(0);
if (typeof el.selectionStart == "number" &&
typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
} else {
var range = document.selection.createRange();
var stored_range = range.duplicate();
stored_range.moveToElementText( el );
stored_range.setEndPoint( 'EndToEnd', range );
start = stored_range.text.length - range.text.length;
end = start + range.text.length;
// so, uh, we're close, but we need to search for line breaks and
// adjust the start/end points accordingly since IE counts them as
// 2 characters in TextRange.
var s = start;
var lb = 0;
var i;
debug('IE: start position is currently ' + s);
for ( i=0; i < s; i++ ) {
if ( el.value.charAt(i).match(/\r/) ) {
++lb;
}
}
if ( lb ) {
debug('IE start: compensating for ' + lb + ' line breaks');
start = start - lb;
lb = 0;
}
var e = end;
for ( i=0; i < e; i++ ) {
if ( el.value.charAt(i).match(/\r/) ) {
++lb;
}
}
if ( lb ) {
debug('IE end: compensating for ' + lb + ' line breaks');
end = end - lb;
}
}
return {
start: start,
end: end
};
} // end if ($field.length)
},
/**
* getFieldSelection
* Returns the currently selected substring of the textarea.
*
* @param jQuery A jQuery object for the textarea.
* @return string Selected string.
*/
getFieldSelection: function( $field ) {
var selStr = '';
var selPos;
if ( $field.length ) {
selPos = FunctionBar.getFieldSelectionPosition( $field );
selStr = $field.val().substring( selPos.start, selPos.end );
debug('Selected: ' + selStr + ' (' + selPos.start + ', ' +
selPos.end + ')');
return selStr;
}
return false;
},
isShown: function() {
return ($('#gollum-editor-function-bar').is(':visible'));
},
refresh: function() {
if ( EditorHas.functionBar() ) {
debug('Refreshing function bar');
if ( LanguageDefinition.isValid() ) {
$('#gollum-editor-function-bar a.function-button').unbind('click');
FunctionBar.activate();
if ( Help ) {
Help.setActiveHelp( LanguageDefinition.getActiveLanguage() );
}
} else {
debug('Language definition is invalid.');
if ( FunctionBar.isShown() ) {
// deactivate the function bar; it's not gonna work now
FunctionBar.deactivate();
}
if ( Help.isShown() ) {
Help.hide();
}
}
}
},
/**
* replaceFieldSelection
* Replaces the currently selected substring of the textarea with
* a new string.
*
* @param jQuery A jQuery object for the textarea.
* @param string The string to replace the current selection with.
* @param boolean Reselect the new text range.
*/
replaceFieldSelection: function( $field, replaceText, reselect, cursorOffset ) {
var selPos = FunctionBar.getFieldSelectionPosition( $field );
var fullStr = $field.val();
var selectNew = true;
if ( reselect === false) {
selectNew = false;
}
var scrollTop = null;
if ( $field[0].scrollTop ) {
scrollTop = $field[0].scrollTop;
}
$field.val( fullStr.substring(0, selPos.start) + replaceText +
fullStr.substring(selPos.end) );
$field[0].focus();
if ( selectNew ) {
if ( $field[0].setSelectionRange ) {
if ( cursorOffset ) {
$field[0].setSelectionRange(
selPos.start + cursorOffset,
selPos.start + cursorOffset
);
} else {
$field[0].setSelectionRange( selPos.start,
selPos.start + replaceText.length );
}
} else if ( $field[0].createTextRange ) {
var range = $field[0].createTextRange();
range.collapse( true );
if ( cursorOffset ) {
range.moveEnd( selPos.start + cursorOffset );
range.moveStart( selPos.start + cursorOffset );
} else {
range.moveEnd( 'character', selPos.start + replaceText.length );
range.moveStart( 'character', selPos.start );
}
range.select();
}
}
if ( scrollTop ) {
// this jumps sometimes in FF
$field[0].scrollTop = scrollTop;
}
}
};
/**
* FormatSelector
*
* Functions relating to the format selector (if it exists)
*/
var FormatSelector = {
$_SELECTOR: null,
/**
* FormatSelector.evtChangeFormat
* Event handler for when a format has been changed by the format
* selector. Will automatically load a new language definition
* via JS if necessary.
*
* @return void
*/
evtChangeFormat: function( e ) {
var newMarkup = $(this).val();
FormatSelector.updateCommitMessage( newMarkup );
LanguageDefinition.setActiveLanguage( newMarkup );
},
updateCommitMessage: function( newMarkup ) {
var msg = document.getElementById( "gollum-editor-message-field" );
var val = msg.value;
// Must start with created or updated.
if (/^(?:created|updated)/i.test(val)) {
msg.value = val.replace( /\([^\)]*\)$/, "(" + newMarkup + ")" );
}
},
/**
* FormatSelector.init
* Initializes the format selector.
*
* @return void
*/
init: function( $sel ) {
debug('Initializing format selector');
// unbind events if init is being called twice for some reason
if ( FormatSelector.$_SELECTOR &&
typeof FormatSelector.$_SELECTOR == 'object' ) {
FormatSelector.$_SELECTOR.unbind( 'change' );
}
FormatSelector.$_SELECTOR = $sel;
// set format selector to the current language
FormatSelector.updateSelected();
FormatSelector.$_SELECTOR.change( FormatSelector.evtChangeFormat );
},
/**
* FormatSelector.update
*/
updateSelected: function() {
var currentLang = LanguageDefinition.getActiveLanguage();
FormatSelector.$_SELECTOR.val( currentLang );
}
};
/**
* Help
*
* Functions that manage the display and loading of inline help files.
*/
var Help = {
_ACTIVE_HELP: '',
_LOADED_HELP_LANGS: [],
_HELP: {},
/**
* Help.define
*
* Defines a new help context and enables the help function if it
* exists in the Gollum Function Bar.
*
* @param string name The name you're giving to this help context.
* Generally, this should match the language name.
* @param object definitionObject The definition object being loaded from a
* language / help definition file.
* @return void
*/
define: function( name, definitionObject ) {
if ( Help.isValidHelpFormat( definitionObject ) ) {
debug('help is a valid format');
Help._ACTIVE_HELP_LANG = name;
Help._LOADED_HELP_LANGS.push( name );
Help._HELP[name] = definitionObject;
if ( $("#function-help").length ) {
if ( $('#function-help').hasClass('disabled') ) {
$('#function-help').removeClass('disabled');
}
$('#function-help').unbind('click');
$('#function-help').click( Help.evtHelpButtonClick );
// generate help menus
Help.generateHelpMenuFor( name );
if ( $('#gollum-editor-help').length &&
typeof $('#gollum-editor-help').attr('data-autodisplay') !== 'undefined' &&
$('#gollum-editor-help').attr('data-autodisplay') === 'true' ) {
Help.show();
}
}
} else {
if ( $('#function-help').length ) {
$('#function-help').addClass('disabled');
}
}
},
/**
* Help.generateHelpMenuFor
* Generates the markup for the main help menu given a context name.
*
* @param string name The context name.
* @return void
*/
generateHelpMenuFor: function( name ) {
if ( !Help._HELP[name] ) {
debug('Help is not defined for ' + name.toString());
return false;
}
var helpData = Help._HELP[name];
// clear this shiz out
$('#gollum-editor-help-parent').html('');
$('#gollum-editor-help-list').html('');
$('#gollum-editor-help-content').html('');
// go go inefficient algorithm
for ( var i=0; i < helpData.length; i++ ) {
if ( typeof helpData[i] != 'object' ) {
break;
}
var $newLi = $('<li><a href="#" rel="' + i + '">' +
helpData[i].menuName + '</a></li>');
$('#gollum-editor-help-parent').append( $newLi );
if ( i === 0 ) {
// select on first run
$newLi.children('a').addClass('selected');
}
$newLi.children('a').click( Help.evtParentMenuClick );
}
// generate parent submenu on first run
Help.generateSubMenu( helpData[0], 0 );
$($('#gollum-editor-help-list li a').get(0)).click();
},
/**
* Help.generateSubMenu
* Generates the markup for the inline help sub-menu given the data
* object for the submenu and the array index to start at.
*
* @param object subData The data for the sub-menu.
* @param integer index The index clicked on (parent menu index).
* @return void
*/
generateSubMenu: function( subData, index ) {
$('#gollum-editor-help-list').html('');
$('#gollum-editor-help-content').html('');
for ( var i=0; i < subData.content.length; i++ ) {
if ( typeof subData.content[i] != 'object' ) {
break;
}
var $subLi = $('<li><a href="#" rel="' + index + ':' + i + '">' +
subData.content[i].menuName + '</a></li>');
$('#gollum-editor-help-list').append( $subLi );
$subLi.children('a').click( Help.evtSubMenuClick );
}
},
hide: function() {
if ( $.browser.msie ) {
$('#gollum-editor-help').css('display', 'none');
} else {
$('#gollum-editor-help').animate({
opacity: 0
}, 200, function() {
$('#gollum-editor-help')
.animate({ height: 'hide' }, 200);
});
}
},
show: function() {
if ( $.browser.msie ) {
// bypass effects for internet explorer, since it does weird crap
// to text antialiasing with opacity animations
$('#gollum-editor-help').css('display', 'block');
} else {
$('#gollum-editor-help').animate({
height: 'show'
}, 200, function() {
$('#gollum-editor-help')
.animate({ opacity: 1 }, 300);
});
}
},
/**
* Help.showHelpFor
* Displays the actual help content given the two menu indexes, which are
* rendered in the rel="" attributes of the help menus
*
* @param integer index1 parent index
* @param integer index2 submenu index
* @return void
*/
showHelpFor: function( index1, index2 ) {
var html =
Help._HELP[Help._ACTIVE_HELP_LANG][index1].content[index2].data;
$('#gollum-editor-help-content').html(html);
},
/**
* Help.isLoadedFor
* Returns true if help is loaded for a specific markup language,
* false otherwise.
*
* @param string name The name of the markup language.
* @return boolean
*/
isLoadedFor: function( name ) {
for ( var i=0; i < Help._LOADED_HELP_LANGS.length; i++ ) {
if ( name == Help._LOADED_HELP_LANGS[i] ) {
return true;
}
}
return false;
},
isShown: function() {
return ($('#gollum-editor-help').is(':visible'));
},
/**
* Help.isValidHelpFormat
* Does a quick check to make sure that the help definition isn't in a
* completely messed-up format.
*
* @param object (Array) helpArr The help definition array.
* @return boolean
*/
isValidHelpFormat: function( helpArr ) {
return ( typeof helpArr == 'object' &&
helpArr.length &&
typeof helpArr[0].menuName == 'string' &&
typeof helpArr[0].content == 'object' &&
helpArr[0].content.length );
},
/**
* Help.setActiveHelp
* Sets the active help definition to the one defined in the argument,
* re-rendering the help menu to match the new definition.
*
* @param string name The name of the help definition.
* @return void
*/
setActiveHelp: function( name ) {
if ( !Help.isLoadedFor( name ) ) {
if ( $('#function-help').length ) {
$('#function-help').addClass('disabled');
}
if ( Help.isShown() ) {
Help.hide();
}
} else {
Help._ACTIVE_HELP_LANG = name;
if ( $("#function-help").length ) {
if ( $('#function-help').hasClass('disabled') ) {
$('#function-help').removeClass('disabled');
}
$('#function-help').unbind('click');
$('#function-help').click( Help.evtHelpButtonClick );
Help.generateHelpMenuFor( name );
}
}
},
/**
* Help.evtHelpButtonClick
* Event handler for clicking the help button in the function bar.
*
* @param jQuery.Event e The jQuery event object.
* @return void
*/
evtHelpButtonClick: function( e ) {
e.preventDefault();
if ( Help.isShown() ) {
// turn off autodisplay if it's on
if ( $('#gollum-editor-help').length &&
$('#gollum-editor-help').attr('data-autodisplay') !== 'undefined' &&
$('#gollum-editor-help').attr('data-autodisplay') === 'true' ) {
$.post('/wiki/help?_method=delete');
$('#gollum-editor-help').attr('data-autodisplay', '');
}
Help.hide(); }
else { Help.show(); }
},
/**
* Help.evtParentMenuClick
* Event handler for clicking on an item in the parent menu. Automatically
* renders the submenu for the parent menu as well as the first result for
* the actual plain text.
*
* @param jQuery.Event e The jQuery event object.
* @return void
*/
evtParentMenuClick: function( e ) {
e.preventDefault();
// short circuit if we've selected this already
if ( $(this).hasClass('selected') ) { return; }
// populate from help data for this
var helpIndex = $(this).attr('rel');
var subData = Help._HELP[Help._ACTIVE_HELP_LANG][helpIndex];
$('#gollum-editor-help-parent li a').removeClass('selected');
$(this).addClass('selected');
Help.generateSubMenu( subData, helpIndex );
$($('#gollum-editor-help-list li a').get(0)).click();
},
/**
* Help.evtSubMenuClick
* Event handler for clicking an item in a help submenu. Renders the
* appropriate text for the submenu link.
*
* @param jQuery.Event e The jQuery event object.
* @return void
*/
evtSubMenuClick: function( e ) {
e.preventDefault();
if ( $(this).hasClass('selected') ) { return; }
// split index rel data
var rawIndex = $(this).attr('rel').split(':');
$('#gollum-editor-help-list li a').removeClass('selected');
$(this).addClass('selected');
Help.showHelpFor( rawIndex[0], rawIndex[1] );
}
};
// Publicly-accessible function to Help.define
$.GollumEditor.defineHelp = Help.define;
// Dialog exists as its own thing now
$.GollumEditor.Dialog = $.GollumDialog;
$.GollumEditor.replaceSelection = function( repText ) {
FunctionBar.replaceFieldSelection( $('#gollum-editor-body'), repText );
};
// Placeholder exists as its own thing now
$.GollumEditor.Placeholder = $.GollumPlaceholder;
})(jQuery);
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MultiSelectPanel = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _classnames = _interopRequireDefault(require("classnames"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var MultiSelectPanel = /*#__PURE__*/function (_Component) {
_inherits(MultiSelectPanel, _Component);
var _super = _createSuper(MultiSelectPanel);
function MultiSelectPanel() {
_classCallCheck(this, MultiSelectPanel);
return _super.apply(this, arguments);
}
_createClass(MultiSelectPanel, [{
key: "renderElement",
value: function renderElement() {
var _this = this;
var panelClassName = (0, _classnames.default)('p-multiselect-panel p-component', this.props.panelClassName);
return /*#__PURE__*/_react.default.createElement("div", {
className: panelClassName,
style: this.props.panelStyle,
ref: function ref(el) {
return _this.element = el;
},
onClick: this.props.onClick
}, this.props.header, /*#__PURE__*/_react.default.createElement("div", {
className: "p-multiselect-items-wrapper",
style: {
maxHeight: this.props.scrollHeight
}
}, /*#__PURE__*/_react.default.createElement("ul", {
className: "p-multiselect-items p-component",
role: "listbox",
"aria-multiselectable": true
}, this.props.children)));
}
}, {
key: "render",
value: function render() {
var element = this.renderElement();
if (this.props.appendTo) {
return /*#__PURE__*/_reactDom.default.createPortal(element, this.props.appendTo);
} else {
return element;
}
}
}]);
return MultiSelectPanel;
}(_react.Component);
exports.MultiSelectPanel = MultiSelectPanel;
_defineProperty(MultiSelectPanel, "defaultProps", {
appendTo: null,
header: null,
onClick: null,
scrollHeight: null,
panelClassName: null,
panelStyle: null
});
_defineProperty(MultiSelectPanel, "propTypes", {
appendTo: _propTypes.default.object,
header: _propTypes.default.any,
onClick: _propTypes.default.func,
scrollHeight: _propTypes.default.string,
panelClassName: _propTypes.default.string,
panelStyle: _propTypes.default.object
}); |
import { Injectable, defineInjectable, inject } from '@angular/core';
import { Angulartics2 } from 'angulartics2';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var Angulartics2Piwik = /** @class */ (function () {
function Angulartics2Piwik(angulartics2) {
var _this = this;
this.angulartics2 = angulartics2;
if (typeof (_paq) === 'undefined') {
console.warn('Piwik not found');
}
this.angulartics2.setUsername
.subscribe(function (x) { return _this.setUsername(x); });
this.angulartics2.setUserProperties
.subscribe(function (x) { return _this.setUserProperties(x); });
}
/**
* @return {?}
*/
Angulartics2Piwik.prototype.startTracking = /**
* @return {?}
*/
function () {
var _this = this;
this.angulartics2.pageTrack
.pipe(this.angulartics2.filterDeveloperMode())
.subscribe(function (x) { return _this.pageTrack(x.path); });
this.angulartics2.eventTrack
.pipe(this.angulartics2.filterDeveloperMode())
.subscribe(function (x) { return _this.eventTrack(x.action, x.properties); });
};
/**
* @param {?} path
* @param {?=} location
* @return {?}
*/
Angulartics2Piwik.prototype.pageTrack = /**
* @param {?} path
* @param {?=} location
* @return {?}
*/
function (path, location) {
try {
_paq.push(['setDocumentTitle', window.document.title]);
_paq.push(['setCustomUrl', path]);
_paq.push(['trackPageView']);
}
catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
};
/**
* Track a basic event in Piwik, or send an ecommerce event.
*
* @param action A string corresponding to the type of event that needs to be tracked.
* @param properties The properties that need to be logged with the event.
*/
/**
* Track a basic event in Piwik, or send an ecommerce event.
*
* @param {?} action A string corresponding to the type of event that needs to be tracked.
* @param {?=} properties The properties that need to be logged with the event.
* @return {?}
*/
Angulartics2Piwik.prototype.eventTrack = /**
* Track a basic event in Piwik, or send an ecommerce event.
*
* @param {?} action A string corresponding to the type of event that needs to be tracked.
* @param {?=} properties The properties that need to be logged with the event.
* @return {?}
*/
function (action, properties) {
if (properties === void 0) { properties = {}; }
/** @type {?} */
var params = [];
switch (action) {
/**
* @description Sets the current page view as a product or category page view. When you call
* setEcommerceView it must be followed by a call to trackPageView to record the product or
* category page view.
*
* @link https://piwik.org/docs/ecommerce-analytics/#tracking-product-page-views-category-page-views-optional
* @link https://developer.piwik.org/api-reference/tracking-javascript#ecommerce
*
* @property productSKU (required) SKU: Product unique identifier
* @property productName (optional) Product name
* @property categoryName (optional) Product category, or array of up to 5 categories
* @property price (optional) Product Price as displayed on the page
*/
case 'setEcommerceView':
params = ['setEcommerceView',
properties.productSKU,
properties.productName,
properties.categoryName,
properties.price,
];
break;
/**
* @description Adds a product into the ecommerce order. Must be called for each product in
* the order.
*
* @link https://piwik.org/docs/ecommerce-analytics/#tracking-ecommerce-orders-items-purchased-required
* @link https://developer.piwik.org/api-reference/tracking-javascript#ecommerce
*
* @property productSKU (required) SKU: Product unique identifier
* @property productName (optional) Product name
* @property categoryName (optional) Product category, or array of up to 5 categories
* @property price (recommended) Product price
* @property quantity (optional, default to 1) Product quantity
*/
case 'addEcommerceItem':
params = [
'addEcommerceItem',
properties.productSKU,
properties.productName,
properties.productCategory,
properties.price,
properties.quantity,
];
break;
/**
* @description Tracks a shopping cart. Call this javascript function every time a user is
* adding, updating or deleting a product from the cart.
*
* @link https://piwik.org/docs/ecommerce-analytics/#tracking-add-to-cart-items-added-to-the-cart-optional
* @link https://developer.piwik.org/api-reference/tracking-javascript#ecommerce
*
* @property grandTotal (required) Cart amount
*/
case 'trackEcommerceCartUpdate':
params = ['trackEcommerceCartUpdate', properties.grandTotal];
break;
/**
* @description Tracks an Ecommerce order, including any ecommerce item previously added to
* the order. orderId and grandTotal (ie. revenue) are required parameters.
*
* @link https://piwik.org/docs/ecommerce-analytics/#tracking-ecommerce-orders-items-purchased-required
* @link https://developer.piwik.org/api-reference/tracking-javascript#ecommerce
*
* @property orderId (required) Unique Order ID
* @property grandTotal (required) Order Revenue grand total (includes tax, shipping, and subtracted discount)
* @property subTotal (optional) Order sub total (excludes shipping)
* @property tax (optional) Tax amount
* @property shipping (optional) Shipping amount
* @property discount (optional) Discount offered (set to false for unspecified parameter)
*/
case 'trackEcommerceOrder':
params = [
'trackEcommerceOrder',
properties.orderId,
properties.grandTotal,
properties.subTotal,
properties.tax,
properties.shipping,
properties.discount,
];
break;
/**
* @description Tracks an Ecommerce goal
*
* @link https://piwik.org/docs/tracking-goals-web-analytics/
* @link https://developer.piwik.org/guides/tracking-javascript-guide#manually-trigger-goal-conversions
*
* @property goalId (required) Unique Goal ID
* @property value (optional) passed to goal tracking
*/
case 'trackGoal':
params = [
'trackGoal',
properties.goalId,
properties.value,
];
break;
/**
* @description Tracks a site search
*
* @link https://piwik.org/docs/site-search/
* @link https://developer.piwik.org/guides/tracking-javascript-guide#internal-search-tracking
*
* @property keyword (required) Keyword searched for
* @property category (optional) Search category
* @property searchCount (optional) Number of results
*/
case 'trackSiteSearch':
params = [
'trackSiteSearch',
properties.keyword,
properties.category,
properties.searchCount,
];
break;
/**
* @description Logs an event with an event category (Videos, Music, Games...), an event
* action (Play, Pause, Duration, Add Playlist, Downloaded, Clicked...), and an optional
* event name and optional numeric value.
*
* @link https://piwik.org/docs/event-tracking/
* @link https://developer.piwik.org/api-reference/tracking-javascript#using-the-tracker-object
*
* @property category
* @property action
* @property name (optional, recommended)
* @property value (optional)
*/
default:
// PAQ requires that eventValue be an integer, see: http://piwik.org/docs/event-tracking
if (properties.value) {
/** @type {?} */
var parsed = parseInt(properties.value, 10);
properties.value = isNaN(parsed) ? 0 : parsed;
}
params = [
'trackEvent',
properties.category,
action,
properties.name || properties.label,
properties.value,
];
}
try {
_paq.push(params);
}
catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
};
/**
* @param {?} userId
* @return {?}
*/
Angulartics2Piwik.prototype.setUsername = /**
* @param {?} userId
* @return {?}
*/
function (userId) {
try {
_paq.push(['setUserId', userId]);
}
catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
};
/**
* Sets custom dimensions if at least one property has the key "dimension<n>",
* e.g. dimension10. If there are custom dimensions, any other property is ignored.
*
* If there are no custom dimensions in the given properties object, the properties
* object is saved as a custom variable.
*
* If in doubt, prefer custom dimensions.
* @link https://piwik.org/docs/custom-variables/
*/
/**
* Sets custom dimensions if at least one property has the key "dimension<n>",
* e.g. dimension10. If there are custom dimensions, any other property is ignored.
*
* If there are no custom dimensions in the given properties object, the properties
* object is saved as a custom variable.
*
* If in doubt, prefer custom dimensions.
* @link https://piwik.org/docs/custom-variables/
* @param {?} properties
* @return {?}
*/
Angulartics2Piwik.prototype.setUserProperties = /**
* Sets custom dimensions if at least one property has the key "dimension<n>",
* e.g. dimension10. If there are custom dimensions, any other property is ignored.
*
* If there are no custom dimensions in the given properties object, the properties
* object is saved as a custom variable.
*
* If in doubt, prefer custom dimensions.
* @link https://piwik.org/docs/custom-variables/
* @param {?} properties
* @return {?}
*/
function (properties) {
/** @type {?} */
var dimensions = this.setCustomDimensions(properties);
try {
if (dimensions.length === 0) {
_paq.push(['setCustomVariable', properties]);
}
}
catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
};
/**
* @private
* @param {?} properties
* @return {?}
*/
Angulartics2Piwik.prototype.setCustomDimensions = /**
* @private
* @param {?} properties
* @return {?}
*/
function (properties) {
/** @type {?} */
var dimensionRegex = /dimension[1-9]\d*/;
/** @type {?} */
var dimensions = Object.keys(properties)
.filter(function (key) { return dimensionRegex.exec(key); });
dimensions.forEach(function (dimension) {
/** @type {?} */
var number = Number(dimension.substr(9));
_paq.push(['setCustomDimension', number, properties[dimension]]);
});
return dimensions;
};
Angulartics2Piwik.decorators = [
{ type: Injectable, args: [{ providedIn: 'root' },] }
];
/** @nocollapse */
Angulartics2Piwik.ctorParameters = function () { return [
{ type: Angulartics2 }
]; };
/** @nocollapse */ Angulartics2Piwik.ngInjectableDef = defineInjectable({ factory: function Angulartics2Piwik_Factory() { return new Angulartics2Piwik(inject(Angulartics2)); }, token: Angulartics2Piwik, providedIn: "root" });
return Angulartics2Piwik;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
export { Angulartics2Piwik };
//# sourceMappingURL=angulartics2-piwik.js.map |
(function(window){
var urlCount = 0,
NativeMediaSource = window.MediaSource || window.WebKitMediaSource || {},
nativeUrl = window.URL || {},
EventEmitter,
flvCodec = /video\/flv; codecs=["']vp6,aac["']/,
objectUrlPrefix = 'blob:vjs-media-source/';
EventEmitter = function(){};
EventEmitter.prototype.init = function(){
this.listeners = [];
};
EventEmitter.prototype.addEventListener = function(type, listener){
if (!this.listeners[type]){
this.listeners[type] = [];
}
this.listeners[type].unshift(listener);
};
EventEmitter.prototype.trigger = function(event){
var listeners = this.listeners[event.type] || [],
i = listeners.length;
while (i--) {
listeners[i](event);
}
};
// extend the media source APIs
// Media Source
videojs.MediaSource = function(){
var self = this;
videojs.MediaSource.prototype.init.call(this);
this.sourceBuffers = [];
this.readyState = 'closed';
this.listeners = {
sourceopen: [function(event){
// find the swf where we will push media data
self.swfObj = document.getElementById(event.swfId);
self.readyState = 'open';
// trigger load events
if (self.swfObj) {
self.swfObj.vjs_load();
}
}],
webkitsourceopen: [function(event){
self.trigger({
type: 'sourceopen'
});
}]
};
};
videojs.MediaSource.prototype = new EventEmitter();
// create a new source buffer to receive a type of media data
videojs.MediaSource.prototype.addSourceBuffer = function(type){
var sourceBuffer;
// if this is an FLV type, we'll push data to flash
if (flvCodec.test(type)) {
// Flash source buffers
sourceBuffer = new videojs.SourceBuffer(this);
} else {
// native source buffers
sourceBuffer = this.nativeSource.addSourceBuffer.apply(this.nativeSource, arguments);
}
this.sourceBuffers.push(sourceBuffer);
return sourceBuffer;
};
videojs.MediaSource.prototype.endOfStream = function(){
this.swfObj.vjs_endOfStream();
this.readyState = 'ended';
};
// store references to the media sources so they can be connected
// to a video element (a swf object)
videojs.mediaSources = {};
// provide a method for a swf object to notify JS that a media source is now open
videojs.MediaSource.open = function(msObjectURL, swfId){
var ms = videojs.mediaSources[msObjectURL];
if (ms) {
ms.trigger({
type: 'sourceopen',
swfId: swfId
});
} else {
throw new Error('Media Source not found (Video.js)');
}
};
// Source Buffer
videojs.SourceBuffer = function(source){
videojs.SourceBuffer.prototype.init.call(this);
this.source = source;
this.buffer = [];
};
videojs.SourceBuffer.prototype = new EventEmitter();
// accept video data and pass to the video (swf) object
videojs.SourceBuffer.prototype.appendBuffer = function(uint8Array){
var binary = '',
i = 0,
len = uint8Array.byteLength,
b64str;
this.buffer.push(uint8Array);
// base64 encode the bytes
for (i = 0; i < len; i++) {
binary += String.fromCharCode(uint8Array[i])
}
b64str = window.btoa(binary);
this.trigger({type:'update'});
// bypass normal ExternalInterface calls and pass xml directly
// EI can be slow by default
this.source.swfObj.CallFunction('<invoke name="vjs_appendBuffer"'
+ 'returntype="javascript"><arguments><string>'
+ b64str
+ '</string></arguments></invoke>');
this.trigger({type:'updateend'});
};
// URL
videojs.URL = {
createObjectURL: function(object){
var url = objectUrlPrefix + urlCount;
urlCount++;
// setup the mapping back to object
videojs.mediaSources[url] = object;
return url;
}
};
// plugin
videojs.plugin('mediaSource', function(options){
var player = this;
player.on('loadstart', function(){
var url = player.currentSrc(),
trigger = function(event){
mediaSource.trigger(event);
},
mediaSource;
if (player.techName === 'Html5' && url.indexOf(objectUrlPrefix) === 0) {
// use the native media source implementation
mediaSource = videojs.mediaSources[url];
if (!mediaSource.nativeUrl) {
// initialize the native source
mediaSource.nativeSource = new NativeMediaSource();
mediaSource.nativeSource.addEventListener('sourceopen', trigger, false);
mediaSource.nativeSource.addEventListener('webkitsourceopen', trigger, false);
mediaSource.nativeUrl = nativeUrl.createObjectURL(mediaSource.nativeSource);
}
player.src(mediaSource.nativeUrl);
}
});
});
})(this);
|
// PLUGIN: TV - an interactive debug console plugin for hapi
// TV is a simple web page in which developers can view server logs for their requests.
// https://github.com/hapijs/tv
/*
var config = require("config");
module.exports = function registerTv(server){
server.register(
{
register: require('tv'),
options: {
host: config.get("host"),
port: config.get("port") + 1,
endpoint: config.get("debugEndpoint")
}
},
function (err) {
if (err){ throw err; }
}
);
};
*/ |
#!/usr/bin/env babel-node --optional es7.asyncFunctions
import fs from 'fs';
import path from 'path';
import { Schema } from '../data/schema';
import { graphql } from 'graphql';
import { introspectionQuery } from 'graphql/utilities';
async () => {
var result = await (graphql(Schema, introspectionQuery));
if (result.errors) {
console.error('ERROR: ', JSON.stringify(result.errors, null, 2));
} else {
fs.writeFileSync(
path.join(__dirname, '../data/schema.json'),
JSON.stringify(result, null, 2)
);
}
}();
|
import generateConfig from '../../rollup-generate-config';
import pkg from './package.json';
export default generateConfig(pkg, 'valueTypes');
|
(function (angular) {
'use strict';
angular.module('birdyard.users')
.factory('authService', ['$rootScope', '$timeout', '$q', 'firebaseService', '$Auth', '$firebaseObject', 'colorService', 'presenceService',
function ($rootScope, $timeout, $q, firebaseService, $Auth, $firebaseObject, colorService, presenceService) {
// Private
var $user = null;
function getCurrentUser() {
if ($user) {
return $user;
} else {
$user = $Auth.$getAuth();
return $user;
}
}
// Strip-out *_normal*
function getLargeAvatarURL(url) {
var start, end;
start = url.indexOf('_normal.');
end = start + '_normal'.length;
if (start > -1) {
return url.substring(0, start) + url.substring(end);
} else {
return url;
}
}
// Scrub-away any extra or sensitive data, store only what we need
function formatAuthData(authData) {
// Their Birdyard-specific properties (name and avatar) will be set later-on
return {
uid: authData.uid,
expires: authData.expires,
provider: authData.provider,
language: authData[authData.provider].cachedUserProfile.lang || 'en',
handle: '@' + authData[authData.provider].username,
providerData: {
// These represent defaults to the user's customizable fields...
name: authData[authData.provider].displayName,
avatar: authData[authData.provider].profileImageURL,
avatar_lg: getLargeAvatarURL(authData[authData.provider].profileImageURL)
},
};
}
// Pre configure some properties for new users
function formatNewUser(authData) {
authData.name = authData.providerData.name;
authData.accent = colorService.random();
authData.social = false;
authData.description = '';
return authData;
}
// Sub-in provider data props if user has not chosen their own...
// E.g. A Birdyard user can have a different display name than their display name in Twitter,
// but if they choose not to, it will default to the twitter displayName.
function formatUserData(userData) {
if (userData) {
userData.name = userData.name || userData.providerData.name;
// Note: for now let's just stick with the Twitter avatar
// userData.avatar = userData.avatar || userData.providerData.avatar;
userData.avatar = userData.providerData.avatar;
userData.avatar_lg = userData.providerData.avatar_lg || userData.providerData.avatar;
return userData;
} else {
return null;
}
}
// Public
var _authService = {};
// Set user data after auth
function _signIn(authData) {
return $q(function (resolve, reject) {
var formatted = formatAuthData(authData);
var $ref = firebaseService.getRef('users');
$ref.on('value', function ($users) {
if ($users.child(authData.uid).exists()) {
// Update as to not overwrite existing properties
var $user = $ref.child(authData.uid);
$user.update(formatted);
resolve(formatted); // Not a new user!
} else {
// Give the user a random color if they haven't chosen one
var formattedNewUser = formatNewUser(formatted);
$ref.child(authData.uid).set(formattedNewUser);
resolve(formattedNewUser); // New user!
}
});
});
}
function _signOut() {
return $q(function (resolve, reject) {
$user = null;
var $ref = firebaseService.getRef();
$ref.unauth();
resolve();
});
}
function _updateUser(userData) {
return $q(function (resolve, reject) {
var $ref = firebaseService.getRef('users', userData.uid);
$ref.update(userData);
resolve();
});
}
function _getUser(uid) {
return $q(function (resolve, reject) {
var _uid = null;
if (uid) {
_uid = uid;
} else {
var _user = getCurrentUser();
if (_user) {
_uid = _user.uid;
}
}
if (_uid) {
var $ref = firebaseService.getRef('users', _uid);
$ref.on('value', function ($user) {
var user = $user.val();
if (user) {
resolve(formatUserData(user));
}
});
}
});
}
function _getAvatar(uid) {
return $q(function (resolve, reject) {
_getUser(uid).then(function($user) {
if ($user.avatar) {
var avatar = $user.avatar || $user.providerData.avatar;
resolve(avatar);
} else {
resolve('');
}
});
});
}
_authService.signIn = _signIn;
_authService.signOut = _signOut;
_authService.updateUser = _updateUser;
_authService.getUser = _getUser;
_authService.getAvatar = _getAvatar;
return _authService;
}]);
})(angular); |
import { RequestHook, Selector } from 'testcafe';
import { resolve } from 'path';
const ReExecutablePromise = require(resolve('./lib/utils/re-executable-promise'));
export default class CustomHook extends RequestHook {
constructor (config) {
super(null, config);
this.pendingAjaxRequestIds = new Set();
this._hasAjaxRequests = false;
}
onRequest (event) {
if (event.isAjax) {
this.pendingAjaxRequestIds.add(event._requestInfo.requestId);
this._hasAjaxRequests = true;
}
}
onResponse (event) {
this.pendingAjaxRequestIds.delete(event.requestId);
}
get hasAjaxRequests () {
return ReExecutablePromise.fromFn(async () => this._hasAjaxRequests);
}
}
const hook1 = new CustomHook();
const hook2 = new CustomHook({});
const hook3 = new CustomHook({ includeHeaders: true });
fixture `GH-4516`
.page `http://localhost:3000/fixtures/regression/gh-4516/pages/index.html`;
test.requestHooks(hook1)('Without config', async t => {
await t
.expect(Selector('#result').visible).ok()
.expect(hook1.hasAjaxRequests).ok()
.expect(hook1.pendingAjaxRequestIds.size).eql(0);
});
test.requestHooks(hook2)('With empty config', async t => {
await t
.expect(Selector('#result').visible).ok()
.expect(hook2.hasAjaxRequests).ok()
.expect(hook2.pendingAjaxRequestIds.size).eql(0);
});
test.requestHooks(hook3)('With includeHeaders', async t => {
await t
.expect(Selector('#result').visible).ok()
.expect(hook3.hasAjaxRequests).ok()
.expect(hook3.pendingAjaxRequestIds.size).eql(0);
});
|
module.exports = {
blog: require('./blog'),
auth: require('./auth')
};
|
import mixpanel from 'mixpanel-browser';
import {editorReady} from '../../actions/instrumentation';
import {makeInstrumentEnvironmentReady} from '../instrumentEnvironmentReady';
import {makeTestLogic} from './helpers';
test('dispatches to mixpanel on the first editor ready action', async () => {
const testLogic = makeTestLogic(makeInstrumentEnvironmentReady());
const timestamp = 12345;
await testLogic(editorReady('html', timestamp));
expect(mixpanel.track).toHaveBeenCalledWith('Environment Ready', {
Timestamp: timestamp,
});
});
test('does not send additional events to mixpanel', async () => {
const testLogic = makeTestLogic(makeInstrumentEnvironmentReady());
await testLogic(editorReady('html', 0));
mixpanel.track.mockClear();
await testLogic(editorReady('css', 0));
expect(mixpanel.track).not.toHaveBeenCalled();
});
|
(function (define) {
define( function ( ){
return { name: 'one' };
});
}(typeof define === 'function' && define.amd ? define : function () {
}));
|
// If you want to suggest a new language you can use this file as a template.
// To reduce the file size you should remove the comment lines (the ones that start with // )
if(!window.calendar_languages) {
window.calendar_languages = {};
}
// Here you define the language and Country code. Replace en-US with your own.
// First letters: the language code (lower case). See http://www.loc.gov/standards/iso639-2/php/code_list.php
// Last letters: the Country code (upper case). See http://www.iso.org/iso/home/standards/country_codes/country_names_and_code_elements.htm
window.calendar_languages['he-IL'] = {
error_noview: 'ืืื ืฉื ื: ืืชืฆืืื {0} ืื ื ืืฆืื',
error_dateformat: 'ืืื ืฉื ื: ืชืื ืืช ืชืืจืื ืฉืืืื {0}. ืืื ืฆืจืืื ืืืืืช \"ืขืืฉืื\" ืื \"yyyy-mm-dd\"',
error_loadurl: 'ืืื ืฉื ื: ืืชืืืช URL ืฉื ืืืืจืืข ืืื ื ืืืืืจืช',
error_where: 'ืืื ืฉื ื: ืืืืื ื ืืืื ืฉืืื {0}. ืืื ืืืื ืืืืืช \"ืืื\" ืื \"ืืงืืื\" ืื \"ืืืื\" ืืืื',
error_timedevide: 'ืืื ืฉื ื: ืคืจืืืจ ืืืืงืช ืืืื ืืืืจ ืืืชืืืง ื- 60 ืืื ื ืงืืืืช ืขืฉืจืื ืืืช. ืืฉืื ืืื 10, 15, 30',
no_events_in_day: 'ืืื ืืืจืืขืื ืืืื ืื.',
// {0} will be replaced with the year (example: 2013)
title_year: '{0}',
// {0} will be replaced with the month name (example: September)
// {1} will be replaced with the year (example: 2013)
title_month: '{0} โ{1}',
// {0} will be replaced with the week number (example: 37)
// {1} will be replaced with the year (example: 2013)
title_week: 'ืฉืืืข {0} ืืชืื {1}',
// {0} will be replaced with the weekday name (example: Thursday)
// {1} will be replaced with the day of the month (example: 12)
// {2} will be replaced with the month name (example: September)
// {3} will be replaced with the year (example: 2013)
title_day: '{0} {1} {2}, {3}',
week:'ืฉืืืข {0}',
all_day: 'ืืื ืฉืื',
time: 'ืฉืขื',
events: 'ืืืจืืขืื',
before_time: 'ืืกืชืืื ืืคื ื ืฆืืจ ืืืื',
after_time: 'ืืชืืื ืืืจื ืฆืืจ ืืืื',
m0: 'ืื ืืืจ',
m1: 'ืคืืจืืืจ',
m2: 'ืืจืฅ',
m3: 'ืืคืจืื',
m4: 'ืืื',
m5: 'ืืื ื',
m6: 'ืืืื',
m7: 'ืืืืืกื',
m8: 'ืกืคืืืืจ',
m9: 'ืืืงืืืืจ',
m10: 'ื ืืืืืจ',
m11: 'ืืฆืืืจ',
ms0: 'ืื ื',
ms1: 'ืคืืจ',
ms2: 'ืืจืฅ',
ms3: 'ืืคืจ',
ms4: 'ืืื',
ms5: 'ืืื ',
ms6: 'ืืื',
ms7: 'ืืื',
ms8: 'ืกืคื',
ms9: 'ืืืง',
ms10: 'ื ืื',
ms11: 'ืืฆื',
d0: 'ืจืืฉืื',
d1: 'ืฉื ื',
d2: 'ืฉืืืฉื',
d3: 'ืจืืืขื',
d4: 'ืืืืฉื',
d5: 'ืฉืืฉื',
d6: 'ืฉืืช',
// Which is the first day of the week (2 for sunday, 1 for monday)
first_day: 2,
// The list of the holidays.
// Each holiday has a date definition and a name (in your language)
// For instance:
// holidays: {
// 'date': 'name',
// 'date': 'name',
// ...
// 'date': 'name' //No ending comma for the last holiday
// }
// The format of the date may be one of the following:
// # For a holiday recurring every year in the same day: 'dd-mm' (dd is the day of the month, mm is the month). For example: '25-12'.
// # For a holiday that exists only in one specific year: 'dd-mm-yyyy' (dd is the day of the month, mm is the month, yyyy is the year). For example: '31-01-2013'
// # For Easter: use simply 'easter'
// # For holidays that are based on the Easter date: 'easter+offset in days'.
// Some examples:
// - 'easter-2' is Good Friday (2 days before Easter)
// - 'easter+1' is Easter Monday (1 day after Easter)
// - 'easter+39' is the Ascension Day
// - 'easter+49' is Pentecost
// # For holidays that are on a specific weekday after the beginning of a month: 'mm+n*w', where 'mm' is the month, 'n' is the ordinal position, 'w' is the weekday being 0: Sunday, 1: Monday, ..., 6: Saturnday
// For example:
// - Second (2) Monday (1) in October (10): '10+2*1'
// # For holidays that are on a specific weekday before the ending of a month: 'mm-n*w', where 'mm' is the month, 'n' is the ordinal position, 'w' is the weekday being 0: Sunday, 1: Monday, ..., 6: Saturnday
// For example:
// - Last (1) Saturnday (6) in Match (03): '03-1*6'
// - Last (1) Monday (1) in May (05): '05-1*1'
// # You can also specify a holiday that lasts more than one day. To do that use the format 'start>end' where 'start' and 'end' are specified as above.
// For example:
// - From 1 January to 6 January: '01-01>06-01'
// - Easter and the day after Easter: 'easter>easter+1'
// Limitations: currently the multi-day holydays can't cross an year. So, for example, you can't specify a range as '30-12>01-01'; as a workaround you can specify two distinct holidays (for instance '30-12>31-12' and '01-01').
holidays: {
}
};
|
require("./node");
var transform = module.exports = require("../transformation");
transform.options = require("../transformation/file/options");
transform.version = require("../../../package").version;
transform.transform = transform;
transform.run = function (code, opts = {}) {
opts.sourceMaps = "inline";
return new Function(transform(code, opts).code)();
};
transform.load = function (url, callback, opts = {}, hold) {
opts.filename = opts.filename || url;
var xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest();
xhr.open("GET", url, true);
if ("overrideMimeType" in xhr) xhr.overrideMimeType("text/plain");
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
var status = xhr.status;
if (status === 0 || status === 200) {
var param = [xhr.responseText, opts];
if (!hold) transform.run.apply(transform, param);
if (callback) callback(param);
} else {
throw new Error(`Could not load ${url}`);
}
};
xhr.send(null);
};
var runScripts = function () {
var scripts = [];
var types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"];
var index = 0;
var exec = function () {
var param = scripts[index];
if (param instanceof Array) {
transform.run.apply(transform, param);
index++;
exec();
}
};
var run = function (script, i) {
var opts = {};
if (script.src) {
transform.load(script.src, function (param) {
scripts[i] = param;
exec();
}, opts, true);
} else {
opts.filename = "embedded";
scripts[i] = [script.innerHTML, opts];
}
};
var _scripts = global.document .getElementsByTagName("script");
for (var i = 0; i < _scripts.length; ++i) {
var _script = _scripts[i];
if (types.indexOf(_script.type) >= 0) scripts.push(_script);
}
for (i in scripts) {
run(scripts[i], i);
}
exec();
};
if (global.addEventListener) {
global.addEventListener("DOMContentLoaded", runScripts, false);
} else if (global.attachEvent) {
global.attachEvent("onload", runScripts);
}
|
module.exports = require('./lib/connect')
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName: '',
errorMessages: Ember.computed('errors', function() {
if (this.get('errors.length')) {
return `${ this.get('errors').join(', ') }.`;
}
}),
actions: {
clearMessages() {
this.set('errors', null);
}
}
});
|
var cp_space_serializer_8h =
[
[ "cpSpaceSerializerDelegate", "classcp_space_serializer_delegate.html", "classcp_space_serializer_delegate" ],
[ "cpSpaceSerializer", "classcp_space_serializer.html", "classcp_space_serializer" ],
[ "__CPSPACESERIALIZER_H__", "cp_space_serializer_8h.html#aa21d15bcdad4b0f9b8c8d5023170964c", null ],
[ "CPSS_DEFAULT_MAKE_ID", "cp_space_serializer_8h.html#a7389a52166405857d02dd5966a6f1eca", null ],
[ "CPSS_ID", "cp_space_serializer_8h.html#a8cb859ab15a471ddef05a880ac60b41c", null ]
]; |
/*
Siesta 2.0.5
Copyright(c) 2009-2013 Bryntum AB
http://bryntum.com/contact
http://bryntum.com/products/siesta/license
*/
/**
@class Siesta.Recorder.TargetExtractor.Recognizer.DatePicker
*
* A class recognizing the Ext JS DatePicker component
**/
Class('Siesta.Recorder.TargetExtractor.Recognizer.DatePicker', {
methods : {
recognize : function (node) {
if (!node.className.match(/\bx-datepicker-date\b/)) {
return;
}
return [
['.x-datepicker-date:contains(' + node.innerHTML + ')']
];
}
}
});
|
var mongoose = require('mongoose');
var User = mongoose.model('User');
// Estrategia de autenticaciรณn con Twitter
var TwitterStrategy = require('passport-twitter').Strategy;
// Estrategia de autenticaciรณn con Facebook
var FacebookStrategy = require('passport-facebook').Strategy;
// Fichero de configuraciรณn donde se encuentran las API keys
// Este archivo no debe subirse a GitHub ya que contiene datos
// que pueden comprometer la seguridad de la aplicaciรณn.
var config = require('./config');
// Exportamos como mรณdulo las funciones de passport, de manera que
// podamos utilizarlas en otras partes de la aplicaciรณn.
// De esta manera, mantenemos el cรณdigo separado en varios archivos
// logrando que sea mรกs manejable.
module.exports = function(passport) {
// Serializa al usuario para almacenarlo en la sesiรณn
passport.serializeUser(function(user, done) {
done(null, user);
});
// Deserializa el objeto usuario almacenado en la sesiรณn para
// poder utilizarlo
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
// Configuraciรณn del autenticado con Twitter
passport.use(new TwitterStrategy({
consumerKey : config.twitter.key,
consumerSecret : config.twitter.secret,
callbackURL : '/auth/twitter/callback'
}, function(accessToken, refreshToken, profile, done) {
// Busca en la base de datos si el usuario ya se autenticรณ en otro
// momento y ya estรก almacenado en ella
User.findOne({provider_id: profile.id}, function(err, user) {
if(err) throw(err);
// Si existe en la Base de Datos, lo devuelve
if(!err && user!= null) return done(null, user);
// Si no existe crea un nuevo objecto usuario
var user = new User({
provider_id : profile.id,
provider : profile.provider,
name : profile.displayName,
photo : profile.photos[0].value
});
//...y lo almacena en la base de datos
user.save(function(err) {
if(err) throw err;
done(null, user);
});
});
}));
// Configuraciรณn del autenticado con Facebook
passport.use(new FacebookStrategy({
clientID : config.facebook.key,
clientSecret : config.facebook.secret,
callbackURL : '/auth/facebook/callback',
profileFields : ['id', 'displayName', /*'provider',*/ 'photos']
}, function(accessToken, refreshToken, profile, done) {
// El campo 'profileFields' nos permite que los campos que almacenamos
// se llamen igual tanto para si el usuario se autentica por Twitter o
// por Facebook, ya que cada proveedor entrega los datos en el JSON con
// un nombre diferente.
// Passport esto lo sabe y nos lo pone mรกs sencillo con ese campo
User.findOne({provider_id: profile.id}, function(err, user) {
if(err) throw(err);
if(!err && user!= null) return done(null, user);
// Al igual que antes, si el usuario ya existe lo devuelve
// y si no, lo crea y salva en la base de datos
var user = new User({
provider_id : profile.id,
provider : profile.provider,
name : profile.displayName,
photo : profile.photos[0].value
});
user.save(function(err) {
if(err) throw err;
done(null, user);
});
});
}));
};
|
/*!
* Bootstrap-select v1.13.1 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2018 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["jquery"], function (a0) {
return (factory(a0));
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else {
factory(root["jQuery"]);
}
}(this, function (jQuery) {
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Intet valgt',
noneResultsText: 'Ingen resultater fundet {0}',
countSelectedText: function (numSelected, numTotal) {
return (numSelected == 1) ? "{0} valgt" : "{0} valgt";
},
maxOptionsText: function (numAll, numGroup) {
return [
(numAll == 1) ? 'Begrรฆnsning nรฅet (max {n} valgt)' : 'Begrรฆnsning nรฅet (max {n} valgte)',
(numGroup == 1) ? 'Gruppe-begrรฆnsning nรฅet (max {n} valgt)' : 'Gruppe-begrรฆnsning nรฅet (max {n} valgte)'
];
},
selectAllText: 'Markรฉr alle',
deselectAllText: 'Afmarkรฉr alle',
multipleSeparator: ', '
};
})(jQuery);
}));
|
'use_strict';
/*
* Model Names Register:
* only registered model can have relations
*
* Relations register:
* there must be some evidence of relations, to prevent duplicities,
* and easy getting relation details, such as type, or constructor
*
*/
var _models = {};
var _relations = {};
module.exports = {
/**
* Register model name and his constructor
* @param {String} name Name of model, must be unique
* @param {Object} modelConstructor
*/
add: function(name, modelConstructor){
if(_models[name]) throw new Error('Model with name "' +name+ '" already exists, choose another name.');
_models[name] = modelConstructor;
},
/**
* Quick check if model name is registered
* @param {String} name model name
* @returns {Boolean} true/false
*/
has: function(name){
return !!_models[name];
},
/**
* Alias for has
* @param {String} name model name
* @returns {Boolean} true/false
*/
exists: function(name){
return !!_models[name];
},
/**
* Model Constructor getter
* @param {String} name registered constructor name
* @returns {Object} model constructor
*/
get: function(name){
return _models[name];
},
/**
* Model Constructor Names getter
* @returns {Array} model names
*/
getNames: function(){
return Object.keys(_models);
},
/**
* remove Model reference from registered model names
* use it only when you are replacing existing Model with another
* @param {String} name
*/
remove: function(name){
delete _models[name];
},
/**
* Models relation register
* @param {String} id unique relation id
* @param {Object} opts relation options
*/
setRelation: function(id, opts){
_relations[id] = opts;
},
/**
* Models relation getter
* @param {String} id relation id
* @returns {Object} relation options
*/
getRelation: function(id){
return _relations[id];
}
}; |
var _ = require('lodash'),
deepExtend = require('deep-extend');
module.exports = function (queryObj, properties, deep) {
return function updateRelations(assetGraph) {
assetGraph.findRelations(queryObj).forEach(function (relation) {
if (deep) {
deepExtend(relation, properties);
} else {
_.extend(relation, properties);
}
});
};
};
|
Date.prototype.format = function(format) {
var o = {
"M+" : this.getMonth() + 1, // month
"d+" : this.getDate(), // day
"h+" : this.getHours(), // hour
"m+" : this.getMinutes(), // minute
"s+" : this.getSeconds(), // second
"q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
"S" : this.getMilliseconds()
// millisecond
};
if (/(y+)/.test(format))
format = format.replace(RegExp.$1, (this.getFullYear() + "")
.substr(4 - RegExp.$1.length));
for ( var k in o)
if (new RegExp("(" + k + ")").test(format))
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
: ("00" + o[k]).substr(("" + o[k]).length));
return format;
}; |
(function() {
"use strict";
describe('Mouse controls - noSwitching Range Horizontal', function() {
var helper,
RzSliderOptions,
$rootScope,
$timeout;
beforeEach(module('test-helper'));
beforeEach(inject(function(TestHelper, _RzSliderOptions_, _$rootScope_, _$timeout_) {
helper = TestHelper;
RzSliderOptions = _RzSliderOptions_;
$rootScope = _$rootScope_;
$timeout = _$timeout_;
}));
afterEach(function() {
helper.clean();
});
beforeEach(function() {
var sliderConf = {
min: 45,
max: 55,
options: {
floor: 0,
ceil: 100,
noSwitching: true
}
};
helper.createRangeSlider(sliderConf);
});
afterEach(function() {
// to clean document listener
helper.fireMouseup();
});
it('should not switch min and max handles if minH is dragged after maxH', function() {
helper.fireMousedown(helper.slider.minH, 0);
var expectedValue = 60;
helper.moveMouseToValue(expectedValue);
expect(helper.scope.slider.min).to.equal(55);
});
it('should not switch min and max handles if maxH is dragged before minH', function() {
helper.fireMousedown(helper.slider.maxH, 0);
var expectedValue = 20;
helper.moveMouseToValue(expectedValue);
expect(helper.scope.slider.max).to.equal(45);
});
it('should move minH if minH==maxH and click is on the left side of the bar', function() {
helper.scope.slider.min = helper.scope.slider.max = 50;
helper.scope.$digest();
var expectedValue = 30,
offset = helper.getMousePosition(expectedValue);
helper.fireMousedown(helper.slider.fullBar, offset);
expect(helper.scope.slider.min).to.equal(30);
expect(helper.scope.slider.max).to.equal(50);
});
it('should move maxH if minH==maxH and click is on the right side of the bar', function() {
helper.scope.slider.min = helper.scope.slider.max = 50;
helper.scope.$digest();
var expectedValue = 70,
offset = helper.getMousePosition(expectedValue);
helper.fireMousedown(helper.slider.fullBar, offset);
expect(helper.scope.slider.min).to.equal(50);
expect(helper.scope.slider.max).to.equal(70);
});
});
describe('Right to left Mouse controls - noSwitching Range Horizontal', function() {
var helper,
RzSliderOptions,
$rootScope,
$timeout;
beforeEach(module('test-helper'));
beforeEach(inject(function(TestHelper, _RzSliderOptions_, _$rootScope_, _$timeout_) {
helper = TestHelper;
RzSliderOptions = _RzSliderOptions_;
$rootScope = _$rootScope_;
$timeout = _$timeout_;
}));
afterEach(function() {
helper.clean();
});
beforeEach(function() {
var sliderConf = {
min: 45,
max: 55,
options: {
floor: 0,
ceil: 100,
noSwitching: true,
rightToLeft: true
}
};
helper.createRangeSlider(sliderConf);
});
afterEach(function() {
// to clean document listener
helper.fireMouseup();
});
it('should not switch min and max handles if minH is dragged after maxH', function() {
helper.fireMousedown(helper.slider.minH, 0);
var expectedValue = 60;
helper.moveMouseToValue(expectedValue);
expect(helper.scope.slider.min).to.equal(55);
});
it('should not switch min and max handles if maxH is dragged before minH', function() {
helper.fireMousedown(helper.slider.maxH, 0);
var expectedValue = 20;
helper.moveMouseToValue(expectedValue);
expect(helper.scope.slider.max).to.equal(45);
});
it('should move minH if minH==maxH and click is on the left side of the bar', function() {
helper.scope.slider.min = helper.scope.slider.max = 50;
helper.scope.$digest();
var expectedValue = 30,
offset = helper.getMousePosition(expectedValue);
helper.fireMousedown(helper.slider.fullBar, offset);
expect(helper.scope.slider.min).to.equal(30);
expect(helper.scope.slider.max).to.equal(50);
});
it('should move maxH if minH==maxH and click is on the right side of the bar', function() {
helper.scope.slider.min = helper.scope.slider.max = 50;
helper.scope.$digest();
var expectedValue = 70,
offset = helper.getMousePosition(expectedValue);
helper.fireMousedown(helper.slider.fullBar, offset);
expect(helper.scope.slider.min).to.equal(50);
expect(helper.scope.slider.max).to.equal(70);
});
});
}());
|
function exposeTestFunctionNames() {
return [
'testGetItems',
'testGetNext',
'testGetPrev',
'testEach'
];
}
function testGetItems() {
var eventSource = tm.timeline.getBand(0).getEventSource(), items, item;
assertEquals("Four items in eventSource", 4, eventSource.getCount());
items = tm.getItems();
assertEquals("Timemap got all items", 4, items.length);
items = tm.datasets['test1'].getItems();
items = tm.datasets['test2'].getItems();
assertEquals("Dataset 2 got its items", 2, items.length);
item = tm.datasets['test1'].getItems(1);
assertEquals("Dataset got correct item by index", 'Test 1', item.getTitle());
}
function testGetNext() {
var item, target;
item = tm.datasets['test1'].getItems(1);
target = tm.datasets['test1'].getItems(0);
assertEquals("Found next w/in dataset", target, item.getNext());
item = tm.datasets['test1'].getItems(0);
target = tm.datasets['test2'].getItems(1);
assertEquals("Found next across datasets", target, item.getNext());
item = tm.datasets['test2'].getItems(0);
target = null;
assertEquals("Last item had no next", target, item.getNext());
}
function testGetPrev() {
var eventSource = tm.timeline.getBand(0).getEventSource();
// getPrev requires Timeline 2.2.0+ - skip test otherwise
if (eventSource.getReverseIterator) {
var item, target;
item = tm.datasets['test1'].getItems(0);
target = tm.datasets['test1'].getItems(1);
assertEquals("Found previous w/in dataset", target, item.getPrev());
item = tm.datasets['test2'].getItems(1);
target = tm.datasets['test1'].getItems(0);
assertEquals("Found previous across datasets", target, item.getPrev());
item = tm.datasets['test1'].getItems(1);
target = null;
assertEquals("First item had no previous", target, item.getPrev());
}
}
function testEach() {
var f1 = function(item) { item.flag = 1; };
tm.datasets['test1'].each(f1);
var items = tm.datasets['test1'].getItems();
for (var x=0; x<items.length; x++) {
assertEquals("Database function has been applied to item " + items[x].getTitle(), 1, items[x].flag);
}
var f2 = function(item) { item.flag = 2; };
tm.eachItem(f2);
var items = tm.getItems();
for (x=0; x<items.length; x++) {
assertEquals("Timemap function has been applied to item " + items[x].getTitle(), 2, items[x].flag);
}
var f3 = function(ds) { ds.flag = 3; };
tm.each(f3);
for (x=1; x<=2; x++) {
var ds = tm.datasets['test' + x];
assertEquals("Timemap function has been applied to dataset " + ds.getTitle(), 3, ds.flag);
}
}
// page setup script
function setUpPage() {
tm = TimeMap.init({
mapId: "map", // Id of map div element (required)
timelineId: "timeline", // Id of timeline div element (required)
datasets: [
{
title: "Test Dataset 1",
id: "test1",
type: "basic",
options: {
items: [
{
"start" : "1980-01-02",
"point" : {
"lat" : 23.456,
"lon" : 12.345
},
"title" : "Test 2"
},
{
"start" : "1980-01-01",
"point" : {
"lat" : 23.456,
"lon" : 12.345
},
"title" : "Test 1"
}
]
}
},
{
title: "Test Dataset 2",
id: "test2",
type: "basic",
options: {
items: [
{
"start" : "1980-01-05",
"point" : {
"lat" : 23.456,
"lon" : 12.345
},
"title" : "Test 4"
},
{
"start" : "1980-01-04",
"point" : {
"lat" : 23.456,
"lon" : 12.345
},
"title" : "Test 3"
}
]
}
}
]
});
setUpPageStatus = "complete";
}
function setUp() {
var eventSource = tm.timeline.getBand(0).getEventSource();
tm.timeline.getBand(0).setCenterVisibleDate(eventSource.getEarliestDate());
tm.showDatasets();
}
|
module.exports = function (grunt) {
require('load-grunt-tasks')(grunt);
var pkg = grunt.file.readJSON('package.json');
var colors = {
'red': '#F44336',
'pink': '#E91E63',
'purple': '#9C27B0',
'deep-purple': '#673AB7',
'indigo': '#3F51B5',
'blue': '#2196F3',
'light-blue': '#039BE5',
'cyan': '#0097A7',
'teal': '#26A69A',
'green': '#43A047',
'light-green': '#689F38',
'lime': '#AFB42B',
'yellow': '#FBC02D',
'amber': '#FF6F00',
'orange': '#EF6C00',
'deep-orange': '#FF5722',
'brown': '#795548',
'grey': '#757575',
'blue-grey': '#607D8B'
};
var fileCreatorTask = {};
var lessFiles = {
"dist/material-light.css": "less/style.less",
"dist/material-static.css": "less/static.less"
};
var replaceFiles = [
{src: ['dist/material-light.css'], dest: 'dist/material-light.css'},
{src: ['dist/material-static.css'], dest: 'dist/material-static.css'},
{src: ['plugin/pom.xml'], dest: 'plugin/pom.xml'}
];
var cssMinFiles = {
'dist/material-light.css': ['dist/material-light.css'],
'dist/material-static.css': ['dist/material-static.css']
};
for (var name in colors) {
var color = colors[name];
fileCreatorTask['.tmp/' + name + '.less'] = new Function('fs', 'fd', 'done', '{\
fs.writeFileSync(fd, \'@import "../less/style";@color-primary:' + color + ';@color-link:' + color + ';\');\
done();\
}');
var distFile = 'dist/material-' + name + '.css';
lessFiles[distFile] = '.tmp/' + name + '.less';
replaceFiles.push({src: [distFile], dest: distFile});
cssMinFiles[distFile] = distFile
}
grunt.initConfig({
"file-creator": {
dist: fileCreatorTask
},
clean: {
dist: {
src: ["dist/*"]
}
},
imagemin: {
dynamic: {
options: {
svgoPlugins: [{
removeDoctype: true,
removeXMLProcInst: true,
removeComments: true,
removeMetadata: true,
removeTitle: true,
removeDesc: true,
removeUselessDefs: true,
removeEditorsNSData: true,
removeEmptyAttrs: true,
removeHiddenElems: true,
removeEmptyText: true,
removeEmptyContainers: true,
removeViewBox: true,
cleanUpEnableBackground: true,
minifyStyles: true,
convertStyleToAttrs: true,
convertColors: true,
convertPathData: true,
convertTransform: true,
removeUnknownsAndDefaults: true,
removeNonInheritableGroupAttrs: true,
removeUselessStrokeAndFill: true,
removeUnusedNS: true,
cleanupIDs: true,
cleanupNumericValues: true,
moveElemsAttrsToGroup: true,
moveGroupAttrsToElems: true,
collapseGroups: true,
removeRasterImages: true,
mergePaths: true,
convertShapeToPath: true,
sortAttrs: true,
transformsWithOnePath: true,
removeDimensions: true,
removeAttrs: true,
addClassesToSVGElement: true,
removeStyleElement: true
}]
},
files: [{
expand: true,
cwd: 'node_modules/jenkins-core-theme/images/',
src: ['**/*.svg'],
dest: 'node_modules/jenkins-core-theme/images/'
}]
}
},
less: {
dist: {
files: lessFiles
}
},
replace: {
dist: {
options: {
patterns: [
{
match: 'version',
replacement: pkg.version
},
{
match: /material-theme<\/artifactId>\s+<version>[^>]*<\/version>/g,
replacement: 'material-theme</artifactId>\n <version>' + pkg.version + '</version>'
}
]
},
files: replaceFiles
}
},
cssmin: {
minify: {
files: cssMinFiles
}
},
postcss: {
options: {
map: false,
processors: [
require('autoprefixer')({browsers: 'last 2 versions'}), // add vendor prefixes
require('postcss-encode-base64-inlined-images'),
require('cssnano')() // minify the result
]
},
dist: {
src: 'dist/material*.css'
}
},
imageEmbed: {
light: {
src: ["dist/material-light.css"],
dest: "dist/material-light.css",
options: {
deleteAfterEncoding: false
}
}, light_blue: {
src: ["dist/material-light-blue.css"],
dest: "dist/material-light-blue.css",
options: {
deleteAfterEncoding: false
}
},
static: {
src: ["dist/material-static.css"],
dest: "dist/material-static.css",
options: {
deleteAfterEncoding: false
}
}
},
fileExists: {
scripts: Object.keys(lessFiles)
}
});
// Default task(s).
grunt.registerTask('default', ['clean', 'file-creator', 'imagemin', 'less', 'replace', 'cssmin', 'postcss']);
grunt.registerTask('test', ['default', 'fileExists']);
};
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
global.ng.common.locales['sw'] = [
'sw',
[['am', 'pm'], ['AM', 'PM'], u],
[['AM', 'PM'], u, u],
[
['S', 'M', 'T', 'W', 'T', 'F', 'S'],
['Jumapili', 'Jumatatu', 'Jumanne', 'Jumatano', 'Alhamisi', 'Ijumaa', 'Jumamosi'], u, u
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Des'],
[
'Januari', 'Februari', 'Machi', 'Aprili', 'Mei', 'Juni', 'Julai', 'Agosti', 'Septemba',
'Oktoba', 'Novemba', 'Desemba'
]
],
u,
[['KK', 'BK'], u, ['Kabla ya Kristo', 'Baada ya Kristo']],
1,
[6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
['{1} {0}', u, u, u],
['.', ',', ';', '%', '+', '-', 'E', 'ร', 'โฐ', 'โ', 'NaN', ':'],
['#,##0.###', '#,##0%', 'ยคย #,##0.00', '#E0'],
'TZS',
'TSh',
'Shilingi ya Tanzania',
{
'JPY': ['JPยฅ', 'ยฅ'],
'KES': ['Ksh'],
'THB': ['เธฟ'],
'TWD': ['NT$'],
'TZS': ['TSh'],
'USD': ['US$', '$']
},
'ltr',
plural,
[
[
['usiku', 'mchana', 'alfajiri', 'asubuhi', 'mchana', 'jioni', 'usiku'],
['saa sita za usiku', 'adhuhuri', 'alfajiri', 'asubuhi', 'mchana', 'jioni', 'usiku'],
[
'saa sita za usiku', 'saa sita za mchana', 'alfajiri', 'asubuhi', 'mchana', 'jioni',
'usiku'
]
],
[
[
'saa sita za usiku', 'saa sita za mchana', 'alfajiri', 'asubuhi', 'mchana', 'jioni',
'usiku'
],
['saa sita za usiku', 'adhuhuri', 'alfajiri', 'asubuhi', 'alasiri', 'jioni', 'usiku'],
[
'saa sita za usiku', 'saa sita za mchana', 'alfajiri', 'asubuhi', 'mchana', 'jioni',
'usiku'
]
],
[
'00:00', '12:00', ['04:00', '07:00'], ['07:00', '12:00'], ['12:00', '16:00'],
['16:00', '19:00'], ['19:00', '04:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
|
Resizeable = Class.create();
Resizeable.prototype = {
startX: null,
startY: null,
startWidth: null,
startHeight: null,
active: false,
elem: null,
cont: null,
handle: null,
onend: null,
minWidth: 0,
minHeight: 0,
initialize: function(container,element,options) {
this.cont = $(container);
this.elem = $(element);
if(options.minWidth) this.minWidth = options.minWidth;
if(options.minHeight) this.minHeight = options.minHeight;
if(options.onEnd) {
this.onend = options.onEnd;
}
this.handle = $(options.handle);
Element.makePositioned(container);
this.eventMouseDown = this.onMouseDown.bindAsEventListener(this);
this.eventMouseUp = this.onMouseUp.bindAsEventListener(this);
this.eventMouseMove = this.onMouseMove.bindAsEventListener(this);
Event.observe(this.handle, "mousedown", this.eventMouseDown);
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mousemove", this.eventMouseMove);
Event.observe(this.handle, "mousemove", this.eventMouseMove);
this.heightDiff = this.cont.getHeight() - this.elem.getHeight();
},
mousePos: function(e) {
return { x: Event.pointerX(e), y: Event.pointerY(e) };
},
onMouseDown: function(e) {
var pos = this.mousePos(e);
this.startX = pos.x;
this.startY = pos.y;
this.containerWidth = this.cont.getWidth();
this.containerHeight = this.cont.getHeight();
document.body.focus(); // Keep firefox from dragging selected text
document.onselectstart=function(event){window.event.returnValue=false; return false;} // Prevent IE highlight text
this.handle.ondragstart = function() { return false; }// Prevent IE image drag
this.active = true;
return false; // Cancel additional events
},
onMouseUp: function(e) {
if(this.active) {
this.onMouseMove(e);
document.onselectstart=null; // Cancel IE funcs
this.handle.ondragstart = null; // Cancel IE funcs
this.active = false;
if(this.onend) this.onend();
return false; // Cancel additional events
}
},
onMouseMove: function(e) {
if(this.active) {
var pos = this.mousePos(e);
var diffX = pos.x - this.startX;
var diffY = pos.y - this.startY;
var newWidth = (this.containerWidth + diffX);
if(newWidth < this.minWidth) newWidth = this.minWidth;
var newHeight = (this.containerHeight + diffY);
if(newHeight < this.minHeight) newHeight = this.minHeight;
this.cont.style.width = newWidth + "px";
this.cont.style.height = newHeight + "px";
//this.elem.style.width = (this.startWidth + diffX) + "px";
this.elem.style.height = (newHeight - this.heightDiff) + "px";
if(Prototype.Browser.WebKit) window.scrollBy(0,0);
document.body.focus(); // Keep firefox from dragging selected text
return false;
}
}
};
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/main'
],
output: {
path: path.join(__dirname, 'public', 'dist'),
filename: 'app.js',
publicPath: 'http://localhost:3000/dist/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel-loader'],
}
]
},
devtool: 'eval',
}
|
$(function() {
$(".article-sidebar .sticky").css('width', $(".article-sidebar .sticky").width()-2);
$(".article-sidebar .sticky").sticky({topSpacing:45});
$(".article-sidebar ul.categories a").on('click', function(e) {
if (!$(this).siblings('ul').length)
return;
e.preventDefault();
$(this).parent().toggleClass('active');
});
function checkSuggestion() {
var viewport_bottom = $window.scrollTop() + $window.height();
var height = $elem.height();
var bottom = $elem.offset().top + $elem.height();
if (bottom <= viewport_bottom) {
$target.fadeIn();
} else {
$target.fadeOut();
}
}
if ($('.article-suggest').length) {
var $window = $(window);
var $elem = $('article.body');
var $target = $('.article-suggest');
$window.scroll(checkSuggestion);
checkSuggestion();
}
// CONTRIBUTORS
$('.contributors > li .header').on('click', function(e) {
$(this).siblings('ul').slideToggle();
});
}); |
"use strict";
// this prevents Rekuire from being cached, so 'parent' is always updated
delete require.cache[require.resolve(__filename)];
var path = require('path');
var scanner = require('./helpers/scanner');
var findBase = require('./helpers/findBase');
var baseDir = findBase(module.parent.paths);
var pkg = require(path.join(baseDir, "package.json"));
if (pkg.rekuire){
if (pkg.rekuire.ignore){
scanner.ignore(pkg.rekuire.ignore);
}
}
var _ = require('underscore');
var extensions = ['.js','.json','.coffee'];
// SCANNING THE FOLDERS AS SOON AS THIS FILE LOADS
var scanResults = scanner.scan(baseDir,extensions);
var filesInProject = scanResults.filesInProject;
var ambiguousFileNames = scanResults.ambiguousFileNames;
module.exports = rekuire;
function rekuire(requirement){
return getModule(requirement).module
}
/**
**********************************
PUBLIC METHODS
**********************************
**/
rekuire.path = function(requirement){
return getPath(requirement);
};
rekuire.ignore = function(/*args*/){
var args = Array.prototype.slice.call(arguments);
scanner.ignore(args);
scanResults = scanner.rescan();
filesInProject = scanResults.filesInProject;
ambiguousFileNames = scanResults.ambiguousFileNames;
};
/**
**********************************
PRIVATE METHODS
**********************************
**/
function getPath(requirement){
var location = getModule(requirement).path;
if (location === undefined){
throw "Could not locate a local for a module named ["+requirement+"]";
}
return location;
}
function isDefined(val){
return typeof val === 'string' || typeof val === 'object' ;
}
function getModule(requirement){
var calleePath = path.dirname(module.parent.filename);
var parentReq = module.parent.require.bind(module);
var retModule = null;
var modulePath = null;
var error = "";
if (isDefined(ambiguousFileNames[requirement])){
throw new Error('Ambiguity Error: There are more then one files that is named '+requirement+
'. \n\t' + ambiguousFileNames[requirement].join('\n\t') +
'\nYou can use require("rekuire").ignore("folder_to_ignore") to prevent Rekuire from scanning unwanted folders.');
}
if (isDefined(filesInProject[requirement])){
// User typed in a relative path
retModule = parentReq(filesInProject[requirement]);
modulePath = filesInProject[requirement];
}else{
// User typed in a module name
modulePath = path.normalize(calleePath+"/"+requirement);
try{
retModule = parentReq(modulePath);
}catch(e){
// module by that name was not found in the scanner, maybe it's a general node module.
error += e +"\n";
}
// General node module
if (retModule == null){
modulePath = requirement;
try{
retModule = parentReq(requirement);
}catch(e){
error += e +"\n";
}
}
}
if(!retModule){
throw new Error("Can not find a module by the name of ["+requirement+"] or it has returned empty. nested: "+error);
}
return { module: retModule, path: modulePath};
}
|
let WebpackExtractPlugin = require('extract-text-webpack-plugin')
class ExtractTextPluginFactory {
/**
* Create a new class instance.
*
* @param {string|boolean} cssPath
*/
constructor(mix, cssPath) {
if (typeof cssPath === 'boolean') {
cssPath = path.join(global.entry.base || '', 'vue-styles.css');
this.useDefault = true;
}
this.mix = mix;
this.path = cssPath;
}
/**
* Build up the necessary ExtractTextPlugin instance.
*/
build() {
if (this.mix.preprocessors) {
// If no output path is provided, we can use the default plugin.
if (this.useDefault) return this.mix.preprocessors[0].getExtractPlugin();
// If what the user passed matches the output to mix.preprocessor(),
// then we can use that plugin instead and append to it.
if (this.pluginIsAlreadyBuilt()) return this.getPlugin();
}
// Otherwise, we'll setup a new plugin to toss the styles into it.
return new WebpackExtractPlugin(this.outputPath());
}
/**
* Check if the the provided path is already registered as an extract instance.
*/
pluginIsAlreadyBuilt() {
return this.mix.preprocessors.find(
preprocessor => preprocessor.output.path === this.path
);
}
/**
* Fetch the Extract plugin instance that matches the current output path.
*/
getPlugin() {
return this.mix.preprocessors.find(
preprocessor => preprocessor.getExtractPlugin().filename === this.outputPath()
).getExtractPlugin();
}
/**
* Prepare the appropriate output path.
*/
outputPath() {
let segments = new File(this.path).parsePath();
let regex = new RegExp('^(\.\/)?' + global.options.publicPath);
let pathVariant = global.options.versioning ? 'hashedPath' : 'path';
return segments[pathVariant].replace(regex, '').replace(/\\/g, '/');
}
}
module.exports = ExtractTextPluginFactory;
|
'use strict';
var extname = require('../extname');
/**
* Constants
*/
var TARGET_TYPES = ['html', 'jade', 'slm', 'jsx', 'haml'];
var IMAGES = ['jpeg', 'jpg', 'png', 'gif'];
var DEFAULT_TARGET = TARGET_TYPES[0];
/**
* Transform module
*/
var transform = module.exports = exports = function (filepath, i, length, sourceFile, targetFile) {
var type;
if (targetFile && targetFile.path) {
var ext = extname(targetFile.path);
type = typeFromExt(ext);
}
if (!isTargetType(type)) {
type = DEFAULT_TARGET;
}
var func = transform[type];
if (func) {
return func.apply(transform, arguments);
}
};
/**
* Options
*/
transform.selfClosingTag = false;
/**
* Transform functions
*/
TARGET_TYPES.forEach(function (targetType) {
transform[targetType] = function (filepath) {
var ext = extname(filepath);
var type = typeFromExt(ext);
var func = transform[targetType][type];
if (func) {
return func.apply(transform[targetType], arguments);
}
};
});
transform.html.css = function (filepath) {
return '<link rel="stylesheet" href="' + filepath + '"' + end();
};
transform.html.js = function (filepath) {
return '<script src="' + filepath + '"></script>';
};
transform.html.jsx = function (filepath) {
return '<script type="text/jsx" src="' + filepath + '"></script>';
};
transform.html.html = function (filepath) {
return '<link rel="import" href="' + filepath + '"' + end();
};
transform.html.coffee = function (filepath) {
return '<script type="text/coffeescript" src="' + filepath + '"></script>';
};
transform.html.image = function (filepath) {
return '<img src="' + filepath + '"' + end();
};
transform.jade.css = function (filepath) {
return 'link(rel="stylesheet", href="' + filepath + '")';
};
transform.jade.js = function (filepath) {
return 'script(src="' + filepath + '")';
};
transform.jade.jade = function (filepath) {
return 'include ' + filepath;
};
transform.jade.html = function (filepath) {
return 'link(rel="import", href="' + filepath + '")';
};
transform.jade.coffee = function (filepath) {
return 'script(type="text/coffeescript", src="' + filepath + '")';
};
transform.jade.image = function (filepath) {
return 'img(src="' + filepath + '")';
};
transform.slm.css = function (filepath) {
return 'link rel="stylesheet" href="' + filepath + '"';
};
transform.slm.js = function (filepath) {
return 'script src="' + filepath + '"';
};
transform.slm.html = function (filepath) {
return 'link rel="import" href="' + filepath + '"';
};
transform.slm.coffee = function (filepath) {
return 'script type="text/coffeescript" src="' + filepath + '"';
};
transform.slm.image = function (filepath) {
return 'img src="' + filepath + '"';
};
transform.haml.css = function (filepath) {
return '%link{rel:"stylesheet", href:"' + filepath + '"}';
};
transform.haml.js = function (filepath) {
return '%script{src:"' + filepath + '"}';
};
transform.haml.html = function (filepath) {
return '%link{rel:"import", href:"' + filepath + '"}';
};
transform.haml.coffee = function (filepath) {
return '%script{type:"text/coffeescript", src:"' + filepath + '"}';
};
transform.haml.image = function (filepath) {
return '%img{src:"' + filepath + '"}';
};
/**
* Transformations for jsx is like html
* but always with self closing tags, invalid jsx otherwise
*/
Object.keys(transform.html).forEach(function (type) {
transform.jsx[type] = function () {
var originalOption = transform.selfClosingTag;
transform.selfClosingTag = true;
var result = transform.html[type].apply(transform.html, arguments);
transform.selfClosingTag = originalOption;
return result;
};
});
function end () {
return transform.selfClosingTag ? ' />' : '>';
}
function typeFromExt (ext) {
ext = ext.toLowerCase();
if (isImage(ext)) {
return 'image';
}
return ext;
}
function isImage (ext) {
return IMAGES.indexOf(ext) > -1;
}
function isTargetType (type) {
if (!type) {
return false;
}
return TARGET_TYPES.indexOf(type) > -1;
}
|
var response_lib = require('../lib/response_lib');
var reql = require('../lib/request_lib');
function timestags (keys) {
this.myKeys = keys;
}
timestags.prototype.search = function (args, callback, myKeys) {
var callbackReturn = response_lib.checkCallback(args, callback);
args = callbackReturn.args;
callback = callbackReturn.callback;
var query = response_lib.checkQuery(args);
var path = '/'.concat('svc/', 'suggest/v1/timestags?',
query, 'api-key=', this.myKeys['timestags']);
reql.get(path, callback, args);
console.log("THIS");
};
module.exports = timestags;
|
var errors = require('./errors');
function Collection() {
this.store = {};
this.lastId = 0;
}
Collection.prototype.seed = function(obj, cb) {
this.store = obj;
cb();
};
Collection.prototype.findAll = function(cb) {
var items = [];
for (var id in this.store) {
items.push(this.store[id]);
}
cb(null, items);
};
Collection.prototype.create = function(obj, cb) {
this.lastId++;
obj.id = this.lastId;
this.store[this.lastId] = obj;
cb(null, obj);
};
Collection.prototype.update = function(id, obj, cb) {
this.find(id, function(err, item) {
if (err) return cb(err);
for (var key in obj) {
item[key] = obj[key];
}
cb(null, item);
});
};
Collection.prototype.find = function(id, cb) {
id = parseInt(id, 10);
var obj = this.store[id];
if (obj) {
cb(null, obj);
} else {
cb(new errors.NotFound('Item not found'));
}
};
module.exports.notes = new Collection('notes');
|
/* */
"format global";
/**
* Copyright 2015 Telerik AD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["gn-PY"] = {
name: "gn-PY",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["-n $","n $"],
decimals: 0,
",": ".",
".": ",",
groupSize: [3],
symbol: "โฒ"
}
},
calendars: {
standard: {
days: {
names: ["arateฤฉ","arakรตi","araapy","ararundy","arapo","arapoteฤฉ","arapokรตi"],
namesAbbr: ["teฤฉ","kรตi","apy","ndy","po","oteฤฉ","okรตi"],
namesShort: ["A1","A2","A3","A4","A5","A6","A7"]
},
months: {
names: ["jasyteฤฉ","jasykรตi","jasyapy","jasyrundy","jasypo","jasypoteฤฉ","jasypokรตi","jasypoapy","jasyporundy","jasypa","jasypateฤฉ","jasypakรตi"],
namesAbbr: ["jteฤฉ","jkรตi","japy","jrun","jpo","jpot","jpok","jpoa","jpor","jpa","jpat","jpak"]
},
AM: ["a.m.","a.m.","A.M."],
PM: ["p.m.","p.m.","P.M."],
patterns: {
d: "dd/MM/yyyy",
D: "dddd, dd MMMM, yyyy",
F: "dddd, dd MMMM, yyyy HH:mm:ss",
g: "dd/MM/yyyy HH:mm",
G: "dd/MM/yyyy HH:mm:ss",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM, yyyy",
Y: "MMMM, yyyy"
},
"/": "/",
":": ":",
firstDay: 0
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); |
import React from 'react';
import SvgIcon from '../../SvgIcon';
const HardwareKeyboardArrowLeft = (props) => (
<SvgIcon {...props}>
<path d="M15.41 16.09l-4.58-4.59 4.58-4.59L14 5.5l-6 6 6 6z"/>
</SvgIcon>
);
HardwareKeyboardArrowLeft.displayName = 'HardwareKeyboardArrowLeft';
HardwareKeyboardArrowLeft.muiName = 'SvgIcon';
export default HardwareKeyboardArrowLeft;
|
var _ = require('underscore'),
$ = require('jquery'),
React = require('react'),
Field = require('../Field'),
Note = require('../../components/Note'),
Select = require('react-select');
module.exports = Field.create({
shouldCollapse: function() {
return this.props.collapse && !this.hasExisting();
},
fileFieldNode: function() {
return this.refs.fileField.getDOMNode();
},
changeFile: function() {
this.refs.fileField.getDOMNode().click();
},
getFileSource: function() {
if (this.hasLocal()) {
return this.state.localSource;
} else if (this.hasExisting()) {
return this.props.value.url;
} else {
return null;
}
},
getFileURL: function() {
if (!this.hasLocal() && this.hasExisting()) {
return this.props.value.url;
}
},
undoRemove: function() {
this.fileFieldNode().value = '';
this.setState({
removeExisting: false,
localSource: null,
origin: false,
action: null
});
},
fileChanged: function (event) {
this.setState({
origin: 'local'
});
},
removeFile: function (e) {
var state = {
localSource: null,
origin: false
};
if (this.hasLocal()) {
this.fileFieldNode().value = '';
} else if (this.hasExisting()) {
state.removeExisting = true;
if (this.props.autoCleanup) {
if (e.altKey) {
state.action = 'reset';
} else {
state.action = 'delete';
}
} else {
if (e.altKey) {
state.action = 'delete';
} else {
state.action = 'reset';
}
}
}
this.setState(state);
},
hasLocal: function() {
return this.state.origin === 'local';
},
hasFile: function() {
return this.hasExisting() || this.hasLocal();
},
hasExisting: function() {
return !!this.props.value.filename;
},
getFilename: function() {
if (this.hasLocal()) {
return this.fileFieldNode().value.split('\\').pop();
} else {
return this.props.value.filename;
}
},
renderFileDetails: function (add) {
var values = null;
if (this.hasFile() && !this.state.removeExisting) {
values = <div className='file-values'>
<div className='field-value'>{this.getFilename()}</div>
</div>;
}
return <div key={this.props.path + '_details'} className='file-details'>
{values}
{add}
</div>;
},
renderAlert: function() {
if (this.hasLocal()) {
return <div className='upload-queued pull-left'>
<div className='alert alert-success'>File selected - save to upload</div>
</div>;
} else if (this.state.origin === 'cloudinary') {
return <div className='select-queued pull-left'>
<div className='alert alert-success'>File selected from Cloudinary</div>
</div>;
} else if (this.state.removeExisting) {
return <div className='delete-queued pull-left'>
<div className='alert alert-danger'>File {this.props.autoCleanup ? 'deleted' : 'removed'} - save to confirm</div>
</div>;
} else {
return null;
}
},
renderClearButton: function() {
if (this.state.removeExisting) {
return <button type='button' className='btn btn-link btn-cancel btn-undo-file' onClick={this.undoRemove}>
Undo Remove
</button>;
} else {
var clearText;
if (this.hasLocal()) {
clearText = 'Cancel Upload';
} else {
clearText = (this.props.autoCleanup ? 'Delete File' : 'Remove File');
}
return <button type='button' className='btn btn-link btn-cancel btn-delete-file' onClick={this.removeFile}>
{clearText}
</button>;
}
},
renderFileField: function() {
return <input ref='fileField' type='file' name={this.props.paths.upload} className='field-upload' onChange={this.fileChanged} />;
},
renderFileAction: function() {
return <input type='hidden' name={this.props.paths.action} className='field-action' value={this.state.action} />;
},
renderFileToolbar: function() {
return <div key={this.props.path + '_toolbar'} className='file-toolbar'>
<div className='pull-left'>
<button type='button' onClick={this.changeFile} className='btn btn-default btn-upload-file'>
{this.hasFile() ? 'Change' : 'Upload'} File
</button>
{this.hasFile() && this.renderClearButton()}
</div>
</div>;
},
renderUI: function() {
var container = [],
body = [],
hasFile = this.hasFile(),
fieldClassName = 'field-ui';
if (hasFile) {
fieldClassName += ' has-file';
}
if (this.shouldRenderField()) {
if (hasFile) {
container.push(this.renderFileDetails(this.renderAlert()));
}
body.push(this.renderFileToolbar());
} else {
if (hasFile) {
container.push(this.renderFileDetails());
} else {
container.push(<div className='help-block'>no file</div>);
}
}
return <div className='field field-type-localfile'>
<label className='field-label'>{this.props.label}</label>
{this.renderFileField()}
{this.renderFileAction()}
<div className={fieldClassName}>
<div className='file-container'>{container}</div>
{body}
<Note note={this.props.note} />
</div>
</div>;
}
});
|
var _ = require('lodash');
var jsParser = require('esprima');
var walk = require('dgeni-packages/jsdoc/lib/walk');
var LEADING_STAR = /^[^\S\r\n]*\*[^\S\n\r]?/gm;
module.exports = {
name: 'jsdoc',
description: 'Read js documents',
runAfter: ['files-read'],
runBefore: ['parsing-tags'],
exports: {
//The jsdoc file reader isn't able to handle docs of non-js type,
//so we simply put all the other docs into a placeholder array
//until jsdoc processing is done
otherDocs: ['value', []],
},
process: function(docs, config, otherDocs) {
var jsdocDocs = [];
docs.forEach(function(doc) {
if (doc.docType === 'source' && doc.fileType === 'js') {
jsdocDocs = jsdocDocs.concat(parseComments(doc));
} else {
otherDocs.push(doc);
}
});
return jsdocDocs;
}
};
function parseComments(doc) {
var ast = jsParser.parse(doc.content, {
loc: true,
range: true,
comment: true
});
// Below code is adapted from the jsdoc dgeni-package by Pete Bacon Darwin
// https://github.com/angular/dgeni-packages
// https://github.com/angular/dgeni-packages/blob/master/LICENSE
return _(ast.comments)
.filter(function(comment) {
// To test for a jsdoc comment (i.e. starting with /** ), we need to check for
// a leading star since the parser strips off the first "/*"
return comment.type === 'Block' && comment.value.charAt(0) === '*';
})
.map(function(comment) {
// Strip off any leading stars
var text = comment.value.replace(LEADING_STAR, '');
// Trim off leading and trailing whitespace
text = text.trim();
// Extract the information about the code directly after this comment
var codeNode = walk.findNodeAfter(ast, comment.range[1]);
var codeAncestors = codeNode && walk.ancestor(ast, codeNode.node);
// Create a doc from this comment
return _.assign({}, doc, {
startingLine: comment.loc.start.line,
endingLine: comment.loc.end.line,
content: text,
codeNode: codeNode,
codeAncestors: codeAncestors
});
})
.value();
}
|
var extend = require('extend');
var _ = require('lodash');
var async = require('async');
var nodemailer = require('nodemailer');
var nunjucks = require('nunjucks');
var urls = require('url');
/**
* emailMixin
* @augments Augments the apos object with a mixin method for attaching
* a simple self.email method to modules, so that they can delivewr email
* conveniently using templates rendered in the context of that module.
* @see static
*/
module.exports = function(self) {
// This mixin adds a self.email method to the specified module object.
//
// Your module must also have mixinModuleAssets.
//
// IF YOU ARE WRITING A SUBCLASS OF AN OBJECT THAT ALREADY HAS THIS MIXIN
//
// When subclassing you do NOT need to invoke this mixin as the methods
// are already present on the base class object.
//
// HOW TO USE THE MIXIN
//
// If you are creating a new module from scratch that does not subclass another,
// invoke the mixin this way in your constructor:
//
// `self._apos.mixinModuleEmail(self);`
//
// Then you may send email like this throughout your module:
//
// return self.email(
// req,
// person,
// 'Your request to reset your password on {{ host }}',
// 'resetRequestEmail',
// {
// url: self._action + '/reset?reset=' + reset
// },
// function(err) { ... }
// );
//
// REQUEST OBJECT
//
// "req" is the request object and must be present.
//
// SENDER ("FROM")
//
// "from" is the full name and email address of the sender. You may
// pass a string formatted like this:
//
// "Bob Smith <bob@example.com>"
//
// OR an object with "email" and "fullName" properties. "title" is also
// accepted if "fullName" is not present.
//
// Note that req.user (when logged in) and any "person" object from
// apostrophe-people are both acceptable as "from" arguments.
//
// You may omit the "from" argument and set it via configuration in
// app.js instead as described below.
//
// If you omit it AND don't configure it, you'll get a terrible "from" address!
// You have been warned!
//
// RECIPIENT
//
// "to" works just like "from". However, it is required and there are no
// options for it in app.js.
//
// SUBJECT LINE
//
// The fourth argument is the subject line. It is rendered by nunjucks and can see
// the data you pass in the sixth argument and other variables as described below.
//
// It is easy to override the subject in app.js as described below.
//
// TEMPLATE NAME
//
// The fifth argument is the template name. If it is "resetRequestEmail", then
// self.email will look for the templates resetRequestEmail.txt and resetRequestEmail.html
// in your module's views folder, render both of them, and build an email with both
// plaintext and HTML parts for maximum compatibility. You can override these templates
// at project level in lib/modules/modulename exactly as you would for any other template.
//
// DATA
//
// All properties passed as part of the sixth argument are passed to the templates
// as nunjucks data. They are also available in the subject line.
//
// In addition, the following variables are automatically supplied:
//
// "host" is the hostname of the site, as determined from req.
//
// "baseUrl" is the base URL of the site, like: http://sitename.com
//
// ABSOLUTE URLS
//
// URLs in emails must be absolute, but most of the time in your code you use
// relative URLs starting with /. As a convenience, self.email() will automatically
// transform properties beginning with "url" or ending in "Url" into
// absolute URLs before passing your data on to the templates. This rule is
// applied recursively to the data object, so an array of events will all have
// their .url properties made absolute.
//
// SENDING EMAIL IN TASKS
//
// The req object used in tasks will generate the correct absolute URLs
// only if you add a "baseUrl" property to it, which should look like:
//
// http://mysite.com
//
// Note there is no slash after the hostname.
//
// CALLBACK
//
// The final argument is a standard node callback function and will receive
// an error if any takes place.
//
// CONFIGURATION: EASY OVERRIDES IN APP.JS VIA THE "EMAIL" OPTION
//
// NOTE: FOR THESE FEATURES TO WORK, your module must set self._options or
// self.options to the options object it was configured with. This happens
// automatically for everything derived from apostrophe-snippets.
//
// When you configure your module, pass an object as the "email" option, with
// sub-properties as described below.
//
// OVERRIDING THE SUBJECT
//
// The subject can be overridden in app.js when configuring your module.
// If the template name (fifth argument) is "resetRequestEmail", then the
// option "resetRequestEmailSubject" overrides the subject.
//
// OVERRIDING THE "FROM" ADDRESS
//
// It is easy to override the "from" address. If the "from" option is
// a string or is absent, and the template name is "resetRequestEmail", then the
// "resetRequestEmailFrom" option determines who the email comes from if
// present. If there is no such option then the "from" option
// determines who the email comes from. If this option is not set either
// and the "from" argument was omitted, then the email comes from:
//
// 'Do Not Reply <donotreply@example.com>'
//
// But this is terrible, so make sure you set the appropriate options.
//
// In app.js you may set the from address to a string in this format:
// "Bob Smith <donotreply@example.com>"
//
// Or use an object with fullName and email properties.
//
// PLEASE NOTE: if you pass an object as the "from" argument, configuration options are
// always ignored in favor of what you passed. However if you pass a string it is
// assumed to be a hard-coded default and options are allowed to override it.
self.mixinModuleEmail = function(module) {
module.email = function(req, from, to, subject, template, data, callback) {
var moduleOptions = module._options || module.options || {};
var options = moduleOptions.email || {};
if (!callback) {
// "from" may be omitted entirely, shift down one
callback = data;
data = template;
template = subject;
subject = to;
to = from;
from = undefined;
}
// Object passed for from always wins, string can be overridden
if ((!from) || (typeof(from) === 'string')) {
from = options[template + 'From'] || options['from'] || from || {
fullName: 'Do Not Reply',
email: 'donotreply@example.com'
};
}
var finalData = {};
// Allow middleware to supply baseUrl; if it's not there
// use the sitewide option; if that's not there construct it
// from what we do know about the request
var baseUrl = req.baseUrl || self.options.baseUrl || (req.protocol + '://' + req.get('Host'));
var parsed = urls.parse(baseUrl);
var host = parsed.host;
var protocol = parsed.protocol;
// Easy subject override via app.js configuration
subject = options[template + 'Subject'] || subject;
// bc with a not-so-great templating syntax for subject lines that was
// most likely only used once for %HOST%
subject = subject.replace(/%HOST%/, '{{ host }}');
_.extend(finalData, data, true);
self._mailMixinAbsoluteUrls(finalData, baseUrl);
finalData.host = host;
finalData.baseUrl = baseUrl;
_.defaults(options, {
// transport and transportOptions are ignored if options.mailer
// has been passed when constructing the module, as apostrophe-site will
// always do
transport: 'sendmail',
transportOptions: {}
});
if (!module._mailer) {
if (moduleOptions.mailer) {
// This will always work with apostrophe-site
module._mailer = moduleOptions.mailer;
} else {
// An alternative for those not using apostrophe-site
module._mailer = nodemailer.createTransport(options.transport, options.transportOptions);
}
}
var message = {
from: fixAddress(from),
to: fixAddress(to),
subject: module.renderString(subject, finalData, req),
text: module.render(template + '.txt', finalData, req),
html: module.render(template + '.html', finalData, req)
};
return module._mailer.sendMail(message, callback);
};
function fixAddress(to) {
if (typeof(to) === 'string') {
return to;
}
return (to.fullName || to.title).replace(/[<\>]/g, '') + ' <' + to.email + '>';
}
};
self._mailMixinAbsoluteUrls = function(data, baseUrl) {
_.each(data, function(val, key) {
if (typeof(val) === 'object') {
self._mailMixinAbsoluteUrls(val, baseUrl);
return;
}
if ((typeof(key) === 'string') && ((key === 'url') || (key.match(/Url$/)))) {
if ((val.charAt(0) === '/') && baseUrl) {
val = baseUrl + val;
data[key] = val;
}
}
});
};
};
|
'use strict';
var _ = require('underscore'),
path = require('path'),
Promise = require('bluebird'),
errorHelper = require(path.join(global.__libdir, 'errorHelper')),
recallHelper = require(path.join(global.__libdir, 'recallHelper')),
mongoAdapter = require(path.join(global.__adptsdir, 'mongo'));
/**
* Adds a comment to a recall
* @param {Object} obj The params object.
* @param {String} obj.recallnumber The recall number.
* @param {String} obj.name The user's name.
* @param {String} [obj.location] The location of the user.
* @param {String} obj.comment The comment.
* @returns {Promise<Object>}
*/
exports.add = function (obj) {
return Promise.try(function validate () {
if (!obj.recallnumber || !_.isString(obj.recallnumber)) {
throw errorHelper.getValidationError('Invalid recallnumber');
}
if (!obj.name || !_.isString(obj.name)) {
throw errorHelper.getValidationError('Invalid name');
}
if (obj.location && !_.isString(obj.location)) {
throw errorHelper.getValidationError('Invalid location');
}
if (obj.location && !recallHelper.isValidState(obj.location)) {
throw errorHelper.getValidationError('Invalid location; it must be a valid state');
}
if (!obj.comment || !_.isString(obj.comment)) {
throw errorHelper.getValidationError('Invalid comment');
}
}).then(function () {
return mongoAdapter.addComment({
recallnumber: obj.recallnumber,
name: obj.name,
location: obj.location,
comment: obj.comment
}).then(function (comment) {
// delete mongo's internal stuff
delete comment.__v;
delete comment._id;
// remove the recall number as it's duplicated from the recall record
delete comment.recallnumber;
return comment;
});
});
};
|
var _ = require('underscore');
var runLog = require('../run-log.js');
var catalog = require('../catalog/catalog.js');
var archinfo = require('../archinfo.js');
var isopack = require('../isobuild/isopack.js');
var buildmessage = require('../buildmessage.js');
var Console = require('../console.js').Console;
var auth = require('../auth.js');
var files = require('../fs/files.js');
var tropohouse = require('./tropohouse.js');
var release = require('./release.js');
var packageMapModule = require('./package-map.js');
/**
* Check to see if an update is available. If so, download and install
* it before returning.
*
* options: showBanner
*/
var checkInProgress = false;
exports.tryToDownloadUpdate = function (options) {
options = options || {};
// Don't run more than one check simultaneously. It should be
// harmless but having two downloads happening simultaneously (and
// two sets of messages being printed) would be confusing.
if (checkInProgress)
return;
checkInProgress = true;
checkForUpdate(!! options.showBanner, !! options.printErrors);
checkInProgress = false;
};
var firstCheck = true;
var checkForUpdate = function (showBanner, printErrors) {
// While we're doing background stuff, try to revoke any old tokens in our
// session file.
auth.tryRevokeOldTokens({ timeout: 15 * 1000 });
if (firstCheck) {
// We want to avoid a potential race condition here, because we run an
// update almost immediately at run. We don't want to drop the resolver
// cache; that would be slow. "meteor run" itself should have run a refresh
// anyway. So, the first time, we just skip the remote catalog sync. But
// we do want to do the out-of-date release checks, so we can't just delay
// the first update cycle.
firstCheck = false;
} else {
try {
catalog.official.refresh();
} catch (err) {
Console.debug("Failed to refresh catalog, ignoring error", err);
return;
}
}
if (!release.current.isProperRelease())
return;
updateMeteorToolSymlink(printErrors);
maybeShowBanners();
};
var lastShowTimes = {};
var shouldShow = function (key, maxAge) {
var now = +(new Date);
if (maxAge === undefined) {
maxAge = 12 * 60 * 60 * 1000;
}
var lastShow = lastShowTimes[key];
if (lastShow !== undefined) {
var age = now - lastShow;
if (age < maxAge) {
return false;
}
}
lastShowTimes[key] = now;
return true;
};
var maybeShowBanners = function () {
var releaseData = release.current.getCatalogReleaseData();
var banner = releaseData.banner;
if (banner) {
var bannerDate =
banner.lastUpdated ? new Date(banner.lastUpdated) : new Date;
if (catalog.official.shouldShowBanner(release.current.name, bannerDate)) {
// This banner is new; print it!
runLog.log("");
runLog.log(banner.text);
runLog.log("");
catalog.official.setBannerShownDate(release.current.name, bannerDate);
return;
}
}
// We now consider printing some simpler banners, if this isn't the latest
// release. But if the user specified a release manually with --release, we
// don't bother: we only want to tell users about ways to update *their app*.
if (release.forced)
return;
const catalogUtils = require('../catalog/catalog-utils.js');
// Didn't print a banner? Maybe we have a patch release to recommend.
var track = release.current.getReleaseTrack();
var patchReleaseVersion = releaseData.patchReleaseVersion;
if (patchReleaseVersion) {
var patchRelease = catalog.official.getReleaseVersion(
track, patchReleaseVersion);
if (patchRelease && patchRelease.recommended) {
var patchKey = "patchrelease-" + track + "-" + patchReleaseVersion;
if (shouldShow(patchKey)) {
runLog.log(
"=> A patch (" +
catalogUtils.displayRelease(track, patchReleaseVersion) +
") for your current release is available!");
runLog.log(" Update this project now with 'meteor update --patch'.");
}
return;
}
}
// There's no patch (so no urgent exclamation!) but there may be something
// worth mentioning.
// XXX maybe run constraint solver to change the message depending on whether
// or not it will actually work?
var currentReleaseOrderKey = releaseData.orderKey || null;
var futureReleases = catalog.official.getSortedRecommendedReleaseVersions(
track, currentReleaseOrderKey);
if (futureReleases.length) {
var futureReleaseKey = "futurerelease-" + track + "-" + futureReleases[0];
if (shouldShow(futureReleaseKey)) {
runLog.log(
"=> " + catalogUtils.displayRelease(track, futureReleases[0]) +
" is available. Update this project with 'meteor update'.");
}
return;
}
};
// Update ~/.meteor/meteor to point to the tool binary from the tools of the
// latest recommended release on the default release track.
var updateMeteorToolSymlink = function (printErrors) {
// Get the latest release version of METEOR. (*Always* of the default
// track, not of whatever we happen to be running: we always want the tool
// symlink to go to the default track.)
var latestReleaseVersion = catalog.official.getDefaultReleaseVersion();
// Maybe you're on some random track with nothing recommended. That's OK.
if (!latestReleaseVersion)
return;
var latestRelease = catalog.official.getReleaseVersion(
latestReleaseVersion.track, latestReleaseVersion.version);
if (!latestRelease)
throw Error("latest release doesn't exist?");
if (!latestRelease.tool)
throw Error("latest release doesn't have a tool?");
var latestReleaseToolParts = latestRelease.tool.split('@');
var latestReleaseToolPackage = latestReleaseToolParts[0];
var latestReleaseToolVersion = latestReleaseToolParts[1];
var relativeToolPath = tropohouse.default.packagePath(
latestReleaseToolPackage, latestReleaseToolVersion, true);
var localLatestReleaseLink = tropohouse.default.latestMeteorSymlink();
if (! localLatestReleaseLink.startsWith(relativeToolPath + files.pathSep)) {
// The latest release from the catalog is not where the ~/.meteor/meteor
// symlink points to. Let's make sure we have that release on disk,
// and then update the symlink.
var packageMap =
packageMapModule.PackageMap.fromReleaseVersion(latestRelease);
var messages = buildmessage.capture(function () {
tropohouse.default.downloadPackagesMissingFromMap(packageMap);
});
if (messages.hasMessages()) {
// Ignore errors because we are running in the background, uness we
// specifically requested to print errors because we are testing this
// feature.
if (printErrors) {
Console.printMessages(messages);
}
return;
}
var toolIsopack = new isopack.Isopack;
toolIsopack.initFromPath(
latestReleaseToolPackage,
tropohouse.default.packagePath(latestReleaseToolPackage,
latestReleaseToolVersion));
var toolRecord = _.findWhere(toolIsopack.toolsOnDisk,
{arch: archinfo.host()});
// XXX maybe we shouldn't throw from this background thing
// counter: this is super weird and should never ever happen.
if (!toolRecord)
throw Error("latest release has no tool?");
tropohouse.default.linkToLatestMeteor(files.pathJoin(
relativeToolPath, toolRecord.path, 'meteor'));
}
};
|
/* global document, clearTimeout, setTimeout */
import View from './View';
import Speaker from './Speaker';
/*
* Bar represents the bottom menu bar of every mediaPlayer.
* It contains a Speaker and an icon.
* Every Bar is a View.
* Ex.: var bar = Bar({elementID: element, id: id});
*/
const Bar = (spec) => {
const that = View({});
let waiting;
// Variables
// DOM element in which the Bar will be appended
that.elementID = spec.elementID;
// Bar ID
that.id = spec.id;
// Container
that.div = document.createElement('div');
that.div.setAttribute('id', `bar_${that.id}`);
that.div.setAttribute('class', 'licode_bar');
// Bottom bar
that.bar = document.createElement('div');
that.bar.setAttribute('style', 'width: 100%; height: 15%; max-height: 30px; ' +
'position: absolute; bottom: 0; right: 0; ' +
'background-color: rgba(255,255,255,0.62)');
that.bar.setAttribute('id', `subbar_${that.id}`);
that.bar.setAttribute('class', 'licode_subbar');
// Lynckia icon
that.link = document.createElement('a');
that.link.setAttribute('href', 'http://www.lynckia.com/');
that.link.setAttribute('class', 'licode_link');
that.link.setAttribute('target', '_blank');
that.logo = document.createElement('img');
that.logo.setAttribute('style', 'width: 100%; height: 100%; max-width: 30px; ' +
'position: absolute; top: 0; left: 2px;');
that.logo.setAttribute('class', 'licode_logo');
that.logo.setAttribute('alt', 'Lynckia');
that.logo.setAttribute('src', `${that.url}/assets/star.svg`);
// Private functions
const show = (displaying) => {
let action = displaying;
if (displaying !== 'block') {
action = 'none';
} else {
clearTimeout(waiting);
}
that.div.setAttribute('style',
`width: 100%; height: 100%; position: relative; bottom: 0; right: 0; display: ${action}`);
};
// Public functions
that.display = () => {
show('block');
};
that.hide = () => {
waiting = setTimeout(show, 1000);
};
document.getElementById(that.elementID).appendChild(that.div);
that.div.appendChild(that.bar);
that.bar.appendChild(that.link);
that.link.appendChild(that.logo);
// Speaker component
if (!spec.stream.screen && (spec.options === undefined ||
spec.options.speaker === undefined ||
spec.options.speaker === true)) {
that.speaker = Speaker({ elementID: `subbar_${that.id}`,
id: that.id,
stream: spec.stream,
media: spec.media });
}
that.display();
that.hide();
return that;
};
export default Bar;
|
/**
* @depends {nrs.js}
*/
var NRS = (function(NRS, $, undefined) {
var _password;
var _decryptionPassword;
var _decryptedTransactions = {};
var _encryptedNote = null;
var _sharedKeys = {};
var _hash = {
init: SHA256_init,
update: SHA256_write,
getBytes: SHA256_finalize
};
NRS.generatePublicKey = function(secretPhrase) {
if (!secretPhrase) {
if (NRS.rememberPassword) {
secretPhrase = _password;
} else {
throw $.t("error_generate_public_key_no_password");
}
}
return NRS.getPublicKey(converters.stringToHexString(secretPhrase));
}
NRS.getPublicKey = function(secretPhrase, isAccountNumber) {
if (isAccountNumber) {
var accountNumber = secretPhrase;
var publicKey = "";
//synchronous!
NRS.sendRequest("getAccountPublicKey", {
"account": accountNumber
}, function(response) {
if (!response.publicKey) {
throw $.t("error_no_public_key");
} else {
publicKey = response.publicKey;
}
}, false);
return publicKey;
} else {
var secretPhraseBytes = converters.hexStringToByteArray(secretPhrase);
var digest = simpleHash(secretPhraseBytes);
return converters.byteArrayToHexString(curve25519.keygen(digest).p);
}
}
NRS.getPrivateKey = function(secretPhrase) {
SHA256_init();
SHA256_write(converters.stringToByteArray(secretPhrase));
return converters.shortArrayToHexString(curve25519_clamp(converters.byteArrayToShortArray(SHA256_finalize())));
}
NRS.getAccountId = function(secretPhrase) {
return NRS.getAccountIdFromPublicKey(NRS.getPublicKey(converters.stringToHexString(secretPhrase)));
/*
if (NRS.accountInfo && NRS.accountInfo.publicKey && publicKey != NRS.accountInfo.publicKey) {
return -1;
}
*/
}
NRS.getAccountIdFromPublicKey = function(publicKey, RSFormat) {
var hex = converters.hexStringToByteArray(publicKey);
_hash.init();
_hash.update(hex);
var account = _hash.getBytes();
account = converters.byteArrayToHexString(account);
var slice = (converters.hexStringToByteArray(account)).slice(0, 8);
var accountId = byteArrayToBigInteger(slice).toString();
if (RSFormat) {
var address = new NxtAddress();
if (address.set(accountId)) {
return address.toString();
} else {
return "";
}
} else {
return accountId;
}
}
NRS.encryptNote = function(message, options, secretPhrase) {
try {
if (!options.sharedKey) {
if (!options.privateKey) {
if (!secretPhrase) {
if (NRS.rememberPassword) {
secretPhrase = _password;
} else {
throw {
"message": $.t("error_encryption_passphrase_required"),
"errorCode": 1
};
}
}
options.privateKey = converters.hexStringToByteArray(NRS.getPrivateKey(secretPhrase));
}
if (!options.publicKey) {
if (!options.account) {
throw {
"message": $.t("error_account_id_not_specified"),
"errorCode": 2
};
}
try {
options.publicKey = converters.hexStringToByteArray(NRS.getPublicKey(options.account, true));
} catch (err) {
var nxtAddress = new NxtAddress();
if (!nxtAddress.set(options.account)) {
throw {
"message": $.t("error_invalid_account_id"),
"errorCode": 3
};
} else {
throw {
"message": $.t("error_public_key_not_specified"),
"errorCode": 4
};
}
}
} else if (typeof options.publicKey == "string") {
options.publicKey = converters.hexStringToByteArray(options.publicKey);
}
}
var encrypted = encryptData(converters.stringToByteArray(message), options);
return {
"message": converters.byteArrayToHexString(encrypted.data),
"nonce": converters.byteArrayToHexString(encrypted.nonce)
};
} catch (err) {
if (err.errorCode && err.errorCode < 5) {
throw err;
} else {
throw {
"message": $.t("error_message_encryption"),
"errorCode": 5
};
}
}
}
NRS.decryptData = function(data, options, secretPhrase) {
try {
return NRS.decryptNote(message, options, secretPhrase);
} catch (err) {
var mesage = String(err.message ? err.message : err);
if (err.errorCode && err.errorCode == 1) {
return false;
} else {
if (options.title) {
var translatedTitle = NRS.getTranslatedFieldName(options.title).toLowerCase();
if (!translatedTitle) {
translatedTitle = String(options.title).escapeHTML().toLowerCase();
}
return $.t("error_could_not_decrypt_var", {
"var": translatedTitle
}).capitalize();
} else {
return $.t("error_could_not_decrypt");
}
}
}
}
NRS.decryptNote = function(message, options, secretPhrase) {
try {
if (!options.sharedKey) {
if (!options.privateKey) {
if (!secretPhrase) {
if (NRS.rememberPassword) {
secretPhrase = _password;
} else if (_decryptionPassword) {
secretPhrase = _decryptionPassword;
} else {
throw {
"message": $.t("error_decryption_passphrase_required"),
"errorCode": 1
};
}
}
options.privateKey = converters.hexStringToByteArray(NRS.getPrivateKey(secretPhrase));
}
if (!options.publicKey) {
if (!options.account) {
throw {
"message": $.t("error_account_id_not_specified"),
"errorCode": 2
};
}
options.publicKey = converters.hexStringToByteArray(NRS.getPublicKey(options.account, true));
}
}
options.nonce = converters.hexStringToByteArray(options.nonce);
return decryptData(converters.hexStringToByteArray(message), options);
} catch (err) {
if (err.errorCode && err.errorCode < 3) {
throw err;
} else {
throw {
"message": $.t("error_message_decryption"),
"errorCode": 3
};
}
}
}
NRS.getSharedKeyWithAccount = function(account) {
try {
if (account in _sharedKeys) {
return _sharedKeys[account];
}
var secretPhrase;
if (NRS.rememberPassword) {
secretPhrase = _password;
} else if (_decryptionPassword) {
secretPhrase = _decryptionPassword;
} else {
throw {
"message": $.t("error_passphrase_required"),
"errorCode": 3
};
}
var privateKey = converters.hexStringToByteArray(NRS.getPrivateKey(secretPhrase));
var publicKey = converters.hexStringToByteArray(NRS.getPublicKey(account, true));
var sharedKey = getSharedKey(privateKey, publicKey);
var sharedKeys = Object.keys(_sharedKeys);
if (sharedKeys.length > 50) {
delete _sharedKeys[sharedKeys[0]];
}
_sharedKeys[account] = sharedKey;
} catch (err) {
throw err;
}
}
NRS.signBytes = function(message, secretPhrase) {
var messageBytes = converters.hexStringToByteArray(message);
var secretPhraseBytes = converters.hexStringToByteArray(secretPhrase);
var digest = simpleHash(secretPhraseBytes);
var s = curve25519.keygen(digest).s;
var m = simpleHash(messageBytes);
_hash.init();
_hash.update(m);
_hash.update(s);
var x = _hash.getBytes();
var y = curve25519.keygen(x).p;
_hash.init();
_hash.update(m);
_hash.update(y);
var h = _hash.getBytes();
var v = curve25519.sign(h, x, s);
return converters.byteArrayToHexString(v.concat(h));
}
NRS.verifyBytes = function(signature, message, publicKey) {
var signatureBytes = converters.hexStringToByteArray(signature);
var messageBytes = converters.hexStringToByteArray(message);
var publicKeyBytes = converters.hexStringToByteArray(publicKey);
var v = signatureBytes.slice(0, 32);
var h = signatureBytes.slice(32);
var y = curve25519.verify(v, h, publicKeyBytes);
var m = simpleHash(messageBytes);
_hash.init();
_hash.update(m);
_hash.update(y);
var h2 = _hash.getBytes();
return areByteArraysEqual(h, h2);
}
NRS.setEncryptionPassword = function(password) {
_password = password;
}
NRS.setDecryptionPassword = function(password) {
_decryptionPassword = password;
}
NRS.addDecryptedTransaction = function(identifier, content) {
if (!_decryptedTransactions[identifier]) {
_decryptedTransactions[identifier] = content;
}
}
NRS.tryToDecryptMessage = function(message) {
if (_decryptedTransactions && _decryptedTransactions[message.transaction]) {
return _decryptedTransactions[message.transaction].encryptedMessage;
}
try {
if (!message.attachment.encryptedMessage.data) {
return $.t("message_empty");
} else {
var decoded = NRS.decryptNote(message.attachment.encryptedMessage.data, {
"nonce": message.attachment.encryptedMessage.nonce,
"account": (message.recipient == NRS.account ? message.sender : message.recipient)
});
}
return decoded;
} catch (err) {
throw err;
}
}
NRS.tryToDecrypt = function(transaction, fields, account, options) {
var showDecryptionForm = false;
if (!options) {
options = {};
}
var nrFields = Object.keys(fields).length;
var formEl = (options.formEl ? String(options.formEl).escapeHTML() : "#transaction_info_output_bottom");
var outputEl = (options.outputEl ? String(options.outputEl).escapeHTML() : "#transaction_info_output_bottom");
var output = "";
var identifier = (options.identifier ? transaction[options.identifier] : transaction.transaction);
//check in cache first..
if (_decryptedTransactions && _decryptedTransactions[identifier]) {
var decryptedTransaction = _decryptedTransactions[identifier];
$.each(fields, function(key, title) {
if (typeof title != "string") {
title = title.title;
}
if (key in decryptedTransaction) {
output += "<div style='" + (!options.noPadding && title ? "padding-left:5px;" : "") + "'>" + (title ? "<label" + (nrFields > 1 ? " style='margin-top:5px'" : "") + "><i class='fa fa-lock'></i> " + String(title).escapeHTML() + "</label>" : "") + "<div>" + String(decryptedTransaction[key]).escapeHTML().nl2br() + "</div></div>";
} else {
//if a specific key was not found, the cache is outdated..
output = "";
delete _decryptedTransactions[identifier];
return false;
}
});
}
if (!output) {
$.each(fields, function(key, title) {
var data = "";
var encrypted = "";
var nonce = "";
var nonceField = (typeof title != "string" ? title.nonce : key + "Nonce");
if (key == "encryptedMessage" || key == "encryptToSelfMessage") {
encrypted = transaction.attachment[key].data;
nonce = transaction.attachment[key].nonce;
} else if (transaction.attachment && transaction.attachment[key]) {
encrypted = transaction.attachment[key];
nonce = transaction.attachment[nonceField];
} else if (transaction[key] && typeof transaction[key] == "object") {
encrypted = transaction[key].data;
nonce = transaction[key].nonce;
} else if (transaction[key]) {
encrypted = transaction[key];
nonce = transaction[nonceField];
} else {
encrypted = "";
}
if (encrypted) {
if (typeof title != "string") {
title = title.title;
}
try {
data = NRS.decryptNote(encrypted, {
"nonce": nonce,
"account": account
});
} catch (err) {
var mesage = String(err.message ? err.message : err);
if (err.errorCode && err.errorCode == 1) {
showDecryptionForm = true;
return false;
} else {
if (title) {
var translatedTitle = NRS.getTranslatedFieldName(title).toLowerCase();
if (!translatedTitle) {
translatedTitle = String(title).escapeHTML().toLowerCase();
}
data = $.t("error_could_not_decrypt_var", {
"var": translatedTitle
}).capitalize();
} else {
data = $.t("error_could_not_decrypt");
}
}
}
output += "<div style='" + (!options.noPadding && title ? "padding-left:5px;" : "") + "'>" + (title ? "<label" + (nrFields > 1 ? " style='margin-top:5px'" : "") + "><i class='fa fa-lock'></i> " + String(title).escapeHTML() + "</label>" : "") + "<div>" + String(data).escapeHTML().nl2br() + "</div></div>";
}
});
}
if (showDecryptionForm) {
_encryptedNote = {
"transaction": transaction,
"fields": fields,
"account": account,
"options": options,
"identifier": identifier
};
$("#decrypt_note_form_container").detach().appendTo(formEl);
$("#decrypt_note_form_container, " + formEl).show();
} else {
NRS.removeDecryptionForm();
$(outputEl).append(output).show();
}
}
NRS.removeDecryptionForm = function($modal) {
if (($modal && $modal.find("#decrypt_note_form_container").length) || (!$modal && $("#decrypt_note_form_container").length)) {
$("#decrypt_note_form_container input").val("");
$("#decrypt_note_form_container").find(".callout").html($.t("passphrase_required_to_decrypt_data"));
$("#decrypt_note_form_container").hide().detach().appendTo("body");
}
}
$("#decrypt_note_form_container button.btn-primary").click(function() {
NRS.decryptNoteFormSubmit();
});
$("#decrypt_note_form_container").on("submit", function(e) {
e.preventDefault();
NRS.decryptNoteFormSubmit();
});
NRS.decryptNoteFormSubmit = function() {
var $form = $("#decrypt_note_form_container");
if (!_encryptedNote) {
$form.find(".callout").html($.t("error_encrypted_note_not_found")).show();
return;
}
var password = $form.find("input[name=secretPhrase]").val();
if (!password) {
if (NRS.rememberPassword) {
password = _password;
} else if (_decryptionPassword) {
password = _decryptionPassword;
} else {
$form.find(".callout").html($.t("error_passphrase_required")).show();
return;
}
}
var accountId = NRS.getAccountId(password);
if (accountId != NRS.account) {
$form.find(".callout").html($.t("error_incorrect_passphrase")).show();
return;
}
var rememberPassword = $form.find("input[name=rememberPassword]").is(":checked");
var otherAccount = _encryptedNote.account;
var output = "";
var decryptionError = false;
var decryptedFields = {};
var inAttachment = ("attachment" in _encryptedNote.transaction);
var nrFields = Object.keys(_encryptedNote.fields).length;
$.each(_encryptedNote.fields, function(key, title) {
var data = "";
var encrypted = "";
var nonce = "";
var nonceField = (typeof title != "string" ? title.nonce : key + "Nonce");
if (key == "encryptedMessage" || key == "encryptToSelfMessage") {
if (key == "encryptToSelfMessage") {
otherAccount=accountId;
}
encrypted = _encryptedNote.transaction.attachment[key].data;
nonce = _encryptedNote.transaction.attachment[key].nonce;
} else if (_encryptedNote.transaction.attachment && _encryptedNote.transaction.attachment[key]) {
encrypted = _encryptedNote.transaction.attachment[key];
nonce = _encryptedNote.transaction.attachment[nonceField];
} else if (_encryptedNote.transaction[key] && typeof _encryptedNote.transaction[key] == "object") {
encrypted = _encryptedNote.transaction[key].data;
nonce = _encryptedNote.transaction[key].nonce;
} else if (_encryptedNote.transaction[key]) {
encrypted = _encryptedNote.transaction[key];
nonce = _encryptedNote.transaction[nonceField];
} else {
encrypted = "";
}
if (encrypted) {
if (typeof title != "string") {
title = title.title;
}
try {
data = NRS.decryptNote(encrypted, {
"nonce": nonce,
"account": otherAccount
}, password);
decryptedFields[key] = data;
} catch (err) {
decryptionError = true;
var message = String(err.message ? err.message : err);
$form.find(".callout").html(message.escapeHTML());
return false;
}
output += "<div style='" + (!_encryptedNote.options.noPadding && title ? "padding-left:5px;" : "") + "'>" + (title ? "<label" + (nrFields > 1 ? " style='margin-top:5px'" : "") + "><i class='fa fa-lock'></i> " + String(title).escapeHTML() + "</label>" : "") + "<div>" + String(data).autoLink().nl2br() + "</div></div>";
}
});
if (decryptionError) {
return;
}
_decryptedTransactions[_encryptedNote.identifier] = decryptedFields;
//only save 150 decryptions maximum in cache...
var decryptionKeys = Object.keys(_decryptedTransactions);
if (decryptionKeys.length > 150) {
delete _decryptedTransactions[decryptionKeys[0]];
}
NRS.removeDecryptionForm();
var outputEl = (_encryptedNote.options.outputEl ? String(_encryptedNote.options.outputEl).escapeHTML() : "#transaction_info_output_bottom");
$(outputEl).append(output).show();
_encryptedNote = null;
if (rememberPassword) {
_decryptionPassword = password;
}
}
NRS.decryptAllMessages = function(messages, password) {
if (!password) {
throw {
"message": $.t("error_passphrase_required"),
"errorCode": 1
};
} else {
var accountId = NRS.getAccountId(password);
if (accountId != NRS.account) {
throw {
"message": $.t("error_incorrect_passphrase"),
"errorCode": 2
};
}
}
var success = 0;
var error = 0;
for (var i = 0; i < messages.length; i++) {
var message = messages[i];
if (message.attachment.encryptedMessage && !_decryptedTransactions[message.transaction]) {
try {
var otherUser = (message.sender == NRS.account ? message.recipient : message.sender);
var decoded = NRS.decryptNote(message.attachment.encryptedMessage.data, {
"nonce": message.attachment.encryptedMessage.nonce,
"account": otherUser
}, password);
_decryptedTransactions[message.transaction] = {
"encryptedMessage": decoded
};
success++;
} catch (err) {
_decryptedTransactions[message.transaction] = {
"encryptedMessage": $.t("error_decryption_unknown")
};
error++;
}
}
}
if (success || !error) {
return true;
} else {
return false;
}
}
function simpleHash(message) {
_hash.init();
_hash.update(message);
return _hash.getBytes();
}
function areByteArraysEqual(bytes1, bytes2) {
if (bytes1.length !== bytes2.length)
return false;
for (var i = 0; i < bytes1.length; ++i) {
if (bytes1[i] !== bytes2[i])
return false;
}
return true;
}
function curve25519_clamp(curve) {
curve[0] &= 0xFFF8;
curve[15] &= 0x7FFF;
curve[15] |= 0x4000;
return curve;
}
function byteArrayToBigInteger(byteArray, startIndex) {
var value = new BigInteger("0", 10);
var temp1, temp2;
for (var i = byteArray.length - 1; i >= 0; i--) {
temp1 = value.multiply(new BigInteger("256", 10));
temp2 = temp1.add(new BigInteger(byteArray[i].toString(10), 10));
value = temp2;
}
return value;
}
function aesEncrypt(plaintext, options) {
if (!window.crypto && !window.msCrypto) {
throw {
"errorCode": -1,
"message": $.t("error_encryption_browser_support")
};
}
// CryptoJS likes WordArray parameters
var text = converters.byteArrayToWordArray(plaintext);
if (!options.sharedKey) {
var sharedKey = getSharedKey(options.privateKey, options.publicKey);
} else {
var sharedKey = options.sharedKey.slice(0); //clone
}
for (var i = 0; i < 32; i++) {
sharedKey[i] ^= options.nonce[i];
}
var key = CryptoJS.SHA256(converters.byteArrayToWordArray(sharedKey));
var tmp = new Uint8Array(16);
if (window.crypto) {
window.crypto.getRandomValues(tmp);
} else {
window.msCrypto.getRandomValues(tmp);
}
var iv = converters.byteArrayToWordArray(tmp);
var encrypted = CryptoJS.AES.encrypt(text, key, {
iv: iv
});
var ivOut = converters.wordArrayToByteArray(encrypted.iv);
var ciphertextOut = converters.wordArrayToByteArray(encrypted.ciphertext);
return ivOut.concat(ciphertextOut);
}
function aesDecrypt(ivCiphertext, options) {
if (ivCiphertext.length < 16 || ivCiphertext.length % 16 != 0) {
throw {
name: "invalid ciphertext"
};
}
var iv = converters.byteArrayToWordArray(ivCiphertext.slice(0, 16));
var ciphertext = converters.byteArrayToWordArray(ivCiphertext.slice(16));
if (!options.sharedKey) {
var sharedKey = getSharedKey(options.privateKey, options.publicKey);
} else {
var sharedKey = options.sharedKey.slice(0); //clone
}
for (var i = 0; i < 32; i++) {
sharedKey[i] ^= options.nonce[i];
}
var key = CryptoJS.SHA256(converters.byteArrayToWordArray(sharedKey));
var encrypted = CryptoJS.lib.CipherParams.create({
ciphertext: ciphertext,
iv: iv,
key: key
});
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
iv: iv
});
var plaintext = converters.wordArrayToByteArray(decrypted);
return plaintext;
}
function encryptData(plaintext, options) {
if (!window.crypto && !window.msCrypto) {
throw {
"errorCode": -1,
"message": $.t("error_encryption_browser_support")
};
}
if (!options.sharedKey) {
options.sharedKey = getSharedKey(options.privateKey, options.publicKey);
}
var compressedPlaintext = pako.gzip(new Uint8Array(plaintext));
options.nonce = new Uint8Array(32);
if (window.crypto) {
window.crypto.getRandomValues(options.nonce);
} else {
window.msCrypto.getRandomValues(options.nonce);
}
var data = aesEncrypt(compressedPlaintext, options);
return {
"nonce": options.nonce,
"data": data
};
}
function decryptData(data, options) {
if (!options.sharedKey) {
options.sharedKey = getSharedKey(options.privateKey, options.publicKey);
}
var compressedPlaintext = aesDecrypt(data, options);
var binData = new Uint8Array(compressedPlaintext);
var data = pako.inflate(binData);
return converters.byteArrayToString(data);
}
function getSharedKey(key1, key2) {
return converters.shortArrayToByteArray(curve25519_(converters.byteArrayToShortArray(key1), converters.byteArrayToShortArray(key2), null));
}
return NRS;
}(NRS || {}, jQuery)); |
jui.define("chart.brush.scatter", [ "util.base" ], function(_) {
/**
* @class chart.brush.scatter
*
* ์ ์ผ๋ก ์ด๋ฃจ์ด์ง ๋ฐ์ดํ๋ฅผ ํํํ๋ ๋ธ๋ฌ์ฌ
*
* @extends chart.brush.core
*/
var ScatterBrush = function() {
this.getSymbolType = function(key, value) {
var symbol = this.brush.symbol,
target = this.brush.target[key];
if(_.typeCheck("function", symbol)) {
var res = symbol.apply(this.chart, [ target, value ]);
if (res == "triangle" || res == "cross" || res == "rectangle" || res == "rect" || res == "circle") {
return {
type : "default",
uri : res
};
} else {
return {
type : "image",
uri : res
};
}
}
return {
type : "default",
uri : symbol
};
}
/**
* @method createScatter
*
* ์ขํ๋ณ scatter ์์ฑ
*
* @param {Object} pos
* @param {Number} index
* @return {util.svg.element}
*/
this.createScatter = function(pos, dataIndex, targetIndex, symbol) {
var self = this,
elem = null,
w = h = this.brush.size;
var color = this.color(dataIndex, targetIndex),
borderColor = this.chart.theme("scatterBorderColor"),
borderWidth = this.chart.theme("scatterBorderWidth");
if(symbol.type == "image") {
elem = this.chart.svg.image({
"xlink:href": symbol.uri,
width: w + borderWidth,
height: h + borderWidth,
x: pos.x - (w / 2) - borderWidth,
y: pos.y - (h / 2)
});
} else {
if(symbol.uri == "triangle" || symbol.uri == "cross") {
elem = this.chart.svg.group({ width: w, height: h }, function() {
if(symbol.uri == "triangle") {
var poly = self.chart.svg.polygon();
poly.point(0, h)
.point(w, h)
.point(w / 2, 0);
} else {
self.chart.svg.line({ stroke: color, "stroke-width": borderWidth * 2, x1: 0, y1: 0, x2: w, y2: h });
self.chart.svg.line({ stroke: color, "stroke-width": borderWidth * 2, x1: 0, y1: w, x2: h, y2: 0 });
}
}).translate(pos.x - (w / 2), pos.y - (h / 2));
} else {
if(symbol.uri == "rectangle" || symbol.uri == "rect") {
elem = this.chart.svg.rect({
width: w,
height: h,
x: pos.x - (w / 2),
y: pos.y - (h / 2)
});
} else {
elem = this.chart.svg.ellipse({
rx: w / 2,
ry: h / 2,
cx: pos.x,
cy: pos.y
});
}
}
if(symbol.uri != "cross") {
elem.attr({
fill: color,
stroke: borderColor,
"stroke-width": borderWidth
})
.hover(function () {
if(elem == self.activeScatter) return;
var opts = {
fill: self.chart.theme("scatterHoverColor"),
stroke: color,
"stroke-width": borderWidth * 2,
opacity: 1
};
if(self.brush.hoverSync) {
for(var i = 0; i < self.cachedSymbol[dataIndex].length; i++) {
opts.stroke = self.color(dataIndex, i);
self.cachedSymbol[dataIndex][i].attr(opts);
}
} else {
elem.attr(opts);
}
}, function () {
if(elem == self.activeScatter) return;
var opts = {
fill: color,
stroke: borderColor,
"stroke-width": borderWidth,
opacity: (self.brush.hide) ? 0 : 1
};
if(self.brush.hoverSync) {
for(var i = 0; i < self.cachedSymbol[dataIndex].length; i++) {
opts.fill = self.color(dataIndex, i);
self.cachedSymbol[dataIndex][i].attr(opts);
}
} else {
elem.attr(opts);
}
});
}
}
return elem;
}
/**
* @method drawScatter
*
* scatter ๊ทธ๋ฆฌ๊ธฐ
*
* @param {Array} points
* @return {util.svg.element} g element ๋ฆฌํด
*/
this.drawScatter = function(points) {
// hoverSync ์ต์
์ฒ๋ฆฌ๋ฅผ ์ํ ์บ์ฑ ์ฒ๋ฆฌ
this.cachedSymbol = {};
var self = this,
g = this.chart.svg.group(),
borderColor = this.chart.theme("scatterBorderColor"),
borderWidth = this.chart.theme("scatterBorderWidth");
for(var i = 0; i < points.length; i++) {
for(var j = 0; j < points[i].length; j++) {
if(!this.cachedSymbol[j]) {
this.cachedSymbol[j] = [];
}
if(this.brush.hideZero && points[i].value[j] === 0) {
continue;
}
var data = {
x: points[i].x[j],
y: points[i].y[j],
max: points[i].max[j],
min: points[i].min[j],
value: points[i].value[j]
};
var symbol = this.getSymbolType(i, data.value),
p = this.createScatter(data, j, i, symbol),
d = this.brush.display;
// hoverSync ์ต์
์ ์ํ ์๋ฆฌ๋จผํธ ์บ์ฑ
if(symbol.type == "default" && symbol.uri != "cross") {
this.cachedSymbol[j].push(p);
}
// Max & Min ํดํ ์์ฑ
if((d == "max" && data.max) || (d == "min" && data.min) || d == "all") {
g.append(this.drawTooltip(data.x, data.y, this.format(data.value)));
}
// ์ปฌ๋ผ ๋ฐ ๊ธฐ๋ณธ ๋ธ๋ฌ์ฌ ์ด๋ฒคํธ ์ค์
if(this.brush.activeEvent != null) {
(function(scatter, data, color, symbol) {
var x = data.x,
y = data.y,
text = self.format(data.value);
scatter.on(self.brush.activeEvent, function(e) {
if(symbol.type == "default" && symbol.uri != "cross") {
if (self.activeScatter != null) {
self.activeScatter.attr({
fill: self.activeScatter.attributes["stroke"],
stroke: borderColor,
"stroke-width": borderWidth,
opacity: (self.brush.hide) ? 0 : 1
});
}
self.activeScatter = scatter;
self.activeScatter.attr({
fill: self.chart.theme("scatterHoverColor"),
stroke: color,
"stroke-width": borderWidth * 2,
opacity: 1
});
}
self.activeTooltip.html(text);
self.activeTooltip.translate(x, y);
});
scatter.attr({ cursor: "pointer" });
})(p, data, this.color(j, i), this.getSymbolType(i, data.value));
}
if(this.brush.hide) {
p.attr({ opacity: 0 });
}
this.addEvent(p, j, i);
g.append(p);
}
}
// ์กํฐ๋ธ ํดํ
this.activeTooltip = this.drawTooltip(0, 0, "");
g.append(this.activeTooltip);
return g;
}
this.drawTooltip = function(x, y, text) {
return this.chart.text({
y: -this.brush.size,
"text-anchor" : "middle",
"font-size" : this.chart.theme("tooltipPointFontSize"),
"font-weight" : this.chart.theme("tooltipPointFontWeight")
}, text).translate(x, y);
}
/**
* @method draw
*
* @return {util.svg.element}
*/
this.draw = function() {
return this.drawScatter(this.getXY());
}
this.drawAnimate = function() {
var area = this.chart.area();
return this.chart.svg.animateTransform({
attributeName: "transform",
type: "translate",
from: area.x + " " + area.height,
to: area.x + " " + area.y,
begin: "0s" ,
dur: "0.4s",
repeatCount: "1"
});
}
}
ScatterBrush.setup = function() {
return {
/** @cfg {"circle"/"triangle"/"rectangle"/"cross"/"callback"} [symbol="circle"] Determines the shape of a (circle, rectangle, cross, triangle). */
symbol: "circle",
/** @cfg {Number} [size=7] Determines the size of a starter. */
size: 7,
/** @cfg {Boolean} [hide=false] Hide the scatter, will be displayed only when the mouse is over. */
hide: false,
/** @cfg {Boolean} [hideZero=false] When scatter value is zero, will be hidden. */
hideZero: false,
/** @cfg {Boolean} [hoverSync=false] Over effect synchronization of all the target's symbol. */
hoverSync: false,
/** @cfg {String} [activeEvent=null] Activates the scatter in question when a configured event occurs (click, mouseover, etc). */
activeEvent: null,
/** @cfg {"max"/"min"/"all"} [display=null] Shows a tooltip on the scatter for the minimum/maximum value. */
display: null,
/** @cfg {Boolean} [clip=false] If the brush is drawn outside of the chart, cut the area. */
clip: false
};
}
return ScatterBrush;
}, "chart.brush.core"); |
import sinon from 'sinon';
import {expect} from 'chai';
import FetchPlease from '../src/fetch-please';
let XMLHttpRequest = sinon.useFakeXMLHttpRequest();
describe('Method putRequest()', () => {
before(function() {
this.requests = [];
this.api = new FetchPlease('/api/', {XMLHttpRequest});
XMLHttpRequest.onCreate = (xhr) => {
this.requests.push(xhr);
};
});
it('exists', function() {
expect(this.api.putRequest).to.be.a('function');
});
it('sends request', function() {
expect(this.requests.length).to.equal(0);
let {xhr, promise} = this.api.putRequest('users', null);
expect(xhr).to.be.an.instanceof(XMLHttpRequest);
expect(xhr.method).be.equal('PUT');
expect(promise).to.be.an.instanceof(Promise);
expect(this.requests.length).to.equal(1);
xhr.respond(200, {'content-type': 'application/json'}, '{"a":1}');
return promise.then((data) => {
expect(data).to.deep.equal({a: 1});
});
});
after(function() {
this.api = null;
this.requests = [];
XMLHttpRequest.onCreate = null;
});
});
describe('Method put()', () => {
before(function() {
this.requests = [];
this.api = new FetchPlease('/api/', {XMLHttpRequest});
XMLHttpRequest.onCreate = (xhr) => {
this.requests.push(xhr);
};
});
it('exists', function() {
expect(this.api.put).to.be.a('function');
});
it('sends request', function() {
expect(this.requests.length).to.equal(0);
let promise = this.api.put('users', null);
expect(promise).to.be.an.instanceof(Promise);
expect(this.requests.length).to.equal(1);
this.requests[0].respond(200, {'content-type': 'application/json'}, '{"a":1}');
return promise.then((data) => {
expect(data).to.deep.equal({a: 1});
});
});
after(function() {
this.api = null;
this.requests = [];
XMLHttpRequest.onCreate = null;
});
});
|
"use strict";
/**
* DateFormat ใขใธใฅใผใซ
*
* @module {DateFormat} DateFormat
* @class {DateFormat}
*/
module.exports = new (function DateFormat() {
/**
* ๅฎ่กใณใณใใญในใ
*
* @type {Function}
*/
const self = this;
/**
* ๆฅๆๆๅญๅใซใใ
*/
const _init = function _init() {
};
/**
* ๆฅๆๆๅญๅใซใใ
*
* @param {String} format
* @param {Number} time 1970/01/01 00:00:00 UTCใใใฎ็ต้็ง
* @return {String} ๆฅๆๆๅญๅ
*/
const _strftime = function _strftime(format='%Y/%m/%d %H:%M:%S.%N', time=-1) {
const now = new Date();
if ( isFinite(time) === true && time >= 0.0 ) {
now.setTime(time*1000);
}
const result = format.replace(/%([\d\x20\x2d]?)([A-Za-z])/g, function(match, $p1, $p2){
switch ( $p2 ) {
case 'Y':
match = ('0000' + now.getFullYear() ).substr(-4);
break;
case 'm':
match = ('00' + (now.getMonth() + 1) ).substr(-2);
break;
case 'd':
match = ('00' + now.getDate() ).substr(-2);
break;
case 'H':
match = ('00' + now.getHours() ).substr(-2);
break;
case 'M':
match = ('00' + now.getMinutes() ).substr(-2);
break;
case 'S':
match = ('00' + now.getSeconds() ).substr(-2);
break;
case 'N': case 'L':
match = ('000' + now.getMilliseconds()).substr(-3);
break;
case 's':
match = Math.floor(now.getTime() / 1000);
break;
case 'Z': case 'z':
let o = now.getTimezoneOffset();
let q = o % 60;
let p = (o-q) / 60;
match = '+' + ('00' + p).substr(-2) + ('00' + q).substr(-2);
break;
case 'n':
match = EOL;
break;
case 't':
match = TAB;
break;
default:
break;
}
return match;
});
return result;
};
// -------------------------------------------------------------------------
/**
* ๆฅๆๆๅญๅใซใใ
*
* @param {String} format
* @param {Number} time
* @return {String} ๆฅๆๆๅญๅ
*/
self.strftime = function strftime(format='%Y/%m/%d %H:%M:%S.%3N', time=-1) {
return _strftime(format, time);
};
// -------------------------------------------------------------------------
_init();
return self;
})();
|
Clazz.declarePackage ("JS");
Clazz.load (["JU.JmolMolecule", "JU.BS", "$.Lst", "JS.VTemp"], "JS.SmilesSearch", ["java.util.Arrays", "$.Hashtable", "JU.AU", "$.SB", "$.V3", "JS.SmilesAromatic", "$.SmilesAtom", "$.SmilesBond", "$.SmilesMeasure", "$.SmilesParser", "JU.BSUtil", "$.Logger"], function () {
c$ = Clazz.decorateAsClass (function () {
this.patternAtoms = null;
this.pattern = null;
this.jmolAtoms = null;
this.smartsAtoms = null;
this.bioAtoms = null;
this.jmolAtomCount = 0;
this.bsSelected = null;
this.bsRequired = null;
this.firstMatchOnly = false;
this.matchAllAtoms = false;
this.isSmarts = false;
this.isSmilesFind = false;
this.subSearches = null;
this.haveSelected = false;
this.haveBondStereochemistry = false;
this.haveAtomStereochemistry = false;
this.needRingData = false;
this.needAromatic = true;
this.needRingMemberships = false;
this.ringDataMax = -2147483648;
this.measures = null;
this.flags = 0;
this.ringSets = null;
this.bsAromatic = null;
this.bsAromatic5 = null;
this.bsAromatic6 = null;
this.lastChainAtom = null;
this.asVector = false;
this.getMaps = false;
this.top = null;
this.isSilent = false;
this.isRingCheck = false;
this.selectedAtomCount = 0;
this.ringData = null;
this.ringCounts = null;
this.ringConnections = null;
this.bsFound = null;
this.htNested = null;
this.nNested = 0;
this.nestedBond = null;
this.vReturn = null;
this.bsReturn = null;
this.ignoreStereochemistry = false;
this.noAromatic = false;
this.aromaticDouble = false;
this.bsCheck = null;
this.v = null;
Clazz.instantialize (this, arguments);
}, JS, "SmilesSearch", JU.JmolMolecule);
Clazz.prepareFields (c$, function () {
this.patternAtoms = new Array (16);
this.measures = new JU.Lst ();
this.bsAromatic = new JU.BS ();
this.bsAromatic5 = new JU.BS ();
this.bsAromatic6 = new JU.BS ();
this.top = this;
this.bsFound = new JU.BS ();
this.bsReturn = new JU.BS ();
this.v = new JS.VTemp ();
});
Clazz.defineMethod (c$, "toString",
function () {
var sb = new JU.SB ().append (this.pattern);
sb.append ("\nmolecular formula: " + this.getMolecularFormula (true, null, false));
return sb.toString ();
});
Clazz.defineMethod (c$, "setSelected",
function (bs) {
if (bs == null) {
bs = JU.BS.newN (this.jmolAtomCount);
bs.setBits (0, this.jmolAtomCount);
}this.bsSelected = bs;
}, "JU.BS");
Clazz.defineMethod (c$, "setAtomArray",
function () {
if (this.patternAtoms.length > this.ac) this.patternAtoms = JU.AU.arrayCopyObject (this.patternAtoms, this.ac);
this.nodes = this.patternAtoms;
});
Clazz.defineMethod (c$, "addAtom",
function () {
if (this.ac >= this.patternAtoms.length) this.patternAtoms = JU.AU.doubleLength (this.patternAtoms);
var sAtom = new JS.SmilesAtom ().setIndex (this.ac);
this.patternAtoms[this.ac] = sAtom;
this.ac++;
return sAtom;
});
Clazz.defineMethod (c$, "addNested",
function (pattern) {
if (this.top.htNested == null) this.top.htNested = new java.util.Hashtable ();
this.setNested (++this.top.nNested, pattern);
return this.top.nNested;
}, "~S");
Clazz.defineMethod (c$, "clear",
function () {
this.bsReturn.clearAll ();
this.nNested = 0;
this.htNested = null;
this.nestedBond = null;
this.clearBsFound (-1);
});
Clazz.defineMethod (c$, "setNested",
function (iNested, o) {
this.top.htNested.put ("_" + iNested, o);
}, "~N,~O");
Clazz.defineMethod (c$, "getNested",
function (iNested) {
return this.top.htNested.get ("_" + iNested);
}, "~N");
Clazz.defineMethod (c$, "getMissingHydrogenCount",
function () {
var n = 0;
var nH;
for (var i = 0; i < this.ac; i++) if ((nH = this.patternAtoms[i].missingHydrogenCount) >= 0) n += nH;
return n;
});
Clazz.defineMethod (c$, "setRingData",
function (bsA) {
if (this.needAromatic) this.needRingData = true;
var noAromatic = ((this.flags & 1) != 0);
this.needAromatic = new Boolean (this.needAromatic & ( new Boolean ((bsA == null) & !noAromatic).valueOf ())).valueOf ();
if (!this.needAromatic) {
this.bsAromatic.clearAll ();
if (bsA != null) this.bsAromatic.or (bsA);
if (!this.needRingMemberships && !this.needRingData) return;
}this.getRingData (this.needRingData, this.flags, null);
}, "JU.BS");
Clazz.defineMethod (c$, "getRingData",
function (needRingData, flags, vRings) {
var aromaticStrict = ((flags & 4) != 0);
var aromaticDefined = ((flags & 8) != 0);
if (aromaticStrict && vRings == null) vRings = JU.AU.createArrayOfArrayList (4);
if (aromaticDefined && this.needAromatic) {
this.bsAromatic = JS.SmilesAromatic.checkAromaticDefined (this.jmolAtoms, this.bsSelected);
aromaticStrict = false;
}if (this.ringDataMax < 0) this.ringDataMax = 8;
if (aromaticStrict && this.ringDataMax < 6) this.ringDataMax = 6;
if (needRingData) {
this.ringCounts = Clazz.newIntArray (this.jmolAtomCount, 0);
this.ringConnections = Clazz.newIntArray (this.jmolAtomCount, 0);
this.ringData = new Array (this.ringDataMax + 1);
}this.ringSets = new JU.SB ();
var s = "****";
while (s.length < this.ringDataMax) s += s;
var v5 = null;
for (var i = 3; i <= this.ringDataMax; i++) {
if (i > this.jmolAtomCount) continue;
var smarts = "*1" + s.substring (0, i - 2) + "*1";
var search = JS.SmilesParser.getMolecule (smarts, true);
var vR = this.subsearch (search, false, true);
if (vRings != null && i <= 5) {
var v = new JU.Lst ();
for (var j = vR.size (); --j >= 0; ) v.addLast (vR.get (j));
vRings[i - 3] = v;
}if (this.needAromatic) {
if (!aromaticDefined && (!aromaticStrict || i == 5 || i == 6)) for (var r = vR.size (); --r >= 0; ) {
var bs = vR.get (r);
if (aromaticDefined || JS.SmilesAromatic.isFlatSp2Ring (this.jmolAtoms, this.bsSelected, bs, (aromaticStrict ? 0.1 : 0.01))) this.bsAromatic.or (bs);
}
if (aromaticStrict) {
switch (i) {
case 5:
v5 = vR;
break;
case 6:
if (aromaticDefined) this.bsAromatic = JS.SmilesAromatic.checkAromaticDefined (this.jmolAtoms, this.bsAromatic);
else JS.SmilesAromatic.checkAromaticStrict (this.jmolAtoms, this.bsAromatic, v5, vR);
vRings[3] = new JU.Lst ();
this.setAromatic56 (v5, this.bsAromatic5, 5, vRings[3]);
this.setAromatic56 (vR, this.bsAromatic6, 6, vRings[3]);
break;
}
}}if (needRingData) {
this.ringData[i] = new JU.BS ();
for (var k = 0; k < vR.size (); k++) {
var r = vR.get (k);
this.ringData[i].or (r);
for (var j = r.nextSetBit (0); j >= 0; j = r.nextSetBit (j + 1)) this.ringCounts[j]++;
}
}}
if (needRingData) {
for (var i = this.bsSelected.nextSetBit (0); i >= 0; i = this.bsSelected.nextSetBit (i + 1)) {
var atom = this.jmolAtoms[i];
var bonds = atom.getEdges ();
if (bonds != null) for (var k = bonds.length; --k >= 0; ) if (this.ringCounts[atom.getBondedAtomIndex (k)] > 0) this.ringConnections[i]++;
}
}}, "~B,~N,~A");
Clazz.defineMethod (c$, "setAromatic56",
function (vRings, bs56, n56, vAromatic56) {
for (var k = 0; k < vRings.size (); k++) {
var r = vRings.get (k);
this.v.bsTemp.clearAll ();
this.v.bsTemp.or (r);
this.v.bsTemp.and (this.bsAromatic);
if (this.v.bsTemp.cardinality () == n56) {
bs56.or (r);
if (vAromatic56 != null) vAromatic56.addLast (r);
}}
}, "JU.Lst,JU.BS,~N,JU.Lst");
Clazz.defineMethod (c$, "subsearch",
function (search, firstAtomOnly, isRingCheck) {
search.ringSets = this.ringSets;
search.jmolAtoms = this.jmolAtoms;
search.jmolAtomCount = this.jmolAtomCount;
search.bsSelected = this.bsSelected;
search.htNested = this.htNested;
search.isSmilesFind = this.isSmilesFind;
search.bsCheck = this.bsCheck;
search.isSmarts = true;
search.bsAromatic = this.bsAromatic;
search.bsAromatic5 = this.bsAromatic5;
search.bsAromatic6 = this.bsAromatic6;
search.ringData = this.ringData;
search.ringCounts = this.ringCounts;
search.ringConnections = this.ringConnections;
if (firstAtomOnly) {
search.bsRequired = null;
search.firstMatchOnly = false;
search.matchAllAtoms = false;
} else if (isRingCheck) {
search.bsRequired = null;
search.isSilent = true;
search.isRingCheck = true;
search.asVector = true;
search.matchAllAtoms = false;
} else {
search.haveSelected = this.haveSelected;
search.bsRequired = this.bsRequired;
search.firstMatchOnly = this.firstMatchOnly;
search.matchAllAtoms = this.matchAllAtoms;
search.getMaps = this.getMaps;
search.asVector = this.asVector;
search.vReturn = this.vReturn;
search.bsReturn = this.bsReturn;
}return search.search (firstAtomOnly);
}, "JS.SmilesSearch,~B,~B");
Clazz.defineMethod (c$, "search",
function (firstAtomOnly) {
this.ignoreStereochemistry = ((this.flags & 2) != 0);
this.noAromatic = ((this.flags & 1) != 0);
this.aromaticDouble = ((this.flags & 16) != 0);
if (JU.Logger.debugging && !this.isSilent) JU.Logger.debug ("SmilesSearch processing " + this.pattern);
if (this.vReturn == null && (this.asVector || this.getMaps)) this.vReturn = new JU.Lst ();
if (this.bsSelected == null) {
this.bsSelected = JU.BS.newN (this.jmolAtomCount);
this.bsSelected.setBits (0, this.jmolAtomCount);
}this.selectedAtomCount = this.bsSelected.cardinality ();
if (this.subSearches != null) {
for (var i = 0; i < this.subSearches.length; i++) {
if (this.subSearches[i] == null) continue;
this.subsearch (this.subSearches[i], false, false);
if (this.firstMatchOnly) {
if (this.vReturn == null ? this.bsReturn.nextSetBit (0) >= 0 : this.vReturn.size () > 0) break;
}}
} else if (this.ac > 0) {
this.checkMatch (null, -1, -1, firstAtomOnly);
}return (this.asVector || this.getMaps ? this.vReturn : this.bsReturn);
}, "~B");
Clazz.defineMethod (c$, "checkMatch",
function (patternAtom, atomNum, iAtom, firstAtomOnly) {
var jmolAtom;
var jmolBonds;
if (patternAtom == null) {
if (this.nestedBond == null) {
this.clearBsFound (-1);
} else {
this.bsReturn.clearAll ();
}} else {
if (this.bsFound.get (iAtom) || !this.bsSelected.get (iAtom)) return true;
jmolAtom = this.jmolAtoms[iAtom];
if (!this.isRingCheck) {
if (patternAtom.atomsOr != null) {
for (var ii = 0; ii < patternAtom.nAtomsOr; ii++) if (!this.checkMatch (patternAtom.atomsOr[ii], atomNum, iAtom, firstAtomOnly)) return false;
return true;
}if (patternAtom.primitives == null) {
if (!this.checkPrimitiveAtom (patternAtom, iAtom)) return true;
} else {
for (var i = 0; i < patternAtom.nPrimitives; i++) if (!this.checkPrimitiveAtom (patternAtom.primitives[i], iAtom)) return true;
}}jmolBonds = jmolAtom.getEdges ();
for (var i = patternAtom.getBondCount (); --i >= 0; ) {
var patternBond = patternAtom.getBond (i);
if (patternBond.getAtomIndex2 () != patternAtom.index) continue;
var atom1 = patternBond.atom1;
var matchingAtom = atom1.getMatchingAtom ();
switch (patternBond.order) {
case 96:
case 112:
if (!this.checkMatchBond (patternAtom, atom1, patternBond, iAtom, matchingAtom, null)) return true;
break;
default:
var k = 0;
for (; k < jmolBonds.length; k++) if ((jmolBonds[k].getAtomIndex1 () == matchingAtom || jmolBonds[k].getAtomIndex2 () == matchingAtom) && jmolBonds[k].isCovalent ()) break;
if (k == jmolBonds.length) return true;
if (!this.checkMatchBond (patternAtom, atom1, patternBond, iAtom, matchingAtom, jmolBonds[k])) return true;
}
}
this.patternAtoms[patternAtom.index].setMatchingAtom (iAtom);
if (JU.Logger.debugging && !this.isSilent) JU.Logger.debug ("pattern atom " + atomNum + " " + patternAtom);
this.bsFound.set (iAtom);
}if (!this.continueMatch (atomNum, iAtom, firstAtomOnly)) return false;
if (iAtom >= 0) this.clearBsFound (iAtom);
return true;
}, "JS.SmilesAtom,~N,~N,~B");
Clazz.defineMethod (c$, "continueMatch",
function (atomNum, iAtom, firstAtomOnly) {
var jmolAtom;
var jmolBonds;
if (++atomNum < this.ac) {
var newPatternAtom = this.patternAtoms[atomNum];
var newPatternBond = (iAtom >= 0 ? newPatternAtom.getBondTo (null) : atomNum == 0 ? this.nestedBond : null);
if (newPatternBond == null) {
var bs = JU.BSUtil.copy (this.bsFound);
if (newPatternAtom.notBondedIndex >= 0) {
var pa = this.patternAtoms[newPatternAtom.notBondedIndex];
var a = this.jmolAtoms[pa.getMatchingAtom ()];
if (pa.isBioAtom) {
var ii = (a).getOffsetResidueAtom ("0", 1);
if (ii >= 0) bs.set (ii);
ii = (a).getOffsetResidueAtom ("0", -1);
if (ii >= 0) bs.set (ii);
} else {
jmolBonds = a.getEdges ();
for (var k = 0; k < jmolBonds.length; k++) bs.set (jmolBonds[k].getOtherAtomNode (a).getIndex ());
}}var skipGroup = (iAtom >= 0 && newPatternAtom.isBioAtom && (newPatternAtom.atomName == null || newPatternAtom.residueChar != null));
for (var j = this.bsSelected.nextSetBit (0); j >= 0; j = this.bsSelected.nextSetBit (j + 1)) {
if (!bs.get (j) && !this.checkMatch (newPatternAtom, atomNum, j, firstAtomOnly)) return false;
if (skipGroup) {
var j1 = (this.jmolAtoms[j]).getOffsetResidueAtom (newPatternAtom.atomName, 1);
if (j1 >= 0) j = j1 - 1;
}}
this.bsFound = bs;
return true;
}jmolAtom = this.jmolAtoms[newPatternBond.atom1.getMatchingAtom ()];
switch (newPatternBond.order) {
case 96:
var nextGroupAtom = (jmolAtom).getOffsetResidueAtom (newPatternAtom.atomName, 1);
if (nextGroupAtom >= 0) {
var bs = JU.BSUtil.copy (this.bsFound);
(jmolAtom).getGroupBits (this.bsFound);
if (!this.checkMatch (newPatternAtom, atomNum, nextGroupAtom, firstAtomOnly)) return false;
this.bsFound = bs;
}return true;
case 112:
var vLinks = new JU.Lst ();
(jmolAtom).getCrossLinkLeadAtomIndexes (vLinks);
var bs = JU.BSUtil.copy (this.bsFound);
(jmolAtom).getGroupBits (this.bsFound);
for (var j = 0; j < vLinks.size (); j++) if (!this.checkMatch (newPatternAtom, atomNum, vLinks.get (j).intValue (), firstAtomOnly)) return false;
this.bsFound = bs;
return true;
}
jmolBonds = jmolAtom.getEdges ();
if (jmolBonds != null) for (var j = 0; j < jmolBonds.length; j++) if (!this.checkMatch (newPatternAtom, atomNum, jmolAtom.getBondedAtomIndex (j), firstAtomOnly)) return false;
this.clearBsFound (iAtom);
return true;
}if (!this.ignoreStereochemistry && !this.checkStereochemistry ()) return true;
var bs = new JU.BS ();
var nMatch = 0;
for (var j = 0; j < this.ac; j++) {
var i = this.patternAtoms[j].getMatchingAtom ();
if (!firstAtomOnly && this.top.haveSelected && !this.patternAtoms[j].selected) continue;
nMatch++;
bs.set (i);
if (this.patternAtoms[j].isBioAtom && this.patternAtoms[j].atomName == null) (this.jmolAtoms[i]).getGroupBits (bs);
if (firstAtomOnly) break;
if (!this.isSmarts && this.patternAtoms[j].missingHydrogenCount > 0) this.getHydrogens (this.jmolAtoms[i], bs);
}
if (this.bsRequired != null && !this.bsRequired.intersects (bs)) return true;
if (this.matchAllAtoms && bs.cardinality () != this.selectedAtomCount) return true;
if (this.bsCheck != null) {
if (firstAtomOnly) {
this.bsCheck.clearAll ();
for (var j = 0; j < this.ac; j++) {
this.bsCheck.set (this.patternAtoms[j].getMatchingAtom ());
}
if (this.bsCheck.cardinality () != this.ac) return true;
} else {
if (bs.cardinality () != this.ac) return true;
}}this.bsReturn.or (bs);
if (this.getMaps) {
var map = Clazz.newIntArray (nMatch, 0);
for (var j = 0, nn = 0; j < this.ac; j++) {
if (!firstAtomOnly && this.top.haveSelected && !this.patternAtoms[j].selected) continue;
map[nn++] = this.patternAtoms[j].getMatchingAtom ();
}
this.vReturn.addLast (map);
return !this.firstMatchOnly;
}if (this.asVector) {
var isOK = true;
for (var j = this.vReturn.size (); --j >= 0 && isOK; ) isOK = !((this.vReturn.get (j)).equals (bs));
if (!isOK) return true;
this.vReturn.addLast (bs);
}if (this.isRingCheck) {
this.ringSets.append (" ");
for (var k = atomNum * 3 + 2; --k > atomNum; ) this.ringSets.append ("-").appendI (this.patternAtoms[(k <= atomNum * 2 ? atomNum * 2 - k + 1 : k - 1) % atomNum].getMatchingAtom ());
this.ringSets.append ("- ");
return true;
}if (this.firstMatchOnly) return false;
return (bs.cardinality () != this.selectedAtomCount);
}, "~N,~N,~B");
Clazz.defineMethod (c$, "clearBsFound",
function (iAtom) {
if (iAtom < 0) {
if (this.bsCheck == null) {
this.bsFound.clearAll ();
}} else this.bsFound.clear (iAtom);
}, "~N");
Clazz.defineMethod (c$, "getHydrogens",
function (atom, bsHydrogens) {
var b = atom.getEdges ();
var k = -1;
for (var i = 0; i < b.length; i++) if (this.jmolAtoms[atom.getBondedAtomIndex (i)].getElementNumber () == 1) {
k = atom.getBondedAtomIndex (i);
if (bsHydrogens == null) break;
bsHydrogens.set (k);
}
return (k >= 0 ? this.jmolAtoms[k] : null);
}, "JU.Node,JU.BS");
Clazz.defineMethod (c$, "checkPrimitiveAtom",
function (patternAtom, iAtom) {
var atom = this.jmolAtoms[iAtom];
var foundAtom = patternAtom.not;
while (true) {
var n;
if (patternAtom.iNested > 0) {
var o = this.getNested (patternAtom.iNested);
if (Clazz.instanceOf (o, JS.SmilesSearch)) {
var search = o;
if (patternAtom.isBioAtom) search.nestedBond = patternAtom.getBondTo (null);
o = this.subsearch (search, true, false);
if (o == null) o = new JU.BS ();
if (!patternAtom.isBioAtom) this.setNested (patternAtom.iNested, o);
}foundAtom = (patternAtom.not != ((o).get (iAtom)));
break;
}if (patternAtom.isBioAtom) {
var a = atom;
if (patternAtom.atomName != null && (patternAtom.isLeadAtom () ? !a.isLeadAtom () : !patternAtom.atomName.equals (a.getAtomName ().toUpperCase ()))) break;
if (patternAtom.notCrossLinked && a.getCrossLinkLeadAtomIndexes (null)) break;
if (patternAtom.residueName != null && !patternAtom.residueName.equals (a.getGroup3 (false).toUpperCase ())) break;
if (patternAtom.residueChar != null) {
if (patternAtom.isDna () && !a.isDna () || patternAtom.isRna () && !a.isRna () || patternAtom.isProtein () && !a.isProtein () || patternAtom.isNucleic () && !a.isNucleic ()) break;
var s = a.getGroup1 ('\0').toUpperCase ();
var isOK = patternAtom.residueChar.equals (s);
switch (patternAtom.residueChar.charAt (0)) {
case 'N':
isOK = patternAtom.isNucleic () ? a.isNucleic () : isOK;
break;
case 'R':
isOK = patternAtom.isNucleic () ? a.isPurine () : isOK;
break;
case 'Y':
isOK = patternAtom.isNucleic () ? a.isPyrimidine () : isOK;
break;
}
if (!isOK) break;
}if (patternAtom.elementNumber >= 0 && patternAtom.elementNumber != atom.getElementNumber ()) break;
} else {
if (patternAtom.atomName != null && (!patternAtom.atomName.equals (atom.getAtomName ().toUpperCase ()))) break;
if (patternAtom.jmolIndex >= 0 && atom.getIndex () != patternAtom.jmolIndex) break;
if (patternAtom.atomType != null && !patternAtom.atomType.equals (atom.getAtomType ())) break;
if (patternAtom.elementNumber >= 0 && patternAtom.elementNumber != atom.getElementNumber ()) break;
var isAromatic = patternAtom.isAromatic ();
if (!this.noAromatic && !patternAtom.aromaticAmbiguous && isAromatic != this.bsAromatic.get (iAtom)) break;
if ((n = patternAtom.getAtomicMass ()) != -2147483648) {
var isotope = atom.getIsotopeNumber ();
if (n >= 0 && n != isotope || n < 0 && isotope != 0 && -n != isotope) {
break;
}}if ((n = patternAtom.getCharge ()) != -2147483648 && n != atom.getFormalCharge ()) break;
n = patternAtom.getCovalentHydrogenCount () + patternAtom.missingHydrogenCount;
if (n >= 0 && n != atom.getCovalentHydrogenCount ()) break;
n = patternAtom.implicitHydrogenCount;
if (n != -2147483648) {
var nH = atom.getImplicitHydrogenCount ();
if (n == -1 ? nH == 0 : n != nH) break;
}if (patternAtom.degree > 0 && patternAtom.degree != atom.getCovalentBondCount ()) break;
if (patternAtom.nonhydrogenDegree > 0 && patternAtom.nonhydrogenDegree != atom.getCovalentBondCount () - atom.getCovalentHydrogenCount ()) break;
if (patternAtom.valence > 0 && patternAtom.valence != atom.getValence ()) break;
if (patternAtom.connectivity > 0 && patternAtom.connectivity != atom.getCovalentBondCount () + atom.getImplicitHydrogenCount ()) break;
if (this.ringData != null && patternAtom.ringSize >= -1) {
if (patternAtom.ringSize <= 0) {
if ((this.ringCounts[iAtom] == 0) != (patternAtom.ringSize == 0)) break;
} else {
var rd = this.ringData[patternAtom.ringSize == 500 ? 5 : patternAtom.ringSize == 600 ? 6 : patternAtom.ringSize];
if (rd == null || !rd.get (iAtom)) break;
if (!this.noAromatic) if (patternAtom.ringSize == 500) {
if (!this.bsAromatic5.get (iAtom)) break;
} else if (patternAtom.ringSize == 600) {
if (!this.bsAromatic6.get (iAtom)) break;
}}}if (this.ringData != null && patternAtom.ringMembership >= -1) {
if (patternAtom.ringMembership == -1 ? this.ringCounts[iAtom] == 0 : this.ringCounts[iAtom] != patternAtom.ringMembership) break;
}if (patternAtom.ringConnectivity >= 0) {
n = this.ringConnections[iAtom];
if (patternAtom.ringConnectivity == -1 && n == 0 || patternAtom.ringConnectivity != -1 && n != patternAtom.ringConnectivity) break;
}}foundAtom = !foundAtom;
break;
}
return foundAtom;
}, "JS.SmilesAtom,~N");
Clazz.defineMethod (c$, "checkMatchBond",
function (patternAtom, atom1, patternBond, iAtom, matchingAtom, bond) {
if (patternBond.bondsOr != null) {
for (var ii = 0; ii < patternBond.nBondsOr; ii++) if (this.checkMatchBond (patternAtom, atom1, patternBond.bondsOr[ii], iAtom, matchingAtom, bond)) return true;
return false;
}if (patternBond.primitives == null) {
if (!this.checkPrimitiveBond (patternBond, iAtom, matchingAtom, bond)) return false;
} else {
for (var i = 0; i < patternBond.nPrimitives; i++) if (!this.checkPrimitiveBond (patternBond.primitives[i], iAtom, matchingAtom, bond)) return false;
}patternBond.matchingBond = bond;
return true;
}, "JS.SmilesAtom,JS.SmilesAtom,JS.SmilesBond,~N,~N,JU.Edge");
Clazz.defineMethod (c$, "checkPrimitiveBond",
function (patternBond, iAtom1, iAtom2, bond) {
var bondFound = false;
switch (patternBond.order) {
case 96:
return (patternBond.isNot != (this.bioAtoms[iAtom2].getOffsetResidueAtom ("0", 1) == this.bioAtoms[iAtom1].getOffsetResidueAtom ("0", 0)));
case 112:
return (patternBond.isNot != this.bioAtoms[iAtom1].isCrossLinked (this.bioAtoms[iAtom2]));
}
var isAromatic1 = (!this.noAromatic && this.bsAromatic.get (iAtom1));
var isAromatic2 = (!this.noAromatic && this.bsAromatic.get (iAtom2));
var order = bond.getCovalentOrder ();
if (isAromatic1 && isAromatic2) {
switch (patternBond.order) {
case 17:
case 65:
bondFound = JS.SmilesSearch.isRingBond (this.ringSets, iAtom1, iAtom2);
break;
case 1:
bondFound = !this.isSmarts || !JS.SmilesSearch.isRingBond (this.ringSets, iAtom1, iAtom2);
break;
case 2:
bondFound = !this.isSmarts || this.aromaticDouble && (order == 2 || order == 514);
break;
case 769:
case 1025:
case 81:
case -1:
bondFound = true;
break;
}
} else {
switch (patternBond.order) {
case 81:
case -1:
bondFound = true;
break;
case 1:
case 257:
case 513:
bondFound = (order == 1 || order == 1041 || order == 1025);
break;
case 769:
bondFound = (order == (this.isSmilesFind ? 33 : 1));
break;
case 1025:
bondFound = (order == (this.isSmilesFind ? 97 : 1));
break;
case 2:
bondFound = (order == 2);
break;
case 3:
bondFound = (order == 3);
break;
case 65:
bondFound = JS.SmilesSearch.isRingBond (this.ringSets, iAtom1, iAtom2);
break;
}
}return bondFound != patternBond.isNot;
}, "JS.SmilesBond,~N,~N,JU.Edge");
c$.isRingBond = Clazz.defineMethod (c$, "isRingBond",
function (ringSets, i, j) {
return (ringSets != null && ringSets.indexOf ("-" + i + "-" + j + "-") >= 0);
}, "JU.SB,~N,~N");
Clazz.defineMethod (c$, "checkStereochemistry",
function () {
for (var i = 0; i < this.measures.size (); i++) if (!this.measures.get (i).check ()) return false;
if (this.haveAtomStereochemistry) {
if (JU.Logger.debugging) JU.Logger.debug ("checking stereochemistry...");
var atom1 = null;
var atom2 = null;
var atom3 = null;
var atom4 = null;
var atom5 = null;
var atom6 = null;
var sAtom1 = null;
var sAtom2 = null;
var jn;
for (var i = 0; i < this.ac; i++) {
var sAtom = this.patternAtoms[i];
var atom0 = this.jmolAtoms[sAtom.getMatchingAtom ()];
var nH = sAtom.missingHydrogenCount;
if (nH < 0) nH = 0;
var chiralClass = sAtom.getChiralClass ();
if (chiralClass == -2147483648) continue;
var order = sAtom.getChiralOrder ();
if (this.isSmilesFind && (atom0.getAtomSite () >> 8) != chiralClass) return false;
atom4 = null;
if (JU.Logger.debugging) JU.Logger.debug ("...type " + chiralClass + " for pattern atom " + sAtom + " " + atom0);
switch (chiralClass) {
case 2:
var isAllene = true;
if (isAllene) {
sAtom1 = sAtom.getBond (0).getOtherAtom (sAtom);
sAtom2 = sAtom.getBond (1).getOtherAtom (sAtom);
if (sAtom1 == null || sAtom2 == null) continue;
var sAtom1a = sAtom;
var sAtom2a = sAtom;
while (sAtom1.getBondCount () == 2 && sAtom2.getBondCount () == 2 && sAtom1.getValence () == 4 && sAtom2.getValence () == 4) {
var b = sAtom1.getBondNotTo (sAtom1a, true);
sAtom1a = sAtom1;
sAtom1 = b.getOtherAtom (sAtom1);
b = sAtom2.getBondNotTo (sAtom2a, true);
sAtom2a = sAtom2;
sAtom2 = b.getOtherAtom (sAtom2);
}
sAtom = sAtom1;
}jn = new Array (6);
jn[4] = new JS.SmilesAtom ().setIndex (604);
var nBonds = sAtom.getBondCount ();
for (var k = 0; k < nBonds; k++) {
sAtom1 = sAtom.bonds[k].getOtherAtom (sAtom);
if (sAtom.bonds[k].matchingBond.getCovalentOrder () == 2) {
if (sAtom2 == null) sAtom2 = sAtom1;
} else if (jn[0] == null) {
jn[0] = this.getJmolAtom (sAtom1.getMatchingAtom ());
} else {
jn[1] = this.getJmolAtom (sAtom1.getMatchingAtom ());
}}
if (sAtom2 == null) continue;
nBonds = sAtom2.getBondCount ();
if (nBonds < 2 || nBonds > 3) continue;
for (var k = 0; k < nBonds; k++) {
sAtom1 = sAtom2.bonds[k].getOtherAtom (sAtom2);
if (sAtom2.bonds[k].matchingBond.getCovalentOrder () == 2) {
} else if (jn[2] == null) {
jn[2] = this.getJmolAtom (sAtom1.getMatchingAtom ());
} else {
jn[3] = this.getJmolAtom (sAtom1.getMatchingAtom ());
}}
if (this.isSmilesFind) {
if (jn[1] == null) this.getX (sAtom, jn, 1, false, isAllene);
if (jn[3] == null) this.getX (sAtom2, jn, 3, false, false);
if (!this.setSmilesCoordinates (atom0, sAtom, sAtom2, jn)) return false;
}if (jn[1] == null) this.getX (sAtom, jn, 1, true, false);
if (jn[3] == null) this.getX (sAtom2, jn, 3, true, false);
if (!JS.SmilesSearch.checkStereochemistryAll (sAtom.not, atom0, chiralClass, order, jn[0], jn[1], jn[2], jn[3], null, null, this.v)) return false;
continue;
case 4:
case 8:
case 5:
case 6:
atom1 = this.getJmolAtom (sAtom.getMatchingBondedAtom (0));
switch (nH) {
case 0:
atom2 = this.getJmolAtom (sAtom.getMatchingBondedAtom (1));
break;
case 1:
atom2 = this.getHydrogens (this.getJmolAtom (sAtom.getMatchingAtom ()), null);
if (sAtom.isFirst) {
var a = atom2;
atom2 = atom1;
atom1 = a;
}break;
default:
continue;
}
atom3 = this.getJmolAtom (sAtom.getMatchingBondedAtom (2 - nH));
atom4 = this.getJmolAtom (sAtom.getMatchingBondedAtom (3 - nH));
atom5 = this.getJmolAtom (sAtom.getMatchingBondedAtom (4 - nH));
atom6 = this.getJmolAtom (sAtom.getMatchingBondedAtom (5 - nH));
if (this.isSmilesFind && !this.setSmilesCoordinates (atom0, sAtom, sAtom2, [atom1, atom2, atom3, atom4, atom5, atom6])) return false;
if (!JS.SmilesSearch.checkStereochemistryAll (sAtom.not, atom0, chiralClass, order, atom1, atom2, atom3, atom4, atom5, atom6, this.v)) return false;
continue;
}
}
}if (this.haveBondStereochemistry) {
for (var k = 0; k < this.ac; k++) {
var sAtom1 = this.patternAtoms[k];
var sAtom2 = null;
var sAtomDirected1 = null;
var sAtomDirected2 = null;
var dir1 = 0;
var dir2 = 0;
var bondType = 0;
var b;
var nBonds = sAtom1.getBondCount ();
var isAtropisomer = false;
for (var j = 0; j < nBonds; j++) {
b = sAtom1.getBond (j);
var isAtom2 = (b.atom2 === sAtom1);
var type = b.order;
switch (type) {
case 769:
case 1025:
case 2:
if (isAtom2) continue;
sAtom2 = b.atom2;
bondType = type;
isAtropisomer = (type != 2);
if (isAtropisomer) dir1 = (b.isNot ? -1 : 1);
break;
case 257:
case 513:
sAtomDirected1 = (isAtom2 ? b.atom1 : b.atom2);
dir1 = (isAtom2 != (type == 257) ? 1 : -1);
break;
}
}
if (isAtropisomer) {
b = sAtom1.getBondNotTo (sAtom2, false);
if (b == null) return false;
sAtomDirected1 = b.getOtherAtom (sAtom1);
b = sAtom2.getBondNotTo (sAtom1, false);
if (b == null) return false;
sAtomDirected2 = b.getOtherAtom (sAtom2);
} else {
if (sAtom2 == null || dir1 == 0) continue;
nBonds = sAtom2.getBondCount ();
for (var j = 0; j < nBonds && dir2 == 0; j++) {
b = sAtom2.getBond (j);
var isAtom2 = (b.atom2 === sAtom2);
var type = b.order;
switch (type) {
case 257:
case 513:
sAtomDirected2 = (isAtom2 ? b.atom1 : b.atom2);
dir2 = (isAtom2 != (type == 257) ? 1 : -1);
break;
}
}
if (dir2 == 0) continue;
}if (this.isSmilesFind) this.setSmilesBondCoordinates (sAtom1, sAtom2, bondType);
var dbAtom1 = this.getJmolAtom (sAtom1.getMatchingAtom ());
var dbAtom2 = this.getJmolAtom (sAtom2.getMatchingAtom ());
var dbAtom1a = this.getJmolAtom (sAtomDirected1.getMatchingAtom ());
var dbAtom2a = this.getJmolAtom (sAtomDirected2.getMatchingAtom ());
if (dbAtom1a == null || dbAtom2a == null) return false;
JS.SmilesMeasure.setTorsionData (dbAtom1a, dbAtom1, dbAtom2, dbAtom2a, this.v, isAtropisomer);
if (isAtropisomer) {
dir2 = (bondType == 769 ? 1 : -1);
var f = this.v.vTemp1.dot (this.v.vTemp2);
if (f < 0.05 || f > 0.95 || this.v.vNorm1.dot (this.v.vNorm2) * dir1 * dir2 > 0) return false;
} else {
if (this.v.vTemp1.dot (this.v.vTemp2) * dir1 * dir2 < 0) return false;
}}
}return true;
});
Clazz.defineMethod (c$, "getX",
function (sAtom, jn, pt, haveCoordinates, needHSwitch) {
var atom = this.getJmolAtom (sAtom.getMatchingAtom ());
var doSwitch = sAtom.isFirst || pt == 3;
if (haveCoordinates) {
if (this.isSmarts) {
var b = atom.getEdges ();
for (var i = 0; i < b.length; i++) {
if (b[i].getCovalentOrder () == 2) continue;
var a = this.jmolAtoms[atom.getBondedAtomIndex (i)];
if (a === jn[pt - 1]) continue;
jn[pt] = a;
break;
}
}if (jn[pt] == null) {
var v = new JU.V3 ();
var n = 0;
for (var i = 0; i < 4; i++) {
if (jn[i] == null) continue;
n++;
v.sub (jn[i]);
}
if (v.length () == 0) {
v.setT ((jn[4]));
doSwitch = false;
} else {
v.scaleAdd2 (n + 1, this.getJmolAtom (sAtom.getMatchingAtom ()), v);
doSwitch = this.isSmilesFind || doSwitch;
}jn[pt] = new JS.SmilesAtom ().setIndex (-1);
(jn[pt]).setT (v);
}}if (jn[pt] == null) {
jn[pt] = this.getHydrogens (atom, null);
if (needHSwitch) doSwitch = true;
}if (jn[pt] != null && doSwitch) {
var a = jn[pt];
jn[pt] = jn[pt - 1];
jn[pt - 1] = a;
}}, "JS.SmilesAtom,~A,~N,~B,~B");
c$.checkStereochemistryAll = Clazz.defineMethod (c$, "checkStereochemistryAll",
function (isNot, atom0, chiralClass, order, atom1, atom2, atom3, atom4, atom5, atom6, v) {
switch (chiralClass) {
default:
case 2:
case 4:
return (isNot == (JS.SmilesSearch.getHandedness (atom2, atom3, atom4, atom1, v) != order));
case 5:
return (isNot == (!JS.SmilesSearch.isDiaxial (atom0, atom0, atom5, atom1, v, -0.95) || JS.SmilesSearch.getHandedness (atom2, atom3, atom4, atom1, v) != order));
case 6:
if (isNot != (!JS.SmilesSearch.isDiaxial (atom0, atom0, atom6, atom1, v, -0.95))) return false;
JS.SmilesSearch.getPlaneNormals (atom2, atom3, atom4, atom5, v);
if (isNot != (v.vNorm1.dot (v.vNorm2) < 0 || v.vNorm2.dot (v.vNorm3) < 0)) return false;
v.vNorm2.sub2 (atom0, atom1);
return (isNot == ((v.vNorm1.dot (v.vNorm2) < 0 ? 2 : 1) == order));
case 8:
JS.SmilesSearch.getPlaneNormals (atom1, atom2, atom3, atom4, v);
return (v.vNorm1.dot (v.vNorm2) < 0 ? isNot == (order != 3) : v.vNorm2.dot (v.vNorm3) < 0 ? isNot == (order != 2) : isNot == (order != 1));
}
}, "~B,JU.Node,~N,~N,JU.Node,JU.Node,JU.Node,JU.Node,JU.Node,JU.Node,JS.VTemp");
Clazz.defineMethod (c$, "getJmolAtom",
function (i) {
return (i < 0 || i >= this.jmolAtoms.length ? null : this.jmolAtoms[i]);
}, "~N");
Clazz.defineMethod (c$, "setSmilesBondCoordinates",
function (sAtom1, sAtom2, bondType) {
var dbAtom1 = this.jmolAtoms[sAtom1.getMatchingAtom ()];
var dbAtom2 = this.jmolAtoms[sAtom2.getMatchingAtom ()];
dbAtom1.set (-1, 0, 0);
dbAtom2.set (1, 0, 0);
if (bondType == 2) {
var nBonds = 0;
var dir1 = 0;
var bonds = dbAtom1.getEdges ();
for (var k = bonds.length; --k >= 0; ) {
var bond = bonds[k];
var atom = bond.getOtherAtomNode (dbAtom1);
if (atom === dbAtom2) continue;
atom.set (-1, (nBonds++ == 0) ? -1 : 1, 0);
var mode = (bond.getAtomIndex2 () == dbAtom1.getIndex () ? nBonds : -nBonds);
switch (bond.order) {
case 1025:
dir1 = mode;
break;
case 1041:
dir1 = -mode;
}
}
var dir2 = 0;
nBonds = 0;
var atoms = new Array (2);
bonds = dbAtom2.getEdges ();
for (var k = bonds.length; --k >= 0; ) {
var bond = bonds[k];
var atom = bond.getOtherAtomNode (dbAtom2);
if (atom === dbAtom1) continue;
atoms[nBonds] = atom;
atom.set (1, (nBonds++ == 0) ? 1 : -1, 0);
var mode = (bond.getAtomIndex2 () == dbAtom2.getIndex () ? nBonds : -nBonds);
switch (bond.order) {
case 1025:
dir2 = mode;
break;
case 1041:
dir2 = -mode;
}
}
if ((dir1 * dir2 > 0) == (Math.abs (dir1) % 2 == Math.abs (dir2) % 2)) {
var y = (atoms[0]).y;
(atoms[0]).y = (atoms[1]).y;
(atoms[1]).y = y;
}} else {
var bonds = dbAtom1.getEdges ();
var dir = 0;
for (var k = bonds.length; --k >= 0; ) {
var bond = bonds[k];
if (bond.getOtherAtomNode (dbAtom1) === dbAtom2) {
dir = (bond.order == 33 ? 1 : -1);
break;
}}
for (var k = bonds.length; --k >= 0; ) {
var bond = bonds[k];
var atom = bond.getOtherAtomNode (dbAtom1);
if (atom !== dbAtom2) atom.set (-1, 1, 0);
}
bonds = dbAtom2.getEdges ();
for (var k = bonds.length; --k >= 0; ) {
var bond = bonds[k];
var atom = bond.getOtherAtomNode (dbAtom2);
if (atom !== dbAtom1) atom.set (1, 1, -dir / 2.0);
}
}}, "JS.SmilesAtom,JS.SmilesAtom,~N");
Clazz.defineMethod (c$, "setSmilesCoordinates",
function (atom, sAtom, sAtom2, cAtoms) {
var atomSite = atom.getAtomSite ();
if (atomSite == -2147483648) return false;
var chiralClass = atomSite >> 8;
var chiralOrder = atomSite & 0xFF;
var a2 = (chiralClass == 2 || chiralClass == 3 ? a2 = this.jmolAtoms[sAtom2.getMatchingAtom ()] : null);
atom.set (0, 0, 0);
atom = this.jmolAtoms[sAtom.getMatchingAtom ()];
atom.set (0, 0, 0);
var map = this.getMappedAtoms (atom, a2, cAtoms);
switch (chiralClass) {
case 2:
case 4:
if (chiralOrder == 2) {
var i = map[0];
map[0] = map[1];
map[1] = i;
}cAtoms[map[0]].set (0, 0, 1);
cAtoms[map[1]].set (1, 0, -1);
cAtoms[map[2]].set (0, 1, -1);
cAtoms[map[3]].set (-1, -1, -1);
break;
case 8:
switch (chiralOrder) {
case 1:
cAtoms[map[0]].set (1, 0, 0);
cAtoms[map[1]].set (0, 1, 0);
cAtoms[map[2]].set (-1, 0, 0);
cAtoms[map[3]].set (0, -1, 0);
break;
case 2:
cAtoms[map[0]].set (1, 0, 0);
cAtoms[map[1]].set (-1, 0, 0);
cAtoms[map[2]].set (0, 1, 0);
cAtoms[map[3]].set (0, -1, 0);
break;
case 3:
cAtoms[map[0]].set (1, 0, 0);
cAtoms[map[1]].set (0, 1, 0);
cAtoms[map[2]].set (0, -1, 0);
cAtoms[map[3]].set (-1, 0, 0);
break;
}
break;
case 5:
case 6:
var n = map.length;
if (chiralOrder == 2) {
var i = map[0];
map[0] = map[n - 1];
map[n - 1] = i;
}cAtoms[map[0]].set (0, 0, 1);
cAtoms[map[n - 1]].set (0, 0, -1);
cAtoms[map[1]].set (1, 0, 0);
cAtoms[map[2]].set (0, 1, 0);
cAtoms[map[3]].set (-1, 0, 0);
if (n == 6) cAtoms[map[4]].set (0, -1, 0);
break;
}
return true;
}, "JU.Node,JS.SmilesAtom,JS.SmilesAtom,~A");
Clazz.defineMethod (c$, "getMappedAtoms",
function (atom, a2, cAtoms) {
var map = Clazz.newIntArray (cAtoms[4] == null ? 4 : cAtoms[5] == null ? 5 : 6, 0);
for (var i = 0; i < map.length; i++) map[i] = (cAtoms[i] == null ? 104 + i * 100 : cAtoms[i].getIndex ());
var k;
var bonds = atom.getEdges ();
var b2 = (a2 == null ? null : a2.getEdges ());
for (var i = 0; i < map.length; i++) {
for (k = 0; k < bonds.length; k++) if (bonds[k].getOtherAtomNode (atom) === cAtoms[i]) break;
if (k < bonds.length) {
map[i] = (k * 10 + 100) + i;
} else if (a2 != null) {
for (k = 0; k < b2.length; k++) if (b2[k].getOtherAtomNode (a2) === cAtoms[i]) break;
if (k < b2.length) map[i] = (k * 10 + 300) + i;
}}
java.util.Arrays.sort (map);
for (var i = 0; i < map.length; i++) {
map[i] = map[i] % 10;
}
return map;
}, "JU.Node,JU.Node,~A");
c$.isDiaxial = Clazz.defineMethod (c$, "isDiaxial",
function (atomA, atomB, atom1, atom2, v, f) {
v.vA.sub2 (atomA, atom1);
v.vB.sub2 (atomB, atom2);
v.vA.normalize ();
v.vB.normalize ();
return (v.vA.dot (v.vB) < f);
}, "JU.Node,JU.Node,JU.Node,JU.Node,JS.VTemp,~N");
c$.getHandedness = Clazz.defineMethod (c$, "getHandedness",
function (a, b, c, pt, v) {
var d = JS.SmilesAromatic.getNormalThroughPoints (a, b, c, v.vTemp, v.vA, v.vB);
return (JS.SmilesSearch.distanceToPlane (v.vTemp, d, pt) > 0 ? 1 : 2);
}, "JU.Node,JU.Node,JU.Node,JU.Node,JS.VTemp");
c$.getPlaneNormals = Clazz.defineMethod (c$, "getPlaneNormals",
function (atom1, atom2, atom3, atom4, v) {
JS.SmilesAromatic.getNormalThroughPoints (atom1, atom2, atom3, v.vNorm1, v.vTemp1, v.vTemp2);
JS.SmilesAromatic.getNormalThroughPoints (atom2, atom3, atom4, v.vNorm2, v.vTemp1, v.vTemp2);
JS.SmilesAromatic.getNormalThroughPoints (atom3, atom4, atom1, v.vNorm3, v.vTemp1, v.vTemp2);
}, "JU.Node,JU.Node,JU.Node,JU.Node,JS.VTemp");
c$.distanceToPlane = Clazz.defineMethod (c$, "distanceToPlane",
function (norm, w, pt) {
return (norm == null ? NaN : (norm.x * pt.x + norm.y * pt.y + norm.z * pt.z + w) / Math.sqrt (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z));
}, "JU.V3,~N,JU.P3");
Clazz.defineMethod (c$, "createTopoMap",
function (bsAromatic) {
if (bsAromatic == null) bsAromatic = new JU.BS ();
var nAtomsMissing = this.getMissingHydrogenCount ();
var atoms = new Array (this.ac + nAtomsMissing);
this.jmolAtoms = atoms;
var ptAtom = 0;
var bsFixH = new JU.BS ();
for (var i = 0; i < this.ac; i++) {
var sAtom = this.patternAtoms[i];
var cclass = sAtom.getChiralClass ();
var n = sAtom.missingHydrogenCount;
if (n < 0) n = 0;
var atom = atoms[ptAtom] = new JS.SmilesAtom ().setAll (0, ptAtom, cclass == -2147483648 ? cclass : (cclass << 8) + sAtom.getChiralOrder (), sAtom.elementNumber, sAtom.getCharge ());
atom.atomName = sAtom.atomName;
atom.residueName = sAtom.residueName;
atom.residueChar = sAtom.residueChar;
atom.isBioAtom = sAtom.isBioAtom;
atom.$isLeadAtom = sAtom.$isLeadAtom;
atom.setAtomicMass (sAtom.getAtomicMass ());
if (sAtom.isAromatic ()) bsAromatic.set (ptAtom);
if (!sAtom.isFirst && n == 1 && cclass > 0) bsFixH.set (ptAtom);
sAtom.setMatchingAtom (ptAtom++);
var bonds = new Array (sAtom.getBondCount () + n);
atom.setBonds (bonds);
while (--n >= 0) {
var atomH = atoms[ptAtom] = new JS.SmilesAtom ().setAll (0, ptAtom, 0, 1, 0);
ptAtom++;
atomH.setBonds ( new Array (1));
var b = new JS.SmilesBond (atom, atomH, 1, false);
JU.Logger.info ("" + b);
}
}
for (var i = 0; i < this.ac; i++) {
var sAtom = this.patternAtoms[i];
var i1 = sAtom.getMatchingAtom ();
var atom1 = atoms[i1];
var n = sAtom.getBondCount ();
for (var j = 0; j < n; j++) {
var sBond = sAtom.getBond (j);
var firstAtom = (sBond.atom1 === sAtom);
if (firstAtom) {
var order = 1;
switch (sBond.order) {
case 769:
order = 33;
break;
case 1025:
order = 97;
break;
case 257:
order = 1025;
break;
case 513:
order = 1041;
break;
case 112:
case 96:
order = sBond.order;
break;
case 1:
order = 1;
break;
case 17:
order = 514;
break;
case 2:
order = 2;
break;
case 3:
order = 3;
break;
}
var atom2 = atoms[sBond.atom2.getMatchingAtom ()];
var b = new JS.SmilesBond (atom1, atom2, order, false);
atom2.bondCount--;
JU.Logger.info ("" + b);
} else {
var atom2 = atoms[sBond.atom1.getMatchingAtom ()];
var b = atom2.getBondTo (atom1);
atom1.addBond (b);
}}
}
for (var i = bsFixH.nextSetBit (0); i >= 0; i = bsFixH.nextSetBit (i + 1)) {
var bonds = atoms[i].getEdges ();
var b = bonds[0];
bonds[0] = bonds[1];
bonds[1] = b;
}
}, "JU.BS");
Clazz.defineMethod (c$, "setTop",
function (parent) {
if (parent == null) this.top = this;
else this.top = parent.getTop ();
}, "JS.SmilesSearch");
Clazz.defineMethod (c$, "getTop",
function () {
return (this.top === this ? this : this.top.getTop ());
});
Clazz.defineMethod (c$, "getSelections",
function () {
var ht = this.top.htNested;
if (ht == null || this.jmolAtoms.length == 0) return;
var htNew = new java.util.Hashtable ();
for (var entry, $entry = ht.entrySet ().iterator (); $entry.hasNext () && ((entry = $entry.next ()) || true);) {
var key = entry.getValue ().toString ();
if (key.startsWith ("select")) {
var bs = (htNew.containsKey (key) ? htNew.get (key) : this.smartsAtoms[0].findAtomsLike (key.substring (6)));
if (bs == null) bs = new JU.BS ();
htNew.put (key, bs);
entry.setValue (bs);
}}
});
Clazz.defineStatics (c$,
"INITIAL_ATOMS", 16);
});
|
'use strict'
const fs = require('../fs')
const path = require('path')
const util = require('util')
function getStats (src, dest, opts) {
const statFunc = opts.dereference
? (file) => fs.stat(file, { bigint: true })
: (file) => fs.lstat(file, { bigint: true })
return Promise.all([
statFunc(src),
statFunc(dest).catch(err => {
if (err.code === 'ENOENT') return null
throw err
})
]).then(([srcStat, destStat]) => ({ srcStat, destStat }))
}
function getStatsSync (src, dest, opts) {
let destStat
const statFunc = opts.dereference
? (file) => fs.statSync(file, { bigint: true })
: (file) => fs.lstatSync(file, { bigint: true })
const srcStat = statFunc(src)
try {
destStat = statFunc(dest)
} catch (err) {
if (err.code === 'ENOENT') return { srcStat, destStat: null }
throw err
}
return { srcStat, destStat }
}
function checkPaths (src, dest, funcName, opts, cb) {
util.callbackify(getStats)(src, dest, opts, (err, stats) => {
if (err) return cb(err)
const { srcStat, destStat } = stats
if (destStat) {
if (areIdentical(srcStat, destStat)) {
const srcBaseName = path.basename(src)
const destBaseName = path.basename(dest)
if (funcName === 'move' &&
srcBaseName !== destBaseName &&
srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
return cb(null, { srcStat, destStat, isChangingCase: true })
}
return cb(new Error('Source and destination must not be the same.'))
}
if (srcStat.isDirectory() && !destStat.isDirectory()) {
return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`))
}
if (!srcStat.isDirectory() && destStat.isDirectory()) {
return cb(new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`))
}
}
if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
return cb(new Error(errMsg(src, dest, funcName)))
}
return cb(null, { srcStat, destStat })
})
}
function checkPathsSync (src, dest, funcName, opts) {
const { srcStat, destStat } = getStatsSync(src, dest, opts)
if (destStat) {
if (areIdentical(srcStat, destStat)) {
const srcBaseName = path.basename(src)
const destBaseName = path.basename(dest)
if (funcName === 'move' &&
srcBaseName !== destBaseName &&
srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
return { srcStat, destStat, isChangingCase: true }
}
throw new Error('Source and destination must not be the same.')
}
if (srcStat.isDirectory() && !destStat.isDirectory()) {
throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
}
if (!srcStat.isDirectory() && destStat.isDirectory()) {
throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)
}
}
if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
throw new Error(errMsg(src, dest, funcName))
}
return { srcStat, destStat }
}
// recursively check if dest parent is a subdirectory of src.
// It works for all file types including symlinks since it
// checks the src and dest inodes. It starts from the deepest
// parent and stops once it reaches the src parent or the root path.
function checkParentPaths (src, srcStat, dest, funcName, cb) {
const srcParent = path.resolve(path.dirname(src))
const destParent = path.resolve(path.dirname(dest))
if (destParent === srcParent || destParent === path.parse(destParent).root) return cb()
fs.stat(destParent, { bigint: true }, (err, destStat) => {
if (err) {
if (err.code === 'ENOENT') return cb()
return cb(err)
}
if (areIdentical(srcStat, destStat)) {
return cb(new Error(errMsg(src, dest, funcName)))
}
return checkParentPaths(src, srcStat, destParent, funcName, cb)
})
}
function checkParentPathsSync (src, srcStat, dest, funcName) {
const srcParent = path.resolve(path.dirname(src))
const destParent = path.resolve(path.dirname(dest))
if (destParent === srcParent || destParent === path.parse(destParent).root) return
let destStat
try {
destStat = fs.statSync(destParent, { bigint: true })
} catch (err) {
if (err.code === 'ENOENT') return
throw err
}
if (areIdentical(srcStat, destStat)) {
throw new Error(errMsg(src, dest, funcName))
}
return checkParentPathsSync(src, srcStat, destParent, funcName)
}
function areIdentical (srcStat, destStat) {
return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev
}
// return true if dest is a subdir of src, otherwise false.
// It only checks the path strings.
function isSrcSubdir (src, dest) {
const srcArr = path.resolve(src).split(path.sep).filter(i => i)
const destArr = path.resolve(dest).split(path.sep).filter(i => i)
return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true)
}
function errMsg (src, dest, funcName) {
return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`
}
module.exports = {
checkPaths,
checkPathsSync,
checkParentPaths,
checkParentPathsSync,
isSrcSubdir,
areIdentical
}
|
import { T as Transport } from './transport-ce07b771.js';
import { S as Sync } from './util-89055384.js';
import { M as Master } from './master-04a42192.js';
import { g as getFilterPlayerView } from './filter-player-view-43ed49b0.js';
import ioNamespace__default from 'socket.io-client';
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* InMemory data storage.
*/
class InMemory extends Sync {
/**
* Creates a new InMemory storage.
*/
constructor() {
super();
this.state = new Map();
this.initial = new Map();
this.metadata = new Map();
this.log = new Map();
}
/**
* Create a new match.
*
* @override
*/
createMatch(matchID, opts) {
this.initial.set(matchID, opts.initialState);
this.setState(matchID, opts.initialState);
this.setMetadata(matchID, opts.metadata);
}
/**
* Write the match metadata to the in-memory object.
*/
setMetadata(matchID, metadata) {
this.metadata.set(matchID, metadata);
}
/**
* Write the match state to the in-memory object.
*/
setState(matchID, state, deltalog) {
if (deltalog && deltalog.length > 0) {
const log = this.log.get(matchID) || [];
this.log.set(matchID, [...log, ...deltalog]);
}
this.state.set(matchID, state);
}
/**
* Fetches state for a particular matchID.
*/
fetch(matchID, opts) {
const result = {};
if (opts.state) {
result.state = this.state.get(matchID);
}
if (opts.metadata) {
result.metadata = this.metadata.get(matchID);
}
if (opts.log) {
result.log = this.log.get(matchID) || [];
}
if (opts.initialState) {
result.initialState = this.initial.get(matchID);
}
return result;
}
/**
* Remove the match state from the in-memory object.
*/
wipe(matchID) {
this.state.delete(matchID);
this.metadata.delete(matchID);
}
/**
* Return all keys.
*
* @override
*/
listMatches(opts) {
return [...this.metadata.entries()]
.filter(([, metadata]) => {
if (!opts) {
return true;
}
if (opts.gameName !== undefined &&
metadata.gameName !== opts.gameName) {
return false;
}
if (opts.where !== undefined) {
if (opts.where.isGameover !== undefined) {
const isGameover = metadata.gameover !== undefined;
if (isGameover !== opts.where.isGameover) {
return false;
}
}
if (opts.where.updatedBefore !== undefined &&
metadata.updatedAt >= opts.where.updatedBefore) {
return false;
}
if (opts.where.updatedAfter !== undefined &&
metadata.updatedAt <= opts.where.updatedAfter) {
return false;
}
}
return true;
})
.map(([key]) => key);
}
}
class WithLocalStorageMap extends Map {
constructor(key) {
super();
this.key = key;
const cache = JSON.parse(localStorage.getItem(this.key)) || [];
cache.forEach((entry) => this.set(...entry));
}
sync() {
const entries = [...this.entries()];
localStorage.setItem(this.key, JSON.stringify(entries));
}
set(key, value) {
super.set(key, value);
this.sync();
return this;
}
delete(key) {
const result = super.delete(key);
this.sync();
return result;
}
}
/**
* locaStorage data storage.
*/
class LocalStorage extends InMemory {
constructor(storagePrefix = 'bgio') {
super();
const StorageMap = (stateKey) => new WithLocalStorageMap(`${storagePrefix}_${stateKey}`);
this.state = StorageMap('state');
this.initial = StorageMap('initial');
this.metadata = StorageMap('metadata');
this.log = StorageMap('log');
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Returns null if it is not a bot's turn.
* Otherwise, returns a playerID of a bot that may play now.
*/
function GetBotPlayer(state, bots) {
if (state.ctx.gameover !== undefined) {
return null;
}
if (state.ctx.activePlayers) {
for (const key of Object.keys(bots)) {
if (key in state.ctx.activePlayers) {
return key;
}
}
}
else if (state.ctx.currentPlayer in bots) {
return state.ctx.currentPlayer;
}
return null;
}
/**
* Creates a local version of the master that the client
* can interact with.
*/
class LocalMaster extends Master {
constructor({ game, bots, storageKey, persist }) {
const clientCallbacks = {};
const initializedBots = {};
if (game && game.ai && bots) {
for (const playerID in bots) {
const bot = bots[playerID];
initializedBots[playerID] = new bot({
game,
enumerate: game.ai.enumerate,
seed: game.seed,
});
}
}
const send = ({ playerID, ...data }) => {
const callback = clientCallbacks[playerID];
if (callback !== undefined) {
callback(filterPlayerView(playerID, data));
}
};
const filterPlayerView = getFilterPlayerView(game);
const transportAPI = {
send,
sendAll: (payload) => {
for (const playerID in clientCallbacks) {
send({ playerID, ...payload });
}
},
};
const storage = persist ? new LocalStorage(storageKey) : new InMemory();
super(game, storage, transportAPI);
this.connect = (playerID, callback) => {
clientCallbacks[playerID] = callback;
};
this.subscribe(({ state, matchID }) => {
if (!bots) {
return;
}
const botPlayer = GetBotPlayer(state, initializedBots);
if (botPlayer !== null) {
setTimeout(async () => {
const botAction = await initializedBots[botPlayer].play(state, botPlayer);
await this.onUpdate(botAction.action, state._stateID, matchID, botAction.action.payload.playerID);
}, 100);
}
});
}
}
/**
* Local
*
* Transport interface that embeds a GameMaster within it
* that you can connect multiple clients to.
*/
class LocalTransport extends Transport {
/**
* Creates a new Mutiplayer instance.
* @param {string} matchID - The game ID to connect to.
* @param {string} playerID - The player ID associated with this client.
* @param {string} gameName - The game type (the `name` field in `Game`).
* @param {string} numPlayers - The number of players.
*/
constructor({ master, ...opts }) {
super(opts);
this.master = master;
}
sendChatMessage(matchID, chatMessage) {
const args = [
matchID,
chatMessage,
this.credentials,
];
this.master.onChatMessage(...args);
}
sendAction(state, action) {
this.master.onUpdate(action, state._stateID, this.matchID, this.playerID);
}
requestSync() {
this.master.onSync(this.matchID, this.playerID, this.credentials, this.numPlayers);
}
connect() {
this.setConnectionStatus(true);
this.master.connect(this.playerID, (data) => this.notifyClient(data));
this.requestSync();
}
disconnect() {
this.setConnectionStatus(false);
}
updateMatchID(id) {
this.matchID = id;
this.connect();
}
updatePlayerID(id) {
this.playerID = id;
this.connect();
}
updateCredentials(credentials) {
this.credentials = credentials;
this.connect();
}
}
/**
* Global map storing local master instances.
*/
const localMasters = new Map();
/**
* Create a local transport.
*/
function Local({ bots, persist, storageKey } = {}) {
return (transportOpts) => {
const { gameKey, game } = transportOpts;
let master;
const instance = localMasters.get(gameKey);
if (instance &&
instance.bots === bots &&
instance.storageKey === storageKey &&
instance.persist === persist) {
master = instance.master;
}
if (!master) {
master = new LocalMaster({ game, bots, persist, storageKey });
localMasters.set(gameKey, { master, bots, persist, storageKey });
}
return new LocalTransport({ master, ...transportOpts });
};
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const io = ioNamespace__default;
/**
* SocketIO
*
* Transport interface that interacts with the Master via socket.io.
*/
class SocketIOTransport extends Transport {
/**
* Creates a new Multiplayer instance.
* @param {object} socket - Override for unit tests.
* @param {object} socketOpts - Options to pass to socket.io.
* @param {object} store - Redux store
* @param {string} matchID - The game ID to connect to.
* @param {string} playerID - The player ID associated with this client.
* @param {string} credentials - Authentication credentials
* @param {string} gameName - The game type (the `name` field in `Game`).
* @param {string} numPlayers - The number of players.
* @param {string} server - The game server in the form of 'hostname:port'. Defaults to the server serving the client if not provided.
*/
constructor({ socket, socketOpts, server, ...opts }) {
super(opts);
this.server = server;
this.socket = socket;
this.socketOpts = socketOpts;
}
sendAction(state, action) {
const args = [
action,
state._stateID,
this.matchID,
this.playerID,
];
this.socket.emit('update', ...args);
}
sendChatMessage(matchID, chatMessage) {
const args = [
matchID,
chatMessage,
this.credentials,
];
this.socket.emit('chat', ...args);
}
connect() {
if (!this.socket) {
if (this.server) {
let server = this.server;
if (server.search(/^https?:\/\//) == -1) {
server = 'http://' + this.server;
}
if (server.slice(-1) != '/') {
// add trailing slash if not already present
server = server + '/';
}
this.socket = io(server + this.gameName, this.socketOpts);
}
else {
this.socket = io('/' + this.gameName, this.socketOpts);
}
}
// Called when another player makes a move and the
// master broadcasts the update as a patch to other clients (including
// this one).
this.socket.on('patch', (matchID, prevStateID, stateID, patch, deltalog) => {
this.notifyClient({
type: 'patch',
args: [matchID, prevStateID, stateID, patch, deltalog],
});
});
// Called when another player makes a move and the
// master broadcasts the update to other clients (including
// this one).
this.socket.on('update', (matchID, state, deltalog) => {
this.notifyClient({
type: 'update',
args: [matchID, state, deltalog],
});
});
// Called when the client first connects to the master
// and requests the current game state.
this.socket.on('sync', (matchID, syncInfo) => {
this.notifyClient({ type: 'sync', args: [matchID, syncInfo] });
});
// Called when new player joins the match or changes
// it's connection status
this.socket.on('matchData', (matchID, matchData) => {
this.notifyClient({ type: 'matchData', args: [matchID, matchData] });
});
this.socket.on('chat', (matchID, chatMessage) => {
this.notifyClient({ type: 'chat', args: [matchID, chatMessage] });
});
// Keep track of connection status.
this.socket.on('connect', () => {
// Initial sync to get game state.
this.requestSync();
this.setConnectionStatus(true);
});
this.socket.on('disconnect', () => {
this.setConnectionStatus(false);
});
}
disconnect() {
this.socket.close();
this.socket = null;
this.setConnectionStatus(false);
}
requestSync() {
if (this.socket) {
const args = [
this.matchID,
this.playerID,
this.credentials,
this.numPlayers,
];
this.socket.emit('sync', ...args);
}
}
updateMatchID(id) {
this.matchID = id;
this.requestSync();
}
updatePlayerID(id) {
this.playerID = id;
this.requestSync();
}
updateCredentials(credentials) {
this.credentials = credentials;
this.requestSync();
}
}
function SocketIO({ server, socketOpts } = {}) {
return (transportOpts) => new SocketIOTransport({
server,
socketOpts,
...transportOpts,
});
}
export { Local as L, SocketIO as S };
|
var optimizeConfig = {
constantConstraintFactor: 100,
repulsionPower1: -8,
repulsionFactor: 50000,
repulsionThreshold: 5,
repulsionPower2: 2
};
var makeSegment = function(params) {
var groupIdx = params.groupIdx;
var tileIdx = params.tileIdx;
var patternIdx = params.patternIdx;
params.polygonID = polylist[groupIdx].tiles[tileIdx].polygonID;
params.customIdx = polylist[groupIdx].tiles[tileIdx].patterns[patternIdx].customIndex;
var v1 = params.vertexRange[0];
var v2 = params.vertexRange[1];
var fix = params.fix;
var segmentNode = params.this;
var getElement = function() {
var group = polylist[groupIdx];
var tile = group.tiles[tileIdx];
var modelTile = _.find(assembleSVGDrawer.get(), function(t) {
return t.polygonID === tile.polygonID;
});
var pattern = modelTile.patterns[patternIdx];
var isStraightSegment = (_.all(_.slice(pattern.intersectedVertices, v1 + 1, v2), function(v) {
return v.intersect;
}));
var isBounded = (v1 >= 0) && (v2 < pattern.intersectedVertices.length);
if (!isBounded) {
throw new Error("Vertex indices are invalid.");
} else if (!isStraightSegment) {
throw new Error("Segments must be straight lines.");
} else {
return {group: group, tile: tile, pattern: pattern};
}
};
// get pattern segment pointed to and retrieve global coords
var getCoords = function() {
var element = getElement();
var patternCoords = [element.pattern.intersectedVertices[v1].coords,
element.pattern.intersectedVertices[v2].coords];
return num.matrixToCoords(num.dot(element.group.transform, num.dot(element.tile.transform,
num.coordsToMatrix(patternCoords))));
};
var getRawNeighboringHandlePoints = function() {
var element = getElement();
var previousHandleIndexInIntersectedVertices = _.findLastIndex(
element.pattern.intersectedVertices, function(v,i) {
return i <= v1 && (!v.intersect || i === 0);
});
var nextHandleIndexInIntersectedVertices = _.findIndex(
element.pattern.intersectedVertices, function(v, i) {
return i >= v2 && (!v.intersect || i === element.pattern.intersectedVertices.length - 1);
});
return [previousHandleIndexInIntersectedVertices, nextHandleIndexInIntersectedVertices];
};
// compute pattern handles once
// clicking on them in the GUI mutates the "fix" parameter
// which gets passed to "getInterface"
var patternHandles = (function() {
var element = getElement();
var patternType = patternOptions[element.tile.patternParams.index].name;
var handles;
if (patternType === "Custom") {
console.assert(typeof element.pattern.customIndex !== "undefined", "Custom index does not exist.");
var ct = element.tile.customTemplate[element.pattern.customIndex];
var neighboringHandlePoints = getRawNeighboringHandlePoints();
var numOfHandlesUpTo = _.filter(element.pattern.intersectedVertices, function(v , i) {
return i < neighboringHandlePoints[0] && (!v.intersect || i === 0);
}).length;
handles = [{
polygonID: params.polygonID,
isCustom: true,
intersectingIdx: neighboringHandlePoints[0],
fix: true,
customIdx: params.customIdx,
customTemplateIdx: numOfHandlesUpTo - 1
}, {
polygonID: params.polygonID,
isCustom: true,
intersectingIdx: neighboringHandlePoints[1],
fix: true,
customIdx: params.customIdx,
customTemplateIdx: numOfHandlesUpTo
}];
var numHandles = ct.points.length;
if (ct.symmetrySpec === "mirrorNoCrop") {
if (numOfHandlesUpTo === numHandles) {
handles[1].customTemplateIdx = numOfHandlesUpTo - 1;
} else if (numOfHandlesUpTo > numHandles) {
handles[0].customTemplateIdx = numHandles * 2 - numOfHandlesUpTo;
handles[1].customTemplateIdx = numHandles * 2 - 1 - numOfHandlesUpTo;
}
} else if (ct.symmetrySpec === "mirrorCrop") {
if (numOfHandlesUpTo > numHandles - 1) {
handles[0].customTemplateIdx = numHandles * 2 - 1 - numOfHandlesUpTo;
handles[1].customTemplateIdx = numHandles * 2 - 2 - numOfHandlesUpTo;
}
}
handles = _.filter(handles, function(h) {
return h.customTemplateIdx >= 0 && h.customTemplateIdx < numHandles;
});
} else if (["Star", "Rosette", "Extended Rosette", "Hankin"].indexOf(patternType) > -1) {
var firstHandleIdx = _.findIndex(
element.pattern.intersectedVertices, function(v,i) {
return (!v.intersect && i > 0);
});
var lastHandleIndex = _.findLastIndex(
element.pattern.intersectedVertices, function(v, i) {
return (!v.intersect && i < element.pattern.intersectedVertices.length - 1);
});
var intersectingIdx = ((v1 + v2) / 2 - (firstHandleIdx + lastHandleIndex) / 2 < 0) ?
firstHandleIdx : lastHandleIndex;
handles = [{
polygonID: params.polygonID,
isCustom: false,
intersectingIdx: intersectingIdx,
fix: true
}];
} else {
throw new Error("Optimization is unsupported for this pattern type.");
}
var tileTransform = num.dot(element.group.transform, element.tile.transform);
_.each(handles, function(h) {
h.coords = num.matrixToCoords(num.dot(tileTransform,
num.coordsToMatrix([element.pattern.intersectedVertices[h.intersectingIdx].coords])))[0];
});
return handles;
})();
var getInterface = function() {
return _.filter(patternHandles, function(ph) {
return !ph.fix;
});
};
var setFixity = function(fixity) {
fix = fixity;
};
return {
originalParams: params,
patternHandles: patternHandles,
getElement: getElement,
getCoords: getCoords,
getInterface: getInterface,
getNode: segmentNode,
setFixity: setFixity
};
};
var patternHandleComparator = function(d1, d2) {
return (d1.polygonID === d2.polygonID &&
((!d1.isCustom && !d2.isCustom) ||
(d1.customIdx === d2.customIdx && d1.customTemplateIdx === d2.customTemplateIdx)));
};
var constraintUtils = {
getAcuteAngleFromVectors: function(vectors) {
var v1 = vectors[0];
var v2 = vectors[1];
var cosOfAngle = num.dot(v1,v2) / (num.norm2(v1) * num.norm2(v2));
return Math.acos(Math.abs(cosOfAngle)) * 180 / Math.PI;
},
getAcuteAngleBetween: function(segments) {
return this.getAcuteAngleFromVectors(_.map(segments, function(s) {
return num.vectorFromEnds(s.getCoords());
}));
},
getAngleOf: function(seg) {
return this.getAcuteAngleFromVectors([num.vectorFromEnds(seg.getCoords()), [1, 0]]);
},
getLengthOf: function(seg) {
return num.norm2(num.vectorFromEnds(seg.getCoords()));
}
};
var enforceConstructor = function(options) {
return {
numSegments: options.numSegments,
instructionText: options.instructionText,
constantConstraint: options.constantConstraint,
constructor: function(segments) {
if (segments.length !== options.numSegments) {
throw new Error("Number of segments must be exactly " + options.numSegments);
}
var evaluateFn = options.constructor(segments);
return {
evaluate: evaluateFn,
segments: segments,
displayName: options.displayName,
evaluateUnit: options.evaluateUnit,
factor: options.factor || 1,
evaluateCache: [],
cached: false,
withInput: options.withInput
};
}
};
};
var enforceParallel = enforceConstructor({
constructor: function(segments) {
return function() {
return constraintUtils.getAcuteAngleBetween(segments);
};
},
displayName: "Parallel",
numSegments: 2,
instructionText: "Select two segments to make parallel.",
constantConstraint: false,
evaluateUnit: "ยฐ"
});
var enforcePerpendicular = enforceConstructor({
constructor: function(segments) {
return function() {
return Math.abs(constraintUtils.getAcuteAngleBetween(segments) - 90);
};
},
displayName: "Perpendicular",
numSegments: 2,
instructionText: "Select two segments to make perpendicular.",
constantConstraint: false,
evaluateUnit: "ยฐ"
});
var enforceCollinear = enforceConstructor({
constructor: function(segments) {
var distToSegment = function(p, comparisonLine) {
var v = comparisonLine[0];
var w = comparisonLine[1];
var l2 = num.norm2(num.vectorFromEnds([v, w]));
if (l2 === 0) {
return num.norm2(num.vectorFromEnds([p, v]));
}
var t = ((p[0] - v[0]) * (w[0] - v[0]) + (p[1] - v[1]) * (w[1] - v[1])) / (l2 * l2);
return num.norm2(num.vectorFromEnds([p, [v[0] + t * (w[0] - v[0]),
v[1] + t * (w[1] - v[1])]]));
};
return function() {
var seg1 = segments[0];
var seg2 = segments[1];
var seg1Coords = seg1.getCoords();
var seg2Coords = seg2.getCoords();
var comparisonLine;
if (seg1.getInterface().length === 0) {
var comparisonLine = seg1Coords;
} else if (seg2.getInterface().length === 0) {
var comparisonLine = seg2Coords;
} else {
var seg1Midpt = [(seg1Coords[0][0] + seg1Coords[1][0])/2,
(seg1Coords[0][1] + seg1Coords[1][1])/2];
var seg2Midpt = [(seg2Coords[0][0] + seg2Coords[1][0])/2,
(seg2Coords[0][1] + seg2Coords[1][1])/2];
comparisonLine = [seg1Midpt, seg2Midpt];
}
return _.sum(_.map(seg1Coords.concat(seg2Coords), function(c) {
return distToSegment(c, comparisonLine);
}));
// comment out old implementation for now
// var v1 = num.vectorFromEnds(seg1Coords);
// var v2 = num.vectorFromEnds(seg2Coords);
// var v3 = num.vectorFromEnds([seg1Coords[0], seg2Coords[0]]);
// var v4 = num.vectorFromEnds([seg1Coords[0], seg2Coords[1]]);
// var v5 = num.vectorFromEnds([seg1Coords[1], seg2Coords[0]]);
// var v6 = num.vectorFromEnds([seg1Coords[1], seg2Coords[1]]);
// var n1 = num.norm2(v1);
// var n2 = num.norm2(v2);
// var n3 = num.norm2(v3);
// var n4 = num.norm2(v4);
// var n5 = num.norm2(v5);
// var n6 = num.norm2(v6);
// var pairs;
// if (seg1.getInterface().length === 0) {
// pairs = [[v1,v3,n1,n3], [v1,v4,n1,n4], [v1,v5,n1,n5], [v1,v6,n1,n6]];
// } else if (seg2.getInterface().length === 0) {
// pairs = [[v2,v3,n2,n3], [v2,v4,n2,n4], [v2,v5,n2,n5], [v2,v6,n2,n6]];
// } else {
// pairs = [[v1,v3,n1,n3], [v1,v4,n1,n4], [v1,v5,n1,n5], [v1,v6,n1,n6],
// [v2,v3,n2,n3], [v2,v4,n2,n4], [v2,v5,n2,n5], [v2,v6,n2,n6]];
// }
// var angles = _.map(pairs, function(params) {
// var cosOfAngle = num.dot(params[0], params[1]) / (params[2] * params[3]);
// return Math.acos(Math.abs(cosOfAngle)) * 180 / Math.PI;
// });
// return _.sum(angles) / pairs.length;
};
},
displayName: "Collinear",
numSegments: 2,
instructionText: "Select two segments to make collinear.",
constantConstraint: false,
evaluateUnit: "px"
});
var enforceEqualLength = enforceConstructor({
constructor: function(segments) {
return function() {
return Math.abs(constraintUtils.getLengthOf(segments[0]) -
constraintUtils.getLengthOf(segments[1]));
};
},
displayName: "Equal length",
numSegments: 2,
instructionText: "Select two segments to make equal length.",
constantConstraint: false,
evaluateUnit: "px"
});
var enforceBisection = enforceConstructor({
constructor: function(segments) {
return function() {
var aCoords = segments[0].getCoords();
var bCoords = segments[1].getCoords();
var a1 = {x: aCoords[0][0], y: aCoords[0][1]};
var a2 = {x: aCoords[1][0], y: aCoords[1][1]};
var b1 = {x: bCoords[0][0], y: bCoords[0][1]};
var b2 = {x: bCoords[1][0], y: bCoords[1][1]};
var intersect = Intersection.intersectLineLine(a1, a2, b1, b2);
if (intersect.status === "No Intersection") {
return Math.pow(10, 10);
}
return Math.abs(intersect.points[0].relative - 0.5) * constraintUtils.getLengthOf(segments[0]) +
Math.abs(intersect.points[0].relative2 - 0.5) * constraintUtils.getLengthOf(segments[1]);
};
},
displayName: "Bisect",
numSegments: 2,
instructionText: "Select two segments to bisect.",
constantConstraint: false,
evaluateUnit: "px"
});
var enforceConstantGradient = enforceConstructor({
constructor: function(segments) {
var seg = segments[0];
var originalAngle = constraintUtils.getAngleOf(seg);
return function() {
return Math.abs(originalAngle - constraintUtils.getAngleOf(seg)) * 10;
};
},
displayName: "Const Gradient",
numSegments: 1,
instructionText: "Select a segment whose gradient to hold constant.",
constantConstraint: true,
evaluateUnit: "ยฐ",
factor: 10
});
var enforceConstantLength = enforceConstructor({
constructor: function(segments) {
var seg = segments[0];
var originalLength = constraintUtils.getLengthOf(seg);
return function() {
return Math.abs(originalLength - constraintUtils.getLengthOf(seg));
};
},
displayName: "Const Length",
numSegments: 1,
instructionText: "Select a segment whose length to hold constant.",
constantConstraint: true,
evaluateUnit: "px"
});
var enforceConstantAngle = enforceConstructor({
constructor: function(segments) {
var originalAngle = constraintUtils.getAcuteAngleBetween(segments);
return function() {
return Math.abs(originalAngle - constraintUtils.getAcuteAngleBetween(segments));
};
},
displayName: "Const Angle",
numSegments: 2,
instructionText: "Select two segments to hold meeting angle constant.",
constantConstraint: true,
evaluateUnit: "ยฐ",
factor: 10
});
var enforceSpecificAngle = enforceConstructor({
constructor: function(segments) {
return function() {
var angle = constraintUtils.getAcuteAngleBetween(segments);
var inputValue = this.withInput.paramValue;
return Math.abs(angle - inputValue);
};
},
displayName: "Angle of ",
numSegments: 2,
instructionText: "Select two segments to meet at a particular angle.",
withInput: {
markup: "<input autocomplete='off' type='text' class='constraintParam'></input> ยฐ",
paramValue: 0
},
evaluateUnit: "ยฐ"
});
var enforceSpecificGradient = enforceConstructor({
constructor: function(segments) {
return function() {
var angle = constraintUtils.getAngleOf(segments[0]);
var inputValue = this.withInput.paramValue;
return Math.abs(angle - inputValue);
};
},
displayName: "Gradient of ",
numSegments: 1,
instructionText: "Select a segment which is to be a specific gradient.",
withInput: {
markup: "<input autocomplete='off' type='text' class='constraintParam'></input> ยฐ",
paramValue: 0
},
evaluateUnit: "ยฐ"
});
var enforceSpecificLength = enforceConstructor({
constructor: function(segments) {
return function() {
var length = constraintUtils.getLengthOf(segments[0]);
var inputValue = this.withInput.paramValue;
return Math.abs(length - inputValue);
};
},
displayName: "Length of ",
numSegments: 1,
instructionText: "Select a segment which is to be a specific length.",
withInput: {
markup: "<input autocomplete='off' type='text' class='constraintParam'></input>px",
paramValue: 50,
},
evaluateUnit: "px"
});
var enforceLengthRatio = enforceConstructor({
constructor: function(segments) {
return function() {
var lengths = _.map(segments, constraintUtils.getLengthOf);
var inputValue = this.withInput.paramValue;
return Math.abs(lengths[0] / lengths[1] - inputValue);
};
},
displayName: "Length ratio of ",
numSegments: 2,
instructionText: "Select two segments whose length ratio are to be constrained.",
withInput: {
markup: "<input autocomplete='off' type='text' class='constraintParam'></input>",
paramValue: 1,
},
evaluateUnit: ""
});
var enforceLengthDifference = enforceConstructor({
constructor: function(segments) {
return function() {
var lengths = _.map(segments, constraintUtils.getLengthOf);
var inputValue = this.withInput.paramValue;
return Math.abs(Math.abs(lengths[0] - lengths[1]) - inputValue);
};
},
displayName: "Length diff of ",
numSegments: 2,
instructionText: "Select two segments whose length difference are to be constrained.",
withInput: {
markup: "<input autocomplete='off' type='text' class='constraintParam'></input>px",
paramValue: 0,
},
evaluateUnit: "px"
});
var createObjectives = function(objectives) {
var evaluate = function() {
var evaluatedValues = _.map(objectives, function(f) { return f.evaluate() * f.factor; });
return _.reduce(evaluatedValues,function(a,b) { return a + b; });
};
var getInterface = function() {
var segments = _.flatten(_.map(objectives, function(o) { return o.segments; }));
var interfaces = _.flatten(_.map(segments, function(s) { return s.getInterface(); }));
// basic _.uniq function with custom comparator
var reduced = _.reduce(interfaces, function(acc, i) {
var findFn = function(i2) {
return patternHandleComparator(i, i2);
};
if (_.find(acc, findFn)) {
return acc;
} else {
return acc.concat(i);
}
}, []);
return reduced;
};
var optimize = function() {
var customInterface = this.getInterface();
var initialVector = _.flatten(_.map(customInterface, function(i) {
var tile = _.find(assembleSVGDrawer.get(), function(t) {
return t.polygonID === i.polygonID;
});
if (i.isCustom) {
return num.getTranslation(
tile.customTemplate[i.customIdx].points[i.customTemplateIdx].transform);
} else {
return tile.patternParams.param1;
}
}));
var numIterations = 0;
var fnc = function(vector) {
var f = updateCustomTemplates(vector, customInterface, evaluate);
return f;
};
var dfnc = function(precision) {
return function(vector) {
var n = vector.length;
var dfvec = _.map(_.range(n), function(i) {
var diff = [];
_.each(_.range(n), function(j) {
if (i === j) {
diff.push(precision);
} else {
diff.push(0);
}
});
var v1 = num.vecSum(vector, diff);
var v2 = num.vecSub(vector, diff);
var fv1 = fnc(v1);
var fv2 = fnc(v2);
var df = (fnc(v1) - fnc(v2)) / (2 * precision);
return df;
});
return dfvec;
};
};
var optimizer = this;
return new Promise(function(resolve, reject) {
console.time("powell");
powell(initialVector, fnc, 0.001, function(result) {
console.timeEnd("powell");
redrawTiles();
invalidateStripCache();
_.each(objectives, function(o) {
o.cached = false;
});
optimizer.draw();
redrawConstraintList();
resolve(result);
});
});
};
var draw = function() {
d3.selectAll(".pattern-segment-fixed")
.attr("d", function(d) {
var group = polylist[d.groupIdx];
var tile = group.tiles[d.tileIdx];
var pattern = tile.patterns[d.patternIdx];
var intersectedVertices = pattern.intersectedVertices;
var patternCoords = _.pluck(intersectedVertices.slice(d.vertexRange[0], d.vertexRange[1] + 1), "coords");
var globalCoords = num.matrixToCoords(num.dot(group.transform,
num.dot(tile.transform, num.coordsToMatrix(patternCoords))));
d.globalCoords = globalCoords;
return d3.svg.line()(globalCoords);
});
updateFixedPatternSegmentHandlePositions(d3.selectAll(".pattern-segment-fixable-point"));
};
return {
evaluate: evaluate,
getInterface: getInterface,
optimize: optimize,
draw: draw
};
};
var redrawTiles = function() {
assembleSVGDrawer.draw();
var tilesInCanvas = assembleCanvas.selectAll("g.tile");
tilesInCanvas.each(function(d, i) {
var modelTile = _.find(assembleSVGDrawer.get(), function(t) {
return t.polygonID === d.polygonID;
});
if (modelTile.patternParams) {
// if model tile has a pattern, redraw patterns in d
d3.select(this).selectAll("path.pattern").remove();
d.customTemplate = _.cloneDeep(modelTile.customTemplate);
d.patternParams = _.cloneDeep(modelTile.patternParams);
var patternFn = patternOptions[d.patternParams.index].generator(d, d.patternParams.param1, d.patternParams.param2);
polygonAddPattern(d, makePatterns(patternFn));
polygonAddPatternMetadata(d);
drawPatterns(d3.select(this), {});
}
});
};
var updateCustomTemplates = function(vector, customInterface, evaluator) {
var vectorCopy = vector.slice();
var tiles = _.indexBy(_.uniq(_.map(customInterface, function(ci) {
return _.find(assembleSVGDrawer.get(), function(t) {
return t.polygonID === ci.polygonID;
});
})), "polygonID");
var intersectedVertexInterfaces = _.indexBy(_.map(tiles, function(t) {
return {
polygonID: t.polygonID,
vertexInterface: _.map(t.patterns, function(p) {
return _.pluck(p.intersectedVertices, "intersect");
})
};
}), "polygonID");
_.each(customInterface, function(ci) {
if (ci.isCustom) {
tiles[ci.polygonID].customTemplate[ci.customIdx]
.points[ci.customTemplateIdx] = {
transform: num.translate.apply(null, vectorCopy.splice(0, 2))
};
} else {
tiles[ci.polygonID].patternParams.param1 = vectorCopy.splice(0, 1)[0];
}
});
_.each(tiles, function(tile) {
var patternFn = makePatterns(patternOptions[tile.patternParams.index]
.generator(tile, tile.patternParams.param1, tile.patternParams.param2));
polygonAddPattern(tile, patternFn);
polygonAddPatternMetadata(tile);
});
if (_.all(tiles, function(tile) {
if (_.all(tile.patterns, function(p, idx) {
var newIntersectData = _.pluck(p.intersectedVertices, "intersect");
var intersectDataPreserved = _.isEqual(newIntersectData,
intersectedVertexInterfaces[tile.polygonID].vertexInterface[idx]);
return intersectDataPreserved;
})) {
assembleSVGDrawer.replace(tile);
return true;
} else {
return false;
}
})) {
var value = evaluator() + _.sum(_.map(tiles, getRepulsionForce));
return value;
} else {
// went out of bounds
return Math.pow(10,10);
}
};
var getRepulsionForce = function(tile) {
var interiorVertices = _.flatten(_.map(tile.patterns, function(p) {
return _.filter(p.intersectedVertices, function(iv) {
return !iv.intersect;
});
}));
var vertexRepulsion = 0;
for (var i = 0; i < interiorVertices.length; i++) {
for (var j = i + 1; j < interiorVertices.length; j++) {
var displacement = num.norm2(num.vectorFromEnds(
[interiorVertices[i].coords, interiorVertices[j].coords]));
vertexRepulsion += optimizeConfig.repulsionFactor * Math.pow(displacement, optimizeConfig.repulsionPower1);
}
}
var vertexOutOfPolygonForce = 0;
if (tile.customTemplate) {
var inTilePredicate = generateInRegionPredicate(tile.vertices, num.id);
var interiorTemplateVertices = _.flatten(_.map(tile.customTemplate, function(ct) {
return _.map(ct.points, function(p) {
return {
coords: num.getTranslation(p.transform),
occurences: ct.applicableEdges.length
};
});
}));
// assumes that custom template is actually symmetrical
vertexOutOfPolygonForce = _.sum(_.map(interiorTemplateVertices, function(v) {
var distFromEdges = _.map(tile.edges, function(e) {
return num.distFromPtToLineSquared(v.coords, e.ends);
});
var distFromEdge = Math.min.apply(Math, distFromEdges);
var inPoly = inTilePredicate(v.coords);
var f = 0;
if (inPoly && distFromEdge < optimizeConfig.repulsionThreshold) {
// linear from 0 to 1
f = 1 - distFromEdge / optimizeConfig.repulsionThreshold;
} else if (!inPoly) {
// quadratic increase
f = 1 + Math.pow(distFromEdge, optimizeConfig.repulsionPower2);
}
return f * v.occurences;
}));
}
return vertexRepulsion + vertexOutOfPolygonForce;
};
var setupOptimizeOverlay = function() {
assembleOptimizeOverlay.style("visibility", "visible");
assembleOptimizeCanvas.style("visibility", "visible");
optimizeTable.style("display", "block");
var patternSegments = _.flattenDeep(_.map(polylist, function(group, groupIdx) {
return _.map(group.tiles, function(tile, tileIdx) {
return _.map(tile.patterns, function(p, patternIdx) {
var segments = [];
var transformedVertices = _.map(p.intersectedVertices, function(v) {
var coords = num.matrixToCoords(num.dot(group.transform,
num.dot(tile.transform, num.coordsToMatrix([v.coords]))))[0];
return {intersect: v.intersect, coords: coords};
});
var curSegment = {groupIdx: groupIdx, tileIdx: tileIdx, patternIdx: patternIdx, startIdx: 0, vertices: []};
for (var i = 0; i < transformedVertices.length; i++) {
var curVertex = transformedVertices[i];
curSegment.vertices.push(curVertex);
if ((!curVertex.intersect && i !== 0) || i === transformedVertices.length - 1) {
curSegment.endIdx = i;
curSegment.curRange = [
{idx: 0, isActive: false},
{idx: curSegment.vertices.length - 1, isActive: false}];
segments.push(curSegment);
curSegment = {groupIdx: groupIdx, tileIdx: tileIdx, patternIdx: patternIdx, startIdx: i, vertices: [curVertex]};
}
}
return segments;
});
});
}));
assembleOptimizeCanvas.selectAll(".pattern-segment, .pattern-segment-endpoint").remove();
assembleOptimizeCanvas.selectAll(".pattern-segment").data(patternSegments)
.enter()
.append("path")
.each(function(d) { d.this = this; })
.classed("pattern-segment", true)
.attr("d", function(d) {
return d3.svg.line()(_.pluck(d.vertices.slice(d.curRange[0].idx, d.curRange[1].idx + 1), "coords"));
});
};
var teardownOptimizeOverlay = function() {
assembleOptimizeOverlay.style("visibility", "hidden");
assembleOptimizeCanvas.style("visibility", "hidden");
optimizeTable.style("display", "none");
};
var patternSelectHandler = function(list, limit) {
return function(d) {
if (list.indexOf(d) > -1) {
// remove it from the list
list.splice(list.indexOf(d), 1);
d3.select(this).classed("selected", false);
} else {
if (list.length < limit) {
list.push(d);
d3.select(this).classed("selected", true);
}
}
d3.selectAll(".pattern-segment")
.filter(function(d) {
return !d3.select(this).classed("selected");
}).classed("selectable", list.length < limit);
drawPatternSegmentEndpoints(list);
var disableNext = !(list.length === limit || (list.length >= 3 && limit === Infinity));
d3.select("#nextOptimizeBtn")
.classed("disabled", disableNext);
$("#nextOptimizeBtnGroup").tooltip("destroy")
.tooltip({placement: "bottom", title: disableNext ?
"Select the required number of segments first." : ""});
};
};
var updatePatternSegmentEndpointPositions = function(sel) {
return sel
.attr("cx", function(d) {
if (d.isStart) {
return d.seg.vertices[d.seg.curRange[0].idx].coords[0];
} else {
return d.seg.vertices[d.seg.curRange[1].idx].coords[0];
}
})
.attr("cy", function(d) {
if (d.isStart) {
return d.seg.vertices[d.seg.curRange[0].idx].coords[1];
} else {
return d.seg.vertices[d.seg.curRange[1].idx].coords[1];
}
});
};
var updateFixedPatternSegmentHandlePositions = function(sel) {
return sel
.each(function(d) {
var element = d.seg.getElement();
var tileTransform = num.dot(element.group.transform, element.tile.transform);
d.coords = num.matrixToCoords(num.dot(tileTransform,
num.coordsToMatrix([element.pattern.intersectedVertices[d.intersectingIdx].coords])))[0];
})
.attr("cx", function(d) { return d.coords[0]; })
.attr("cy", function(d) { return d.coords[1]; });
};
var patternSegmentDrag = d3.behavior.drag()
.on("drag", function(d, i) {
var distances = _.map(d.seg.vertices, function(v) {
return num.norm2(num.vecSub(v.coords, [d3.event.x, d3.event.y]));
});
var minDistIdx = _.reduce(distances, function(iMin, x, i) {
var curDist = x;
if (d.isStart && i >= d.seg.curRange[1].idx) {
curDist = Infinity;
} else if (!d.isStart && i <= d.seg.curRange[0].idx) {
curDist = Infinity;
}
return curDist < distances[iMin] ? i : iMin;
}, d.point.idx);
if (minDistIdx !== d.point.idx) {
if (d.isStart) {
d.seg.curRange[0].idx = minDistIdx;
} else {
d.seg.curRange[1].idx = minDistIdx;
}
d.point.idx = minDistIdx;
updatePatternSegmentEndpointPositions(d3.select(this));
d3.select(d.seg.this)
.attr("d", function(d) {
return d3.svg.line()(_.pluck(d.vertices.slice(d.curRange[0].idx, d.curRange[1].idx + 1), "coords"));
});
}
});
var drawPatternSegmentEndpoints = function(segmentList) {
var endpointsList = _.flatten(_.map(segmentList, function(seg) {
return [{seg: seg, isStart: true, point: seg.curRange[0]}, {seg: seg, isStart: false, point: seg.curRange[seg.curRange.length - 1]}];
}));
assembleOptimizeCanvas.selectAll(".pattern-segment-endpoint").remove();
var endpoints = assembleOptimizeCanvas.selectAll(".pattern-segment-endpoint").data(endpointsList)
.enter()
.append("circle")
.classed("pattern-segment-endpoint clickable", true)
.attr("r", 4)
.on("mouseover", function(d) {
d3.select(this).attr("r", 5);
})
.on("mouseout", function(d) {
d3.select(this).attr("r", 4);
})
.call(patternSegmentDrag);
return updatePatternSegmentEndpointPositions(endpoints);
};
var drawPatternSegmentCustomPoints = function(segmentList) {
var handlePoints = _.flatten(_.map(segmentList, function(seg) {
_.each(seg.patternHandles, function(ph) {
ph.seg = seg;
});
return seg.patternHandles;
}));
assembleOptimizeCanvas.selectAll(".pattern-segment-endpoint").remove();
var endpoints = assembleOptimizeCanvas.selectAll(".pattern-segment-endpoint").data(handlePoints)
.enter()
.append("circle")
.classed("pattern-segment-fixable-point clickable", true)
.classed("selected", function(d1) {
var isSelected = _.find(createObjectives(optimizationConstraints).getInterface(),
function(d2) { return patternHandleComparator(d1, d2); });
d1.fix = !isSelected;
return isSelected;
})
.attr("r", 3)
.attr("cx", function(d) { return d.coords[0]; })
.attr("cy", function(d) { return d.coords[1]; })
.on("mouseover", function(d) { d3.select(this).attr("r", 4); })
.on("mouseout", function(d) { d3.select(this).attr("r", 3); })
.on("click", function(d1) {
d1.fix = !d1.fix;
d3.selectAll(".pattern-segment-fixable-point")
.filter(function(d2) {
return patternHandleComparator(d1, d2);
})
.each(function(d2) {
d2.fix = d1.fix;
})
.classed("selected", !d1.fix);
var disableNext = _.all(d3.selectAll(".pattern-segment-fixable-point.clickable")[0], function(n) {
return n.__data__.fix;
});
d3.select("#nextOptimizeBtn")
.classed("disabled", disableNext);
$("#nextOptimizeBtnGroup").tooltip("destroy")
.tooltip({placement: "bottom", title: disableNext ?
"Select at least one point to vary." : ""});
});
var disableNext = _.all(d3.selectAll(".pattern-segment-fixable-point.clickable")[0],
function(n) {
return n.__data__.fix;
});
d3.select("#nextOptimizeBtn")
.classed("disabled", disableNext);
$("#nextOptimizeBtnGroup").tooltip("destroy")
.tooltip({placement: "bottom", title: disableNext ?
"Select at least one point to vary." : ""});
};
var bindToNextBtn = function(f) {
nextOptimizeBtn.on("click", f);
};
var finishSelection = function(constraintSpec, selectedSegmentObjects) {
return function() {
d3.selectAll(".pattern-segment.selected")
.classed("pattern-segment selected", false)
.classed("pattern-segment-fixed", true);
d3.selectAll(".pattern-segment-fixable-point")
.classed("clickable", false)
.on("click", null)
.filter(function(d) { return d.fix; })
.remove();
exitConstraintSelection();
var constructor = constraintSpec.constructor;
optimizationConstraints.push(constructor(selectedSegmentObjects));
_.each(optimizationConstraints, function(o) {
// reset cache to only one element
o.evaluateCache.splice(0, o.evaluateCache.length - 1);
});
redrawConstraintList();
bindToNextBtn(null);
};
};
var constraintHandler = function(constraintSpec) {
return function() {
setupOptimizeOverlay();
d3.select("#nextOptimizeBtn").text("Next").classed("disabled", true);
d3.select(".svg-instruction-bar").classed("hidden", false);
d3.selectAll(".constraint-btns .btn")
.classed("btn-primary", false)
.classed("disabled btn-default", true);
d3.selectAll("path.pattern-segment").classed("selectable", true);
assembleSvgOptimizeLabel.text(constraintSpec.instructionText);
var selectedSegments = [];
$("#nextOptimizeBtnGroup").tooltip('destroy').tooltip({
placement: "bottom",
title: "Select the required number of segments first."});
assembleOptimizeCanvas.selectAll(".pattern-segment")
.on("click", patternSelectHandler(selectedSegments, constraintSpec.numSegments));
if (constraintSpec.constantConstraint) {
d3.select("#nextOptimizeBtn").text("Finish");
}
bindToNextBtn(function() {
d3.selectAll("path.pattern-segment").classed("selectable", false)
.on("click", null);
assembleOptimizeCanvas.selectAll(".pattern-segment-endpoint").remove();
var selectedSegmentObjects = _.map(selectedSegments, function(seg) {
seg.vertexRange = [seg.startIdx + seg.curRange[0].idx, seg.startIdx + seg.curRange[1].idx];
return makeSegment(seg);
});
if (constraintSpec.constantConstraint) {
finishSelection(constraintSpec, selectedSegmentObjects)();
} else {
assembleSvgOptimizeLabel.text("Select points to vary during optimization.");
drawPatternSegmentCustomPoints(selectedSegmentObjects);
d3.select("#nextOptimizeBtn").text("Finish");
bindToNextBtn(finishSelection(constraintSpec, selectedSegmentObjects));
}
});
};
};
var exitConstraintSelection = function() {
assembleOptimizeCanvas.selectAll(".pattern-segment, .pattern-segment-endpoint, .pattern-segment-fixable-point.clickable").remove();
d3.select(".svg-instruction-bar").classed("hidden", true);
d3.selectAll(".constraint-btns .btn")
.classed("btn-primary", true)
.classed("disabled btn-default", false);
};
var optimizationConstraints = [];
var highlightNodes = function(nodes) {
d3.selectAll(".pattern-segment-fixed, .pattern-segment-fixable-point")
.classed("highlighted", function(d) {
return (_.find(nodes, function(n) {
return n === (d.this || d.seg.getNode);
}));
})
.classed("translucent-segment", function(d) {
return !d3.select(this).classed("highlighted");
});
};
var resetHighlightNodes = function() {
d3.selectAll(".pattern-segment-fixed, .pattern-segment-fixable-point")
.classed("translucent-segment highlighted", false);
};
var deleteNodes = function(nodes) {
d3.selectAll(".pattern-segment-fixed, .pattern-segment-fixable-point")
.filter(function(d) {
return (_.find(nodes, function(n) {
return n === (d.this || d.seg.getNode);
}));
})
.remove();
};
var deleteConstraint = function(constraint) {
deleteNodes(_.pluck(constraint.segments, "getNode"));
optimizationConstraints.splice(optimizationConstraints.indexOf(constraint), 1);
redrawConstraintList();
};
var deleteAllConstraints = function() {
deleteNodes(_.flatten(_.map(optimizationConstraints, function(c) {
return _.pluck(c.segments, "getNode");
})));
optimizationConstraints.splice(0, optimizationConstraints.length);
redrawConstraintList();
};
var updateObjectiveValues = function() {
_.each(optimizationConstraints, function(d) {
if (!d.cached) {
d.evaluateCache.push(d.evaluate());
if (d.evaluateCache.length > 2) {
d.evaluateCache.splice(0, d.evaluateCache.length - 2);
}
d.cached = true;
}
});
totalObjectiveLabel.text(function() {
var value = "";
var indices = (_.all(optimizationConstraints, function(d) {
return d.evaluateCache.length === 2;
})) ? [0,1] : [0];
return "Sum of objectives: " + _.map(indices, function(i) {
return parseFloat((_.sum(_.map(optimizationConstraints, function(o) {
return o.evaluateCache[i] * o.factor;
}))).toPrecision(3));
}).join("โ");
});
sidebarConstraintForm.selectAll(".constraint-row").selectAll(".objectiveLabel")
.html(function() {
var d = this.parentNode.__data__;
return "Objective value: " + _.map(d.evaluateCache, function(n) {
return parseFloat(n.toPrecision(3)) + d.evaluateUnit;
}).join("โ");
});
};
var redrawConstraintList = function() {
sidebarConstraintForm.selectAll(".constraint-row").remove();
if (optimizationConstraints.length === 0) {
optimizeBtnDiv.style("display", "none");
noConstraintsSoFar.style("display", "block");
totalObjectiveLabel.text("");
return;
}
// implicit else
optimizeBtnDiv.style("display", "block");
noConstraintsSoFar.style("display", "none");
var ctr = (function() {
var num = 0;
return function() {
num += 1;
return num;
};
})();
var listRows = sidebarConstraintForm.selectAll(".constraint-row").data(optimizationConstraints)
.enter()
.append("div").classed("constraint-row", true)
.html(function(d) {
var deleteX = "<a class='strip-table-x' href='#'><i class='fa fa-times'></i></a>";
var inputParams = d.withInput ? (" " + d.withInput.markup) : "";
var displayName = "<h5 class='inline-title'>" + d.displayName + inputParams + "</h5>";
var segmentList = "(<span class='segments'></span>)";
var objective = "<div class='objectiveLabel small'></div>";
var scaleFactor = "<div class='scaleLabel small'>Scaling factor: <input type='text' class='constraintScale'> x</div>";
return deleteX + " " + displayName + " " + segmentList + objective + scaleFactor;
}).each(function(d) {
d3.select(this).select(".constraintScale")
.attr("value", function() {
var d = this.parentNode.parentNode.__data__;
return d.factor;
})
.on("blur", function() {
var d = this.parentNode.parentNode.__data__;
d.factor = parseFloat($(this).val(), 10);
updateObjectiveValues();
});
if (d.withInput) {
d3.select(this).select(".constraintParam")
.attr("value", function() {
var d = this.parentNode.parentNode.__data__;
return d.withInput.paramValue;
})
.on("blur", function() {
var d = this.parentNode.parentNode.__data__;
d.withInput.paramValue = parseFloat($(this).val(), 10);
d.cached = false;
d.evaluateCache.splice(d.evaluateCache.length - 1, 1);
updateObjectiveValues();
});
}
});
updateObjectiveValues();
listRows.select(".strip-table-x")
.on("click", function(d, i) {
var constraint = this.parentNode.__data__;
deleteConstraint(constraint);
});
listRows.select("h5")
.on("mouseover", function() {
var d = this.parentNode.__data__;
highlightNodes(_.pluck(d.segments, "getNode"));
})
.on("mouseout", resetHighlightNodes);
listRows.select(".segments").selectAll(".segment-label")
.data(function(d) { return this.parentNode.parentNode.__data__.segments; })
.enter()
.append("span")
.classed("segment-label", true)
.html(function(d, i) {
var fullList = this.parentNode.parentNode.__data__.segments;
return "<a href='#'>#" + ctr() + ((i === fullList.length - 1) ? "" : ", ") + "</a>";
})
.on("mouseover", function(d) {
highlightNodes([d.getNode]);
})
.on("mouseout", resetHighlightNodes);
}; |
Clazz.declarePackage ("JS");
Clazz.load (null, "JS.ScriptContext", ["java.util.Hashtable", "JS.SV"], function () {
c$ = Clazz.decorateAsClass (function () {
this.aatoken = null;
this.allowJSThreads = false;
this.chk = false;
this.contextPath = " >> ";
this.vars = null;
this.displayLoadErrorsSave = false;
this.errorMessage = null;
this.errorMessageUntranslated = null;
this.errorType = null;
this.executionPaused = false;
this.executionStepping = false;
this.functionName = null;
this.iCommandError = -1;
this.id = 0;
this.isComplete = true;
this.isFunction = false;
this.isJSThread = false;
this.isStateScript = false;
this.isTryCatch = false;
this.iToken = 0;
this.lineEnd = 2147483647;
this.lineIndices = null;
this.lineNumbers = null;
this.mustResumeEval = false;
this.outputBuffer = null;
this.parallelProcessor = null;
this.parentContext = null;
this.pc = 0;
this.pc0 = 0;
this.pcEnd = 2147483647;
this.script = null;
this.scriptExtensions = null;
this.scriptFileName = null;
this.scriptLevel = 0;
this.statement = null;
this.htFileCache = null;
this.statementLength = 0;
this.token = null;
this.tryPt = 0;
this.theToken = null;
this.theTok = 0;
this.pointers = null;
Clazz.instantialize (this, arguments);
}, JS, "ScriptContext");
Clazz.makeConstructor (c$,
function () {
this.id = ++JS.ScriptContext.contextCount;
});
Clazz.defineMethod (c$, "setMustResume",
function () {
var sc = this;
while (sc != null) {
sc.mustResumeEval = true;
sc.pc = sc.pc0;
sc = sc.parentContext;
}
});
Clazz.defineMethod (c$, "getVariable",
function ($var) {
var context = this;
while (context != null && !context.isFunction) {
if (context.vars != null && context.vars.containsKey ($var)) return context.vars.get ($var);
context = context.parentContext;
}
return null;
}, "~S");
Clazz.defineMethod (c$, "getFullMap",
function () {
var ht = new java.util.Hashtable ();
var context = this;
if (this.contextPath != null) ht.put ("_path", JS.SV.newS (this.contextPath));
while (context != null && !context.isFunction) {
if (context.vars != null) for (var key, $key = context.vars.keySet ().iterator (); $key.hasNext () && ((key = $key.next ()) || true);) if (!ht.containsKey (key)) {
var val = context.vars.get (key);
if (val.tok != 2 || val.intValue != 2147483647) ht.put (key, val);
}
context = context.parentContext;
}
return ht;
});
Clazz.defineMethod (c$, "saveTokens",
function (aa) {
this.aatoken = aa;
if (aa == null) {
this.pointers = null;
return;
}this.pointers = Clazz.newIntArray (aa.length, 0);
for (var i = this.pointers.length; --i >= 0; ) this.pointers[i] = aa[i][0].intValue;
}, "~A");
Clazz.defineMethod (c$, "restoreTokens",
function () {
if (this.pointers != null) for (var i = this.pointers.length; --i >= 0; ) this.aatoken[i][0].intValue = this.pointers[i];
return this.aatoken;
});
Clazz.defineMethod (c$, "getTokenCount",
function () {
return (this.aatoken == null ? -1 : this.aatoken.length);
});
Clazz.defineMethod (c$, "getToken",
function (i) {
return this.aatoken[i];
}, "~N");
Clazz.defineStatics (c$,
"contextCount", 0);
});
|
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=getClasses;var _react=_interopRequireDefault(require("react")),_createShallow=_interopRequireDefault(require("./createShallow")),shallow=(0,_createShallow.default)();function getClasses(e){var r,t=e.type.useStyles;return shallow(_react.default.createElement(function(){return r=t(e.props),null},null)),r} |
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),require("./turn-order-4ab12333.js"),require("immer"),require("./plugin-random-7425844d.js"),require("lodash.isplainobject");var reducer=require("./reducer-fa65c6b2.js");require("rfc6902");var initialize=require("./initialize-d89f4805.js"),transport=require("./transport-b1874dfa.js"),util=require("./util-38a5fa06.js"),filterPlayerView=require("./filter-player-view-a8eeb11e.js");exports.CreateGameReducer=reducer.CreateGameReducer,exports.ProcessGameConfig=reducer.ProcessGameConfig,exports.InitializeGame=initialize.InitializeGame,exports.Transport=transport.Transport,exports.Async=util.Async,exports.Sync=util.Sync,exports.createMatch=util.createMatch,exports.getFilterPlayerView=filterPlayerView.getFilterPlayerView; |
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.FormLabelRoot = exports.overridesResolver = void 0;
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _clsx = _interopRequireDefault(require("clsx"));
var _utils = require("@material-ui/utils");
var _unstyled = require("@material-ui/unstyled");
var _formControlState = _interopRequireDefault(require("../FormControl/formControlState"));
var _useFormControl = _interopRequireDefault(require("../FormControl/useFormControl"));
var _capitalize = _interopRequireDefault(require("../utils/capitalize"));
var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps"));
var _experimentalStyled = _interopRequireDefault(require("../styles/experimentalStyled"));
var _formLabelClasses = _interopRequireWildcard(require("./formLabelClasses"));
var _jsxRuntime = require("react/jsx-runtime");
const overridesResolver = ({
styleProps
}, styles) => {
return (0, _utils.deepmerge)((0, _extends2.default)({}, styleProps.color === 'secondary' && styles.colorSecondary, styleProps.filled && styles.filled, {
[`& .${_formLabelClasses.default.asterisk}`]: (0, _extends2.default)({}, styles.asterisk)
}), styles.root || {});
};
exports.overridesResolver = overridesResolver;
const useUtilityClasses = styleProps => {
const {
classes,
color,
focused,
disabled,
error,
filled,
required
} = styleProps;
const slots = {
root: ['root', `color${(0, _capitalize.default)(color)}`, disabled && 'disabled', error && 'error', filled && 'filled', focused && 'focused', required && 'required'],
asterisk: ['asterisk', error && 'error']
};
return (0, _unstyled.unstable_composeClasses)(slots, _formLabelClasses.getFormLabelUtilityClasses, classes);
};
const FormLabelRoot = (0, _experimentalStyled.default)('label', {}, {
name: 'MuiFormLabel',
slot: 'Root',
overridesResolver
})(({
theme,
styleProps
}) => (0, _extends2.default)({
color: theme.palette.text.secondary
}, theme.typography.body1, {
lineHeight: '1.4375em',
padding: 0,
'&.Mui-focused': {
color: theme.palette[styleProps.color].main
},
'&.Mui-disabled': {
color: theme.palette.text.disabled
},
'&.Mui-error': {
color: theme.palette.error.main
}
}));
exports.FormLabelRoot = FormLabelRoot;
const AsteriskComponent = (0, _experimentalStyled.default)('span', {}, {
name: 'MuiFormLabel',
slot: 'Asterisk'
})(({
theme
}) => ({
'&.Mui-error': {
color: theme.palette.error.main
}
}));
const FormLabel = /*#__PURE__*/React.forwardRef(function FormLabel(inProps, ref) {
const props = (0, _useThemeProps.default)({
props: inProps,
name: 'MuiFormLabel'
});
const {
children,
className,
component = 'label'
} = props,
other = (0, _objectWithoutPropertiesLoose2.default)(props, ["children", "className", "color", "component", "disabled", "error", "filled", "focused", "required"]);
const muiFormControl = (0, _useFormControl.default)();
const fcs = (0, _formControlState.default)({
props,
muiFormControl,
states: ['color', 'required', 'focused', 'disabled', 'error', 'filled']
});
const styleProps = (0, _extends2.default)({}, props, {
color: fcs.color || 'primary',
component,
disabled: fcs.disabled,
error: fcs.error,
filled: fcs.filled,
focused: fcs.focused,
required: fcs.required
});
const classes = useUtilityClasses(styleProps);
return /*#__PURE__*/(0, _jsxRuntime.jsxs)(FormLabelRoot, (0, _extends2.default)({
as: component,
styleProps: styleProps,
className: (0, _clsx.default)(classes.root, className),
ref: ref
}, other, {
children: [children, fcs.required && /*#__PURE__*/(0, _jsxRuntime.jsxs)(AsteriskComponent, {
styleProps: styleProps,
"aria-hidden": true,
className: classes.asterisk,
children: ["\u2009", '*']
})]
}));
});
process.env.NODE_ENV !== "production" ? FormLabel.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content of the component.
*/
children: _propTypes.default.node,
/**
* Override or extend the styles applied to the component.
*/
classes: _propTypes.default.object,
/**
* @ignore
*/
className: _propTypes.default.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
*/
color: _propTypes.default.oneOf(['primary', 'secondary']),
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: _propTypes.default.elementType,
/**
* If `true`, the label should be displayed in a disabled state.
*/
disabled: _propTypes.default.bool,
/**
* If `true`, the label is displayed in an error state.
*/
error: _propTypes.default.bool,
/**
* If `true`, the label should use filled classes key.
*/
filled: _propTypes.default.bool,
/**
* If `true`, the input of this label is focused (used by `FormGroup` components).
*/
focused: _propTypes.default.bool,
/**
* If `true`, the label will indicate that the `input` is required.
*/
required: _propTypes.default.bool,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: _propTypes.default.object
} : void 0;
var _default = FormLabel;
exports.default = _default; |
/**
* useful colors for bash
*/
'use strict';
module.exports = {
black: '\x1b[0;30m',
dkgray: '\x1b[1;30m',
brick: '\x1b[0;31m',
red: '\x1b[1;31m',
green: '\x1b[0;32m',
lime: '\x1b[1;32m',
brown: '\x1b[0;33m',
yellow: '\x1b[1;33m',
navy: '\x1b[0;34m',
blue: '\x1b[1;34m',
violet: '\x1b[0;35m',
magenta: '\x1b[1;35m',
teal: '\x1b[0;36m',
cyan: '\x1b[1;36m',
ltgray: '\x1b[0;37m',
white: '\x1b[1;37m',
reset: '\x1b[0m'
}; |
/*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var finalhandler = require('finalhandler');
var Router = require('./router');
var methods = require('methods');
var middleware = require('./middleware/init');
var query = require('./middleware/query');
var debug = require('debug')('express:application');
var View = require('./view');
var http = require('http');
var compileETag = require('./utils').compileETag;
var compileQueryParser = require('./utils').compileQueryParser;
var compileTrust = require('./utils').compileTrust;
var deprecate = require('depd')('express');
var flatten = require('array-flatten');
var merge = require('utils-merge');
var resolve = require('path').resolve;
var slice = Array.prototype.slice;
/**
* Application prototype.
*/
var app = exports = module.exports = {};
/**
* Variable for trust proxy inheritance back-compat
* @private
*/
var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';
/**
* Initialize the server.
*
* - setup default configuration
* - setup default middleware
* - setup route reflection methods
*
* @private
*/
app.init = function init() {
this.cache = {};
this.engines = {};
this.settings = {};
this.defaultConfiguration();
};
/**
* Initialize application configuration.
* @private
*/
app.defaultConfiguration = function defaultConfiguration() {
var env = process.env.NODE_ENV || 'development';
// default settings
this.enable('x-powered-by');
this.set('etag', 'weak');
this.set('env', env);
this.set('query parser', 'extended');
this.set('subdomain offset', 2);
this.set('trust proxy', false);
// trust proxy inherit back-compat
Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
configurable: true,
value: true
});
debug('booting in %s mode', env);
this.on('mount', function onmount(parent) {
// inherit trust proxy
if (this.settings[trustProxyDefaultSymbol] === true
&& typeof parent.settings['trust proxy fn'] === 'function') {
delete this.settings['trust proxy'];
delete this.settings['trust proxy fn'];
}
// inherit protos
this.request.__proto__ = parent.request;
this.response.__proto__ = parent.response;
this.engines.__proto__ = parent.engines;
this.settings.__proto__ = parent.settings;
});
// setup locals
this.locals = Object.create(null);
// top-most app is mounted at /
this.mountpath = '/';
// default locals
this.locals.settings = this.settings;
// default configuration
this.set('view', View);
this.set('views', resolve('views'));
this.set('jsonp callback name', 'callback');
if (env === 'production') {
this.enable('view cache');
}
Object.defineProperty(this, 'router', {
get: function() {
throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');
}
});
};
/**
* lazily adds the base router if it has not yet been added.
*
* We cannot add the base router in the defaultConfiguration because
* it reads app settings which might be set after that has run.
*
* @private
*/
app.lazyrouter = function lazyrouter() {
if (!this._router) {
this._router = new Router({
caseSensitive: this.enabled('case sensitive routing'),
strict: this.enabled('strict routing')
});
this._router.use(query(this.get('query parser fn')));
this._router.use(middleware.init(this));
}
};
/**
* Dispatch a req, res pair into the application. Starts pipeline processing.
*
* If no callback is provided, then default error handlers will respond
* in the event of an error bubbling through the stack.
*
* @private
*/
app.handle = function handle(req, res, callback) {
var router = this._router;
// final handler
var done = callback || finalhandler(req, res, {
env: this.get('env'),
onerror: logerror.bind(this)
});
// no routes
if (!router) {
debug('no routes defined on app');
done();
return;
}
router.handle(req, res, done);
};
/**
* Proxy `Router#use()` to add middleware to the app router.
* See Router#use() documentation for details.
*
* If the _fn_ parameter is an express app, then it will be
* mounted at the _route_ specified.
*
* @public
*/
app.use = function use(fn) {
var offset = 0;
var path = '/';
// default path to '/'
// disambiguate app.use([fn])
if (typeof fn !== 'function') {
var arg = fn;
while (Array.isArray(arg) && arg.length !== 0) {
arg = arg[0];
}
// first arg is the path
if (typeof arg !== 'function') {
offset = 1;
path = fn;
}
}
var fns = flatten(slice.call(arguments, offset));
if (fns.length === 0) {
throw new TypeError('app.use() requires middleware functions');
}
// setup router
this.lazyrouter();
var router = this._router;
fns.forEach(function (fn) {
// non-express app
if (!fn || !fn.handle || !fn.set) {
return router.use(path, fn);
}
debug('.use app under %s', path);
fn.mountpath = path;
fn.parent = this;
// restore .app property on req and res
router.use(path, function mounted_app(req, res, next) {
var orig = req.app;
fn.handle(req, res, function (err) {
req.__proto__ = orig.request;
res.__proto__ = orig.response;
next(err);
});
});
// mounted an app
fn.emit('mount', this);
}, this);
return this;
};
/**
* Proxy to the app `Router#route()`
* Returns a new `Route` instance for the _path_.
*
* Routes are isolated middleware stacks for specific paths.
* See the Route api docs for details.
*
* @public
*/
app.route = function route(path) {
this.lazyrouter();
return this._router.route(path);
};
/**
* Register the given template engine callback `fn`
* as `ext`.
*
* By default will `require()` the engine based on the
* file extension. For example if you try to render
* a "foo.jade" file Express will invoke the following internally:
*
* app.engine('jade', require('jade').__express);
*
* For engines that do not provide `.__express` out of the box,
* or if you wish to "map" a different extension to the template engine
* you may use this method. For example mapping the EJS template engine to
* ".html" files:
*
* app.engine('html', require('ejs').renderFile);
*
* In this case EJS provides a `.renderFile()` method with
* the same signature that Express expects: `(path, options, callback)`,
* though note that it aliases this method as `ejs.__express` internally
* so if you're using ".ejs" extensions you dont need to do anything.
*
* Some template engines do not follow this convention, the
* [Consolidate.js](https://github.com/tj/consolidate.js)
* library was created to map all of node's popular template
* engines to follow this convention, thus allowing them to
* work seamlessly within Express.
*
* @param {String} ext
* @param {Function} fn
* @return {app} for chaining
* @public
*/
app.engine = function engine(ext, fn) {
if (typeof fn !== 'function') {
throw new Error('callback function required');
}
// get file extension
var extension = ext[0] !== '.'
? '.' + ext
: ext;
// store engine
this.engines[extension] = fn;
return this;
};
/**
* Proxy to `Router#param()` with one added api feature. The _name_ parameter
* can be an array of names.
*
* See the Router#param() docs for more details.
*
* @param {String|Array} name
* @param {Function} fn
* @return {app} for chaining
* @public
*/
app.param = function param(name, fn) {
this.lazyrouter();
if (Array.isArray(name)) {
for (var i = 0; i < name.length; i++) {
this.param(name[i], fn);
}
return this;
}
this._router.param(name, fn);
return this;
};
/**
* Assign `setting` to `val`, or return `setting`'s value.
*
* app.set('foo', 'bar');
* app.get('foo');
* // => "bar"
*
* Mounted servers inherit their parent server's settings.
*
* @param {String} setting
* @param {*} [val]
* @return {Server} for chaining
* @public
*/
app.set = function set(setting, val) {
if (arguments.length === 1) {
// app.get(setting)
return this.settings[setting];
}
debug('set "%s" to %o', setting, val);
// set value
this.settings[setting] = val;
// trigger matched settings
switch (setting) {
case 'etag':
this.set('etag fn', compileETag(val));
break;
case 'query parser':
this.set('query parser fn', compileQueryParser(val));
break;
case 'trust proxy':
this.set('trust proxy fn', compileTrust(val));
// trust proxy inherit back-compat
Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
configurable: true,
value: false
});
break;
}
return this;
};
/**
* Return the app's absolute pathname
* based on the parent(s) that have
* mounted it.
*
* For example if the application was
* mounted as "/admin", which itself
* was mounted as "/blog" then the
* return value would be "/blog/admin".
*
* @return {String}
* @private
*/
app.path = function path() {
return this.parent
? this.parent.path() + this.mountpath
: '';
};
/**
* Check if `setting` is enabled (truthy).
*
* app.enabled('foo')
* // => false
*
* app.enable('foo')
* app.enabled('foo')
* // => true
*
* @param {String} setting
* @return {Boolean}
* @public
*/
app.enabled = function enabled(setting) {
return Boolean(this.set(setting));
};
/**
* Check if `setting` is disabled.
*
* app.disabled('foo')
* // => true
*
* app.enable('foo')
* app.disabled('foo')
* // => false
*
* @param {String} setting
* @return {Boolean}
* @public
*/
app.disabled = function disabled(setting) {
return !this.set(setting);
};
/**
* Enable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @public
*/
app.enable = function enable(setting) {
return this.set(setting, true);
};
/**
* Disable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @public
*/
app.disable = function disable(setting) {
return this.set(setting, false);
};
/**
* Delegate `.VERB(...)` calls to `router.VERB(...)`.
*/
methods.forEach(function(method){
app[method] = function(path){
if (method === 'get' && arguments.length === 1) {
// app.get(setting)
return this.set(path);
}
this.lazyrouter();
var route = this._router.route(path);
route[method].apply(route, slice.call(arguments, 1));
return this;
};
});
/**
* Special-cased "all" method, applying the given route `path`,
* middleware, and callback to _every_ HTTP method.
*
* @param {String} path
* @param {Function} ...
* @return {app} for chaining
* @public
*/
app.all = function all(path) {
this.lazyrouter();
var route = this._router.route(path);
var args = slice.call(arguments, 1);
for (var i = 0; i < methods.length; i++) {
route[methods[i]].apply(route, args);
}
return this;
};
// del -> delete alias
app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');
/**
* Render the given view `name` name with `options`
* and a callback accepting an error and the
* rendered template string.
*
* Example:
*
* app.render('email', { name: 'Tobi' }, function(err, html){
* // ...
* })
*
* @param {String} name
* @param {Object|Function} options or fn
* @param {Function} callback
* @public
*/
app.render = function render(name, options, callback) {
var cache = this.cache;
var done = callback;
var engines = this.engines;
var opts = options;
var renderOptions = {};
var view;
// support callback function as second arg
if (typeof options === 'function') {
done = options;
opts = {};
}
// merge app.locals
merge(renderOptions, this.locals);
// merge options._locals
if (opts._locals) {
merge(renderOptions, opts._locals);
}
// merge options
merge(renderOptions, opts);
// set .cache unless explicitly provided
if (renderOptions.cache == null) {
renderOptions.cache = this.enabled('view cache');
}
// primed cache
if (renderOptions.cache) {
view = cache[name];
}
// view
if (!view) {
var View = this.get('view');
view = new View(name, {
defaultEngine: this.get('view engine'),
root: this.get('views'),
engines: engines
});
if (!view.path) {
var dirs = Array.isArray(view.root) && view.root.length > 1
? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'
: 'directory "' + view.root + '"'
var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
err.view = view;
return done(err);
}
// prime the cache
if (renderOptions.cache) {
cache[name] = view;
}
}
// render
tryRender(view, renderOptions, done);
};
/**
* Listen for connections.
*
* A node `http.Server` is returned, with this
* application (which is a `Function`) as its
* callback. If you wish to create both an HTTP
* and HTTPS server you may do so with the "http"
* and "https" modules as shown here:
*
* var http = require('http')
* , https = require('https')
* , express = require('express')
* , app = express();
*
* http.createServer(app).listen(80);
* https.createServer({ ... }, app).listen(443);
*
* @return {http.Server}
* @public
*/
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
/**
* Log error using console.error.
*
* @param {Error} err
* @private
*/
function logerror(err) {
/* istanbul ignore next */
if (this.get('env') !== 'test') console.error(err.stack || err.toString());
}
/**
* Try rendering a view.
* @private
*/
function tryRender(view, options, callback) {
try {
view.render(options, callback);
} catch (err) {
callback(err);
}
}
|
document.write('Hello HTML'); |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'preview', 'ja', {
preview: 'ใใฌใใฅใผ'
} );
|
var util = require('util');
function ConfigurationError(message) {
this.name = 'ConfigurationError';
this.message = message || 'Invalid configuration file given';
}
util.inherits(ConfigurationError, Error);
exports.ConfigurationError = ConfigurationError;
|
/*
Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
dojo.require("dojox.gfx.svg");
dojo.experimental("dojox.gfx.svg_attach");
(function(){
dojox.gfx.attachNode=function(_1){
if(!_1){
return null;
}
var s=null;
switch(_1.tagName.toLowerCase()){
case dojox.gfx.Rect.nodeType:
s=new dojox.gfx.Rect(_1);
_2(s);
break;
case dojox.gfx.Ellipse.nodeType:
s=new dojox.gfx.Ellipse(_1);
_3(s,dojox.gfx.defaultEllipse);
break;
case dojox.gfx.Polyline.nodeType:
s=new dojox.gfx.Polyline(_1);
_3(s,dojox.gfx.defaultPolyline);
break;
case dojox.gfx.Path.nodeType:
s=new dojox.gfx.Path(_1);
_3(s,dojox.gfx.defaultPath);
break;
case dojox.gfx.Circle.nodeType:
s=new dojox.gfx.Circle(_1);
_3(s,dojox.gfx.defaultCircle);
break;
case dojox.gfx.Line.nodeType:
s=new dojox.gfx.Line(_1);
_3(s,dojox.gfx.defaultLine);
break;
case dojox.gfx.Image.nodeType:
s=new dojox.gfx.Image(_1);
_3(s,dojox.gfx.defaultImage);
break;
case dojox.gfx.Text.nodeType:
var t=_1.getElementsByTagName("textPath");
if(t&&t.length){
s=new dojox.gfx.TextPath(_1);
_3(s,dojox.gfx.defaultPath);
_4(s);
}else{
s=new dojox.gfx.Text(_1);
_5(s);
}
_6(s);
break;
default:
return null;
}
if(!(s instanceof dojox.gfx.Image)){
_7(s);
_8(s);
}
_9(s);
return s;
};
dojox.gfx.attachSurface=function(_a){
var s=new dojox.gfx.Surface();
s.rawNode=_a;
var _b=_a.getElementsByTagName("defs");
if(_b.length==0){
return null;
}
s.defNode=_b[0];
return s;
};
var _7=function(_c){
var _d=_c.rawNode.getAttribute("fill");
if(_d=="none"){
_c.fillStyle=null;
return;
}
var _e=null,_f=dojox.gfx.svg.getRef(_d);
if(_f){
switch(_f.tagName.toLowerCase()){
case "lineargradient":
_e=_10(dojox.gfx.defaultLinearGradient,_f);
dojo.forEach(["x1","y1","x2","y2"],function(x){
_e[x]=_f.getAttribute(x);
});
break;
case "radialgradient":
_e=_10(dojox.gfx.defaultRadialGradient,_f);
dojo.forEach(["cx","cy","r"],function(x){
_e[x]=_f.getAttribute(x);
});
_e.cx=_f.getAttribute("cx");
_e.cy=_f.getAttribute("cy");
_e.r=_f.getAttribute("r");
break;
case "pattern":
_e=dojo.lang.shallowCopy(dojox.gfx.defaultPattern,true);
dojo.forEach(["x","y","width","height"],function(x){
_e[x]=_f.getAttribute(x);
});
_e.src=_f.firstChild.getAttributeNS(dojox.gfx.svg.xmlns.xlink,"href");
break;
}
}else{
_e=new dojo.Color(_d);
var _11=_c.rawNode.getAttribute("fill-opacity");
if(_11!=null){
_e.a=_11;
}
}
_c.fillStyle=_e;
};
var _10=function(_12,_13){
var _14=dojo.clone(_12);
_14.colors=[];
for(var i=0;i<_13.childNodes.length;++i){
_14.colors.push({offset:_13.childNodes[i].getAttribute("offset"),color:new dojo.Color(_13.childNodes[i].getAttribute("stop-color"))});
}
return _14;
};
var _8=function(_15){
var _16=_15.rawNode,_17=_16.getAttribute("stroke");
if(_17==null||_17=="none"){
_15.strokeStyle=null;
return;
}
var _18=_15.strokeStyle=dojo.clone(dojox.gfx.defaultStroke);
var _19=new dojo.Color(_17);
if(_19){
_18.color=_19;
_18.color.a=_16.getAttribute("stroke-opacity");
_18.width=_16.getAttribute("stroke-width");
_18.cap=_16.getAttribute("stroke-linecap");
_18.join=_16.getAttribute("stroke-linejoin");
if(_18.join=="miter"){
_18.join=_16.getAttribute("stroke-miterlimit");
}
_18.style=_16.getAttribute("dojoGfxStrokeStyle");
}
};
var _9=function(_1a){
var _1b=_1a.rawNode.getAttribute("transform");
if(_1b.match(/^matrix\(.+\)$/)){
var t=_1b.slice(7,-1).split(",");
_1a.matrix=dojox.gfx.matrix.normalize({xx:parseFloat(t[0]),xy:parseFloat(t[2]),yx:parseFloat(t[1]),yy:parseFloat(t[3]),dx:parseFloat(t[4]),dy:parseFloat(t[5])});
}else{
_1a.matrix=null;
}
};
var _6=function(_1c){
var _1d=_1c.fontStyle=dojo.clone(dojox.gfx.defaultFont),r=_1c.rawNode;
_1d.style=r.getAttribute("font-style");
_1d.variant=r.getAttribute("font-variant");
_1d.weight=r.getAttribute("font-weight");
_1d.size=r.getAttribute("font-size");
_1d.family=r.getAttribute("font-family");
};
var _3=function(_1e,def){
var _1f=_1e.shape=dojo.clone(def),r=_1e.rawNode;
for(var i in _1f){
_1f[i]=r.getAttribute(i);
}
};
var _2=function(_20){
_3(_20,dojox.gfx.defaultRect);
_20.shape.r=Math.min(_20.rawNode.getAttribute("rx"),_20.rawNode.getAttribute("ry"));
};
var _5=function(_21){
var _22=_21.shape=dojo.clone(dojox.gfx.defaultText),r=_21.rawNode;
_22.x=r.getAttribute("x");
_22.y=r.getAttribute("y");
_22.align=r.getAttribute("text-anchor");
_22.decoration=r.getAttribute("text-decoration");
_22.rotated=parseFloat(r.getAttribute("rotate"))!=0;
_22.kerning=r.getAttribute("kerning")=="auto";
_22.text=r.firstChild.nodeValue;
};
var _4=function(_23){
var _24=_23.shape=dojo.clone(dojox.gfx.defaultTextPath),r=_23.rawNode;
_24.align=r.getAttribute("text-anchor");
_24.decoration=r.getAttribute("text-decoration");
_24.rotated=parseFloat(r.getAttribute("rotate"))!=0;
_24.kerning=r.getAttribute("kerning")=="auto";
_24.text=r.firstChild.nodeValue;
};
})();
|
// Authentication using passport, a node module
var passport = require('passport');
// logging out
exports.logout = function (req, res) {
req.logout();
res.redirect('/login');
};
module.exports.googleCallback = function (req, res) {
req.session.googleCredentials = req.authInfo;
// Return user profile back to client
res.send(req.user);
};
|
'use strict';
let path = require('path');
let webpack = require('webpack');
module.exports = {
entry: {
maskedinput_defaultfunctionality: './app/maskedinput/defaultfunctionality/main.ts',
maskedinput_fluidsize: './app/maskedinput/fluidsize/main.ts',
maskedinput_events: './app/maskedinput/events/main.ts',
maskedinput_righttoleftlayout: './app/maskedinput/righttoleftlayout/main.ts',
menu_defaultfunctionality: './app/menu/defaultfunctionality/main.ts',
menu_contextmenu: './app/menu/contextmenu/main.ts',
menu_verticalmenu: './app/menu/verticalmenu/main.ts',
menu_minimizedmenu: './app/menu/minimizedmenu/main.ts',
menu_opendirection: './app/menu/opendirection/main.ts',
menu_columns: './app/menu/columns/main.ts',
menu_images: './app/menu/images/main.ts',
menu_jsonmenu: './app/menu/jsonmenu/main.ts',
menu_xmlmenu: './app/menu/xmlmenu/main.ts',
menu_loadmenufromarray: './app/menu/loadmenufromarray/main.ts',
menu_centermenuitems: './app/menu/centermenuitems/main.ts',
menu_fluidsize: './app/menu/fluidsize/main.ts',
menu_keyboardnavigation: './app/menu/keyboardnavigation/main.ts',
menu_righttoleftlayout: './app/menu/righttoleftlayout/main.ts',
navbar_defaultfunctionality: './app/navbar/defaultfunctionality/main.ts',
navbar_verticalnavbar: './app/navbar/verticalnavbar/main.ts',
navbar_minimizednavbar: './app/navbar/minimizednavbar/main.ts',
navbar_righttoleftlayout: './app/navbar/righttoleftlayout/main.ts',
navigationbar_defaultfunctionality: './app/navigationbar/defaultfunctionality/main.ts',
navigationbar_multipleexpanded: './app/navigationbar/multipleexpanded/main.ts',
navigationbar_disabled: './app/navigationbar/disabled/main.ts',
navigationbar_events: './app/navigationbar/events/main.ts',
navigationbar_togglemode: './app/navigationbar/togglemode/main.ts',
navigationbar_fittocontainer: './app/navigationbar/fittocontainer/main.ts',
navigationbar_fluidsize: './app/navigationbar/fluidsize/main.ts',
navigationbar_keyboardnavigation: './app/navigationbar/keyboardnavigation/main.ts',
navigationbar_righttoleftlayout: './app/navigationbar/righttoleftlayout/main.ts',
notification_defaultfunctionality: './app/notification/defaultfunctionality/main.ts',
notification_notificationcontainer: './app/notification/notificationcontainer/main.ts',
notification_events: './app/notification/events/main.ts',
notification_customicon: './app/notification/customicon/main.ts',
notification_settings: './app/notification/settings/main.ts',
notification_fluidsize: './app/notification/fluidsize/main.ts',
notification_righttoleftlayout: './app/notification/righttoleftlayout/main.ts',
numberinput_defaultfunctionality: './app/numberinput/defaultfunctionality/main.ts',
numberinput_validation: './app/numberinput/validation/main.ts',
numberinput_settings: './app/numberinput/settings/main.ts',
numberinput_simpleinputmode: './app/numberinput/simpleinputmode/main.ts',
numberinput_templates: './app/numberinput/templates/main.ts',
numberinput_fluidsize: './app/numberinput/fluidsize/main.ts',
numberinput_events: './app/numberinput/events/main.ts',
numberinput_righttoleftlayout: './app/numberinput/righttoleftlayout/main.ts',
numberinput_twowaydatabinding: './app/numberinput/twowaydatabinding/main.ts',
panel_defaultfunctionality: './app/panel/defaultfunctionality/main.ts',
panel_dockpanel: './app/panel/dockpanel/main.ts',
panel_fluidsize: './app/panel/fluidsize/main.ts',
panel_righttoleftlayout: './app/panel/righttoleftlayout/main.ts',
passwordinput_defaultfunctionality: './app/passwordinput/defaultfunctionality/main.ts',
passwordinput_customstrengthrendering: './app/passwordinput/customstrengthrendering/main.ts',
passwordinput_fluidsize: './app/passwordinput/fluidsize/main.ts',
passwordinput_righttoleftlayout: './app/passwordinput/righttoleftlayout/main.ts',
passwordinput_twowaydatabinding: './app/passwordinput/twowaydatabinding/main.ts'
},
output: {
path: path.resolve(__dirname + '/aot'),
filename: '[name].bundle.js'
},
module: {
loaders:
[
{
test: /\.ts$/,
loaders: ['awesome-typescript-loader', 'angular2-template-loader?keepUrl=true'],
exclude: [/\.(spec|e2e)\.ts$/]
},
{
test: /\.html$/,
use: 'raw-loader'
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader']
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: [
'raw-loader',
'img-loader'
]
}
]
},
plugins: [
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.ProgressPlugin(),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)@angular/,
path.join(process.cwd(), 'app')
)
],
resolve: {
extensions: ['.ts', '.js']
}
};
|
/*
* Crypto-JS v2.5.3
* http://code.google.com/p/crypto-js/
* (c) 2009-2012 by Jeff Mott. All rights reserved.
* http://code.google.com/p/crypto-js/wiki/License
*/
(function(){
// Shortcuts
var C = Crypto,
util = C.util,
charenc = C.charenc,
UTF8 = charenc.UTF8,
Binary = charenc.Binary;
var MARC4 = C.MARC4 = {
/**
* Public API
*/
encrypt: function (message, password) {
var
// Convert to bytes
m = UTF8.stringToBytes(message),
// Generate random IV
iv = util.randomBytes(16),
// Generate key
k = password.constructor == String ?
// Derive key from passphrase
C.PBKDF2(password, iv, 32, { asBytes: true }) :
// else, assume byte array representing cryptographic key
password;
// Encrypt
MARC4._marc4(m, k, 1536);
// Return ciphertext
return util.bytesToBase64(iv.concat(m));
},
decrypt: function (ciphertext, password) {
var
// Convert to bytes
c = util.base64ToBytes(ciphertext),
// Separate IV and message
iv = c.splice(0, 16),
// Generate key
k = password.constructor == String ?
// Derive key from passphrase
C.PBKDF2(password, iv, 32, { asBytes: true }) :
// else, assume byte array representing cryptographic key
password;
// Decrypt
MARC4._marc4(c, k, 1536);
// Return plaintext
return UTF8.bytesToString(c);
},
/**
* Internal methods
*/
// The core
_marc4: function (m, k, drop) {
// State variables
var i, j, s, temp;
// Key setup
for (i = 0, s = []; i < 256; i++) s[i] = i;
for (i = 0, j = 0; i < 256; i++) {
j = (j + s[i] + k[i % k.length]) % 256;
// Swap
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
// Clear counters
i = j = 0;
// Encryption
for (var k = -drop; k < m.length; k++) {
i = (i + 1) % 256;
j = (j + s[i]) % 256;
// Swap
temp = s[i];
s[i] = s[j];
s[j] = temp;
// Stop here if we're still dropping keystream
if (k < 0) continue;
// Encrypt
m[k] ^= s[(s[i] + s[j]) % 256];
}
}
};
})();
|
lychee.define('game.entity.Ball').includes([
'lychee.game.Sprite'
]).exports(function(lychee, game, global, attachments) {
var _texture = attachments['png'];
var Class = function() {
var settings = {
radius: 11,
collision: lychee.game.Entity.COLLISION.A,
shape: lychee.game.Entity.SHAPE.circle,
texture: _texture,
map: null
};
lychee.game.Sprite.call(this, settings);
settings = null;
};
Class.prototype = {
};
return Class;
});
|
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', {
title: 'Express'
});
});
module.exports = router;
|
"use strict";
var CSSStyleDeclaration = require("cssstyle").CSSStyleDeclaration;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var notImplemented = require("./not-implemented");
var History = require("./history");
var VirtualConsole = require("../virtual-console");
var define = require("../utils").define;
var inherits = require("../utils").inheritFrom;
var resolveHref = require("../utils").resolveHref;
var EventTarget = require("../living/generated/events/EventTarget");
var namedPropertiesWindow = require("../living/named-properties-window");
var cssom = require("cssom");
var postMessage = require("../living/post-message");
const DOMException = require("../web-idl/DOMException");
const btoa = require("../../base64").btoa;
const atob = require("../../base64").atob;
const idlUtils = require("../living/generated/util");
// NB: the require() must be after assigning `module.export` because this require() is circular
module.exports = Window;
var dom = require("../living");
var cssSelectorSplitRE = /((?:[^,"']|"[^"]*"|'[^']*')+)/;
var defaultStyleSheet = cssom.parse(require("./default-stylesheet"));
dom.Window = Window;
// NOTE: per https://heycam.github.io/webidl/#Global, all properties on the Window object must be own-properties.
// That is why we assign everything inside of the constructor, instead of using a shared prototype.
// You can verify this in e.g. Firefox or Internet Explorer, which do a good job with Web IDL compliance.
function Window(options) {
EventTarget.setup(this);
var window = this;
///// INTERFACES FROM THE DOM
// TODO: consider a mode of some sort where these are not shared between all DOM instances
// It'd be very memory-expensive in most cases, though.
define(window, dom);
///// PRIVATE DATA PROPERTIES
// vm initialization is defered until script processing is activated (in level1/core)
this._globalProxy = this;
this.__timers = [];
// List options explicitly to be clear which are passed through
this._document = new dom.HTMLDocument({
parsingMode: options.parsingMode,
contentType: options.contentType,
cookieJar: options.cookieJar,
parser: options.parser,
url: options.url,
referrer: options.referrer,
cookie: options.cookie,
deferClose: options.deferClose,
resourceLoader: options.resourceLoader,
concurrentNodeIterators: options.concurrentNodeIterators,
defaultView: this._globalProxy,
global: this
});
// Set up the window as if it's a top level window.
// If it's not, then references will be corrected by frame/iframe code.
this._parent = this._top = this._globalProxy;
// This implements window.frames.length, since window.frames returns a
// self reference to the window object. This value is incremented in the
// HTMLFrameElement init function (see: level2/html.js).
this._length = 0;
if (options.virtualConsole) {
if (options.virtualConsole instanceof VirtualConsole) {
this._virtualConsole = options.virtualConsole;
} else {
throw new TypeError(
"options.virtualConsole must be a VirtualConsole (from createVirtualConsole)");
}
} else {
this._virtualConsole = new VirtualConsole();
}
///// GETTERS
define(this, {
get length() {
return window._length;
},
get window() {
return window._globalProxy;
},
get frames() {
return window._globalProxy;
},
get self() {
return window._globalProxy;
},
get parent() {
return window._parent;
},
get top() {
return window._top;
},
get document() {
return window._document;
},
get location() {
return window._document._location;
}
});
namedPropertiesWindow.initializeWindow(this, dom.HTMLCollection);
///// METHODS for [ImplicitThis] hack
// See https://lists.w3.org/Archives/Public/public-script-coord/2015JanMar/0109.html
this.addEventListener = this.addEventListener.bind(this);
this.removeEventListener = this.removeEventListener.bind(this);
this.dispatchEvent = this.dispatchEvent.bind(this);
///// METHODS
this.setTimeout = function (fn, ms) {
return startTimer(window, setTimeout, clearTimeout, fn, ms);
};
this.setInterval = function (fn, ms) {
return startTimer(window, setInterval, clearInterval, fn, ms);
};
this.clearInterval = stopTimer.bind(this, window);
this.clearTimeout = stopTimer.bind(this, window);
this.__stopAllTimers = stopAllTimers.bind(this, window);
this.Image = function (width, height) {
var element = window._document.createElement("img");
element.width = width;
element.height = height;
return element;
};
function wrapConsoleMethod(method) {
return function () {
var args = Array.prototype.slice.call(arguments);
window._virtualConsole.emit.apply(window._virtualConsole, [method].concat(args));
};
}
this.postMessage = postMessage;
this.atob = function (str) {
const result = atob(str);
if (result === null) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"The string to be encoded contains invalid characters.");
}
return result;
};
this.btoa = function (str) {
const result = btoa(str);
if (result === null) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"The string to be encoded contains invalid characters.");
}
return result;
};
this.XMLHttpRequest = function () {
var xhr = new XMLHttpRequest();
var lastUrl = "";
xhr._open = xhr.open;
xhr.open = function (method, url, async, user, password) {
lastUrl = fixUrlForBuggyXhr(resolveHref(window.document.URL, url));
return xhr._open(method, lastUrl, async, user, password);
};
xhr._getAllResponseHeaders = xhr.getAllResponseHeaders;
xhr.getAllResponseHeaders = function () {
if (lastUrl.startsWith("file:")) {
// Monkey patch this function for files. The node-xhr module will crash for file URLs.
return null;
}
return xhr._getAllResponseHeaders();
};
xhr._send = xhr.send;
xhr.send = function (data) {
var cookieJar = window.document._cookieJar;
var cookieStr = cookieJar.getCookieStringSync(lastUrl, {http: true});
if (cookieStr) {
xhr.setDisableHeaderCheck(true);
xhr.setRequestHeader("cookie", cookieStr);
xhr.setDisableHeaderCheck(false);
}
function setReceivedCookies() {
if (xhr.readyState === xhr.HEADERS_RECEIVED) {
var receivedCookies = xhr.getResponseHeader("set-cookie");
if (receivedCookies) {
receivedCookies = Array.isArray(receivedCookies) ? receivedCookies : [receivedCookies];
receivedCookies.forEach(function (cookieStr) {
cookieJar.setCookieSync(cookieStr, lastUrl, {
http: true,
ignoreError: true
});
});
}
xhr.removeEventListener("readystatechange", setReceivedCookies);
}
}
xhr.addEventListener("readystatechange", setReceivedCookies);
return xhr._send(data);
};
Object.defineProperty(xhr, "response", {
get: function () {
if (this.responseType === "text" || !this.responseType) {
// Spec says "text" or "", but responseType support is incomplete, so we need to catch more cases.
return this.responseText;
} else if (this.responseType === "json") {
return JSON.parse(this.responseText);
} else {
return null; // emulate failed request
}
},
enumerable: true,
configurable: true
});
return xhr;
};
this.close = function () {
// Recursively close child frame windows, then ourselves.
var currentWindow = this;
(function windowCleaner(window) {
var i;
// We could call window.frames.length etc, but window.frames just points
// back to window.
if (window.length > 0) {
for (i = 0; i < window.length; i++) {
windowCleaner(window[i]);
}
}
// We"re already in our own window.close().
if (window !== currentWindow) {
window.close();
}
})(this);
// Clear out all listeners. Any in-flight or upcoming events should not get delivered.
idlUtils.implForWrapper(this, "EventTarget")._events = Object.create(null);
if (this._document) {
if (this._document.body) {
this._document.body.innerHTML = "";
}
if (this._document.close) {
// It's especially important to clear out the listeners here because document.close() causes a "load" event to
// fire.
this._document._listeners = Object.create(null);
this._document.close();
}
delete this._document;
}
stopAllTimers(currentWindow);
};
this.getComputedStyle = function (node) {
var s = node.style;
var cs = new CSSStyleDeclaration();
var forEach = Array.prototype.forEach;
function setPropertiesFromRule(rule) {
if (!rule.selectorText) {
return;
}
var selectors = rule.selectorText.split(cssSelectorSplitRE);
var matched = false;
selectors.forEach(function (selectorText) {
if (selectorText !== "" && selectorText !== "," && !matched && matchesDontThrow(node, selectorText)) {
matched = true;
forEach.call(rule.style, function (property) {
cs.setProperty(property, rule.style.getPropertyValue(property), rule.style.getPropertyPriority(property));
});
}
});
}
function readStylesFromStyleSheet(sheet) {
forEach.call(sheet.cssRules, function (rule) {
if (rule.media) {
if (Array.prototype.indexOf.call(rule.media, "screen") !== -1) {
forEach.call(rule.cssRules, setPropertiesFromRule);
}
} else {
setPropertiesFromRule(rule);
}
});
}
readStylesFromStyleSheet(defaultStyleSheet);
forEach.call(node.ownerDocument.styleSheets, readStylesFromStyleSheet);
forEach.call(s, function (property) {
cs.setProperty(property, s.getPropertyValue(property), s.getPropertyPriority(property));
});
return cs;
};
///// PUBLIC DATA PROPERTIES (TODO: should be getters)
this.history = new History(this);
this.console = {
assert: wrapConsoleMethod("assert"),
clear: wrapConsoleMethod("clear"),
count: wrapConsoleMethod("count"),
debug: wrapConsoleMethod("debug"),
error: wrapConsoleMethod("error"),
group: wrapConsoleMethod("group"),
groupCollapse: wrapConsoleMethod("groupCollapse"),
groupEnd: wrapConsoleMethod("groupEnd"),
info: wrapConsoleMethod("info"),
log: wrapConsoleMethod("log"),
table: wrapConsoleMethod("table"),
time: wrapConsoleMethod("time"),
timeEnd: wrapConsoleMethod("timeEnd"),
trace: wrapConsoleMethod("trace"),
warn: wrapConsoleMethod("warn")
};
function notImplementedMethod(name) {
return function () {
notImplemented(name, window);
};
}
define(this, {
navigator: {
get userAgent() { return "Node.js (" + process.platform + "; U; rv:" + process.version + ")"; },
get appName() { return "Node.js jsDom"; },
get platform() { return process.platform; },
get appVersion() { return process.version; },
noUI: true,
get cookieEnabled() { return true; }
},
name: "nodejs",
innerWidth: 1024,
innerHeight: 768,
outerWidth: 1024,
outerHeight: 768,
pageXOffset: 0,
pageYOffset: 0,
screenX: 0,
screenY: 0,
screenLeft: 0,
screenTop: 0,
scrollX: 0,
scrollY: 0,
scrollTop: 0,
scrollLeft: 0,
screen: {
width: 0,
height: 0
},
alert: notImplementedMethod("window.alert"),
blur: notImplementedMethod("window.blur"),
confirm: notImplementedMethod("window.confirm"),
createPopup: notImplementedMethod("window.createPopup"),
focus: notImplementedMethod("window.focus"),
moveBy: notImplementedMethod("window.moveBy"),
moveTo: notImplementedMethod("window.moveTo"),
open: notImplementedMethod("window.open"),
print: notImplementedMethod("window.print"),
prompt: notImplementedMethod("window.prompt"),
resizeBy: notImplementedMethod("window.resizeBy"),
resizeTo: notImplementedMethod("window.resizeTo"),
scroll: notImplementedMethod("window.scroll"),
scrollBy: notImplementedMethod("window.scrollBy"),
scrollTo: notImplementedMethod("window.scrollTo")
});
///// INITIALIZATION
process.nextTick(function () {
if (!window.document) {
return; // window might've been closed already
}
var ev = window.document.createEvent("HTMLEvents");
ev.initEvent("load", false, false);
if (window.document.readyState === "complete") {
window.dispatchEvent(ev);
} else {
window.document.addEventListener("load", function (ev) {
window.dispatchEvent(ev);
});
}
});
}
inherits(EventTarget.interface, Window, EventTarget.interface.prototype);
function matchesDontThrow(el, selector) {
try {
return el.matches(selector);
} catch (e) {
return false;
}
}
function startTimer(window, startFn, stopFn, callback, ms) {
var res = startFn(callback, ms);
window.__timers.push([res, stopFn]);
return res;
}
function stopTimer(window, id) {
if (typeof id === "undefined") {
return;
}
for (var i in window.__timers) {
if (window.__timers[i][0] === id) {
window.__timers[i][1].call(window, id);
window.__timers.splice(i, 1);
break;
}
}
}
function stopAllTimers(window) {
window.__timers.forEach(function (t) {
t[1].call(window, t[0]);
});
window.__timers = [];
}
function fixUrlForBuggyXhr(url) {
// node-XMLHttpRequest doesn't properly handle file URLs. It only accepts file://C:/..., not file:///C:/...
// See https://github.com/tmpvar/jsdom/pull/1180
return url.replace(/^file:\/\/\/([a-zA-Z]:)/, "file://$1");
}
|
import path from 'path';
/*
* Return path to write file to inside outputDir.
*
* @param {object} svgPathObj
* path objects from path.parse
*
* @param {string} innerPath
* Path (relative to options.svgDir) to svg file
* e.g. if svgFile was /home/user/icons/path/to/svg/file.svg
* options.svgDir is /home/user/icons/
* innerPath is path/to/svg
*
* @param {object} options
* @return {string} output file dest relative to outputDir
*/
function defaultDestRewriter(svgPathObj, innerPath, options) {
let fileName = svgPathObj.base;
if (options.fileSuffix) {
fileName.replace(options.fileSuffix, '.svg');
} else {
fileName = fileName.replace('.svg', '.js');
}
fileName = fileName.replace(/(^.)|(_)(.)/g, (match, p1, p2, p3) => (p1 || p3).toUpperCase());
return path.join(innerPath, fileName);
}
export default defaultDestRewriter;
|
var Builder = require('../index');
var expect = require('chai').expect;
var toFileURL = require('../lib/utils.js').toFileURL;
var fs = require('fs');
suite('Test compiler cache', function() {
var builder = new Builder('test/fixtures/test-cache-tree');
builder.config({ transpiler: 'babel' });
test('Use compile cache entry when available', function() {
var loadName = 'simple.js';
var outputPath = 'test/output/cached.js';
var cacheObj;
var tree;
return builder.trace(loadName).then(function(_tree) {
tree = _tree;
return builder.bundle(tree);
})
.then(function() {
var cacheEntry = builder.getCache();
expect(cacheEntry).to.be.an('object');
cacheObj = cacheEntry.compile.loads['simple.js'];
expect(cacheObj).to.be.an('object');
expect(cacheObj.hash).to.be.a('string');
expect(cacheObj.output).to.be.an('object');
// poison cache
cacheObj.output.source = cacheObj.output.source.replace('hate', 'love');
return builder.bundle(tree);
})
.then(function(output) {
// verify buildTree use poisoned cache rather than recompiling
var outputSource = output.source;
expect(outputSource).not.to.contain('hate caches');
expect(outputSource).to.contain('love caches');
// invalidate poisoned cache entry and rebuild
cacheObj.hash = 'out of date';
return builder.bundle(tree);
})
.then(function(output) {
// verify original source is used once more
var outputSource = output.source;
expect(outputSource).to.contain('hate caches');
expect(outputSource).not.to.contain('love caches');
});
});
test('Use trace cache when available', function() {
// construct the load record for the cache
var cacheObj = {
trace: {
'simple.js': {
name: 'simple.js',
path: 'fixtures/test-cache-tree/simple.js',
metadata: {
deps: [],
format: 'amd',
isAnon: true
},
deps: [],
depMap: {},
source: 'define([], function(module) {\n console.log(\'fake cache\');\n});\n',
originalSource: 'define([], function(module) {\n console.log(\'fake cache\');\n});\n'
}
}
};
builder.reset();
builder.setCache(cacheObj);
return builder.bundle('simple.js').then(function(output) {
expect(output.source).to.contain('fake cache');
});
});
test('Cache invalidation', function() {
var cacheObj = {
trace: {
'simple.js': {},
'another/path.js': {}
}
};
builder.reset();
builder.setCache(cacheObj);
var invalidated = builder.invalidate('*');
assert.deepEqual(invalidated, [builder.loader.normalizeSync('simple.js'), builder.loader.normalizeSync('another/path.js')]);
cacheObj = {
trace: {
'simple.js': {},
'new/path.js': {},
'deep/wildcard/test.js': {}
}
};
builder.setCache(cacheObj);
invalidated = builder.invalidate('new/path.js');
assert.deepEqual(invalidated, [builder.loader.normalizeSync('new/path.js')]);
invalidated = builder.invalidate('deep/*.js');
assert.deepEqual(invalidated, [builder.loader.normalizeSync('deep/wildcard/test.js')]);
});
test('builder.loader.fetch sets load.metadata.timestamp', function() {
var source = 'export var p = 5;';
var builder = new Builder('test/output');
fs.writeFileSync('./test/output/timestamp-module.js', source);
var address = builder.loader.normalizeSync('./test/output/timestamp-module.js');
var load = { name: address, address: address, metadata: {} };
return builder.loader.fetch(load)
.then(function(text) {
//console.log(JSON.stringify(load));
assert(text == source); // true
assert(load.metadata.deps); // true
assert(load.metadata.timestamp); // false
})
});
test('Bundle example', function() {
var builder = new Builder('test/output');
fs.writeFileSync('./test/output/dynamic-module.js', 'export var p = 5;');
return builder.bundle('dynamic-module.js')
.then(function(output) {
assert(output.source.match(/p = 5/));
fs.writeFileSync('./test/output/dynamic-module.js', 'export var p = 6;');
builder.invalidate('dynamic-module.js');
return builder.bundle('dynamic-module.js');
})
.then(function(output) {
assert(output.source.match(/p = 6/));
});
});
test('Bundle example with imported file', function() {
var builder = new Builder('test/output');
fs.writeFileSync('./test/output/dynamic-import.js', [
'const d = 9;',
'export default d;'
].join('\n'));
fs.writeFileSync('./test/output/dynamic-main.js', [
'import d from "./dynamic-import.js";',
'console.log(d);'
].join('\n'));
return builder.bundle('dynamic-main.js')
.then(function(output) {
assert(output.source.match(/d = 9/));
assert(output.source.match(/console/));
fs.writeFileSync('./test/output/dynamic-import.js', [
'import "./dynamic-import2.js";', // Add another transitive dependency.
'const d = 7;',
'export default d;'
].join('\n'));
builder.invalidate('dynamic-import.js');
fs.writeFileSync('./test/output/dynamic-import2.js', [
'const u = "transitive";',
'export default u;'
].join('\n'));
return builder.bundle('dynamic-main.js');
})
.then(function(output) {
assert(output.source.match(/transitive/));
assert(output.source.match(/d = 7/));
assert(output.source.match(/console/));
// Remove the transitive dependency from the build.
fs.writeFileSync('./test/output/dynamic-import.js', [
'const d = 7;',
'export default d;'
].join('\n'));
builder.invalidate('dynamic-import.js');
return builder.bundle('dynamic-main.js');
})
.then(function(output) {
assert(!output.source.match(/transitive/));
});
});
test('Static build example statting check', function() {
var builder = new Builder('test/output');
fs.writeFileSync('./test/output/static-main.js', "import { testThing } from './static-test-module.js'; testThing();");
fs.writeFileSync('./test/output/static-test-module.js', "export function testThing() { console.log('test'); }");
return builder.buildStatic('static-main.js')
.then(function() {
builder.invalidate('static-main.js');
// despite removing the file, it remains cached
fs.unlinkSync('./test/output/static-test-module.js');
return builder.buildStatic('static-main.js');
});
});
test('Static build example dependency reload check', function() {
var builder = new Builder('test/output');
fs.writeFileSync('./test/output/static-main.js', "import { testThing } from './static-test-module.js'; testThing();");
fs.writeFileSync('./test/output/static-test-module.js', "export function testThing() { console.log('test'); }");
return builder.buildStatic('static-main.js')
.then(function() {
fs.writeFileSync('./test/output/static-test-module.js', "export function testThing() { console.log('new test'); }")
builder.invalidate('static-test-module.js');
return builder.buildStatic('static-main.js');
});
});
test('Static build, fetch override', function () {
var builder = new Builder('test/fixtures/test-tree');
return builder.buildStatic('foo.js', {
fetch: function (load, fetch) {
if (load.name.indexOf('foo.js') !== -1) {
return fs.readFileSync('test/fixtures/test-tree/cjs.js', 'utf8');
} else {
return fetch(load);
}
}
});
});
test('Static build, fetch override with callback', function () {
var builder = new Builder('test/fixtures/test-tree');
return builder.buildStatic('cjs.js', {
fetch: function (load, fetch) {
return fetch(load);
}
});
});
test('Static string build', function () {
var builder = new Builder('test/fixtures/test-tree');
return builder.bundle('foo.js', {
fetch: function (load, fetch) {
if (load.name.indexOf('foo.js') !== -1) {
return fs.readFileSync('test/fixtures/test-tree/cjs.js', 'utf8');
} else {
return fetch(load);
}
}
});
});
});
|
'use strict';
module.exports = {
isModuleUnificationProject(project) {
return project && project.isModuleUnification && project.isModuleUnification();
}
}; |
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
// import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// registerServiceWorker();
|
/*
Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.cometd.timestamp"]){dojo._hasResource["dojox.cometd.timestamp"]=true;dojo.provide("dojox.cometd.timestamp");dojo.require("dojox.cometd._base");dojox.cometd._extendOutList.push(function(_1){_1.timestamp=new Date().toUTCString();return _1;});} |
/*
YUI 3.8.0pr2 (build 154)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add("lang/datatype-date-format",function(e){e.Intl.add("datatype-date-format","",{a:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],A:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],b:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],B:["January","February","March","April","May","June","July","August","September","October","November","December"],c:"%Y-%m-%dT%H:%M:%S%z",p:["AM","PM"],P:["am","pm"],x:"%Y-%m-%d",X:"%H:%M:%S"})},"3.8.0pr2");
|
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Support: IE9
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "@VERSION",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler and self cleanup method
completed = function() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
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" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
// Support: Safari <= 5.1 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if ( obj.constructor &&
!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: JSON.parse,
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
trim: function( text ) {
return text == null ? "" : core_trim.call( text );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : core_indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: Date.now,
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
|
import { deprecate } from '@ember/application/deprecations';
import materializeRadios from './md-radios';
export default materializeRadios.extend({
init() {
this._super(...arguments);
deprecate('{{materialize-radios}} has been deprecated. Please use {{md-radios}} instead', false, {
url: 'https://github.com/sgasser/ember-cli-materialize/issues/67'
});
}
});
|
'use strict';
(function() {
// Cursos Controller Spec
describe('Cursos Controller Tests', function() {
// Initialize global variables
var CursosController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the Cursos controller.
CursosController = $controller('CursosController', {
$scope: scope
});
}));
it('$scope.find() should create an array with at least one Curso object fetched from XHR', inject(function(Cursos) {
// Create sample Curso using the Cursos service
var sampleCurso = new Cursos({
name: 'New Curso'
});
// Create a sample Cursos array that includes the new Curso
var sampleCursos = [sampleCurso];
// Set GET response
$httpBackend.expectGET('cursos').respond(sampleCursos);
// Run controller functionality
scope.find();
$httpBackend.flush();
// Test scope value
expect(scope.cursos).toEqualData(sampleCursos);
}));
it('$scope.findOne() should create an array with one Curso object fetched from XHR using a cursoId URL parameter', inject(function(Cursos) {
// Define a sample Curso object
var sampleCurso = new Cursos({
name: 'New Curso'
});
// Set the URL parameter
$stateParams.cursoId = '525a8422f6d0f87f0e407a33';
// Set GET response
$httpBackend.expectGET(/cursos\/([0-9a-fA-F]{24})$/).respond(sampleCurso);
// Run controller functionality
scope.findOne();
$httpBackend.flush();
// Test scope value
expect(scope.curso).toEqualData(sampleCurso);
}));
it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Cursos) {
// Create a sample Curso object
var sampleCursoPostData = new Cursos({
name: 'New Curso'
});
// Create a sample Curso response
var sampleCursoResponse = new Cursos({
_id: '525cf20451979dea2c000001',
name: 'New Curso'
});
// Fixture mock form input values
scope.name = 'New Curso';
// Set POST response
$httpBackend.expectPOST('cursos', sampleCursoPostData).respond(sampleCursoResponse);
// Run controller functionality
scope.create();
$httpBackend.flush();
// Test form inputs are reset
expect(scope.name).toEqual('');
// Test URL redirection after the Curso was created
expect($location.path()).toBe('/cursos/' + sampleCursoResponse._id);
}));
it('$scope.update() should update a valid Curso', inject(function(Cursos) {
// Define a sample Curso put data
var sampleCursoPutData = new Cursos({
_id: '525cf20451979dea2c000001',
name: 'New Curso'
});
// Mock Curso in scope
scope.curso = sampleCursoPutData;
// Set PUT response
$httpBackend.expectPUT(/cursos\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
scope.update();
$httpBackend.flush();
// Test URL location to new object
expect($location.path()).toBe('/cursos/' + sampleCursoPutData._id);
}));
it('$scope.remove() should send a DELETE request with a valid cursoId and remove the Curso from the scope', inject(function(Cursos) {
// Create new Curso object
var sampleCurso = new Cursos({
_id: '525a8422f6d0f87f0e407a33'
});
// Create new Cursos array and include the Curso
scope.cursos = [sampleCurso];
// Set expected DELETE response
$httpBackend.expectDELETE(/cursos\/([0-9a-fA-F]{24})$/).respond(204);
// Run controller functionality
scope.remove(sampleCurso);
$httpBackend.flush();
// Test array after successful delete
expect(scope.cursos.length).toBe(0);
}));
});
}()); |
/*!
* Bootstrap-select v1.13.6 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2019 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
!function(e,t){void 0===e&&void 0!==window&&(e=window),"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery")):t(e.jQuery)}(this,function(e){e.fn.selectpicker.defaults={noneSelectedText:"Niets geselecteerd",noneResultsText:"Geen resultaten gevonden voor {0}",countSelectedText:"{0} van {1} geselecteerd",maxOptionsText:["Limiet bereikt ({n} {var} max)","Groep limiet bereikt ({n} {var} max)",["items","item"]],selectAllText:"Alles selecteren",deselectAllText:"Alles deselecteren",multipleSeparator:", "}}); |
/*!
* jQuery JavaScript Library v1.10.1 -wrap,-offset
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-06-03T15:13Z
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<10
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.10.1 -wrap,-offset",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler
completed = function( event ) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
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" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( jQuery.support.ownLast ) {
for ( key in obj ) {
return core_hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
},
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
/*!
* Sizzle CSS Selector Engine v1.9.4-pre
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-05-27
*/
(function( window, undefined ) {
var i,
support,
cachedruns,
Expr,
getText,
isXML,
compile,
outermostContext,
sortInput,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
hasDuplicate = false,
sortOrder = function() { return 0; },
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rsibling = new RegExp( whitespace + "*[+~]" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied if the test fails
* @param {Boolean} test The result of a test. If true, null will be set as the handler in leiu of the specified handler
*/
function addHandle( attrs, handler, test ) {
attrs = attrs.split("|");
var current,
i = attrs.length,
setHandle = test ? null : handler;
while ( i-- ) {
// Don't override a user's handler
if ( !(current = Expr.attrHandle[ attrs[i] ]) || current === handler ) {
Expr.attrHandle[ attrs[i] ] = setHandle;
}
}
}
/**
* Fetches boolean attributes by node
* @param {Element} elem
* @param {String} name
*/
function boolHandler( elem, name ) {
// XML does not need to be checked as this will not be assigned for XML documents
var val = elem.getAttributeNode( name );
return val && val.specified ?
val.value :
elem[ name ] === true ? name.toLowerCase() : null;
}
/**
* Fetches attributes without interpolation
* http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
* @param {Element} elem
* @param {String} name
*/
function interpolationHandler( elem, name ) {
// XML does not need to be checked as this will not be assigned for XML documents
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
/**
* Uses defaultValue to retrieve value in IE6/7
* @param {Element} elem
* @param {String} name
*/
function valueHandler( elem ) {
// Ignore the value *property* on inputs by using defaultValue
// Fallback to Sizzle.attr by returning undefined where appropriate
// XML does not need to be checked as this will not be assigned for XML documents
if ( elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns Returns -1 if a precedes b, 1 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.parentWindow;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
if ( parent && parent.frameElement ) {
parent.attachEvent( "onbeforeunload", function() {
setDocument();
});
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
// Support: IE<8
// Prevent attribute/property "interpolation"
div.innerHTML = "<a href='#'></a>";
addHandle( "type|href|height|width", interpolationHandler, div.firstChild.getAttribute("href") === "#" );
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
addHandle( booleans, boolHandler, div.getAttribute("disabled") == null );
div.className = "i";
return !div.getAttribute("className");
});
// Support: IE<9
// Retrieving value should defer to defaultValue
support.input = assert(function( div ) {
div.innerHTML = "<input>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
});
// IE6/7 still return empty string for value,
// but are actually retrieving the property
addHandle( "value", valueHandler, support.attributes && support.input );
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Opera 10-12/IE8
// ^= $= *= and empty values
// Should not select anything
// Support: Windows 8 Native Apps
// The type attribute is restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "t", "" );
if ( div.querySelectorAll("[t^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( doc.createElement("div") ) & 1;
});
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
if ( compare ) {
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
}
// Not directly comparable, sort on existence of method
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = ( fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined );
return val === undefined ?
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null :
val;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] && match[4] !== undefined ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Initialize against the default document
setDocument();
// Support: Chrome<<14
// Always assume duplicates if they aren't passed to the comparison function
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function( support ) {
var all, a, input, select, fragment, opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Finish early in limited (non-browser) environments
all = div.getElementsByTagName("*") || [];
a = div.getElementsByTagName("a")[ 0 ];
if ( !a || !a.style || !all.length ) {
return support;
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName("tbody").length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName("link").length;
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute("href") === "/a";
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
support.opacity = /^0.5/.test( a.style.opacity );
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!a.style.cssFloat;
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Will be defined later
support.inlineBlockNeedsLayout = false;
support.shrinkWrapBlocks = false;
support.pixelPosition = false;
support.deleteExpando = true;
support.noCloneEvent = true;
support.reliableMarginRight = true;
support.boxSizingReliable = true;
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment = document.createDocumentFragment();
fragment.appendChild( input );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
for ( i in { submit: true, change: true, focusin: true }) {
div.setAttribute( eventName = "on" + i, "t" );
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Support: IE<9
// Iteration over object's inherited properties before its own.
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild( container ).appendChild( div );
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior.
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
// Workaround failing boxSizing test due to offsetWidth returning wrong value
// with some non-1 values of body zoom, ticket #13543
jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
support.boxSizing = div.offsetWidth === 4;
});
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if ( support.inlineBlockNeedsLayout ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})({});
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"applet": true,
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
data = null,
i = 0,
elem = this[0];
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[i].name;
if ( name.indexOf("data-") === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n\f]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// Use proper attribute retrieval(#6932, #12072)
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
jQuery.expr.attrHandle[ name ] = fn;
return ret;
} :
function( elem, name, isXML ) {
return isXML ?
undefined :
elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords =
// Some attributes are constructed with empty-string values when not defined
function( elem, name, isXML ) {
var ret;
return isXML ?
undefined :
(ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
};
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ret.specified ?
ret.value :
undefined;
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !jQuery.support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === core_strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var isSimple = /^.[^:#\[\.,]*$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
cur = ret.push( cur );
break;
}
}
}
return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( isSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var
// Snapshot the DOM in case .domManip sweeps something relevant into its fragment
args = jQuery.map( this, function( elem ) {
return [ elem.nextSibling, elem.parentNode ];
}),
i = 0;
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
var next = args[ i++ ],
parent = args[ i++ ];
if ( parent ) {
// Don't use the snapshot next if it has moved (#13810)
if ( next && next.parentNode !== parent ) {
next = this.nextSibling;
}
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
// Allow new content to include elements from the context set
}, true );
// Force removal if there was no new content (e.g., from empty arguments)
return i ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback, allowIntersection ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, self.html() );
}
self.domManip( args, callback, allowIntersection );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[i], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== core_strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
}
}
}
}
},
_evalUrl: function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
}
});
var iframe, getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
var len, styles,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
var bool = typeof state === "boolean";
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, _computed ) {
var left, rs, rsLeft,
computed = _computed || getStyles( elem ),
ret = computed ? computed[ name ] : undefined,
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
jQuery.fn[ type ] = function( fn ){
return this.on( type, fn );
};
});
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
// Otherwise add one to the end
cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
var xhrCallbacks, xhrSupported,
xhrId = 0,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject && function() {
// Abort all pending requests
var key;
for ( key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
};
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
xhrSupported = jQuery.ajaxSettings.xhr();
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = jQuery.support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( err ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, responseHeaders, statusText, responses;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) ) {
jQuery.fx.start();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Limit scope pollution from any deprecated API
// (function() {
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// })();
if ( typeof module === "object" && module && typeof module.exports === "object" ) {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
} else {
// Otherwise expose jQuery to the global object as usual
window.jQuery = window.$ = jQuery;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function () { return jQuery; } );
}
}
})( window );
|
'use strict';
const config = {
nitro: {
patterns: {
atom: {
template: 'project/blueprints/pattern',
path: 'src/patterns/atoms',
patternPrefix: 'a',
},
molecule: {
template: 'project/blueprints/pattern',
path: 'src/patterns/molecules',
patternPrefix: 'm',
},
organism: {
template: 'project/blueprints/pattern',
path: 'src/patterns/organisms',
patternPrefix: 'o',
},
},
},
};
module.exports = config.nitro.patterns;
|
// Description:
// Ask a question of the form 'should we ...'
//
// Dependencies:
// None
//
// Configuration:
// None
//
// Commands:
// hubot should we <query>
// hubot should I <query>
//
// Author:
// andyroyle
var responses = [
'It is certain',
'It is decidedly so',
'Without a doubt',
'Yes definitely',
'You may rely on it',
'As I see it, yes',
'Most likely',
'Outlook good',
'Yes',
'Signs point to yes',
'Reply hazy try again',
'Ask again later',
'Better not tell you now',
'Cannot predict now',
'Concentrate and ask again',
'Don\'t count on it',
'My reply is no',
'My sources say no',
'Outlook not so good',
'Very doubtful'
]
module.exports = function(robot){
logger = robot.logger;
robot.respond(/should we (.*)/i, function(msg){
msg.send(getRandom())
});
robot.respond(/should I (.*)/i, function(msg){
msg.reply(getRandom())
});
};
var getRandom = function(){
return responses[Math.floor(Math.random() * responses.length)];
}; |
/**
* ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v19.1.3
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
var gridOptionsWrapper_1 = require("./gridOptionsWrapper");
var columnController_1 = require("./columnController/columnController");
var eventService_1 = require("./eventService");
var logger_1 = require("./logger");
var events_1 = require("./events");
var context_1 = require("./context/context");
var context_2 = require("./context/context");
var context_3 = require("./context/context");
var context_4 = require("./context/context");
var AlignedGridsService = /** @class */ (function () {
function AlignedGridsService() {
// flag to mark if we are consuming. to avoid cyclic events (ie other grid firing back to master
// while processing a master event) we mark this if consuming an event, and if we are, then
// we don't fire back any events.
this.consuming = false;
}
AlignedGridsService.prototype.setBeans = function (loggerFactory) {
this.logger = loggerFactory.create('AlignedGridsService');
};
AlignedGridsService.prototype.registerGridComp = function (gridPanel) {
this.gridPanel = gridPanel;
};
AlignedGridsService.prototype.init = function () {
this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_MOVED, this.fireColumnEvent.bind(this));
this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_VISIBLE, this.fireColumnEvent.bind(this));
this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_PINNED, this.fireColumnEvent.bind(this));
this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_GROUP_OPENED, this.fireColumnEvent.bind(this));
this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_RESIZED, this.fireColumnEvent.bind(this));
this.eventService.addEventListener(events_1.Events.EVENT_BODY_SCROLL, this.fireScrollEvent.bind(this));
};
// common logic across all the fire methods
AlignedGridsService.prototype.fireEvent = function (callback) {
// if we are already consuming, then we are acting on an event from a master,
// so we don't cause a cyclic firing of events
if (this.consuming) {
return;
}
// iterate through the aligned grids, and pass each aligned grid service to the callback
var otherGrids = this.gridOptionsWrapper.getAlignedGrids();
if (otherGrids) {
otherGrids.forEach(function (otherGridOptions) {
if (otherGridOptions.api) {
var alignedGridService = otherGridOptions.api.__getAlignedGridService();
callback(alignedGridService);
}
});
}
};
// common logic across all consume methods. very little common logic, however extracting
// guarantees consistency across the methods.
AlignedGridsService.prototype.onEvent = function (callback) {
this.consuming = true;
callback();
this.consuming = false;
};
AlignedGridsService.prototype.fireColumnEvent = function (event) {
this.fireEvent(function (alignedGridsService) {
alignedGridsService.onColumnEvent(event);
});
};
AlignedGridsService.prototype.fireScrollEvent = function (event) {
if (event.direction !== 'horizontal') {
return;
}
this.fireEvent(function (alignedGridsService) {
alignedGridsService.onScrollEvent(event);
});
};
AlignedGridsService.prototype.onScrollEvent = function (event) {
var _this = this;
this.onEvent(function () {
_this.gridPanel.setHorizontalScrollPosition(event.left);
});
};
AlignedGridsService.prototype.getMasterColumns = function (event) {
var result = [];
if (event.columns) {
event.columns.forEach(function (column) {
result.push(column);
});
}
else if (event.column) {
result.push(event.column);
}
return result;
};
AlignedGridsService.prototype.getColumnIds = function (event) {
var result = [];
if (event.columns) {
event.columns.forEach(function (column) {
result.push(column.getColId());
});
}
else if (event.columns) {
result.push(event.column.getColId());
}
return result;
};
AlignedGridsService.prototype.onColumnEvent = function (event) {
var _this = this;
this.onEvent(function () {
switch (event.type) {
case events_1.Events.EVENT_COLUMN_MOVED:
case events_1.Events.EVENT_COLUMN_VISIBLE:
case events_1.Events.EVENT_COLUMN_PINNED:
case events_1.Events.EVENT_COLUMN_RESIZED:
var colEvent = event;
_this.processColumnEvent(colEvent);
break;
case events_1.Events.EVENT_COLUMN_GROUP_OPENED:
var groupOpenedEvent = event;
_this.processGroupOpenedEvent(groupOpenedEvent);
break;
case events_1.Events.EVENT_COLUMN_PIVOT_CHANGED:
// we cannot support pivoting with aligned grids as the columns will be out of sync as the
// grids will have columns created based on the row data of the grid.
console.warn('ag-Grid: pivoting is not supported with aligned grids. ' +
'You can only use one of these features at a time in a grid.');
break;
}
});
};
AlignedGridsService.prototype.processGroupOpenedEvent = function (groupOpenedEvent) {
// likewise for column group
var masterColumnGroup = groupOpenedEvent.columnGroup;
var otherColumnGroup = undefined;
if (masterColumnGroup) {
var groupId = masterColumnGroup.getGroupId();
otherColumnGroup = this.columnController.getOriginalColumnGroup(groupId);
}
if (masterColumnGroup && !otherColumnGroup) {
return;
}
this.logger.log('onColumnEvent-> processing ' + groupOpenedEvent + ' expanded = ' + masterColumnGroup.isExpanded());
this.columnController.setColumnGroupOpened(otherColumnGroup, masterColumnGroup.isExpanded(), "alignedGridChanged");
};
AlignedGridsService.prototype.processColumnEvent = function (colEvent) {
var _this = this;
// the column in the event is from the master grid. need to
// look up the equivalent from this (other) grid
var masterColumn = colEvent.column;
var otherColumn = undefined;
if (masterColumn) {
otherColumn = this.columnController.getPrimaryColumn(masterColumn.getColId());
}
// if event was with respect to a master column, that is not present in this
// grid, then we ignore the event
if (masterColumn && !otherColumn) {
return;
}
// in time, all the methods below should use the column ids, it's a more generic way
// of handling columns, and also allows for single or multi column events
var columnIds = this.getColumnIds(colEvent);
var masterColumns = this.getMasterColumns(colEvent);
switch (colEvent.type) {
case events_1.Events.EVENT_COLUMN_MOVED:
var movedEvent = colEvent;
this.logger.log("onColumnEvent-> processing " + colEvent.type + " toIndex = " + movedEvent.toIndex);
this.columnController.moveColumns(columnIds, movedEvent.toIndex, "alignedGridChanged");
break;
case events_1.Events.EVENT_COLUMN_VISIBLE:
var visibleEvent = colEvent;
this.logger.log("onColumnEvent-> processing " + colEvent.type + " visible = " + visibleEvent.visible);
this.columnController.setColumnsVisible(columnIds, visibleEvent.visible, "alignedGridChanged");
break;
case events_1.Events.EVENT_COLUMN_PINNED:
var pinnedEvent = colEvent;
this.logger.log("onColumnEvent-> processing " + colEvent.type + " pinned = " + pinnedEvent.pinned);
this.columnController.setColumnsPinned(columnIds, pinnedEvent.pinned, "alignedGridChanged");
break;
case events_1.Events.EVENT_COLUMN_RESIZED:
var resizedEvent_1 = colEvent;
masterColumns.forEach(function (column) {
_this.logger.log("onColumnEvent-> processing " + colEvent.type + " actualWidth = " + column.getActualWidth());
_this.columnController.setColumnWidth(column.getColId(), column.getActualWidth(), false, resizedEvent_1.finished, "alignedGridChanged");
});
break;
}
};
__decorate([
context_3.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], AlignedGridsService.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_3.Autowired('columnController'),
__metadata("design:type", columnController_1.ColumnController)
], AlignedGridsService.prototype, "columnController", void 0);
__decorate([
context_3.Autowired('eventService'),
__metadata("design:type", eventService_1.EventService)
], AlignedGridsService.prototype, "eventService", void 0);
__decorate([
__param(0, context_2.Qualifier('loggerFactory')),
__metadata("design:type", Function),
__metadata("design:paramtypes", [logger_1.LoggerFactory]),
__metadata("design:returntype", void 0)
], AlignedGridsService.prototype, "setBeans", null);
__decorate([
context_4.PostConstruct,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], AlignedGridsService.prototype, "init", null);
AlignedGridsService = __decorate([
context_1.Bean('alignedGridsService')
], AlignedGridsService);
return AlignedGridsService;
}());
exports.AlignedGridsService = AlignedGridsService;
|
/**
* @license
* v1.2.10-1
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2019 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https://github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issues
*/
import { mergeMaps, objectToMap, jsS, PnPClientStorage } from '@pnp/common';
/**
* Class used to manage the current application settings
*
*/
class Settings {
/**
* Creates a new instance of the settings class
*
* @constructor
*/
constructor(_settings = new Map()) {
this._settings = _settings;
}
/**
* Adds a new single setting, or overwrites a previous setting with the same key
*
* @param {string} key The key used to store this setting
* @param {string} value The setting value to store
*/
add(key, value) {
this._settings.set(key, value);
}
/**
* Adds a JSON value to the collection as a string, you must use getJSON to rehydrate the object when read
*
* @param {string} key The key used to store this setting
* @param {any} value The setting value to store
*/
addJSON(key, value) {
this._settings.set(key, jsS(value));
}
/**
* Applies the supplied hash to the setting collection overwriting any existing value, or created new values
*
* @param {TypedHash<any>} hash The set of values to add
*/
apply(hash) {
return new Promise((resolve, reject) => {
try {
this._settings = mergeMaps(this._settings, objectToMap(hash));
resolve();
}
catch (e) {
reject(e);
}
});
}
/**
* Loads configuration settings into the collection from the supplied provider and returns a Promise
*
* @param {IConfigurationProvider} provider The provider from which we will load the settings
*/
load(provider) {
return new Promise((resolve, reject) => {
provider.getConfiguration().then((value) => {
this._settings = mergeMaps(this._settings, objectToMap(value));
resolve();
}).catch(reject);
});
}
/**
* Gets a value from the configuration
*
* @param {string} key The key whose value we want to return. Returns null if the key does not exist
* @return {string} string value from the configuration
*/
get(key) {
return this._settings.get(key) || null;
}
/**
* Gets a JSON value, rehydrating the stored string to the original object
*
* @param {string} key The key whose value we want to return. Returns null if the key does not exist
* @return {any} object from the configuration
*/
getJSON(key) {
const o = this.get(key);
if (o === undefined || o === null) {
return o;
}
return JSON.parse(o);
}
}
/**
* A caching provider which can wrap other non-caching providers
*
*/
class CachingConfigurationProvider {
/**
* Creates a new caching configuration provider
* @constructor
* @param {IConfigurationProvider} wrappedProvider Provider which will be used to fetch the configuration
* @param {string} cacheKey Key that will be used to store cached items to the cache
* @param {IPnPClientStore} cacheStore OPTIONAL storage, which will be used to store cached settings.
*/
constructor(wrappedProvider, cacheKey, cacheStore) {
this.wrappedProvider = wrappedProvider;
this.cacheKey = cacheKey;
this.wrappedProvider = wrappedProvider;
this.store = (cacheStore) ? cacheStore : this.selectPnPCache();
}
/**
* Gets the wrapped configuration providers
*
* @return {IConfigurationProvider} Wrapped configuration provider
*/
getWrappedProvider() {
return this.wrappedProvider;
}
/**
* Loads the configuration values either from the cache or from the wrapped provider
*
* @return {Promise<TypedHash<string>>} Promise of loaded configuration values
*/
getConfiguration() {
// Cache not available, pass control to the wrapped provider
if ((!this.store) || (!this.store.enabled)) {
return this.wrappedProvider.getConfiguration();
}
return this.store.getOrPut(this.cacheKey, () => {
return this.wrappedProvider.getConfiguration().then((providedConfig) => {
this.store.put(this.cacheKey, providedConfig);
return providedConfig;
});
});
}
selectPnPCache() {
const pnpCache = new PnPClientStorage();
if ((pnpCache.local) && (pnpCache.local.enabled)) {
return pnpCache.local;
}
if ((pnpCache.session) && (pnpCache.session.enabled)) {
return pnpCache.session;
}
throw Error("Cannot create a caching configuration provider since cache is not available.");
}
}
/**
* A configuration provider which loads configuration values from a SharePoint list
*
*/
class SPListConfigurationProvider {
/**
* Creates a new SharePoint list based configuration provider
* @constructor
* @param {string} webUrl Url of the SharePoint site, where the configuration list is located
* @param {string} listTitle Title of the SharePoint list, which contains the configuration settings (optional, default: "config")
* @param {string} keyFieldName The name of the field in the list to use as the setting key (optional, default: "Title")
* @param {string} valueFieldName The name of the field in the list to use as the setting value (optional, default: "Value")
*/
constructor(web, listTitle = "config", keyFieldName = "Title", valueFieldName = "Value") {
this.web = web;
this.listTitle = listTitle;
this.keyFieldName = keyFieldName;
this.valueFieldName = valueFieldName;
}
/**
* Loads the configuration values from the SharePoint list
*
* @return {Promise<TypedHash<string>>} Promise of loaded configuration values
*/
getConfiguration() {
return this.web.lists.getByTitle(this.listTitle).items.select(this.keyFieldName, this.valueFieldName).get()
.then((data) => data.reduce((c, item) => {
c[item[this.keyFieldName]] = item[this.valueFieldName];
return c;
}, {}));
}
/**
* Wraps the current provider in a cache enabled provider
*
* @return {CachingConfigurationProvider} Caching providers which wraps the current provider
*/
asCaching(cacheKey = `pnp_configcache_splist_${this.web.toUrl()}+${this.listTitle}`) {
return new CachingConfigurationProvider(this, cacheKey);
}
}
export { Settings, CachingConfigurationProvider, SPListConfigurationProvider };
//# sourceMappingURL=config-store.js.map
|
/*!
* OOUI v0.29.6
* https://www.mediawiki.org/wiki/OOUI
*
* Copyright 2011โ2018 OOUI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2018-12-05T00:15:55Z
*/
( function ( OO ) {
'use strict';
/**
* Namespace for all classes, static methods and static properties.
*
* @class
* @singleton
*/
OO.ui = {};
OO.ui.bind = $.proxy;
/**
* @property {Object}
*/
OO.ui.Keys = {
UNDEFINED: 0,
BACKSPACE: 8,
DELETE: 46,
LEFT: 37,
RIGHT: 39,
UP: 38,
DOWN: 40,
ENTER: 13,
END: 35,
HOME: 36,
TAB: 9,
PAGEUP: 33,
PAGEDOWN: 34,
ESCAPE: 27,
SHIFT: 16,
SPACE: 32
};
/**
* Constants for MouseEvent.which
*
* @property {Object}
*/
OO.ui.MouseButtons = {
LEFT: 1,
MIDDLE: 2,
RIGHT: 3
};
/**
* @property {number}
* @private
*/
OO.ui.elementId = 0;
/**
* Generate a unique ID for element
*
* @return {string} ID
*/
OO.ui.generateElementId = function () {
OO.ui.elementId++;
return 'ooui-' + OO.ui.elementId;
};
/**
* Check if an element is focusable.
* Inspired by :focusable in jQueryUI v1.11.4 - 2015-04-14
*
* @param {jQuery} $element Element to test
* @return {boolean} Element is focusable
*/
OO.ui.isFocusableElement = function ( $element ) {
var nodeName,
element = $element[ 0 ];
// Anything disabled is not focusable
if ( element.disabled ) {
return false;
}
// Check if the element is visible
if ( !(
// This is quicker than calling $element.is( ':visible' )
$.expr.pseudos.visible( element ) &&
// Check that all parents are visible
!$element.parents().addBack().filter( function () {
return $.css( this, 'visibility' ) === 'hidden';
} ).length
) ) {
return false;
}
// Check if the element is ContentEditable, which is the string 'true'
if ( element.contentEditable === 'true' ) {
return true;
}
// Anything with a non-negative numeric tabIndex is focusable.
// Use .prop to avoid browser bugs
if ( $element.prop( 'tabIndex' ) >= 0 ) {
return true;
}
// Some element types are naturally focusable
// (indexOf is much faster than regex in Chrome and about the
// same in FF: https://jsperf.com/regex-vs-indexof-array2)
nodeName = element.nodeName.toLowerCase();
if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) {
return true;
}
// Links and areas are focusable if they have an href
if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) {
return true;
}
return false;
};
/**
* Find a focusable child
*
* @param {jQuery} $container Container to search in
* @param {boolean} [backwards] Search backwards
* @return {jQuery} Focusable child, or an empty jQuery object if none found
*/
OO.ui.findFocusable = function ( $container, backwards ) {
var $focusable = $( [] ),
// $focusableCandidates is a superset of things that
// could get matched by isFocusableElement
$focusableCandidates = $container
.find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
if ( backwards ) {
$focusableCandidates = Array.prototype.reverse.call( $focusableCandidates );
}
$focusableCandidates.each( function () {
var $this = $( this );
if ( OO.ui.isFocusableElement( $this ) ) {
$focusable = $this;
return false;
}
} );
return $focusable;
};
/**
* Get the user's language and any fallback languages.
*
* These language codes are used to localize user interface elements in the user's language.
*
* In environments that provide a localization system, this function should be overridden to
* return the user's language(s). The default implementation returns English (en) only.
*
* @return {string[]} Language codes, in descending order of priority
*/
OO.ui.getUserLanguages = function () {
return [ 'en' ];
};
/**
* Get a value in an object keyed by language code.
*
* @param {Object.<string,Mixed>} obj Object keyed by language code
* @param {string|null} [lang] Language code, if omitted or null defaults to any user language
* @param {string} [fallback] Fallback code, used if no matching language can be found
* @return {Mixed} Local value
*/
OO.ui.getLocalValue = function ( obj, lang, fallback ) {
var i, len, langs;
// Requested language
if ( obj[ lang ] ) {
return obj[ lang ];
}
// Known user language
langs = OO.ui.getUserLanguages();
for ( i = 0, len = langs.length; i < len; i++ ) {
lang = langs[ i ];
if ( obj[ lang ] ) {
return obj[ lang ];
}
}
// Fallback language
if ( obj[ fallback ] ) {
return obj[ fallback ];
}
// First existing language
for ( lang in obj ) {
return obj[ lang ];
}
return undefined;
};
/**
* Check if a node is contained within another node
*
* Similar to jQuery#contains except a list of containers can be supplied
* and a boolean argument allows you to include the container in the match list
*
* @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
* @param {HTMLElement} contained Node to find
* @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
* @return {boolean} The node is in the list of target nodes
*/
OO.ui.contains = function ( containers, contained, matchContainers ) {
var i;
if ( !Array.isArray( containers ) ) {
containers = [ containers ];
}
for ( i = containers.length - 1; i >= 0; i-- ) {
if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
return true;
}
}
return false;
};
/**
* Return a function, that, as long as it continues to be invoked, will not
* be triggered. The function will be called after it stops being called for
* N milliseconds. If `immediate` is passed, trigger the function on the
* leading edge, instead of the trailing.
*
* Ported from: http://underscorejs.org/underscore.js
*
* @param {Function} func Function to debounce
* @param {number} [wait=0] Wait period in milliseconds
* @param {boolean} [immediate] Trigger on leading edge
* @return {Function} Debounced function
*/
OO.ui.debounce = function ( func, wait, immediate ) {
var timeout;
return function () {
var context = this,
args = arguments,
later = function () {
timeout = null;
if ( !immediate ) {
func.apply( context, args );
}
};
if ( immediate && !timeout ) {
func.apply( context, args );
}
if ( !timeout || wait ) {
clearTimeout( timeout );
timeout = setTimeout( later, wait );
}
};
};
/**
* Puts a console warning with provided message.
*
* @param {string} message Message
*/
OO.ui.warnDeprecation = function ( message ) {
if ( OO.getProp( window, 'console', 'warn' ) !== undefined ) {
// eslint-disable-next-line no-console
console.warn( message );
}
};
/**
* Returns a function, that, when invoked, will only be triggered at most once
* during a given window of time. If called again during that window, it will
* wait until the window ends and then trigger itself again.
*
* As it's not knowable to the caller whether the function will actually run
* when the wrapper is called, return values from the function are entirely
* discarded.
*
* @param {Function} func Function to throttle
* @param {number} wait Throttle window length, in milliseconds
* @return {Function} Throttled function
*/
OO.ui.throttle = function ( func, wait ) {
var context, args, timeout,
previous = 0,
run = function () {
timeout = null;
previous = OO.ui.now();
func.apply( context, args );
};
return function () {
// Check how long it's been since the last time the function was
// called, and whether it's more or less than the requested throttle
// period. If it's less, run the function immediately. If it's more,
// set a timeout for the remaining time -- but don't replace an
// existing timeout, since that'd indefinitely prolong the wait.
var remaining = wait - ( OO.ui.now() - previous );
context = this;
args = arguments;
if ( remaining <= 0 ) {
// Note: unless wait was ridiculously large, this means we'll
// automatically run the first time the function was called in a
// given period. (If you provide a wait period larger than the
// current Unix timestamp, you *deserve* unexpected behavior.)
clearTimeout( timeout );
run();
} else if ( !timeout ) {
timeout = setTimeout( run, remaining );
}
};
};
/**
* A (possibly faster) way to get the current timestamp as an integer
*
* @return {number} Current timestamp, in milliseconds since the Unix epoch
*/
OO.ui.now = Date.now || function () {
return new Date().getTime();
};
/**
* Reconstitute a JavaScript object corresponding to a widget created by
* the PHP implementation.
*
* This is an alias for `OO.ui.Element.static.infuse()`.
*
* @param {string|HTMLElement|jQuery} idOrNode
* A DOM id (if a string) or node for the widget to infuse.
* @param {Object} [config] Configuration options
* @return {OO.ui.Element}
* The `OO.ui.Element` corresponding to this (infusable) document node.
*/
OO.ui.infuse = function ( idOrNode, config ) {
return OO.ui.Element.static.infuse( idOrNode, config );
};
( function () {
/**
* Message store for the default implementation of OO.ui.msg
*
* Environments that provide a localization system should not use this, but should override
* OO.ui.msg altogether.
*
* @private
*/
var messages = {
// Tool tip for a button that moves items in a list down one place
'ooui-outline-control-move-down': 'Move item down',
// Tool tip for a button that moves items in a list up one place
'ooui-outline-control-move-up': 'Move item up',
// Tool tip for a button that removes items from a list
'ooui-outline-control-remove': 'Remove item',
// Label for the toolbar group that contains a list of all other available tools
'ooui-toolbar-more': 'More',
// Label for the fake tool that expands the full list of tools in a toolbar group
'ooui-toolgroup-expand': 'More',
// Label for the fake tool that collapses the full list of tools in a toolbar group
'ooui-toolgroup-collapse': 'Fewer',
// Default label for the tooltip for the button that removes a tag item
'ooui-item-remove': 'Remove',
// Default label for the accept button of a confirmation dialog
'ooui-dialog-message-accept': 'OK',
// Default label for the reject button of a confirmation dialog
'ooui-dialog-message-reject': 'Cancel',
// Title for process dialog error description
'ooui-dialog-process-error': 'Something went wrong',
// Label for process dialog dismiss error button, visible when describing errors
'ooui-dialog-process-dismiss': 'Dismiss',
// Label for process dialog retry action button, visible when describing only recoverable errors
'ooui-dialog-process-retry': 'Try again',
// Label for process dialog retry action button, visible when describing only warnings
'ooui-dialog-process-continue': 'Continue',
// Label for the file selection widget's select file button
'ooui-selectfile-button-select': 'Select a file',
// Label for the file selection widget if file selection is not supported
'ooui-selectfile-not-supported': 'File selection is not supported',
// Label for the file selection widget when no file is currently selected
'ooui-selectfile-placeholder': 'No file is selected',
// Label for the file selection widget's drop target
'ooui-selectfile-dragdrop-placeholder': 'Drop file here',
// Label for the help icon attached to a form field
'ooui-field-help': 'Help'
};
/**
* Get a localized message.
*
* After the message key, message parameters may optionally be passed. In the default implementation,
* any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
* Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
* they support unnamed, ordered message parameters.
*
* In environments that provide a localization system, this function should be overridden to
* return the message translated in the user's language. The default implementation always returns
* English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
* follows.
*
* @example
* var i, iLen, button,
* messagePath = 'oojs-ui/dist/i18n/',
* languages = [ $.i18n().locale, 'ur', 'en' ],
* languageMap = {};
*
* for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
* languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
* }
*
* $.i18n().load( languageMap ).done( function() {
* // Replace the built-in `msg` only once we've loaded the internationalization.
* // OOUI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
* // you put off creating any widgets until this promise is complete, no English
* // will be displayed.
* OO.ui.msg = $.i18n;
*
* // A button displaying "OK" in the default locale
* button = new OO.ui.ButtonWidget( {
* label: OO.ui.msg( 'ooui-dialog-message-accept' ),
* icon: 'check'
* } );
* $( 'body' ).append( button.$element );
*
* // A button displaying "OK" in Urdu
* $.i18n().locale = 'ur';
* button = new OO.ui.ButtonWidget( {
* label: OO.ui.msg( 'ooui-dialog-message-accept' ),
* icon: 'check'
* } );
* $( 'body' ).append( button.$element );
* } );
*
* @param {string} key Message key
* @param {...Mixed} [params] Message parameters
* @return {string} Translated message with parameters substituted
*/
OO.ui.msg = function ( key ) {
var message = messages[ key ],
params = Array.prototype.slice.call( arguments, 1 );
if ( typeof message === 'string' ) {
// Perform $1 substitution
message = message.replace( /\$(\d+)/g, function ( unused, n ) {
var i = parseInt( n, 10 );
return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
} );
} else {
// Return placeholder if message not found
message = '[' + key + ']';
}
return message;
};
}() );
/**
* Package a message and arguments for deferred resolution.
*
* Use this when you are statically specifying a message and the message may not yet be present.
*
* @param {string} key Message key
* @param {...Mixed} [params] Message parameters
* @return {Function} Function that returns the resolved message when executed
*/
OO.ui.deferMsg = function () {
var args = arguments;
return function () {
return OO.ui.msg.apply( OO.ui, args );
};
};
/**
* Resolve a message.
*
* If the message is a function it will be executed, otherwise it will pass through directly.
*
* @param {Function|string} msg Deferred message, or message text
* @return {string} Resolved message
*/
OO.ui.resolveMsg = function ( msg ) {
if ( typeof msg === 'function' ) {
return msg();
}
return msg;
};
/**
* @param {string} url
* @return {boolean}
*/
OO.ui.isSafeUrl = function ( url ) {
// Keep this function in sync with php/Tag.php
var i, protocolWhitelist;
function stringStartsWith( haystack, needle ) {
return haystack.substr( 0, needle.length ) === needle;
}
protocolWhitelist = [
'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
];
if ( url === '' ) {
return true;
}
for ( i = 0; i < protocolWhitelist.length; i++ ) {
if ( stringStartsWith( url, protocolWhitelist[ i ] + ':' ) ) {
return true;
}
}
// This matches '//' too
if ( stringStartsWith( url, '/' ) || stringStartsWith( url, './' ) ) {
return true;
}
if ( stringStartsWith( url, '?' ) || stringStartsWith( url, '#' ) ) {
return true;
}
return false;
};
/**
* Check if the user has a 'mobile' device.
*
* For our purposes this means the user is primarily using an
* on-screen keyboard, touch input instead of a mouse and may
* have a physically small display.
*
* It is left up to implementors to decide how to compute this
* so the default implementation always returns false.
*
* @return {boolean} User is on a mobile device
*/
OO.ui.isMobile = function () {
return false;
};
/**
* Get the additional spacing that should be taken into account when displaying elements that are
* clipped to the viewport, e.g. dropdown menus and popups. This is meant to be overridden to avoid
* such menus overlapping any fixed headers/toolbars/navigation used by the site.
*
* @return {Object} Object with the properties 'top', 'right', 'bottom', 'left', each representing
* the extra spacing from that edge of viewport (in pixels)
*/
OO.ui.getViewportSpacing = function () {
return {
top: 0,
right: 0,
bottom: 0,
left: 0
};
};
/**
* Get the default overlay, which is used by various widgets when they are passed `$overlay: true`.
* See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
*
* @return {jQuery} Default overlay node
*/
OO.ui.getDefaultOverlay = function () {
if ( !OO.ui.$defaultOverlay ) {
OO.ui.$defaultOverlay = $( '<div>' ).addClass( 'oo-ui-defaultOverlay' );
$( 'body' ).append( OO.ui.$defaultOverlay );
}
return OO.ui.$defaultOverlay;
};
/*!
* Mixin namespace.
*/
/**
* Namespace for OOUI mixins.
*
* Mixins are named according to the type of object they are intended to
* be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
* mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
* is intended to be mixed in to an instance of OO.ui.Widget.
*
* @class
* @singleton
*/
OO.ui.mixin = {};
/**
* Each Element represents a rendering in the DOMโa button or an icon, for example, or anything
* that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
* connected to them and can't be interacted with.
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
* to the top level (e.g., the outermost div) of the element. See the [OOUI documentation on MediaWiki][2]
* for an example.
* [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#cssExample
* @cfg {string} [id] The HTML id attribute used in the rendered tag.
* @cfg {string} [text] Text to insert
* @cfg {Array} [content] An array of content elements to append (after #text).
* Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
* Instances of OO.ui.Element will have their $element appended.
* @cfg {jQuery} [$content] Content elements to append (after #text).
* @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
* @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
* Data can also be specified with the #setData method.
*/
OO.ui.Element = function OoUiElement( config ) {
if ( OO.ui.isDemo ) {
this.initialConfig = config;
}
// Configuration initialization
config = config || {};
// Properties
this.$ = $;
this.elementId = null;
this.visible = true;
this.data = config.data;
this.$element = config.$element ||
$( document.createElement( this.getTagName() ) );
this.elementGroup = null;
// Initialization
if ( Array.isArray( config.classes ) ) {
this.$element.addClass( config.classes );
}
if ( config.id ) {
this.setElementId( config.id );
}
if ( config.text ) {
this.$element.text( config.text );
}
if ( config.content ) {
// The `content` property treats plain strings as text; use an
// HtmlSnippet to append HTML content. `OO.ui.Element`s get their
// appropriate $element appended.
this.$element.append( config.content.map( function ( v ) {
if ( typeof v === 'string' ) {
// Escape string so it is properly represented in HTML.
return document.createTextNode( v );
} else if ( v instanceof OO.ui.HtmlSnippet ) {
// Bypass escaping.
return v.toString();
} else if ( v instanceof OO.ui.Element ) {
return v.$element;
}
return v;
} ) );
}
if ( config.$content ) {
// The `$content` property treats plain strings as HTML.
this.$element.append( config.$content );
}
};
/* Setup */
OO.initClass( OO.ui.Element );
/* Static Properties */
/**
* The name of the HTML tag used by the element.
*
* The static value may be ignored if the #getTagName method is overridden.
*
* @static
* @inheritable
* @property {string}
*/
OO.ui.Element.static.tagName = 'div';
/* Static Methods */
/**
* Reconstitute a JavaScript object corresponding to a widget created
* by the PHP implementation.
*
* @param {string|HTMLElement|jQuery} idOrNode
* A DOM id (if a string) or node for the widget to infuse.
* @param {Object} [config] Configuration options
* @return {OO.ui.Element}
* The `OO.ui.Element` corresponding to this (infusable) document node.
* For `Tag` objects emitted on the HTML side (used occasionally for content)
* the value returned is a newly-created Element wrapping around the existing
* DOM node.
*/
OO.ui.Element.static.infuse = function ( idOrNode, config ) {
var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, config, false );
// Verify that the type matches up.
// FIXME: uncomment after T89721 is fixed, see T90929.
/*
if ( !( obj instanceof this['class'] ) ) {
throw new Error( 'Infusion type mismatch!' );
}
*/
return obj;
};
/**
* Implementation helper for `infuse`; skips the type check and has an
* extra property so that only the top-level invocation touches the DOM.
*
* @private
* @param {string|HTMLElement|jQuery} idOrNode
* @param {Object} [config] Configuration options
* @param {jQuery.Promise} [domPromise] A promise that will be resolved
* when the top-level widget of this infusion is inserted into DOM,
* replacing the original node; only used internally.
* @return {OO.ui.Element}
*/
OO.ui.Element.static.unsafeInfuse = function ( idOrNode, config, domPromise ) {
// look for a cached result of a previous infusion.
var id, $elem, error, data, cls, parts, parent, obj, top, state, infusedChildren;
if ( typeof idOrNode === 'string' ) {
id = idOrNode;
$elem = $( document.getElementById( id ) );
} else {
$elem = $( idOrNode );
id = $elem.attr( 'id' );
}
if ( !$elem.length ) {
if ( typeof idOrNode === 'string' ) {
error = 'Widget not found: ' + idOrNode;
} else if ( idOrNode && idOrNode.selector ) {
error = 'Widget not found: ' + idOrNode.selector;
} else {
error = 'Widget not found';
}
throw new Error( error );
}
if ( $elem[ 0 ].oouiInfused ) {
$elem = $elem[ 0 ].oouiInfused;
}
data = $elem.data( 'ooui-infused' );
if ( data ) {
// cached!
if ( data === true ) {
throw new Error( 'Circular dependency! ' + id );
}
if ( domPromise ) {
// pick up dynamic state, like focus, value of form inputs, scroll position, etc.
state = data.constructor.static.gatherPreInfuseState( $elem, data );
// restore dynamic state after the new element is re-inserted into DOM under infused parent
domPromise.done( data.restorePreInfuseState.bind( data, state ) );
infusedChildren = $elem.data( 'ooui-infused-children' );
if ( infusedChildren && infusedChildren.length ) {
infusedChildren.forEach( function ( data ) {
var state = data.constructor.static.gatherPreInfuseState( $elem, data );
domPromise.done( data.restorePreInfuseState.bind( data, state ) );
} );
}
}
return data;
}
data = $elem.attr( 'data-ooui' );
if ( !data ) {
throw new Error( 'No infusion data found: ' + id );
}
try {
data = JSON.parse( data );
} catch ( _ ) {
data = null;
}
if ( !( data && data._ ) ) {
throw new Error( 'No valid infusion data found: ' + id );
}
if ( data._ === 'Tag' ) {
// Special case: this is a raw Tag; wrap existing node, don't rebuild.
return new OO.ui.Element( $.extend( {}, config, { $element: $elem } ) );
}
parts = data._.split( '.' );
cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
if ( cls === undefined ) {
throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
}
// Verify that we're creating an OO.ui.Element instance
parent = cls.parent;
while ( parent !== undefined ) {
if ( parent === OO.ui.Element ) {
// Safe
break;
}
parent = parent.parent;
}
if ( parent !== OO.ui.Element ) {
throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
}
if ( !domPromise ) {
top = $.Deferred();
domPromise = top.promise();
}
$elem.data( 'ooui-infused', true ); // prevent loops
data.id = id; // implicit
infusedChildren = [];
data = OO.copy( data, null, function deserialize( value ) {
var infused;
if ( OO.isPlainObject( value ) ) {
if ( value.tag ) {
infused = OO.ui.Element.static.unsafeInfuse( value.tag, config, domPromise );
infusedChildren.push( infused );
// Flatten the structure
infusedChildren.push.apply( infusedChildren, infused.$element.data( 'ooui-infused-children' ) || [] );
infused.$element.removeData( 'ooui-infused-children' );
return infused;
}
if ( value.html !== undefined ) {
return new OO.ui.HtmlSnippet( value.html );
}
}
} );
// allow widgets to reuse parts of the DOM
data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
// pick up dynamic state, like focus, value of form inputs, scroll position, etc.
state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
// rebuild widget
// eslint-disable-next-line new-cap
obj = new cls( $.extend( {}, config, data ) );
// If anyone is holding a reference to the old DOM element,
// let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
// Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
$elem[ 0 ].oouiInfused = obj.$element;
// now replace old DOM with this new DOM.
if ( top ) {
// An efficient constructor might be able to reuse the entire DOM tree of the original element,
// so only mutate the DOM if we need to.
if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
$elem.replaceWith( obj.$element );
}
top.resolve();
}
obj.$element.data( 'ooui-infused', obj );
obj.$element.data( 'ooui-infused-children', infusedChildren );
// set the 'data-ooui' attribute so we can identify infused widgets
obj.$element.attr( 'data-ooui', '' );
// restore dynamic state after the new element is inserted into DOM
domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
return obj;
};
/**
* Pick out parts of `node`'s DOM to be reused when infusing a widget.
*
* This method **must not** make any changes to the DOM, only find interesting pieces and add them
* to `config` (which should then be returned). Actual DOM juggling should then be done by the
* constructor, which will be given the enhanced config.
*
* @protected
* @param {HTMLElement} node
* @param {Object} config
* @return {Object}
*/
OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
return config;
};
/**
* Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
* (and its children) that represent an Element of the same class and the given configuration,
* generated by the PHP implementation.
*
* This method is called just before `node` is detached from the DOM. The return value of this
* function will be passed to #restorePreInfuseState after the newly created widget's #$element
* is inserted into DOM to replace `node`.
*
* @protected
* @param {HTMLElement} node
* @param {Object} config
* @return {Object}
*/
OO.ui.Element.static.gatherPreInfuseState = function () {
return {};
};
/**
* Get a jQuery function within a specific document.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
* @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
* not in an iframe
* @return {Function} Bound jQuery function
*/
OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
function wrapper( selector ) {
return $( selector, wrapper.context );
}
wrapper.context = this.getDocument( context );
if ( $iframe ) {
wrapper.$iframe = $iframe;
}
return wrapper;
};
/**
* Get the document of an element.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
* @return {HTMLDocument|null} Document object
*/
OO.ui.Element.static.getDocument = function ( obj ) {
// jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
// Empty jQuery selections might have a context
obj.context ||
// HTMLElement
obj.ownerDocument ||
// Window
obj.document ||
// HTMLDocument
( obj.nodeType === Node.DOCUMENT_NODE && obj ) ||
null;
};
/**
* Get the window of an element or document.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
* @return {Window} Window object
*/
OO.ui.Element.static.getWindow = function ( obj ) {
var doc = this.getDocument( obj );
return doc.defaultView;
};
/**
* Get the direction of an element or document.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
* @return {string} Text direction, either 'ltr' or 'rtl'
*/
OO.ui.Element.static.getDir = function ( obj ) {
var isDoc, isWin;
if ( obj instanceof $ ) {
obj = obj[ 0 ];
}
isDoc = obj.nodeType === Node.DOCUMENT_NODE;
isWin = obj.document !== undefined;
if ( isDoc || isWin ) {
if ( isWin ) {
obj = obj.document;
}
obj = obj.body;
}
return $( obj ).css( 'direction' );
};
/**
* Get the offset between two frames.
*
* TODO: Make this function not use recursion.
*
* @static
* @param {Window} from Window of the child frame
* @param {Window} [to=window] Window of the parent frame
* @param {Object} [offset] Offset to start with, used internally
* @return {Object} Offset object, containing left and top properties
*/
OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
var i, len, frames, frame, rect;
if ( !to ) {
to = window;
}
if ( !offset ) {
offset = { top: 0, left: 0 };
}
if ( from.parent === from ) {
return offset;
}
// Get iframe element
frames = from.parent.document.getElementsByTagName( 'iframe' );
for ( i = 0, len = frames.length; i < len; i++ ) {
if ( frames[ i ].contentWindow === from ) {
frame = frames[ i ];
break;
}
}
// Recursively accumulate offset values
if ( frame ) {
rect = frame.getBoundingClientRect();
offset.left += rect.left;
offset.top += rect.top;
if ( from !== to ) {
this.getFrameOffset( from.parent, offset );
}
}
return offset;
};
/**
* Get the offset between two elements.
*
* The two elements may be in a different frame, but in that case the frame $element is in must
* be contained in the frame $anchor is in.
*
* @static
* @param {jQuery} $element Element whose position to get
* @param {jQuery} $anchor Element to get $element's position relative to
* @return {Object} Translated position coordinates, containing top and left properties
*/
OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
var iframe, iframePos,
pos = $element.offset(),
anchorPos = $anchor.offset(),
elementDocument = this.getDocument( $element ),
anchorDocument = this.getDocument( $anchor );
// If $element isn't in the same document as $anchor, traverse up
while ( elementDocument !== anchorDocument ) {
iframe = elementDocument.defaultView.frameElement;
if ( !iframe ) {
throw new Error( '$element frame is not contained in $anchor frame' );
}
iframePos = $( iframe ).offset();
pos.left += iframePos.left;
pos.top += iframePos.top;
elementDocument = iframe.ownerDocument;
}
pos.left -= anchorPos.left;
pos.top -= anchorPos.top;
return pos;
};
/**
* Get element border sizes.
*
* @static
* @param {HTMLElement} el Element to measure
* @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
*/
OO.ui.Element.static.getBorders = function ( el ) {
var doc = el.ownerDocument,
win = doc.defaultView,
style = win.getComputedStyle( el, null ),
$el = $( el ),
top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
return {
top: top,
left: left,
bottom: bottom,
right: right
};
};
/**
* Get dimensions of an element or window.
*
* @static
* @param {HTMLElement|Window} el Element to measure
* @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
*/
OO.ui.Element.static.getDimensions = function ( el ) {
var $el, $win,
doc = el.ownerDocument || el.document,
win = doc.defaultView;
if ( win === el || el === doc.documentElement ) {
$win = $( win );
return {
borders: { top: 0, left: 0, bottom: 0, right: 0 },
scroll: {
top: $win.scrollTop(),
left: $win.scrollLeft()
},
scrollbar: { right: 0, bottom: 0 },
rect: {
top: 0,
left: 0,
bottom: $win.innerHeight(),
right: $win.innerWidth()
}
};
} else {
$el = $( el );
return {
borders: this.getBorders( el ),
scroll: {
top: $el.scrollTop(),
left: $el.scrollLeft()
},
scrollbar: {
right: $el.innerWidth() - el.clientWidth,
bottom: $el.innerHeight() - el.clientHeight
},
rect: el.getBoundingClientRect()
};
}
};
/**
* Get the number of pixels that an element's content is scrolled to the left.
*
* Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
* Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
*
* This function smooths out browser inconsistencies (nicely described in the README at
* <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
* with Firefox's 'scrollLeft', which seems the sanest.
*
* @static
* @method
* @param {HTMLElement|Window} el Element to measure
* @return {number} Scroll position from the left.
* If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
* and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
* If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
* and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
*/
OO.ui.Element.static.getScrollLeft = ( function () {
var rtlScrollType = null;
function test() {
var $definer = $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
definer = $definer[ 0 ];
$definer.appendTo( 'body' );
if ( definer.scrollLeft > 0 ) {
// Safari, Chrome
rtlScrollType = 'default';
} else {
definer.scrollLeft = 1;
if ( definer.scrollLeft === 0 ) {
// Firefox, old Opera
rtlScrollType = 'negative';
} else {
// Internet Explorer, Edge
rtlScrollType = 'reverse';
}
}
$definer.remove();
}
return function getScrollLeft( el ) {
var isRoot = el.window === el ||
el === el.ownerDocument.body ||
el === el.ownerDocument.documentElement,
scrollLeft = isRoot ? $( window ).scrollLeft() : el.scrollLeft,
// All browsers use the correct scroll type ('negative') on the root, so don't
// do any fixups when looking at the root element
direction = isRoot ? 'ltr' : $( el ).css( 'direction' );
if ( direction === 'rtl' ) {
if ( rtlScrollType === null ) {
test();
}
if ( rtlScrollType === 'reverse' ) {
scrollLeft = -scrollLeft;
} else if ( rtlScrollType === 'default' ) {
scrollLeft = scrollLeft - el.scrollWidth + el.clientWidth;
}
}
return scrollLeft;
};
}() );
/**
* Get the root scrollable element of given element's document.
*
* On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
* the scrollTop property; instead we have to use `document.body`. Changing and testing the value
* lets us use 'body' or 'documentElement' based on what is working.
*
* https://code.google.com/p/chromium/issues/detail?id=303131
*
* @static
* @param {HTMLElement} el Element to find root scrollable parent for
* @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
* depending on browser
*/
OO.ui.Element.static.getRootScrollableElement = function ( el ) {
var scrollTop, body;
if ( OO.ui.scrollableElement === undefined ) {
body = el.ownerDocument.body;
scrollTop = body.scrollTop;
body.scrollTop = 1;
// In some browsers (observed in Chrome 56 on Linux Mint 18.1),
// body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
if ( Math.round( body.scrollTop ) === 1 ) {
body.scrollTop = scrollTop;
OO.ui.scrollableElement = 'body';
} else {
OO.ui.scrollableElement = 'documentElement';
}
}
return el.ownerDocument[ OO.ui.scrollableElement ];
};
/**
* Get closest scrollable container.
*
* Traverses up until either a scrollable element or the root is reached, in which case the root
* scrollable element will be returned (see #getRootScrollableElement).
*
* @static
* @param {HTMLElement} el Element to find scrollable container for
* @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
* @return {HTMLElement} Closest scrollable container
*/
OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
var i, val,
// Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
// 'overflow-y' have different values, so we need to check the separate properties.
props = [ 'overflow-x', 'overflow-y' ],
$parent = $( el ).parent();
if ( dimension === 'x' || dimension === 'y' ) {
props = [ 'overflow-' + dimension ];
}
// Special case for the document root (which doesn't really have any scrollable container, since
// it is the ultimate scrollable container, but this is probably saner than null or exception)
if ( $( el ).is( 'html, body' ) ) {
return this.getRootScrollableElement( el );
}
while ( $parent.length ) {
if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
return $parent[ 0 ];
}
i = props.length;
while ( i-- ) {
val = $parent.css( props[ i ] );
// We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
// scrolled in that direction, but they can actually be scrolled programatically. The user can
// unintentionally perform a scroll in such case even if the application doesn't scroll
// programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
// This could cause funny issues...
if ( val === 'auto' || val === 'scroll' ) {
return $parent[ 0 ];
}
}
$parent = $parent.parent();
}
// The element is unattached... return something mostly sane
return this.getRootScrollableElement( el );
};
/**
* Scroll element into view.
*
* @static
* @param {HTMLElement} el Element to scroll into view
* @param {Object} [config] Configuration options
* @param {string} [config.duration='fast'] jQuery animation duration value
* @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
* to scroll in both directions
* @return {jQuery.Promise} Promise which resolves when the scroll is complete
*/
OO.ui.Element.static.scrollIntoView = function ( el, config ) {
var position, animations, container, $container, elementDimensions, containerDimensions, $window,
deferred = $.Deferred();
// Configuration initialization
config = config || {};
animations = {};
container = this.getClosestScrollableContainer( el, config.direction );
$container = $( container );
elementDimensions = this.getDimensions( el );
containerDimensions = this.getDimensions( container );
$window = $( this.getWindow( el ) );
// Compute the element's position relative to the container
if ( $container.is( 'html, body' ) ) {
// If the scrollable container is the root, this is easy
position = {
top: elementDimensions.rect.top,
bottom: $window.innerHeight() - elementDimensions.rect.bottom,
left: elementDimensions.rect.left,
right: $window.innerWidth() - elementDimensions.rect.right
};
} else {
// Otherwise, we have to subtract el's coordinates from container's coordinates
position = {
top: elementDimensions.rect.top - ( containerDimensions.rect.top + containerDimensions.borders.top ),
bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom - containerDimensions.scrollbar.bottom - elementDimensions.rect.bottom,
left: elementDimensions.rect.left - ( containerDimensions.rect.left + containerDimensions.borders.left ),
right: containerDimensions.rect.right - containerDimensions.borders.right - containerDimensions.scrollbar.right - elementDimensions.rect.right
};
}
if ( !config.direction || config.direction === 'y' ) {
if ( position.top < 0 ) {
animations.scrollTop = containerDimensions.scroll.top + position.top;
} else if ( position.top > 0 && position.bottom < 0 ) {
animations.scrollTop = containerDimensions.scroll.top + Math.min( position.top, -position.bottom );
}
}
if ( !config.direction || config.direction === 'x' ) {
if ( position.left < 0 ) {
animations.scrollLeft = containerDimensions.scroll.left + position.left;
} else if ( position.left > 0 && position.right < 0 ) {
animations.scrollLeft = containerDimensions.scroll.left + Math.min( position.left, -position.right );
}
}
if ( !$.isEmptyObject( animations ) ) {
$container.stop( true ).animate( animations, config.duration === undefined ? 'fast' : config.duration );
$container.queue( function ( next ) {
deferred.resolve();
next();
} );
} else {
deferred.resolve();
}
return deferred.promise();
};
/**
* Force the browser to reconsider whether it really needs to render scrollbars inside the element
* and reserve space for them, because it probably doesn't.
*
* Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
* similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
* to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
* and then reattach (or show) them back.
*
* @static
* @param {HTMLElement} el Element to reconsider the scrollbars on
*/
OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
var i, len, scrollLeft, scrollTop, nodes = [];
// Save scroll position
scrollLeft = el.scrollLeft;
scrollTop = el.scrollTop;
// Detach all children
while ( el.firstChild ) {
nodes.push( el.firstChild );
el.removeChild( el.firstChild );
}
// Force reflow
// eslint-disable-next-line no-void
void el.offsetHeight;
// Reattach all children
for ( i = 0, len = nodes.length; i < len; i++ ) {
el.appendChild( nodes[ i ] );
}
// Restore scroll position (no-op if scrollbars disappeared)
el.scrollLeft = scrollLeft;
el.scrollTop = scrollTop;
};
/* Methods */
/**
* Toggle visibility of an element.
*
* @param {boolean} [show] Make element visible, omit to toggle visibility
* @fires visible
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.Element.prototype.toggle = function ( show ) {
show = show === undefined ? !this.visible : !!show;
if ( show !== this.isVisible() ) {
this.visible = show;
this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
this.emit( 'toggle', show );
}
return this;
};
/**
* Check if element is visible.
*
* @return {boolean} element is visible
*/
OO.ui.Element.prototype.isVisible = function () {
return this.visible;
};
/**
* Get element data.
*
* @return {Mixed} Element data
*/
OO.ui.Element.prototype.getData = function () {
return this.data;
};
/**
* Set element data.
*
* @param {Mixed} data Element data
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.Element.prototype.setData = function ( data ) {
this.data = data;
return this;
};
/**
* Set the element has an 'id' attribute.
*
* @param {string} id
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.Element.prototype.setElementId = function ( id ) {
this.elementId = id;
this.$element.attr( 'id', id );
return this;
};
/**
* Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
* and return its value.
*
* @return {string}
*/
OO.ui.Element.prototype.getElementId = function () {
if ( this.elementId === null ) {
this.setElementId( OO.ui.generateElementId() );
}
return this.elementId;
};
/**
* Check if element supports one or more methods.
*
* @param {string|string[]} methods Method or list of methods to check
* @return {boolean} All methods are supported
*/
OO.ui.Element.prototype.supports = function ( methods ) {
var i, len,
support = 0;
methods = Array.isArray( methods ) ? methods : [ methods ];
for ( i = 0, len = methods.length; i < len; i++ ) {
if ( typeof this[ methods[ i ] ] === 'function' ) {
support++;
}
}
return methods.length === support;
};
/**
* Update the theme-provided classes.
*
* @localdoc This is called in element mixins and widget classes any time state changes.
* Updating is debounced, minimizing overhead of changing multiple attributes and
* guaranteeing that theme updates do not occur within an element's constructor
*/
OO.ui.Element.prototype.updateThemeClasses = function () {
OO.ui.theme.queueUpdateElementClasses( this );
};
/**
* Get the HTML tag name.
*
* Override this method to base the result on instance information.
*
* @return {string} HTML tag name
*/
OO.ui.Element.prototype.getTagName = function () {
return this.constructor.static.tagName;
};
/**
* Check if the element is attached to the DOM
*
* @return {boolean} The element is attached to the DOM
*/
OO.ui.Element.prototype.isElementAttached = function () {
return $.contains( this.getElementDocument(), this.$element[ 0 ] );
};
/**
* Get the DOM document.
*
* @return {HTMLDocument} Document object
*/
OO.ui.Element.prototype.getElementDocument = function () {
// Don't cache this in other ways either because subclasses could can change this.$element
return OO.ui.Element.static.getDocument( this.$element );
};
/**
* Get the DOM window.
*
* @return {Window} Window object
*/
OO.ui.Element.prototype.getElementWindow = function () {
return OO.ui.Element.static.getWindow( this.$element );
};
/**
* Get closest scrollable container.
*
* @return {HTMLElement} Closest scrollable container
*/
OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
};
/**
* Get group element is in.
*
* @return {OO.ui.mixin.GroupElement|null} Group element, null if none
*/
OO.ui.Element.prototype.getElementGroup = function () {
return this.elementGroup;
};
/**
* Set group element is in.
*
* @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.Element.prototype.setElementGroup = function ( group ) {
this.elementGroup = group;
return this;
};
/**
* Scroll element into view.
*
* @param {Object} [config] Configuration options
* @return {jQuery.Promise} Promise which resolves when the scroll is complete
*/
OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
if (
!this.isElementAttached() ||
!this.isVisible() ||
( this.getElementGroup() && !this.getElementGroup().isVisible() )
) {
return $.Deferred().resolve();
}
return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
};
/**
* Restore the pre-infusion dynamic state for this widget.
*
* This method is called after #$element has been inserted into DOM. The parameter is the return
* value of #gatherPreInfuseState.
*
* @protected
* @param {Object} state
*/
OO.ui.Element.prototype.restorePreInfuseState = function () {
};
/**
* Wraps an HTML snippet for use with configuration values which default
* to strings. This bypasses the default html-escaping done to string
* values.
*
* @class
*
* @constructor
* @param {string} [content] HTML content
*/
OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
// Properties
this.content = content;
};
/* Setup */
OO.initClass( OO.ui.HtmlSnippet );
/* Methods */
/**
* Render into HTML.
*
* @return {string} Unchanged HTML snippet.
*/
OO.ui.HtmlSnippet.prototype.toString = function () {
return this.content;
};
/**
* Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
* that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
* See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
* {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
* {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
*
* @abstract
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.Layout = function OoUiLayout( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.Layout.parent.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
// Initialization
this.$element.addClass( 'oo-ui-layout' );
};
/* Setup */
OO.inheritClass( OO.ui.Layout, OO.ui.Element );
OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
/* Methods */
/**
* Reset scroll offsets
*
* @chainable
* @return {OO.ui.Layout} The layout, for chaining
*/
OO.ui.Layout.prototype.resetScroll = function () {
this.$element[ 0 ].scrollTop = 0;
// TODO: Reset scrollLeft in an RTL-aware manner, see OO.ui.Element.static.getScrollLeft.
return this;
};
/**
* Widgets are compositions of one or more OOUI elements that users can both view
* and interact with. All widgets can be configured and modified via a standard API,
* and their state can change dynamically according to a model.
*
* @abstract
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
* appearance reflects this state.
*/
OO.ui.Widget = function OoUiWidget( config ) {
// Initialize config
config = $.extend( { disabled: false }, config );
// Parent constructor
OO.ui.Widget.parent.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.disabled = null;
this.wasDisabled = null;
// Initialization
this.$element.addClass( 'oo-ui-widget' );
this.setDisabled( !!config.disabled );
};
/* Setup */
OO.inheritClass( OO.ui.Widget, OO.ui.Element );
OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
/* Events */
/**
* @event disable
*
* A 'disable' event is emitted when the disabled state of the widget changes
* (i.e. on disable **and** enable).
*
* @param {boolean} disabled Widget is disabled
*/
/**
* @event toggle
*
* A 'toggle' event is emitted when the visibility of the widget changes.
*
* @param {boolean} visible Widget is visible
*/
/* Methods */
/**
* Check if the widget is disabled.
*
* @return {boolean} Widget is disabled
*/
OO.ui.Widget.prototype.isDisabled = function () {
return this.disabled;
};
/**
* Set the 'disabled' state of the widget.
*
* When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
*
* @param {boolean} disabled Disable widget
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
var isDisabled;
this.disabled = !!disabled;
isDisabled = this.isDisabled();
if ( isDisabled !== this.wasDisabled ) {
this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
this.$element.attr( 'aria-disabled', isDisabled.toString() );
this.emit( 'disable', isDisabled );
this.updateThemeClasses();
}
this.wasDisabled = isDisabled;
return this;
};
/**
* Update the disabled state, in case of changes in parent widget.
*
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.Widget.prototype.updateDisabled = function () {
this.setDisabled( this.disabled );
return this;
};
/**
* Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
* value.
*
* If this function returns null, the widget should have a meaningful #simulateLabelClick method
* instead.
*
* @return {string|null} The ID of the labelable element
*/
OO.ui.Widget.prototype.getInputId = function () {
return null;
};
/**
* Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
* HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
* override this method to provide intuitive, accessible behavior.
*
* By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
* Individual widgets may override it too.
*
* This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
* directly.
*/
OO.ui.Widget.prototype.simulateLabelClick = function () {
};
/**
* Theme logic.
*
* @abstract
* @class
*
* @constructor
*/
OO.ui.Theme = function OoUiTheme() {
this.elementClassesQueue = [];
this.debouncedUpdateQueuedElementClasses = OO.ui.debounce( this.updateQueuedElementClasses );
};
/* Setup */
OO.initClass( OO.ui.Theme );
/* Methods */
/**
* Get a list of classes to be applied to a widget.
*
* The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
* otherwise state transitions will not work properly.
*
* @param {OO.ui.Element} element Element for which to get classes
* @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
*/
OO.ui.Theme.prototype.getElementClasses = function () {
return { on: [], off: [] };
};
/**
* Update CSS classes provided by the theme.
*
* For elements with theme logic hooks, this should be called any time there's a state change.
*
* @param {OO.ui.Element} element Element for which to update classes
*/
OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
var $elements = $( [] ),
classes = this.getElementClasses( element );
if ( element.$icon ) {
$elements = $elements.add( element.$icon );
}
if ( element.$indicator ) {
$elements = $elements.add( element.$indicator );
}
$elements
.removeClass( classes.off )
.addClass( classes.on );
};
/**
* @private
*/
OO.ui.Theme.prototype.updateQueuedElementClasses = function () {
var i;
for ( i = 0; i < this.elementClassesQueue.length; i++ ) {
this.updateElementClasses( this.elementClassesQueue[ i ] );
}
// Clear the queue
this.elementClassesQueue = [];
};
/**
* Queue #updateElementClasses to be called for this element.
*
* @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
* to make them synchronous.
*
* @param {OO.ui.Element} element Element for which to update classes
*/
OO.ui.Theme.prototype.queueUpdateElementClasses = function ( element ) {
// Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
// the most common case (this method is often called repeatedly for the same element).
if ( this.elementClassesQueue.lastIndexOf( element ) !== -1 ) {
return;
}
this.elementClassesQueue.push( element );
this.debouncedUpdateQueuedElementClasses();
};
/**
* Get the transition duration in milliseconds for dialogs opening/closing
*
* The dialog should be fully rendered this many milliseconds after the
* ready process has executed.
*
* @return {number} Transition duration in milliseconds
*/
OO.ui.Theme.prototype.getDialogTransitionDuration = function () {
return 0;
};
/**
* The TabIndexedElement class is an attribute mixin used to add additional functionality to an
* element created by another class. The mixin provides a โtabIndexโ property, which specifies the
* order in which users will navigate through the focusable elements via the "tab" key.
*
* @example
* // TabIndexedElement is mixed into the ButtonWidget class
* // to provide a tabIndex property.
* var button1 = new OO.ui.ButtonWidget( {
* label: 'fourth',
* tabIndex: 4
* } );
* var button2 = new OO.ui.ButtonWidget( {
* label: 'second',
* tabIndex: 2
* } );
* var button3 = new OO.ui.ButtonWidget( {
* label: 'third',
* tabIndex: 3
* } );
* var button4 = new OO.ui.ButtonWidget( {
* label: 'first',
* tabIndex: 1
* } );
* $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
* the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
* functionality will be applied to it instead.
* @cfg {string|number|null} [tabIndex=0] Number that specifies the elementโs position in the tab-navigation
* order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
* to remove the element from the tab-navigation flow.
*/
OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
// Configuration initialization
config = $.extend( { tabIndex: 0 }, config );
// Properties
this.$tabIndexed = null;
this.tabIndex = null;
// Events
this.connect( this, { disable: 'onTabIndexedElementDisable' } );
// Initialization
this.setTabIndex( config.tabIndex );
this.setTabIndexedElement( config.$tabIndexed || this.$element );
};
/* Setup */
OO.initClass( OO.ui.mixin.TabIndexedElement );
/* Methods */
/**
* Set the element that should use the tabindex functionality.
*
* This method is used to retarget a tabindex mixin so that its functionality applies
* to the specified element. If an element is currently using the functionality, the mixinโs
* effect on that element is removed before the new element is set up.
*
* @param {jQuery} $tabIndexed Element that should use the tabindex functionality
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
var tabIndex = this.tabIndex;
// Remove attributes from old $tabIndexed
this.setTabIndex( null );
// Force update of new $tabIndexed
this.$tabIndexed = $tabIndexed;
this.tabIndex = tabIndex;
return this.updateTabIndex();
};
/**
* Set the value of the tabindex.
*
* @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
tabIndex = /^-?\d+$/.test( tabIndex ) ? Number( tabIndex ) : null;
if ( this.tabIndex !== tabIndex ) {
this.tabIndex = tabIndex;
this.updateTabIndex();
}
return this;
};
/**
* Update the `tabindex` attribute, in case of changes to tab index or
* disabled state.
*
* @private
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
if ( this.$tabIndexed ) {
if ( this.tabIndex !== null ) {
// Do not index over disabled elements
this.$tabIndexed.attr( {
tabindex: this.isDisabled() ? -1 : this.tabIndex,
// Support: ChromeVox and NVDA
// These do not seem to inherit aria-disabled from parent elements
'aria-disabled': this.isDisabled().toString()
} );
} else {
this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
}
}
return this;
};
/**
* Handle disable events.
*
* @private
* @param {boolean} disabled Element is disabled
*/
OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
this.updateTabIndex();
};
/**
* Get the value of the tabindex.
*
* @return {number|null} Tabindex value
*/
OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
return this.tabIndex;
};
/**
* Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
*
* If the element already has an ID then that is returned, otherwise unique ID is
* generated, set on the element, and returned.
*
* @return {string|null} The ID of the focusable element
*/
OO.ui.mixin.TabIndexedElement.prototype.getInputId = function () {
var id;
if ( !this.$tabIndexed ) {
return null;
}
if ( !this.isLabelableNode( this.$tabIndexed ) ) {
return null;
}
id = this.$tabIndexed.attr( 'id' );
if ( id === undefined ) {
id = OO.ui.generateElementId();
this.$tabIndexed.attr( 'id', id );
}
return id;
};
/**
* Whether the node is 'labelable' according to the HTML spec
* (i.e., whether it can be interacted with through a `<label for="โฆ">`).
* See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
*
* @private
* @param {jQuery} $node
* @return {boolean}
*/
OO.ui.mixin.TabIndexedElement.prototype.isLabelableNode = function ( $node ) {
var
labelableTags = [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
tagName = $node.prop( 'tagName' ).toLowerCase();
if ( tagName === 'input' && $node.attr( 'type' ) !== 'hidden' ) {
return true;
}
if ( labelableTags.indexOf( tagName ) !== -1 ) {
return true;
}
return false;
};
/**
* Focus this element.
*
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.TabIndexedElement.prototype.focus = function () {
if ( !this.isDisabled() ) {
this.$tabIndexed.focus();
}
return this;
};
/**
* Blur this element.
*
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.TabIndexedElement.prototype.blur = function () {
this.$tabIndexed.blur();
return this;
};
/**
* @inheritdoc OO.ui.Widget
*/
OO.ui.mixin.TabIndexedElement.prototype.simulateLabelClick = function () {
this.focus();
};
/**
* ButtonElement is often mixed into other classes to generate a button, which is a clickable
* interface element that can be configured with access keys for accessibility.
* See the [OOUI documentation on MediaWiki] [1] for examples.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$button] The button element created by the class.
* If this configuration is omitted, the button element will use a generated `<a>`.
* @cfg {boolean} [framed=true] Render the button with a frame
*/
OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$button = null;
this.framed = null;
this.active = config.active !== undefined && config.active;
this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
this.onMouseDownHandler = this.onMouseDown.bind( this );
this.onDocumentKeyUpHandler = this.onDocumentKeyUp.bind( this );
this.onKeyDownHandler = this.onKeyDown.bind( this );
this.onClickHandler = this.onClick.bind( this );
this.onKeyPressHandler = this.onKeyPress.bind( this );
// Initialization
this.$element.addClass( 'oo-ui-buttonElement' );
this.toggleFramed( config.framed === undefined || config.framed );
this.setButtonElement( config.$button || $( '<a>' ) );
};
/* Setup */
OO.initClass( OO.ui.mixin.ButtonElement );
/* Static Properties */
/**
* Cancel mouse down events.
*
* This property is usually set to `true` to prevent the focus from changing when the button is clicked.
* Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
* use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
* parent widget.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
/* Events */
/**
* A 'click' event is emitted when the button element is clicked.
*
* @event click
*/
/* Methods */
/**
* Set the button element.
*
* This method is used to retarget a button mixin so that its functionality applies to
* the specified button element instead of the one created by the class. If a button element
* is already set, the method will remove the mixinโs effect on that element.
*
* @param {jQuery} $button Element to use as button
*/
OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
if ( this.$button ) {
this.$button
.removeClass( 'oo-ui-buttonElement-button' )
.removeAttr( 'role accesskey' )
.off( {
mousedown: this.onMouseDownHandler,
keydown: this.onKeyDownHandler,
click: this.onClickHandler,
keypress: this.onKeyPressHandler
} );
}
this.$button = $button
.addClass( 'oo-ui-buttonElement-button' )
.on( {
mousedown: this.onMouseDownHandler,
keydown: this.onKeyDownHandler,
click: this.onClickHandler,
keypress: this.onKeyPressHandler
} );
// Add `role="button"` on `<a>` elements, where it's needed
// `toUpperCase()` is added for XHTML documents
if ( this.$button.prop( 'tagName' ).toUpperCase() === 'A' ) {
this.$button.attr( 'role', 'button' );
}
};
/**
* Handles mouse down events.
*
* @protected
* @param {jQuery.Event} e Mouse down event
* @return {undefined/boolean} False to prevent default if event is handled
*/
OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
return;
}
this.$element.addClass( 'oo-ui-buttonElement-pressed' );
// Run the mouseup handler no matter where the mouse is when the button is let go, so we can
// reliably remove the pressed class
this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
// Prevent change of focus unless specifically configured otherwise
if ( this.constructor.static.cancelButtonMouseDownEvents ) {
return false;
}
};
/**
* Handles document mouse up events.
*
* @protected
* @param {MouseEvent} e Mouse up event
*/
OO.ui.mixin.ButtonElement.prototype.onDocumentMouseUp = function ( e ) {
if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
return;
}
this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
// Stop listening for mouseup, since we only needed this once
this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
};
// Deprecated alias since 0.28.3
OO.ui.mixin.ButtonElement.prototype.onMouseUp = function () {
OO.ui.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
this.onDocumentMouseUp.apply( this, arguments );
};
/**
* Handles mouse click events.
*
* @protected
* @param {jQuery.Event} e Mouse click event
* @fires click
* @return {undefined/boolean} False to prevent default if event is handled
*/
OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
if ( this.emit( 'click' ) ) {
return false;
}
}
};
/**
* Handles key down events.
*
* @protected
* @param {jQuery.Event} e Key down event
*/
OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
return;
}
this.$element.addClass( 'oo-ui-buttonElement-pressed' );
// Run the keyup handler no matter where the key is when the button is let go, so we can
// reliably remove the pressed class
this.getElementDocument().addEventListener( 'keyup', this.onDocumentKeyUpHandler, true );
};
/**
* Handles document key up events.
*
* @protected
* @param {KeyboardEvent} e Key up event
*/
OO.ui.mixin.ButtonElement.prototype.onDocumentKeyUp = function ( e ) {
if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
return;
}
this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
// Stop listening for keyup, since we only needed this once
this.getElementDocument().removeEventListener( 'keyup', this.onDocumentKeyUpHandler, true );
};
// Deprecated alias since 0.28.3
OO.ui.mixin.ButtonElement.prototype.onKeyUp = function () {
OO.ui.warnDeprecation( 'onKeyUp is deprecated, use onDocumentKeyUp instead' );
this.onDocumentKeyUp.apply( this, arguments );
};
/**
* Handles key press events.
*
* @protected
* @param {jQuery.Event} e Key press event
* @fires click
* @return {undefined/boolean} False to prevent default if event is handled
*/
OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
if ( this.emit( 'click' ) ) {
return false;
}
}
};
/**
* Check if button has a frame.
*
* @return {boolean} Button is framed
*/
OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
return this.framed;
};
/**
* Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
*
* @param {boolean} [framed] Make button framed, omit to toggle
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
framed = framed === undefined ? !this.framed : !!framed;
if ( framed !== this.framed ) {
this.framed = framed;
this.$element
.toggleClass( 'oo-ui-buttonElement-frameless', !framed )
.toggleClass( 'oo-ui-buttonElement-framed', framed );
this.updateThemeClasses();
}
return this;
};
/**
* Set the button's active state.
*
* The active state can be set on:
*
* - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
* - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
* - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
*
* @protected
* @param {boolean} value Make button active
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
this.active = !!value;
this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
this.updateThemeClasses();
return this;
};
/**
* Check if the button is active
*
* @protected
* @return {boolean} The button is active
*/
OO.ui.mixin.ButtonElement.prototype.isActive = function () {
return this.active;
};
/**
* Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
* {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
* items from the group is done through the interface the class provides.
* For more information, please see the [OOUI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
*
* @abstract
* @mixins OO.EmitterList
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$group] The container element created by the class. If this configuration
* is omitted, the group element will use a generated `<div>`.
*/
OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
// Configuration initialization
config = config || {};
// Mixin constructors
OO.EmitterList.call( this, config );
// Properties
this.$group = null;
// Initialization
this.setGroupElement( config.$group || $( '<div>' ) );
};
/* Setup */
OO.mixinClass( OO.ui.mixin.GroupElement, OO.EmitterList );
/* Events */
/**
* @event change
*
* A change event is emitted when the set of selected items changes.
*
* @param {OO.ui.Element[]} items Items currently in the group
*/
/* Methods */
/**
* Set the group element.
*
* If an element is already set, items will be moved to the new element.
*
* @param {jQuery} $group Element to use as group
*/
OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
var i, len;
this.$group = $group;
for ( i = 0, len = this.items.length; i < len; i++ ) {
this.$group.append( this.items[ i ].$element );
}
};
/**
* Find an item by its data.
*
* Only the first item with matching data will be returned. To return all matching items,
* use the #findItemsFromData method.
*
* @param {Object} data Item data to search for
* @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
*/
OO.ui.mixin.GroupElement.prototype.findItemFromData = function ( data ) {
var i, len, item,
hash = OO.getHash( data );
for ( i = 0, len = this.items.length; i < len; i++ ) {
item = this.items[ i ];
if ( hash === OO.getHash( item.getData() ) ) {
return item;
}
}
return null;
};
/**
* Find items by their data.
*
* All items with matching data will be returned. To return only the first match, use the #findItemFromData method instead.
*
* @param {Object} data Item data to search for
* @return {OO.ui.Element[]} Items with equivalent data
*/
OO.ui.mixin.GroupElement.prototype.findItemsFromData = function ( data ) {
var i, len, item,
hash = OO.getHash( data ),
items = [];
for ( i = 0, len = this.items.length; i < len; i++ ) {
item = this.items[ i ];
if ( hash === OO.getHash( item.getData() ) ) {
items.push( item );
}
}
return items;
};
/**
* Add items to the group.
*
* Items will be added to the end of the group array unless the optional `index` parameter specifies
* a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
*
* @param {OO.ui.Element[]} items An array of items to add to the group
* @param {number} [index] Index of the insertion point
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
// Mixin method
OO.EmitterList.prototype.addItems.call( this, items, index );
this.emit( 'change', this.getItems() );
return this;
};
/**
* @inheritdoc
*/
OO.ui.mixin.GroupElement.prototype.moveItem = function ( items, newIndex ) {
// insertItemElements expects this.items to not have been modified yet, so call before the mixin
this.insertItemElements( items, newIndex );
// Mixin method
newIndex = OO.EmitterList.prototype.moveItem.call( this, items, newIndex );
return newIndex;
};
/**
* @inheritdoc
*/
OO.ui.mixin.GroupElement.prototype.insertItem = function ( item, index ) {
item.setElementGroup( this );
this.insertItemElements( item, index );
// Mixin method
index = OO.EmitterList.prototype.insertItem.call( this, item, index );
return index;
};
/**
* Insert elements into the group
*
* @private
* @param {OO.ui.Element} itemWidget Item to insert
* @param {number} index Insertion index
*/
OO.ui.mixin.GroupElement.prototype.insertItemElements = function ( itemWidget, index ) {
if ( index === undefined || index < 0 || index >= this.items.length ) {
this.$group.append( itemWidget.$element );
} else if ( index === 0 ) {
this.$group.prepend( itemWidget.$element );
} else {
this.items[ index ].$element.before( itemWidget.$element );
}
};
/**
* Remove the specified items from a group.
*
* Removed items are detached (not removed) from the DOM so that they may be reused.
* To remove all items from a group, you may wish to use the #clearItems method instead.
*
* @param {OO.ui.Element[]} items An array of items to remove
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
var i, len, item, index;
// Remove specific items elements
for ( i = 0, len = items.length; i < len; i++ ) {
item = items[ i ];
index = this.items.indexOf( item );
if ( index !== -1 ) {
item.setElementGroup( null );
item.$element.detach();
}
}
// Mixin method
OO.EmitterList.prototype.removeItems.call( this, items );
this.emit( 'change', this.getItems() );
return this;
};
/**
* Clear all items from the group.
*
* Cleared items are detached from the DOM, not removed, so that they may be reused.
* To remove only a subset of items from a group, use the #removeItems method.
*
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.GroupElement.prototype.clearItems = function () {
var i, len;
// Remove all item elements
for ( i = 0, len = this.items.length; i < len; i++ ) {
this.items[ i ].setElementGroup( null );
this.items[ i ].$element.detach();
}
// Mixin method
OO.EmitterList.prototype.clearItems.call( this );
this.emit( 'change', this.getItems() );
return this;
};
/**
* LabelElement is often mixed into other classes to generate a label, which
* helps identify the function of an interface element.
* See the [OOUI documentation on MediaWiki] [1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$label] The label element created by the class. If this
* configuration is omitted, the label element will use a generated `<span>`.
* @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
* as a plaintext string, a jQuery selection of elements, or a function that will produce a string
* in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
* [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
* @cfg {boolean} [invisibleLabel] Whether the label should be visually hidden (but still accessible
* to screen-readers).
*/
OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$label = null;
this.label = null;
this.invisibleLabel = null;
// Initialization
this.setLabel( config.label || this.constructor.static.label );
this.setLabelElement( config.$label || $( '<span>' ) );
this.setInvisibleLabel( config.invisibleLabel );
};
/* Setup */
OO.initClass( OO.ui.mixin.LabelElement );
/* Events */
/**
* @event labelChange
* @param {string} value
*/
/* Static Properties */
/**
* The label text. The label can be specified as a plaintext string, a function that will
* produce a string in the future, or `null` for no label. The static value will
* be overridden if a label is specified with the #label config option.
*
* @static
* @inheritable
* @property {string|Function|null}
*/
OO.ui.mixin.LabelElement.static.label = null;
/* Static methods */
/**
* Highlight the first occurrence of the query in the given text
*
* @param {string} text Text
* @param {string} query Query to find
* @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
* @return {jQuery} Text with the first match of the query
* sub-string wrapped in highlighted span
*/
OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query, compare ) {
var i, tLen, qLen,
offset = -1,
$result = $( '<span>' );
if ( compare ) {
tLen = text.length;
qLen = query.length;
for ( i = 0; offset === -1 && i <= tLen - qLen; i++ ) {
if ( compare( query, text.slice( i, i + qLen ) ) === 0 ) {
offset = i;
}
}
} else {
offset = text.toLowerCase().indexOf( query.toLowerCase() );
}
if ( !query.length || offset === -1 ) {
$result.text( text );
} else {
$result.append(
document.createTextNode( text.slice( 0, offset ) ),
$( '<span>' )
.addClass( 'oo-ui-labelElement-label-highlight' )
.text( text.slice( offset, offset + query.length ) ),
document.createTextNode( text.slice( offset + query.length ) )
);
}
return $result.contents();
};
/* Methods */
/**
* Set the label element.
*
* If an element is already set, it will be cleaned up before setting up the new element.
*
* @param {jQuery} $label Element to use as label
*/
OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
if ( this.$label ) {
this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
}
this.$label = $label.addClass( 'oo-ui-labelElement-label' );
this.setLabelContent( this.label );
};
/**
* Set the label.
*
* An empty string will result in the label being hidden. A string containing only whitespace will
* be converted to a single ` `.
*
* @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
* text; or null for no label
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
label = ( ( typeof label === 'string' || label instanceof $ ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null;
if ( this.label !== label ) {
if ( this.$label ) {
this.setLabelContent( label );
}
this.label = label;
this.emit( 'labelChange' );
}
this.$element.toggleClass( 'oo-ui-labelElement', !!this.label && !this.invisibleLabel );
return this;
};
/**
* Set whether the label should be visually hidden (but still accessible to screen-readers).
*
* @param {boolean} invisibleLabel
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.LabelElement.prototype.setInvisibleLabel = function ( invisibleLabel ) {
invisibleLabel = !!invisibleLabel;
if ( this.invisibleLabel !== invisibleLabel ) {
this.invisibleLabel = invisibleLabel;
this.emit( 'labelChange' );
}
this.$label.toggleClass( 'oo-ui-labelElement-invisible', this.invisibleLabel );
// Pretend that there is no label, a lot of CSS has been written with this assumption
this.$element.toggleClass( 'oo-ui-labelElement', !!this.label && !this.invisibleLabel );
return this;
};
/**
* Set the label as plain text with a highlighted query
*
* @param {string} text Text label to set
* @param {string} query Substring of text to highlight
* @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query, compare ) {
return this.setLabel( this.constructor.static.highlightQuery( text, query, compare ) );
};
/**
* Get the label.
*
* @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
* text; or null for no label
*/
OO.ui.mixin.LabelElement.prototype.getLabel = function () {
return this.label;
};
/**
* Set the content of the label.
*
* Do not call this method until after the label element has been set by #setLabelElement.
*
* @private
* @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
* text; or null for no label
*/
OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
if ( typeof label === 'string' ) {
if ( label.match( /^\s*$/ ) ) {
// Convert whitespace only string to a single non-breaking space
this.$label.html( ' ' );
} else {
this.$label.text( label );
}
} else if ( label instanceof OO.ui.HtmlSnippet ) {
this.$label.html( label.toString() );
} else if ( label instanceof $ ) {
this.$label.empty().append( label );
} else {
this.$label.empty();
}
};
/**
* IconElement is often mixed into other classes to generate an icon.
* Icons are graphics, about the size of normal text. They are used to aid the user
* in locating a control or to convey information in a space-efficient way. See the
* [OOUI documentation on MediaWiki] [1] for a list of icons
* included in the library.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
* the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
* the icon element be set to an existing icon instead of the one generated by this class, set a
* value using a jQuery selection. For example:
*
* // Use a <div> tag instead of a <span>
* $icon: $("<div>")
* // Use an existing icon element instead of the one generated by the class
* $icon: this.$element
* // Use an icon element from a child widget
* $icon: this.childwidget.$element
* @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., โremoveโ or โmenuโ), or a map of
* symbolic names. A map is used for i18n purposes and contains a `default` icon
* name and additional names keyed by language code. The `default` name is used when no icon is keyed
* by the user's language.
*
* Example of an i18n map:
*
* { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
* See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
* [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
* @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
* text. The icon title is displayed when users move the mouse over the icon.
*/
OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$icon = null;
this.icon = null;
this.iconTitle = null;
// Initialization
this.setIcon( config.icon || this.constructor.static.icon );
this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
this.setIconElement( config.$icon || $( '<span>' ) );
};
/* Setup */
OO.initClass( OO.ui.mixin.IconElement );
/* Static Properties */
/**
* The symbolic name of the icon (e.g., โremoveโ or โmenuโ), or a map of symbolic names. A map is used
* for i18n purposes and contains a `default` icon name and additional names keyed by
* language code. The `default` name is used when no icon is keyed by the user's language.
*
* Example of an i18n map:
*
* { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
*
* Note: the static property will be overridden if the #icon configuration is used.
*
* @static
* @inheritable
* @property {Object|string}
*/
OO.ui.mixin.IconElement.static.icon = null;
/**
* The icon title, displayed when users move the mouse over the icon. The value can be text, a
* function that returns title text, or `null` for no title.
*
* The static property will be overridden if the #iconTitle configuration is used.
*
* @static
* @inheritable
* @property {string|Function|null}
*/
OO.ui.mixin.IconElement.static.iconTitle = null;
/* Methods */
/**
* Set the icon element. This method is used to retarget an icon mixin so that its functionality
* applies to the specified icon element instead of the one created by the class. If an icon
* element is already set, the mixinโs effect on that element is removed. Generated CSS classes
* and mixin methods will no longer affect the element.
*
* @param {jQuery} $icon Element to use as icon
*/
OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
if ( this.$icon ) {
this.$icon
.removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
.removeAttr( 'title' );
}
this.$icon = $icon
.addClass( 'oo-ui-iconElement-icon' )
.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon )
.toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
if ( this.iconTitle !== null ) {
this.$icon.attr( 'title', this.iconTitle );
}
this.updateThemeClasses();
};
/**
* Set icon by symbolic name (e.g., โremoveโ or โmenuโ). Use `null` to remove an icon.
* The icon parameter can also be set to a map of icon names. See the #icon config setting
* for an example.
*
* @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
* by language code, or `null` to remove the icon.
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
if ( this.icon !== icon ) {
if ( this.$icon ) {
if ( this.icon !== null ) {
this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
}
if ( icon !== null ) {
this.$icon.addClass( 'oo-ui-icon-' + icon );
}
}
this.icon = icon;
}
this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
if ( this.$icon ) {
this.$icon.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon );
}
this.updateThemeClasses();
return this;
};
/**
* Set the icon title. Use `null` to remove the title.
*
* @param {string|Function|null} iconTitle A text string used as the icon title,
* a function that returns title text, or `null` for no title.
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
iconTitle =
( typeof iconTitle === 'function' || ( typeof iconTitle === 'string' && iconTitle.length ) ) ?
OO.ui.resolveMsg( iconTitle ) : null;
if ( this.iconTitle !== iconTitle ) {
this.iconTitle = iconTitle;
if ( this.$icon ) {
if ( this.iconTitle !== null ) {
this.$icon.attr( 'title', iconTitle );
} else {
this.$icon.removeAttr( 'title' );
}
}
}
return this;
};
/**
* Get the symbolic name of the icon.
*
* @return {string} Icon name
*/
OO.ui.mixin.IconElement.prototype.getIcon = function () {
return this.icon;
};
/**
* Get the icon title. The title text is displayed when a user moves the mouse over the icon.
*
* @return {string} Icon title text
*/
OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
return this.iconTitle;
};
/**
* IndicatorElement is often mixed into other classes to generate an indicator.
* Indicators are small graphics that are generally used in two ways:
*
* - To draw attention to the status of an item. For example, an indicator might be
* used to show that an item in a list has errors that need to be resolved.
* - To clarify the function of a control that acts in an exceptional way (a button
* that opens a menu instead of performing an action directly, for example).
*
* For a list of indicators included in the library, please see the
* [OOUI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$indicator] The indicator element created by the class. If this
* configuration is omitted, the indicator element will use a generated `<span>`.
* @cfg {string} [indicator] Symbolic name of the indicator (e.g., โclearโ or โdownโ).
* See the [OOUI documentation on MediaWiki][2] for a list of indicators included
* in the library.
* [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
* @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
* or a function that returns title text. The indicator title is displayed when users move
* the mouse over the indicator.
*/
OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$indicator = null;
this.indicator = null;
this.indicatorTitle = null;
// Initialization
this.setIndicator( config.indicator || this.constructor.static.indicator );
this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
this.setIndicatorElement( config.$indicator || $( '<span>' ) );
};
/* Setup */
OO.initClass( OO.ui.mixin.IndicatorElement );
/* Static Properties */
/**
* Symbolic name of the indicator (e.g., โclearโ or โdownโ).
* The static property will be overridden if the #indicator configuration is used.
*
* @static
* @inheritable
* @property {string|null}
*/
OO.ui.mixin.IndicatorElement.static.indicator = null;
/**
* A text string used as the indicator title, a function that returns title text, or `null`
* for no title. The static property will be overridden if the #indicatorTitle configuration is used.
*
* @static
* @inheritable
* @property {string|Function|null}
*/
OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
/* Methods */
/**
* Set the indicator element.
*
* If an element is already set, it will be cleaned up before setting up the new element.
*
* @param {jQuery} $indicator Element to use as indicator
*/
OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
if ( this.$indicator ) {
this.$indicator
.removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
.removeAttr( 'title' );
}
this.$indicator = $indicator
.addClass( 'oo-ui-indicatorElement-indicator' )
.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator )
.toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
if ( this.indicatorTitle !== null ) {
this.$indicator.attr( 'title', this.indicatorTitle );
}
this.updateThemeClasses();
};
/**
* Set the indicator by its symbolic name: โclearโ, โdownโ, โrequiredโ, โsearchโ, โupโ. Use `null` to remove the indicator.
*
* @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
if ( this.indicator !== indicator ) {
if ( this.$indicator ) {
if ( this.indicator !== null ) {
this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
}
if ( indicator !== null ) {
this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
}
}
this.indicator = indicator;
}
this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
if ( this.$indicator ) {
this.$indicator.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator );
}
this.updateThemeClasses();
return this;
};
/**
* Set the indicator title.
*
* The title is displayed when a user moves the mouse over the indicator.
*
* @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
* `null` for no indicator title
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
indicatorTitle =
( typeof indicatorTitle === 'function' || ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ) ?
OO.ui.resolveMsg( indicatorTitle ) : null;
if ( this.indicatorTitle !== indicatorTitle ) {
this.indicatorTitle = indicatorTitle;
if ( this.$indicator ) {
if ( this.indicatorTitle !== null ) {
this.$indicator.attr( 'title', indicatorTitle );
} else {
this.$indicator.removeAttr( 'title' );
}
}
}
return this;
};
/**
* Get the symbolic name of the indicator (e.g., โclearโ or โdownโ).
*
* @return {string} Symbolic name of indicator
*/
OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
return this.indicator;
};
/**
* Get the indicator title.
*
* The title is displayed when a user moves the mouse over the indicator.
*
* @return {string} Indicator title text
*/
OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
return this.indicatorTitle;
};
/**
* The FlaggedElement class is an attribute mixin, meaning that it is used to add
* additional functionality to an element created by another class. The class provides
* a โflagsโ property assigned the name (or an array of names) of styling flags,
* which are used to customize the look and feel of a widget to better describe its
* importance and functionality.
*
* The library currently contains the following styling flags for general use:
*
* - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
* - **destructive**: Destructive styling is applied to convey that the widget will remove something.
*
* The flags affect the appearance of the buttons:
*
* @example
* // FlaggedElement is mixed into ButtonWidget to provide styling flags
* var button1 = new OO.ui.ButtonWidget( {
* label: 'Progressive',
* flags: 'progressive'
* } );
* var button2 = new OO.ui.ButtonWidget( {
* label: 'Destructive',
* flags: 'destructive'
* } );
* $( 'body' ).append( button1.$element, button2.$element );
*
* {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
* Please see the [OOUI documentation on MediaWiki] [1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary') to apply.
* Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
* [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
* @cfg {jQuery} [$flagged] The flagged element. By default,
* the flagged functionality is applied to the element created by the class ($element).
* If a different element is specified, the flagged functionality will be applied to it instead.
*/
OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.flags = {};
this.$flagged = null;
// Initialization
this.setFlags( config.flags );
this.setFlaggedElement( config.$flagged || this.$element );
};
/* Events */
/**
* @event flag
* A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
* parameter contains the name of each modified flag and indicates whether it was
* added or removed.
*
* @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
* that the flag was added, `false` that the flag was removed.
*/
/* Methods */
/**
* Set the flagged element.
*
* This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
* If an element is already set, the method will remove the mixinโs effect on that element.
*
* @param {jQuery} $flagged Element that should be flagged
*/
OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
var classNames = Object.keys( this.flags ).map( function ( flag ) {
return 'oo-ui-flaggedElement-' + flag;
} );
if ( this.$flagged ) {
this.$flagged.removeClass( classNames );
}
this.$flagged = $flagged.addClass( classNames );
};
/**
* Check if the specified flag is set.
*
* @param {string} flag Name of flag
* @return {boolean} The flag is set
*/
OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
// This may be called before the constructor, thus before this.flags is set
return this.flags && ( flag in this.flags );
};
/**
* Get the names of all flags set.
*
* @return {string[]} Flag names
*/
OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
// This may be called before the constructor, thus before this.flags is set
return Object.keys( this.flags || {} );
};
/**
* Clear all flags.
*
* @chainable
* @return {OO.ui.Element} The element, for chaining
* @fires flag
*/
OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
var flag, className,
changes = {},
remove = [],
classPrefix = 'oo-ui-flaggedElement-';
for ( flag in this.flags ) {
className = classPrefix + flag;
changes[ flag ] = false;
delete this.flags[ flag ];
remove.push( className );
}
if ( this.$flagged ) {
this.$flagged.removeClass( remove );
}
this.updateThemeClasses();
this.emit( 'flag', changes );
return this;
};
/**
* Add one or more flags.
*
* @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
* or an object keyed by flag name with a boolean value that indicates whether the flag should
* be added (`true`) or removed (`false`).
* @chainable
* @return {OO.ui.Element} The element, for chaining
* @fires flag
*/
OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
var i, len, flag, className,
changes = {},
add = [],
remove = [],
classPrefix = 'oo-ui-flaggedElement-';
if ( typeof flags === 'string' ) {
className = classPrefix + flags;
// Set
if ( !this.flags[ flags ] ) {
this.flags[ flags ] = true;
add.push( className );
}
} else if ( Array.isArray( flags ) ) {
for ( i = 0, len = flags.length; i < len; i++ ) {
flag = flags[ i ];
className = classPrefix + flag;
// Set
if ( !this.flags[ flag ] ) {
changes[ flag ] = true;
this.flags[ flag ] = true;
add.push( className );
}
}
} else if ( OO.isPlainObject( flags ) ) {
for ( flag in flags ) {
className = classPrefix + flag;
if ( flags[ flag ] ) {
// Set
if ( !this.flags[ flag ] ) {
changes[ flag ] = true;
this.flags[ flag ] = true;
add.push( className );
}
} else {
// Remove
if ( this.flags[ flag ] ) {
changes[ flag ] = false;
delete this.flags[ flag ];
remove.push( className );
}
}
}
}
if ( this.$flagged ) {
this.$flagged
.addClass( add )
.removeClass( remove );
}
this.updateThemeClasses();
this.emit( 'flag', changes );
return this;
};
/**
* TitledElement is mixed into other classes to provide a `title` attribute.
* Titles are rendered by the browser and are made visible when the user moves
* the mouse over the element. Titles are not visible on touch devices.
*
* @example
* // TitledElement provides a 'title' attribute to the
* // ButtonWidget class
* var button = new OO.ui.ButtonWidget( {
* label: 'Button with Title',
* title: 'I am a button'
* } );
* $( 'body' ).append( button.$element );
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
* If this config is omitted, the title functionality is applied to $element, the
* element created by the class.
* @cfg {string|Function} [title] The title text or a function that returns text. If
* this config is omitted, the value of the {@link #static-title static title} property is used.
*/
OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$titled = null;
this.title = null;
// Initialization
this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title );
this.setTitledElement( config.$titled || this.$element );
};
/* Setup */
OO.initClass( OO.ui.mixin.TitledElement );
/* Static Properties */
/**
* The title text, a function that returns text, or `null` for no title. The value of the static property
* is overridden if the #title config option is used.
*
* @static
* @inheritable
* @property {string|Function|null}
*/
OO.ui.mixin.TitledElement.static.title = null;
/* Methods */
/**
* Set the titled element.
*
* This method is used to retarget a TitledElement mixin so that its functionality applies to the specified element.
* If an element is already set, the mixinโs effect on that element is removed before the new element is set up.
*
* @param {jQuery} $titled Element that should use the 'titled' functionality
*/
OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
if ( this.$titled ) {
this.$titled.removeAttr( 'title' );
}
this.$titled = $titled;
if ( this.title ) {
this.updateTitle();
}
};
/**
* Set title.
*
* @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
title = ( typeof title === 'string' && title.length ) ? title : null;
if ( this.title !== title ) {
this.title = title;
this.updateTitle();
}
return this;
};
/**
* Update the title attribute, in case of changes to title or accessKey.
*
* @protected
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.TitledElement.prototype.updateTitle = function () {
var title = this.getTitle();
if ( this.$titled ) {
if ( title !== null ) {
// Only if this is an AccessKeyedElement
if ( this.formatTitleWithAccessKey ) {
title = this.formatTitleWithAccessKey( title );
}
this.$titled.attr( 'title', title );
} else {
this.$titled.removeAttr( 'title' );
}
}
return this;
};
/**
* Get title.
*
* @return {string} Title string
*/
OO.ui.mixin.TitledElement.prototype.getTitle = function () {
return this.title;
};
/**
* AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
* Accesskeys allow an user to go to a specific element by using
* a shortcut combination of a browser specific keys + the key
* set to the field.
*
* @example
* // AccessKeyedElement provides an 'accesskey' attribute to the
* // ButtonWidget class
* var button = new OO.ui.ButtonWidget( {
* label: 'Button with Accesskey',
* accessKey: 'k'
* } );
* $( 'body' ).append( button.$element );
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
* If this config is omitted, the accesskey functionality is applied to $element, the
* element created by the class.
* @cfg {string|Function} [accessKey] The key or a function that returns the key. If
* this config is omitted, no accesskey will be added.
*/
OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$accessKeyed = null;
this.accessKey = null;
// Initialization
this.setAccessKey( config.accessKey || null );
this.setAccessKeyedElement( config.$accessKeyed || this.$element );
// If this is also a TitledElement and it initialized before we did, we may have
// to update the title with the access key
if ( this.updateTitle ) {
this.updateTitle();
}
};
/* Setup */
OO.initClass( OO.ui.mixin.AccessKeyedElement );
/* Static Properties */
/**
* The access key, a function that returns a key, or `null` for no accesskey.
*
* @static
* @inheritable
* @property {string|Function|null}
*/
OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
/* Methods */
/**
* Set the accesskeyed element.
*
* This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
* If an element is already set, the mixin's effect on that element is removed before the new element is set up.
*
* @param {jQuery} $accessKeyed Element that should use the 'accesskeyed' functionality
*/
OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
if ( this.$accessKeyed ) {
this.$accessKeyed.removeAttr( 'accesskey' );
}
this.$accessKeyed = $accessKeyed;
if ( this.accessKey ) {
this.$accessKeyed.attr( 'accesskey', this.accessKey );
}
};
/**
* Set accesskey.
*
* @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
if ( this.accessKey !== accessKey ) {
if ( this.$accessKeyed ) {
if ( accessKey !== null ) {
this.$accessKeyed.attr( 'accesskey', accessKey );
} else {
this.$accessKeyed.removeAttr( 'accesskey' );
}
}
this.accessKey = accessKey;
// Only if this is a TitledElement
if ( this.updateTitle ) {
this.updateTitle();
}
}
return this;
};
/**
* Get accesskey.
*
* @return {string} accessKey string
*/
OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
return this.accessKey;
};
/**
* Add information about the access key to the element's tooltip label.
* (This is only public for hacky usage in FieldLayout.)
*
* @param {string} title Tooltip label for `title` attribute
* @return {string}
*/
OO.ui.mixin.AccessKeyedElement.prototype.formatTitleWithAccessKey = function ( title ) {
var accessKey;
if ( !this.$accessKeyed ) {
// Not initialized yet; the constructor will call updateTitle() which will rerun this function
return title;
}
// Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
if ( $.fn.updateTooltipAccessKeys && $.fn.updateTooltipAccessKeys.getAccessKeyLabel ) {
accessKey = $.fn.updateTooltipAccessKeys.getAccessKeyLabel( this.$accessKeyed[ 0 ] );
} else {
accessKey = this.getAccessKey();
}
if ( accessKey ) {
title += ' [' + accessKey + ']';
}
return title;
};
/**
* ButtonWidget is a generic widget for buttons. A wide variety of looks,
* feels, and functionality can be customized via the classโs configuration options
* and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
* and examples.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
*
* @example
* // A button widget
* var button = new OO.ui.ButtonWidget( {
* label: 'Button with Icon',
* icon: 'trash',
* title: 'Remove'
* } );
* $( 'body' ).append( button.$element );
*
* NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.ButtonElement
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.TitledElement
* @mixins OO.ui.mixin.FlaggedElement
* @mixins OO.ui.mixin.TabIndexedElement
* @mixins OO.ui.mixin.AccessKeyedElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [active=false] Whether button should be shown as active
* @cfg {string} [href] Hyperlink to visit when the button is clicked.
* @cfg {string} [target] The frame or window in which to open the hyperlink.
* @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
*/
OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.ButtonWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.ButtonElement.call( this, config );
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
OO.ui.mixin.FlaggedElement.call( this, config );
OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
// Properties
this.href = null;
this.target = null;
this.noFollow = false;
// Events
this.connect( this, { disable: 'onDisable' } );
// Initialization
this.$button.append( this.$icon, this.$label, this.$indicator );
this.$element
.addClass( 'oo-ui-buttonWidget' )
.append( this.$button );
this.setActive( config.active );
this.setHref( config.href );
this.setTarget( config.target );
this.setNoFollow( config.noFollow );
};
/* Setup */
OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.ButtonWidget.static.cancelButtonMouseDownEvents = false;
/**
* @static
* @inheritdoc
*/
OO.ui.ButtonWidget.static.tagName = 'span';
/* Methods */
/**
* Get hyperlink location.
*
* @return {string} Hyperlink location
*/
OO.ui.ButtonWidget.prototype.getHref = function () {
return this.href;
};
/**
* Get hyperlink target.
*
* @return {string} Hyperlink target
*/
OO.ui.ButtonWidget.prototype.getTarget = function () {
return this.target;
};
/**
* Get search engine traversal hint.
*
* @return {boolean} Whether search engines should avoid traversing this hyperlink
*/
OO.ui.ButtonWidget.prototype.getNoFollow = function () {
return this.noFollow;
};
/**
* Set hyperlink location.
*
* @param {string|null} href Hyperlink location, null to remove
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
href = typeof href === 'string' ? href : null;
if ( href !== null && !OO.ui.isSafeUrl( href ) ) {
href = './' + href;
}
if ( href !== this.href ) {
this.href = href;
this.updateHref();
}
return this;
};
/**
* Update the `href` attribute, in case of changes to href or
* disabled state.
*
* @private
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.ButtonWidget.prototype.updateHref = function () {
if ( this.href !== null && !this.isDisabled() ) {
this.$button.attr( 'href', this.href );
} else {
this.$button.removeAttr( 'href' );
}
return this;
};
/**
* Handle disable events.
*
* @private
* @param {boolean} disabled Element is disabled
*/
OO.ui.ButtonWidget.prototype.onDisable = function () {
this.updateHref();
};
/**
* Set hyperlink target.
*
* @param {string|null} target Hyperlink target, null to remove
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
target = typeof target === 'string' ? target : null;
if ( target !== this.target ) {
this.target = target;
if ( target !== null ) {
this.$button.attr( 'target', target );
} else {
this.$button.removeAttr( 'target' );
}
}
return this;
};
/**
* Set search engine traversal hint.
*
* @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
noFollow = typeof noFollow === 'boolean' ? noFollow : true;
if ( noFollow !== this.noFollow ) {
this.noFollow = noFollow;
if ( noFollow ) {
this.$button.attr( 'rel', 'nofollow' );
} else {
this.$button.removeAttr( 'rel' );
}
}
return this;
};
// Override method visibility hints from ButtonElement
/**
* @method setActive
* @inheritdoc
*/
/**
* @method isActive
* @inheritdoc
*/
/**
* A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
* its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
* removed, and cleared from the group.
*
* @example
* // Example: A ButtonGroupWidget with two buttons
* var button1 = new OO.ui.PopupButtonWidget( {
* label: 'Select a category',
* icon: 'menu',
* popup: {
* $content: $( '<p>List of categories...</p>' ),
* padded: true,
* align: 'left'
* }
* } );
* var button2 = new OO.ui.ButtonWidget( {
* label: 'Add item'
* });
* var buttonGroup = new OO.ui.ButtonGroupWidget( {
* items: [button1, button2]
* } );
* $( 'body' ).append( buttonGroup.$element );
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
*/
OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.ButtonGroupWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
// Initialization
this.$element.addClass( 'oo-ui-buttonGroupWidget' );
if ( Array.isArray( config.items ) ) {
this.addItems( config.items );
}
};
/* Setup */
OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.ButtonGroupWidget.static.tagName = 'span';
/* Methods */
/**
* Focus the widget
*
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.ButtonGroupWidget.prototype.focus = function () {
if ( !this.isDisabled() ) {
if ( this.items[ 0 ] ) {
this.items[ 0 ].focus();
}
}
return this;
};
/**
* @inheritdoc
*/
OO.ui.ButtonGroupWidget.prototype.simulateLabelClick = function () {
this.focus();
};
/**
* IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
* which creates a label that identifies the iconโs function. See the [OOUI documentation on MediaWiki] [1]
* for a list of icons included in the library.
*
* @example
* // An icon widget with a label
* var myIcon = new OO.ui.IconWidget( {
* icon: 'help',
* title: 'Help'
* } );
* // Create a label.
* var iconLabel = new OO.ui.LabelWidget( {
* label: 'Help'
* } );
* $( 'body' ).append( myIcon.$element, iconLabel.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.TitledElement
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.FlaggedElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.IconWidget = function OoUiIconWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.IconWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element, invisibleLabel: true } ) );
OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
// Initialization
this.$element.addClass( 'oo-ui-iconWidget' );
// Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
// nested in other widgets, because this widget used to not mix in LabelElement.
this.$element.removeClass( 'oo-ui-labelElement-label' );
};
/* Setup */
OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.IconWidget.static.tagName = 'span';
/**
* IndicatorWidgets create indicators, which are small graphics that are generally used to draw
* attention to the status of an item or to clarify the function within a control. For a list of
* indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
*
* @example
* // Example of an indicator widget
* var indicator1 = new OO.ui.IndicatorWidget( {
* indicator: 'required'
* } );
*
* // Create a fieldset layout to add a label
* var fieldset = new OO.ui.FieldsetLayout();
* fieldset.addItems( [
* new OO.ui.FieldLayout( indicator1, { label: 'A required indicator:' } )
* ] );
* $( 'body' ).append( fieldset.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.TitledElement
* @mixins OO.ui.mixin.LabelElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.IndicatorWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element, invisibleLabel: true } ) );
// Initialization
this.$element.addClass( 'oo-ui-indicatorWidget' );
// Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
// nested in other widgets, because this widget used to not mix in LabelElement.
this.$element.removeClass( 'oo-ui-labelElement-label' );
};
/* Setup */
OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.LabelElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.IndicatorWidget.static.tagName = 'span';
/**
* LabelWidgets help identify the function of interface elements. Each LabelWidget can
* be configured with a `label` option that is set to a string, a label node, or a function:
*
* - String: a plaintext string
* - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
* label that includes a link or special styling, such as a gray color or additional graphical elements.
* - Function: a function that will produce a string in the future. Functions are used
* in cases where the value of the label is not currently defined.
*
* In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
* will come into focus when the label is clicked.
*
* @example
* // Examples of LabelWidgets
* var label1 = new OO.ui.LabelWidget( {
* label: 'plaintext label'
* } );
* var label2 = new OO.ui.LabelWidget( {
* label: $( '<a href="default.html">jQuery label</a>' )
* } );
* // Create a fieldset layout with fields for each example
* var fieldset = new OO.ui.FieldsetLayout();
* fieldset.addItems( [
* new OO.ui.FieldLayout( label1 ),
* new OO.ui.FieldLayout( label2 )
* ] );
* $( 'body' ).append( fieldset.$element );
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.TitledElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
* Clicking the label will focus the specified input field.
*/
OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.LabelWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
OO.ui.mixin.TitledElement.call( this, config );
// Properties
this.input = config.input;
// Initialization
if ( this.input ) {
if ( this.input.getInputId() ) {
this.$element.attr( 'for', this.input.getInputId() );
} else {
this.$label.on( 'click', function () {
this.input.simulateLabelClick();
}.bind( this ) );
}
}
this.$element.addClass( 'oo-ui-labelWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.LabelWidget.static.tagName = 'label';
/**
* PendingElement is a mixin that is used to create elements that notify users that something is happening
* and that they should wait before proceeding. The pending state is visually represented with a pending
* texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
* field of a {@link OO.ui.TextInputWidget text input widget}.
*
* Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
* used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
* in process dialogs.
*
* @example
* function MessageDialog( config ) {
* MessageDialog.parent.call( this, config );
* }
* OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
*
* MessageDialog.static.name = 'myMessageDialog';
* MessageDialog.static.actions = [
* { action: 'save', label: 'Done', flags: 'primary' },
* { label: 'Cancel', flags: 'safe' }
* ];
*
* MessageDialog.prototype.initialize = function () {
* MessageDialog.parent.prototype.initialize.apply( this, arguments );
* this.content = new OO.ui.PanelLayout( { padded: true } );
* this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
* this.$body.append( this.content.$element );
* };
* MessageDialog.prototype.getBodyHeight = function () {
* return 100;
* }
* MessageDialog.prototype.getActionProcess = function ( action ) {
* var dialog = this;
* if ( action === 'save' ) {
* dialog.getActions().get({actions: 'save'})[0].pushPending();
* return new OO.ui.Process()
* .next( 1000 )
* .next( function () {
* dialog.getActions().get({actions: 'save'})[0].popPending();
* } );
* }
* return MessageDialog.parent.prototype.getActionProcess.call( this, action );
* };
*
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
*
* var dialog = new MessageDialog();
* windowManager.addWindows( [ dialog ] );
* windowManager.openWindow( dialog );
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
*/
OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.pending = 0;
this.$pending = null;
// Initialisation
this.setPendingElement( config.$pending || this.$element );
};
/* Setup */
OO.initClass( OO.ui.mixin.PendingElement );
/* Methods */
/**
* Set the pending element (and clean up any existing one).
*
* @param {jQuery} $pending The element to set to pending.
*/
OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
if ( this.$pending ) {
this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
}
this.$pending = $pending;
if ( this.pending > 0 ) {
this.$pending.addClass( 'oo-ui-pendingElement-pending' );
}
};
/**
* Check if an element is pending.
*
* @return {boolean} Element is pending
*/
OO.ui.mixin.PendingElement.prototype.isPending = function () {
return !!this.pending;
};
/**
* Increase the pending counter. The pending state will remain active until the counter is zero
* (i.e., the number of calls to #pushPending and #popPending is the same).
*
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.PendingElement.prototype.pushPending = function () {
if ( this.pending === 0 ) {
this.$pending.addClass( 'oo-ui-pendingElement-pending' );
this.updateThemeClasses();
}
this.pending++;
return this;
};
/**
* Decrease the pending counter. The pending state will remain active until the counter is zero
* (i.e., the number of calls to #pushPending and #popPending is the same).
*
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.PendingElement.prototype.popPending = function () {
if ( this.pending === 1 ) {
this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
this.updateThemeClasses();
}
this.pending = Math.max( 0, this.pending - 1 );
return this;
};
/**
* Element that will stick adjacent to a specified container, even when it is inserted elsewhere
* in the document (for example, in an OO.ui.Window's $overlay).
*
* The elements's position is automatically calculated and maintained when window is resized or the
* page is scrolled. If you reposition the container manually, you have to call #position to make
* sure the element is still placed correctly.
*
* As positioning is only possible when both the element and the container are attached to the DOM
* and visible, it's only done after you call #togglePositioning. You might want to do this inside
* the #toggle method to display a floating popup, for example.
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
* @cfg {jQuery} [$floatableContainer] Node to position adjacent to
* @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
* 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
* 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
* 'top': Align the top edge with $floatableContainer's top edge
* 'bottom': Align the bottom edge with $floatableContainer's bottom edge
* 'center': Vertically align the center with $floatableContainer's center
* @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
* 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
* 'after': Directly after $floatableContainer, aligning f's start edge with fC's end edge
* 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
* 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
* 'center': Horizontally align the center with $floatableContainer's center
* @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
* is out of view
*/
OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$floatable = null;
this.$floatableContainer = null;
this.$floatableWindow = null;
this.$floatableClosestScrollable = null;
this.floatableOutOfView = false;
this.onFloatableScrollHandler = this.position.bind( this );
this.onFloatableWindowResizeHandler = this.position.bind( this );
// Initialization
this.setFloatableContainer( config.$floatableContainer );
this.setFloatableElement( config.$floatable || this.$element );
this.setVerticalPosition( config.verticalPosition || 'below' );
this.setHorizontalPosition( config.horizontalPosition || 'start' );
this.hideWhenOutOfView = config.hideWhenOutOfView === undefined ? true : !!config.hideWhenOutOfView;
};
/* Methods */
/**
* Set floatable element.
*
* If an element is already set, it will be cleaned up before setting up the new element.
*
* @param {jQuery} $floatable Element to make floatable
*/
OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
if ( this.$floatable ) {
this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
this.$floatable.css( { left: '', top: '' } );
}
this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
this.position();
};
/**
* Set floatable container.
*
* The element will be positioned relative to the specified container.
*
* @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
*/
OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
this.$floatableContainer = $floatableContainer;
if ( this.$floatable ) {
this.position();
}
};
/**
* Change how the element is positioned vertically.
*
* @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
*/
OO.ui.mixin.FloatableElement.prototype.setVerticalPosition = function ( position ) {
if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position ) === -1 ) {
throw new Error( 'Invalid value for vertical position: ' + position );
}
if ( this.verticalPosition !== position ) {
this.verticalPosition = position;
if ( this.$floatable ) {
this.position();
}
}
};
/**
* Change how the element is positioned horizontally.
*
* @param {string} position 'before', 'after', 'start', 'end' or 'center'
*/
OO.ui.mixin.FloatableElement.prototype.setHorizontalPosition = function ( position ) {
if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position ) === -1 ) {
throw new Error( 'Invalid value for horizontal position: ' + position );
}
if ( this.horizontalPosition !== position ) {
this.horizontalPosition = position;
if ( this.$floatable ) {
this.position();
}
}
};
/**
* Toggle positioning.
*
* Do not turn positioning on until after the element is attached to the DOM and visible.
*
* @param {boolean} [positioning] Enable positioning, omit to toggle
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
var closestScrollableOfContainer;
if ( !this.$floatable || !this.$floatableContainer ) {
return this;
}
positioning = positioning === undefined ? !this.positioning : !!positioning;
if ( positioning && !this.warnedUnattached && !this.isElementAttached() ) {
OO.ui.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
this.warnedUnattached = true;
}
if ( this.positioning !== positioning ) {
this.positioning = positioning;
closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
// If the scrollable is the root, we have to listen to scroll events
// on the window because of browser inconsistencies.
if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
}
if ( positioning ) {
this.$floatableWindow = $( this.getElementWindow() );
this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
this.$floatableClosestScrollable = $( closestScrollableOfContainer );
this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
// Initial position after visible
this.position();
} else {
if ( this.$floatableWindow ) {
this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
this.$floatableWindow = null;
}
if ( this.$floatableClosestScrollable ) {
this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
this.$floatableClosestScrollable = null;
}
this.$floatable.css( { left: '', right: '', top: '' } );
}
}
return this;
};
/**
* Check whether the bottom edge of the given element is within the viewport of the given container.
*
* @private
* @param {jQuery} $element
* @param {jQuery} $container
* @return {boolean}
*/
OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) {
var elemRect, contRect, topEdgeInBounds, bottomEdgeInBounds, leftEdgeInBounds, rightEdgeInBounds,
startEdgeInBounds, endEdgeInBounds, viewportSpacing,
direction = $element.css( 'direction' );
elemRect = $element[ 0 ].getBoundingClientRect();
if ( $container[ 0 ] === window ) {
viewportSpacing = OO.ui.getViewportSpacing();
contRect = {
top: 0,
left: 0,
right: document.documentElement.clientWidth,
bottom: document.documentElement.clientHeight
};
contRect.top += viewportSpacing.top;
contRect.left += viewportSpacing.left;
contRect.right -= viewportSpacing.right;
contRect.bottom -= viewportSpacing.bottom;
} else {
contRect = $container[ 0 ].getBoundingClientRect();
}
topEdgeInBounds = elemRect.top >= contRect.top && elemRect.top <= contRect.bottom;
bottomEdgeInBounds = elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom;
leftEdgeInBounds = elemRect.left >= contRect.left && elemRect.left <= contRect.right;
rightEdgeInBounds = elemRect.right >= contRect.left && elemRect.right <= contRect.right;
if ( direction === 'rtl' ) {
startEdgeInBounds = rightEdgeInBounds;
endEdgeInBounds = leftEdgeInBounds;
} else {
startEdgeInBounds = leftEdgeInBounds;
endEdgeInBounds = rightEdgeInBounds;
}
if ( this.verticalPosition === 'below' && !bottomEdgeInBounds ) {
return false;
}
if ( this.verticalPosition === 'above' && !topEdgeInBounds ) {
return false;
}
if ( this.horizontalPosition === 'before' && !startEdgeInBounds ) {
return false;
}
if ( this.horizontalPosition === 'after' && !endEdgeInBounds ) {
return false;
}
// The other positioning values are all about being inside the container,
// so in those cases all we care about is that any part of the container is visible.
return elemRect.top <= contRect.bottom && elemRect.bottom >= contRect.top &&
elemRect.left <= contRect.right && elemRect.right >= contRect.left;
};
/**
* Check if the floatable is hidden to the user because it was offscreen.
*
* @return {boolean} Floatable is out of view
*/
OO.ui.mixin.FloatableElement.prototype.isFloatableOutOfView = function () {
return this.floatableOutOfView;
};
/**
* Position the floatable below its container.
*
* This should only be done when both of them are attached to the DOM and visible.
*
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.FloatableElement.prototype.position = function () {
if ( !this.positioning ) {
return this;
}
if ( !(
// To continue, some things need to be true:
// The element must actually be in the DOM
this.isElementAttached() && (
// The closest scrollable is the current window
this.$floatableClosestScrollable[ 0 ] === this.getElementWindow() ||
// OR is an element in the element's DOM
$.contains( this.getElementDocument(), this.$floatableClosestScrollable[ 0 ] )
)
) ) {
// Abort early if important parts of the widget are no longer attached to the DOM
return this;
}
this.floatableOutOfView = this.hideWhenOutOfView && !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable );
if ( this.floatableOutOfView ) {
this.$floatable.addClass( 'oo-ui-element-hidden' );
return this;
} else {
this.$floatable.removeClass( 'oo-ui-element-hidden' );
}
this.$floatable.css( this.computePosition() );
// We updated the position, so re-evaluate the clipping state.
// (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
// will not notice the need to update itself.)
// TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
// it not listen to the right events in the right places?
if ( this.clip ) {
this.clip();
}
return this;
};
/**
* Compute how #$floatable should be positioned based on the position of #$floatableContainer
* and the positioning settings. This is a helper for #position that shouldn't be called directly,
* but may be overridden by subclasses if they want to change or add to the positioning logic.
*
* @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
*/
OO.ui.mixin.FloatableElement.prototype.computePosition = function () {
var isBody, scrollableX, scrollableY, containerPos,
horizScrollbarHeight, vertScrollbarWidth, scrollTop, scrollLeft,
newPos = { top: '', left: '', bottom: '', right: '' },
direction = this.$floatableContainer.css( 'direction' ),
$offsetParent = this.$floatable.offsetParent();
if ( $offsetParent.is( 'html' ) ) {
// The innerHeight/Width and clientHeight/Width calculations don't work well on the
// <html> element, but they do work on the <body>
$offsetParent = $( $offsetParent[ 0 ].ownerDocument.body );
}
isBody = $offsetParent.is( 'body' );
scrollableX = $offsetParent.css( 'overflow-x' ) === 'scroll' || $offsetParent.css( 'overflow-x' ) === 'auto';
scrollableY = $offsetParent.css( 'overflow-y' ) === 'scroll' || $offsetParent.css( 'overflow-y' ) === 'auto';
vertScrollbarWidth = $offsetParent.innerWidth() - $offsetParent.prop( 'clientWidth' );
horizScrollbarHeight = $offsetParent.innerHeight() - $offsetParent.prop( 'clientHeight' );
// We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
// or if it isn't scrollable
scrollTop = scrollableY && !isBody ? $offsetParent.scrollTop() : 0;
scrollLeft = scrollableX && !isBody ? OO.ui.Element.static.getScrollLeft( $offsetParent[ 0 ] ) : 0;
// Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
// if the <body> has a margin
containerPos = isBody ?
this.$floatableContainer.offset() :
OO.ui.Element.static.getRelativePosition( this.$floatableContainer, $offsetParent );
containerPos.bottom = containerPos.top + this.$floatableContainer.outerHeight();
containerPos.right = containerPos.left + this.$floatableContainer.outerWidth();
containerPos.start = direction === 'rtl' ? containerPos.right : containerPos.left;
containerPos.end = direction === 'rtl' ? containerPos.left : containerPos.right;
if ( this.verticalPosition === 'below' ) {
newPos.top = containerPos.bottom;
} else if ( this.verticalPosition === 'above' ) {
newPos.bottom = $offsetParent.outerHeight() - containerPos.top;
} else if ( this.verticalPosition === 'top' ) {
newPos.top = containerPos.top;
} else if ( this.verticalPosition === 'bottom' ) {
newPos.bottom = $offsetParent.outerHeight() - containerPos.bottom;
} else if ( this.verticalPosition === 'center' ) {
newPos.top = containerPos.top +
( this.$floatableContainer.height() - this.$floatable.height() ) / 2;
}
if ( this.horizontalPosition === 'before' ) {
newPos.end = containerPos.start;
} else if ( this.horizontalPosition === 'after' ) {
newPos.start = containerPos.end;
} else if ( this.horizontalPosition === 'start' ) {
newPos.start = containerPos.start;
} else if ( this.horizontalPosition === 'end' ) {
newPos.end = containerPos.end;
} else if ( this.horizontalPosition === 'center' ) {
newPos.left = containerPos.left +
( this.$floatableContainer.width() - this.$floatable.width() ) / 2;
}
if ( newPos.start !== undefined ) {
if ( direction === 'rtl' ) {
newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.start;
} else {
newPos.left = newPos.start;
}
delete newPos.start;
}
if ( newPos.end !== undefined ) {
if ( direction === 'rtl' ) {
newPos.left = newPos.end;
} else {
newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.end;
}
delete newPos.end;
}
// Account for scroll position
if ( newPos.top !== '' ) {
newPos.top += scrollTop;
}
if ( newPos.bottom !== '' ) {
newPos.bottom -= scrollTop;
}
if ( newPos.left !== '' ) {
newPos.left += scrollLeft;
}
if ( newPos.right !== '' ) {
newPos.right -= scrollLeft;
}
// Account for scrollbar gutter
if ( newPos.bottom !== '' ) {
newPos.bottom -= horizScrollbarHeight;
}
if ( direction === 'rtl' ) {
if ( newPos.left !== '' ) {
newPos.left -= vertScrollbarWidth;
}
} else {
if ( newPos.right !== '' ) {
newPos.right -= vertScrollbarWidth;
}
}
return newPos;
};
/**
* Element that can be automatically clipped to visible boundaries.
*
* Whenever the element's natural height changes, you have to call
* {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
* clipping correctly.
*
* The dimensions of #$clippableContainer will be compared to the boundaries of the
* nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
* then #$clippable will be given a fixed reduced height and/or width and will be made
* scrollable. By default, #$clippable and #$clippableContainer are the same element,
* but you can build a static footer by setting #$clippableContainer to an element that contains
* #$clippable and the footer.
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
* @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
* omit to use #$clippable
*/
OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$clippable = null;
this.$clippableContainer = null;
this.clipping = false;
this.clippedHorizontally = false;
this.clippedVertically = false;
this.$clippableScrollableContainer = null;
this.$clippableScroller = null;
this.$clippableWindow = null;
this.idealWidth = null;
this.idealHeight = null;
this.onClippableScrollHandler = this.clip.bind( this );
this.onClippableWindowResizeHandler = this.clip.bind( this );
// Initialization
if ( config.$clippableContainer ) {
this.setClippableContainer( config.$clippableContainer );
}
this.setClippableElement( config.$clippable || this.$element );
};
/* Methods */
/**
* Set clippable element.
*
* If an element is already set, it will be cleaned up before setting up the new element.
*
* @param {jQuery} $clippable Element to make clippable
*/
OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
if ( this.$clippable ) {
this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
}
this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
this.clip();
};
/**
* Set clippable container.
*
* This is the container that will be measured when deciding whether to clip. When clipping,
* #$clippable will be resized in order to keep the clippable container fully visible.
*
* If the clippable container is unset, #$clippable will be used.
*
* @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
*/
OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
this.$clippableContainer = $clippableContainer;
if ( this.$clippable ) {
this.clip();
}
};
/**
* Toggle clipping.
*
* Do not turn clipping on until after the element is attached to the DOM and visible.
*
* @param {boolean} [clipping] Enable clipping, omit to toggle
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
clipping = clipping === undefined ? !this.clipping : !!clipping;
if ( clipping && !this.warnedUnattached && !this.isElementAttached() ) {
OO.ui.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
this.warnedUnattached = true;
}
if ( this.clipping !== clipping ) {
this.clipping = clipping;
if ( clipping ) {
this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
// If the clippable container is the root, we have to listen to scroll events and check
// jQuery.scrollTop on the window because of browser inconsistencies
this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
$( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
this.$clippableScrollableContainer;
this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
this.$clippableWindow = $( this.getElementWindow() )
.on( 'resize', this.onClippableWindowResizeHandler );
// Initial clip after visible
this.clip();
} else {
this.$clippable.css( {
width: '',
height: '',
maxWidth: '',
maxHeight: '',
overflowX: '',
overflowY: ''
} );
OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
this.$clippableScrollableContainer = null;
this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
this.$clippableScroller = null;
this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
this.$clippableWindow = null;
}
}
return this;
};
/**
* Check if the element will be clipped to fit the visible area of the nearest scrollable container.
*
* @return {boolean} Element will be clipped to the visible area
*/
OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
return this.clipping;
};
/**
* Check if the bottom or right of the element is being clipped by the nearest scrollable container.
*
* @return {boolean} Part of the element is being clipped
*/
OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
return this.clippedHorizontally || this.clippedVertically;
};
/**
* Check if the right of the element is being clipped by the nearest scrollable container.
*
* @return {boolean} Part of the element is being clipped
*/
OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
return this.clippedHorizontally;
};
/**
* Check if the bottom of the element is being clipped by the nearest scrollable container.
*
* @return {boolean} Part of the element is being clipped
*/
OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
return this.clippedVertically;
};
/**
* Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
*
* @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
* @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
*/
OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
this.idealWidth = width;
this.idealHeight = height;
if ( !this.clipping ) {
// Update dimensions
this.$clippable.css( { width: width, height: height } );
}
// While clipping, idealWidth and idealHeight are not considered
};
/**
* Return the side of the clippable on which it is "anchored" (aligned to something else).
* ClippableElement will clip the opposite side when reducing element's width.
*
* Classes that mix in ClippableElement should override this to return 'right' if their
* clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
* If your class also mixes in FloatableElement, this is handled automatically.
*
* (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
* always in pixels, even if they were unset or set to 'auto'.)
*
* When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
*
* @return {string} 'left' or 'right'
*/
OO.ui.mixin.ClippableElement.prototype.getHorizontalAnchorEdge = function () {
if ( this.computePosition && this.positioning && this.computePosition().right !== '' ) {
return 'right';
}
return 'left';
};
/**
* Return the side of the clippable on which it is "anchored" (aligned to something else).
* ClippableElement will clip the opposite side when reducing element's width.
*
* Classes that mix in ClippableElement should override this to return 'bottom' if their
* clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
* If your class also mixes in FloatableElement, this is handled automatically.
*
* (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
* always in pixels, even if they were unset or set to 'auto'.)
*
* When in doubt, 'top' is a sane fallback.
*
* @return {string} 'top' or 'bottom'
*/
OO.ui.mixin.ClippableElement.prototype.getVerticalAnchorEdge = function () {
if ( this.computePosition && this.positioning && this.computePosition().bottom !== '' ) {
return 'bottom';
}
return 'top';
};
/**
* Clip element to visible boundaries and allow scrolling when needed. You should call this method
* when the element's natural height changes.
*
* Element will be clipped the bottom or right of the element is within 10px of the edge of, or
* overlapped by, the visible area of the nearest scrollable container.
*
* Because calling clip() when the natural height changes isn't always possible, we also set
* max-height when the element isn't being clipped. This means that if the element tries to grow
* beyond the edge, something reasonable will happen before clip() is called.
*
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.ClippableElement.prototype.clip = function () {
var extraHeight, extraWidth, viewportSpacing,
desiredWidth, desiredHeight, allotedWidth, allotedHeight,
naturalWidth, naturalHeight, clipWidth, clipHeight,
$item, itemRect, $viewport, viewportRect, availableRect,
direction, vertScrollbarWidth, horizScrollbarHeight,
// Extra tolerance so that the sloppy code below doesn't result in results that are off
// by one or two pixels. (And also so that we have space to display drop shadows.)
// Chosen by fair dice roll.
buffer = 7;
if ( !this.clipping ) {
// this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
return this;
}
function rectIntersection( a, b ) {
var out = {};
out.top = Math.max( a.top, b.top );
out.left = Math.max( a.left, b.left );
out.bottom = Math.min( a.bottom, b.bottom );
out.right = Math.min( a.right, b.right );
return out;
}
viewportSpacing = OO.ui.getViewportSpacing();
if ( this.$clippableScrollableContainer.is( 'html, body' ) ) {
$viewport = $( this.$clippableScrollableContainer[ 0 ].ownerDocument.body );
// Dimensions of the browser window, rather than the element!
viewportRect = {
top: 0,
left: 0,
right: document.documentElement.clientWidth,
bottom: document.documentElement.clientHeight
};
viewportRect.top += viewportSpacing.top;
viewportRect.left += viewportSpacing.left;
viewportRect.right -= viewportSpacing.right;
viewportRect.bottom -= viewportSpacing.bottom;
} else {
$viewport = this.$clippableScrollableContainer;
viewportRect = $viewport[ 0 ].getBoundingClientRect();
// Convert into a plain object
viewportRect = $.extend( {}, viewportRect );
}
// Account for scrollbar gutter
direction = $viewport.css( 'direction' );
vertScrollbarWidth = $viewport.innerWidth() - $viewport.prop( 'clientWidth' );
horizScrollbarHeight = $viewport.innerHeight() - $viewport.prop( 'clientHeight' );
viewportRect.bottom -= horizScrollbarHeight;
if ( direction === 'rtl' ) {
viewportRect.left += vertScrollbarWidth;
} else {
viewportRect.right -= vertScrollbarWidth;
}
// Add arbitrary tolerance
viewportRect.top += buffer;
viewportRect.left += buffer;
viewportRect.right -= buffer;
viewportRect.bottom -= buffer;
$item = this.$clippableContainer || this.$clippable;
extraHeight = $item.outerHeight() - this.$clippable.outerHeight();
extraWidth = $item.outerWidth() - this.$clippable.outerWidth();
itemRect = $item[ 0 ].getBoundingClientRect();
// Convert into a plain object
itemRect = $.extend( {}, itemRect );
// Item might already be clipped, so we can't just use its dimensions (in case we might need to
// make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
if ( this.getHorizontalAnchorEdge() === 'right' ) {
itemRect.left = viewportRect.left;
} else {
itemRect.right = viewportRect.right;
}
if ( this.getVerticalAnchorEdge() === 'bottom' ) {
itemRect.top = viewportRect.top;
} else {
itemRect.bottom = viewportRect.bottom;
}
availableRect = rectIntersection( viewportRect, itemRect );
desiredWidth = Math.max( 0, availableRect.right - availableRect.left );
desiredHeight = Math.max( 0, availableRect.bottom - availableRect.top );
// It should never be desirable to exceed the dimensions of the browser viewport... right?
desiredWidth = Math.min( desiredWidth,
document.documentElement.clientWidth - viewportSpacing.left - viewportSpacing.right );
desiredHeight = Math.min( desiredHeight,
document.documentElement.clientHeight - viewportSpacing.top - viewportSpacing.right );
allotedWidth = Math.ceil( desiredWidth - extraWidth );
allotedHeight = Math.ceil( desiredHeight - extraHeight );
naturalWidth = this.$clippable.prop( 'scrollWidth' );
naturalHeight = this.$clippable.prop( 'scrollHeight' );
clipWidth = allotedWidth < naturalWidth;
clipHeight = allotedHeight < naturalHeight;
if ( clipWidth ) {
// The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
// Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
this.$clippable.css( 'overflowX', 'scroll' );
// eslint-disable-next-line no-void
void this.$clippable[ 0 ].offsetHeight; // Force reflow
this.$clippable.css( {
width: Math.max( 0, allotedWidth ),
maxWidth: ''
} );
} else {
this.$clippable.css( {
overflowX: '',
width: this.idealWidth || '',
maxWidth: Math.max( 0, allotedWidth )
} );
}
if ( clipHeight ) {
// The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
// Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
this.$clippable.css( 'overflowY', 'scroll' );
// eslint-disable-next-line no-void
void this.$clippable[ 0 ].offsetHeight; // Force reflow
this.$clippable.css( {
height: Math.max( 0, allotedHeight ),
maxHeight: ''
} );
} else {
this.$clippable.css( {
overflowY: '',
height: this.idealHeight || '',
maxHeight: Math.max( 0, allotedHeight )
} );
}
// If we stopped clipping in at least one of the dimensions
if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
}
this.clippedHorizontally = clipWidth;
this.clippedVertically = clipHeight;
return this;
};
/**
* PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
* By default, each popup has an anchor that points toward its origin.
* Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
*
* Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
*
* @example
* // A popup widget.
* var popup = new OO.ui.PopupWidget( {
* $content: $( '<p>Hi there!</p>' ),
* padded: true,
* width: 300
* } );
*
* $( 'body' ).append( popup.$element );
* // To display the popup, toggle the visibility to 'true'.
* popup.toggle( true );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.ClippableElement
* @mixins OO.ui.mixin.FloatableElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
* @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
* @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
* @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
* 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
* of $floatableContainer
* 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
* of $floatableContainer
* 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
* endwards (right/left) to the vertical center of $floatableContainer
* 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
* startwards (left/right) to the vertical center of $floatableContainer
* @cfg {string} [align='center'] How to align the popup to $floatableContainer
* 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
* as possible while still keeping the anchor within the popup;
* if position is before/after, move the popup as far downwards as possible.
* 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
* as possible while still keeping the anchor within the popup;
* if position in before/after, move the popup as far upwards as possible.
* 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
* of the popup with the center of $floatableContainer.
* 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
* 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
* @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
* 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
* desired direction to display the popup without clipping
* @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
* See the [OOUI docs on MediaWiki][3] for an example.
* [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
* @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
* @cfg {jQuery} [$content] Content to append to the popup's body
* @cfg {jQuery} [$footer] Content to append to the popup's footer
* @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
* @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
* This config option is only relevant if #autoClose is set to `true`. See the [OOUI documentation on MediaWiki][2]
* for an example.
* [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
* @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
* button.
* @cfg {boolean} [padded=false] Add padding to the popup's body
*/
OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.PopupWidget.parent.call( this, config );
// Properties (must be set before ClippableElement constructor call)
this.$body = $( '<div>' );
this.$popup = $( '<div>' );
// Mixin constructors
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
$clippable: this.$body,
$clippableContainer: this.$popup
} ) );
OO.ui.mixin.FloatableElement.call( this, config );
// Properties
this.$anchor = $( '<div>' );
// If undefined, will be computed lazily in computePosition()
this.$container = config.$container;
this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
this.autoClose = !!config.autoClose;
this.transitionTimeout = null;
this.anchored = false;
this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
// Initialization
this.setSize( config.width, config.height );
this.toggleAnchor( config.anchor === undefined || config.anchor );
this.setAlignment( config.align || 'center' );
this.setPosition( config.position || 'below' );
this.setAutoFlip( config.autoFlip === undefined || config.autoFlip );
this.setAutoCloseIgnore( config.$autoCloseIgnore );
this.$body.addClass( 'oo-ui-popupWidget-body' );
this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
this.$popup
.addClass( 'oo-ui-popupWidget-popup' )
.append( this.$body );
this.$element
.addClass( 'oo-ui-popupWidget' )
.append( this.$popup, this.$anchor );
// Move content, which was added to #$element by OO.ui.Widget, to the body
// FIXME This is gross, we should use '$body' or something for the config
if ( config.$content instanceof $ ) {
this.$body.append( config.$content );
}
if ( config.padded ) {
this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
}
if ( config.head ) {
this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
this.$head = $( '<div>' )
.addClass( 'oo-ui-popupWidget-head' )
.append( this.$label, this.closeButton.$element );
this.$popup.prepend( this.$head );
}
if ( config.$footer ) {
this.$footer = $( '<div>' )
.addClass( 'oo-ui-popupWidget-footer' )
.append( config.$footer );
this.$popup.append( this.$footer );
}
// Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
// that reference properties not initialized at that time of parent class construction
// TODO: Find a better way to handle post-constructor setup
this.visible = false;
this.$element.addClass( 'oo-ui-element-hidden' );
};
/* Setup */
OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.FloatableElement );
/* Events */
/**
* @event ready
*
* The popup is ready: it is visible and has been positioned and clipped.
*/
/* Methods */
/**
* Handles document mouse down events.
*
* @private
* @param {MouseEvent} e Mouse down event
*/
OO.ui.PopupWidget.prototype.onDocumentMouseDown = function ( e ) {
if (
this.isVisible() &&
!OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true )
) {
this.toggle( false );
}
};
// Deprecated alias since 0.28.3
OO.ui.PopupWidget.prototype.onMouseDown = function () {
OO.ui.warnDeprecation( 'onMouseDown is deprecated, use onDocumentMouseDown instead' );
this.onDocumentMouseDown.apply( this, arguments );
};
/**
* Bind document mouse down listener.
*
* @private
*/
OO.ui.PopupWidget.prototype.bindDocumentMouseDownListener = function () {
// Capture clicks outside popup
this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
// We add 'click' event because iOS safari needs to respond to this event.
// We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
// then it will trigger when scrolling. While iOS Safari has some reported behavior
// of occasionally not emitting 'click' properly, that event seems to be the standard
// that it should be emitting, so we add it to this and will operate the event handler
// on whichever of these events was triggered first
this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler, true );
};
// Deprecated alias since 0.28.3
OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
OO.ui.warnDeprecation( 'bindMouseDownListener is deprecated, use bindDocumentMouseDownListener instead' );
this.bindDocumentMouseDownListener.apply( this, arguments );
};
/**
* Handles close button click events.
*
* @private
*/
OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
if ( this.isVisible() ) {
this.toggle( false );
}
};
/**
* Unbind document mouse down listener.
*
* @private
*/
OO.ui.PopupWidget.prototype.unbindDocumentMouseDownListener = function () {
this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler, true );
};
// Deprecated alias since 0.28.3
OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
OO.ui.warnDeprecation( 'unbindMouseDownListener is deprecated, use unbindDocumentMouseDownListener instead' );
this.unbindDocumentMouseDownListener.apply( this, arguments );
};
/**
* Handles document key down events.
*
* @private
* @param {KeyboardEvent} e Key down event
*/
OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
if (
e.which === OO.ui.Keys.ESCAPE &&
this.isVisible()
) {
this.toggle( false );
e.preventDefault();
e.stopPropagation();
}
};
/**
* Bind document key down listener.
*
* @private
*/
OO.ui.PopupWidget.prototype.bindDocumentKeyDownListener = function () {
this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
};
// Deprecated alias since 0.28.3
OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
OO.ui.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
this.bindDocumentKeyDownListener.apply( this, arguments );
};
/**
* Unbind document key down listener.
*
* @private
*/
OO.ui.PopupWidget.prototype.unbindDocumentKeyDownListener = function () {
this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
};
// Deprecated alias since 0.28.3
OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
OO.ui.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
this.unbindDocumentKeyDownListener.apply( this, arguments );
};
/**
* Show, hide, or toggle the visibility of the anchor.
*
* @param {boolean} [show] Show anchor, omit to toggle
*/
OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
show = show === undefined ? !this.anchored : !!show;
if ( this.anchored !== show ) {
if ( show ) {
this.$element.addClass( 'oo-ui-popupWidget-anchored' );
this.$element.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
} else {
this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
}
this.anchored = show;
}
};
/**
* Change which edge the anchor appears on.
*
* @param {string} edge 'top', 'bottom', 'start' or 'end'
*/
OO.ui.PopupWidget.prototype.setAnchorEdge = function ( edge ) {
if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge ) === -1 ) {
throw new Error( 'Invalid value for edge: ' + edge );
}
if ( this.anchorEdge !== null ) {
this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
}
this.anchorEdge = edge;
if ( this.anchored ) {
this.$element.addClass( 'oo-ui-popupWidget-anchored-' + edge );
}
};
/**
* Check if the anchor is visible.
*
* @return {boolean} Anchor is visible
*/
OO.ui.PopupWidget.prototype.hasAnchor = function () {
return this.anchored;
};
/**
* Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
* `.toggle( true )` after its #$element is attached to the DOM.
*
* Do not show the popup while it is not attached to the DOM. The calculations required to display
* it in the right place and with the right dimensions only work correctly while it is attached.
* Side-effects may include broken interface and exceptions being thrown. This wasn't always
* strictly enforced, so currently it only generates a warning in the browser console.
*
* @fires ready
* @inheritdoc
*/
OO.ui.PopupWidget.prototype.toggle = function ( show ) {
var change, normalHeight, oppositeHeight, normalWidth, oppositeWidth;
show = show === undefined ? !this.isVisible() : !!show;
change = show !== this.isVisible();
if ( show && !this.warnedUnattached && !this.isElementAttached() ) {
OO.ui.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
this.warnedUnattached = true;
}
if ( show && !this.$floatableContainer && this.isElementAttached() ) {
// Fall back to the parent node if the floatableContainer is not set
this.setFloatableContainer( this.$element.parent() );
}
if ( change && show && this.autoFlip ) {
// Reset auto-flipping before showing the popup again. It's possible we no longer need to flip
// (e.g. if the user scrolled).
this.isAutoFlipped = false;
}
// Parent method
OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
if ( change ) {
this.togglePositioning( show && !!this.$floatableContainer );
if ( show ) {
if ( this.autoClose ) {
this.bindDocumentMouseDownListener();
this.bindDocumentKeyDownListener();
}
this.updateDimensions();
this.toggleClipping( true );
if ( this.autoFlip ) {
if ( this.popupPosition === 'above' || this.popupPosition === 'below' ) {
if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
// If opening the popup in the normal direction causes it to be clipped, open
// in the opposite one instead
normalHeight = this.$element.height();
this.isAutoFlipped = !this.isAutoFlipped;
this.position();
if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
// If that also causes it to be clipped, open in whichever direction
// we have more space
oppositeHeight = this.$element.height();
if ( oppositeHeight < normalHeight ) {
this.isAutoFlipped = !this.isAutoFlipped;
this.position();
}
}
}
}
if ( this.popupPosition === 'before' || this.popupPosition === 'after' ) {
if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
// If opening the popup in the normal direction causes it to be clipped, open
// in the opposite one instead
normalWidth = this.$element.width();
this.isAutoFlipped = !this.isAutoFlipped;
// Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
// which causes positioning to be off. Toggle clipping back and fort to work around.
this.toggleClipping( false );
this.position();
this.toggleClipping( true );
if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
// If that also causes it to be clipped, open in whichever direction
// we have more space
oppositeWidth = this.$element.width();
if ( oppositeWidth < normalWidth ) {
this.isAutoFlipped = !this.isAutoFlipped;
// Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
// which causes positioning to be off. Toggle clipping back and fort to work around.
this.toggleClipping( false );
this.position();
this.toggleClipping( true );
}
}
}
}
}
this.emit( 'ready' );
} else {
this.toggleClipping( false );
if ( this.autoClose ) {
this.unbindDocumentMouseDownListener();
this.unbindDocumentKeyDownListener();
}
}
}
return this;
};
/**
* Set the size of the popup.
*
* Changing the size may also change the popup's position depending on the alignment.
*
* @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
* @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
* @param {boolean} [transition=false] Use a smooth transition
* @chainable
*/
OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
this.width = width !== undefined ? width : 320;
this.height = height !== undefined ? height : null;
if ( this.isVisible() ) {
this.updateDimensions( transition );
}
};
/**
* Update the size and position.
*
* Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
* be called automatically.
*
* @param {boolean} [transition=false] Use a smooth transition
* @chainable
*/
OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
var widget = this;
// Prevent transition from being interrupted
clearTimeout( this.transitionTimeout );
if ( transition ) {
// Enable transition
this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
}
this.position();
if ( transition ) {
// Prevent transitioning after transition is complete
this.transitionTimeout = setTimeout( function () {
widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
}, 200 );
} else {
// Prevent transitioning immediately
this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
}
};
/**
* @inheritdoc
*/
OO.ui.PopupWidget.prototype.computePosition = function () {
var direction, align, vertical, start, end, near, far, sizeProp, popupSize, anchorSize, anchorPos,
anchorOffset, anchorMargin, parentPosition, positionProp, positionAdjustment, floatablePos,
offsetParentPos, containerPos, popupPosition, viewportSpacing,
popupPos = {},
anchorCss = { left: '', right: '', top: '', bottom: '' },
popupPositionOppositeMap = {
above: 'below',
below: 'above',
before: 'after',
after: 'before'
},
alignMap = {
ltr: {
'force-left': 'backwards',
'force-right': 'forwards'
},
rtl: {
'force-left': 'forwards',
'force-right': 'backwards'
}
},
anchorEdgeMap = {
above: 'bottom',
below: 'top',
before: 'end',
after: 'start'
},
hPosMap = {
forwards: 'start',
center: 'center',
backwards: this.anchored ? 'before' : 'end'
},
vPosMap = {
forwards: 'top',
center: 'center',
backwards: 'bottom'
};
if ( !this.$container ) {
// Lazy-initialize $container if not specified in constructor
this.$container = $( this.getClosestScrollableElementContainer() );
}
direction = this.$container.css( 'direction' );
// Set height and width before we do anything else, since it might cause our measurements
// to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
this.$popup.css( {
width: this.width !== null ? this.width : 'auto',
height: this.height !== null ? this.height : 'auto'
} );
align = alignMap[ direction ][ this.align ] || this.align;
popupPosition = this.popupPosition;
if ( this.isAutoFlipped ) {
popupPosition = popupPositionOppositeMap[ popupPosition ];
}
// If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
vertical = popupPosition === 'before' || popupPosition === 'after';
start = vertical ? 'top' : ( direction === 'rtl' ? 'right' : 'left' );
end = vertical ? 'bottom' : ( direction === 'rtl' ? 'left' : 'right' );
near = vertical ? 'top' : 'left';
far = vertical ? 'bottom' : 'right';
sizeProp = vertical ? 'Height' : 'Width';
popupSize = vertical ? ( this.height || this.$popup.height() ) : ( this.width || this.$popup.width() );
this.setAnchorEdge( anchorEdgeMap[ popupPosition ] );
this.horizontalPosition = vertical ? popupPosition : hPosMap[ align ];
this.verticalPosition = vertical ? vPosMap[ align ] : popupPosition;
// Parent method
parentPosition = OO.ui.mixin.FloatableElement.prototype.computePosition.call( this );
// Find out which property FloatableElement used for positioning, and adjust that value
positionProp = vertical ?
( parentPosition.top !== '' ? 'top' : 'bottom' ) :
( parentPosition.left !== '' ? 'left' : 'right' );
// Figure out where the near and far edges of the popup and $floatableContainer are
floatablePos = this.$floatableContainer.offset();
floatablePos[ far ] = floatablePos[ near ] + this.$floatableContainer[ 'outer' + sizeProp ]();
// Measure where the offsetParent is and compute our position based on that and parentPosition
offsetParentPos = this.$element.offsetParent()[ 0 ] === document.documentElement ?
{ top: 0, left: 0 } :
this.$element.offsetParent().offset();
if ( positionProp === near ) {
popupPos[ near ] = offsetParentPos[ near ] + parentPosition[ near ];
popupPos[ far ] = popupPos[ near ] + popupSize;
} else {
popupPos[ far ] = offsetParentPos[ near ] +
this.$element.offsetParent()[ 'inner' + sizeProp ]() - parentPosition[ far ];
popupPos[ near ] = popupPos[ far ] - popupSize;
}
if ( this.anchored ) {
// Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
anchorPos = ( floatablePos[ start ] + floatablePos[ end ] ) / 2;
anchorOffset = ( start === far ? -1 : 1 ) * ( anchorPos - popupPos[ start ] );
// If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
// this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
anchorSize = this.$anchor[ 0 ][ 'scroll' + sizeProp ];
anchorMargin = parseFloat( this.$anchor.css( 'margin-' + start ) );
if ( anchorOffset + anchorMargin < 2 * anchorSize ) {
// Not enough space for the anchor on the start side; pull the popup startwards
positionAdjustment = ( positionProp === start ? -1 : 1 ) *
( 2 * anchorSize - ( anchorOffset + anchorMargin ) );
} else if ( anchorOffset + anchorMargin > popupSize - 2 * anchorSize ) {
// Not enough space for the anchor on the end side; pull the popup endwards
positionAdjustment = ( positionProp === end ? -1 : 1 ) *
( anchorOffset + anchorMargin - ( popupSize - 2 * anchorSize ) );
} else {
positionAdjustment = 0;
}
} else {
positionAdjustment = 0;
}
// Check if the popup will go beyond the edge of this.$container
containerPos = this.$container[ 0 ] === document.documentElement ?
{ top: 0, left: 0 } :
this.$container.offset();
containerPos[ far ] = containerPos[ near ] + this.$container[ 'inner' + sizeProp ]();
if ( this.$container[ 0 ] === document.documentElement ) {
viewportSpacing = OO.ui.getViewportSpacing();
containerPos[ near ] += viewportSpacing[ near ];
containerPos[ far ] -= viewportSpacing[ far ];
}
// Take into account how much the popup will move because of the adjustments we're going to make
popupPos[ near ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
popupPos[ far ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
if ( containerPos[ near ] + this.containerPadding > popupPos[ near ] ) {
// Popup goes beyond the near (left/top) edge, move it to the right/bottom
positionAdjustment += ( positionProp === near ? 1 : -1 ) *
( containerPos[ near ] + this.containerPadding - popupPos[ near ] );
} else if ( containerPos[ far ] - this.containerPadding < popupPos[ far ] ) {
// Popup goes beyond the far (right/bottom) edge, move it to the left/top
positionAdjustment += ( positionProp === far ? 1 : -1 ) *
( popupPos[ far ] - ( containerPos[ far ] - this.containerPadding ) );
}
if ( this.anchored ) {
// Adjust anchorOffset for positionAdjustment
anchorOffset += ( positionProp === start ? -1 : 1 ) * positionAdjustment;
// Position the anchor
anchorCss[ start ] = anchorOffset;
this.$anchor.css( anchorCss );
}
// Move the popup if needed
parentPosition[ positionProp ] += positionAdjustment;
return parentPosition;
};
/**
* Set popup alignment
*
* @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
* `backwards` or `forwards`.
*/
OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
// Validate alignment
if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
this.align = align;
} else {
this.align = 'center';
}
this.position();
};
/**
* Get popup alignment
*
* @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
* `backwards` or `forwards`.
*/
OO.ui.PopupWidget.prototype.getAlignment = function () {
return this.align;
};
/**
* Change the positioning of the popup.
*
* @param {string} position 'above', 'below', 'before' or 'after'
*/
OO.ui.PopupWidget.prototype.setPosition = function ( position ) {
if ( [ 'above', 'below', 'before', 'after' ].indexOf( position ) === -1 ) {
position = 'below';
}
this.popupPosition = position;
this.position();
};
/**
* Get popup positioning.
*
* @return {string} 'above', 'below', 'before' or 'after'
*/
OO.ui.PopupWidget.prototype.getPosition = function () {
return this.popupPosition;
};
/**
* Set popup auto-flipping.
*
* @param {boolean} autoFlip Whether to automatically switch the popup's position between
* 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
* desired direction to display the popup without clipping
*/
OO.ui.PopupWidget.prototype.setAutoFlip = function ( autoFlip ) {
autoFlip = !!autoFlip;
if ( this.autoFlip !== autoFlip ) {
this.autoFlip = autoFlip;
}
};
/**
* Set which elements will not close the popup when clicked.
*
* For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
*
* @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
*/
OO.ui.PopupWidget.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore ) {
this.$autoCloseIgnore = $autoCloseIgnore;
};
/**
* Get an ID of the body element, this can be used as the
* `aria-describedby` attribute for an input field.
*
* @return {string} The ID of the body element
*/
OO.ui.PopupWidget.prototype.getBodyId = function () {
var id = this.$body.attr( 'id' );
if ( id === undefined ) {
id = OO.ui.generateElementId();
this.$body.attr( 'id', id );
}
return id;
};
/**
* PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
* A popup is a container for content. It is overlaid and positioned absolutely. By default, each
* popup has an anchor, which is an arrow-like protrusion that points toward the popupโs origin.
* See {@link OO.ui.PopupWidget PopupWidget} for an example.
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {Object} [popup] Configuration to pass to popup
* @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
*/
OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.popup = new OO.ui.PopupWidget( $.extend(
{
autoClose: true,
$floatableContainer: this.$element
},
config.popup,
{
$autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore )
}
) );
};
/* Methods */
/**
* Get popup.
*
* @return {OO.ui.PopupWidget} Popup widget
*/
OO.ui.mixin.PopupElement.prototype.getPopup = function () {
return this.popup;
};
/**
* PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
* which is used to display additional information or options.
*
* @example
* // Example of a popup button.
* var popupButton = new OO.ui.PopupButtonWidget( {
* label: 'Popup button with options',
* icon: 'menu',
* popup: {
* $content: $( '<p>Additional options here.</p>' ),
* padded: true,
* align: 'force-left'
* }
* } );
* // Append the button to the DOM.
* $( 'body' ).append( popupButton.$element );
*
* @class
* @extends OO.ui.ButtonWidget
* @mixins OO.ui.mixin.PopupElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
* the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
* containing `<div>` and has a larger area. By default, the popup uses relative positioning.
* See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
*/
OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.PopupButtonWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.PopupElement.call( this, config );
// Properties
this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
// Events
this.connect( this, { click: 'onAction' } );
// Initialization
this.$element
.addClass( 'oo-ui-popupButtonWidget' );
this.popup.$element
.addClass( 'oo-ui-popupButtonWidget-popup' )
.toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
.toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
this.$overlay.append( this.popup.$element );
};
/* Setup */
OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
/* Methods */
/**
* Handle the button action being triggered.
*
* @private
*/
OO.ui.PopupButtonWidget.prototype.onAction = function () {
this.popup.toggle();
};
/**
* Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
*
* Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
*
* @private
* @abstract
* @class
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
// Mixin constructors
OO.ui.mixin.GroupElement.call( this, config );
};
/* Setup */
OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
/* Methods */
/**
* Set the disabled state of the widget.
*
* This will also update the disabled state of child widgets.
*
* @param {boolean} disabled Disable widget
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
var i, len;
// Parent method
// Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
OO.ui.Widget.prototype.setDisabled.call( this, disabled );
// During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
if ( this.items ) {
for ( i = 0, len = this.items.length; i < len; i++ ) {
this.items[ i ].updateDisabled();
}
}
return this;
};
/**
* Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
*
* Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
* allows bidirectional communication.
*
* Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
*
* @private
* @abstract
* @class
*
* @constructor
*/
OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
//
};
/* Methods */
/**
* Check if widget is disabled.
*
* Checks parent if present, making disabled state inheritable.
*
* @return {boolean} Widget is disabled
*/
OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
return this.disabled ||
( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
};
/**
* Set group element is in.
*
* @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
// Parent method
// Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
OO.ui.Element.prototype.setElementGroup.call( this, group );
// Initialize item disabled states
this.updateDisabled();
return this;
};
/**
* OptionWidgets are special elements that can be selected and configured with data. The
* data is often unique for each option, but it does not have to be. OptionWidgets are used
* with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
* and examples, please see the [OOUI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.ItemWidget
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.FlaggedElement
* @mixins OO.ui.mixin.AccessKeyedElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.OptionWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.ItemWidget.call( this );
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.FlaggedElement.call( this, config );
OO.ui.mixin.AccessKeyedElement.call( this, config );
// Properties
this.selected = false;
this.highlighted = false;
this.pressed = false;
// Initialization
this.$element
.data( 'oo-ui-optionWidget', this )
// Allow programmatic focussing (and by accesskey), but not tabbing
.attr( 'tabindex', '-1' )
.attr( 'role', 'option' )
.attr( 'aria-selected', 'false' )
.addClass( 'oo-ui-optionWidget' )
.append( this.$label );
};
/* Setup */
OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement );
/* Static Properties */
/**
* Whether this option can be selected. See #setSelected.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.OptionWidget.static.selectable = true;
/**
* Whether this option can be highlighted. See #setHighlighted.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.OptionWidget.static.highlightable = true;
/**
* Whether this option can be pressed. See #setPressed.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.OptionWidget.static.pressable = true;
/**
* Whether this option will be scrolled into view when it is selected.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
/* Methods */
/**
* Check if the option can be selected.
*
* @return {boolean} Item is selectable
*/
OO.ui.OptionWidget.prototype.isSelectable = function () {
return this.constructor.static.selectable && !this.disabled && this.isVisible();
};
/**
* Check if the option can be highlighted. A highlight indicates that the option
* may be selected when a user presses enter or clicks. Disabled items cannot
* be highlighted.
*
* @return {boolean} Item is highlightable
*/
OO.ui.OptionWidget.prototype.isHighlightable = function () {
return this.constructor.static.highlightable && !this.disabled && this.isVisible();
};
/**
* Check if the option can be pressed. The pressed state occurs when a user mouses
* down on an item, but has not yet let go of the mouse.
*
* @return {boolean} Item is pressable
*/
OO.ui.OptionWidget.prototype.isPressable = function () {
return this.constructor.static.pressable && !this.disabled && this.isVisible();
};
/**
* Check if the option is selected.
*
* @return {boolean} Item is selected
*/
OO.ui.OptionWidget.prototype.isSelected = function () {
return this.selected;
};
/**
* Check if the option is highlighted. A highlight indicates that the
* item may be selected when a user presses enter or clicks.
*
* @return {boolean} Item is highlighted
*/
OO.ui.OptionWidget.prototype.isHighlighted = function () {
return this.highlighted;
};
/**
* Check if the option is pressed. The pressed state occurs when a user mouses
* down on an item, but has not yet let go of the mouse. The item may appear
* selected, but it will not be selected until the user releases the mouse.
*
* @return {boolean} Item is pressed
*/
OO.ui.OptionWidget.prototype.isPressed = function () {
return this.pressed;
};
/**
* Set the optionโs selected state. In general, all modifications to the selection
* should be handled by the SelectWidgetโs {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
* method instead of this method.
*
* @param {boolean} [state=false] Select option
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
if ( this.constructor.static.selectable ) {
this.selected = !!state;
this.$element
.toggleClass( 'oo-ui-optionWidget-selected', state )
.attr( 'aria-selected', state.toString() );
if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
this.scrollElementIntoView();
}
this.updateThemeClasses();
}
return this;
};
/**
* Set the optionโs highlighted state. In general, all programmatic
* modifications to the highlight should be handled by the
* SelectWidgetโs {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
* method instead of this method.
*
* @param {boolean} [state=false] Highlight option
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
if ( this.constructor.static.highlightable ) {
this.highlighted = !!state;
this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
this.updateThemeClasses();
}
return this;
};
/**
* Set the optionโs pressed state. In general, all
* programmatic modifications to the pressed state should be handled by the
* SelectWidgetโs {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
* method instead of this method.
*
* @param {boolean} [state=false] Press option
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
if ( this.constructor.static.pressable ) {
this.pressed = !!state;
this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
this.updateThemeClasses();
}
return this;
};
/**
* Get text to match search strings against.
*
* The default implementation returns the label text, but subclasses
* can override this to provide more complex behavior.
*
* @return {string|boolean} String to match search string against
*/
OO.ui.OptionWidget.prototype.getMatchText = function () {
var label = this.getLabel();
return typeof label === 'string' ? label : this.$label.text();
};
/**
* A SelectWidget is of a generic selection of options. The OOUI library contains several types of
* select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
* {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
* menu selects}.
*
* This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
* information, please see the [OOUI documentation on MediaWiki][1].
*
* @example
* // Example of a select widget with three options
* var select = new OO.ui.SelectWidget( {
* items: [
* new OO.ui.OptionWidget( {
* data: 'a',
* label: 'Option One',
* } ),
* new OO.ui.OptionWidget( {
* data: 'b',
* label: 'Option Two',
* } ),
* new OO.ui.OptionWidget( {
* data: 'c',
* label: 'Option Three',
* } )
* ]
* } );
* $( 'body' ).append( select.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
*
* @abstract
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.GroupWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
* Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
* the [OOUI documentation on MediaWiki] [2] for examples.
* [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
*/
OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.SelectWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
// Properties
this.pressed = false;
this.selecting = null;
this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
this.onDocumentMouseMoveHandler = this.onDocumentMouseMove.bind( this );
this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
this.onDocumentKeyPressHandler = this.onDocumentKeyPress.bind( this );
this.keyPressBuffer = '';
this.keyPressBufferTimer = null;
this.blockMouseOverEvents = 0;
// Events
this.connect( this, {
toggle: 'onToggle'
} );
this.$element.on( {
focusin: this.onFocus.bind( this ),
mousedown: this.onMouseDown.bind( this ),
mouseover: this.onMouseOver.bind( this ),
mouseleave: this.onMouseLeave.bind( this )
} );
// Initialization
this.$element
.addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
.attr( 'role', 'listbox' );
this.setFocusOwner( this.$element );
if ( Array.isArray( config.items ) ) {
this.addItems( config.items );
}
};
/* Setup */
OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
/* Events */
/**
* @event highlight
*
* A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
*
* @param {OO.ui.OptionWidget|null} item Highlighted item
*/
/**
* @event press
*
* A `press` event is emitted when the #pressItem method is used to programmatically modify the
* pressed state of an option.
*
* @param {OO.ui.OptionWidget|null} item Pressed item
*/
/**
* @event select
*
* A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
*
* @param {OO.ui.OptionWidget|null} item Selected item
*/
/**
* @event choose
* A `choose` event is emitted when an item is chosen with the #chooseItem method.
* @param {OO.ui.OptionWidget} item Chosen item
*/
/**
* @event add
*
* An `add` event is emitted when options are added to the select with the #addItems method.
*
* @param {OO.ui.OptionWidget[]} items Added items
* @param {number} index Index of insertion point
*/
/**
* @event remove
*
* A `remove` event is emitted when options are removed from the select with the #clearItems
* or #removeItems methods.
*
* @param {OO.ui.OptionWidget[]} items Removed items
*/
/* Methods */
/**
* Handle focus events
*
* @private
* @param {jQuery.Event} event
*/
OO.ui.SelectWidget.prototype.onFocus = function ( event ) {
var item;
if ( event.target === this.$element[ 0 ] ) {
// This widget was focussed, e.g. by the user tabbing to it.
// The styles for focus state depend on one of the items being selected.
if ( !this.findSelectedItem() ) {
item = this.findFirstSelectableItem();
}
} else {
if ( event.target.tabIndex === -1 ) {
// One of the options got focussed (and the event bubbled up here).
// They can't be tabbed to, but they can be activated using accesskeys.
// OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
item = this.findTargetItem( event );
} else {
// There is something actually user-focusable in one of the labels of the options, and the
// user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change the focus).
return;
}
}
if ( item ) {
if ( item.constructor.static.highlightable ) {
this.highlightItem( item );
} else {
this.selectItem( item );
}
}
if ( event.target !== this.$element[ 0 ] ) {
this.$focusOwner.focus();
}
};
/**
* Handle mouse down events.
*
* @private
* @param {jQuery.Event} e Mouse down event
* @return {undefined/boolean} False to prevent default if event is handled
*/
OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
var item;
if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
this.togglePressed( true );
item = this.findTargetItem( e );
if ( item && item.isSelectable() ) {
this.pressItem( item );
this.selecting = item;
this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
}
}
return false;
};
/**
* Handle document mouse up events.
*
* @private
* @param {MouseEvent} e Mouse up event
* @return {undefined/boolean} False to prevent default if event is handled
*/
OO.ui.SelectWidget.prototype.onDocumentMouseUp = function ( e ) {
var item;
this.togglePressed( false );
if ( !this.selecting ) {
item = this.findTargetItem( e );
if ( item && item.isSelectable() ) {
this.selecting = item;
}
}
if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
this.pressItem( null );
this.chooseItem( this.selecting );
this.selecting = null;
}
this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
return false;
};
// Deprecated alias since 0.28.3
OO.ui.SelectWidget.prototype.onMouseUp = function () {
OO.ui.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
this.onDocumentMouseUp.apply( this, arguments );
};
/**
* Handle document mouse move events.
*
* @private
* @param {MouseEvent} e Mouse move event
*/
OO.ui.SelectWidget.prototype.onDocumentMouseMove = function ( e ) {
var item;
if ( !this.isDisabled() && this.pressed ) {
item = this.findTargetItem( e );
if ( item && item !== this.selecting && item.isSelectable() ) {
this.pressItem( item );
this.selecting = item;
}
}
};
// Deprecated alias since 0.28.3
OO.ui.SelectWidget.prototype.onMouseMove = function () {
OO.ui.warnDeprecation( 'onMouseMove is deprecated, use onDocumentMouseMove instead' );
this.onDocumentMouseMove.apply( this, arguments );
};
/**
* Handle mouse over events.
*
* @private
* @param {jQuery.Event} e Mouse over event
* @return {undefined/boolean} False to prevent default if event is handled
*/
OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
var item;
if ( this.blockMouseOverEvents ) {
return;
}
if ( !this.isDisabled() ) {
item = this.findTargetItem( e );
this.highlightItem( item && item.isHighlightable() ? item : null );
}
return false;
};
/**
* Handle mouse leave events.
*
* @private
* @param {jQuery.Event} e Mouse over event
* @return {undefined/boolean} False to prevent default if event is handled
*/
OO.ui.SelectWidget.prototype.onMouseLeave = function () {
if ( !this.isDisabled() ) {
this.highlightItem( null );
}
return false;
};
/**
* Handle document key down events.
*
* @protected
* @param {KeyboardEvent} e Key down event
*/
OO.ui.SelectWidget.prototype.onDocumentKeyDown = function ( e ) {
var nextItem,
handled = false,
currentItem = this.findHighlightedItem() || this.findSelectedItem();
if ( !this.isDisabled() && this.isVisible() ) {
switch ( e.keyCode ) {
case OO.ui.Keys.ENTER:
if ( currentItem && currentItem.constructor.static.highlightable ) {
// Was only highlighted, now let's select it. No-op if already selected.
this.chooseItem( currentItem );
handled = true;
}
break;
case OO.ui.Keys.UP:
case OO.ui.Keys.LEFT:
this.clearKeyPressBuffer();
nextItem = this.findRelativeSelectableItem( currentItem, -1 );
handled = true;
break;
case OO.ui.Keys.DOWN:
case OO.ui.Keys.RIGHT:
this.clearKeyPressBuffer();
nextItem = this.findRelativeSelectableItem( currentItem, 1 );
handled = true;
break;
case OO.ui.Keys.ESCAPE:
case OO.ui.Keys.TAB:
if ( currentItem && currentItem.constructor.static.highlightable ) {
currentItem.setHighlighted( false );
}
this.unbindDocumentKeyDownListener();
this.unbindDocumentKeyPressListener();
// Don't prevent tabbing away / defocusing
handled = false;
break;
}
if ( nextItem ) {
if ( nextItem.constructor.static.highlightable ) {
this.highlightItem( nextItem );
} else {
this.chooseItem( nextItem );
}
this.scrollItemIntoView( nextItem );
}
if ( handled ) {
e.preventDefault();
e.stopPropagation();
}
}
};
// Deprecated alias since 0.28.3
OO.ui.SelectWidget.prototype.onKeyDown = function () {
OO.ui.warnDeprecation( 'onKeyDown is deprecated, use onDocumentKeyDown instead' );
this.onDocumentKeyDown.apply( this, arguments );
};
/**
* Bind document key down listener.
*
* @protected
*/
OO.ui.SelectWidget.prototype.bindDocumentKeyDownListener = function () {
this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
};
// Deprecated alias since 0.28.3
OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
OO.ui.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
this.bindDocumentKeyDownListener.apply( this, arguments );
};
/**
* Unbind document key down listener.
*
* @protected
*/
OO.ui.SelectWidget.prototype.unbindDocumentKeyDownListener = function () {
this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
};
// Deprecated alias since 0.28.3
OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
OO.ui.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
this.unbindDocumentKeyDownListener.apply( this, arguments );
};
/**
* Scroll item into view, preventing spurious mouse highlight actions from happening.
*
* @param {OO.ui.OptionWidget} item Item to scroll into view
*/
OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) {
var widget = this;
// Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
// and around 100-150 ms after it is finished.
this.blockMouseOverEvents++;
item.scrollElementIntoView().done( function () {
setTimeout( function () {
widget.blockMouseOverEvents--;
}, 200 );
} );
};
/**
* Clear the key-press buffer
*
* @protected
*/
OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
if ( this.keyPressBufferTimer ) {
clearTimeout( this.keyPressBufferTimer );
this.keyPressBufferTimer = null;
}
this.keyPressBuffer = '';
};
/**
* Handle key press events.
*
* @protected
* @param {KeyboardEvent} e Key press event
* @return {undefined/boolean} False to prevent default if event is handled
*/
OO.ui.SelectWidget.prototype.onDocumentKeyPress = function ( e ) {
var c, filter, item;
if ( !e.charCode ) {
if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
return false;
}
return;
}
// eslint-disable-next-line no-restricted-properties
if ( String.fromCodePoint ) {
// eslint-disable-next-line no-restricted-properties
c = String.fromCodePoint( e.charCode );
} else {
c = String.fromCharCode( e.charCode );
}
if ( this.keyPressBufferTimer ) {
clearTimeout( this.keyPressBufferTimer );
}
this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
item = this.findHighlightedItem() || this.findSelectedItem();
if ( this.keyPressBuffer === c ) {
// Common (if weird) special case: typing "xxxx" will cycle through all
// the items beginning with "x".
if ( item ) {
item = this.findRelativeSelectableItem( item, 1 );
}
} else {
this.keyPressBuffer += c;
}
filter = this.getItemMatcher( this.keyPressBuffer, false );
if ( !item || !filter( item ) ) {
item = this.findRelativeSelectableItem( item, 1, filter );
}
if ( item ) {
if ( this.isVisible() && item.constructor.static.highlightable ) {
this.highlightItem( item );
} else {
this.chooseItem( item );
}
this.scrollItemIntoView( item );
}
e.preventDefault();
e.stopPropagation();
};
// Deprecated alias since 0.28.3
OO.ui.SelectWidget.prototype.onKeyPress = function () {
OO.ui.warnDeprecation( 'onKeyPress is deprecated, use onDocumentKeyPress instead' );
this.onDocumentKeyPress.apply( this, arguments );
};
/**
* Get a matcher for the specific string
*
* @protected
* @param {string} s String to match against items
* @param {boolean} [exact=false] Only accept exact matches
* @return {Function} function ( OO.ui.OptionWidget ) => boolean
*/
OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
var re;
// eslint-disable-next-line no-restricted-properties
if ( s.normalize ) {
// eslint-disable-next-line no-restricted-properties
s = s.normalize();
}
s = exact ? s.trim() : s.replace( /^\s+/, '' );
re = '^\\s*' + s.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
if ( exact ) {
re += '\\s*$';
}
re = new RegExp( re, 'i' );
return function ( item ) {
var matchText = item.getMatchText();
// eslint-disable-next-line no-restricted-properties
if ( matchText.normalize ) {
// eslint-disable-next-line no-restricted-properties
matchText = matchText.normalize();
}
return re.test( matchText );
};
};
/**
* Bind document key press listener.
*
* @protected
*/
OO.ui.SelectWidget.prototype.bindDocumentKeyPressListener = function () {
this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
};
// Deprecated alias since 0.28.3
OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
OO.ui.warnDeprecation( 'bindKeyPressListener is deprecated, use bindDocumentKeyPressListener instead' );
this.bindDocumentKeyPressListener.apply( this, arguments );
};
/**
* Unbind document key down listener.
*
* If you override this, be sure to call this.clearKeyPressBuffer() from your
* implementation.
*
* @protected
*/
OO.ui.SelectWidget.prototype.unbindDocumentKeyPressListener = function () {
this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
this.clearKeyPressBuffer();
};
// Deprecated alias since 0.28.3
OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
OO.ui.warnDeprecation( 'unbindKeyPressListener is deprecated, use unbindDocumentKeyPressListener instead' );
this.unbindDocumentKeyPressListener.apply( this, arguments );
};
/**
* Visibility change handler
*
* @protected
* @param {boolean} visible
*/
OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
if ( !visible ) {
this.clearKeyPressBuffer();
}
};
/**
* Get the closest item to a jQuery.Event.
*
* @private
* @param {jQuery.Event} e
* @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
*/
OO.ui.SelectWidget.prototype.findTargetItem = function ( e ) {
var $option = $( e.target ).closest( '.oo-ui-optionWidget' );
if ( !$option.closest( '.oo-ui-selectWidget' ).is( this.$element ) ) {
return null;
}
return $option.data( 'oo-ui-optionWidget' ) || null;
};
/**
* Find selected item.
*
* @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
*/
OO.ui.SelectWidget.prototype.findSelectedItem = function () {
var i, len;
for ( i = 0, len = this.items.length; i < len; i++ ) {
if ( this.items[ i ].isSelected() ) {
return this.items[ i ];
}
}
return null;
};
/**
* Find highlighted item.
*
* @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
*/
OO.ui.SelectWidget.prototype.findHighlightedItem = function () {
var i, len;
for ( i = 0, len = this.items.length; i < len; i++ ) {
if ( this.items[ i ].isHighlighted() ) {
return this.items[ i ];
}
}
return null;
};
/**
* Toggle pressed state.
*
* Press is a state that occurs when a user mouses down on an item, but
* has not yet let go of the mouse. The item may appear selected, but it will not be selected
* until the user releases the mouse.
*
* @param {boolean} pressed An option is being pressed
*/
OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
if ( pressed === undefined ) {
pressed = !this.pressed;
}
if ( pressed !== this.pressed ) {
this.$element
.toggleClass( 'oo-ui-selectWidget-pressed', pressed )
.toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
this.pressed = pressed;
}
};
/**
* Highlight an option. If the `item` param is omitted, no options will be highlighted
* and any existing highlight will be removed. The highlight is mutually exclusive.
*
* @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
* @fires highlight
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
var i, len, highlighted,
changed = false;
for ( i = 0, len = this.items.length; i < len; i++ ) {
highlighted = this.items[ i ] === item;
if ( this.items[ i ].isHighlighted() !== highlighted ) {
this.items[ i ].setHighlighted( highlighted );
changed = true;
}
}
if ( changed ) {
if ( item ) {
this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
} else {
this.$focusOwner.removeAttr( 'aria-activedescendant' );
}
this.emit( 'highlight', item );
}
return this;
};
/**
* Fetch an item by its label.
*
* @param {string} label Label of the item to select.
* @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
* @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
*/
OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
var i, item, found,
len = this.items.length,
filter = this.getItemMatcher( label, true );
for ( i = 0; i < len; i++ ) {
item = this.items[ i ];
if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
return item;
}
}
if ( prefix ) {
found = null;
filter = this.getItemMatcher( label, false );
for ( i = 0; i < len; i++ ) {
item = this.items[ i ];
if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
if ( found ) {
return null;
}
found = item;
}
}
if ( found ) {
return found;
}
}
return null;
};
/**
* Programmatically select an option by its label. If the item does not exist,
* all options will be deselected.
*
* @param {string} [label] Label of the item to select.
* @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
* @fires select
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
var itemFromLabel = this.getItemFromLabel( label, !!prefix );
if ( label === undefined || !itemFromLabel ) {
return this.selectItem();
}
return this.selectItem( itemFromLabel );
};
/**
* Programmatically select an option by its data. If the `data` parameter is omitted,
* or if the item does not exist, all options will be deselected.
*
* @param {Object|string} [data] Value of the item to select, omit to deselect all
* @fires select
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
var itemFromData = this.findItemFromData( data );
if ( data === undefined || !itemFromData ) {
return this.selectItem();
}
return this.selectItem( itemFromData );
};
/**
* Programmatically select an option by its reference. If the `item` parameter is omitted,
* all options will be deselected.
*
* @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
* @fires select
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
var i, len, selected,
changed = false;
for ( i = 0, len = this.items.length; i < len; i++ ) {
selected = this.items[ i ] === item;
if ( this.items[ i ].isSelected() !== selected ) {
this.items[ i ].setSelected( selected );
changed = true;
}
}
if ( changed ) {
if ( item && !item.constructor.static.highlightable ) {
if ( item ) {
this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
} else {
this.$focusOwner.removeAttr( 'aria-activedescendant' );
}
}
this.emit( 'select', item );
}
return this;
};
/**
* Press an item.
*
* Press is a state that occurs when a user mouses down on an item, but has not
* yet let go of the mouse. The item may appear selected, but it will not be selected until the user
* releases the mouse.
*
* @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
* @fires press
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
var i, len, pressed,
changed = false;
for ( i = 0, len = this.items.length; i < len; i++ ) {
pressed = this.items[ i ] === item;
if ( this.items[ i ].isPressed() !== pressed ) {
this.items[ i ].setPressed( pressed );
changed = true;
}
}
if ( changed ) {
this.emit( 'press', item );
}
return this;
};
/**
* Choose an item.
*
* Note that โchooseโ should never be modified programmatically. A user can choose
* an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
* use the #selectItem method.
*
* This method is identical to #selectItem, but may vary in subclasses that take additional action
* when users choose an item with the keyboard or mouse.
*
* @param {OO.ui.OptionWidget} item Item to choose
* @fires choose
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
if ( item ) {
this.selectItem( item );
this.emit( 'choose', item );
}
return this;
};
/**
* Find an option by its position relative to the specified item (or to the start of the option array,
* if item is `null`). The direction in which to search through the option array is specified with a
* number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
* `null` if there are no options in the array.
*
* @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
* @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
* @param {Function} [filter] Only consider items for which this function returns
* true. Function takes an OO.ui.OptionWidget and returns a boolean.
* @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
*/
OO.ui.SelectWidget.prototype.findRelativeSelectableItem = function ( item, direction, filter ) {
var currentIndex, nextIndex, i,
increase = direction > 0 ? 1 : -1,
len = this.items.length;
if ( item instanceof OO.ui.OptionWidget ) {
currentIndex = this.items.indexOf( item );
nextIndex = ( currentIndex + increase + len ) % len;
} else {
// If no item is selected and moving forward, start at the beginning.
// If moving backward, start at the end.
nextIndex = direction > 0 ? 0 : len - 1;
}
for ( i = 0; i < len; i++ ) {
item = this.items[ nextIndex ];
if (
item instanceof OO.ui.OptionWidget && item.isSelectable() &&
( !filter || filter( item ) )
) {
return item;
}
nextIndex = ( nextIndex + increase + len ) % len;
}
return null;
};
/**
* Find the next selectable item or `null` if there are no selectable items.
* Disabled options and menu-section markers and breaks are not selectable.
*
* @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
*/
OO.ui.SelectWidget.prototype.findFirstSelectableItem = function () {
return this.findRelativeSelectableItem( null, 1 );
};
/**
* Add an array of options to the select. Optionally, an index number can be used to
* specify an insertion point.
*
* @param {OO.ui.OptionWidget[]} items Items to add
* @param {number} [index] Index to insert items after
* @fires add
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
// Mixin method
OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
// Always provide an index, even if it was omitted
this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
return this;
};
/**
* Remove the specified array of options from the select. Options will be detached
* from the DOM, not removed, so they can be reused later. To remove all options from
* the select, you may wish to use the #clearItems method instead.
*
* @param {OO.ui.OptionWidget[]} items Items to remove
* @fires remove
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
var i, len, item;
// Deselect items being removed
for ( i = 0, len = items.length; i < len; i++ ) {
item = items[ i ];
if ( item.isSelected() ) {
this.selectItem( null );
}
}
// Mixin method
OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
this.emit( 'remove', items );
return this;
};
/**
* Clear all options from the select. Options will be detached from the DOM, not removed,
* so that they can be reused later. To remove a subset of options from the select, use
* the #removeItems method.
*
* @fires remove
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.SelectWidget.prototype.clearItems = function () {
var items = this.items.slice();
// Mixin method
OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
// Clear selection
this.selectItem( null );
this.emit( 'remove', items );
return this;
};
/**
* Set the DOM element which has focus while the user is interacting with this SelectWidget.
*
* Currently this is just used to set `aria-activedescendant` on it.
*
* @protected
* @param {jQuery} $focusOwner
*/
OO.ui.SelectWidget.prototype.setFocusOwner = function ( $focusOwner ) {
this.$focusOwner = $focusOwner;
};
/**
* DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
* with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
* This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
* options. For more information about options and selects, please see the
* [OOUI documentation on MediaWiki][1].
*
* @example
* // Decorated options in a select widget
* var select = new OO.ui.SelectWidget( {
* items: [
* new OO.ui.DecoratedOptionWidget( {
* data: 'a',
* label: 'Option with icon',
* icon: 'help'
* } ),
* new OO.ui.DecoratedOptionWidget( {
* data: 'b',
* label: 'Option with indicator',
* indicator: 'next'
* } )
* ]
* } );
* $( 'body' ).append( select.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
*
* @class
* @extends OO.ui.OptionWidget
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
// Parent constructor
OO.ui.DecoratedOptionWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
// Initialization
this.$element
.addClass( 'oo-ui-decoratedOptionWidget' )
.prepend( this.$icon )
.append( this.$indicator );
};
/* Setup */
OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
/**
* MenuOptionWidget is an option widget that looks like a menu item. The class is used with
* OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
* the [OOUI documentation on MediaWiki] [1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
*
* @class
* @extends OO.ui.DecoratedOptionWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
// Parent constructor
OO.ui.MenuOptionWidget.parent.call( this, config );
// Properties
this.checkIcon = new OO.ui.IconWidget( {
icon: 'check',
classes: [ 'oo-ui-menuOptionWidget-checkIcon' ]
} );
// Initialization
this.$element
.prepend( this.checkIcon.$element )
.addClass( 'oo-ui-menuOptionWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
/**
* MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
* {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
*
* @example
* var myDropdown = new OO.ui.DropdownWidget( {
* menu: {
* items: [
* new OO.ui.MenuSectionOptionWidget( {
* label: 'Dogs'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'corgi',
* label: 'Welsh Corgi'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'poodle',
* label: 'Standard Poodle'
* } ),
* new OO.ui.MenuSectionOptionWidget( {
* label: 'Cats'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'lion',
* label: 'Lion'
* } )
* ]
* }
* } );
* $( 'body' ).append( myDropdown.$element );
*
* @class
* @extends OO.ui.DecoratedOptionWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
// Parent constructor
OO.ui.MenuSectionOptionWidget.parent.call( this, config );
// Initialization
this.$element.addClass( 'oo-ui-menuSectionOptionWidget' )
.removeAttr( 'role aria-selected' );
};
/* Setup */
OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.MenuSectionOptionWidget.static.selectable = false;
/**
* @static
* @inheritdoc
*/
OO.ui.MenuSectionOptionWidget.static.highlightable = false;
/**
* MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
* is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
* See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
* and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
* MenuSelectWidgets themselves are not instantiated directly, rather subclassed
* and customized to be opened, closed, and displayed as needed.
*
* By default, menus are clipped to the visible viewport and are not visible when a user presses the
* mouse outside the menu.
*
* Menus also have support for keyboard interaction:
*
* - Enter/Return key: choose and select a menu option
* - Up-arrow key: highlight the previous menu option
* - Down-arrow key: highlight the next menu option
* - Esc key: hide the menu
*
* Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
*
* Please see the [OOUI documentation on MediaWiki][1] for more information.
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
*
* @class
* @extends OO.ui.SelectWidget
* @mixins OO.ui.mixin.ClippableElement
* @mixins OO.ui.mixin.FloatableElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
* the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
* and {@link OO.ui.mixin.LookupElement LookupElement}
* @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
* the text the user types. This config is used by {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
* @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
* anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
* that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
* that button, unless the button (or its parent widget) is passed in here.
* @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
* @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
* @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
* @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
* @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
* @cfg {number} [width] Width of the menu
*/
OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.MenuSelectWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
OO.ui.mixin.FloatableElement.call( this, config );
// Initial vertical positions other than 'center' will result in
// the menu being flipped if there is not enough space in the container.
// Store the original position so we know what to reset to.
this.originalVerticalPosition = this.verticalPosition;
// Properties
this.autoHide = config.autoHide === undefined || !!config.autoHide;
this.hideOnChoose = config.hideOnChoose === undefined || !!config.hideOnChoose;
this.filterFromInput = !!config.filterFromInput;
this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
this.$widget = config.widget ? config.widget.$element : null;
this.$autoCloseIgnore = config.$autoCloseIgnore || $( [] );
this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
this.highlightOnFilter = !!config.highlightOnFilter;
this.width = config.width;
// Initialization
this.$element.addClass( 'oo-ui-menuSelectWidget' );
if ( config.widget ) {
this.setFocusOwner( config.widget.$tabIndexed );
}
// Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
// that reference properties not initialized at that time of parent class construction
// TODO: Find a better way to handle post-constructor setup
this.visible = false;
this.$element.addClass( 'oo-ui-element-hidden' );
};
/* Setup */
OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.FloatableElement );
/* Events */
/**
* @event ready
*
* The menu is ready: it is visible and has been positioned and clipped.
*/
/* Static properties */
/**
* Positions to flip to if there isn't room in the container for the
* menu in a specific direction.
*
* @property {Object.<string,string>}
*/
OO.ui.MenuSelectWidget.static.flippedPositions = {
below: 'above',
above: 'below',
top: 'bottom',
bottom: 'top'
};
/* Methods */
/**
* Handles document mouse down events.
*
* @protected
* @param {MouseEvent} e Mouse down event
*/
OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
if (
this.isVisible() &&
!OO.ui.contains(
this.$element.add( this.$widget ).add( this.$autoCloseIgnore ).get(),
e.target,
true
)
) {
this.toggle( false );
}
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.onDocumentKeyDown = function ( e ) {
var currentItem = this.findHighlightedItem() || this.findSelectedItem();
if ( !this.isDisabled() && this.isVisible() ) {
switch ( e.keyCode ) {
case OO.ui.Keys.LEFT:
case OO.ui.Keys.RIGHT:
// Do nothing if a text field is associated, arrow keys will be handled natively
if ( !this.$input ) {
OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
}
break;
case OO.ui.Keys.ESCAPE:
case OO.ui.Keys.TAB:
if ( currentItem ) {
currentItem.setHighlighted( false );
}
this.toggle( false );
// Don't prevent tabbing away, prevent defocusing
if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
e.preventDefault();
e.stopPropagation();
}
break;
default:
OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
return;
}
}
};
/**
* Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
* or after items were added/removed (always).
*
* @protected
*/
OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
var i, item, items, visible, section, sectionEmpty, filter, exactFilter,
anyVisible = false,
len = this.items.length,
showAll = !this.isVisible(),
exactMatch = false;
if ( this.$input && this.filterFromInput ) {
filter = showAll ? null : this.getItemMatcher( this.$input.val() );
exactFilter = this.getItemMatcher( this.$input.val(), true );
// Hide non-matching options, and also hide section headers if all options
// in their section are hidden.
for ( i = 0; i < len; i++ ) {
item = this.items[ i ];
if ( item instanceof OO.ui.MenuSectionOptionWidget ) {
if ( section ) {
// If the previous section was empty, hide its header
section.toggle( showAll || !sectionEmpty );
}
section = item;
sectionEmpty = true;
} else if ( item instanceof OO.ui.OptionWidget ) {
visible = showAll || filter( item );
exactMatch = exactMatch || exactFilter( item );
anyVisible = anyVisible || visible;
sectionEmpty = sectionEmpty && !visible;
item.toggle( visible );
}
}
// Process the final section
if ( section ) {
section.toggle( showAll || !sectionEmpty );
}
if ( anyVisible && this.items.length && !exactMatch ) {
this.scrollItemIntoView( this.items[ 0 ] );
}
if ( !anyVisible ) {
this.highlightItem( null );
}
this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible );
if ( this.highlightOnFilter ) {
// Highlight the first item on the list
item = null;
items = this.getItems();
for ( i = 0; i < items.length; i++ ) {
if ( items[ i ].isVisible() ) {
item = items[ i ];
break;
}
}
this.highlightItem( item );
}
}
// Reevaluate clipping
this.clip();
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.bindDocumentKeyDownListener = function () {
if ( this.$input ) {
this.$input.on( 'keydown', this.onDocumentKeyDownHandler );
} else {
OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyDownListener.call( this );
}
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyDownListener = function () {
if ( this.$input ) {
this.$input.off( 'keydown', this.onDocumentKeyDownHandler );
} else {
OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyDownListener.call( this );
}
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.bindDocumentKeyPressListener = function () {
if ( this.$input ) {
if ( this.filterFromInput ) {
this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
this.updateItemVisibility();
}
} else {
OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyPressListener.call( this );
}
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyPressListener = function () {
if ( this.$input ) {
if ( this.filterFromInput ) {
this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
this.updateItemVisibility();
}
} else {
OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyPressListener.call( this );
}
};
/**
* Choose an item.
*
* When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
*
* Note that โchooseโ should never be modified programmatically. A user can choose an option with the keyboard
* or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
*
* @param {OO.ui.OptionWidget} item Item to choose
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
if ( this.hideOnChoose ) {
this.toggle( false );
}
return this;
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
// Parent method
OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
this.updateItemVisibility();
return this;
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
// Parent method
OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
this.updateItemVisibility();
return this;
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.clearItems = function () {
// Parent method
OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
this.updateItemVisibility();
return this;
};
/**
* Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
* `.toggle( true )` after its #$element is attached to the DOM.
*
* Do not show the menu while it is not attached to the DOM. The calculations required to display
* it in the right place and with the right dimensions only work correctly while it is attached.
* Side-effects may include broken interface and exceptions being thrown. This wasn't always
* strictly enforced, so currently it only generates a warning in the browser console.
*
* @fires ready
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
var change, originalHeight, flippedHeight;
visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
change = visible !== this.isVisible();
if ( visible && !this.warnedUnattached && !this.isElementAttached() ) {
OO.ui.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
this.warnedUnattached = true;
}
if ( change && visible ) {
// Reset position before showing the popup again. It's possible we no longer need to flip
// (e.g. if the user scrolled).
this.setVerticalPosition( this.originalVerticalPosition );
}
// Parent method
OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
if ( change ) {
if ( visible ) {
if ( this.width ) {
this.setIdealSize( this.width );
} else if ( this.$floatableContainer ) {
this.$clippable.css( 'width', 'auto' );
this.setIdealSize(
this.$floatableContainer[ 0 ].offsetWidth > this.$clippable[ 0 ].offsetWidth ?
// Dropdown is smaller than handle so expand to width
this.$floatableContainer[ 0 ].offsetWidth :
// Dropdown is larger than handle so auto size
'auto'
);
this.$clippable.css( 'width', '' );
}
this.togglePositioning( !!this.$floatableContainer );
this.toggleClipping( true );
this.bindDocumentKeyDownListener();
this.bindDocumentKeyPressListener();
if (
( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
this.originalVerticalPosition !== 'center'
) {
// If opening the menu in one direction causes it to be clipped, flip it
originalHeight = this.$element.height();
this.setVerticalPosition(
this.constructor.static.flippedPositions[ this.originalVerticalPosition ]
);
if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
// If flipping also causes it to be clipped, open in whichever direction
// we have more space
flippedHeight = this.$element.height();
if ( originalHeight > flippedHeight ) {
this.setVerticalPosition( this.originalVerticalPosition );
}
}
}
// Note that we do not flip the menu's opening direction if the clipping changes
// later (e.g. after the user scrolls), that seems like it would be annoying
this.$focusOwner.attr( 'aria-expanded', 'true' );
if ( this.findSelectedItem() ) {
this.$focusOwner.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
this.findSelectedItem().scrollElementIntoView( { duration: 0 } );
}
// Auto-hide
if ( this.autoHide ) {
this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
}
this.emit( 'ready' );
} else {
this.$focusOwner.removeAttr( 'aria-activedescendant' );
this.unbindDocumentKeyDownListener();
this.unbindDocumentKeyPressListener();
this.$focusOwner.attr( 'aria-expanded', 'false' );
this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
this.togglePositioning( false );
this.toggleClipping( false );
}
}
return this;
};
/**
* DropdownWidgets are not menus themselves, rather they contain a menu of options created with
* OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
* users can interact with it.
*
* If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
* OO.ui.DropdownInputWidget instead.
*
* @example
* // Example: A DropdownWidget with a menu that contains three options
* var dropDown = new OO.ui.DropdownWidget( {
* label: 'Dropdown menu: Select a menu option',
* menu: {
* items: [
* new OO.ui.MenuOptionWidget( {
* data: 'a',
* label: 'First'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'b',
* label: 'Second'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'c',
* label: 'Third'
* } )
* ]
* }
* } );
*
* $( 'body' ).append( dropDown.$element );
*
* dropDown.getMenu().selectItemByData( 'b' );
*
* dropDown.getMenu().findSelectedItem().getData(); // returns 'b'
*
* For more information, please see the [OOUI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.TitledElement
* @mixins OO.ui.mixin.TabIndexedElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
* @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
* the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
* containing `<div>` and has a larger area. By default, the menu uses relative positioning.
* See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
*/
OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
// Configuration initialization
config = $.extend( { indicator: 'down' }, config );
// Parent constructor
OO.ui.DropdownWidget.parent.call( this, config );
// Properties (must be set before TabIndexedElement constructor call)
this.$handle = $( '<span>' );
this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
// Mixin constructors
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
// Properties
this.menu = new OO.ui.MenuSelectWidget( $.extend( {
widget: this,
$floatableContainer: this.$element
}, config.menu ) );
// Events
this.$handle.on( {
click: this.onClick.bind( this ),
keydown: this.onKeyDown.bind( this ),
// Hack? Handle type-to-search when menu is not expanded and not handling its own events
keypress: this.menu.onDocumentKeyPressHandler,
blur: this.menu.clearKeyPressBuffer.bind( this.menu )
} );
this.menu.connect( this, {
select: 'onMenuSelect',
toggle: 'onMenuToggle'
} );
// Initialization
this.$handle
.addClass( 'oo-ui-dropdownWidget-handle' )
.attr( {
role: 'combobox',
'aria-owns': this.menu.getElementId(),
'aria-autocomplete': 'list'
} )
.append( this.$icon, this.$label, this.$indicator );
this.$element
.addClass( 'oo-ui-dropdownWidget' )
.append( this.$handle );
this.$overlay.append( this.menu.$element );
};
/* Setup */
OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
/* Methods */
/**
* Get the menu.
*
* @return {OO.ui.MenuSelectWidget} Menu of widget
*/
OO.ui.DropdownWidget.prototype.getMenu = function () {
return this.menu;
};
/**
* Handles menu select events.
*
* @private
* @param {OO.ui.MenuOptionWidget} item Selected menu item
*/
OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
var selectedLabel;
if ( !item ) {
this.setLabel( null );
return;
}
selectedLabel = item.getLabel();
// If the label is a DOM element, clone it, because setLabel will append() it
if ( selectedLabel instanceof $ ) {
selectedLabel = selectedLabel.clone();
}
this.setLabel( selectedLabel );
};
/**
* Handle menu toggle events.
*
* @private
* @param {boolean} isVisible Open state of the menu
*/
OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) {
this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible );
this.$handle.attr(
'aria-expanded',
this.$element.hasClass( 'oo-ui-dropdownWidget-open' ).toString()
);
};
/**
* Handle mouse click events.
*
* @private
* @param {jQuery.Event} e Mouse click event
* @return {undefined/boolean} False to prevent default if event is handled
*/
OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
this.menu.toggle();
}
return false;
};
/**
* Handle key down events.
*
* @private
* @param {jQuery.Event} e Key down event
* @return {undefined/boolean} False to prevent default if event is handled
*/
OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
if (
!this.isDisabled() &&
(
e.which === OO.ui.Keys.ENTER ||
(
e.which === OO.ui.Keys.SPACE &&
// Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
// Space only closes the menu is the user is not typing to search.
this.menu.keyPressBuffer === ''
) ||
(
!this.menu.isVisible() &&
(
e.which === OO.ui.Keys.UP ||
e.which === OO.ui.Keys.DOWN
)
)
)
) {
this.menu.toggle();
return false;
}
};
/**
* RadioOptionWidget is an option widget that looks like a radio button.
* The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
* Please see the [OOUI documentation on MediaWiki] [1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
*
* @class
* @extends OO.ui.OptionWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
// Configuration initialization
config = config || {};
// Properties (must be done before parent constructor which calls #setDisabled)
this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
// Parent constructor
OO.ui.RadioOptionWidget.parent.call( this, config );
// Initialization
// Remove implicit role, we're handling it ourselves
this.radio.$input.attr( 'role', 'presentation' );
this.$element
.addClass( 'oo-ui-radioOptionWidget' )
.attr( 'role', 'radio' )
.attr( 'aria-checked', 'false' )
.removeAttr( 'aria-selected' )
.prepend( this.radio.$element );
};
/* Setup */
OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.RadioOptionWidget.static.highlightable = false;
/**
* @static
* @inheritdoc
*/
OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
/**
* @static
* @inheritdoc
*/
OO.ui.RadioOptionWidget.static.pressable = false;
/**
* @static
* @inheritdoc
*/
OO.ui.RadioOptionWidget.static.tagName = 'label';
/* Methods */
/**
* @inheritdoc
*/
OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
this.radio.setSelected( state );
this.$element
.attr( 'aria-checked', state.toString() )
.removeAttr( 'aria-selected' );
return this;
};
/**
* @inheritdoc
*/
OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
this.radio.setDisabled( this.isDisabled() );
return this;
};
/**
* RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
* options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
* an interface for adding, removing and selecting options.
* Please see the [OOUI documentation on MediaWiki][1] for more information.
*
* If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
* OO.ui.RadioSelectInputWidget instead.
*
* @example
* // A RadioSelectWidget with RadioOptions.
* var option1 = new OO.ui.RadioOptionWidget( {
* data: 'a',
* label: 'Selected radio option'
* } );
*
* var option2 = new OO.ui.RadioOptionWidget( {
* data: 'b',
* label: 'Unselected radio option'
* } );
*
* var radioSelect=new OO.ui.RadioSelectWidget( {
* items: [ option1, option2 ]
* } );
*
* // Select 'option 1' using the RadioSelectWidget's selectItem() method.
* radioSelect.selectItem( option1 );
*
* $( 'body' ).append( radioSelect.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
*
* @class
* @extends OO.ui.SelectWidget
* @mixins OO.ui.mixin.TabIndexedElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
// Parent constructor
OO.ui.RadioSelectWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.TabIndexedElement.call( this, config );
// Events
this.$element.on( {
focus: this.bindDocumentKeyDownListener.bind( this ),
blur: this.unbindDocumentKeyDownListener.bind( this )
} );
// Initialization
this.$element
.addClass( 'oo-ui-radioSelectWidget' )
.attr( 'role', 'radiogroup' );
};
/* Setup */
OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
/**
* MultioptionWidgets are special elements that can be selected and configured with data. The
* data is often unique for each option, but it does not have to be. MultioptionWidgets are used
* with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
* and examples, please see the [OOUI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Multioptions
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.ItemWidget
* @mixins OO.ui.mixin.LabelElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [selected=false] Whether the option is initially selected
*/
OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.MultioptionWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.ItemWidget.call( this );
OO.ui.mixin.LabelElement.call( this, config );
// Properties
this.selected = null;
// Initialization
this.$element
.addClass( 'oo-ui-multioptionWidget' )
.append( this.$label );
this.setSelected( config.selected );
};
/* Setup */
OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget );
OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement );
/* Events */
/**
* @event change
*
* A change event is emitted when the selected state of the option changes.
*
* @param {boolean} selected Whether the option is now selected
*/
/* Methods */
/**
* Check if the option is selected.
*
* @return {boolean} Item is selected
*/
OO.ui.MultioptionWidget.prototype.isSelected = function () {
return this.selected;
};
/**
* Set the optionโs selected state. In general, all modifications to the selection
* should be handled by the SelectWidgetโs {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
* method instead of this method.
*
* @param {boolean} [state=false] Select option
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) {
state = !!state;
if ( this.selected !== state ) {
this.selected = state;
this.emit( 'change', state );
this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state );
}
return this;
};
/**
* MultiselectWidget allows selecting multiple options from a list.
*
* For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
*
* @class
* @abstract
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.GroupWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
*/
OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) {
// Parent constructor
OO.ui.MultiselectWidget.parent.call( this, config );
// Configuration initialization
config = config || {};
// Mixin constructors
OO.ui.mixin.GroupWidget.call( this, config );
// Events
this.aggregate( { change: 'select' } );
// This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
// by GroupElement only when items are added/removed
this.connect( this, { select: [ 'emit', 'change' ] } );
// Initialization
if ( config.items ) {
this.addItems( config.items );
}
this.$group.addClass( 'oo-ui-multiselectWidget-group' );
this.$element.addClass( 'oo-ui-multiselectWidget' )
.append( this.$group );
};
/* Setup */
OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget );
/* Events */
/**
* @event change
*
* A change event is emitted when the set of items changes, or an item is selected or deselected.
*/
/**
* @event select
*
* A select event is emitted when an item is selected or deselected.
*/
/* Methods */
/**
* Find options that are selected.
*
* @return {OO.ui.MultioptionWidget[]} Selected options
*/
OO.ui.MultiselectWidget.prototype.findSelectedItems = function () {
return this.items.filter( function ( item ) {
return item.isSelected();
} );
};
/**
* Find the data of options that are selected.
*
* @return {Object[]|string[]} Values of selected options
*/
OO.ui.MultiselectWidget.prototype.findSelectedItemsData = function () {
return this.findSelectedItems().map( function ( item ) {
return item.data;
} );
};
/**
* Select options by reference. Options not mentioned in the `items` array will be deselected.
*
* @param {OO.ui.MultioptionWidget[]} items Items to select
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) {
this.items.forEach( function ( item ) {
var selected = items.indexOf( item ) !== -1;
item.setSelected( selected );
} );
return this;
};
/**
* Select items by their data. Options not mentioned in the `datas` array will be deselected.
*
* @param {Object[]|string[]} datas Values of items to select
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) {
var items,
widget = this;
items = datas.map( function ( data ) {
return widget.findItemFromData( data );
} );
this.selectItems( items );
return this;
};
/**
* CheckboxMultioptionWidget is an option widget that looks like a checkbox.
* The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
* Please see the [OOUI documentation on MediaWiki] [1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
*
* @class
* @extends OO.ui.MultioptionWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) {
// Configuration initialization
config = config || {};
// Properties (must be done before parent constructor which calls #setDisabled)
this.checkbox = new OO.ui.CheckboxInputWidget();
// Parent constructor
OO.ui.CheckboxMultioptionWidget.parent.call( this, config );
// Events
this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) );
this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
// Initialization
this.$element
.addClass( 'oo-ui-checkboxMultioptionWidget' )
.prepend( this.checkbox.$element );
};
/* Setup */
OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.CheckboxMultioptionWidget.static.tagName = 'label';
/* Methods */
/**
* Handle checkbox selected state change.
*
* @private
*/
OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () {
this.setSelected( this.checkbox.isSelected() );
};
/**
* @inheritdoc
*/
OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) {
OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state );
this.checkbox.setSelected( state );
return this;
};
/**
* @inheritdoc
*/
OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) {
OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled );
this.checkbox.setDisabled( this.isDisabled() );
return this;
};
/**
* Focus the widget.
*/
OO.ui.CheckboxMultioptionWidget.prototype.focus = function () {
this.checkbox.focus();
};
/**
* Handle key down events.
*
* @protected
* @param {jQuery.Event} e
*/
OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) {
var
element = this.getElementGroup(),
nextItem;
if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) {
nextItem = element.getRelativeFocusableItem( this, -1 );
} else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) {
nextItem = element.getRelativeFocusableItem( this, 1 );
}
if ( nextItem ) {
e.preventDefault();
nextItem.focus();
}
};
/**
* CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
* checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
* CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
* Please see the [OOUI documentation on MediaWiki][1] for more information.
*
* If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
* OO.ui.CheckboxMultiselectInputWidget instead.
*
* @example
* // A CheckboxMultiselectWidget with CheckboxMultioptions.
* var option1 = new OO.ui.CheckboxMultioptionWidget( {
* data: 'a',
* selected: true,
* label: 'Selected checkbox'
* } );
*
* var option2 = new OO.ui.CheckboxMultioptionWidget( {
* data: 'b',
* label: 'Unselected checkbox'
* } );
*
* var multiselect=new OO.ui.CheckboxMultiselectWidget( {
* items: [ option1, option2 ]
* } );
*
* $( 'body' ).append( multiselect.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
*
* @class
* @extends OO.ui.MultiselectWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) {
// Parent constructor
OO.ui.CheckboxMultiselectWidget.parent.call( this, config );
// Properties
this.$lastClicked = null;
// Events
this.$group.on( 'click', this.onClick.bind( this ) );
// Initialization
this.$element
.addClass( 'oo-ui-checkboxMultiselectWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget );
/* Methods */
/**
* Get an option by its position relative to the specified item (or to the start of the option array,
* if item is `null`). The direction in which to search through the option array is specified with a
* number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
* `null` if there are no options in the array.
*
* @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
* @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
* @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
*/
OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) {
var currentIndex, nextIndex, i,
increase = direction > 0 ? 1 : -1,
len = this.items.length;
if ( item ) {
currentIndex = this.items.indexOf( item );
nextIndex = ( currentIndex + increase + len ) % len;
} else {
// If no item is selected and moving forward, start at the beginning.
// If moving backward, start at the end.
nextIndex = direction > 0 ? 0 : len - 1;
}
for ( i = 0; i < len; i++ ) {
item = this.items[ nextIndex ];
if ( item && !item.isDisabled() ) {
return item;
}
nextIndex = ( nextIndex + increase + len ) % len;
}
return null;
};
/**
* Handle click events on checkboxes.
*
* @param {jQuery.Event} e
*/
OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) {
var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items,
$lastClicked = this.$lastClicked,
$nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' )
.not( '.oo-ui-widget-disabled' );
// Allow selecting multiple options at once by Shift-clicking them
if ( $lastClicked && $nowClicked.length && e.shiftKey ) {
$options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' );
lastClickedIndex = $options.index( $lastClicked );
nowClickedIndex = $options.index( $nowClicked );
// If it's the same item, either the user is being silly, or it's a fake event generated by the
// browser. In either case we don't need custom handling.
if ( nowClickedIndex !== lastClickedIndex ) {
items = this.items;
wasSelected = items[ nowClickedIndex ].isSelected();
direction = nowClickedIndex > lastClickedIndex ? 1 : -1;
// This depends on the DOM order of the items and the order of the .items array being the same.
for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) {
if ( !items[ i ].isDisabled() ) {
items[ i ].setSelected( !wasSelected );
}
}
// For the now-clicked element, use immediate timeout to allow the browser to do its own
// handling first, then set our value. The order in which events happen is different for
// clicks on the <input> and on the <label> and there are additional fake clicks fired for
// non-click actions that change the checkboxes.
e.preventDefault();
setTimeout( function () {
if ( !items[ nowClickedIndex ].isDisabled() ) {
items[ nowClickedIndex ].setSelected( !wasSelected );
}
} );
}
}
if ( $nowClicked.length ) {
this.$lastClicked = $nowClicked;
}
};
/**
* Focus the widget
*
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.CheckboxMultiselectWidget.prototype.focus = function () {
var item;
if ( !this.isDisabled() ) {
item = this.getRelativeFocusableItem( null, 1 );
if ( item ) {
item.focus();
}
}
return this;
};
/**
* @inheritdoc
*/
OO.ui.CheckboxMultiselectWidget.prototype.simulateLabelClick = function () {
this.focus();
};
/**
* Progress bars visually display the status of an operation, such as a download,
* and can be either determinate or indeterminate:
*
* - **determinate** process bars show the percent of an operation that is complete.
*
* - **indeterminate** process bars use a visual display of motion to indicate that an operation
* is taking place. Because the extent of an indeterminate operation is unknown, the bar does
* not use percentages.
*
* The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
*
* @example
* // Examples of determinate and indeterminate progress bars.
* var progressBar1 = new OO.ui.ProgressBarWidget( {
* progress: 33
* } );
* var progressBar2 = new OO.ui.ProgressBarWidget();
*
* // Create a FieldsetLayout to layout progress bars
* var fieldset = new OO.ui.FieldsetLayout;
* fieldset.addItems( [
* new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
* new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
* ] );
* $( 'body' ).append( fieldset.$element );
*
* @class
* @extends OO.ui.Widget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
* To create a determinate progress bar, specify a number that reflects the initial percent complete.
* By default, the progress bar is indeterminate.
*/
OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.ProgressBarWidget.parent.call( this, config );
// Properties
this.$bar = $( '<div>' );
this.progress = null;
// Initialization
this.setProgress( config.progress !== undefined ? config.progress : false );
this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
this.$element
.attr( {
role: 'progressbar',
'aria-valuemin': 0,
'aria-valuemax': 100
} )
.addClass( 'oo-ui-progressBarWidget' )
.append( this.$bar );
};
/* Setup */
OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.ProgressBarWidget.static.tagName = 'div';
/* Methods */
/**
* Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
*
* @return {number|boolean} Progress percent
*/
OO.ui.ProgressBarWidget.prototype.getProgress = function () {
return this.progress;
};
/**
* Set the percent of the process completed or `false` for an indeterminate process.
*
* @param {number|boolean} progress Progress percent or `false` for indeterminate
*/
OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
this.progress = progress;
if ( progress !== false ) {
this.$bar.css( 'width', this.progress + '%' );
this.$element.attr( 'aria-valuenow', this.progress );
} else {
this.$bar.css( 'width', '' );
this.$element.removeAttr( 'aria-valuenow' );
}
this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false );
};
/**
* InputWidget is the base class for all input widgets, which
* include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
* {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
* See the [OOUI documentation on MediaWiki] [1] for more information and examples.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
*
* @abstract
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.FlaggedElement
* @mixins OO.ui.mixin.TabIndexedElement
* @mixins OO.ui.mixin.TitledElement
* @mixins OO.ui.mixin.AccessKeyedElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [name=''] The value of the inputโs HTML `name` attribute.
* @cfg {string} [value=''] The value of the input.
* @cfg {string} [dir] The directionality of the input (ltr/rtl).
* @cfg {string} [inputId] The value of the inputโs HTML `id` attribute.
* @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
* before it is accepted.
*/
OO.ui.InputWidget = function OoUiInputWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.InputWidget.parent.call( this, config );
// Properties
// See #reusePreInfuseDOM about config.$input
this.$input = config.$input || this.getInputElement( config );
this.value = '';
this.inputFilter = config.inputFilter;
// Mixin constructors
OO.ui.mixin.FlaggedElement.call( this, config );
OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
// Events
this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
// Initialization
this.$input
.addClass( 'oo-ui-inputWidget-input' )
.attr( 'name', config.name )
.prop( 'disabled', this.isDisabled() );
this.$element
.addClass( 'oo-ui-inputWidget' )
.append( this.$input );
this.setValue( config.value );
if ( config.dir ) {
this.setDir( config.dir );
}
if ( config.inputId !== undefined ) {
this.setInputId( config.inputId );
}
};
/* Setup */
OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
/* Static Methods */
/**
* @inheritdoc
*/
OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
// Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
return config;
};
/**
* @inheritdoc
*/
OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
if ( config.$input && config.$input.length ) {
state.value = config.$input.val();
// Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
state.focus = config.$input.is( ':focus' );
}
return state;
};
/* Events */
/**
* @event change
*
* A change event is emitted when the value of the input changes.
*
* @param {string} value
*/
/* Methods */
/**
* Get input element.
*
* Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
* different circumstances. The element must have a `value` property (like form elements).
*
* @protected
* @param {Object} config Configuration options
* @return {jQuery} Input element
*/
OO.ui.InputWidget.prototype.getInputElement = function () {
return $( '<input>' );
};
/**
* Handle potentially value-changing events.
*
* @private
* @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
*/
OO.ui.InputWidget.prototype.onEdit = function () {
var widget = this;
if ( !this.isDisabled() ) {
// Allow the stack to clear so the value will be updated
setTimeout( function () {
widget.setValue( widget.$input.val() );
} );
}
};
/**
* Get the value of the input.
*
* @return {string} Input value
*/
OO.ui.InputWidget.prototype.getValue = function () {
// Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
// it, and we won't know unless they're kind enough to trigger a 'change' event.
var value = this.$input.val();
if ( this.value !== value ) {
this.setValue( value );
}
return this.value;
};
/**
* Set the directionality of the input.
*
* @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.InputWidget.prototype.setDir = function ( dir ) {
this.$input.prop( 'dir', dir );
return this;
};
/**
* Set the value of the input.
*
* @param {string} value New value
* @fires change
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.InputWidget.prototype.setValue = function ( value ) {
value = this.cleanUpValue( value );
// Update the DOM if it has changed. Note that with cleanUpValue, it
// is possible for the DOM value to change without this.value changing.
if ( this.$input.val() !== value ) {
this.$input.val( value );
}
if ( this.value !== value ) {
this.value = value;
this.emit( 'change', this.value );
}
// The first time that the value is set (probably while constructing the widget),
// remember it in defaultValue. This property can be later used to check whether
// the value of the input has been changed since it was created.
if ( this.defaultValue === undefined ) {
this.defaultValue = this.value;
this.$input[ 0 ].defaultValue = this.defaultValue;
}
return this;
};
/**
* Clean up incoming value.
*
* Ensures value is a string, and converts undefined and null to empty string.
*
* @private
* @param {string} value Original value
* @return {string} Cleaned up value
*/
OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
if ( value === undefined || value === null ) {
return '';
} else if ( this.inputFilter ) {
return this.inputFilter( String( value ) );
} else {
return String( value );
}
};
/**
* @inheritdoc
*/
OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
if ( this.$input ) {
this.$input.prop( 'disabled', this.isDisabled() );
}
return this;
};
/**
* Set the 'id' attribute of the `<input>` element.
*
* @param {string} id
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.InputWidget.prototype.setInputId = function ( id ) {
this.$input.attr( 'id', id );
return this;
};
/**
* @inheritdoc
*/
OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
if ( state.value !== undefined && state.value !== this.getValue() ) {
this.setValue( state.value );
}
if ( state.focus ) {
this.focus();
}
};
/**
* Data widget intended for creating 'hidden'-type inputs.
*
* @class
* @extends OO.ui.Widget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [value=''] The value of the input.
* @cfg {string} [name=''] The value of the inputโs HTML `name` attribute.
*/
OO.ui.HiddenInputWidget = function OoUiHiddenInputWidget( config ) {
// Configuration initialization
config = $.extend( { value: '', name: '' }, config );
// Parent constructor
OO.ui.HiddenInputWidget.parent.call( this, config );
// Initialization
this.$element.attr( {
type: 'hidden',
value: config.value,
name: config.name
} );
this.$element.removeAttr( 'aria-disabled' );
};
/* Setup */
OO.inheritClass( OO.ui.HiddenInputWidget, OO.ui.Widget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.HiddenInputWidget.static.tagName = 'input';
/**
* ButtonInputWidget is used to submit HTML forms and is intended to be used within
* a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
* want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
* HTML `<button>` (the default) or an HTML `<input>` tags. See the
* [OOUI documentation on MediaWiki] [1] for more information.
*
* @example
* // A ButtonInputWidget rendered as an HTML button, the default.
* var button = new OO.ui.ButtonInputWidget( {
* label: 'Input button',
* icon: 'check',
* value: 'check'
* } );
* $( 'body' ).append( button.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
*
* @class
* @extends OO.ui.InputWidget
* @mixins OO.ui.mixin.ButtonElement
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.TitledElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
* @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
* Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
* non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
* be set to `true` when thereโs need to support IE 6 in a form with multiple buttons.
*/
OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
// Configuration initialization
config = $.extend( { type: 'button', useInputTag: false }, config );
// See InputWidget#reusePreInfuseDOM about config.$input
if ( config.$input ) {
config.$input.empty();
}
// Properties (must be set before parent constructor, which calls #setValue)
this.useInputTag = config.useInputTag;
// Parent constructor
OO.ui.ButtonInputWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
// Initialization
if ( !config.useInputTag ) {
this.$input.append( this.$icon, this.$label, this.$indicator );
}
this.$element.addClass( 'oo-ui-buttonInputWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.ButtonInputWidget.static.tagName = 'span';
/* Methods */
/**
* @inheritdoc
* @protected
*/
OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
var type;
type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
};
/**
* Set label value.
*
* If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
*
* @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
* text, or `null` for no label
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
if ( typeof label === 'function' ) {
label = OO.ui.resolveMsg( label );
}
if ( this.useInputTag ) {
// Discard non-plaintext labels
if ( typeof label !== 'string' ) {
label = '';
}
this.$input.val( label );
}
return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
};
/**
* Set the value of the input.
*
* This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
* they do not support {@link #value values}.
*
* @param {string} value New value
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
if ( !this.useInputTag ) {
OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
}
return this;
};
/**
* @inheritdoc
*/
OO.ui.ButtonInputWidget.prototype.getInputId = function () {
// Disable generating `<label>` elements for buttons. One would very rarely need additional label
// for a button, and it's already a big clickable target, and it causes unexpected rendering.
return null;
};
/**
* CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
* Note that these {@link OO.ui.InputWidget input widgets} are best laid out
* in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
* alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
*
* This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
*
* @example
* // An example of selected, unselected, and disabled checkbox inputs
* var checkbox1=new OO.ui.CheckboxInputWidget( {
* value: 'a',
* selected: true
* } );
* var checkbox2=new OO.ui.CheckboxInputWidget( {
* value: 'b'
* } );
* var checkbox3=new OO.ui.CheckboxInputWidget( {
* value:'c',
* disabled: true
* } );
* // Create a fieldset layout with fields for each checkbox.
* var fieldset = new OO.ui.FieldsetLayout( {
* label: 'Checkboxes'
* } );
* fieldset.addItems( [
* new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
* new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
* new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
* ] );
* $( 'body' ).append( fieldset.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
*
* @class
* @extends OO.ui.InputWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
*/
OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.CheckboxInputWidget.parent.call( this, config );
// Properties
this.checkIcon = new OO.ui.IconWidget( {
icon: 'check',
classes: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
} );
// Initialization
this.$element
.addClass( 'oo-ui-checkboxInputWidget' )
// Required for pretty styling in WikimediaUI theme
.append( this.checkIcon.$element );
this.setSelected( config.selected !== undefined ? config.selected : false );
};
/* Setup */
OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.CheckboxInputWidget.static.tagName = 'span';
/* Static Methods */
/**
* @inheritdoc
*/
OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
state.checked = config.$input.prop( 'checked' );
return state;
};
/* Methods */
/**
* @inheritdoc
* @protected
*/
OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
return $( '<input>' ).attr( 'type', 'checkbox' );
};
/**
* @inheritdoc
*/
OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
var widget = this;
if ( !this.isDisabled() ) {
// Allow the stack to clear so the value will be updated
setTimeout( function () {
widget.setSelected( widget.$input.prop( 'checked' ) );
} );
}
};
/**
* Set selection state of this checkbox.
*
* @param {boolean} state `true` for selected
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
state = !!state;
if ( this.selected !== state ) {
this.selected = state;
this.$input.prop( 'checked', this.selected );
this.emit( 'change', this.selected );
}
// The first time that the selection state is set (probably while constructing the widget),
// remember it in defaultSelected. This property can be later used to check whether
// the selection state of the input has been changed since it was created.
if ( this.defaultSelected === undefined ) {
this.defaultSelected = this.selected;
this.$input[ 0 ].defaultChecked = this.defaultSelected;
}
return this;
};
/**
* Check if this checkbox is selected.
*
* @return {boolean} Checkbox is selected
*/
OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
// Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
// it, and we won't know unless they're kind enough to trigger a 'change' event.
var selected = this.$input.prop( 'checked' );
if ( this.selected !== selected ) {
this.setSelected( selected );
}
return this.selected;
};
/**
* @inheritdoc
*/
OO.ui.CheckboxInputWidget.prototype.simulateLabelClick = function () {
if ( !this.isDisabled() ) {
this.$input.click();
}
this.focus();
};
/**
* @inheritdoc
*/
OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
this.setSelected( state.checked );
}
};
/**
* DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
* within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
* of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
* more information about input widgets.
*
* A DropdownInputWidget always has a value (one of the options is always selected), unless there
* are no options. If no `value` configuration option is provided, the first option is selected.
* If you need a state representing no value (no option being selected), use a DropdownWidget.
*
* This and OO.ui.RadioSelectInputWidget support the same configuration options.
*
* @example
* // Example: A DropdownInputWidget with three options
* var dropdownInput = new OO.ui.DropdownInputWidget( {
* options: [
* { data: 'a', label: 'First' },
* { data: 'b', label: 'Second'},
* { data: 'c', label: 'Third' }
* ]
* } );
* $( 'body' ).append( dropdownInput.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
*
* @class
* @extends OO.ui.InputWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: โฆ, label: โฆ }`
* @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
* @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
* the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
* containing `<div>` and has a larger area. By default, the menu uses relative positioning.
* See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
*/
OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
// Configuration initialization
config = config || {};
// Properties (must be done before parent constructor which calls #setDisabled)
this.dropdownWidget = new OO.ui.DropdownWidget( $.extend(
{
$overlay: config.$overlay
},
config.dropdown
) );
// Set up the options before parent constructor, which uses them to validate config.value.
// Use this instead of setOptions() because this.$input is not set up yet.
this.setOptionsData( config.options || [] );
// Parent constructor
OO.ui.DropdownInputWidget.parent.call( this, config );
// Events
this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
// Initialization
this.$element
.addClass( 'oo-ui-dropdownInputWidget' )
.append( this.dropdownWidget.$element );
this.setTabIndexedElement( this.dropdownWidget.$tabIndexed );
};
/* Setup */
OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
/* Methods */
/**
* @inheritdoc
* @protected
*/
OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
return $( '<select>' );
};
/**
* Handles menu select events.
*
* @private
* @param {OO.ui.MenuOptionWidget|null} item Selected menu item
*/
OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
this.setValue( item ? item.getData() : '' );
};
/**
* @inheritdoc
*/
OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
var selected;
value = this.cleanUpValue( value );
// Only allow setting values that are actually present in the dropdown
selected = this.dropdownWidget.getMenu().findItemFromData( value ) ||
this.dropdownWidget.getMenu().findFirstSelectableItem();
this.dropdownWidget.getMenu().selectItem( selected );
value = selected ? selected.getData() : '';
OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
if ( this.optionsDirty ) {
// We reached this from the constructor or from #setOptions.
// We have to update the <select> element.
this.updateOptionsInterface();
}
return this;
};
/**
* @inheritdoc
*/
OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
this.dropdownWidget.setDisabled( state );
OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
return this;
};
/**
* Set the options available for this input.
*
* @param {Object[]} options Array of menu options in the format `{ data: โฆ, label: โฆ }`
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
var value = this.getValue();
this.setOptionsData( options );
// Re-set the value to update the visible interface (DropdownWidget and <select>).
// In case the previous value is no longer an available option, select the first valid one.
this.setValue( value );
return this;
};
/**
* Set the internal list of options, used e.g. by setValue() to see which options are allowed.
*
* This method may be called before the parent constructor, so various properties may not be
* intialized yet.
*
* @param {Object[]} options Array of menu options in the format `{ data: โฆ, label: โฆ }`
* @private
*/
OO.ui.DropdownInputWidget.prototype.setOptionsData = function ( options ) {
var
optionWidgets,
widget = this;
this.optionsDirty = true;
optionWidgets = options.map( function ( opt ) {
var optValue;
if ( opt.optgroup !== undefined ) {
return widget.createMenuSectionOptionWidget( opt.optgroup );
}
optValue = widget.cleanUpValue( opt.data );
return widget.createMenuOptionWidget(
optValue,
opt.label !== undefined ? opt.label : optValue
);
} );
this.dropdownWidget.getMenu().clearItems().addItems( optionWidgets );
};
/**
* Create a menu option widget.
*
* @protected
* @param {string} data Item data
* @param {string} label Item label
* @return {OO.ui.MenuOptionWidget} Option widget
*/
OO.ui.DropdownInputWidget.prototype.createMenuOptionWidget = function ( data, label ) {
return new OO.ui.MenuOptionWidget( {
data: data,
label: label
} );
};
/**
* Create a menu section option widget.
*
* @protected
* @param {string} label Section item label
* @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
*/
OO.ui.DropdownInputWidget.prototype.createMenuSectionOptionWidget = function ( label ) {
return new OO.ui.MenuSectionOptionWidget( {
label: label
} );
};
/**
* Update the user-visible interface to match the internal list of options and value.
*
* This method must only be called after the parent constructor.
*
* @private
*/
OO.ui.DropdownInputWidget.prototype.updateOptionsInterface = function () {
var
$optionsContainer = this.$input,
defaultValue = this.defaultValue,
widget = this;
this.$input.empty();
this.dropdownWidget.getMenu().getItems().forEach( function ( optionWidget ) {
var $optionNode;
if ( !( optionWidget instanceof OO.ui.MenuSectionOptionWidget ) ) {
$optionNode = $( '<option>' )
.attr( 'value', optionWidget.getData() )
.text( optionWidget.getLabel() );
// Remember original selection state. This property can be later used to check whether
// the selection state of the input has been changed since it was created.
$optionNode[ 0 ].defaultSelected = ( optionWidget.getData() === defaultValue );
$optionsContainer.append( $optionNode );
} else {
$optionNode = $( '<optgroup>' )
.attr( 'label', optionWidget.getLabel() );
widget.$input.append( $optionNode );
$optionsContainer = $optionNode;
}
} );
this.optionsDirty = false;
};
/**
* @inheritdoc
*/
OO.ui.DropdownInputWidget.prototype.focus = function () {
this.dropdownWidget.focus();
return this;
};
/**
* @inheritdoc
*/
OO.ui.DropdownInputWidget.prototype.blur = function () {
this.dropdownWidget.blur();
return this;
};
/**
* RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
* in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
* with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
* please see the [OOUI documentation on MediaWiki][1].
*
* This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
*
* @example
* // An example of selected, unselected, and disabled radio inputs
* var radio1 = new OO.ui.RadioInputWidget( {
* value: 'a',
* selected: true
* } );
* var radio2 = new OO.ui.RadioInputWidget( {
* value: 'b'
* } );
* var radio3 = new OO.ui.RadioInputWidget( {
* value: 'c',
* disabled: true
* } );
* // Create a fieldset layout with fields for each radio button.
* var fieldset = new OO.ui.FieldsetLayout( {
* label: 'Radio inputs'
* } );
* fieldset.addItems( [
* new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
* new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
* new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
* ] );
* $( 'body' ).append( fieldset.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
*
* @class
* @extends OO.ui.InputWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
*/
OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.RadioInputWidget.parent.call( this, config );
// Initialization
this.$element
.addClass( 'oo-ui-radioInputWidget' )
// Required for pretty styling in WikimediaUI theme
.append( $( '<span>' ) );
this.setSelected( config.selected !== undefined ? config.selected : false );
};
/* Setup */
OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.RadioInputWidget.static.tagName = 'span';
/* Static Methods */
/**
* @inheritdoc
*/
OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
state.checked = config.$input.prop( 'checked' );
return state;
};
/* Methods */
/**
* @inheritdoc
* @protected
*/
OO.ui.RadioInputWidget.prototype.getInputElement = function () {
return $( '<input>' ).attr( 'type', 'radio' );
};
/**
* @inheritdoc
*/
OO.ui.RadioInputWidget.prototype.onEdit = function () {
// RadioInputWidget doesn't track its state.
};
/**
* Set selection state of this radio button.
*
* @param {boolean} state `true` for selected
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
// RadioInputWidget doesn't track its state.
this.$input.prop( 'checked', state );
// The first time that the selection state is set (probably while constructing the widget),
// remember it in defaultSelected. This property can be later used to check whether
// the selection state of the input has been changed since it was created.
if ( this.defaultSelected === undefined ) {
this.defaultSelected = state;
this.$input[ 0 ].defaultChecked = this.defaultSelected;
}
return this;
};
/**
* Check if this radio button is selected.
*
* @return {boolean} Radio is selected
*/
OO.ui.RadioInputWidget.prototype.isSelected = function () {
return this.$input.prop( 'checked' );
};
/**
* @inheritdoc
*/
OO.ui.RadioInputWidget.prototype.simulateLabelClick = function () {
if ( !this.isDisabled() ) {
this.$input.click();
}
this.focus();
};
/**
* @inheritdoc
*/
OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
this.setSelected( state.checked );
}
};
/**
* RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
* within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
* of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
* more information about input widgets.
*
* This and OO.ui.DropdownInputWidget support the same configuration options.
*
* @example
* // Example: A RadioSelectInputWidget with three options
* var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
* options: [
* { data: 'a', label: 'First' },
* { data: 'b', label: 'Second'},
* { data: 'c', label: 'Third' }
* ]
* } );
* $( 'body' ).append( radioSelectInput.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
*
* @class
* @extends OO.ui.InputWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: โฆ, label: โฆ }`
*/
OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
// Configuration initialization
config = config || {};
// Properties (must be done before parent constructor which calls #setDisabled)
this.radioSelectWidget = new OO.ui.RadioSelectWidget();
// Set up the options before parent constructor, which uses them to validate config.value.
// Use this instead of setOptions() because this.$input is not set up yet
this.setOptionsData( config.options || [] );
// Parent constructor
OO.ui.RadioSelectInputWidget.parent.call( this, config );
// Events
this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
// Initialization
this.$element
.addClass( 'oo-ui-radioSelectInputWidget' )
.append( this.radioSelectWidget.$element );
this.setTabIndexedElement( this.radioSelectWidget.$tabIndexed );
};
/* Setup */
OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
/* Static Methods */
/**
* @inheritdoc
*/
OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
return state;
};
/**
* @inheritdoc
*/
OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
// Cannot reuse the `<input type=radio>` set
delete config.$input;
return config;
};
/* Methods */
/**
* @inheritdoc
* @protected
*/
OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
// Use this instead of <input type="hidden">, because hidden inputs do not have separate
// 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
};
/**
* Handles menu select events.
*
* @private
* @param {OO.ui.RadioOptionWidget} item Selected menu item
*/
OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
this.setValue( item.getData() );
};
/**
* @inheritdoc
*/
OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
var selected;
value = this.cleanUpValue( value );
// Only allow setting values that are actually present in the dropdown
selected = this.radioSelectWidget.findItemFromData( value ) ||
this.radioSelectWidget.findFirstSelectableItem();
this.radioSelectWidget.selectItem( selected );
value = selected ? selected.getData() : '';
OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
return this;
};
/**
* @inheritdoc
*/
OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
this.radioSelectWidget.setDisabled( state );
OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
return this;
};
/**
* Set the options available for this input.
*
* @param {Object[]} options Array of menu options in the format `{ data: โฆ, label: โฆ }`
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
var value = this.getValue();
this.setOptionsData( options );
// Re-set the value to update the visible interface (RadioSelectWidget).
// In case the previous value is no longer an available option, select the first valid one.
this.setValue( value );
return this;
};
/**
* Set the internal list of options, used e.g. by setValue() to see which options are allowed.
*
* This method may be called before the parent constructor, so various properties may not be
* intialized yet.
*
* @param {Object[]} options Array of menu options in the format `{ data: โฆ, label: โฆ }`
* @private
*/
OO.ui.RadioSelectInputWidget.prototype.setOptionsData = function ( options ) {
var widget = this;
this.radioSelectWidget
.clearItems()
.addItems( options.map( function ( opt ) {
var optValue = widget.cleanUpValue( opt.data );
return new OO.ui.RadioOptionWidget( {
data: optValue,
label: opt.label !== undefined ? opt.label : optValue
} );
} ) );
};
/**
* @inheritdoc
*/
OO.ui.RadioSelectInputWidget.prototype.focus = function () {
this.radioSelectWidget.focus();
return this;
};
/**
* @inheritdoc
*/
OO.ui.RadioSelectInputWidget.prototype.blur = function () {
this.radioSelectWidget.blur();
return this;
};
/**
* CheckboxMultiselectInputWidget is a
* {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
* HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
* HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
* more information about input widgets.
*
* @example
* // Example: A CheckboxMultiselectInputWidget with three options
* var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
* options: [
* { data: 'a', label: 'First' },
* { data: 'b', label: 'Second'},
* { data: 'c', label: 'Third' }
* ]
* } );
* $( 'body' ).append( multiselectInput.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
*
* @class
* @extends OO.ui.InputWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: โฆ, label: โฆ, disabled: โฆ }`
*/
OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) {
// Configuration initialization
config = config || {};
// Properties (must be done before parent constructor which calls #setDisabled)
this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget();
// Must be set before the #setOptionsData call below
this.inputName = config.name;
// Set up the options before parent constructor, which uses them to validate config.value.
// Use this instead of setOptions() because this.$input is not set up yet
this.setOptionsData( config.options || [] );
// Parent constructor
OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config );
// Events
this.checkboxMultiselectWidget.connect( this, { select: 'onCheckboxesSelect' } );
// Initialization
this.$element
.addClass( 'oo-ui-checkboxMultiselectInputWidget' )
.append( this.checkboxMultiselectWidget.$element );
// We don't use this.$input, but rather the CheckboxInputWidgets inside each option
this.$input.detach();
};
/* Setup */
OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget );
/* Static Methods */
/**
* @inheritdoc
*/
OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState( node, config );
state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
.toArray().map( function ( el ) { return el.value; } );
return state;
};
/**
* @inheritdoc
*/
OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config );
// Cannot reuse the `<input type=checkbox>` set
delete config.$input;
return config;
};
/* Methods */
/**
* @inheritdoc
* @protected
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () {
// Actually unused
return $( '<unused>' );
};
/**
* Handles CheckboxMultiselectWidget select events.
*
* @private
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.onCheckboxesSelect = function () {
this.setValue( this.checkboxMultiselectWidget.findSelectedItemsData() );
};
/**
* @inheritdoc
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () {
var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
.toArray().map( function ( el ) { return el.value; } );
if ( this.value !== value ) {
this.setValue( value );
}
return this.value;
};
/**
* @inheritdoc
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) {
value = this.cleanUpValue( value );
this.checkboxMultiselectWidget.selectItemsByData( value );
OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value );
if ( this.optionsDirty ) {
// We reached this from the constructor or from #setOptions.
// We have to update the <select> element.
this.updateOptionsInterface();
}
return this;
};
/**
* Clean up incoming value.
*
* @param {string[]} value Original value
* @return {string[]} Cleaned up value
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) {
var i, singleValue,
cleanValue = [];
if ( !Array.isArray( value ) ) {
return cleanValue;
}
for ( i = 0; i < value.length; i++ ) {
singleValue =
OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( this, value[ i ] );
// Remove options that we don't have here
if ( !this.checkboxMultiselectWidget.findItemFromData( singleValue ) ) {
continue;
}
cleanValue.push( singleValue );
}
return cleanValue;
};
/**
* @inheritdoc
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) {
this.checkboxMultiselectWidget.setDisabled( state );
OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state );
return this;
};
/**
* Set the options available for this input.
*
* @param {Object[]} options Array of menu options in the format `{ data: โฆ, label: โฆ, disabled: โฆ }`
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) {
var value = this.getValue();
this.setOptionsData( options );
// Re-set the value to update the visible interface (CheckboxMultiselectWidget).
// This will also get rid of any stale options that we just removed.
this.setValue( value );
return this;
};
/**
* Set the internal list of options, used e.g. by setValue() to see which options are allowed.
*
* This method may be called before the parent constructor, so various properties may not be
* intialized yet.
*
* @param {Object[]} options Array of menu options in the format `{ data: โฆ, label: โฆ }`
* @private
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.setOptionsData = function ( options ) {
var widget = this;
this.optionsDirty = true;
this.checkboxMultiselectWidget
.clearItems()
.addItems( options.map( function ( opt ) {
var optValue, item, optDisabled;
optValue =
OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( widget, opt.data );
optDisabled = opt.disabled !== undefined ? opt.disabled : false;
item = new OO.ui.CheckboxMultioptionWidget( {
data: optValue,
label: opt.label !== undefined ? opt.label : optValue,
disabled: optDisabled
} );
// Set the 'name' and 'value' for form submission
item.checkbox.$input.attr( 'name', widget.inputName );
item.checkbox.setValue( optValue );
return item;
} ) );
};
/**
* Update the user-visible interface to match the internal list of options and value.
*
* This method must only be called after the parent constructor.
*
* @private
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.updateOptionsInterface = function () {
var defaultValue = this.defaultValue;
this.checkboxMultiselectWidget.getItems().forEach( function ( item ) {
// Remember original selection state. This property can be later used to check whether
// the selection state of the input has been changed since it was created.
var isDefault = defaultValue.indexOf( item.getData() ) !== -1;
item.checkbox.defaultSelected = isDefault;
item.checkbox.$input[ 0 ].defaultChecked = isDefault;
} );
this.optionsDirty = false;
};
/**
* @inheritdoc
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.focus = function () {
this.checkboxMultiselectWidget.focus();
return this;
};
/**
* TextInputWidgets, like HTML text inputs, can be configured with options that customize the
* size of the field as well as its presentation. In addition, these widgets can be configured
* with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
* validation-pattern (used to determine if an input value is valid or not) and an input filter,
* which modifies incoming values rather than validating them.
* Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
*
* This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
*
* @example
* // Example of a text input widget
* var textInput = new OO.ui.TextInputWidget( {
* value: 'Text input'
* } )
* $( 'body' ).append( textInput.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
*
* @class
* @extends OO.ui.InputWidget
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.PendingElement
* @mixins OO.ui.mixin.LabelElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
* 'email', 'url' or 'number'.
* @cfg {string} [placeholder] Placeholder text
* @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
* instruct the browser to focus this widget.
* @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
* @cfg {number} [maxLength] Maximum number of characters allowed in the input.
*
* For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
* Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
* many emojis) count as 2 characters each.
* @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
* the value or placeholder text: `'before'` or `'after'`
* @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator: 'required'`.
* Note that `false` & setting `indicator: 'required' will result in no indicator shown.
* @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
* @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined` means
* leaving it up to the browser).
* @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
* pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
* (the value must contain only numbers); when RegExp, a regular expression that must match the
* value for it to be considered valid; when Function, a function receiving the value as parameter
* that must return true, or promise resolving to true, for it to be considered valid.
*/
OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
// Configuration initialization
config = $.extend( {
type: 'text',
labelPosition: 'after'
}, config );
// Parent constructor
OO.ui.TextInputWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
OO.ui.mixin.LabelElement.call( this, config );
// Properties
this.type = this.getSaneType( config );
this.readOnly = false;
this.required = false;
this.validate = null;
this.styleHeight = null;
this.scrollWidth = null;
this.setValidation( config.validate );
this.setLabelPosition( config.labelPosition );
// Events
this.$input.on( {
keypress: this.onKeyPress.bind( this ),
blur: this.onBlur.bind( this ),
focus: this.onFocus.bind( this )
} );
this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
this.on( 'labelChange', this.updatePosition.bind( this ) );
this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) );
// Initialization
this.$element
.addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
.append( this.$icon, this.$indicator );
this.setReadOnly( !!config.readOnly );
this.setRequired( !!config.required );
if ( config.placeholder !== undefined ) {
this.$input.attr( 'placeholder', config.placeholder );
}
if ( config.maxLength !== undefined ) {
this.$input.attr( 'maxlength', config.maxLength );
}
if ( config.autofocus ) {
this.$input.attr( 'autofocus', 'autofocus' );
}
if ( config.autocomplete === false ) {
this.$input.attr( 'autocomplete', 'off' );
// Turning off autocompletion also disables "form caching" when the user navigates to a
// different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
$( window ).on( {
beforeunload: function () {
this.$input.removeAttr( 'autocomplete' );
}.bind( this ),
pageshow: function () {
// Browsers don't seem to actually fire this event on "Back", they instead just reload the
// whole page... it shouldn't hurt, though.
this.$input.attr( 'autocomplete', 'off' );
}.bind( this )
} );
}
if ( config.spellcheck !== undefined ) {
this.$input.attr( 'spellcheck', config.spellcheck ? 'true' : 'false' );
}
if ( this.label ) {
this.isWaitingToBeAttached = true;
this.installParentChangeDetector();
}
};
/* Setup */
OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
/* Static Properties */
OO.ui.TextInputWidget.static.validationPatterns = {
'non-empty': /.+/,
integer: /^\d+$/
};
/* Events */
/**
* An `enter` event is emitted when the user presses 'enter' inside the text box.
*
* @event enter
*/
/* Methods */
/**
* Handle icon mouse down events.
*
* @private
* @param {jQuery.Event} e Mouse down event
* @return {undefined/boolean} False to prevent default if event is handled
*/
OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
if ( e.which === OO.ui.MouseButtons.LEFT ) {
this.focus();
return false;
}
};
/**
* Handle indicator mouse down events.
*
* @private
* @param {jQuery.Event} e Mouse down event
* @return {undefined/boolean} False to prevent default if event is handled
*/
OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
if ( e.which === OO.ui.MouseButtons.LEFT ) {
this.focus();
return false;
}
};
/**
* Handle key press events.
*
* @private
* @param {jQuery.Event} e Key press event
* @fires enter If enter key is pressed
*/
OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
if ( e.which === OO.ui.Keys.ENTER ) {
this.emit( 'enter', e );
}
};
/**
* Handle blur events.
*
* @private
* @param {jQuery.Event} e Blur event
*/
OO.ui.TextInputWidget.prototype.onBlur = function () {
this.setValidityFlag();
};
/**
* Handle focus events.
*
* @private
* @param {jQuery.Event} e Focus event
*/
OO.ui.TextInputWidget.prototype.onFocus = function () {
if ( this.isWaitingToBeAttached ) {
// If we've received focus, then we must be attached to the document, and if
// isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
this.onElementAttach();
}
this.setValidityFlag( true );
};
/**
* Handle element attach events.
*
* @private
* @param {jQuery.Event} e Element attach event
*/
OO.ui.TextInputWidget.prototype.onElementAttach = function () {
this.isWaitingToBeAttached = false;
// Any previously calculated size is now probably invalid if we reattached elsewhere
this.valCache = null;
this.positionLabel();
};
/**
* Handle debounced change events.
*
* @param {string} value
* @private
*/
OO.ui.TextInputWidget.prototype.onDebouncedChange = function () {
this.setValidityFlag();
};
/**
* Check if the input is {@link #readOnly read-only}.
*
* @return {boolean}
*/
OO.ui.TextInputWidget.prototype.isReadOnly = function () {
return this.readOnly;
};
/**
* Set the {@link #readOnly read-only} state of the input.
*
* @param {boolean} state Make input read-only
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
this.readOnly = !!state;
this.$input.prop( 'readOnly', this.readOnly );
return this;
};
/**
* Check if the input is {@link #required required}.
*
* @return {boolean}
*/
OO.ui.TextInputWidget.prototype.isRequired = function () {
return this.required;
};
/**
* Set the {@link #required required} state of the input.
*
* @param {boolean} state Make input required
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.TextInputWidget.prototype.setRequired = function ( state ) {
this.required = !!state;
if ( this.required ) {
this.$input
.prop( 'required', true )
.attr( 'aria-required', 'true' );
if ( this.getIndicator() === null ) {
this.setIndicator( 'required' );
}
} else {
this.$input
.prop( 'required', false )
.removeAttr( 'aria-required' );
if ( this.getIndicator() === 'required' ) {
this.setIndicator( null );
}
}
return this;
};
/**
* Support function for making #onElementAttach work across browsers.
*
* This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
* event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
*
* Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
* first time that the element gets attached to the documented.
*/
OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
var mutationObserver, onRemove, topmostNode, fakeParentNode,
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
widget = this;
if ( MutationObserver ) {
// The new way. If only it wasn't so ugly.
if ( this.isElementAttached() ) {
// Widget is attached already, do nothing. This breaks the functionality of this function when
// the widget is detached and reattached. Alas, doing this correctly with MutationObserver
// would require observation of the whole document, which would hurt performance of other,
// more important code.
return;
}
// Find topmost node in the tree
topmostNode = this.$element[ 0 ];
while ( topmostNode.parentNode ) {
topmostNode = topmostNode.parentNode;
}
// We have no way to detect the $element being attached somewhere without observing the entire
// DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
// parent node of $element, and instead detect when $element is removed from it (and thus
// probably attached somewhere else). If there is no parent, we create a "fake" one. If it
// doesn't get attached, we end up back here and create the parent.
mutationObserver = new MutationObserver( function ( mutations ) {
var i, j, removedNodes;
for ( i = 0; i < mutations.length; i++ ) {
removedNodes = mutations[ i ].removedNodes;
for ( j = 0; j < removedNodes.length; j++ ) {
if ( removedNodes[ j ] === topmostNode ) {
setTimeout( onRemove, 0 );
return;
}
}
}
} );
onRemove = function () {
// If the node was attached somewhere else, report it
if ( widget.isElementAttached() ) {
widget.onElementAttach();
}
mutationObserver.disconnect();
widget.installParentChangeDetector();
};
// Create a fake parent and observe it
fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
mutationObserver.observe( fakeParentNode, { childList: true } );
} else {
// Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
// detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
}
};
/**
* @inheritdoc
* @protected
*/
OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
if ( this.getSaneType( config ) === 'number' ) {
return $( '<input>' )
.attr( 'step', 'any' )
.attr( 'type', 'number' );
} else {
return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
}
};
/**
* Get sanitized value for 'type' for given config.
*
* @param {Object} config Configuration options
* @return {string|null}
* @protected
*/
OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
var allowedTypes = [
'text',
'password',
'email',
'url',
'number'
];
return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
};
/**
* Focus the input and select a specified range within the text.
*
* @param {number} from Select from offset
* @param {number} [to] Select to offset, defaults to from
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
var isBackwards, start, end,
input = this.$input[ 0 ];
to = to || from;
isBackwards = to < from;
start = isBackwards ? to : from;
end = isBackwards ? from : to;
this.focus();
try {
input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
} catch ( e ) {
// IE throws an exception if you call setSelectionRange on a unattached DOM node.
// Rather than expensively check if the input is attached every time, just check
// if it was the cause of an error being thrown. If not, rethrow the error.
if ( this.getElementDocument().body.contains( input ) ) {
throw e;
}
}
return this;
};
/**
* Get an object describing the current selection range in a directional manner
*
* @return {Object} Object containing 'from' and 'to' offsets
*/
OO.ui.TextInputWidget.prototype.getRange = function () {
var input = this.$input[ 0 ],
start = input.selectionStart,
end = input.selectionEnd,
isBackwards = input.selectionDirection === 'backward';
return {
from: isBackwards ? end : start,
to: isBackwards ? start : end
};
};
/**
* Get the length of the text input value.
*
* This could differ from the length of #getValue if the
* value gets filtered
*
* @return {number} Input length
*/
OO.ui.TextInputWidget.prototype.getInputLength = function () {
return this.$input[ 0 ].value.length;
};
/**
* Focus the input and select the entire text.
*
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.TextInputWidget.prototype.select = function () {
return this.selectRange( 0, this.getInputLength() );
};
/**
* Focus the input and move the cursor to the start.
*
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
return this.selectRange( 0 );
};
/**
* Focus the input and move the cursor to the end.
*
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
return this.selectRange( this.getInputLength() );
};
/**
* Insert new content into the input.
*
* @param {string} content Content to be inserted
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
var start, end,
range = this.getRange(),
value = this.getValue();
start = Math.min( range.from, range.to );
end = Math.max( range.from, range.to );
this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
this.selectRange( start + content.length );
return this;
};
/**
* Insert new content either side of a selection.
*
* @param {string} pre Content to be inserted before the selection
* @param {string} post Content to be inserted after the selection
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
var start, end,
range = this.getRange(),
offset = pre.length;
start = Math.min( range.from, range.to );
end = Math.max( range.from, range.to );
this.selectRange( start ).insertContent( pre );
this.selectRange( offset + end ).insertContent( post );
this.selectRange( offset + start, offset + end );
return this;
};
/**
* Set the validation pattern.
*
* The validation pattern is either a regular expression, a function, or the symbolic name of a
* pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
* value must contain only numbers).
*
* @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
* of a pattern (either โintegerโ or โnon-emptyโ) defined by the class.
*/
OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
if ( validate instanceof RegExp || validate instanceof Function ) {
this.validate = validate;
} else {
this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
}
};
/**
* Sets the 'invalid' flag appropriately.
*
* @param {boolean} [isValid] Optionally override validation result
*/
OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
var widget = this,
setFlag = function ( valid ) {
if ( !valid ) {
widget.$input.attr( 'aria-invalid', 'true' );
} else {
widget.$input.removeAttr( 'aria-invalid' );
}
widget.setFlags( { invalid: !valid } );
};
if ( isValid !== undefined ) {
setFlag( isValid );
} else {
this.getValidity().then( function () {
setFlag( true );
}, function () {
setFlag( false );
} );
}
};
/**
* Get the validity of current value.
*
* This method returns a promise that resolves if the value is valid and rejects if
* it isn't. Uses the {@link #validate validation pattern} to check for validity.
*
* @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
*/
OO.ui.TextInputWidget.prototype.getValidity = function () {
var result;
function rejectOrResolve( valid ) {
if ( valid ) {
return $.Deferred().resolve().promise();
} else {
return $.Deferred().reject().promise();
}
}
// Check browser validity and reject if it is invalid
if (
this.$input[ 0 ].checkValidity !== undefined &&
this.$input[ 0 ].checkValidity() === false
) {
return rejectOrResolve( false );
}
// Run our checks if the browser thinks the field is valid
if ( this.validate instanceof Function ) {
result = this.validate( this.getValue() );
if ( result && typeof result.promise === 'function' ) {
return result.promise().then( function ( valid ) {
return rejectOrResolve( valid );
} );
} else {
return rejectOrResolve( result );
}
} else {
return rejectOrResolve( this.getValue().match( this.validate ) );
}
};
/**
* Set the position of the inline label relative to that of the value: `โbeforeโ` or `โafterโ`.
*
* @param {string} labelPosition Label position, 'before' or 'after'
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
this.labelPosition = labelPosition;
if ( this.label ) {
// If there is no label and we only change the position, #updatePosition is a no-op,
// but it takes really a lot of work to do nothing.
this.updatePosition();
}
return this;
};
/**
* Update the position of the inline label.
*
* This method is called by #setLabelPosition, and can also be called on its own if
* something causes the label to be mispositioned.
*
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.TextInputWidget.prototype.updatePosition = function () {
var after = this.labelPosition === 'after';
this.$element
.toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
.toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
this.valCache = null;
this.scrollWidth = null;
this.positionLabel();
return this;
};
/**
* Position the label by setting the correct padding on the input.
*
* @private
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.TextInputWidget.prototype.positionLabel = function () {
var after, rtl, property, newCss;
if ( this.isWaitingToBeAttached ) {
// #onElementAttach will be called soon, which calls this method
return this;
}
newCss = {
'padding-right': '',
'padding-left': ''
};
if ( this.label ) {
this.$element.append( this.$label );
} else {
this.$label.detach();
// Clear old values if present
this.$input.css( newCss );
return;
}
after = this.labelPosition === 'after';
rtl = this.$element.css( 'direction' ) === 'rtl';
property = after === rtl ? 'padding-left' : 'padding-right';
newCss[ property ] = this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 );
// We have to clear the padding on the other side, in case the element direction changed
this.$input.css( newCss );
return this;
};
/**
* @class
* @extends OO.ui.TextInputWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) {
config = $.extend( {
icon: 'search'
}, config );
// Parent constructor
OO.ui.SearchInputWidget.parent.call( this, config );
// Events
this.connect( this, {
change: 'onChange'
} );
// Initialization
this.updateSearchIndicator();
this.connect( this, {
disable: 'onDisable'
} );
};
/* Setup */
OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget );
/* Methods */
/**
* @inheritdoc
* @protected
*/
OO.ui.SearchInputWidget.prototype.getSaneType = function () {
return 'search';
};
/**
* @inheritdoc
*/
OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
if ( e.which === OO.ui.MouseButtons.LEFT ) {
// Clear the text field
this.setValue( '' );
this.focus();
return false;
}
};
/**
* Update the 'clear' indicator displayed on type: 'search' text
* fields, hiding it when the field is already empty or when it's not
* editable.
*/
OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () {
if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
this.setIndicator( null );
} else {
this.setIndicator( 'clear' );
}
};
/**
* Handle change events.
*
* @private
*/
OO.ui.SearchInputWidget.prototype.onChange = function () {
this.updateSearchIndicator();
};
/**
* Handle disable events.
*
* @param {boolean} disabled Element is disabled
* @private
*/
OO.ui.SearchInputWidget.prototype.onDisable = function () {
this.updateSearchIndicator();
};
/**
* @inheritdoc
*/
OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) {
OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state );
this.updateSearchIndicator();
return this;
};
/**
* @class
* @extends OO.ui.TextInputWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
* specifies minimum number of rows to display.
* @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
* Use the #maxRows config to specify a maximum number of displayed rows.
* @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
* Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
*/
OO.ui.MultilineTextInputWidget = function OoUiMultilineTextInputWidget( config ) {
config = $.extend( {
type: 'text'
}, config );
// Parent constructor
OO.ui.MultilineTextInputWidget.parent.call( this, config );
// Properties
this.autosize = !!config.autosize;
this.minRows = config.rows !== undefined ? config.rows : '';
this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
// Clone for resizing
if ( this.autosize ) {
this.$clone = this.$input
.clone()
.removeAttr( 'id' )
.removeAttr( 'name' )
.insertAfter( this.$input )
.attr( 'aria-hidden', 'true' )
.addClass( 'oo-ui-element-hidden' );
}
// Events
this.connect( this, {
change: 'onChange'
} );
// Initialization
if ( config.rows ) {
this.$input.attr( 'rows', config.rows );
}
if ( this.autosize ) {
this.$input.addClass( 'oo-ui-textInputWidget-autosized' );
this.isWaitingToBeAttached = true;
this.installParentChangeDetector();
}
};
/* Setup */
OO.inheritClass( OO.ui.MultilineTextInputWidget, OO.ui.TextInputWidget );
/* Static Methods */
/**
* @inheritdoc
*/
OO.ui.MultilineTextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
var state = OO.ui.MultilineTextInputWidget.parent.static.gatherPreInfuseState( node, config );
state.scrollTop = config.$input.scrollTop();
return state;
};
/* Methods */
/**
* @inheritdoc
*/
OO.ui.MultilineTextInputWidget.prototype.onElementAttach = function () {
OO.ui.MultilineTextInputWidget.parent.prototype.onElementAttach.call( this );
this.adjustSize();
};
/**
* Handle change events.
*
* @private
*/
OO.ui.MultilineTextInputWidget.prototype.onChange = function () {
this.adjustSize();
};
/**
* @inheritdoc
*/
OO.ui.MultilineTextInputWidget.prototype.updatePosition = function () {
OO.ui.MultilineTextInputWidget.parent.prototype.updatePosition.call( this );
this.adjustSize();
};
/**
* @inheritdoc
*
* Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
*/
OO.ui.MultilineTextInputWidget.prototype.onKeyPress = function ( e ) {
if (
( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) ||
// Some platforms emit keycode 10 for ctrl+enter in a textarea
e.which === 10
) {
this.emit( 'enter', e );
}
};
/**
* Automatically adjust the size of the text input.
*
* This only affects multiline inputs that are {@link #autosize autosized}.
*
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
* @fires resize
*/
OO.ui.MultilineTextInputWidget.prototype.adjustSize = function () {
var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
idealHeight, newHeight, scrollWidth, property;
if ( this.$input.val() !== this.valCache ) {
if ( this.autosize ) {
this.$clone
.val( this.$input.val() )
.attr( 'rows', this.minRows )
// Set inline height property to 0 to measure scroll height
.css( 'height', 0 );
this.$clone.removeClass( 'oo-ui-element-hidden' );
this.valCache = this.$input.val();
scrollHeight = this.$clone[ 0 ].scrollHeight;
// Remove inline height property to measure natural heights
this.$clone.css( 'height', '' );
innerHeight = this.$clone.innerHeight();
outerHeight = this.$clone.outerHeight();
// Measure max rows height
this.$clone
.attr( 'rows', this.maxRows )
.css( 'height', 'auto' )
.val( '' );
maxInnerHeight = this.$clone.innerHeight();
// Difference between reported innerHeight and scrollHeight with no scrollbars present.
// This is sometimes non-zero on Blink-based browsers, depending on zoom level.
measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
this.$clone.addClass( 'oo-ui-element-hidden' );
// Only apply inline height when expansion beyond natural height is needed
// Use the difference between the inner and outer height as a buffer
newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
if ( newHeight !== this.styleHeight ) {
this.$input.css( 'height', newHeight );
this.styleHeight = newHeight;
this.emit( 'resize' );
}
}
scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
if ( scrollWidth !== this.scrollWidth ) {
property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
// Reset
this.$label.css( { right: '', left: '' } );
this.$indicator.css( { right: '', left: '' } );
if ( scrollWidth ) {
this.$indicator.css( property, scrollWidth );
if ( this.labelPosition === 'after' ) {
this.$label.css( property, scrollWidth );
}
}
this.scrollWidth = scrollWidth;
this.positionLabel();
}
}
return this;
};
/**
* @inheritdoc
* @protected
*/
OO.ui.MultilineTextInputWidget.prototype.getInputElement = function () {
return $( '<textarea>' );
};
/**
* Check if the input automatically adjusts its size.
*
* @return {boolean}
*/
OO.ui.MultilineTextInputWidget.prototype.isAutosizing = function () {
return !!this.autosize;
};
/**
* @inheritdoc
*/
OO.ui.MultilineTextInputWidget.prototype.restorePreInfuseState = function ( state ) {
OO.ui.MultilineTextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
if ( state.scrollTop !== undefined ) {
this.$input.scrollTop( state.scrollTop );
}
};
/**
* ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
* can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
* a value can be chosen instead). Users can choose options from the combo box in one of two ways:
*
* - by typing a value in the text input field. If the value exactly matches the value of a menu
* option, that option will appear to be selected.
* - by choosing a value from the menu. The value of the chosen option will then appear in the text
* input field.
*
* After the user chooses an option, its `data` will be used as a new value for the widget.
* A `label` also can be specified for each option: if given, it will be shown instead of the
* `data` in the dropdown menu.
*
* This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
*
* For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
*
* @example
* // Example: A ComboBoxInputWidget.
* var comboBox = new OO.ui.ComboBoxInputWidget( {
* value: 'Option 1',
* options: [
* { data: 'Option 1' },
* { data: 'Option 2' },
* { data: 'Option 3' }
* ]
* } );
* $( 'body' ).append( comboBox.$element );
*
* @example
* // Example: A ComboBoxInputWidget with additional option labels.
* var comboBox = new OO.ui.ComboBoxInputWidget( {
* value: 'Option 1',
* options: [
* {
* data: 'Option 1',
* label: 'Option One'
* },
* {
* data: 'Option 2',
* label: 'Option Two'
* },
* {
* data: 'Option 3',
* label: 'Option Three'
* }
* ]
* } );
* $( 'body' ).append( comboBox.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
*
* @class
* @extends OO.ui.TextInputWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: โฆ, label: โฆ }`
* @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
* @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
* the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
* containing `<div>` and has a larger area. By default, the menu uses relative positioning.
* See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
*/
OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
// Configuration initialization
config = $.extend( {
autocomplete: false
}, config );
// ComboBoxInputWidget shouldn't support `multiline`
config.multiline = false;
// See InputWidget#reusePreInfuseDOM about `config.$input`
if ( config.$input ) {
config.$input.removeAttr( 'list' );
}
// Parent constructor
OO.ui.ComboBoxInputWidget.parent.call( this, config );
// Properties
this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
this.dropdownButton = new OO.ui.ButtonWidget( {
classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
indicator: 'down',
disabled: this.disabled
} );
this.menu = new OO.ui.MenuSelectWidget( $.extend(
{
widget: this,
input: this,
$floatableContainer: this.$element,
disabled: this.isDisabled()
},
config.menu
) );
// Events
this.connect( this, {
change: 'onInputChange',
enter: 'onInputEnter'
} );
this.dropdownButton.connect( this, {
click: 'onDropdownButtonClick'
} );
this.menu.connect( this, {
choose: 'onMenuChoose',
add: 'onMenuItemsChange',
remove: 'onMenuItemsChange',
toggle: 'onMenuToggle'
} );
// Initialization
this.$input.attr( {
role: 'combobox',
'aria-owns': this.menu.getElementId(),
'aria-autocomplete': 'list'
} );
// Do not override options set via config.menu.items
if ( config.options !== undefined ) {
this.setOptions( config.options );
}
this.$field = $( '<div>' )
.addClass( 'oo-ui-comboBoxInputWidget-field' )
.append( this.$input, this.dropdownButton.$element );
this.$element
.addClass( 'oo-ui-comboBoxInputWidget' )
.append( this.$field );
this.$overlay.append( this.menu.$element );
this.onMenuItemsChange();
};
/* Setup */
OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
/* Methods */
/**
* Get the combobox's menu.
*
* @return {OO.ui.MenuSelectWidget} Menu widget
*/
OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
return this.menu;
};
/**
* Get the combobox's text input widget.
*
* @return {OO.ui.TextInputWidget} Text input widget
*/
OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
return this;
};
/**
* Handle input change events.
*
* @private
* @param {string} value New value
*/
OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
var match = this.menu.findItemFromData( value );
this.menu.selectItem( match );
if ( this.menu.findHighlightedItem() ) {
this.menu.highlightItem( match );
}
if ( !this.isDisabled() ) {
this.menu.toggle( true );
}
};
/**
* Handle input enter events.
*
* @private
*/
OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
if ( !this.isDisabled() ) {
this.menu.toggle( false );
}
};
/**
* Handle button click events.
*
* @private
*/
OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () {
this.menu.toggle();
this.focus();
};
/**
* Handle menu choose events.
*
* @private
* @param {OO.ui.OptionWidget} item Chosen item
*/
OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
this.setValue( item.getData() );
};
/**
* Handle menu item change events.
*
* @private
*/
OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
var match = this.menu.findItemFromData( this.getValue() );
this.menu.selectItem( match );
if ( this.menu.findHighlightedItem() ) {
this.menu.highlightItem( match );
}
this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
};
/**
* Handle menu toggle events.
*
* @private
* @param {boolean} isVisible Open state of the menu
*/
OO.ui.ComboBoxInputWidget.prototype.onMenuToggle = function ( isVisible ) {
this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible );
};
/**
* @inheritdoc
*/
OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
// Parent method
OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
if ( this.dropdownButton ) {
this.dropdownButton.setDisabled( this.isDisabled() );
}
if ( this.menu ) {
this.menu.setDisabled( this.isDisabled() );
}
return this;
};
/**
* Set the options available for this input.
*
* @param {Object[]} options Array of menu options in the format `{ data: โฆ, label: โฆ }`
* @chainable
* @return {OO.ui.Widget} The widget, for chaining
*/
OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
this.getMenu()
.clearItems()
.addItems( options.map( function ( opt ) {
return new OO.ui.MenuOptionWidget( {
data: opt.data,
label: opt.label !== undefined ? opt.label : opt.data
} );
} ) );
return this;
};
/**
* FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
* which is a widget that is specified by reference before any optional configuration settings.
*
* Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
*
* - **left**: The label is placed before the field-widget and aligned with the left margin.
* A left-alignment is used for forms with many fields.
* - **right**: The label is placed before the field-widget and aligned to the right margin.
* A right-alignment is used for long but familiar forms which users tab through,
* verifying the current field with a quick glance at the label.
* - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
* that users fill out from top to bottom.
* - **inline**: The label is placed after the field-widget and aligned to the left.
* An inline-alignment is best used with checkboxes or radio buttons.
*
* Help text can either be:
*
* - accessed via a help icon that appears in the upper right corner of the rendered field layout, or
* - shown as a subtle explanation below the label.
*
* If the help text is brief, or is essential to always expose it, set `helpInline` to `true`. If it
* is long or not essential, leave `helpInline` to its default, `false`.
*
* Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
*
* @class
* @extends OO.ui.Layout
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.TitledElement
*
* @constructor
* @param {OO.ui.Widget} fieldWidget Field widget
* @param {Object} [config] Configuration options
* @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
* or 'inline'
* @cfg {Array} [errors] Error messages about the widget, which will be
* displayed below the widget.
* The array may contain strings or OO.ui.HtmlSnippet instances.
* @cfg {Array} [notices] Notices about the widget, which will be displayed
* below the widget.
* The array may contain strings or OO.ui.HtmlSnippet instances.
* These are more visible than `help` messages when `helpInline` is set, and so
* might be good for transient messages.
* @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
* and `helpInline` is `false`, a "help" icon will appear in the upper-right
* corner of the rendered field; clicking it will display the text in a popup.
* If `helpInline` is `true`, then a subtle description will be shown after the
* label.
* @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
* or shown when the "help" icon is clicked.
* @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
* `help` is given.
* See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
*
* @throws {Error} An error is thrown if no widget is specified
*/
OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
config = fieldWidget;
fieldWidget = config.fieldWidget;
}
// Make sure we have required constructor arguments
if ( fieldWidget === undefined ) {
throw new Error( 'Widget not found' );
}
// Configuration initialization
config = $.extend( { align: 'left', helpInline: false }, config );
// Parent constructor
OO.ui.FieldLayout.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, {
$label: $( '<label>' )
} ) );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
// Properties
this.fieldWidget = fieldWidget;
this.errors = [];
this.notices = [];
this.$field = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
this.$messages = $( '<ul>' );
this.$header = $( '<span>' );
this.$body = $( '<div>' );
this.align = null;
this.helpInline = config.helpInline;
// Events
this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
// Initialization
this.$help = config.help ?
this.createHelpElement( config.help, config.$overlay ) :
$( [] );
if ( this.fieldWidget.getInputId() ) {
this.$label.attr( 'for', this.fieldWidget.getInputId() );
if ( this.helpInline ) {
this.$help.attr( 'for', this.fieldWidget.getInputId() );
}
} else {
this.$label.on( 'click', function () {
this.fieldWidget.simulateLabelClick();
}.bind( this ) );
if ( this.helpInline ) {
this.$help.on( 'click', function () {
this.fieldWidget.simulateLabelClick();
}.bind( this ) );
}
}
this.$element
.addClass( 'oo-ui-fieldLayout' )
.toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() )
.append( this.$body );
this.$body.addClass( 'oo-ui-fieldLayout-body' );
this.$header.addClass( 'oo-ui-fieldLayout-header' );
this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
this.$field
.addClass( 'oo-ui-fieldLayout-field' )
.append( this.fieldWidget.$element );
this.setErrors( config.errors || [] );
this.setNotices( config.notices || [] );
this.setAlignment( config.align );
// Call this again to take into account the widget's accessKey
this.updateTitle();
};
/* Setup */
OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
/* Methods */
/**
* Handle field disable events.
*
* @private
* @param {boolean} value Field is disabled
*/
OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
};
/**
* Get the widget contained by the field.
*
* @return {OO.ui.Widget} Field widget
*/
OO.ui.FieldLayout.prototype.getField = function () {
return this.fieldWidget;
};
/**
* Return `true` if the given field widget can be used with `'inline'` alignment (see
* #setAlignment). Return `false` if it can't or if this can't be determined.
*
* @return {boolean}
*/
OO.ui.FieldLayout.prototype.isFieldInline = function () {
// This is very simplistic, but should be good enough.
return this.getField().$element.prop( 'tagName' ).toLowerCase() === 'span';
};
/**
* @protected
* @param {string} kind 'error' or 'notice'
* @param {string|OO.ui.HtmlSnippet} text
* @return {jQuery}
*/
OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
var $listItem, $icon, message;
$listItem = $( '<li>' );
if ( kind === 'error' ) {
$icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
$listItem.attr( 'role', 'alert' );
} else if ( kind === 'notice' ) {
$icon = new OO.ui.IconWidget( { icon: 'notice' } ).$element;
} else {
$icon = '';
}
message = new OO.ui.LabelWidget( { label: text } );
$listItem
.append( $icon, message.$element )
.addClass( 'oo-ui-fieldLayout-messages-' + kind );
return $listItem;
};
/**
* Set the field alignment mode.
*
* @private
* @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
* @chainable
* @return {OO.ui.BookletLayout} The layout, for chaining
*/
OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
if ( value !== this.align ) {
// Default to 'left'
if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
value = 'left';
}
// Validate
if ( value === 'inline' && !this.isFieldInline() ) {
value = 'top';
}
// Reorder elements
if ( this.helpInline ) {
if ( value === 'top' ) {
this.$header.append( this.$label );
this.$body.append( this.$header, this.$field, this.$help );
} else if ( value === 'inline' ) {
this.$header.append( this.$label, this.$help );
this.$body.append( this.$field, this.$header );
} else {
this.$header.append( this.$label, this.$help );
this.$body.append( this.$header, this.$field );
}
} else {
if ( value === 'top' ) {
this.$header.append( this.$help, this.$label );
this.$body.append( this.$header, this.$field );
} else if ( value === 'inline' ) {
this.$header.append( this.$help, this.$label );
this.$body.append( this.$field, this.$header );
} else {
this.$header.append( this.$label );
this.$body.append( this.$header, this.$help, this.$field );
}
}
// Set classes. The following classes can be used here:
// * oo-ui-fieldLayout-align-left
// * oo-ui-fieldLayout-align-right
// * oo-ui-fieldLayout-align-top
// * oo-ui-fieldLayout-align-inline
if ( this.align ) {
this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
}
this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
this.align = value;
}
return this;
};
/**
* Set the list of error messages.
*
* @param {Array} errors Error messages about the widget, which will be displayed below the widget.
* The array may contain strings or OO.ui.HtmlSnippet instances.
* @chainable
* @return {OO.ui.BookletLayout} The layout, for chaining
*/
OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
this.errors = errors.slice();
this.updateMessages();
return this;
};
/**
* Set the list of notice messages.
*
* @param {Array} notices Notices about the widget, which will be displayed below the widget.
* The array may contain strings or OO.ui.HtmlSnippet instances.
* @chainable
* @return {OO.ui.BookletLayout} The layout, for chaining
*/
OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
this.notices = notices.slice();
this.updateMessages();
return this;
};
/**
* Update the rendering of error and notice messages.
*
* @private
*/
OO.ui.FieldLayout.prototype.updateMessages = function () {
var i;
this.$messages.empty();
if ( this.errors.length || this.notices.length ) {
this.$body.after( this.$messages );
} else {
this.$messages.remove();
return;
}
for ( i = 0; i < this.notices.length; i++ ) {
this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
}
for ( i = 0; i < this.errors.length; i++ ) {
this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
}
};
/**
* Include information about the widget's accessKey in our title. TitledElement calls this method.
* (This is a bit of a hack.)
*
* @protected
* @param {string} title Tooltip label for 'title' attribute
* @return {string}
*/
OO.ui.FieldLayout.prototype.formatTitleWithAccessKey = function ( title ) {
if ( this.fieldWidget && this.fieldWidget.formatTitleWithAccessKey ) {
return this.fieldWidget.formatTitleWithAccessKey( title );
}
return title;
};
/**
* Creates and returns the help element. Also sets the `aria-describedby`
* attribute on the main element of the `fieldWidget`.
*
* @private
* @param {string|OO.ui.HtmlSnippet} [help] Help text.
* @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
* @return {jQuery} The element that should become `this.$help`.
*/
OO.ui.FieldLayout.prototype.createHelpElement = function ( help, $overlay ) {
var helpId, helpWidget;
if ( this.helpInline ) {
helpWidget = new OO.ui.LabelWidget( {
label: help,
classes: [ 'oo-ui-inline-help' ]
} );
helpId = helpWidget.getElementId();
} else {
helpWidget = new OO.ui.PopupButtonWidget( {
$overlay: $overlay,
popup: {
padded: true
},
classes: [ 'oo-ui-fieldLayout-help' ],
framed: false,
icon: 'info',
label: OO.ui.msg( 'ooui-field-help' ),
invisibleLabel: true
} );
if ( help instanceof OO.ui.HtmlSnippet ) {
helpWidget.getPopup().$body.html( help.toString() );
} else {
helpWidget.getPopup().$body.text( help );
}
helpId = helpWidget.getPopup().getBodyId();
}
// Set the 'aria-describedby' attribute on the fieldWidget
// Preference given to an input or a button
(
this.fieldWidget.$input ||
this.fieldWidget.$button ||
this.fieldWidget.$element
).attr( 'aria-describedby', helpId );
return helpWidget.$element;
};
/**
* ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
* and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
* is required and is specified before any optional configuration settings.
*
* Labels can be aligned in one of four ways:
*
* - **left**: The label is placed before the field-widget and aligned with the left margin.
* A left-alignment is used for forms with many fields.
* - **right**: The label is placed before the field-widget and aligned to the right margin.
* A right-alignment is used for long but familiar forms which users tab through,
* verifying the current field with a quick glance at the label.
* - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
* that users fill out from top to bottom.
* - **inline**: The label is placed after the field-widget and aligned to the left.
* An inline-alignment is best used with checkboxes or radio buttons.
*
* Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
* text is specified.
*
* @example
* // Example of an ActionFieldLayout
* var actionFieldLayout = new OO.ui.ActionFieldLayout(
* new OO.ui.TextInputWidget( {
* placeholder: 'Field widget'
* } ),
* new OO.ui.ButtonWidget( {
* label: 'Button'
* } ),
* {
* label: 'An ActionFieldLayout. This label is aligned top',
* align: 'top',
* help: 'This is help text'
* }
* );
*
* $( 'body' ).append( actionFieldLayout.$element );
*
* @class
* @extends OO.ui.FieldLayout
*
* @constructor
* @param {OO.ui.Widget} fieldWidget Field widget
* @param {OO.ui.ButtonWidget} buttonWidget Button widget
* @param {Object} config
*/
OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
config = fieldWidget;
fieldWidget = config.fieldWidget;
buttonWidget = config.buttonWidget;
}
// Parent constructor
OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
// Properties
this.buttonWidget = buttonWidget;
this.$button = $( '<span>' );
this.$input = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
// Initialization
this.$element
.addClass( 'oo-ui-actionFieldLayout' );
this.$button
.addClass( 'oo-ui-actionFieldLayout-button' )
.append( this.buttonWidget.$element );
this.$input
.addClass( 'oo-ui-actionFieldLayout-input' )
.append( this.fieldWidget.$element );
this.$field
.append( this.$input, this.$button );
};
/* Setup */
OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
/**
* FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
* which each contain an individual widget and, optionally, a label. Each Fieldset can be
* configured with a label as well. For more information and examples,
* please see the [OOUI documentation on MediaWiki][1].
*
* @example
* // Example of a fieldset layout
* var input1 = new OO.ui.TextInputWidget( {
* placeholder: 'A text input field'
* } );
*
* var input2 = new OO.ui.TextInputWidget( {
* placeholder: 'A text input field'
* } );
*
* var fieldset = new OO.ui.FieldsetLayout( {
* label: 'Example of a fieldset layout'
* } );
*
* fieldset.addItems( [
* new OO.ui.FieldLayout( input1, {
* label: 'Field One'
* } ),
* new OO.ui.FieldLayout( input2, {
* label: 'Field Two'
* } )
* ] );
* $( 'body' ).append( fieldset.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
*
* @class
* @extends OO.ui.Layout
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
* @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
* in the upper-right corner of the rendered field; clicking it will display the text in a popup.
* For important messages, you are advised to use `notices`, as they are always shown.
* @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
* See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
*/
OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.FieldsetLayout.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.GroupElement.call( this, config );
// Properties
this.$header = $( '<legend>' );
if ( config.help ) {
this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
$overlay: config.$overlay,
popup: {
padded: true
},
classes: [ 'oo-ui-fieldsetLayout-help' ],
framed: false,
icon: 'info',
label: OO.ui.msg( 'ooui-field-help' ),
invisibleLabel: true
} );
if ( config.help instanceof OO.ui.HtmlSnippet ) {
this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
} else {
this.popupButtonWidget.getPopup().$body.text( config.help );
}
this.$help = this.popupButtonWidget.$element;
} else {
this.$help = $( [] );
}
// Initialization
this.$header
.addClass( 'oo-ui-fieldsetLayout-header' )
.append( this.$icon, this.$label, this.$help );
this.$group.addClass( 'oo-ui-fieldsetLayout-group' );
this.$element
.addClass( 'oo-ui-fieldsetLayout' )
.prepend( this.$header, this.$group );
if ( Array.isArray( config.items ) ) {
this.addItems( config.items );
}
};
/* Setup */
OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.FieldsetLayout.static.tagName = 'fieldset';
/**
* FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
* form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
* HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
* See the [OOUI documentation on MediaWiki] [1] for more information and examples.
*
* Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
* includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
* OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
* some fancier controls. Some controls have both regular and InputWidget variants, for example
* OO.ui.DropdownWidget and OO.ui.DropdownInputWidget โ only the latter support form submission and
* often have simplified APIs to match the capabilities of HTML forms.
* See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
* [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
*
* @example
* // Example of a form layout that wraps a fieldset layout
* var input1 = new OO.ui.TextInputWidget( {
* placeholder: 'Username'
* } );
* var input2 = new OO.ui.TextInputWidget( {
* placeholder: 'Password',
* type: 'password'
* } );
* var submit = new OO.ui.ButtonInputWidget( {
* label: 'Submit'
* } );
*
* var fieldset = new OO.ui.FieldsetLayout( {
* label: 'A form layout'
* } );
* fieldset.addItems( [
* new OO.ui.FieldLayout( input1, {
* label: 'Username',
* align: 'top'
* } ),
* new OO.ui.FieldLayout( input2, {
* label: 'Password',
* align: 'top'
* } ),
* new OO.ui.FieldLayout( submit )
* ] );
* var form = new OO.ui.FormLayout( {
* items: [ fieldset ],
* action: '/api/formhandler',
* method: 'get'
* } )
* $( 'body' ).append( form.$element );
*
* @class
* @extends OO.ui.Layout
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [method] HTML form `method` attribute
* @cfg {string} [action] HTML form `action` attribute
* @cfg {string} [enctype] HTML form `enctype` attribute
* @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
*/
OO.ui.FormLayout = function OoUiFormLayout( config ) {
var action;
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.FormLayout.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
// Events
this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
// Make sure the action is safe
action = config.action;
if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
action = './' + action;
}
// Initialization
this.$element
.addClass( 'oo-ui-formLayout' )
.attr( {
method: config.method,
action: action,
enctype: config.enctype
} );
if ( Array.isArray( config.items ) ) {
this.addItems( config.items );
}
};
/* Setup */
OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
/* Events */
/**
* A 'submit' event is emitted when the form is submitted.
*
* @event submit
*/
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.FormLayout.static.tagName = 'form';
/* Methods */
/**
* Handle form submit events.
*
* @private
* @param {jQuery.Event} e Submit event
* @fires submit
* @return {OO.ui.FormLayout} The layout, for chaining
*/
OO.ui.FormLayout.prototype.onFormSubmit = function () {
if ( this.emit( 'submit' ) ) {
return false;
}
};
/**
* PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
* and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
*
* @example
* // Example of a panel layout
* var panel = new OO.ui.PanelLayout( {
* expanded: false,
* framed: true,
* padded: true,
* $content: $( '<p>A panel layout with padding and a frame.</p>' )
* } );
* $( 'body' ).append( panel.$element );
*
* @class
* @extends OO.ui.Layout
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [scrollable=false] Allow vertical scrolling
* @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
* @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
* @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
*/
OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
// Configuration initialization
config = $.extend( {
scrollable: false,
padded: false,
expanded: true,
framed: false
}, config );
// Parent constructor
OO.ui.PanelLayout.parent.call( this, config );
// Initialization
this.$element.addClass( 'oo-ui-panelLayout' );
if ( config.scrollable ) {
this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
}
if ( config.padded ) {
this.$element.addClass( 'oo-ui-panelLayout-padded' );
}
if ( config.expanded ) {
this.$element.addClass( 'oo-ui-panelLayout-expanded' );
}
if ( config.framed ) {
this.$element.addClass( 'oo-ui-panelLayout-framed' );
}
};
/* Setup */
OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
/* Methods */
/**
* Focus the panel layout
*
* The default implementation just focuses the first focusable element in the panel
*/
OO.ui.PanelLayout.prototype.focus = function () {
OO.ui.findFocusable( this.$element ).focus();
};
/**
* HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
* items), with small margins between them. Convenient when you need to put a number of block-level
* widgets on a single line next to each other.
*
* Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
*
* @example
* // HorizontalLayout with a text input and a label
* var layout = new OO.ui.HorizontalLayout( {
* items: [
* new OO.ui.LabelWidget( { label: 'Label' } ),
* new OO.ui.TextInputWidget( { value: 'Text' } )
* ]
* } );
* $( 'body' ).append( layout.$element );
*
* @class
* @extends OO.ui.Layout
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
*/
OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.HorizontalLayout.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
// Initialization
this.$element.addClass( 'oo-ui-horizontalLayout' );
if ( Array.isArray( config.items ) ) {
this.addItems( config.items );
}
};
/* Setup */
OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
/**
* NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
* can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
* (to adjust the value in increments) to allow the user to enter a number.
*
* @example
* // Example: A NumberInputWidget.
* var numberInput = new OO.ui.NumberInputWidget( {
* label: 'NumberInputWidget',
* input: { value: 5 },
* min: 1,
* max: 10
* } );
* $( 'body' ).append( numberInput.$element );
*
* @class
* @extends OO.ui.TextInputWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {Object} [minusButton] Configuration options to pass to the
* {@link OO.ui.ButtonWidget decrementing button widget}.
* @cfg {Object} [plusButton] Configuration options to pass to the
* {@link OO.ui.ButtonWidget incrementing button widget}.
* @cfg {number} [min=-Infinity] Minimum allowed value
* @cfg {number} [max=Infinity] Maximum allowed value
* @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
* @cfg {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
* Defaults to `step` if specified, otherwise `1`.
* @cfg {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
* Defaults to 10 times `buttonStep`.
* @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
*/
OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
var $field = $( '<div>' )
.addClass( 'oo-ui-numberInputWidget-field' );
// Configuration initialization
config = $.extend( {
min: -Infinity,
max: Infinity,
showButtons: true
}, config );
// For backward compatibility
$.extend( config, config.input );
this.input = this;
// Parent constructor
OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
type: 'number'
} ) );
if ( config.showButtons ) {
this.minusButton = new OO.ui.ButtonWidget( $.extend(
{
disabled: this.isDisabled(),
tabIndex: -1,
classes: [ 'oo-ui-numberInputWidget-minusButton' ],
icon: 'subtract'
},
config.minusButton
) );
this.minusButton.$element.attr( 'aria-hidden', 'true' );
this.plusButton = new OO.ui.ButtonWidget( $.extend(
{
disabled: this.isDisabled(),
tabIndex: -1,
classes: [ 'oo-ui-numberInputWidget-plusButton' ],
icon: 'add'
},
config.plusButton
) );
this.plusButton.$element.attr( 'aria-hidden', 'true' );
}
// Events
this.$input.on( {
keydown: this.onKeyDown.bind( this ),
'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
} );
if ( config.showButtons ) {
this.plusButton.connect( this, {
click: [ 'onButtonClick', +1 ]
} );
this.minusButton.connect( this, {
click: [ 'onButtonClick', -1 ]
} );
}
// Build the field
$field.append( this.$input );
if ( config.showButtons ) {
$field
.prepend( this.minusButton.$element )
.append( this.plusButton.$element );
}
// Initialization
if ( config.allowInteger || config.isInteger ) {
// Backward compatibility
config.step = 1;
}
this.setRange( config.min, config.max );
this.setStep( config.buttonStep, config.pageStep, config.step );
// Set the validation method after we set step and range
// so that it doesn't immediately call setValidityFlag
this.setValidation( this.validateNumber.bind( this ) );
this.$element
.addClass( 'oo-ui-numberInputWidget' )
.toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
.append( $field );
};
/* Setup */
OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
/* Methods */
// Backward compatibility
OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
this.setStep( flag ? 1 : null );
};
// Backward compatibility
OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
// Backward compatibility
OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
return this.step === 1;
};
// Backward compatibility
OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
/**
* Set the range of allowed values
*
* @param {number} min Minimum allowed value
* @param {number} max Maximum allowed value
*/
OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
if ( min > max ) {
throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
}
this.min = min;
this.max = max;
this.$input.attr( 'min', this.min );
this.$input.attr( 'max', this.max );
this.setValidityFlag();
};
/**
* Get the current range
*
* @return {number[]} Minimum and maximum values
*/
OO.ui.NumberInputWidget.prototype.getRange = function () {
return [ this.min, this.max ];
};
/**
* Set the stepping deltas
*
* @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
* Defaults to `step` if specified, otherwise `1`.
* @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
* Defaults to 10 times `buttonStep`.
* @param {number|null} [step] If specified, the field only accepts values that are multiples of this.
*/
OO.ui.NumberInputWidget.prototype.setStep = function ( buttonStep, pageStep, step ) {
if ( buttonStep === undefined ) {
buttonStep = step || 1;
}
if ( pageStep === undefined ) {
pageStep = 10 * buttonStep;
}
if ( step !== null && step <= 0 ) {
throw new Error( 'Step value, if given, must be positive' );
}
if ( buttonStep <= 0 ) {
throw new Error( 'Button step value must be positive' );
}
if ( pageStep <= 0 ) {
throw new Error( 'Page step value must be positive' );
}
this.step = step;
this.buttonStep = buttonStep;
this.pageStep = pageStep;
this.$input.attr( 'step', this.step || 'any' );
this.setValidityFlag();
};
/**
* @inheritdoc
*/
OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
if ( value === '' ) {
// Some browsers allow a value in the input even if there isn't one reported by $input.val()
// so here we make sure an 'empty' value is actually displayed as such.
this.$input.val( '' );
}
return OO.ui.NumberInputWidget.parent.prototype.setValue.call( this, value );
};
/**
* Get the current stepping values
*
* @return {number[]} Button step, page step, and validity step
*/
OO.ui.NumberInputWidget.prototype.getStep = function () {
return [ this.buttonStep, this.pageStep, this.step ];
};
/**
* Get the current value of the widget as a number
*
* @return {number} May be NaN, or an invalid number
*/
OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
return +this.getValue();
};
/**
* Adjust the value of the widget
*
* @param {number} delta Adjustment amount
*/
OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
var n, v = this.getNumericValue();
delta = +delta;
if ( isNaN( delta ) || !isFinite( delta ) ) {
throw new Error( 'Delta must be a finite number' );
}
if ( isNaN( v ) ) {
n = 0;
} else {
n = v + delta;
n = Math.max( Math.min( n, this.max ), this.min );
if ( this.step ) {
n = Math.round( n / this.step ) * this.step;
}
}
if ( n !== v ) {
this.setValue( n );
}
};
/**
* Validate input
*
* @private
* @param {string} value Field value
* @return {boolean}
*/
OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
var n = +value;
if ( value === '' ) {
return !this.isRequired();
}
if ( isNaN( n ) || !isFinite( n ) ) {
return false;
}
if ( this.step && Math.floor( n / this.step ) !== n / this.step ) {
return false;
}
if ( n < this.min || n > this.max ) {
return false;
}
return true;
};
/**
* Handle mouse click events.
*
* @private
* @param {number} dir +1 or -1
*/
OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
this.adjustValue( dir * this.buttonStep );
};
/**
* Handle mouse wheel events.
*
* @private
* @param {jQuery.Event} event
* @return {undefined/boolean} False to prevent default if event is handled
*/
OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
var delta = 0;
if ( !this.isDisabled() && this.$input.is( ':focus' ) ) {
// Standard 'wheel' event
if ( event.originalEvent.deltaMode !== undefined ) {
this.sawWheelEvent = true;
}
if ( event.originalEvent.deltaY ) {
delta = -event.originalEvent.deltaY;
} else if ( event.originalEvent.deltaX ) {
delta = event.originalEvent.deltaX;
}
// Non-standard events
if ( !this.sawWheelEvent ) {
if ( event.originalEvent.wheelDeltaX ) {
delta = -event.originalEvent.wheelDeltaX;
} else if ( event.originalEvent.wheelDeltaY ) {
delta = event.originalEvent.wheelDeltaY;
} else if ( event.originalEvent.wheelDelta ) {
delta = event.originalEvent.wheelDelta;
} else if ( event.originalEvent.detail ) {
delta = -event.originalEvent.detail;
}
}
if ( delta ) {
delta = delta < 0 ? -1 : 1;
this.adjustValue( delta * this.buttonStep );
}
return false;
}
};
/**
* Handle key down events.
*
* @private
* @param {jQuery.Event} e Key down event
* @return {undefined/boolean} False to prevent default if event is handled
*/
OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
if ( !this.isDisabled() ) {
switch ( e.which ) {
case OO.ui.Keys.UP:
this.adjustValue( this.buttonStep );
return false;
case OO.ui.Keys.DOWN:
this.adjustValue( -this.buttonStep );
return false;
case OO.ui.Keys.PAGEUP:
this.adjustValue( this.pageStep );
return false;
case OO.ui.Keys.PAGEDOWN:
this.adjustValue( -this.pageStep );
return false;
}
}
};
/**
* @inheritdoc
*/
OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
// Parent method
OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
if ( this.minusButton ) {
this.minusButton.setDisabled( this.isDisabled() );
}
if ( this.plusButton ) {
this.plusButton.setDisabled( this.isDisabled() );
}
return this;
};
}( OO ) );
//# sourceMappingURL=oojs-ui-core.js.map.json |
/*!
* # Semantic UI 2.4.4 - Search
* http://github.com/semantic-org/semantic-ui/
*
*
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ($, window, document, undefined) {
'use strict';
window = (typeof window != 'undefined' && window.Math == Math)
? window
: (typeof self != 'undefined' && self.Math == Math)
? self
: Function('return this')()
;
$.fn.search = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$(this)
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.search.settings, parameters)
: $.extend({}, $.fn.search.settings),
className = settings.className,
metadata = settings.metadata,
regExp = settings.regExp,
fields = settings.fields,
selector = settings.selector,
error = settings.error,
namespace = settings.namespace,
eventNamespace = '.' + namespace,
moduleNamespace = namespace + '-module',
$module = $(this),
$prompt = $module.find(selector.prompt),
$searchButton = $module.find(selector.searchButton),
$results = $module.find(selector.results),
$result = $module.find(selector.result),
$category = $module.find(selector.category),
element = this,
instance = $module.data(moduleNamespace),
disabledBubbled = false,
resultsDismissed = false,
module
;
module = {
initialize: function() {
module.verbose('Initializing module');
module.get.settings();
module.determine.searchFields();
module.bind.events();
module.set.type();
module.create.results();
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying instance');
$module
.off(eventNamespace)
.removeData(moduleNamespace)
;
},
refresh: function() {
module.debug('Refreshing selector cache');
$prompt = $module.find(selector.prompt);
$searchButton = $module.find(selector.searchButton);
$category = $module.find(selector.category);
$results = $module.find(selector.results);
$result = $module.find(selector.result);
},
refreshResults: function() {
$results = $module.find(selector.results);
$result = $module.find(selector.result);
},
bind: {
events: function() {
module.verbose('Binding events to search');
if(settings.automatic) {
$module
.on(module.get.inputEvent() + eventNamespace, selector.prompt, module.event.input)
;
$prompt
.attr('autocomplete', 'off')
;
}
$module
// prompt
.on('focus' + eventNamespace, selector.prompt, module.event.focus)
.on('blur' + eventNamespace, selector.prompt, module.event.blur)
.on('keydown' + eventNamespace, selector.prompt, module.handleKeyboard)
// search button
.on('click' + eventNamespace, selector.searchButton, module.query)
// results
.on('mousedown' + eventNamespace, selector.results, module.event.result.mousedown)
.on('mouseup' + eventNamespace, selector.results, module.event.result.mouseup)
.on('click' + eventNamespace, selector.result, module.event.result.click)
;
}
},
determine: {
searchFields: function() {
// this makes sure $.extend does not add specified search fields to default fields
// this is the only setting which should not extend defaults
if(parameters && parameters.searchFields !== undefined) {
settings.searchFields = parameters.searchFields;
}
}
},
event: {
input: function() {
if(settings.searchDelay) {
clearTimeout(module.timer);
module.timer = setTimeout(function() {
if(module.is.focused()) {
module.query();
}
}, settings.searchDelay);
}
else {
module.query();
}
},
focus: function() {
module.set.focus();
if(settings.searchOnFocus && module.has.minimumCharacters() ) {
module.query(function() {
if(module.can.show() ) {
module.showResults();
}
});
}
},
blur: function(event) {
var
pageLostFocus = (document.activeElement === this),
callback = function() {
module.cancel.query();
module.remove.focus();
module.timer = setTimeout(module.hideResults, settings.hideDelay);
}
;
if(pageLostFocus) {
return;
}
resultsDismissed = false;
if(module.resultsClicked) {
module.debug('Determining if user action caused search to close');
$module
.one('click.close' + eventNamespace, selector.results, function(event) {
if(module.is.inMessage(event) || disabledBubbled) {
$prompt.focus();
return;
}
disabledBubbled = false;
if( !module.is.animating() && !module.is.hidden()) {
callback();
}
})
;
}
else {
module.debug('Input blurred without user action, closing results');
callback();
}
},
result: {
mousedown: function() {
module.resultsClicked = true;
},
mouseup: function() {
module.resultsClicked = false;
},
click: function(event) {
module.debug('Search result selected');
var
$result = $(this),
$title = $result.find(selector.title).eq(0),
$link = $result.is('a[href]')
? $result
: $result.find('a[href]').eq(0),
href = $link.attr('href') || false,
target = $link.attr('target') || false,
title = $title.html(),
// title is used for result lookup
value = ($title.length > 0)
? $title.text()
: false,
results = module.get.results(),
result = $result.data(metadata.result) || module.get.result(value, results),
returnedValue
;
if( $.isFunction(settings.onSelect) ) {
if(settings.onSelect.call(element, result, results) === false) {
module.debug('Custom onSelect callback cancelled default select action');
disabledBubbled = true;
return;
}
}
module.hideResults();
if(value) {
module.set.value(value);
}
if(href) {
module.verbose('Opening search link found in result', $link);
if(target == '_blank' || event.ctrlKey) {
window.open(href);
}
else {
window.location.href = (href);
}
}
}
}
},
handleKeyboard: function(event) {
var
// force selector refresh
$result = $module.find(selector.result),
$category = $module.find(selector.category),
$activeResult = $result.filter('.' + className.active),
currentIndex = $result.index( $activeResult ),
resultSize = $result.length,
hasActiveResult = $activeResult.length > 0,
keyCode = event.which,
keys = {
backspace : 8,
enter : 13,
escape : 27,
upArrow : 38,
downArrow : 40
},
newIndex
;
// search shortcuts
if(keyCode == keys.escape) {
module.verbose('Escape key pressed, blurring search field');
module.hideResults();
resultsDismissed = true;
}
if( module.is.visible() ) {
if(keyCode == keys.enter) {
module.verbose('Enter key pressed, selecting active result');
if( $result.filter('.' + className.active).length > 0 ) {
module.event.result.click.call($result.filter('.' + className.active), event);
event.preventDefault();
return false;
}
}
else if(keyCode == keys.upArrow && hasActiveResult) {
module.verbose('Up key pressed, changing active result');
newIndex = (currentIndex - 1 < 0)
? currentIndex
: currentIndex - 1
;
$category
.removeClass(className.active)
;
$result
.removeClass(className.active)
.eq(newIndex)
.addClass(className.active)
.closest($category)
.addClass(className.active)
;
event.preventDefault();
}
else if(keyCode == keys.downArrow) {
module.verbose('Down key pressed, changing active result');
newIndex = (currentIndex + 1 >= resultSize)
? currentIndex
: currentIndex + 1
;
$category
.removeClass(className.active)
;
$result
.removeClass(className.active)
.eq(newIndex)
.addClass(className.active)
.closest($category)
.addClass(className.active)
;
event.preventDefault();
}
}
else {
// query shortcuts
if(keyCode == keys.enter) {
module.verbose('Enter key pressed, executing query');
module.query();
module.set.buttonPressed();
$prompt.one('keyup', module.remove.buttonFocus);
}
}
},
setup: {
api: function(searchTerm, callback) {
var
apiSettings = {
debug : settings.debug,
on : false,
cache : settings.cache,
action : 'search',
urlData : {
query : searchTerm
},
onSuccess : function(response) {
module.parse.response.call(element, response, searchTerm);
callback();
},
onFailure : function() {
module.displayMessage(error.serverError);
callback();
},
onAbort : function(response) {
},
onError : module.error
},
searchHTML
;
$.extend(true, apiSettings, settings.apiSettings);
module.verbose('Setting up API request', apiSettings);
$module.api(apiSettings);
}
},
can: {
useAPI: function() {
return $.fn.api !== undefined;
},
show: function() {
return module.is.focused() && !module.is.visible() && !module.is.empty();
},
transition: function() {
return settings.transition && $.fn.transition !== undefined && $module.transition('is supported');
}
},
is: {
animating: function() {
return $results.hasClass(className.animating);
},
hidden: function() {
return $results.hasClass(className.hidden);
},
inMessage: function(event) {
if(!event.target) {
return;
}
var
$target = $(event.target),
isInDOM = $.contains(document.documentElement, event.target)
;
return (isInDOM && $target.closest(selector.message).length > 0);
},
empty: function() {
return ($results.html() === '');
},
visible: function() {
return ($results.filter(':visible').length > 0);
},
focused: function() {
return ($prompt.filter(':focus').length > 0);
}
},
get: {
settings: function() {
if($.isPlainObject(parameters) && parameters.searchFullText) {
settings.fullTextSearch = parameters.searchFullText;
module.error(settings.error.oldSearchSyntax, element);
}
},
inputEvent: function() {
var
prompt = $prompt[0],
inputEvent = (prompt !== undefined && prompt.oninput !== undefined)
? 'input'
: (prompt !== undefined && prompt.onpropertychange !== undefined)
? 'propertychange'
: 'keyup'
;
return inputEvent;
},
value: function() {
return $prompt.val();
},
results: function() {
var
results = $module.data(metadata.results)
;
return results;
},
result: function(value, results) {
var
lookupFields = ['title', 'id'],
result = false
;
value = (value !== undefined)
? value
: module.get.value()
;
results = (results !== undefined)
? results
: module.get.results()
;
if(settings.type === 'category') {
module.debug('Finding result that matches', value);
$.each(results, function(index, category) {
if($.isArray(category.results)) {
result = module.search.object(value, category.results, lookupFields)[0];
// don't continue searching if a result is found
if(result) {
return false;
}
}
});
}
else {
module.debug('Finding result in results object', value);
result = module.search.object(value, results, lookupFields)[0];
}
return result || false;
},
},
select: {
firstResult: function() {
module.verbose('Selecting first result');
$result.first().addClass(className.active);
}
},
set: {
focus: function() {
$module.addClass(className.focus);
},
loading: function() {
$module.addClass(className.loading);
},
value: function(value) {
module.verbose('Setting search input value', value);
$prompt
.val(value)
;
},
type: function(type) {
type = type || settings.type;
if(settings.type == 'category') {
$module.addClass(settings.type);
}
},
buttonPressed: function() {
$searchButton.addClass(className.pressed);
}
},
remove: {
loading: function() {
$module.removeClass(className.loading);
},
focus: function() {
$module.removeClass(className.focus);
},
buttonPressed: function() {
$searchButton.removeClass(className.pressed);
}
},
query: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
var
searchTerm = module.get.value(),
cache = module.read.cache(searchTerm)
;
callback = callback || function() {};
if( module.has.minimumCharacters() ) {
if(cache) {
module.debug('Reading result from cache', searchTerm);
module.save.results(cache.results);
module.addResults(cache.html);
module.inject.id(cache.results);
callback();
}
else {
module.debug('Querying for', searchTerm);
if($.isPlainObject(settings.source) || $.isArray(settings.source)) {
module.search.local(searchTerm);
callback();
}
else if( module.can.useAPI() ) {
module.search.remote(searchTerm, callback);
}
else {
module.error(error.source);
callback();
}
}
settings.onSearchQuery.call(element, searchTerm);
}
else {
module.hideResults();
}
},
search: {
local: function(searchTerm) {
var
results = module.search.object(searchTerm, settings.content),
searchHTML
;
module.set.loading();
module.save.results(results);
module.debug('Returned full local search results', results);
if(settings.maxResults > 0) {
module.debug('Using specified max results', results);
results = results.slice(0, settings.maxResults);
}
if(settings.type == 'category') {
results = module.create.categoryResults(results);
}
searchHTML = module.generateResults({
results: results
});
module.remove.loading();
module.addResults(searchHTML);
module.inject.id(results);
module.write.cache(searchTerm, {
html : searchHTML,
results : results
});
},
remote: function(searchTerm, callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if($module.api('is loading')) {
$module.api('abort');
}
module.setup.api(searchTerm, callback);
$module
.api('query')
;
},
object: function(searchTerm, source, searchFields) {
var
results = [],
exactResults = [],
fuzzyResults = [],
searchExp = searchTerm.toString().replace(regExp.escape, '\\$&'),
matchRegExp = new RegExp(regExp.beginsWith + searchExp, 'i'),
// avoid duplicates when pushing results
addResult = function(array, result) {
var
notResult = ($.inArray(result, results) == -1),
notFuzzyResult = ($.inArray(result, fuzzyResults) == -1),
notExactResults = ($.inArray(result, exactResults) == -1)
;
if(notResult && notFuzzyResult && notExactResults) {
array.push(result);
}
}
;
source = source || settings.source;
searchFields = (searchFields !== undefined)
? searchFields
: settings.searchFields
;
// search fields should be array to loop correctly
if(!$.isArray(searchFields)) {
searchFields = [searchFields];
}
// exit conditions if no source
if(source === undefined || source === false) {
module.error(error.source);
return [];
}
// iterate through search fields looking for matches
$.each(searchFields, function(index, field) {
$.each(source, function(label, content) {
var
fieldExists = (typeof content[field] == 'string')
;
if(fieldExists) {
if( content[field].search(matchRegExp) !== -1) {
// content starts with value (first in results)
addResult(results, content);
}
else if(settings.fullTextSearch === 'exact' && module.exactSearch(searchTerm, content[field]) ) {
// content fuzzy matches (last in results)
addResult(exactResults, content);
}
else if(settings.fullTextSearch == true && module.fuzzySearch(searchTerm, content[field]) ) {
// content fuzzy matches (last in results)
addResult(fuzzyResults, content);
}
}
});
});
$.merge(exactResults, fuzzyResults)
$.merge(results, exactResults);
return results;
}
},
exactSearch: function (query, term) {
query = query.toLowerCase();
term = term.toLowerCase();
if(term.indexOf(query) > -1) {
return true;
}
return false;
},
fuzzySearch: function(query, term) {
var
termLength = term.length,
queryLength = query.length
;
if(typeof query !== 'string') {
return false;
}
query = query.toLowerCase();
term = term.toLowerCase();
if(queryLength > termLength) {
return false;
}
if(queryLength === termLength) {
return (query === term);
}
search: for (var characterIndex = 0, nextCharacterIndex = 0; characterIndex < queryLength; characterIndex++) {
var
queryCharacter = query.charCodeAt(characterIndex)
;
while(nextCharacterIndex < termLength) {
if(term.charCodeAt(nextCharacterIndex++) === queryCharacter) {
continue search;
}
}
return false;
}
return true;
},
parse: {
response: function(response, searchTerm) {
var
searchHTML = module.generateResults(response)
;
module.verbose('Parsing server response', response);
if(response !== undefined) {
if(searchTerm !== undefined && response[fields.results] !== undefined) {
module.addResults(searchHTML);
module.inject.id(response[fields.results]);
module.write.cache(searchTerm, {
html : searchHTML,
results : response[fields.results]
});
module.save.results(response[fields.results]);
}
}
}
},
cancel: {
query: function() {
if( module.can.useAPI() ) {
$module.api('abort');
}
}
},
has: {
minimumCharacters: function() {
var
searchTerm = module.get.value(),
numCharacters = searchTerm.length
;
return (numCharacters >= settings.minCharacters);
},
results: function() {
if($results.length === 0) {
return false;
}
var
html = $results.html()
;
return html != '';
}
},
clear: {
cache: function(value) {
var
cache = $module.data(metadata.cache)
;
if(!value) {
module.debug('Clearing cache', value);
$module.removeData(metadata.cache);
}
else if(value && cache && cache[value]) {
module.debug('Removing value from cache', value);
delete cache[value];
$module.data(metadata.cache, cache);
}
}
},
read: {
cache: function(name) {
var
cache = $module.data(metadata.cache)
;
if(settings.cache) {
module.verbose('Checking cache for generated html for query', name);
return (typeof cache == 'object') && (cache[name] !== undefined)
? cache[name]
: false
;
}
return false;
}
},
create: {
categoryResults: function(results) {
var
categoryResults = {}
;
$.each(results, function(index, result) {
if(!result.category) {
return;
}
if(categoryResults[result.category] === undefined) {
module.verbose('Creating new category of results', result.category);
categoryResults[result.category] = {
name : result.category,
results : [result]
}
}
else {
categoryResults[result.category].results.push(result);
}
});
return categoryResults;
},
id: function(resultIndex, categoryIndex) {
var
resultID = (resultIndex + 1), // not zero indexed
categoryID = (categoryIndex + 1),
firstCharCode,
letterID,
id
;
if(categoryIndex !== undefined) {
// start char code for "A"
letterID = String.fromCharCode(97 + categoryIndex);
id = letterID + resultID;
module.verbose('Creating category result id', id);
}
else {
id = resultID;
module.verbose('Creating result id', id);
}
return id;
},
results: function() {
if($results.length === 0) {
$results = $('<div />')
.addClass(className.results)
.appendTo($module)
;
}
}
},
inject: {
result: function(result, resultIndex, categoryIndex) {
module.verbose('Injecting result into results');
var
$selectedResult = (categoryIndex !== undefined)
? $results
.children().eq(categoryIndex)
.children(selector.results)
.first()
.children(selector.result)
.eq(resultIndex)
: $results
.children(selector.result).eq(resultIndex)
;
module.verbose('Injecting results metadata', $selectedResult);
$selectedResult
.data(metadata.result, result)
;
},
id: function(results) {
module.debug('Injecting unique ids into results');
var
// since results may be object, we must use counters
categoryIndex = 0,
resultIndex = 0
;
if(settings.type === 'category') {
// iterate through each category result
$.each(results, function(index, category) {
resultIndex = 0;
$.each(category.results, function(index, value) {
var
result = category.results[index]
;
if(result.id === undefined) {
result.id = module.create.id(resultIndex, categoryIndex);
}
module.inject.result(result, resultIndex, categoryIndex);
resultIndex++;
});
categoryIndex++;
});
}
else {
// top level
$.each(results, function(index, value) {
var
result = results[index]
;
if(result.id === undefined) {
result.id = module.create.id(resultIndex);
}
module.inject.result(result, resultIndex);
resultIndex++;
});
}
return results;
}
},
save: {
results: function(results) {
module.verbose('Saving current search results to metadata', results);
$module.data(metadata.results, results);
}
},
write: {
cache: function(name, value) {
var
cache = ($module.data(metadata.cache) !== undefined)
? $module.data(metadata.cache)
: {}
;
if(settings.cache) {
module.verbose('Writing generated html to cache', name, value);
cache[name] = value;
$module
.data(metadata.cache, cache)
;
}
}
},
addResults: function(html) {
if( $.isFunction(settings.onResultsAdd) ) {
if( settings.onResultsAdd.call($results, html) === false ) {
module.debug('onResultsAdd callback cancelled default action');
return false;
}
}
if(html) {
$results
.html(html)
;
module.refreshResults();
if(settings.selectFirstResult) {
module.select.firstResult();
}
module.showResults();
}
else {
module.hideResults(function() {
$results.empty();
});
}
},
showResults: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if(resultsDismissed) {
return;
}
if(!module.is.visible() && module.has.results()) {
if( module.can.transition() ) {
module.debug('Showing results with css animations');
$results
.transition({
animation : settings.transition + ' in',
debug : settings.debug,
verbose : settings.verbose,
duration : settings.duration,
onComplete : function() {
callback();
},
queue : true
})
;
}
else {
module.debug('Showing results with javascript');
$results
.stop()
.fadeIn(settings.duration, settings.easing)
;
}
settings.onResultsOpen.call($results);
}
},
hideResults: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if( module.is.visible() ) {
if( module.can.transition() ) {
module.debug('Hiding results with css animations');
$results
.transition({
animation : settings.transition + ' out',
debug : settings.debug,
verbose : settings.verbose,
duration : settings.duration,
onComplete : function() {
callback();
},
queue : true
})
;
}
else {
module.debug('Hiding results with javascript');
$results
.stop()
.fadeOut(settings.duration, settings.easing)
;
}
settings.onResultsClose.call($results);
}
},
generateResults: function(response) {
module.debug('Generating html from response', response);
var
template = settings.templates[settings.type],
isProperObject = ($.isPlainObject(response[fields.results]) && !$.isEmptyObject(response[fields.results])),
isProperArray = ($.isArray(response[fields.results]) && response[fields.results].length > 0),
html = ''
;
if(isProperObject || isProperArray ) {
if(settings.maxResults > 0) {
if(isProperObject) {
if(settings.type == 'standard') {
module.error(error.maxResults);
}
}
else {
response[fields.results] = response[fields.results].slice(0, settings.maxResults);
}
}
if($.isFunction(template)) {
html = template(response, fields);
}
else {
module.error(error.noTemplate, false);
}
}
else if(settings.showNoResults) {
html = module.displayMessage(error.noResults, 'empty', error.noResultsHeader);
}
settings.onResults.call(element, response);
return html;
},
displayMessage: function(text, type, header) {
type = type || 'standard';
module.debug('Displaying message', text, type, header);
module.addResults( settings.templates.message(text, type, header) );
return settings.templates.message(text, type, header);
},
setting: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
settings[name] = value;
}
else {
return settings[name];
}
},
internal: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else if(value !== undefined) {
module[name] = value;
}
else {
return module[name];
}
},
debug: function() {
if(!settings.silent && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.debug.apply(console, arguments);
}
}
},
verbose: function() {
if(!settings.silent && settings.verbose && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.verbose.apply(console, arguments);
}
}
},
error: function() {
if(!settings.silent) {
module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
module.error.apply(console, arguments);
}
},
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Element' : element,
'Execution Time' : executionTime
});
}
clearTimeout(module.performance.timer);
module.performance.timer = setTimeout(module.performance.display, 500);
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(module.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if($allModules.length > 1) {
title += ' ' + '(' + $allModules.length + ')';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
invoke: function(query, passedArguments, context) {
var
object = instance,
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && object !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
object = object[camelCaseValue];
}
else if( object[camelCaseValue] !== undefined ) {
found = object[camelCaseValue];
return false;
}
else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
object = object[value];
}
else if( object[value] !== undefined ) {
found = object[value];
return false;
}
else {
return false;
}
});
}
if( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.search.settings = {
name : 'Search',
namespace : 'search',
silent : false,
debug : false,
verbose : false,
performance : true,
// template to use (specified in settings.templates)
type : 'standard',
// minimum characters required to search
minCharacters : 1,
// whether to select first result after searching automatically
selectFirstResult : false,
// API config
apiSettings : false,
// object to search
source : false,
// Whether search should query current term on focus
searchOnFocus : true,
// fields to search
searchFields : [
'title',
'description'
],
// field to display in standard results template
displayField : '',
// search anywhere in value (set to 'exact' to require exact matches
fullTextSearch : 'exact',
// whether to add events to prompt automatically
automatic : true,
// delay before hiding menu after blur
hideDelay : 0,
// delay before searching
searchDelay : 200,
// maximum results returned from search
maxResults : 7,
// whether to store lookups in local cache
cache : true,
// whether no results errors should be shown
showNoResults : true,
// transition settings
transition : 'scale',
duration : 200,
easing : 'easeOutExpo',
// callbacks
onSelect : false,
onResultsAdd : false,
onSearchQuery : function(query){},
onResults : function(response){},
onResultsOpen : function(){},
onResultsClose : function(){},
className: {
animating : 'animating',
active : 'active',
empty : 'empty',
focus : 'focus',
hidden : 'hidden',
loading : 'loading',
results : 'results',
pressed : 'down'
},
error : {
source : 'Cannot search. No source used, and Semantic API module was not included',
noResultsHeader : 'No Results',
noResults : 'Your search returned no results',
logging : 'Error in debug logging, exiting.',
noEndpoint : 'No search endpoint was specified',
noTemplate : 'A valid template name was not specified.',
oldSearchSyntax : 'searchFullText setting has been renamed fullTextSearch for consistency, please adjust your settings.',
serverError : 'There was an issue querying the server.',
maxResults : 'Results must be an array to use maxResults setting',
method : 'The method you called is not defined.'
},
metadata: {
cache : 'cache',
results : 'results',
result : 'result'
},
regExp: {
escape : /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,
beginsWith : '(?:\s|^)'
},
// maps api response attributes to internal representation
fields: {
categories : 'results', // array of categories (category view)
categoryName : 'name', // name of category (category view)
categoryResults : 'results', // array of results (category view)
description : 'description', // result description
image : 'image', // result image
price : 'price', // result price
results : 'results', // array of results (standard)
title : 'title', // result title
url : 'url', // result url
action : 'action', // "view more" object name
actionText : 'text', // "view more" text
actionURL : 'url' // "view more" url
},
selector : {
prompt : '.prompt',
searchButton : '.search.button',
results : '.results',
message : '.results > .message',
category : '.category',
result : '.result',
title : '.title, .name'
},
templates: {
escape: function(string) {
var
badChars = /[&<>"'`]/g,
shouldEscape = /[&<>"'`]/,
escape = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`"
},
escapedChar = function(chr) {
return escape[chr];
}
;
if(shouldEscape.test(string)) {
return string.replace(badChars, escapedChar);
}
return string;
},
message: function(message, type, header) {
var
html = ''
;
if(message !== undefined && type !== undefined) {
html += ''
+ '<div class="message ' + type + '">'
;
if(header) {
html += ''
+ '<div class="header">' + header + '</div class="header">'
;
}
html += ' <div class="description">' + message + '</div>';
html += '</div>';
}
return html;
},
category: function(response, fields) {
var
html = '',
escape = $.fn.search.settings.templates.escape
;
if(response[fields.categoryResults] !== undefined) {
// each category
$.each(response[fields.categoryResults], function(index, category) {
if(category[fields.results] !== undefined && category.results.length > 0) {
html += '<div class="category">';
if(category[fields.categoryName] !== undefined) {
html += '<div class="name">' + category[fields.categoryName] + '</div>';
}
// each item inside category
html += '<div class="results">';
$.each(category.results, function(index, result) {
if(result[fields.url]) {
html += '<a class="result" href="' + result[fields.url] + '">';
}
else {
html += '<a class="result">';
}
if(result[fields.image] !== undefined) {
html += ''
+ '<div class="image">'
+ ' <img src="' + result[fields.image] + '">'
+ '</div>'
;
}
html += '<div class="content">';
if(result[fields.price] !== undefined) {
html += '<div class="price">' + result[fields.price] + '</div>';
}
if(result[fields.title] !== undefined) {
html += '<div class="title">' + result[fields.title] + '</div>';
}
if(result[fields.description] !== undefined) {
html += '<div class="description">' + result[fields.description] + '</div>';
}
html += ''
+ '</div>'
;
html += '</a>';
});
html += '</div>';
html += ''
+ '</div>'
;
}
});
if(response[fields.action]) {
html += ''
+ '<a href="' + response[fields.action][fields.actionURL] + '" class="action">'
+ response[fields.action][fields.actionText]
+ '</a>';
}
return html;
}
return false;
},
standard: function(response, fields) {
var
html = ''
;
if(response[fields.results] !== undefined) {
// each result
$.each(response[fields.results], function(index, result) {
if(result[fields.url]) {
html += '<a class="result" href="' + result[fields.url] + '">';
}
else {
html += '<a class="result">';
}
if(result[fields.image] !== undefined) {
html += ''
+ '<div class="image">'
+ ' <img src="' + result[fields.image] + '">'
+ '</div>'
;
}
html += '<div class="content">';
if(result[fields.price] !== undefined) {
html += '<div class="price">' + result[fields.price] + '</div>';
}
if(result[fields.title] !== undefined) {
html += '<div class="title">' + result[fields.title] + '</div>';
}
if(result[fields.description] !== undefined) {
html += '<div class="description">' + result[fields.description] + '</div>';
}
html += ''
+ '</div>'
;
html += '</a>';
});
if(response[fields.action]) {
html += ''
+ '<a href="' + response[fields.action][fields.actionURL] + '" class="action">'
+ response[fields.action][fields.actionText]
+ '</a>';
}
return html;
}
return false;
}
}
};
})( jQuery, window, document );
|
/*
Copyright (c) 2015-present NAVER Corp.
name: @egjs/flicking
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-flicking
version: 3.2.1
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@egjs/component'), require('@egjs/axes')) :
typeof define === 'function' && define.amd ? define(['@egjs/component', '@egjs/axes'], factory) :
(global = global || self, (global.eg = global.eg || {}, global.eg.Flicking = factory(global.eg.Component, global.eg.Axes)));
}(this, function (Component, Axes) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
};
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
function merge(target) {
var srcs = [];
for (var _i = 1; _i < arguments.length; _i++) {
srcs[_i - 1] = arguments[_i];
}
srcs.forEach(function (source) {
Object.keys(source).forEach(function (key) {
var value = source[key];
target[key] = value;
});
});
return target;
}
function parseElement(element) {
if (!Array.isArray(element)) {
element = [element];
}
var elements = [];
element.forEach(function (el) {
if (isString(el)) {
var tempDiv = document.createElement("div");
tempDiv.innerHTML = el;
elements.push.apply(elements, toArray(tempDiv.children));
} else {
elements.push(el);
}
});
return elements;
} // Check whether browser supports transform: translate3d
// https://stackoverflow.com/questions/5661671/detecting-transform-translate3d-support
var checkTranslateSupport = function () {
var transforms = {
webkitTransform: "-webkit-transform",
msTransform: "-ms-transform",
MozTransform: "-moz-transform",
OTransform: "-o-transform",
transform: "transform"
};
if (typeof document === "undefined") {
return {
name: transforms.transform,
has3d: true
};
}
var supportedStyle = document.documentElement.style;
var transformName = "";
for (var prefixedTransform in transforms) {
if (prefixedTransform in supportedStyle) {
transformName = prefixedTransform;
}
}
if (!transformName) {
throw new Error("Browser doesn't support CSS3 2D Transforms.");
}
var el = document.createElement("div");
document.documentElement.insertBefore(el, null);
el.style[transformName] = "translate3d(1px, 1px, 1px)";
var styleVal = window.getComputedStyle(el).getPropertyValue(transforms[transformName]);
el.parentElement.removeChild(el);
var transformInfo = {
name: transformName,
has3d: styleVal.length > 0 && styleVal !== "none"
};
checkTranslateSupport = function () {
return transformInfo;
};
return transformInfo;
};
function isString(value) {
return typeof value === "string";
} // Get class list of element as string array
function classList(element) {
return element.classList ? toArray(element.classList) : element.className.split(" ");
} // Add class to specified element
function addClass(element, className) {
if (element.classList) {
element.classList.add(className);
} else {
if (element.className.indexOf(className) < 0) {
element.className = (element.className + " " + className).replace(/\s{2,}/g, " ");
}
}
}
function applyCSS(element, cssObj) {
Object.keys(cssObj).forEach(function (property) {
element.style[property] = cssObj[property];
});
}
function clamp(val, min, max) {
return Math.max(Math.min(val, max), min);
} // Min: inclusive, Max: exclusive
function isBetween(val, min, max) {
return val >= min && val <= max;
}
function toArray(iterable) {
return [].slice.call(iterable);
}
function isArray(arr) {
return arr && arr.constructor === Array;
}
function parseArithmeticExpression(cssValue, base, defaultVal) {
// Set base / 2 to default value, if it's undefined
var defaultValue = defaultVal != null ? defaultVal : base / 2;
var cssRegex = /(?:(\+|\-)\s*)?(\d+(?:\.\d+)?(%|px)?)/g;
if (typeof cssValue === "number") {
return clamp(cssValue, 0, base);
}
var idx = 0;
var calculatedValue = 0;
var matchResult = cssRegex.exec(cssValue);
while (matchResult != null) {
var sign = matchResult[1];
var value = matchResult[2];
var unit = matchResult[3];
var parsedValue = parseFloat(value);
if (idx <= 0) {
sign = sign || "+";
} // Return default value for values not in good form
if (!sign) {
return defaultValue;
}
if (unit === "%") {
parsedValue = parsedValue / 100 * base;
}
calculatedValue += sign === "+" ? parsedValue : -parsedValue; // Match next occurrence
++idx;
matchResult = cssRegex.exec(cssValue);
} // None-matched
if (idx === 0) {
return defaultValue;
} // Clamp between 0 ~ base
return clamp(calculatedValue, 0, base);
}
function getProgress(pos, range) {
// start, anchor, end
// -1 , 0 , 1
var min = range[0],
center = range[1],
max = range[2];
if (pos > center && max - center) {
// 0 ~ 1
return (pos - center) / (max - center);
} else if (pos < center && center - min) {
// -1 ~ 0
return (pos - center) / (center - min);
} else if (pos !== center && max - min) {
return (pos - min) / (max - min);
}
return 0;
}
function findIndex(iterable, callback) {
for (var i = 0; i < iterable.length; i += 1) {
var element = iterable[i];
if (element && callback(element)) {
return i;
}
}
return -1;
} // return [0, 1, ...., max - 1]
function counter(max) {
var counterArray = [];
for (var i = 0; i < max; i += 1) {
counterArray[i] = i;
}
return counterArray;
} // Circulate number between range [min, max]
/*
* "indexed" means min and max is not same, so if it's true "min - 1" should be max
* While if it's false, "min - 1" should be "max - 1"
* use `indexed: true` when it should be used for circulating integers like index
* or `indexed: false` when it should be used for something like positions.
*/
function circulate(value, min, max, indexed) {
var size = indexed ? max - min + 1 : max - min;
if (value < min) {
var offset = indexed ? (min - value - 1) % size : (min - value) % size;
value = max - offset;
} else if (value > max) {
var offset = indexed ? (value - max - 1) % size : (value - max) % size;
value = min + offset;
}
return value;
}
function hasClass(element, className) {
if (!element) {
return false;
}
var classes = classList(element);
return findIndex(classes, function (name) {
return name === className;
}) > -1;
}
function restoreStyle(element, originalStyle) {
originalStyle.className ? element.setAttribute("class", originalStyle.className) : element.removeAttribute("class");
originalStyle.style ? element.setAttribute("style", originalStyle.style) : element.removeAttribute("style");
}
/**
* Decorator that makes the method of flicking available in the framework.
* @ko ํ๋ ์์ํฌ์์ ํ๋ฆฌํน์ ๋ฉ์๋๋ฅผ ์ฌ์ฉํ ์ ์๊ฒ ํ๋ ๋ฐ์ฝ๋ ์ดํฐ.
* @memberof eg.Flicking
* @private
* @example
* ```js
* import Flicking, { withFlickingMethods } from "@egjs/flicking";
*
* class Flicking extends React.Component<Partial<FlickingProps & FlickingOptions>> {
* @withFlickingMethods
* private flicking: Flicking;
* }
* ```
*/
function withFlickingMethods(prototype, flickingName) {
Object.keys(FLICKING_METHODS).forEach(function (name) {
if (prototype[name]) {
return;
}
prototype[name] = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var result = (_a = this[flickingName])[name].apply(_a, args); // fix `this` type to return your own `flicking` instance to the instance using the decorator.
if (result === this[flickingName]) {
return this;
} else {
return result;
}
var _a;
};
});
}
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var MOVE_TYPE = {
SNAP: "snap",
FREE_SCROLL: "freeScroll"
};
var DEFAULT_MOVE_TYPE_OPTIONS = {
snap: {
type: "snap",
count: 1
},
freeScroll: {
type: "freeScroll"
}
};
/**
* Default options for creating Flicking.
* @ko ํ๋ฆฌํน์ ๋ง๋ค ๋ ์ฌ์ฉํ๋ ๊ธฐ๋ณธ ์ต์
๋ค
* @private
* @memberof eg.Flicking
*/
var DEFAULT_OPTIONS = {
classPrefix: "eg-flick",
deceleration: 0.0075,
horizontal: true,
circular: false,
infinite: false,
infiniteThreshold: 0,
lastIndex: Infinity,
threshold: 40,
duration: 100,
panelEffect: function (x) {
return 1 - Math.pow(1 - x, 3);
},
defaultIndex: 0,
inputType: ["touch", "mouse"],
thresholdAngle: 45,
bounce: 10,
autoResize: false,
adaptive: false,
zIndex: 2000,
bound: false,
overflow: false,
hanger: "50%",
anchor: "50%",
gap: 0,
moveType: DEFAULT_MOVE_TYPE_OPTIONS.snap,
renderExternal: false
};
var DEFAULT_VIEWPORT_CSS = {
position: "relative",
zIndex: DEFAULT_OPTIONS.zIndex,
width: "100%",
height: "100%",
overflow: "hidden"
};
var DEFAULT_CAMERA_CSS = {
width: "100%",
height: "100%",
willChange: "transform"
};
var DEFAULT_PANEL_CSS = {
position: "absolute"
};
var EVENTS = {
HOLD_START: "holdStart",
HOLD_END: "holdEnd",
MOVE_START: "moveStart",
MOVE: "move",
MOVE_END: "moveEnd",
CHANGE: "change",
RESTORE: "restore",
SELECT: "select",
NEED_PANEL: "needPanel"
};
var AXES_EVENTS = {
HOLD: "hold",
CHANGE: "change",
RELEASE: "release",
ANIMATION_END: "animationEnd",
FINISH: "finish"
};
var STATE_TYPE = {
IDLE: 0,
HOLDING: 1,
DRAGGING: 2,
ANIMATING: 3,
DISABLED: 4
};
var DIRECTION = {
PREV: "PREV",
NEXT: "NEXT"
};
var FLICKING_METHODS = {
prev: true,
next: true,
moveTo: true,
getIndex: true,
getAllPanels: true,
getCurrentPanel: true,
getElement: true,
getPanel: true,
getPanelCount: true,
getStatus: true,
getVisiblePanels: true,
setLastIndex: true,
enableInput: true,
disableInput: true,
destroy: true,
resize: true,
setStatus: true,
addPlugins: true,
removePlugins: true,
isPlaying: true,
getLastIndex: true
};
var TRANSFORM = checkTranslateSupport();
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var Panel =
/*#__PURE__*/
function () {
function Panel(element, index, viewport) {
this.viewport = viewport;
this.prevSibling = null;
this.nextSibling = null;
this.clonedPanels = [];
this.state = {
index: index,
position: 0,
relativeAnchorPosition: 0,
size: 0,
isClone: false,
isVirtual: false,
cloneIndex: -1,
originalStyle: {
className: element.getAttribute("class"),
style: element.getAttribute("style")
},
cachedBbox: null
};
this.setElement(element);
}
var __proto = Panel.prototype;
__proto.resize = function () {
var state = this.state;
var options = this.viewport.options;
var bbox = this.getBbox();
state.size = options.horizontal ? bbox.width : bbox.height;
state.relativeAnchorPosition = parseArithmeticExpression(options.anchor, state.size);
if (!state.isClone) {
this.clonedPanels.forEach(function (panel) {
return panel.resize();
});
}
};
__proto.unCacheBbox = function () {
this.state.cachedBbox = null;
};
__proto.getProgress = function () {
var viewport = this.viewport;
var options = viewport.options;
var panelCount = viewport.panelManager.getPanelCount();
var scrollAreaSize = viewport.getScrollAreaSize();
var relativeIndex = (options.circular ? Math.floor(this.getPosition() / scrollAreaSize) * panelCount : 0) + this.getIndex();
var progress = relativeIndex - viewport.getCurrentProgress();
return progress;
};
__proto.getOutsetProgress = function () {
var viewport = this.viewport;
var outsetRange = [-this.getSize(), viewport.getRelativeHangerPosition() - this.getRelativeAnchorPosition(), viewport.getSize()];
var relativePanelPosition = this.getPosition() - viewport.getCameraPosition();
var outsetProgress = getProgress(relativePanelPosition, outsetRange);
return outsetProgress;
};
__proto.getVisibleRatio = function () {
var viewport = this.viewport;
var panelSize = this.getSize();
var relativePanelPosition = this.getPosition() - viewport.getCameraPosition();
var rightRelativePanelPosition = relativePanelPosition + panelSize;
var visibleSize = Math.min(viewport.getSize(), rightRelativePanelPosition) - Math.max(relativePanelPosition, 0);
var visibleRatio = visibleSize >= 0 ? visibleSize / panelSize : 0;
return visibleRatio;
};
__proto.focus = function (duration) {
var viewport = this.viewport;
var currentPanel = viewport.getCurrentPanel();
var hangerPosition = viewport.getHangerPosition();
var anchorPosition = this.getAnchorPosition();
if (hangerPosition === anchorPosition || !currentPanel) {
return;
}
var currentPosition = currentPanel.getPosition();
var eventType = currentPosition === this.getPosition() ? "" : EVENTS.CHANGE;
viewport.moveTo(this, viewport.findEstimatedPosition(this), eventType, null, duration);
};
__proto.update = function (updateFunction) {
this.getIdenticalPanels().forEach(function (eachPanel) {
updateFunction(eachPanel.getElement());
eachPanel.unCacheBbox();
});
this.viewport.resize();
};
__proto.prev = function () {
var viewport = this.viewport;
var options = viewport.options;
var prevSibling = this.prevSibling;
if (!prevSibling) {
return null;
}
var currentIndex = this.getIndex();
var currentPosition = this.getPosition();
var prevPanelIndex = prevSibling.getIndex();
var prevPanelPosition = prevSibling.getPosition();
var prevPanelSize = prevSibling.getSize();
var hasEmptyPanelBetween = currentIndex - prevPanelIndex > 1;
var notYetMinPanel = options.infinite && currentIndex > 0 && prevPanelIndex > currentIndex;
if (hasEmptyPanelBetween || notYetMinPanel) {
// Empty panel exists between
return null;
}
var newPosition = currentPosition - prevPanelSize - options.gap;
var prevPanel = prevSibling;
if (prevPanelPosition !== newPosition) {
prevPanel = prevSibling.clone(prevSibling.getCloneIndex(), true);
prevPanel.setPosition(newPosition);
}
return prevPanel;
};
__proto.next = function () {
var viewport = this.viewport;
var options = viewport.options;
var nextSibling = this.nextSibling;
var lastIndex = viewport.panelManager.getLastIndex();
if (!nextSibling) {
return null;
}
var currentIndex = this.getIndex();
var currentPosition = this.getPosition();
var nextPanelIndex = nextSibling.getIndex();
var nextPanelPosition = nextSibling.getPosition();
var hasEmptyPanelBetween = nextPanelIndex - currentIndex > 1;
var notYetMaxPanel = options.infinite && currentIndex < lastIndex && nextPanelIndex < currentIndex;
if (hasEmptyPanelBetween || notYetMaxPanel) {
return null;
}
var newPosition = currentPosition + this.getSize() + options.gap;
var nextPanel = nextSibling;
if (nextPanelPosition !== newPosition) {
nextPanel = nextSibling.clone(nextSibling.getCloneIndex(), true);
nextPanel.setPosition(newPosition);
}
return nextPanel;
};
__proto.insertBefore = function (element) {
var viewport = this.viewport;
var parsedElements = parseElement(element);
var firstPanel = viewport.panelManager.firstPanel();
var prevSibling = this.prevSibling; // Finding correct inserting index
// While it should insert removing empty spaces,
// It also should have to be bigger than prevSibling' s index
var targetIndex = prevSibling && firstPanel.getIndex() !== this.getIndex() ? Math.max(prevSibling.getIndex() + 1, this.getIndex() - parsedElements.length) : Math.max(this.getIndex() - parsedElements.length, 0);
return viewport.insert(targetIndex, parsedElements);
};
__proto.insertAfter = function (element) {
return this.viewport.insert(this.getIndex() + 1, element);
};
__proto.remove = function () {
this.viewport.remove(this.getIndex());
return this;
};
__proto.destroy = function (option) {
if (!option.preserveUI) {
var originalStyle = this.state.originalStyle;
restoreStyle(this.element, originalStyle);
} // release resources
for (var x in this) {
this[x] = null;
}
};
__proto.getElement = function () {
return this.element;
};
__proto.getAnchorPosition = function () {
return this.state.position + this.state.relativeAnchorPosition;
};
__proto.getRelativeAnchorPosition = function () {
return this.state.relativeAnchorPosition;
};
__proto.getIndex = function () {
return this.state.index;
};
__proto.getPosition = function () {
return this.state.position;
};
__proto.getSize = function () {
return this.state.size;
};
__proto.getBbox = function () {
var state = this.state;
if (!state.cachedBbox) {
state.cachedBbox = this.element.getBoundingClientRect();
}
return state.cachedBbox;
};
__proto.isClone = function () {
return this.state.isClone;
};
__proto.getCloneIndex = function () {
return this.state.cloneIndex;
};
__proto.getClonedPanels = function () {
var state = this.state;
return state.isClone ? this.original.getClonedPanels() : this.clonedPanels;
};
__proto.getIdenticalPanels = function () {
var state = this.state;
return state.isClone ? this.original.getIdenticalPanels() : [this].concat(this.clonedPanels);
};
__proto.getOriginalPanel = function () {
return this.state.isClone ? this.original : this;
};
__proto.setIndex = function (index) {
var state = this.state;
state.index = index;
this.clonedPanels.forEach(function (panel) {
return panel.state.index = index;
});
};
__proto.setPosition = function (pos) {
var state = this.state;
var options = this.viewport.options;
state.position = pos;
if (!state.isVirtual) {
var elementStyle = this.element.style;
options.horizontal ? elementStyle.left = pos + "px" : elementStyle.top = pos + "px";
}
return this;
};
__proto.clone = function (cloneIndex, isVirtual) {
if (isVirtual === void 0) {
isVirtual = false;
}
var state = this.state;
var viewport = this.viewport;
var cloneElement = isVirtual ? this.element : this.element.cloneNode(true);
var clonedPanel = new Panel(cloneElement, state.index, viewport);
var clonedState = clonedPanel.state;
clonedPanel.original = state.isClone ? this.original : this;
clonedState.isClone = true;
clonedState.isVirtual = isVirtual;
clonedState.cloneIndex = cloneIndex; // Inherit some state values
clonedState.size = state.size;
clonedState.relativeAnchorPosition = state.relativeAnchorPosition;
clonedState.originalStyle = state.originalStyle;
clonedState.cachedBbox = state.cachedBbox;
if (!isVirtual) {
this.clonedPanels.push(clonedPanel);
} else {
clonedPanel.prevSibling = this.prevSibling;
clonedPanel.nextSibling = this.nextSibling;
}
return clonedPanel;
}; // Clone with external element
__proto.cloneExternal = function (cloneIndex, element) {
var clonedPanel = this.clone(cloneIndex);
clonedPanel.setElement(element);
return clonedPanel;
};
__proto.removeElement = function () {
if (!this.viewport.options.renderExternal) {
var element = this.element;
element.parentNode.removeChild(element);
} // Do the same thing for clones
if (!this.state.isClone) {
this.removeClonedPanelsAfter(0);
}
};
__proto.removeClonedPanelsAfter = function (start) {
var removingPanels = this.clonedPanels.splice(start);
removingPanels.forEach(function (panel) {
panel.removeElement();
});
};
__proto.setElement = function (element) {
this.element = element;
var options = this.viewport.options;
if (options.classPrefix) {
addClass(element, options.classPrefix + "-panel");
} // Update size info after applying panel css
applyCSS(this.element, DEFAULT_PANEL_CSS);
};
return Panel;
}();
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var PanelManager =
/*#__PURE__*/
function () {
function PanelManager(cameraElement, options) {
this.cameraElement = cameraElement;
this.panels = [];
this.clones = [];
this.range = {
min: -1,
max: -1
};
this.length = 0;
this.cloneCount = 0;
this.options = options;
this.lastIndex = options.lastIndex;
}
var __proto = PanelManager.prototype;
__proto.firstPanel = function () {
return this.panels[this.range.min];
};
__proto.lastPanel = function () {
return this.panels[this.range.max];
};
__proto.allPanels = function () {
return this.panels.concat(this.clones.reduce(function (allClones, clones) {
return allClones.concat(clones);
}, []));
};
__proto.originalPanels = function () {
return this.panels;
};
__proto.clonedPanels = function () {
return this.clones;
};
__proto.replacePanels = function (newPanels, newClones) {
this.panels = newPanels;
this.clones = newClones;
this.range = {
min: findIndex(newPanels, function (panel) {
return Boolean(panel);
}),
max: newPanels.length - 1
};
this.length = newPanels.filter(function (panel) {
return Boolean(panel);
}).length;
};
__proto.has = function (index) {
return !!this.panels[index];
};
__proto.get = function (index) {
return this.panels[index];
};
__proto.getPanelCount = function () {
return this.length;
};
__proto.getLastIndex = function () {
return this.lastIndex;
};
__proto.getRange = function () {
return this.range;
};
__proto.getCloneCount = function () {
return this.cloneCount;
};
__proto.setLastIndex = function (lastIndex) {
this.lastIndex = lastIndex;
var firstPanel = this.firstPanel();
var lastPanel = this.lastPanel();
if (!firstPanel || !lastPanel) {
return; // no meaning of updating range & length
} // Remove panels above new last index
var range = this.range;
if (lastPanel.getIndex() > lastIndex) {
var removingPanels = this.panels.splice(lastIndex + 1);
removingPanels.forEach(function (panel) {
return panel.removeElement();
});
this.length -= removingPanels.length;
var firstRemovedPanel = removingPanels.filter(function (panel) {
return !!panel;
})[0];
var possibleLastPanel = firstRemovedPanel.prevSibling;
if (possibleLastPanel) {
range.max = possibleLastPanel.getIndex();
} else {
range.min = -1;
range.max = -1;
}
}
};
__proto.setCloneCount = function (cloneCount) {
this.cloneCount = cloneCount;
};
__proto.append = function (newPanels) {
var range = this.range;
(_a = this.panels).push.apply(_a, newPanels);
if (newPanels.length > 0) {
range.min = Math.max(0, range.min);
range.max += newPanels.length;
this.length += newPanels.length;
}
var _a;
}; // Insert at index
// Returns pushed elements from index, inserting at 'empty' position doesn't push elements behind it
__proto.insert = function (index, newPanels) {
var panels = this.panels;
var range = this.range;
var isCircular = this.options.circular;
var lastIndex = this.lastIndex; // Find first panel that index is greater than inserting index
var nextSibling = this.findFirstPanelFrom(index); // if it's null, element will be inserted at last position
// https://developer.mozilla.org/ko/docs/Web/API/Node/insertBefore#Syntax
var firstPanel = this.firstPanel();
var siblingElement = nextSibling ? nextSibling.getElement() : isCircular && firstPanel ? firstPanel.getClonedPanels()[0].getElement() : null; // Insert panels before sibling element
this.insertNewPanels(newPanels, siblingElement);
var pushedIndex = newPanels.length; // Like when setting index 50 while visible panels are 0, 1, 2
if (index > range.max) {
newPanels.forEach(function (panel, offset) {
panels[index + offset] = panel;
});
} else {
var panelsAfterIndex = panels.slice(index, index + newPanels.length); // Find empty from beginning
var emptyPanelCount = findIndex(panelsAfterIndex, function (panel) {
return !!panel;
});
if (emptyPanelCount < 0) {
// All empty
emptyPanelCount = panelsAfterIndex.length;
}
pushedIndex = newPanels.length - emptyPanelCount; // Insert removing empty panels
panels.splice.apply(panels, [index, emptyPanelCount].concat(newPanels)); // Remove panels after last index
if (panels.length > lastIndex + 1) {
var removedPanels = panels.splice(lastIndex + 1).filter(function (panel) {
return Boolean(panel);
});
removedPanels.forEach(function (panel) {
return panel.removeElement();
});
this.length -= removedPanels.length; // Find first
var newLastIndex = lastIndex - findIndex(this.panels.concat().reverse(), function (panel) {
return !!panel;
}); // Can be filled with empty after newLastIndex
this.panels.splice(newLastIndex + 1);
this.range.max = newLastIndex;
}
} // Update index of previous panels
if (pushedIndex > 0) {
panels.slice(index + newPanels.length).forEach(function (panel) {
panel.setIndex(panel.getIndex() + pushedIndex);
});
}
if (isCircular) {
this.addNewClones(index, newPanels, newPanels.length - pushedIndex, nextSibling);
} // Update state
this.length += newPanels.length;
this.updateIndex(index);
return pushedIndex;
};
__proto.replace = function (index, newPanels) {
var panels = this.panels;
var range = this.range;
var isCircular = this.options.circular; // Find first panel that index is greater than inserting index
var nextSibling = this.findFirstPanelFrom(index + newPanels.length); // if it's null, element will be inserted at last position
// https://developer.mozilla.org/ko/docs/Web/API/Node/insertBefore#Syntax
var firstPanel = this.firstPanel();
var siblingElement = nextSibling ? nextSibling.getElement() : isCircular && firstPanel ? firstPanel.getClonedPanels()[0].getElement() : null; // Insert panels before sibling element
this.insertNewPanels(newPanels, siblingElement);
if (index > range.max) {
// Temporarily insert null at index to use splice()
panels[index] = null;
}
var replacedPanels = panels.splice.apply(panels, [index, newPanels.length].concat(newPanels));
var wasNonEmptyCount = replacedPanels.filter(function (panel) {
return Boolean(panel);
}).length;
replacedPanels.forEach(function (panel) {
if (panel) {
panel.removeElement();
}
}); // Suppose inserting [1, 2, 3] at 0 position when there were [empty, 1]
// So length should be increased by 3(inserting panels) - 1(non-empty panels)
this.length += newPanels.length - wasNonEmptyCount;
this.updateIndex(index);
if (isCircular) {
this.addNewClones(index, newPanels, newPanels.length, nextSibling);
}
};
__proto.remove = function (index, deleteCount) {
if (deleteCount === void 0) {
deleteCount = 1;
}
var isCircular = this.options.circular;
var panels = this.panels;
var clones = this.clones; // Delete count should be equal or larger than 0
deleteCount = Math.max(deleteCount, 0);
var deletedPanels = panels.splice(index, deleteCount).filter(function (panel) {
return !!panel;
});
deletedPanels.forEach(function (panel) {
panel.removeElement();
});
if (isCircular) {
clones.forEach(function (cloneSet) {
cloneSet.splice(index, deleteCount);
});
} // Update indexes
panels.slice(index).forEach(function (panel) {
panel.setIndex(panel.getIndex() - deleteCount);
}); // Check last panel is empty
var lastIndex = panels.length - 1;
if (!panels[lastIndex]) {
var reversedPanels = panels.concat().reverse();
var nonEmptyIndexFromLast = findIndex(reversedPanels, function (panel) {
return !!panel;
});
lastIndex = nonEmptyIndexFromLast < 0 ? -1 // All empty
: lastIndex - nonEmptyIndexFromLast; // Remove all empty panels from last
panels.splice(lastIndex + 1);
if (isCircular) {
clones.forEach(function (cloneSet) {
cloneSet.splice(lastIndex + 1);
});
}
} // Update range & length
this.range = {
min: findIndex(panels, function (panel) {
return !!panel;
}),
max: lastIndex
};
this.length -= deletedPanels.length;
if (this.length <= 0) {
// Reset clones
this.clones = [];
}
return deletedPanels;
};
__proto.chainAllPanels = function () {
var allPanels = this.allPanels().filter(function (panel) {
return !!panel;
});
var allPanelsCount = allPanels.length;
if (allPanelsCount <= 0) {
return;
}
allPanels.forEach(function (panel, idx) {
var prevPanel = idx > 0 ? allPanels[idx - 1] : null;
var nextPanel = idx < allPanelsCount - 1 ? allPanels[idx + 1] : null;
panel.prevSibling = prevPanel;
panel.nextSibling = nextPanel;
});
if (this.options.circular) {
var firstPanel = allPanels[0];
var lastPanel = allPanels[allPanelsCount - 1];
firstPanel.prevSibling = lastPanel;
lastPanel.nextSibling = firstPanel;
}
};
__proto.insertClones = function (cloneIndex, index, clonedPanels, deleteCount) {
if (deleteCount === void 0) {
deleteCount = 0;
}
var clones = this.clones;
var lastIndex = this.lastIndex;
if (!clones[cloneIndex]) {
var newClones_1 = [];
clonedPanels.forEach(function (panel, offset) {
newClones_1[index + offset] = panel;
});
clones[cloneIndex] = newClones_1;
} else {
var insertTarget_1 = clones[cloneIndex];
if (index >= insertTarget_1.length) {
clonedPanels.forEach(function (panel, offset) {
insertTarget_1[index + offset] = panel;
});
} else {
insertTarget_1.splice.apply(insertTarget_1, [index, deleteCount].concat(clonedPanels)); // Remove panels after last index
if (clonedPanels.length > lastIndex + 1) {
clonedPanels.splice(lastIndex + 1);
}
}
}
}; // clones are operating in set
__proto.removeClonesAfter = function (cloneIndex) {
var panels = this.panels;
panels.forEach(function (panel) {
panel.removeClonedPanelsAfter(cloneIndex);
});
this.clones.splice(cloneIndex);
}; // Clear both original & cloned
__proto.clear = function () {
this.panels.forEach(function (panel) {
panel.removeElement();
});
this.panels = [];
this.clones = [];
this.length = 0;
this.range = {
min: -1,
max: -1
};
};
__proto.clearClone = function () {
this.panels.forEach(function (panel) {
panel.removeClonedPanelsAfter(0);
});
this.clones = [];
};
__proto.findPanelOf = function (element) {
var allPanels = this.allPanels();
for (var _i = 0, allPanels_1 = allPanels; _i < allPanels_1.length; _i++) {
var panel = allPanels_1[_i];
if (!panel) {
continue;
}
var panelElement = panel.getElement();
if (panelElement.contains(element)) {
return panel;
}
}
};
__proto.findFirstPanelFrom = function (index) {
for (var _i = 0, _a = this.panels; _i < _a.length; _i++) {
var panel = _a[_i];
if (panel && panel.getIndex() >= index) {
return panel;
}
}
};
__proto.addNewClones = function (index, originalPanels, deleteCount, nextSibling) {
var _this = this;
var cameraElement = this.cameraElement;
var cloneCount = this.getCloneCount();
var lastPanel = this.lastPanel();
var lastPanelClones = lastPanel ? lastPanel.getClonedPanels() : [];
var nextSiblingClones = nextSibling ? nextSibling.getClonedPanels() : [];
var _loop_1 = function (cloneIndex) {
var cloneNextSibling = nextSiblingClones[cloneIndex];
var lastPanelSibling = lastPanelClones[cloneIndex];
var cloneSiblingElement = cloneNextSibling ? cloneNextSibling.getElement() : lastPanelSibling ? lastPanelSibling.getElement().nextElementSibling : null;
var newClones = originalPanels.map(function (panel) {
var clone = panel.clone(cloneIndex);
if (!_this.options.renderExternal) {
cameraElement.insertBefore(clone.getElement(), cloneSiblingElement);
}
return clone;
});
this_1.insertClones(cloneIndex, index, newClones, deleteCount);
};
var this_1 = this;
for (var _i = 0, _a = counter(cloneCount); _i < _a.length; _i++) {
var cloneIndex = _a[_i];
_loop_1(cloneIndex);
}
};
__proto.updateIndex = function (insertingIndex) {
var panels = this.panels;
var range = this.range;
var newLastIndex = panels.length - 1;
if (newLastIndex > range.max) {
range.max = newLastIndex;
}
if (insertingIndex < range.min || range.min < 0) {
range.min = insertingIndex;
}
};
__proto.insertNewPanels = function (newPanels, siblingElement) {
if (!this.options.renderExternal) {
var fragment_1 = document.createDocumentFragment();
newPanels.forEach(function (panel) {
return fragment_1.appendChild(panel.getElement());
});
this.cameraElement.insertBefore(fragment_1, siblingElement);
}
};
return PanelManager;
}();
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var State =
/*#__PURE__*/
function () {
function State() {
this.delta = 0;
this.direction = null;
this.targetPanel = null;
this.lastPosition = 0;
}
var __proto = State.prototype;
__proto.onEnter = function (prevState) {
this.delta = prevState.delta;
this.direction = prevState.direction;
this.targetPanel = prevState.targetPanel;
this.lastPosition = prevState.lastPosition;
};
__proto.onExit = function (nextState) {// DO NOTHING
};
__proto.onHold = function (e, context) {// DO NOTHING
};
__proto.onChange = function (e, context) {// DO NOTHING
};
__proto.onRelease = function (e, context) {// DO NOTHING
};
__proto.onAnimationEnd = function (e, context) {// DO NOTHING
};
__proto.onFinish = function (e, context) {// DO NOTHING
};
return State;
}();
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var IdleState =
/*#__PURE__*/
function (_super) {
__extends(IdleState, _super);
function IdleState() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = STATE_TYPE.IDLE;
_this.holding = false;
_this.playing = false;
return _this;
}
var __proto = IdleState.prototype;
__proto.onEnter = function () {
this.direction = null;
this.targetPanel = null;
this.delta = 0;
this.lastPosition = 0;
};
__proto.onHold = function (e, _a) {
var flicking = _a.flicking,
viewport = _a.viewport,
triggerEvent = _a.triggerEvent,
transitTo = _a.transitTo; // Shouldn't do any action until any panels on flicking area
if (flicking.getPanelCount() <= 0) {
if (viewport.options.infinite) {
viewport.moveCamera(viewport.getCameraPosition(), e);
}
transitTo(STATE_TYPE.DISABLED);
return;
}
this.lastPosition = viewport.getCameraPosition();
triggerEvent(EVENTS.HOLD_START, e, true).onSuccess(function () {
transitTo(STATE_TYPE.HOLDING);
}).onStopped(function () {
transitTo(STATE_TYPE.DISABLED);
});
}; // By methods call
__proto.onChange = function (e, context) {
var triggerEvent = context.triggerEvent,
transitTo = context.transitTo;
triggerEvent(EVENTS.MOVE_START, e, false).onSuccess(function () {
// Trigger AnimatingState's onChange, to trigger "move" event immediately
transitTo(STATE_TYPE.ANIMATING).onChange(e, context);
}).onStopped(function () {
transitTo(STATE_TYPE.DISABLED);
});
};
return IdleState;
}(State);
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var HoldingState =
/*#__PURE__*/
function (_super) {
__extends(HoldingState, _super);
function HoldingState() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = STATE_TYPE.HOLDING;
_this.holding = true;
_this.playing = true;
_this.releaseEvent = null;
return _this;
}
var __proto = HoldingState.prototype;
__proto.onChange = function (e, context) {
var flicking = context.flicking,
triggerEvent = context.triggerEvent,
transitTo = context.transitTo;
var offset = flicking.options.horizontal ? e.inputEvent.offsetX : e.inputEvent.offsetY;
this.direction = offset < 0 ? DIRECTION.NEXT : DIRECTION.PREV;
triggerEvent(EVENTS.MOVE_START, e, true).onSuccess(function () {
// Trigger DraggingState's onChange, to trigger "move" event immediately
transitTo(STATE_TYPE.DRAGGING).onChange(e, context);
}).onStopped(function () {
transitTo(STATE_TYPE.DISABLED);
});
};
__proto.onRelease = function (e, context) {
var viewport = context.viewport,
triggerEvent = context.triggerEvent,
transitTo = context.transitTo;
triggerEvent(EVENTS.HOLD_END, e, true);
if (e.delta.flick !== 0) {
// Sometimes "release" event on axes triggered before "change" event
// Especially if user flicked panel fast in really short amount of time
// if delta is not zero, that means above case happened.
// Event flow should be HOLD_START -> MOVE_START -> MOVE -> HOLD_END
// At least one move event should be included between holdStart and holdEnd
e.setTo({
flick: viewport.getCameraPosition()
}, 0);
transitTo(STATE_TYPE.IDLE);
return;
} // Can't handle select event here,
// As "finish" axes event happens
this.releaseEvent = e;
};
__proto.onFinish = function (e, _a) {
var viewport = _a.viewport,
triggerEvent = _a.triggerEvent,
transitTo = _a.transitTo; // Should transite to IDLE state before select event
// As user expects hold is already finished
transitTo(STATE_TYPE.IDLE);
if (!this.releaseEvent) {
return;
} // Handle release event here
// To prevent finish event called twice
var releaseEvent = this.releaseEvent; // Static click
var clickedElement = releaseEvent.inputEvent.srcEvent.target;
var clickedPanel = viewport.panelManager.findPanelOf(clickedElement);
var cameraPosition = viewport.getCameraPosition();
if (clickedPanel) {
var clickedPanelPosition = clickedPanel.getPosition();
var direction = clickedPanelPosition > cameraPosition ? DIRECTION.NEXT : clickedPanelPosition < cameraPosition ? DIRECTION.PREV : null; // Don't provide axes event, to use axes instance instead
triggerEvent(EVENTS.SELECT, null, true, {
direction: direction,
index: clickedPanel.getIndex(),
panel: clickedPanel
});
}
};
return HoldingState;
}(State);
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var DraggingState =
/*#__PURE__*/
function (_super) {
__extends(DraggingState, _super);
function DraggingState() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = STATE_TYPE.DRAGGING;
_this.holding = true;
_this.playing = true;
return _this;
}
var __proto = DraggingState.prototype;
__proto.onChange = function (e, _a) {
var moveCamera = _a.moveCamera,
transitTo = _a.transitTo;
if (!e.delta.flick) {
return;
}
moveCamera(e).onStopped(function () {
transitTo(STATE_TYPE.DISABLED);
});
};
__proto.onRelease = function (e, context) {
var flicking = context.flicking,
viewport = context.viewport,
triggerEvent = context.triggerEvent,
transitTo = context.transitTo,
stopCamera = context.stopCamera;
var delta = this.delta;
var absDelta = Math.abs(delta);
var options = flicking.options;
var horizontal = options.horizontal;
var moveType = viewport.moveType;
var inputEvent = e.inputEvent;
var velocity = horizontal ? inputEvent.velocityX : inputEvent.velocityY;
var inputDelta = horizontal ? inputEvent.deltaX : inputEvent.deltaY;
var isNextDirection = Math.abs(velocity) > 1 ? velocity < 0 : absDelta > 0 ? delta > 0 : inputDelta < 0;
var swipeDistance = viewport.options.bound ? Math.max(absDelta, Math.abs(inputDelta)) : absDelta;
var swipeAngle = inputEvent.deltaX ? Math.abs(180 * Math.atan(inputEvent.deltaY / inputEvent.deltaX) / Math.PI) : 90;
var belowAngleThreshold = horizontal ? swipeAngle <= options.thresholdAngle : swipeAngle > options.thresholdAngle;
var overThreshold = swipeDistance >= options.threshold && belowAngleThreshold;
var moveTypeContext = {
viewport: viewport,
axesEvent: e,
state: this,
swipeDistance: swipeDistance,
isNextDirection: isNextDirection
}; // Update last position to cope with Axes's animating behavior
// Axes uses start position when animation start
triggerEvent(EVENTS.HOLD_END, e, true);
var targetPanel = this.targetPanel;
if (!overThreshold && targetPanel) {
// Interrupted while animating
var interruptDestInfo = moveType.findPanelWhenInterrupted(moveTypeContext);
viewport.moveTo(interruptDestInfo.panel, interruptDestInfo.destPos, interruptDestInfo.eventType, e, interruptDestInfo.duration);
transitTo(STATE_TYPE.ANIMATING);
return;
}
var currentPanel = viewport.getCurrentPanel();
var nearestPanel = viewport.getNearestPanel();
if (!currentPanel || !nearestPanel) {
// There're no panels
e.stop();
transitTo(STATE_TYPE.IDLE);
return;
}
var destInfo = overThreshold ? moveType.findTargetPanel(moveTypeContext) : moveType.findRestorePanel(moveTypeContext);
viewport.moveTo(destInfo.panel, destInfo.destPos, destInfo.eventType, e, destInfo.duration).onSuccess(function () {
transitTo(STATE_TYPE.ANIMATING);
}).onStopped(function () {
transitTo(STATE_TYPE.DISABLED);
stopCamera(e);
});
};
return DraggingState;
}(State);
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var AnimatingState =
/*#__PURE__*/
function (_super) {
__extends(AnimatingState, _super);
function AnimatingState() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = STATE_TYPE.ANIMATING;
_this.holding = false;
_this.playing = true;
return _this;
}
var __proto = AnimatingState.prototype;
__proto.onHold = function (e, _a) {
var viewport = _a.viewport,
triggerEvent = _a.triggerEvent,
transitTo = _a.transitTo;
var options = viewport.options;
var scrollArea = viewport.getScrollArea();
var scrollAreaSize = viewport.getScrollAreaSize();
var loopCount = Math.floor((this.lastPosition + this.delta - scrollArea.prev) / scrollAreaSize);
var targetPanel = this.targetPanel;
if (options.circular && loopCount !== 0 && targetPanel) {
var cloneCount = viewport.panelManager.getCloneCount();
var originalTargetPosition = targetPanel.getPosition(); // cloneIndex is from -1 to cloneCount - 1
var newCloneIndex = circulate(targetPanel.getCloneIndex() - loopCount, -1, cloneCount - 1, true);
var newTargetPosition = originalTargetPosition - loopCount * scrollAreaSize;
var newTargetPanel = targetPanel.getIdenticalPanels()[newCloneIndex + 1].clone(newCloneIndex, true); // Set new target panel considering looped count
newTargetPanel.setPosition(newTargetPosition);
this.targetPanel = newTargetPanel;
} // Reset last position and delta
this.delta = 0;
this.lastPosition = viewport.getCameraPosition(); // Update current panel as current nearest panel
viewport.setCurrentPanel(viewport.getNearestPanel());
triggerEvent(EVENTS.HOLD_START, e, true).onSuccess(function () {
transitTo(STATE_TYPE.DRAGGING);
}).onStopped(function () {
transitTo(STATE_TYPE.DISABLED);
});
};
__proto.onChange = function (e, _a) {
var moveCamera = _a.moveCamera,
transitTo = _a.transitTo;
if (!e.delta.flick) {
return;
}
moveCamera(e).onStopped(function () {
transitTo(STATE_TYPE.DISABLED);
});
};
__proto.onFinish = function (e, _a) {
var flicking = _a.flicking,
viewport = _a.viewport,
triggerEvent = _a.triggerEvent,
transitTo = _a.transitTo;
var isTrusted = e && e.isTrusted;
viewport.options.bound ? viewport.setCurrentPanel(this.targetPanel) : viewport.setCurrentPanel(viewport.getNearestPanel());
transitTo(STATE_TYPE.IDLE);
triggerEvent(EVENTS.MOVE_END, e, isTrusted, {
direction: this.direction
});
if (flicking.options.adaptive) {
viewport.updateAdaptiveSize();
}
};
return AnimatingState;
}(State);
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var DisabledState =
/*#__PURE__*/
function (_super) {
__extends(DisabledState, _super);
function DisabledState() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = STATE_TYPE.DISABLED;
_this.holding = false;
_this.playing = true;
return _this;
}
var __proto = DisabledState.prototype;
__proto.onAnimationEnd = function (e, _a) {
var transitTo = _a.transitTo;
transitTo(STATE_TYPE.IDLE);
};
__proto.onChange = function (e, _a) {
var viewport = _a.viewport,
transitTo = _a.transitTo; // Can stop Axes's change event
e.stop(); // Should update axes position as it's already changed at this moment
viewport.updateAxesPosition(viewport.getCameraPosition());
transitTo(STATE_TYPE.IDLE);
};
__proto.onRelease = function (e, _a) {
var transitTo = _a.transitTo; // This is needed when stopped hold start event
if (e.delta.flick === 0) {
transitTo(STATE_TYPE.IDLE);
}
};
return DisabledState;
}(State);
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var StateMachine =
/*#__PURE__*/
function () {
function StateMachine() {
var _this = this;
this.state = new IdleState();
this.transitTo = function (nextStateType) {
var currentState = _this.state;
if (currentState.type !== nextStateType) {
var nextState = void 0;
switch (nextStateType) {
case STATE_TYPE.IDLE:
nextState = new IdleState();
break;
case STATE_TYPE.HOLDING:
nextState = new HoldingState();
break;
case STATE_TYPE.DRAGGING:
nextState = new DraggingState();
break;
case STATE_TYPE.ANIMATING:
nextState = new AnimatingState();
break;
case STATE_TYPE.DISABLED:
nextState = new DisabledState();
break;
}
currentState.onExit(nextState);
nextState.onEnter(currentState);
_this.state = nextState;
}
return _this.state;
};
}
var __proto = StateMachine.prototype;
__proto.fire = function (eventType, e, context) {
var currentState = this.state;
switch (eventType) {
case AXES_EVENTS.HOLD:
currentState.onHold(e, context);
break;
case AXES_EVENTS.CHANGE:
currentState.onChange(e, context);
break;
case AXES_EVENTS.RELEASE:
currentState.onRelease(e, context);
break;
case AXES_EVENTS.ANIMATION_END:
currentState.onAnimationEnd(e, context);
break;
case AXES_EVENTS.FINISH:
currentState.onFinish(e, context);
break;
}
};
__proto.getState = function () {
return this.state;
};
return StateMachine;
}();
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var MoveType =
/*#__PURE__*/
function () {
function MoveType() {}
var __proto = MoveType.prototype;
__proto.is = function (type) {
return type === this.type;
};
__proto.findRestorePanel = function (ctx) {
var viewport = ctx.viewport;
var options = viewport.options;
var panel = options.circular ? this.findRestorePanelInCircularMode(ctx) : viewport.getCurrentPanel();
return {
panel: panel,
destPos: viewport.findEstimatedPosition(panel),
duration: options.duration,
eventType: EVENTS.RESTORE
};
};
__proto.findPanelWhenInterrupted = function (ctx) {
var state = ctx.state,
viewport = ctx.viewport;
var targetPanel = state.targetPanel;
return {
panel: targetPanel,
destPos: viewport.findEstimatedPosition(targetPanel),
duration: viewport.options.duration,
eventType: ""
};
}; // Calculate minimum distance to "change" panel
__proto.calcBrinkOfChange = function (ctx) {
var viewport = ctx.viewport,
isNextDirection = ctx.isNextDirection;
var options = viewport.options;
var currentPanel = viewport.getCurrentPanel();
var halfGap = options.gap / 2;
var relativeAnchorPosition = currentPanel.getRelativeAnchorPosition(); // Minimum distance needed to decide prev/next panel as nearest
/*
* | Prev | Next |
* |--------|--------------|
* [][ |<-Anchor ][] <- Panel + Half-Gap
*/
var minimumDistanceToChange = isNextDirection ? currentPanel.getSize() - relativeAnchorPosition + halfGap : relativeAnchorPosition + halfGap;
minimumDistanceToChange = Math.max(minimumDistanceToChange, options.threshold);
return minimumDistanceToChange;
};
__proto.findRestorePanelInCircularMode = function (ctx) {
var viewport = ctx.viewport;
var originalPanel = viewport.getCurrentPanel().getOriginalPanel();
var hangerPosition = viewport.getHangerPosition();
var firstClonedPanel = originalPanel.getIdenticalPanels()[1];
var lapped = Math.abs(originalPanel.getAnchorPosition() - hangerPosition) > Math.abs(firstClonedPanel.getAnchorPosition() - hangerPosition);
return !ctx.isNextDirection && lapped ? firstClonedPanel : originalPanel;
};
return MoveType;
}();
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var Snap =
/*#__PURE__*/
function (_super) {
__extends(Snap, _super);
function Snap(count) {
var _this = _super.call(this) || this;
_this.type = MOVE_TYPE.SNAP;
_this.count = count;
return _this;
}
var __proto = Snap.prototype;
__proto.findTargetPanel = function (ctx) {
var viewport = ctx.viewport,
axesEvent = ctx.axesEvent,
swipeDistance = ctx.swipeDistance;
var snapCount = this.count;
var eventDelta = Math.abs(axesEvent.delta.flick);
var currentPanel = viewport.getCurrentPanel();
var nearestPanel = viewport.getNearestPanel();
var minimumDistanceToChange = this.calcBrinkOfChange(ctx); // This can happen when bounce is 0
var shouldMoveWhenBounceIs0 = viewport.canSetBoundMode() && nearestPanel.getIndex() === currentPanel.getIndex();
var shouldMoveToAdjacent = !viewport.isOutOfBound() && (swipeDistance <= minimumDistanceToChange || shouldMoveWhenBounceIs0);
if (snapCount > 1 && eventDelta > minimumDistanceToChange) {
return this.findSnappedPanel(ctx);
} else if (shouldMoveToAdjacent) {
return this.findAdjacentPanel(ctx);
} else {
return {
panel: nearestPanel,
duration: viewport.options.duration,
destPos: viewport.findEstimatedPosition(nearestPanel),
eventType: swipeDistance <= minimumDistanceToChange ? EVENTS.RESTORE : EVENTS.CHANGE
};
}
};
__proto.findSnappedPanel = function (ctx) {
var axesEvent = ctx.axesEvent,
viewport = ctx.viewport,
state = ctx.state,
isNextDirection = ctx.isNextDirection;
var eventDelta = Math.abs(axesEvent.delta.flick);
var minimumDistanceToChange = this.calcBrinkOfChange(ctx);
var snapCount = this.count;
var options = viewport.options;
var scrollAreaSize = viewport.getScrollAreaSize();
var halfGap = options.gap / 2;
var estimatedHangerPos = axesEvent.destPos.flick + viewport.getRelativeHangerPosition();
var panelToMove = viewport.getNearestPanel();
var cycleIndex = panelToMove.getCloneIndex() + 1; // 0(original) or 1(clone)
var passedPanelCount = 0;
while (passedPanelCount < snapCount) {
// Since panelToMove holds also cloned panels, we should use original panel's position
var originalPanel = panelToMove.getOriginalPanel();
var panelPosition = originalPanel.getPosition() + cycleIndex * scrollAreaSize;
var panelSize = originalPanel.getSize();
var panelNextPosition = panelPosition + panelSize + halfGap;
var panelPrevPosition = panelPosition - halfGap; // Current panelToMove contains destPos
if (isNextDirection && panelNextPosition > estimatedHangerPos || !isNextDirection && panelPrevPosition < estimatedHangerPos) {
break;
}
var siblingPanel = isNextDirection ? panelToMove.nextSibling : panelToMove.prevSibling;
if (!siblingPanel) {
break;
}
var panelIndex = panelToMove.getIndex();
var siblingIndex = siblingPanel.getIndex();
if (isNextDirection && siblingIndex <= panelIndex || !isNextDirection && siblingIndex >= panelIndex) {
cycleIndex = isNextDirection ? cycleIndex + 1 : cycleIndex - 1;
}
panelToMove = siblingPanel;
passedPanelCount += 1;
}
var originalPosition = panelToMove.getOriginalPanel().getPosition();
if (cycleIndex !== 0) {
panelToMove = panelToMove.clone(panelToMove.getCloneIndex(), true);
panelToMove.setPosition(originalPosition + cycleIndex * scrollAreaSize);
}
var defaultDuration = viewport.options.duration;
var duration = clamp(axesEvent.duration, defaultDuration, defaultDuration * passedPanelCount);
return {
panel: panelToMove,
destPos: viewport.findEstimatedPosition(panelToMove),
duration: duration,
eventType: Math.max(eventDelta, state.delta) > minimumDistanceToChange ? EVENTS.CHANGE : EVENTS.RESTORE
};
};
__proto.findAdjacentPanel = function (ctx) {
var viewport = ctx.viewport,
isNextDirection = ctx.isNextDirection;
var options = viewport.options;
var currentIndex = viewport.getCurrentIndex();
var currentPanel = viewport.panelManager.get(currentIndex);
var hangerPosition = viewport.getHangerPosition();
var scrollArea = viewport.getScrollArea();
var firstClonedPanel = currentPanel.getIdenticalPanels()[1];
var lapped = options.circular && Math.abs(currentPanel.getAnchorPosition() - hangerPosition) > Math.abs(firstClonedPanel.getAnchorPosition() - hangerPosition); // If lapped in circular mode, use first cloned panel as base panel
var basePanel = lapped ? firstClonedPanel : currentPanel;
var basePosition = basePanel.getPosition();
var adjacentPanel = isNextDirection ? basePanel.nextSibling : basePanel.prevSibling;
var eventType = adjacentPanel ? EVENTS.CHANGE : EVENTS.RESTORE;
var panelToMove = adjacentPanel ? adjacentPanel : basePanel;
var targetRelativeAnchorPosition = panelToMove.getRelativeAnchorPosition();
var estimatedPanelPosition = options.circular ? isNextDirection ? basePosition + basePanel.getSize() + targetRelativeAnchorPosition + options.gap : basePosition - (panelToMove.getSize() - targetRelativeAnchorPosition) - options.gap : panelToMove.getAnchorPosition();
var estimatedPosition = estimatedPanelPosition - viewport.getRelativeHangerPosition();
var destPos = viewport.canSetBoundMode() ? clamp(estimatedPosition, scrollArea.prev, scrollArea.next) : estimatedPosition;
return {
panel: panelToMove,
destPos: destPos,
duration: options.duration,
eventType: eventType
};
};
return Snap;
}(MoveType);
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var FreeScroll =
/*#__PURE__*/
function (_super) {
__extends(FreeScroll, _super);
function FreeScroll() {
var _this = // Set snap count to Infinity
_super.call(this, Infinity) || this;
_this.type = MOVE_TYPE.FREE_SCROLL;
return _this;
}
var __proto = FreeScroll.prototype;
__proto.findTargetPanel = function (ctx) {
var axesEvent = ctx.axesEvent,
state = ctx.state,
viewport = ctx.viewport;
var destPos = axesEvent.destPos.flick;
var minimumDistanceToChange = this.calcBrinkOfChange(ctx);
var scrollArea = viewport.getScrollArea();
var currentPanel = viewport.getCurrentPanel();
var options = viewport.options;
var delta = Math.abs(axesEvent.delta.flick + state.delta);
if (delta > minimumDistanceToChange) {
var destInfo = _super.prototype.findSnappedPanel.call(this, ctx);
destInfo.duration = axesEvent.duration;
destInfo.destPos = destPos;
destInfo.eventType = !options.circular && destInfo.panel === currentPanel ? "" : EVENTS.CHANGE;
return destInfo;
} else {
var estimatedPosition = options.circular ? circulate(destPos, scrollArea.prev, scrollArea.next, false) : destPos;
estimatedPosition = clamp(estimatedPosition, scrollArea.prev, scrollArea.next);
estimatedPosition += viewport.getRelativeHangerPosition();
var estimatedPanel = viewport.findNearestPanelAt(estimatedPosition);
return {
panel: estimatedPanel,
destPos: destPos,
duration: axesEvent.duration,
eventType: ""
};
}
};
__proto.findRestorePanel = function (ctx) {
return this.findTargetPanel(ctx);
};
__proto.findPanelWhenInterrupted = function (ctx) {
var viewport = ctx.viewport;
return {
panel: viewport.getNearestPanel(),
destPos: viewport.getCameraPosition(),
duration: 0,
eventType: ""
};
};
__proto.calcBrinkOfChange = function (ctx) {
var viewport = ctx.viewport,
isNextDirection = ctx.isNextDirection;
var options = viewport.options;
var currentPanel = viewport.getCurrentPanel();
var halfGap = options.gap / 2;
var lastPosition = viewport.stateMachine.getState().lastPosition;
var currentPanelPosition = currentPanel.getPosition(); // As camera can stop anywhere in free scroll mode,
// minimumDistanceToChange should be calculated differently.
// Ref #191(https://github.com/naver/egjs-flicking/issues/191)
var lastHangerPosition = lastPosition + viewport.getRelativeHangerPosition();
var scrollAreaSize = viewport.getScrollAreaSize();
var minimumDistanceToChange = isNextDirection ? currentPanelPosition + currentPanel.getSize() - lastHangerPosition + halfGap : lastHangerPosition - currentPanelPosition + halfGap;
minimumDistanceToChange = Math.abs(minimumDistanceToChange % scrollAreaSize);
return Math.min(minimumDistanceToChange, scrollAreaSize - minimumDistanceToChange);
};
return FreeScroll;
}(Snap);
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var Viewport =
/*#__PURE__*/
function () {
function Viewport(flicking, options, triggerEvent) {
var _this = this;
this.plugins = [];
this.stopCamera = function (axesEvent) {
if (axesEvent && axesEvent.setTo) {
axesEvent.setTo({
flick: _this.state.position
}, 0);
}
_this.stateMachine.transitTo(STATE_TYPE.IDLE);
};
this.flicking = flicking;
this.triggerEvent = triggerEvent;
this.state = {
size: 0,
position: 0,
panelMaintainRatio: 0,
relativeHangerPosition: 0,
scrollArea: {
prev: 0,
next: 0
},
translate: TRANSFORM,
infiniteThreshold: 0,
checkedIndexes: [],
isViewportGiven: false,
isCameraGiven: false,
originalViewportStyle: {
className: null,
style: null
},
originalCameraStyle: {
className: null,
style: null
}
};
this.options = options;
this.stateMachine = new StateMachine();
this.build();
}
var __proto = Viewport.prototype;
__proto.moveTo = function (panel, destPos, eventType, axesEvent, duration) {
var _this = this;
if (duration === void 0) {
duration = this.options.duration;
}
var state = this.state;
var currentState = this.stateMachine.getState();
var currentPosition = state.position;
var isTrusted = axesEvent ? axesEvent.isTrusted : false;
var direction = destPos === currentPosition ? null : destPos > currentPosition ? DIRECTION.NEXT : DIRECTION.PREV;
var eventResult;
if (eventType === EVENTS.CHANGE) {
eventResult = this.triggerEvent(EVENTS.CHANGE, axesEvent, isTrusted, {
index: panel.getIndex(),
panel: panel,
direction: direction
});
} else if (eventType === EVENTS.RESTORE) {
eventResult = this.triggerEvent(EVENTS.RESTORE, axesEvent, isTrusted);
} else {
eventResult = {
onSuccess: function (callback) {
callback();
return this;
},
onStopped: function () {
return this;
}
};
}
eventResult.onSuccess(function () {
currentState.delta = 0;
currentState.lastPosition = _this.getCameraPosition();
currentState.targetPanel = panel;
currentState.direction = destPos === currentPosition ? null : destPos > currentPosition ? DIRECTION.NEXT : DIRECTION.PREV;
if (destPos === currentPosition) {
// no move
_this.nearestPanel = panel;
_this.currentPanel = panel;
}
if (axesEvent && axesEvent.setTo) {
// freeScroll only occurs in release events
axesEvent.setTo({
flick: destPos
}, duration);
} else {
_this.axes.setTo({
flick: destPos
}, duration);
}
});
return eventResult;
};
__proto.moveCamera = function (pos, axesEvent) {
var state = this.state;
var options = this.options;
var transform = state.translate.name; // Update position & nearestPanel
state.position = pos;
this.nearestPanel = this.findNearestPanel();
var nearestPanel = this.nearestPanel;
var originalNearestPosition = nearestPanel ? nearestPanel.getPosition() : 0; // From 0(panel position) to 1(panel position + panel size)
// When it's on gap area value will be (val > 1 || val < 0)
if (nearestPanel) {
var hangerPosition = this.getHangerPosition();
var panelPosition = nearestPanel.getPosition();
var panelSize = nearestPanel.getSize();
var halfGap = options.gap / 2; // As panel's range is from panel position - half gap ~ panel pos + panel size + half gap
state.panelMaintainRatio = (hangerPosition - panelPosition + halfGap) / (panelSize + 2 * halfGap);
} else {
state.panelMaintainRatio = 0;
}
this.checkNeedPanel(axesEvent); // Possibly modified after need panel, if it's looped
var modifiedNearestPosition = nearestPanel ? nearestPanel.getPosition() : 0;
pos += modifiedNearestPosition - originalNearestPosition;
state.position = pos;
var moveVector = options.horizontal ? [-pos, 0] : [0, -pos];
var moveCoord = moveVector.map(function (coord) {
return Math.round(coord) + "px";
}).join(", ");
this.cameraElement.style[transform] = state.translate.has3d ? "translate3d(" + moveCoord + ", 0px)" : "translate(" + moveCoord + ")";
};
__proto.resize = function () {
var panelManager = this.panelManager;
this.updateSize();
this.updateOriginalPanelPositions();
this.updateAdaptiveSize();
this.updateScrollArea(); // Clone panels in circular mode
if (this.options.circular && panelManager.getPanelCount() > 0) {
this.clonePanels();
this.updateClonedPanelPositions();
}
panelManager.chainAllPanels();
this.updateCameraPosition();
this.updatePlugins();
}; // Find nearest anchor from current hanger position
__proto.findNearestPanel = function () {
var state = this.state;
var panelManager = this.panelManager;
var hangerPosition = this.getHangerPosition();
if (this.isOutOfBound()) {
var position = state.position;
return position <= state.scrollArea.prev ? panelManager.firstPanel() : panelManager.lastPanel();
}
return this.findNearestPanelAt(hangerPosition);
};
__proto.findNearestPanelAt = function (position) {
var panelManager = this.panelManager;
var allPanels = panelManager.allPanels();
var minimumDistance = Infinity;
var nearestPanel;
for (var _i = 0, allPanels_1 = allPanels; _i < allPanels_1.length; _i++) {
var panel = allPanels_1[_i];
if (!panel) {
continue;
}
var prevPosition = panel.getPosition();
var nextPosition = prevPosition + panel.getSize(); // Use shortest distance from panel's range
var distance = isBetween(position, prevPosition, nextPosition) ? 0 : Math.min(Math.abs(prevPosition - position), Math.abs(nextPosition - position));
if (distance > minimumDistance) {
break;
} else if (distance === minimumDistance) {
var minimumAnchorDistance = Math.abs(position - nearestPanel.getAnchorPosition());
var anchorDistance = Math.abs(position - panel.getAnchorPosition());
if (anchorDistance > minimumAnchorDistance) {
break;
}
}
minimumDistance = distance;
nearestPanel = panel;
}
return nearestPanel;
};
__proto.findNearestIdenticalPanel = function (panel) {
var nearest = panel;
var shortestDistance = Infinity;
var hangerPosition = this.getHangerPosition();
var identicals = panel.getIdenticalPanels();
identicals.forEach(function (identical) {
var anchorPosition = identical.getAnchorPosition();
var distance = Math.abs(anchorPosition - hangerPosition);
if (distance < shortestDistance) {
nearest = identical;
shortestDistance = distance;
}
});
return nearest;
}; // Find shortest camera position that distance is minimum
__proto.findShortestPositionToPanel = function (panel) {
var state = this.state;
var options = this.options;
var anchorPosition = panel.getAnchorPosition();
var hangerPosition = this.getHangerPosition();
var distance = Math.abs(hangerPosition - anchorPosition);
var scrollAreaSize = state.scrollArea.next - state.scrollArea.prev;
if (!options.circular) {
var position = anchorPosition - state.relativeHangerPosition;
return this.canSetBoundMode() ? clamp(position, state.scrollArea.prev, state.scrollArea.next) : position;
} else {
// If going out of viewport border is more efficient way of moving, choose that position
return distance <= scrollAreaSize - distance ? anchorPosition - state.relativeHangerPosition : anchorPosition > hangerPosition // PREV TO NEXT
? anchorPosition - state.relativeHangerPosition - scrollAreaSize // NEXT TO PREV
: anchorPosition - state.relativeHangerPosition + scrollAreaSize;
}
};
__proto.findEstimatedPosition = function (panel) {
var scrollArea = this.getScrollArea();
var estimatedPosition = panel.getAnchorPosition() - this.getRelativeHangerPosition();
estimatedPosition = this.canSetBoundMode() ? clamp(estimatedPosition, scrollArea.prev, scrollArea.next) : estimatedPosition;
return estimatedPosition;
};
__proto.enable = function () {
this.panInput.enable();
};
__proto.disable = function () {
this.panInput.disable();
};
__proto.insert = function (index, element) {
var _this = this;
var lastIndex = this.panelManager.getLastIndex(); // Index should not below 0
if (index < 0 || index > lastIndex) {
return [];
}
var state = this.state;
var parsedElements = parseElement(element);
var panels = parsedElements.map(function (el, idx) {
return new Panel(el, index + idx, _this);
}).slice(0, lastIndex - index + 1);
if (panels.length <= 0) {
return [];
}
var pushedIndex = this.panelManager.insert(index, panels);
if (!this.currentPanel) {
this.currentPanel = panels[0];
} // Update checked indexes in infinite mode
this.updateCheckedIndexes({
min: index,
max: index
});
state.checkedIndexes.forEach(function (indexes, idx) {
var min = indexes[0],
max = indexes[1];
if (index < min) {
// Push checked index
state.checkedIndexes.splice(idx, 1, [min + pushedIndex, max + pushedIndex]);
}
});
this.resize();
return panels;
};
__proto.replace = function (index, element) {
var _this = this;
var panelManager = this.panelManager;
var lastIndex = panelManager.getLastIndex(); // Index should not below 0
if (index < 0 || index > lastIndex) {
return [];
}
var parsedElements = parseElement(element);
var panels = parsedElements.map(function (el, idx) {
return new Panel(el, index + idx, _this);
}).slice(0, lastIndex - index + 1);
if (panels.length <= 0) {
return [];
}
panelManager.replace(index, panels);
var currentPanel = this.currentPanel;
var wasEmpty = !currentPanel;
if (wasEmpty) {
this.currentPanel = panels[0];
} else if (isBetween(currentPanel.getIndex(), index, index + panels.length - 1)) {
// Current panel is replaced
this.currentPanel = panelManager.get(currentPanel.getIndex());
} // Update checked indexes in infinite mode
this.updateCheckedIndexes({
min: index,
max: index + panels.length - 1
});
this.resize();
var isFreeScroll = this.options.moveType.type === "freeScroll";
if (isFreeScroll && wasEmpty) {
this.moveTo(this.currentPanel, this.findEstimatedPosition(this.currentPanel), "", null, 0);
}
return panels;
};
__proto.remove = function (index, deleteCount) {
if (deleteCount === void 0) {
deleteCount = 1;
} // Index should not below 0
index = Math.max(index, 0);
var panelManager = this.panelManager;
var currentIndex = this.getCurrentIndex();
var removedPanels = panelManager.remove(index, deleteCount);
if (isBetween(currentIndex, index, index + deleteCount - 1)) {
// Current panel is removed
// Use panel at removing index - 1 as new current panel if it exists
var newCurrentIndex = Math.max(index - 1, panelManager.getRange().min);
this.currentPanel = panelManager.get(newCurrentIndex);
} // Update checked indexes in infinite mode
if (deleteCount > 0) {
// Check whether removing index will affect checked indexes
// Suppose index 0 is empty and removed index 1, then checked index 0 should be deleted and vice versa.
this.updateCheckedIndexes({
min: index - 1,
max: index + deleteCount
});
}
this.resize();
return removedPanels;
};
__proto.updateAdaptiveSize = function () {
var options = this.options;
var horizontal = options.horizontal;
var currentPanel = this.getCurrentPanel();
if (!currentPanel) {
return;
}
var sizeToApply;
if (options.adaptive) {
var panelBbox = currentPanel.getBbox();
sizeToApply = horizontal ? panelBbox.height : panelBbox.width;
} else {
// Find minimum height of panels to maximum panel size
var maximumPanelSize = this.panelManager.originalPanels().reduce(function (maximum, panel) {
var panelBbox = panel.getBbox();
return Math.max(maximum, horizontal ? panelBbox.height : panelBbox.width);
}, 0);
sizeToApply = maximumPanelSize;
}
var viewportStyle = this.viewportElement.style;
if (horizontal) {
viewportStyle.height = sizeToApply + "px";
viewportStyle.minHeight = "100%";
viewportStyle.width = "100%";
} else {
viewportStyle.width = sizeToApply + "px";
viewportStyle.minWidth = "100%";
viewportStyle.height = "100%";
}
};
__proto.destroy = function (option) {
var state = this.state;
var wrapper = this.flicking.getElement();
var viewportElement = this.viewportElement;
var cameraElement = this.cameraElement;
var originalPanels = this.panelManager.originalPanels();
this.removePlugins(this.plugins);
if (!option.preserveUI) {
restoreStyle(viewportElement, state.originalViewportStyle);
restoreStyle(cameraElement, state.originalCameraStyle);
if (!state.isCameraGiven && !this.options.renderExternal) {
var topmostElement_1 = state.isViewportGiven ? viewportElement : wrapper;
var deletingElement = state.isViewportGiven ? cameraElement : viewportElement;
originalPanels.forEach(function (panel) {
topmostElement_1.appendChild(panel.getElement());
});
topmostElement_1.removeChild(deletingElement);
}
}
this.axes.destroy();
this.panInput.destroy();
originalPanels.forEach(function (panel) {
panel.destroy(option);
}); // release resources
for (var x in this) {
this[x] = null;
}
};
__proto.restore = function (status) {
var panels = status.panels;
var defaultIndex = this.options.defaultIndex;
var cameraElement = this.cameraElement;
var panelManager = this.panelManager; // Restore index
panelManager.clear();
cameraElement.innerHTML = status.panels.map(function (panel) {
return panel.html;
}).join("");
this.createPanels(); // Reset panel index
panelManager.originalPanels().forEach(function (panel, idx) {
panel.setIndex(panels[idx].index);
});
this.currentPanel = panelManager.get(status.index) || panelManager.get(defaultIndex) || panelManager.firstPanel();
this.resize();
this.axes.setTo({
flick: status.position
}, 0);
this.moveCamera(status.position);
};
__proto.getCurrentPanel = function () {
return this.currentPanel;
};
__proto.getCurrentIndex = function () {
var currentPanel = this.currentPanel;
return currentPanel ? currentPanel.getIndex() : -1;
};
__proto.getNearestPanel = function () {
return this.nearestPanel;
}; // Get progress from nearest panel
__proto.getCurrentProgress = function () {
var currentState = this.stateMachine.getState();
var nearestPanel = currentState.playing || currentState.holding ? this.nearestPanel : this.currentPanel;
var panelManager = this.panelManager;
if (!nearestPanel) {
// There're no panels
return NaN;
}
var _a = this.getScrollArea(),
prevRange = _a.prev,
nextRange = _a.next;
var cameraPosition = this.getCameraPosition();
var isOutOfBound = this.isOutOfBound();
var prevPanel = nearestPanel.prevSibling;
var nextPanel = nearestPanel.nextSibling;
var hangerPosition = this.getHangerPosition();
var nearestAnchorPos = nearestPanel.getAnchorPosition();
if (isOutOfBound && prevPanel && nextPanel && cameraPosition < nextRange // On the basis of anchor, prevPanel is nearestPanel.
&& hangerPosition - prevPanel.getAnchorPosition() < nearestAnchorPos - hangerPosition) {
nearestPanel = prevPanel;
nextPanel = nearestPanel.nextSibling;
prevPanel = nearestPanel.prevSibling;
nearestAnchorPos = nearestPanel.getAnchorPosition();
}
var nearestIndex = nearestPanel.getIndex() + (nearestPanel.getCloneIndex() + 1) * panelManager.getPanelCount();
var nearestSize = nearestPanel.getSize();
if (isOutOfBound) {
var relativeHangerPosition = this.getRelativeHangerPosition();
if (nearestAnchorPos > nextRange + relativeHangerPosition) {
// next bounce area: hangerPosition - relativeHangerPosition - nextRange
hangerPosition = nearestAnchorPos + hangerPosition - relativeHangerPosition - nextRange;
} else if (nearestAnchorPos < prevRange + relativeHangerPosition) {
// prev bounce area: hangerPosition - relativeHangerPosition - prevRange
hangerPosition = nearestAnchorPos + hangerPosition - relativeHangerPosition - prevRange;
}
}
var hangerIsNextToNearestPanel = hangerPosition >= nearestAnchorPos;
var gap = this.options.gap;
var basePosition = nearestAnchorPos;
var targetPosition = nearestAnchorPos;
if (hangerIsNextToNearestPanel) {
targetPosition = nextPanel ? nextPanel.getAnchorPosition() : nearestAnchorPos + nearestSize + gap;
} else {
basePosition = prevPanel ? prevPanel.getAnchorPosition() : nearestAnchorPos - nearestSize - gap;
}
var progressBetween = (hangerPosition - basePosition) / (targetPosition - basePosition);
var startIndex = hangerIsNextToNearestPanel ? nearestIndex : prevPanel ? prevPanel.getIndex() : nearestIndex - 1;
return startIndex + progressBetween;
}; // Update axes flick position without triggering event
__proto.updateAxesPosition = function (position) {
var axes = this.axes;
axes.off();
axes.setTo({
flick: position
}, 0);
axes.on(this.axesHandlers);
};
__proto.getSize = function () {
return this.state.size;
};
__proto.getScrollArea = function () {
return this.state.scrollArea;
};
__proto.isOutOfBound = function () {
var state = this.state;
var options = this.options;
var scrollArea = state.scrollArea;
return !options.circular && options.bound && (state.position <= scrollArea.prev || state.position >= scrollArea.next);
};
__proto.canSetBoundMode = function () {
var state = this.state;
var options = this.options;
var lastPanel = this.panelManager.lastPanel();
if (!lastPanel) {
return false;
}
var summedPanelSize = lastPanel.getPosition() + lastPanel.getSize();
return options.bound && !options.circular && summedPanelSize >= state.size;
};
__proto.getViewportElement = function () {
return this.viewportElement;
};
__proto.getCameraElement = function () {
return this.cameraElement;
};
__proto.getScrollAreaSize = function () {
var scrollArea = this.state.scrollArea;
return scrollArea.next - scrollArea.prev;
};
__proto.getRelativeHangerPosition = function () {
return this.state.relativeHangerPosition;
};
__proto.getHangerPosition = function () {
return this.state.position + this.state.relativeHangerPosition;
};
__proto.getCameraPosition = function () {
return this.state.position;
};
__proto.getCheckedIndexes = function () {
return this.state.checkedIndexes;
};
__proto.setCurrentPanel = function (panel) {
this.currentPanel = panel;
};
__proto.setLastIndex = function (index) {
var currentPanel = this.currentPanel;
var panelManager = this.panelManager;
panelManager.setLastIndex(index);
if (currentPanel && currentPanel.getIndex() > index) {
this.currentPanel = panelManager.lastPanel();
}
this.resize();
};
__proto.connectAxesHandler = function (handlers) {
var axes = this.axes;
this.axesHandlers = handlers;
axes.on(handlers);
};
__proto.addPlugins = function (plugins) {
var _this = this;
var newPlugins = [].concat(plugins);
newPlugins.forEach(function (plugin) {
plugin.init(_this.flicking);
});
this.plugins = this.plugins.concat(newPlugins);
return this;
};
__proto.removePlugins = function (plugins) {
var _this = this;
var currentPlugins = this.plugins;
var removedPlugins = [].concat(plugins);
removedPlugins.forEach(function (plugin) {
var index = currentPlugins.indexOf(plugin);
if (index > -1) {
currentPlugins.splice(index, 1);
}
plugin.destroy(_this.flicking);
});
return this;
};
__proto.updateCheckedIndexes = function (changedRange) {
var state = this.state;
var removed = 0;
state.checkedIndexes.concat().forEach(function (indexes, idx) {
var min = indexes[0],
max = indexes[1]; // Can fill part of indexes in range
if (changedRange.min <= max && changedRange.max >= min) {
// Remove checked index from list
state.checkedIndexes.splice(idx - removed, 1);
removed++;
}
});
};
__proto.build = function () {
this.setElements();
this.applyCSSValue();
this.setMoveType();
this.setAxesInstance();
this.createPanels();
this.setDefaultPanel();
this.resize();
this.moveToDefaultPanel();
};
__proto.setElements = function () {
var state = this.state;
var options = this.options;
var wrapper = this.flicking.getElement();
var classPrefix = options.classPrefix;
var viewportCandidate = wrapper.children[0];
var hasViewportElement = hasClass(viewportCandidate, classPrefix + "-viewport");
var viewportElement = hasViewportElement ? viewportCandidate : document.createElement("div");
var cameraCandidate = hasViewportElement ? viewportElement.children[0] : wrapper.children[0];
var hasCameraElement = hasClass(cameraCandidate, classPrefix + "-camera");
var cameraElement = hasCameraElement ? cameraCandidate : document.createElement("div");
if (!hasCameraElement) {
cameraElement.className = classPrefix + "-camera";
var panelElements = hasViewportElement ? viewportElement.children : wrapper.children; // Make all panels to be a child of camera element
// wrapper <- viewport <- camera <- panels[1...n]
toArray(panelElements).forEach(function (child) {
cameraElement.appendChild(child);
});
} else {
state.originalCameraStyle = {
className: cameraElement.getAttribute("class"),
style: cameraElement.getAttribute("style")
};
}
if (!hasViewportElement) {
viewportElement.className = classPrefix + "-viewport"; // Add viewport element to wrapper
wrapper.appendChild(viewportElement);
} else {
state.originalViewportStyle = {
className: viewportElement.getAttribute("class"),
style: viewportElement.getAttribute("style")
};
}
if (!hasCameraElement || !hasViewportElement) {
viewportElement.appendChild(cameraElement);
}
this.viewportElement = viewportElement;
this.cameraElement = cameraElement;
state.isViewportGiven = hasViewportElement;
state.isCameraGiven = hasCameraElement; // Create PanelManager instance
this.panelManager = new PanelManager(cameraElement, options);
};
__proto.applyCSSValue = function () {
var options = this.options;
var viewportElement = this.viewportElement;
var cameraElement = this.cameraElement; // Set default css values for each element
applyCSS(viewportElement, DEFAULT_VIEWPORT_CSS);
applyCSS(cameraElement, DEFAULT_CAMERA_CSS);
if (options.zIndex) {
viewportElement.style.zIndex = "" + options.zIndex;
}
if (options.overflow) {
viewportElement.style.overflow = "visible";
}
};
__proto.setMoveType = function () {
var moveType = this.options.moveType;
switch (moveType.type) {
case MOVE_TYPE.SNAP:
this.moveType = new Snap(moveType.count);
break;
case MOVE_TYPE.FREE_SCROLL:
this.moveType = new FreeScroll();
break;
default:
throw new Error("moveType is not correct!");
}
};
__proto.setAxesInstance = function () {
var state = this.state;
var options = this.options;
var scrollArea = state.scrollArea;
var horizontal = options.horizontal;
this.axes = new Axes({
flick: {
range: [scrollArea.prev, scrollArea.next],
circular: options.circular,
bounce: [0, 0]
}
}, {
easing: options.panelEffect,
deceleration: options.deceleration,
interruptable: true
});
this.panInput = new Axes.PanInput(this.viewportElement, {
inputType: options.inputType,
thresholdAngle: options.thresholdAngle,
scale: options.horizontal ? [-1, 0] : [0, -1]
});
this.axes.connect(horizontal ? ["flick", ""] : ["", "flick"], this.panInput);
};
__proto.createPanels = function () {
var _this = this; // Panel elements were attached to camera element by Flicking class
var panelElements = this.cameraElement.children; // Initialize panels
var panels = toArray(panelElements).map(function (el, idx) {
return new Panel(el, idx, _this);
});
if (panels.length > 0) {
this.panelManager.append(panels);
}
};
__proto.setDefaultPanel = function () {
var options = this.options;
var panelManager = this.panelManager;
var indexRange = this.panelManager.getRange();
var index = clamp(options.defaultIndex, indexRange.min, indexRange.max);
this.currentPanel = panelManager.get(index);
};
__proto.clonePanels = function () {
var _this = this;
var state = this.state;
var options = this.options;
var panelManager = this.panelManager;
var gap = options.gap;
var viewportSize = state.size;
var firstPanel = panelManager.firstPanel();
var lastPanel = panelManager.lastPanel(); // There're no panels exist
if (!firstPanel) {
return;
} // For each panels, clone itself while last panel's position + size is below viewport size
var panels = panelManager.originalPanels();
var reversedPanels = panels.concat().reverse();
var sumOriginalPanelSize = lastPanel.getPosition() + lastPanel.getSize() - firstPanel.getPosition() + gap;
var relativeAnchorPosition = firstPanel.getRelativeAnchorPosition();
var relativeHangerPosition = this.getRelativeHangerPosition();
var areaPrev = (relativeHangerPosition - relativeAnchorPosition) % sumOriginalPanelSize;
var sizeSum = 0;
var panelAtLeftBoundary;
for (var _i = 0, reversedPanels_1 = reversedPanels; _i < reversedPanels_1.length; _i++) {
var panel = reversedPanels_1[_i];
if (!panel) {
continue;
}
sizeSum += panel.getSize() + gap;
if (sizeSum >= areaPrev) {
panelAtLeftBoundary = panel;
break;
}
}
var areaNext = (viewportSize - relativeHangerPosition + relativeAnchorPosition) % sumOriginalPanelSize;
sizeSum = 0;
var panelAtRightBoundary;
for (var _a = 0, panels_1 = panels; _a < panels_1.length; _a++) {
var panel = panels_1[_a];
if (!panel) {
continue;
}
sizeSum += panel.getSize() + gap;
if (sizeSum >= areaNext) {
panelAtRightBoundary = panel;
break;
}
} // Need one more set of clones on prev area of original panel 0
var needCloneOnPrev = panelAtLeftBoundary.getIndex() !== 0 && panelAtLeftBoundary.getIndex() <= panelAtRightBoundary.getIndex(); // Visible count of panel 0 on first screen
var panel0OnFirstscreen = Math.ceil((relativeHangerPosition + firstPanel.getSize() - relativeAnchorPosition) / sumOriginalPanelSize) + Math.ceil((viewportSize - relativeHangerPosition + relativeAnchorPosition) / sumOriginalPanelSize) - 1; // duplication
var cloneCount = panel0OnFirstscreen + (needCloneOnPrev ? 1 : 0);
var prevCloneCount = panelManager.getCloneCount();
panelManager.setCloneCount(cloneCount);
if (options.renderExternal) {
return;
}
if (cloneCount > prevCloneCount) {
var _loop_1 = function (cloneIndex) {
var clones = panels.map(function (origPanel) {
var clonedPanel = origPanel.clone(cloneIndex);
_this.cameraElement.appendChild(clonedPanel.getElement());
return clonedPanel;
});
panelManager.insertClones(cloneIndex, 0, clones);
}; // should clone more
for (var cloneIndex = prevCloneCount; cloneIndex < cloneCount; cloneIndex++) {
_loop_1(cloneIndex);
}
} else if (cloneCount < prevCloneCount) {
// should remove some
panelManager.removeClonesAfter(cloneCount);
}
};
__proto.moveToDefaultPanel = function () {
var state = this.state;
var panelManager = this.panelManager;
var options = this.options;
var indexRange = this.panelManager.getRange();
var defaultIndex = clamp(options.defaultIndex, indexRange.min, indexRange.max);
var defaultPanel = panelManager.get(defaultIndex);
var defaultPosition = 0;
if (defaultPanel) {
defaultPosition = defaultPanel.getAnchorPosition() - state.relativeHangerPosition;
defaultPosition = this.canSetBoundMode() ? clamp(defaultPosition, state.scrollArea.prev, state.scrollArea.next) : defaultPosition;
}
this.moveCamera(defaultPosition);
this.axes.setTo({
flick: defaultPosition
}, 0);
};
__proto.updateSize = function () {
var state = this.state;
var options = this.options;
var viewportElement = this.viewportElement;
var panels = this.panelManager.originalPanels();
if (!options.horizontal) {
// Don't preserve previous width for adaptive resizing
viewportElement.style.width = "";
} else {
viewportElement.style.height = "";
}
var bbox = viewportElement.getBoundingClientRect(); // Update size & hanger position
state.size = options.horizontal ? bbox.width : bbox.height;
state.relativeHangerPosition = parseArithmeticExpression(options.hanger, state.size);
state.infiniteThreshold = parseArithmeticExpression(options.infiniteThreshold, state.size); // Resize all panels
panels.forEach(function (panel) {
panel.resize();
});
};
__proto.updateOriginalPanelPositions = function () {
var gap = this.options.gap;
var panelManager = this.panelManager;
var firstPanel = panelManager.firstPanel();
var panels = panelManager.originalPanels();
if (!firstPanel) {
return;
}
var currentPanel = this.currentPanel;
var nearestPanel = this.nearestPanel;
var currentState = this.stateMachine.getState();
var scrollArea = this.state.scrollArea; // Update panel position && fit to wrapper
var nextPanelPos = firstPanel.getPosition();
var maintainingPanel = firstPanel;
if (nearestPanel) {
// We should maintain nearestPanel's position
var looped = !isBetween(currentState.lastPosition + currentState.delta, scrollArea.prev, scrollArea.next);
maintainingPanel = looped ? currentPanel : nearestPanel;
} else if (firstPanel.getIndex() > 0) {
maintainingPanel = currentPanel;
}
var panelsBeforeMaintainPanel = panels.slice(0, maintainingPanel.getIndex() + (maintainingPanel.getCloneIndex() + 1) * panels.length);
var accumulatedSize = panelsBeforeMaintainPanel.reduce(function (total, panel) {
return total + panel.getSize() + gap;
}, 0);
nextPanelPos = maintainingPanel.getPosition() - accumulatedSize;
panels.forEach(function (panel) {
var newPosition = nextPanelPos;
var panelSize = panel.getSize();
panel.setPosition(newPosition);
nextPanelPos += panelSize + gap;
});
};
__proto.updateClonedPanelPositions = function () {
var state = this.state;
var options = this.options;
var panelManager = this.panelManager;
var clonedPanels = panelManager.clonedPanels().reduce(function (allClones, clones) {
return allClones.concat(clones);
}, []).filter(function (panel) {
return Boolean(panel);
});
var scrollArea = state.scrollArea;
var firstPanel = panelManager.firstPanel();
var lastPanel = panelManager.lastPanel();
if (!firstPanel) {
return;
}
var sumOriginalPanelSize = lastPanel.getPosition() + lastPanel.getSize() - firstPanel.getPosition() + options.gap; // Locate all cloned panels linearly first
for (var _i = 0, clonedPanels_1 = clonedPanels; _i < clonedPanels_1.length; _i++) {
var panel = clonedPanels_1[_i];
var origPanel = panel.getOriginalPanel();
var cloneIndex = panel.getCloneIndex();
var cloneBasePos = sumOriginalPanelSize * (cloneIndex + 1);
var clonedPanelPos = cloneBasePos + origPanel.getPosition();
panel.setPosition(clonedPanelPos);
}
var lastReplacePosition = firstPanel.getPosition(); // reverse() pollutes original array, so copy it with concat()
for (var _a = 0, _b = clonedPanels.concat().reverse(); _a < _b.length; _a++) {
var panel = _b[_a];
var panelSize = panel.getSize();
var replacePosition = lastReplacePosition - panelSize - options.gap;
if (replacePosition + panelSize <= scrollArea.prev) {
// Replace is not meaningful, as it won't be seen in current scroll area
break;
}
panel.setPosition(replacePosition);
lastReplacePosition = replacePosition;
}
};
__proto.updateScrollArea = function () {
var state = this.state;
var panelManager = this.panelManager;
var options = this.options;
var axes = this.axes; // Set viewport scrollable area
var firstPanel = panelManager.firstPanel();
var lastPanel = panelManager.lastPanel();
var relativeHangerPosition = state.relativeHangerPosition;
if (!firstPanel) {
state.scrollArea = {
prev: 0,
next: 0
};
} else if (this.canSetBoundMode()) {
state.scrollArea = {
prev: firstPanel.getPosition(),
next: lastPanel.getPosition() + lastPanel.getSize() - state.size
};
} else if (options.circular) {
var sumOriginalPanelSize = lastPanel.getPosition() + lastPanel.getSize() - firstPanel.getPosition() + options.gap; // Maximum scroll extends to first clone sequence's first panel
state.scrollArea = {
prev: firstPanel.getAnchorPosition() - relativeHangerPosition,
next: sumOriginalPanelSize + firstPanel.getAnchorPosition() - relativeHangerPosition
};
} else {
state.scrollArea = {
prev: firstPanel.getAnchorPosition() - relativeHangerPosition,
next: lastPanel.getAnchorPosition() - relativeHangerPosition
};
}
var viewportSize = state.size;
var bounce = options.bounce;
var parsedBounce = bounce;
if (isArray(bounce)) {
parsedBounce = bounce.map(function (val) {
return parseArithmeticExpression(val, viewportSize, DEFAULT_OPTIONS.bounce);
});
} else {
var parsedVal = parseArithmeticExpression(bounce, viewportSize, DEFAULT_OPTIONS.bounce);
parsedBounce = [parsedVal, parsedVal];
} // Update axes range and bounce
var flick = axes.axis.flick;
flick.range = [state.scrollArea.prev, state.scrollArea.next];
flick.bounce = parsedBounce;
}; // Update camera position after resizing
__proto.updateCameraPosition = function () {
var state = this.state;
var currentPanel = this.getCurrentPanel();
var currentState = this.stateMachine.getState();
var isFreeScroll = this.moveType.is(MOVE_TYPE.FREE_SCROLL);
var relativeHangerPosition = this.getRelativeHangerPosition();
var halfGap = this.options.gap / 2;
if (currentState.holding || currentState.playing) {
return;
}
var newPosition;
if (isFreeScroll) {
var nearestPanel = this.getNearestPanel();
newPosition = nearestPanel ? nearestPanel.getPosition() - halfGap + (nearestPanel.getSize() + 2 * halfGap) * state.panelMaintainRatio - relativeHangerPosition : this.getCameraPosition();
} else {
newPosition = currentPanel ? currentPanel.getAnchorPosition() - relativeHangerPosition : this.getCameraPosition();
}
if (this.canSetBoundMode()) {
newPosition = clamp(newPosition, state.scrollArea.prev, state.scrollArea.next);
} // Pause & resume axes to prevent axes's "change" event triggered
// This should be done before moveCamera, as moveCamera can trigger needPanel
this.updateAxesPosition(newPosition);
this.moveCamera(newPosition);
};
__proto.updatePlugins = function () {
var _this = this; // update for resize
this.plugins.forEach(function (plugin) {
plugin.update && plugin.update(_this.flicking);
});
};
__proto.checkNeedPanel = function (axesEvent) {
var state = this.state;
var options = this.options;
var panelManager = this.panelManager;
var currentPanel = this.currentPanel;
var nearestPanel = this.nearestPanel;
var currentState = this.stateMachine.getState();
if (!options.infinite) {
return;
}
var gap = options.gap;
var infiniteThreshold = state.infiniteThreshold;
var maxLastIndex = panelManager.getLastIndex();
if (maxLastIndex < 0) {
return;
}
if (!currentPanel || !nearestPanel) {
// There're no panels
this.triggerNeedPanel({
axesEvent: axesEvent,
siblingPanel: null,
direction: null,
indexRange: {
min: 0,
max: maxLastIndex,
length: maxLastIndex + 1
}
});
return;
}
var originalNearestPosition = nearestPanel.getPosition(); // Check next direction
var checkingPanel = !currentState.holding && !currentState.playing ? currentPanel : nearestPanel;
while (checkingPanel) {
var currentIndex = checkingPanel.getIndex();
var nextSibling = checkingPanel.nextSibling;
var lastPanel = panelManager.lastPanel();
var atLastPanel = currentIndex === lastPanel.getIndex();
var nextIndex = !atLastPanel && nextSibling ? nextSibling.getIndex() : maxLastIndex + 1;
var currentNearestPosition = nearestPanel.getPosition();
var panelRight = checkingPanel.getPosition() + checkingPanel.getSize() - (currentNearestPosition - originalNearestPosition);
var cameraNext = state.position + state.size; // There're empty panels between
var emptyPanelExistsBetween = nextIndex - currentIndex > 1; // Expected prev panel's left position is smaller than camera position
var overThreshold = panelRight + gap - infiniteThreshold <= cameraNext;
if (emptyPanelExistsBetween && overThreshold) {
this.triggerNeedPanel({
axesEvent: axesEvent,
siblingPanel: checkingPanel,
direction: DIRECTION.NEXT,
indexRange: {
min: currentIndex + 1,
max: nextIndex - 1,
length: nextIndex - currentIndex - 1
}
});
} // Trigger needPanel in circular & at max panel index
if (options.circular && currentIndex === maxLastIndex && overThreshold) {
var firstPanel = panelManager.firstPanel();
var firstIndex = firstPanel ? firstPanel.getIndex() : -1;
if (firstIndex > 0) {
this.triggerNeedPanel({
axesEvent: axesEvent,
siblingPanel: checkingPanel,
direction: DIRECTION.NEXT,
indexRange: {
min: 0,
max: firstIndex - 1,
length: firstIndex
}
});
}
} // Check whether panels are changed
var lastPanelAfterNeed = panelManager.lastPanel();
var atLastPanelAfterNeed = lastPanelAfterNeed && currentIndex === lastPanelAfterNeed.getIndex();
if (atLastPanelAfterNeed || !overThreshold) {
break;
}
checkingPanel = checkingPanel.nextSibling;
} // Check prev direction
checkingPanel = nearestPanel;
while (checkingPanel) {
var cameraPrev = state.position;
var checkingIndex = checkingPanel.getIndex();
var prevSibling = checkingPanel.prevSibling;
var firstPanel = panelManager.firstPanel();
var atFirstPanel = checkingIndex === firstPanel.getIndex();
var prevIndex = !atFirstPanel && prevSibling ? prevSibling.getIndex() : -1;
var currentNearestPosition = nearestPanel.getPosition();
var panelLeft = checkingPanel.getPosition() - (currentNearestPosition - originalNearestPosition); // There're empty panels between
var emptyPanelExistsBetween = checkingIndex - prevIndex > 1; // Expected prev panel's right position is smaller than camera position
var overThreshold = panelLeft - gap + infiniteThreshold >= cameraPrev;
if (emptyPanelExistsBetween && overThreshold) {
this.triggerNeedPanel({
axesEvent: axesEvent,
siblingPanel: checkingPanel,
direction: DIRECTION.PREV,
indexRange: {
min: prevIndex + 1,
max: checkingIndex - 1,
length: checkingIndex - prevIndex - 1
}
});
} // Trigger needPanel in circular & at panel 0
if (options.circular && checkingIndex === 0 && overThreshold) {
var lastPanel = panelManager.lastPanel();
if (lastPanel && lastPanel.getIndex() < maxLastIndex) {
var lastIndex = lastPanel.getIndex();
this.triggerNeedPanel({
axesEvent: axesEvent,
siblingPanel: checkingPanel,
direction: DIRECTION.PREV,
indexRange: {
min: lastIndex + 1,
max: maxLastIndex,
length: maxLastIndex - lastIndex
}
});
}
} // Check whether panels were changed
var firstPanelAfterNeed = panelManager.firstPanel();
var atFirstPanelAfterNeed = firstPanelAfterNeed && checkingIndex === firstPanelAfterNeed.getIndex(); // Looped in circular mode
if (atFirstPanelAfterNeed || !overThreshold) {
break;
}
checkingPanel = checkingPanel.prevSibling;
}
};
__proto.triggerNeedPanel = function (params) {
var axesEvent = params.axesEvent,
siblingPanel = params.siblingPanel,
direction = params.direction,
indexRange = params.indexRange;
var checkedIndexes = this.state.checkedIndexes;
var alreadyTriggered = checkedIndexes.some(function (_a) {
var min = _a[0],
max = _a[1];
return min === indexRange.min || max === indexRange.max;
});
var hasHandler = this.flicking.hasOn(EVENTS.NEED_PANEL);
if (alreadyTriggered || !hasHandler) {
return;
} // Should done before triggering event, as we can directly add panels by event callback
checkedIndexes.push([indexRange.min, indexRange.max]);
var index = siblingPanel ? siblingPanel.getIndex() : 0;
var isTrusted = axesEvent ? axesEvent.isTrusted : false;
this.triggerEvent(EVENTS.NEED_PANEL, axesEvent, isTrusted, {
index: index,
panel: siblingPanel,
direction: direction,
range: indexRange
});
};
return Viewport;
}();
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
/**
* @memberof eg
* @extends eg.Component
* @support {"ie": "10+", "ch" : "latest", "ff" : "latest", "sf" : "latest" , "edge" : "latest", "ios" : "7+", "an" : "4.X+"}
* @requires {@link https://github.com/naver/egjs-component|eg.Component}
* @requires {@link https://github.com/naver/egjs-axes|eg.Axes}
* @see Easing Functions Cheat Sheet {@link http://easings.net/} <ko>์ด์ง ํจ์ Cheat Sheet {@link http://easings.net/}</ko>
*/
var Flicking =
/*#__PURE__*/
function (_super) {
__extends(Flicking, _super);
/**
* @param element A base element for the eg.Flicking module. When specifying a value as a `string` type, you must specify a css selector string to select the element.<ko>eg.Flicking ๋ชจ๋์ ์ฌ์ฉํ ๊ธฐ์ค ์์. `string`ํ์
์ผ๋ก ๊ฐ ์ง์ ์ ์์๋ฅผ ์ ํํ๊ธฐ ์ํ css ์ ํ์ ๋ฌธ์์ด์ ์ง์ ํด์ผ ํ๋ค.</ko>
* @param options An option object of the eg.Flicking module<ko>eg.Flicking ๋ชจ๋์ ์ต์
๊ฐ์ฒด</ko>
* @param {string} [options.classPrefix="eg-flick"] A prefix of class name will be added for the panels, viewport and camera.<ko>ํจ๋๋ค๊ณผ ๋ทฐํฌํธ, ์นด๋ฉ๋ผ์ ์ถ๊ฐ๋ ํด๋์ค ์ด๋ฆ์ ์ ๋์ฌ.</ko>
* @param {number} [options.deceleration=0.0075] Deceleration value for panel movement animation for animation triggered by manual user input. Higher value means shorter running time.<ko>์ฌ์ฉ์์ ๋์์ผ๋ก ๊ฐ์๋๊ฐ ์ ์ฉ๋ ํจ๋ ์ด๋ ์ ๋๋ฉ์ด์
์ ๊ฐ์๋. ๊ฐ์ด ๋์์๋ก ์ ๋๋ฉ์ด์
์คํ ์๊ฐ์ด ์งง์์ง๋ค.</ko>
* @param {boolean} [options.horizontal=true] Direction of panel movement. (true: horizontal, false: vertical)<ko>ํจ๋ ์ด๋ ๋ฐฉํฅ. (true: ๊ฐ๋ก๋ฐฉํฅ, false: ์ธ๋ก๋ฐฉํฅ)</ko>
* @param {boolean} [options.circular=false] Enables circular mode, which connects first/last panel for continuous scrolling<ko>์ํ ๋ชจ๋๋ฅผ ํ์ฑํํ๋ค. ์ํ ๋ชจ๋์์๋ ์ ๋์ ํจ๋์ด ์๋ก ์ฐ๊ฒฐ๋์ด ๋๊น์๋ ์คํฌ๋กค์ด ๊ฐ๋ฅํ๋ค.</ko>
* @param {boolean} [options.infinite=false] Enables infinite mode, which can automatically trigger needPanel until reaching last panel's index reaches lastIndex<ko>๋ฌดํ ๋ชจ๋๋ฅผ ํ์ฑํํ๋ค. ๋ฌดํ ๋ชจ๋์์๋ needPanel ์ด๋ฒคํธ๋ฅผ ์๋์ผ๋ก ํธ๋ฆฌ๊ฑฐํ๋ค. ํด๋น ๋์์ ๋ง์ง๋ง ํจ๋์ ์ธ๋ฑ์ค๊ฐ lastIndex์ ์ผ์นํ ๋๊น์ง ์ผ์ด๋๋ค.</ko>
* @param {number} [options.infiniteThreshold=0] A Threshold from viewport edge before triggering `needPanel` event in infinite mode.<ko>๋ฌดํ ๋ชจ๋์์ `needPanel`์ด๋ฒคํธ๊ฐ ๋ฐ์ํ๊ธฐ ์ํ ๋ทฐํฌํธ ๋์ผ๋ก๋ถํฐ์ ์ต๋ ๊ฑฐ๋ฆฌ.</ko>
* @param {number} [options.lastIndex=Infinity] Maximum panel index that Flicking can set. Flicking won't trigger `needPanel` when event's panel index is greater than it.<br>Also, if last panel's index reached given index, you can't add more panels.<ko>Flicking์ด ์ค์ ๊ฐ๋ฅํ ํจ๋์ ์ต๋ ์ธ๋ฑ์ค. `needPanel` ์ด๋ฒคํธ์ ์ง์ ๋ ์ธ๋ฑ์ค๊ฐ ์ต๋ ํจ๋์ ๊ฐ์๋ณด๋ค ๊ฐ๊ฑฐ๋ ์ปค์ผ ํ๋ ๊ฒฝ์ฐ์ ์ด๋ฒคํธ๋ฅผ ํธ๋ฆฌ๊ฑฐํ์ง ์๊ฒ ํ๋ค.<br>๋ํ, ๋ง์ง๋ง ํจ๋์ ์ธ๋ฑ์ค๊ฐ ์ฃผ์ด์ง ์ธ๋ฑ์ค์ ๋์ผํ ๊ฒฝ์ฐ, ์๋ก์ด ํจ๋์ ๋ ์ด์ ์ถ๊ฐํ ์ ์๋ค.</ko>
* @param {number} [options.threshold=40] Movement threshold to change panel(unit: pixel). It should be dragged above the threshold to change current panel.<ko>ํจ๋ ๋ณ๊ฒฝ์ ์ํ ์ด๋ ์๊ณ๊ฐ (๋จ์: ํฝ์
). ์ฃผ์ด์ง ๊ฐ ์ด์์ผ๋ก ์คํฌ๋กคํด์ผ๋ง ํจ๋ ๋ณ๊ฒฝ์ด ๊ฐ๋ฅํ๋ค.</ko>
* @param {number} [options.duration=100] Duration of the panel movement animation.(unit: ms)<ko>ํจ๋ ์ด๋ ์ ๋๋ฉ์ด์
์งํ ์๊ฐ.(๋จ์: ms)</ko>
* @param {function} [options.panelEffect=x => 1 - Math.pow(1 - x, 3)] An easing function applied to the panel movement animation. Default value is `easeOutCubic`.<ko>ํจ๋ ์ด๋ ์ ๋๋ฉ์ด์
์ ์ ์ฉํ easingํจ์. ๊ธฐ๋ณธ๊ฐ์ `easeOutCubic`์ด๋ค.</ko>
* @param {number} [options.defaultIndex=0] Index of panel to set as default when initializing. A zero-based integer.<ko>์ด๊ธฐํ์ ์ง์ ํ ๋ํดํธ ํจ๋์ ์ธ๋ฑ์ค๋ก, 0๋ถํฐ ์์ํ๋ ์ ์.</ko>
* @param {string[]} [options.inputType=["touch,"mouse"]] Types of input devices to enable.({@link https://naver.github.io/egjs-axes/release/latest/doc/global.html#PanInputOption Reference})<ko>ํ์ฑํํ ์
๋ ฅ ์ฅ์น ์ข
๋ฅ. ({@link https://naver.github.io/egjs-axes/release/latest/doc/global.html#PanInputOption ์ฐธ๊ณ })</ko>
* @param {number} [options.thresholdAngle=45] The threshold angle value(0 ~ 90).<br>If input angle from click/touched position is above or below this value in horizontal and vertical mode each, scrolling won't happen.<ko>์คํฌ๋กค ๋์์ ๋ง๊ธฐ ์ํ ์๊ณ๊ฐ(0 ~ 90).<br>ํด๋ฆญ/ํฐ์นํ ์ง์ ์ผ๋ก๋ถํฐ ๊ณ์ฐ๋ ์ฌ์ฉ์ ์
๋ ฅ์ ๊ฐ๋๊ฐ horizontal/vertical ๋ชจ๋์์ ๊ฐ๊ฐ ํฌ๊ฑฐ๋ ์์ผ๋ฉด, ์คํฌ๋กค ๋์์ด ์ด๋ฃจ์ด์ง์ง ์๋๋ค.</ko>
* @param {number|string|number[]|string[]} [options.bounce=[10,10]] The size value of the bounce area. Only can be enabled when `circular=false`.<br>You can set different bounce value for prev/next direction by using array.<br>`number` for px value, and `string` for px, and % value relative to viewport size.(ex - 0, "10px", "20%")<ko>๋ฐ์ด์ค ์์ญ์ ํฌ๊ธฐ๊ฐ. `circular=false`์ธ ๊ฒฝ์ฐ์๋ง ์ฌ์ฉํ ์ ์๋ค.<br>๋ฐฐ์ด์ ํตํด prev/next ๋ฐฉํฅ์ ๋ํด ์๋ก ๋ค๋ฅธ ๋ฐ์ด์ค ๊ฐ์ ์ง์ ๊ฐ๋ฅํ๋ค.<br>`number`๋ฅผ ํตํด px๊ฐ์, `stirng`์ ํตํด px ํน์ ๋ทฐํฌํธ ํฌ๊ธฐ ๋๋น %๊ฐ์ ์ฌ์ฉํ ์ ์๋ค.(ex - 0, "10px", "20%")</ko>
* @param {boolean} [options.autoResize=false] Whether resize() method should be called automatically after window resize event.<ko>window์ `resize` ์ด๋ฒคํธ ์ดํ ์๋์ผ๋ก resize()๋ฉ์๋๋ฅผ ํธ์ถํ ์ง์ ์ฌ๋ถ.</ko>
* @param {boolean} [options.adaptive=false] Whether the height(horizontal)/width(vertical) of the viewport element reflects the height/width value of the panel after completing the movement.<ko>๋ชฉ์ ํจ๋๋ก ์ด๋ํ ํ ๊ทธ ํจ๋์ ๋์ด(horizontal)/๋๋น(vertical)๊ฐ์ ๋ทฐํฌํธ ์์์ ๋์ด/๋๋น๊ฐ์ ๋ฐ์ํ ์ง ์ฌ๋ถ.</ko>
* @param {number} [options.zIndex=2000] z-index value for viewport element.<ko>๋ทฐํฌํธ ์๋ฆฌ๋จผํธ์ z-index ๊ฐ.</ko>
* @param {boolean} [options.bound=false] Prevent view from going out of first/last panel. Only can be enabled when `circular=false`.<ko>๋ทฐ๊ฐ ์ฒซ๋ฒ์งธ์ ๋ง์ง๋ง ํจ๋ ๋ฐ์ผ๋ก ๋๊ฐ๋ ๊ฒ์ ๋ง์์ค๋ค. `circular=false`์ธ ๊ฒฝ์ฐ์๋ง ์ฌ์ฉํ ์ ์๋ค.</ko>
* @param {boolean} [options.overflow=false] Disables CSS property `overflow: hidden` in viewport if `true`.<ko>`true`๋ก ์ค์ ์ ๋ทฐํฌํธ์ `overflow: hidden` ์์ฑ์ ํด์ ํ๋ค.</ko>
* @param {string} [options.hanger="50%"] Reference position of hanger in viewport, which hangs panel anchors should be stopped at.<br>Should be provided in px or % value of viewport size.<br>You can combinate those values with plus/minus sign<br>ex) "50", "100px", "0%", "25% + 100px"<ko>๋ทฐํฌํธ ๋ด๋ถ์ ํ์ด์ ์์น. ํจ๋์ ์ต์ปค๋ค์ด ๋ทฐํฌํธ ๋ด์์ ๋ฉ์ถ๋ ์ง์ ์ ํด๋นํ๋ค.<br>px๊ฐ์ด๋, ๋ทฐํฌํธ์ ํฌ๊ธฐ ๋๋น %๊ฐ์ ์ฌ์ฉํ ์ ์๊ณ , ์ด๋ฅผ + ํน์ - ๊ธฐํธ๋ก ์ฐ๊ณํ์ฌ ์ฌ์ฉํ ์๋ ์๋ค.<br>์) "50", "100px", "0%", "25% + 100px"</ko>
* @param {string} [options.anchor="50%"] Reference position of anchor in panels, which can be hanged by viewport hanger.<br>Should be provided in px or % value of panel size.<br>You can combinate those values with plus/minus sign<br>ex) "50", "100px", "0%", "25% + 100px"<ko>ํจ๋ ๋ด๋ถ์ ์ต์ปค์ ์์น. ๋ทฐํฌํธ์ ํ์ด์ ์ฐ๊ณํ์ฌ ํจ๋์ด ํ๋ฉด ๋ด์์ ๋ฉ์ถ๋ ์ง์ ์ ์ค์ ํ ์ ์๋ค.<br>px๊ฐ์ด๋, ํจ๋์ ํฌ๊ธฐ ๋๋น %๊ฐ์ ์ฌ์ฉํ ์ ์๊ณ , ์ด๋ฅผ + ํน์ - ๊ธฐํธ๋ก ์ฐ๊ณํ์ฌ ์ฌ์ฉํ ์๋ ์๋ค.<br>์) "50", "100px", "0%", "25% + 100px"</ko>
* @param {number} [options.gap=0] Space between each panels. Should be given in number.(px).<ko>ํจ๋๊ฐ์ ๋ถ์ฌํ ๊ฐ๊ฒฉ์ ํฌ๊ธฐ๋ฅผ ๋ํ๋ด๋ ์ซ์.(px)</ko>
* @param {eg.Flicking.MoveTypeOption} [options.moveType="snap"] Movement style by user input.(ex: snap, freeScroll)<ko>์ฌ์ฉ์ ์
๋ ฅ์ ์ํ ์ด๋ ๋ฐฉ์.(ex: snap, freeScroll)</ko>
*/
function Flicking(element, options) {
if (options === void 0) {
options = {};
}
var _this = _super.call(this) || this;
/**
* Update panels to current state.
* @ko ํจ๋๋ค์ ํ์ฌ ์ํ์ ๋ง์ถฐ ๊ฐฑ์ ํ๋ค.
* @return {eg.Flicking} The instance itself.<ko>์ธ์คํด์ค ์๊ธฐ ์์ .</ko>
*/
_this.resize = function () {
var viewport = _this.viewport;
viewport.panelManager.allPanels().forEach(function (panel) {
return panel.unCacheBbox();
});
viewport.resize();
return _this;
};
_this.triggerEvent = function (eventName, axesEvent, isTrusted, params) {
if (params === void 0) {
params = {};
}
var viewport = _this.viewport;
var canceled = true; // Ignore events before viewport is initialized
if (viewport) {
var state = viewport.stateMachine.getState();
var _a = viewport.getScrollArea(),
prev = _a.prev,
next = _a.next;
var pos = viewport.getCameraPosition();
var progress = getProgress(pos, [prev, prev, next]);
if (_this.options.circular) {
progress %= 1;
}
canceled = !_super.prototype.trigger.call(_this, eventName, merge({
type: eventName,
index: _this.getIndex(),
panel: _this.getCurrentPanel(),
direction: state.direction,
holding: state.holding,
progress: progress,
axesEvent: axesEvent,
isTrusted: isTrusted
}, params));
}
return {
onSuccess: function (callback) {
if (!canceled) {
callback();
}
return this;
},
onStopped: function (callback) {
if (canceled) {
callback();
}
return this;
}
};
}; // Return result of "move" event triggered
_this.moveCamera = function (axesEvent) {
var viewport = _this.viewport;
var state = viewport.stateMachine.getState();
var options = _this.options;
var pos = axesEvent.pos.flick;
var previousPosition = viewport.getCameraPosition();
if (axesEvent.isTrusted && state.holding) {
var inputOffset = options.horizontal ? axesEvent.inputEvent.offsetX : axesEvent.inputEvent.offsetY;
var isNextDirection = inputOffset < 0;
var cameraChange = pos - previousPosition;
var looped = isNextDirection === pos < previousPosition;
if (options.circular && looped) {
// Reached at max/min range of axes
var scrollAreaSize = viewport.getScrollAreaSize();
cameraChange = (cameraChange > 0 ? -1 : 1) * (scrollAreaSize - Math.abs(cameraChange));
}
var currentDirection = cameraChange === 0 ? state.direction : cameraChange > 0 ? DIRECTION.NEXT : DIRECTION.PREV;
state.direction = currentDirection;
}
state.delta += axesEvent.delta.flick;
viewport.moveCamera(pos, axesEvent);
return _this.triggerEvent(EVENTS.MOVE, axesEvent, axesEvent.isTrusted).onStopped(function () {
// Undo camera movement
viewport.moveCamera(previousPosition, axesEvent);
});
}; // Set flicking wrapper user provided
var wrapper;
if (isString(element)) {
wrapper = document.querySelector(element);
if (!wrapper) {
throw new Error("Base element doesn't exist.");
}
} else if (element.nodeName && element.nodeType === 1) {
wrapper = element;
} else {
throw new Error("Element should be provided in string or HTMLElement.");
}
_this.wrapper = wrapper; // Override default options
_this.options = merge({}, DEFAULT_OPTIONS, options); // Override moveType option
var currentOptions = _this.options;
var moveType = currentOptions.moveType;
if (moveType in DEFAULT_MOVE_TYPE_OPTIONS) {
currentOptions.moveType = DEFAULT_MOVE_TYPE_OPTIONS[moveType];
} // Make viewport instance with panel container element
_this.viewport = new Viewport(_this, _this.options, _this.triggerEvent);
_this.listenInput();
_this.listenResize();
return _this;
}
/**
* Move to the previous panel if it exists.
* @ko ์ด์ ํจ๋์ด ์กด์ฌ์ ํด๋น ํจ๋๋ก ์ด๋ํ๋ค.
* @param [duration=options.duration] Duration of the panel movement animation.(unit: ms)<ko>ํจ๋ ์ด๋ ์ ๋๋ฉ์ด์
์งํ ์๊ฐ.(๋จ์: ms)</ko>
* @return {eg.Flicking} The instance itself.<ko>์ธ์คํด์ค ์๊ธฐ ์์ .</ko>
*/
var __proto = Flicking.prototype;
__proto.prev = function (duration) {
var currentPanel = this.getCurrentPanel();
var currentState = this.viewport.stateMachine.getState();
if (currentPanel && currentState.type === STATE_TYPE.IDLE) {
var prevPanel = currentPanel.prev();
if (prevPanel) {
prevPanel.focus(duration);
}
}
return this;
};
/**
* Move to the next panel if it exists.
* @ko ๋ค์ ํจ๋์ด ์กด์ฌ์ ํด๋น ํจ๋๋ก ์ด๋ํ๋ค.
* @param [duration=options.duration] Duration of the panel movement animation(unit: ms).<ko>ํจ๋ ์ด๋ ์ ๋๋ฉ์ด์
์งํ ์๊ฐ.(๋จ์: ms)</ko>
* @return {eg.Flicking} The instance itself.<ko>์ธ์คํด์ค ์๊ธฐ ์์ .</ko>
*/
__proto.next = function (duration) {
var currentPanel = this.getCurrentPanel();
var currentState = this.viewport.stateMachine.getState();
if (currentPanel && currentState.type === STATE_TYPE.IDLE) {
var nextPanel = currentPanel.next();
if (nextPanel) {
nextPanel.focus(duration);
}
}
return this;
};
/**
* Move to the panel of given index.
* @ko ์ฃผ์ด์ง ์ธ๋ฑ์ค์ ํด๋นํ๋ ํจ๋๋ก ์ด๋ํ๋ค.
* @param index The index number of the panel to move.<ko>์ด๋ํ ํจ๋์ ์ธ๋ฑ์ค ๋ฒํธ.</ko>
* @param duration [duration=options.duration] Duration of the panel movement.(unit: ms)<ko>ํจ๋ ์ด๋ ์ ๋๋ฉ์ด์
์งํ ์๊ฐ.(๋จ์: ms)</ko>
* @return {eg.Flicking} The instance itself.<ko>์ธ์คํด์ค ์๊ธฐ ์์ .</ko>
*/
__proto.moveTo = function (index, duration) {
var viewport = this.viewport;
var panel = viewport.panelManager.get(index);
var state = viewport.stateMachine.getState();
if (!panel || state.type !== STATE_TYPE.IDLE) {
return this;
}
var anchorPosition = panel.getAnchorPosition();
var hangerPosition = viewport.getHangerPosition();
var targetPanel = panel;
if (this.options.circular) {
var scrollAreaSize = viewport.getScrollAreaSize(); // Check all three possible locations, find the nearest position among them.
var possiblePositions = [anchorPosition - scrollAreaSize, anchorPosition, anchorPosition + scrollAreaSize];
var nearestPosition = possiblePositions.reduce(function (nearest, current) {
return Math.abs(current - hangerPosition) < Math.abs(nearest - hangerPosition) ? current : nearest;
}, Infinity) - panel.getRelativeAnchorPosition();
var identicals = panel.getIdenticalPanels();
var offset = nearestPosition - anchorPosition;
if (offset > 0) {
// First cloned panel is nearest
targetPanel = identicals[1];
} else if (offset < 0) {
// Last cloned panel is nearest
targetPanel = identicals[identicals.length - 1];
}
targetPanel = targetPanel.clone(targetPanel.getCloneIndex(), true);
targetPanel.setPosition(nearestPosition);
}
var currentIndex = this.getIndex();
if (hangerPosition === targetPanel.getAnchorPosition() && currentIndex === index) {
return this;
}
var eventType = panel.getIndex() === viewport.getCurrentIndex() ? "" : EVENTS.CHANGE;
viewport.moveTo(targetPanel, viewport.findEstimatedPosition(targetPanel), eventType, null, duration);
return this;
};
/**
* Return index of the current panel. `-1` if no panel exists.
* @ko ํ์ฌ ํจ๋์ ์ธ๋ฑ์ค ๋ฒํธ๋ฅผ ๋ฐํํ๋ค. ํจ๋์ด ํ๋๋ ์์ ๊ฒฝ์ฐ `-1`์ ๋ฐํํ๋ค.
* @return Current panel's index, zero-based integer.<ko>ํ์ฌ ํจ๋์ ์ธ๋ฑ์ค ๋ฒํธ. 0๋ถํฐ ์์ํ๋ ์ ์.</ko>
*/
__proto.getIndex = function () {
return this.viewport.getCurrentIndex();
};
/**
* Return the wrapper element user provided in constructor.
* @ko ์ฌ์ฉ์๊ฐ ์์ฑ์์์ ์ ๊ณตํ ๋ํผ ์๋ฆฌ๋จผํธ๋ฅผ ๋ฐํํ๋ค.
* @return Wrapper element user provided.<ko>์ฌ์ฉ์๊ฐ ์ ๊ณตํ ๋ํผ ์๋ฆฌ๋จผํธ.</ko>
*/
__proto.getElement = function () {
return this.wrapper;
};
/**
* Return current panel. `null` if no panel exists.
* @ko ํ์ฌ ํจ๋์ ๋ฐํํ๋ค. ํจ๋์ด ํ๋๋ ์์ ๊ฒฝ์ฐ `null`์ ๋ฐํํ๋ค.
* @return Current panel.<ko>ํ์ฌ ํจ๋.</ko>
*/
__proto.getCurrentPanel = function () {
var viewport = this.viewport;
var panel = viewport.getCurrentPanel();
return panel ? panel : null;
};
/**
* Return the panel of given index. `null` if it doesn't exists.
* @ko ์ฃผ์ด์ง ์ธ๋ฑ์ค์ ํด๋นํ๋ ํจ๋์ ๋ฐํํ๋ค. ํด๋น ํจ๋์ด ์กด์ฌํ์ง ์์ ์ `null`์ด๋ค.
* @return Panel of given index.<ko>์ฃผ์ด์ง ์ธ๋ฑ์ค์ ํด๋นํ๋ ํจ๋.</ko>
*/
__proto.getPanel = function (index) {
var viewport = this.viewport;
var panel = viewport.panelManager.get(index);
return panel ? panel : null;
};
/**
* Return all panels.
* @ko ๋ชจ๋ ํจ๋๋ค์ ๋ฐํํ๋ค.
* @param - Should include cloned panels or not.<ko>๋ณต์ฌ๋ ํจ๋๋ค์ ํฌํจํ ์ง์ ์ฌ๋ถ.</ko>
* @return All panels.<ko>๋ชจ๋ ํจ๋๋ค.</ko>
*/
__proto.getAllPanels = function (includeClone) {
var viewport = this.viewport;
var panelManager = viewport.panelManager;
var panels = includeClone ? panelManager.allPanels() : panelManager.originalPanels();
return panels.filter(function (panel) {
return !!panel;
});
};
/**
* Return the panels currently shown in viewport area.
* @ko ํ์ฌ ๋ทฐํฌํธ ์์ญ์์ ๋ณด์ฌ์ง๊ณ ์๋ ํจ๋๋ค์ ๋ฐํํ๋ค.
* @return Panels currently shown in viewport area.<ko>ํ์ฌ ๋ทฐํฌํธ ์์ญ์ ๋ณด์ฌ์ง๋ ํจ๋๋ค</ko>
*/
__proto.getVisiblePanels = function () {
return this.getAllPanels(true).filter(function (panel) {
var outsetProgress = panel.getOutsetProgress();
return outsetProgress > -1 && outsetProgress < 1;
});
};
/**
* Return length of original panels.
* @ko ์๋ณธ ํจ๋์ ๊ฐ์๋ฅผ ๋ฐํํ๋ค.
* @return Length of original panels.<ko>์๋ณธ ํจ๋์ ๊ฐ์</ko>
*/
__proto.getPanelCount = function () {
return this.viewport.panelManager.getPanelCount();
};
/**
* Return how many groups of clones are created.
* @ko ๋ช ๊ฐ์ ํด๋ก ๊ทธ๋ฃน์ด ์์ฑ๋์๋์ง๋ฅผ ๋ฐํํ๋ค.
* @return Length of cloned panel groups.<ko>ํด๋ก ๋ ํจ๋ ๊ทธ๋ฃน์ ๊ฐ์</ko>
*/
__proto.getCloneCount = function () {
return this.viewport.panelManager.getCloneCount();
};
/**
* Get maximum panel index for `infinite` mode.
* @ko `infinite` ๋ชจ๋์์ ์ ์ฉ๋๋ ์ถ๊ฐ ๊ฐ๋ฅํ ํจ๋์ ์ต๋ ์ธ๋ฑ์ค ๊ฐ์ ๋ฐํํ๋ค.
* @see {@link eg.Flicking.FlickingOptions}
* @return Maximum index of panel that can be added.<ko>์ต๋ ์ถ๊ฐ ๊ฐ๋ฅํ ํจ๋์ ์ธ๋ฑ์ค.</ko>
*/
__proto.getLastIndex = function () {
return this.viewport.panelManager.getLastIndex();
};
/**
* Set maximum panel index for `infinite' mode.<br>[needPanel]{@link eg.Flicking#events:needPanel} won't be triggered anymore when last panel's index reaches it.<br>Also, you can't add more panels after it.
* @ko `infinite` ๋ชจ๋์์ ์ ์ฉ๋๋ ํจ๋์ ์ต๋ ์ธ๋ฑ์ค๋ฅผ ์ค์ ํ๋ค.<br>๋ง์ง๋ง ํจ๋์ ์ธ๋ฑ์ค๊ฐ ์ค์ ํ ๊ฐ์ ๋๋ฌํ ๊ฒฝ์ฐ ๋ ์ด์ [needPanel]{@link eg.Flicking#events:needPanel} ์ด๋ฒคํธ๊ฐ ๋ฐ์๋์ง ์๋๋ค.<br>๋ํ, ์ค์ ํ ์ธ๋ฑ์ค ์ดํ๋ก ์๋ก์ด ํจ๋์ ์ถ๊ฐํ ์ ์๋ค.
* @param - Maximum panel index.
* @see {@link eg.Flicking.FlickingOptions}
* @return {eg.Flicking} The instance itself.<ko>์ธ์คํด์ค ์๊ธฐ ์์ .</ko>
*/
__proto.setLastIndex = function (index) {
this.viewport.setLastIndex(index);
return this;
};
/**
* Return panel movement animation.
* @ko ํ์ฌ ํจ๋ ์ด๋ ์ ๋๋ฉ์ด์
์ด ์งํ ์ค์ธ์ง๋ฅผ ๋ฐํํ๋ค.
* @return Is animating or not.<ko>์ ๋๋ฉ์ด์
์งํ ์ฌ๋ถ.</ko>
*/
__proto.isPlaying = function () {
return this.viewport.stateMachine.getState().playing;
};
/**
* Unblock input devices.
* @ko ๋ง์๋ ์
๋ ฅ ์ฅ์น๋ก๋ถํฐ์ ์
๋ ฅ์ ํผ๋ค.
* @return {eg.Flicking} The instance itself.<ko>์ธ์คํด์ค ์๊ธฐ ์์ .</ko>
*/
__proto.enableInput = function () {
this.viewport.enable();
return this;
};
/**
* Block input devices.
* @ko ์
๋ ฅ ์ฅ์น๋ก๋ถํฐ์ ์
๋ ฅ์ ๋ง๋๋ค.
* @return {eg.Flicking} The instance itself.<ko>์ธ์คํด์ค ์๊ธฐ ์์ .</ko>
*/
__proto.disableInput = function () {
this.viewport.disable();
return this;
};
/**
* Get current flicking status. You can restore current state by giving returned value to [setStatus()]{@link eg.Flicking#setStatus}.
* @ko ํ์ฌ ์ํ ๊ฐ์ ๋ฐํํ๋ค. ๋ฐํ๋ฐ์ ๊ฐ์ [setStatus()]{@link eg.Flicking#setStatus} ๋ฉ์๋์ ์ธ์๋ก ์ง์ ํ๋ฉด ํ์ฌ ์ํ๋ฅผ ๋ณต์ํ ์ ์๋ค.
* @return An object with current status value information.<ko>ํ์ฌ ์ํ๊ฐ ์ ๋ณด๋ฅผ ๊ฐ์ง ๊ฐ์ฒด.</ko>
*/
__proto.getStatus = function () {
var viewport = this.viewport;
var panels = viewport.panelManager.originalPanels().filter(function (panel) {
return !!panel;
}).map(function (panel) {
return {
html: panel.getElement().outerHTML,
index: panel.getIndex()
};
});
return {
index: viewport.getCurrentIndex(),
panels: panels,
position: viewport.getCameraPosition()
};
};
/**
* Restore to the state of the `status`.
* @ko `status`์ ์ํ๋ก ๋ณต์ํ๋ค.
* @param status Status value to be restored. You can specify the return value of the [getStatus()]{@link eg.Flicking#getStatus} method.<ko>๋ณต์ํ ์ํ ๊ฐ. [getStatus()]{@link eg.Flicking#getStatus}๋ฉ์๋์ ๋ฐํ๊ฐ์ ์ง์ ํ๋ฉด ๋๋ค.</ko>
*/
__proto.setStatus = function (status) {
this.viewport.restore(status);
};
/**
* Add plugins that can have different effects on Flicking.
* @ko ํ๋ฆฌํน์ ๋ค์ํ ํจ๊ณผ๋ฅผ ๋ถ์ฌํ ์ ์๋ ํ๋ฌ๊ทธ์ธ์ ์ถ๊ฐํ๋ค.
* @param - The plugin(s) to add.<ko>์ถ๊ฐํ ํ๋ฌ๊ทธ์ธ(๋ค).</ko>
* @return {eg.Flicking} The instance itself.<ko>์ธ์คํด์ค ์๊ธฐ ์์ .</ko>
*/
__proto.addPlugins = function (plugins) {
this.viewport.addPlugins(plugins);
return this;
};
/**
* Remove plugins from Flicking.
* @ko ํ๋ฆฌํน์ผ๋ก๋ถํฐ ํ๋ฌ๊ทธ์ธ๋ค์ ์ ๊ฑฐํ๋ค.
* @param - The plugin(s) to remove.<ko>์ ๊ฑฐ ํ๋ฌ๊ทธ์ธ(๋ค).</ko>
* @return {eg.Flicking} The instance itself.<ko>์ธ์คํด์ค ์๊ธฐ ์์ .</ko>
*/
__proto.removePlugins = function (plugins) {
this.viewport.removePlugins(plugins);
return this;
};
/**
* Return the reference element and all its children to the state they were in before the instance was created. Remove all attached event handlers. Specify `null` for all attributes of the instance (including inherited attributes).
* @ko ๊ธฐ์ค ์์์ ๊ทธ ํ์ ํจ๋๋ค์ ์ธ์คํด์ค ์์ฑ์ ์ ์ํ๋ก ๋๋๋ฆฐ๋ค. ๋ถ์ฐฉ๋ ๋ชจ๋ ์ด๋ฒคํธ ํธ๋ค๋ฌ๋ฅผ ํ๊ฑฐํ๋ค. ์ธ์คํด์ค์ ๋ชจ๋ ์์ฑ(์์๋ฐ์ ์์ฑํฌํจ)์ `null`์ ์ง์ ํ๋ค.
* @example
* const flick = new eg.Flicking("#flick");
* flick.destroy();
* console.log(flick.moveTo); // null
*/
__proto.destroy = function (option) {
if (option === void 0) {
option = {};
}
this.off();
if (this.options.autoResize) {
window.removeEventListener("resize", this.resize);
}
this.viewport.destroy(option); // release resources
for (var x in this) {
this[x] = null;
}
};
/**
* Add new panels at the beginning of panels.
* @ko ์ ์ผ ์์ ์๋ก์ด ํจ๋์ ์ถ๊ฐํ๋ค.
* @param element - Either HTMLElement, HTML string, or array of them.<br>It can be also HTML string of multiple elements with same depth.<ko>HTMLElement ํน์ HTML ๋ฌธ์์ด, ํน์ ๊ทธ๊ฒ๋ค์ ๋ฐฐ์ด๋ ๊ฐ๋ฅํ๋ค.<br>๋ํ, ๊ฐ์ depth์ ์ฌ๋ฌ ๊ฐ์ ์๋ฆฌ๋จผํธ์ ํด๋นํ๋ HTML ๋ฌธ์์ด๋ ๊ฐ๋ฅํ๋ค.</ko>
* @return Array of appended panels.<ko>์ถ๊ฐ๋ ํจ๋๋ค์ ๋ฐฐ์ด</ko>
* @example
* // Suppose there were no panels at initialization
* const flicking = new eg.Flicking("#flick");
* flicking.replace(3, document.createElement("div")); // Add new panel at index 3
* flicking.prepend("\<div\>Panel\</div\>"); // Prepended at index 2
* flicking.prepend(["\<div\>Panel\</div\>", document.createElement("div")]); // Prepended at index 0, 1
* flicking.prepend("\<div\>Panel\</div\>"); // Prepended at index 0, pushing every panels behind it.
*/
__proto.prepend = function (element) {
var viewport = this.viewport;
var parsedElements = parseElement(element);
var insertingIndex = Math.max(viewport.panelManager.getRange().min - parsedElements.length, 0);
return viewport.insert(insertingIndex, parsedElements);
};
/**
* Add new panels at the end of panels.
* @ko ์ ์ผ ๋์ ์๋ก์ด ํจ๋์ ์ถ๊ฐํ๋ค.
* @param element - Either HTMLElement, HTML string, or array of them.<br>It can be also HTML string of multiple elements with same depth.<ko>HTMLElement ํน์ HTML ๋ฌธ์์ด, ํน์ ๊ทธ๊ฒ๋ค์ ๋ฐฐ์ด๋ ๊ฐ๋ฅํ๋ค.<br>๋ํ, ๊ฐ์ depth์ ์ฌ๋ฌ ๊ฐ์ ์๋ฆฌ๋จผํธ์ ํด๋นํ๋ HTML ๋ฌธ์์ด๋ ๊ฐ๋ฅํ๋ค.</ko>
* @return Array of appended panels.<ko>์ถ๊ฐ๋ ํจ๋๋ค์ ๋ฐฐ์ด</ko>
* @example
* // Suppose there were no panels at initialization
* const flicking = new eg.Flicking("#flick");
* flicking.append(document.createElement("div")); // Appended at index 0
* flicking.append("\<div\>Panel\</div\>"); // Appended at index 1
* flicking.append(["\<div\>Panel\</div\>", document.createElement("div")]); // Appended at index 2, 3
* // Even this is possible
* flicking.append("\<div\>Panel 1\</div\>\<div\>Panel 2\</div\>"); // Appended at index 4, 5
*/
__proto.append = function (element) {
var viewport = this.viewport;
return viewport.insert(viewport.panelManager.getRange().max + 1, element);
};
/**
* Replace existing panels with new panels from given index. If target index is empty, add new panel at target index.
* @ko ์ฃผ์ด์ง ์ธ๋ฑ์ค๋ก๋ถํฐ์ ํจ๋๋ค์ ์๋ก์ด ํจ๋๋ค๋ก ๊ต์ฒดํ๋ค. ์ธ๋ฑ์ค์ ํด๋นํ๋ ์๋ฆฌ๊ฐ ๋น์ด์๋ค๋ฉด, ์๋ก์ด ํจ๋์ ํด๋น ์๋ฆฌ์ ์ง์ด๋ฃ๋๋ค.
* @param index - Start index to replace new panels.<ko>์๋ก์ด ํจ๋๋ค๋ก ๊ต์ฒดํ ์์ ์ธ๋ฑ์ค</ko>
* @param element - Either HTMLElement, HTML string, or array of them.<br>It can be also HTML string of multiple elements with same depth.<ko>HTMLElement ํน์ HTML ๋ฌธ์์ด, ํน์ ๊ทธ๊ฒ๋ค์ ๋ฐฐ์ด๋ ๊ฐ๋ฅํ๋ค.<br>๋ํ, ๊ฐ์ depth์ ์ฌ๋ฌ ๊ฐ์ ์๋ฆฌ๋จผํธ์ ํด๋นํ๋ HTML ๋ฌธ์์ด๋ ๊ฐ๋ฅํ๋ค.</ko>
* @return Array of created panels by replace.<ko>๊ต์ฒด๋์ด ์๋กญ๊ฒ ์ถ๊ฐ๋ ํจ๋๋ค์ ๋ฐฐ์ด</ko>
* @example
* // Suppose there were no panels at initialization
* const flicking = new eg.Flicking("#flick");
*
* // This will add new panel at index 3,
* // Index 0, 1, 2 is empty at this moment.
* // [empty, empty, empty, PANEL]
* flicking.replace(3, document.createElement("div"));
*
* // As index 2 was empty, this will also add new panel at index 2.
* // [empty, empty, PANEL, PANEL]
* flicking.replace(2, "\<div\>Panel\</div\>");
*
* // Index 3 was not empty, so it will replace previous one.
* // It will also add new panels at index 4 and 5.
* // before - [empty, empty, PANEL, PANEL]
* // after - [empty, empty, PANEL, NEW_PANEL, NEW_PANEL, NEW_PANEL]
* flicking.replace(3, ["\<div\>Panel\</div\>", "\<div\>Panel\</div\>", "\<div\>Panel\</div\>"])
*/
__proto.replace = function (index, element) {
return this.viewport.replace(index, element);
};
/**
* Remove panel at target index. This will decrease index of panels behind it.
* @ko `index`์ ํด๋นํ๋ ์๋ฆฌ์ ํจ๋์ ์ ๊ฑฐํ๋ค. ์ํ์ `index` ์ดํ์ ํจ๋๋ค์ ์ธ๋ฑ์ค๊ฐ ๊ฐ์๋๋ค.
* @param index - Index of panel to remove.<ko>์ ๊ฑฐํ ํจ๋์ ์ธ๋ฑ์ค</ko>
* @param {number} [deleteCount=1] - Number of panels to remove from index.<ko>`index` ์ดํ๋ก ์ ๊ฑฐํ ํจ๋์ ๊ฐ์.</ko>
* @return Array of removed panels<ko>์ ๊ฑฐ๋ ํจ๋๋ค์ ๋ฐฐ์ด</ko>
*/
__proto.remove = function (index, deleteCount) {
if (deleteCount === void 0) {
deleteCount = 1;
}
return this.viewport.remove(index, deleteCount);
};
/**
* Synchronize info of panels instance with info given by external rendering.
* @ko ์ธ๋ถ ๋ ๋๋ง ๋ฐฉ์์ ์ํด ์
๋ ฅ๋ฐ์ ํจ๋์ ์ ๋ณด์ ํ์ฌ ํ๋ฆฌํน์ด ๊ฐ๋ ํจ๋ ์ ๋ณด๋ฅผ ๋๊ธฐํํ๋ค.
* @param diffInfo - Info object of how panel elements are changed.<ko>ํจ๋์ DOM ์์๋ค์ ๋ณ๊ฒฝ ์ ๋ณด๋ฅผ ๋ด๋ ์ค๋ธ์ ํธ.</ko>
* @param {HTMLElement[]} [diffInfo.list] - DOM elements list after update.<ko>์
๋ฐ์ดํธ ์ดํ DOM ์์๋ค์ ๋ฆฌ์คํธ</ko>
* @param {number[][]} [diffInfo.maintained] - Index tuple array of DOM elements maintained. Formatted with `[before, after]`.<ko>๋ณ๊ฒฝ ์ ํ์ ์ ์ง๋ DOM ์์๋ค์ ์ธ๋ฑ์ค ํํ ๋ฐฐ์ด. `[์ด์ , ์ดํ]`์ ํ์์ ๊ฐ๊ณ ์์ด์ผ ํ๋ค.</ko>
* @param {number[]} [diffInfo.added] - Index array of DOM elements added to `list`.<ko>`list`์์ ์ถ๊ฐ๋ DOM ์์๋ค์ ์ธ๋ฑ์ค ๋ฐฐ์ด.</ko>
* @param {number[]} [diffInfo.removed] - Index array of DOM elements removed from previous element list.<ko>์ด์ ๋ฆฌ์คํธ์์ ์ ๊ฑฐ๋ DOM ์์๋ค์ ์ธ๋ฑ์ค ๋ฐฐ์ด.</ko>
*/
__proto.sync = function (diffInfo) {
var list = diffInfo.list,
maintained = diffInfo.maintained,
added = diffInfo.added,
changed = diffInfo.changed,
removed = diffInfo.removed; // Did not changed at all
if (added.length <= 0 && removed.length <= 0 && changed.length <= 0) {
return this;
}
var viewport = this.viewport;
var panelManager = viewport.panelManager;
var indexRange = panelManager.getRange();
var isCircular = this.options.circular; // Make sure that new "list" should include cloned elements
var newOriginalPanelCount = list.length / (panelManager.getCloneCount() + 1) >> 0; // Make sure it's integer. Same with Math.floor, but faster
var newCloneCount = (list.length / newOriginalPanelCount >> 0) - 1;
var prevOriginalPanels = panelManager.originalPanels();
var prevClonedPanels = panelManager.clonedPanels();
var newOriginalElements = list.slice(0, newOriginalPanelCount);
var newClonedElements = list.slice(newOriginalPanelCount);
var newPanels = [];
var newClones = counter(newCloneCount).map(function () {
return [];
}); // For maintained panels after external rendering, they should be maintained in newPanels.
var originalMaintained = maintained.filter(function (_a) {
var beforeIdx = _a[0],
afterIdx = _a[1];
return beforeIdx <= indexRange.max;
}); // For newly added panels after external rendering, they will be added with their elements.
var originalAdded = added.filter(function (index) {
return index < newOriginalPanelCount;
});
originalMaintained.forEach(function (_a) {
var beforeIdx = _a[0],
afterIdx = _a[1];
newPanels[afterIdx] = prevOriginalPanels[beforeIdx];
newPanels[afterIdx].setIndex(afterIdx);
});
originalAdded.forEach(function (addIndex) {
newPanels[addIndex] = new Panel(newOriginalElements[addIndex], addIndex, viewport);
});
if (isCircular) {
counter(newCloneCount).forEach(function (groupIndex) {
var cloneGroupOffset = newOriginalPanelCount * groupIndex;
var prevCloneGroup = prevClonedPanels[groupIndex];
var newCloneGroup = newClones[groupIndex];
originalMaintained.forEach(function (_a) {
var beforeIdx = _a[0],
afterIdx = _a[1];
newCloneGroup[afterIdx] = prevCloneGroup ? prevCloneGroup[beforeIdx] : newPanels[afterIdx].cloneExternal(groupIndex, newClonedElements[cloneGroupOffset + afterIdx]);
});
originalAdded.forEach(function (addIndex) {
var newPanel = newPanels[addIndex];
newCloneGroup[addIndex] = newPanel.cloneExternal(groupIndex, newClonedElements[cloneGroupOffset + addIndex]);
});
});
} // Replace current info of panels this holds
added.forEach(function (index) {
viewport.updateCheckedIndexes({
min: index,
max: index
});
});
removed.forEach(function (index) {
viewport.updateCheckedIndexes({
min: index - 1,
max: index + 1
});
});
var checkedIndexes = viewport.getCheckedIndexes();
checkedIndexes.forEach(function (_a, idx) {
var min = _a[0],
max = _a[1]; // Push checked indexes backward
var pushedIndex = added.filter(function (index) {
return index < min && panelManager.has(index);
}).length - removed.filter(function (index) {
return index < min;
}).length;
checkedIndexes.splice(idx, 1, [min + pushedIndex, max + pushedIndex]);
}); // Only effective only when there are least one panel which have changed its index
if (changed.length > 0) {
// Removed checked index by changed ones after pushing
maintained.forEach(function (_a) {
var prev = _a[0],
next = _a[1];
viewport.updateCheckedIndexes({
min: next,
max: next
});
});
}
panelManager.replacePanels(newPanels, newClones);
this.resize();
return this;
};
__proto.listenInput = function () {
var flicking = this;
var viewport = flicking.viewport;
var stateMachine = viewport.stateMachine; // Set event context
flicking.eventContext = {
flicking: flicking,
viewport: flicking.viewport,
transitTo: stateMachine.transitTo,
triggerEvent: flicking.triggerEvent,
moveCamera: flicking.moveCamera,
stopCamera: viewport.stopCamera
};
var handlers = {};
var _loop_1 = function (key) {
var eventType = AXES_EVENTS[key];
handlers[eventType] = function (e) {
return stateMachine.fire(eventType, e, flicking.eventContext);
};
};
for (var key in AXES_EVENTS) {
_loop_1(key);
} // Connect Axes instance with PanInput
flicking.viewport.connectAxesHandler(handlers);
};
__proto.listenResize = function () {
if (this.options.autoResize) {
window.addEventListener("resize", this.resize);
}
};
/**
* Version info string
* @ko ๋ฒ์ ์ ๋ณด ๋ฌธ์์ด
* @example
* eg.Flicking.VERSION; // ex) 3.0.0
* @memberof eg.Flicking
*/
Flicking.VERSION = "3.2.1";
/**
* Direction constant - "PREV" or "NEXT"
* @ko ๋ฐฉํฅ ์์ - "PREV" ๋๋ "NEXT"
* @example
* eg.Flicking.DIRECTION.PREV; // "PREV"
* eg.Flicking.DIRECTION.NEXT; // "NEXT"
*/
Flicking.DIRECTION = DIRECTION;
/**
* Event type object
* @ko ์ด๋ฒคํธ ์ด๋ฆ ๋ฌธ์์ด๋ค์ ๋ด์ ๊ฐ์ฒด
*/
Flicking.EVENTS = EVENTS;
return Flicking;
}(Component);
Flicking.withFlickingMethods = withFlickingMethods;
Flicking.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
Flicking.MOVE_TYPE = MOVE_TYPE;
return Flicking;
}));
//# sourceMappingURL=flicking.js.map
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.